Skip to content

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.

Add gallery maintenance UI (#9700)

Jonathan59ccb0066481
diff --git a/docs/src/content/docs/configuration/01.invokeai-yaml.mdx b/docs/src/content/docs/configuration/01.invokeai-yaml.mdx
index 9e12d25c14..d4a68d54ae 100644
--- a/docs/src/content/docs/configuration/01.invokeai-yaml.mdx
+++ b/docs/src/content/docs/configuration/01.invokeai-yaml.mdx
@@ -4,8 +4,8 @@ sidebar:
order: 1
---
-import { FileTree } from '@astrojs/starlight/components'
-import SettingsDocs from '@lib/components/SettingsDocs.astro'
+import { FileTree } from '@astrojs/starlight/components';
+import SettingsDocs from '@lib/components/SettingsDocs.astro';
Runtime settings, including the location of files and directories, memory usage, and performance, are managed via the `invokeai.yaml` config file or environment variables. A subset of settings may be set via commandline arguments.
@@ -21,15 +21,25 @@ Settings sources are used in this order:
On startup, InvokeAI searches for its "root" directory. This is the directory that contains models, images, the database, and so on. It also contains a configuration file called `invokeai.yaml`.
<FileTree>
- - models/
- - outputs/
- - databases/
- - workflow_thumbnails/
- - style_presets/
- - nodes/
- - configs/
- - invokeai.example.yaml
- - **invokeai.yaml**
+
+- models/
+
+- outputs/
+
+- databases/
+
+- workflow_thumbnails/
+
+- style_presets/
+
+- nodes/
+
+- configs/
+
+- invokeai.example.yaml
+
+- **invokeai.yaml**
+
</FileTree>
InvokeAI searches for the root directory in this order:
@@ -124,11 +134,11 @@ This is controlled by the `generation_devices` setting:
generation_devices: auto # default value
```
-| Value | Behavior |
-| -------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
-| `auto` | Use every available CUDA GPU, running one generation session per GPU concurrently. This is the default. Exception: if the legacy `device` setting is pinned to a specific device, `auto` uses only that device (see Notes below). |
-| `[cuda:0,cuda:1]` | Use the specific devices listed, one session per device. Useful for reserving a GPU for other work. |
-| `[cuda:0]` | Use a single specific device. Generation runs serially, as it did before multi-GPU support. |
+| Value | Behavior |
+| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `auto` | Use every available CUDA GPU, running one generation session per GPU concurrently. This is the default. Exception: if the legacy `device` setting is pinned to a specific device, `auto` uses only that device (see Notes below). |
+| `[cuda:0,cuda:1]` | Use the specific devices listed, one session per device. Useful for reserving a GPU for other work. |
+| `[cuda:0]` | Use a single specific device. Generation runs serially, as it did before multi-GPU support. |
Each entry in the list must be one of `cpu`, `cuda`, `mps`, or `cuda:N`, where `N` is a zero-based device number (`cuda:0` is the first GPU, `cuda:1` the second, and so on). The list may not be empty — use `auto` (or a single-device list) instead.
@@ -158,10 +168,10 @@ This is controlled by the `offload_text_encoders_to_idle_gpus` setting:
offload_text_encoders_to_idle_gpus: true # default value
```
-| Value | Behavior |
+| Value | Behavior |
| ------- | ---------------------------------------------------------------------------------------------------------------- |
-| `true` | Run text encoders on an idle GPU when one is available. This is the default. |
-| `false` | Always run text encoders on the same GPU as the rest of the pipeline (the behavior before this feature existed). |
+| `true` | Run text encoders on an idle GPU when one is available. This is the default. |
+| `false` | Always run text encoders on the same GPU as the rest of the pipeline (the behavior before this feature existed). |
Notes:
@@ -198,25 +208,25 @@ Changing this setting only affects newly-created images. Existing images remain
API responses (JSON, HTML, JS, CSS, SVG) are gzipped before being sent. Already-compressed responses — PNG, WebP, JPEG, MP4 — are passed through untouched, since compressing them costs CPU and returns a body no smaller than the original.
-Compression runs on the server's event loop, which means it blocks *everything else* for its duration: no other request is served and no progress event is delivered while it runs. The `http_compression_level` setting controls that trade-off:
+Compression runs on the server's event loop, which means it blocks _everything else_ for its duration: no other request is served and no progress event is delivered while it runs. The `http_compression_level` setting controls that trade-off:
```yaml
http_compression_level: 9 # default value
```
-| Value | Behavior |
-| ------ | ---------------------------------------------------------------------------------------------- |
-| `0` | No compression. Responses are sent as-is and the compression middleware is not installed. |
-| `1` | Fastest compression, slightly larger output. |
-| `2`–`8` | Progressively slower, marginally smaller. |
-| `9` | Smallest output, by far the slowest. This is the default. |
+| Value | Behavior |
+| ------- | ----------------------------------------------------------------------------------------- |
+| `0` | No compression. Responses are sent as-is and the compression middleware is not installed. |
+| `1` | Fastest compression, slightly larger output. |
+| `2`–`8` | Progressively slower, marginally smaller. |
+| `9` | Smallest output, by far the slowest. This is the default. |
The setting can also be given as the `INVOKEAI_HTTP_COMPRESSION_LEVEL` environment variable.
If the UI feels sluggish while a large library is being browsed, lowering this is one of the cheapest wins available. Measured on the image-name list of a 200,000-image library (8.48 MB of JSON):
-| Level | Time | Output |
-| ----- | ------: | --------: |
+| Level | Time | Output |
+| ----- | ------: | ------------: |
| `1` | 16.4 ms | 6.1% of input |
| `6` | 36.1 ms | 5.9% of input |
| `9` | 90.2 ms | 5.7% of input |
@@ -235,20 +245,20 @@ Every write to InvokeAI's SQLite database is committed to disk before the reques
db_synchronous: full # default value
```
-| Value | Behavior |
-| -------- | ----------------------------------------------------------------------------------------------------------- |
+| Value | Behavior |
+| -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `full` | Every commit is flushed to disk before it is acknowledged. What InvokeAI has always used, and SQLite's default on standard builds. |
-| `normal` | Commits are acknowledged without waiting for the flush. Much faster; a power loss may lose the last few. |
+| `normal` | Commits are acknowledged without waiting for the flush. Much faster; a power loss may lose the last few. |
The setting can also be given as the `INVOKEAI_DB_SYNCHRONOUS` environment variable.
-**`normal` cannot corrupt the database, as long as WAL is in effect.** InvokeAI runs SQLite in WAL mode, and WAL guarantees a consistent database either way. What `normal` gives up is the *most recent transactions* if the machine loses power or the OS crashes mid-write — a just-written image record or a queue status. The image file itself survives on disk, but nothing rebuilds the row, and the gallery is driven by the database: the image is simply gone from it. The gallery orphan scan does not heal this — it *archives* record-less files out of `outputs/` so you can delete them or re-import them, which takes the separate `invokeai/frontend/install/import_images.py` script.
+**`normal` cannot corrupt the database, as long as WAL is in effect.** InvokeAI runs SQLite in WAL mode, and WAL guarantees a consistent database either way. What `normal` gives up is the _most recent transactions_ if the machine loses power or the OS crashes mid-write — a just-written image record or a queue status. The image file itself survives on disk, but nothing rebuilds the row, and the gallery is driven by the database: the image is simply gone from it. An administrator can use **Settings > Data & workspace > Gallery maintenance** to review and remove database records whose image files are missing, or archive untracked image files for later review. Maintenance does not import archived files; use the separate `invokeai/frontend/install/import_images.py` script to import images.
Running the database on a network share is not a supported configuration -- SQLite's locking is unreliable over NFS and SMB, and this is worth avoiding for reasons well beyond durability. Keep `db_dir` on local storage.
-The safeguard exists anyway, because WAL needs shared memory and a few setups cannot provide it: a database on a network share, some container volume drivers, and SQLite builds compiled without WAL all leave a rollback journal in place instead — and on a rollback journal, `normal` *can* corrupt the database on power loss. InvokeAI reads back the journal mode it actually got, so in that case it ignores `normal`, uses `full`, and logs a warning naming the mode. An in-memory database (`use_memory_db`) has no durability to trade and is unaffected.
+The safeguard exists anyway, because WAL needs shared memory and a few setups cannot provide it: a database on a network share, some container volume drivers, and SQLite builds compiled without WAL all leave a rollback journal in place instead — and on a rollback journal, `normal` _can_ corrupt the database on power loss. InvokeAI reads back the journal mode it actually got, so in that case it ignores `normal`, uses `full`, and logs a warning naming the mode. An in-memory database (`use_memory_db`) has no durability to trade and is unaffected.
-`db_synchronous` applies to the application's own database connection. The standalone scripts that open the database directly — `scripts/gallery_maintenance.py` and `invokeai/frontend/install/import_images.py` — leave SQLite's own default in place, so the measurements below describe the running app, not those scripts.
+`db_synchronous` applies to the application's own database connection. Gallery maintenance is an administrator action in Settings and uses that same application database connection, so its database work follows this setting. The image import script, `invokeai/frontend/install/import_images.py`, still opens the database independently and leaves SQLite's own default in place; the measurements below describe the running app, not that script.
Measured on a copy of a real library, 300 single-row inserts each committed on its own:
diff --git a/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx b/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx
index 602406e3a3..1a2e518f4b 100644
--- a/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx
+++ b/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx
@@ -5,7 +5,7 @@ sidebar:
order: 4
---
-import { Steps } from '@astrojs/starlight/components'
+import { Steps } from '@astrojs/starlight/components';
## Overview
@@ -46,16 +46,16 @@ If at any time you wish to revert to single-user mode, simply comment out the `m
The image generation queue is processed by a single worker, so jobs run one at a time. The `session_queue_mode` option controls the order in which pending jobs are selected:
-| Mode | Behavior |
-|------|----------|
+| Mode | Behavior |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `round_robin` (default) | Interleaves jobs across users — each user is served one job before any user is served a second. A single user enqueuing a large batch can no longer monopolize the queue. |
-| `FIFO` | Strict first-come, first-serve. Jobs run in the order they were enqueued (respecting priority), so a large batch drains completely before the next user's jobs start. |
+| `FIFO` | Strict first-come, first-serve. Jobs run in the order they were enqueued (respecting priority), so a large batch drains completely before the next user's jobs start. |
Set it in `invokeai.yaml`:
```yaml
multiuser: true
-session_queue_mode: round_robin # or FIFO
+session_queue_mode: round_robin # or FIFO
```
Or via the `INVOKEAI_SESSION_QUEUE_MODE` environment variable:
@@ -84,30 +84,27 @@ When InvokeAI starts for the first time in multi-user mode, you'll see the **Adm
- Cannot be changed later without database access
2. **Display Name**: Enter a friendly name
-
- - Example: "System Administrator" or your real name
- - Can be changed later in your profile
- - Visible to other users in shared contexts
+ - Example: "System Administrator" or your real name
+ - Can be changed later in your profile
+ - Visible to other users in shared contexts
3. **Password**: Create a strong administrator password
-
- - **Minimum requirements:**
-
- - At least 8 characters long
- - Contains uppercase letters (A-Z)
- - Contains lowercase letters (a-z)
- - Contains numbers (0-9)
-
- - **Recommended:**
-
- - Use 12+ characters
- - Include special characters (!@#$%^&*)
- - Use a password manager to generate and store
- - Don't reuse passwords from other services
+ - **Minimum requirements:**
+ - At least 8 characters long
+ - Contains uppercase letters (A-Z)
+ - Contains lowercase letters (a-z)
+ - Contains numbers (0-9)
+
+ - **Recommended:**
+ - Use 12+ characters
+ - Include special characters (!@#$%^&\*)
+ - Use a password manager to generate and store
+ - Don't reuse passwords from other services
4. **Confirm Password**: Re-enter the password
5. Click **Create Administrator Account**
+
</Steps>
:::caution[Important]
@@ -120,10 +117,10 @@ InvokeAI can run in single-user or multi-user mode, controlled by the `multiuser
```yaml
# Enable/disable multi-user mode
-multiuser: true # Enable multi-user mode (requires authentication)
+multiuser: true # Enable multi-user mode (requires authentication)
# Optional password policy
-strict_password_checking: true # Enforce uppercase/lowercase/number requirements
+strict_password_checking: true # Enforce uppercase/lowercase/number requirements
```
JWT secrets are generated automatically and stored in the database. Session lifetimes default to 24 hours, or 7 days when the user selects "Remember me". See Secret Key Management below if you need to rotate the JWT secret.
@@ -139,10 +136,15 @@ JWT secrets are generated automatically and stored in the database. Session life
When upgrading from a single-user installation or switching modes:
<Steps>
+
1. **Automatic Migration**: The database will automatically migrate to multi-user schema when multi-user mode is first enabled
+
2. **Legacy Data Ownership**: Existing data (boards, images, workflows) created in single-user mode is assigned to an internal user named "system"
+
3. **Administrator Access**: Only administrators will have access to legacy "system"-owned assets when in multi-user mode
+
4. **No Data Loss**: All existing content is preserved
+
</Steps>
**Migration Process:**
@@ -188,12 +190,12 @@ All command-line arguments are optional. The scripts will prompt you to provide
The commands are:
-| Name | Function | Example CLI Usage |
-|--------------------|---------------|--------------------|
-|**invoke-useradd** | add a user | `invoke-useradd --email [email protected] --name "Example User" --password "badpassword"` |
-|**invoke-usermod** | modify a user | `invoke-usermod --email [email protected] --name "Mr. Example User" --password "8adsf2**%"` |
-|**invoke-userdel** | delete a user | `invoke-userdel --email [email protected] --force` |
-|**invoke-userlist** | list all users| `invoke-userlist` |
+| Name | Function | Example CLI Usage |
+| ------------------- | -------------- | ------------------------------------------------------------------------------------------ |
+| **invoke-useradd** | add a user | `invoke-useradd --email [email protected] --name "Example User" --password "badpassword"` |
+| **invoke-usermod** | modify a user | `invoke-usermod --email [email protected] --name "Mr. Example User" --password "8adsf2**%"` |
+| **invoke-userdel** | delete a user | `invoke-userdel --email [email protected] --force` |
+| **invoke-userlist** | list all users | `invoke-userlist` |
Pass the `--help` argument to get the usage of each script. For example:
@@ -224,8 +226,25 @@ workflows, queue items, or style presets they created — those rows remain in t
a user_id that no longer exists, and will not appear in other (non-admin) users' galleries.
Administrators keep gallery visibility of the orphaned images and videos and can review or delete
them from there. Physical media files in `outputs/images` and `outputs/videos` are also left in
-place: orphan image files can be removed with a gallery maintenance script, while video files should
-be deleted through the gallery (which removes the file along with the record) or cleaned up manually.
+place. Administrators can use **Settings > Data & workspace > Gallery maintenance** to review and
+remove database records whose image files are missing, archive image files and thumbnails that are
+not associated with database records, or regenerate missing thumbnails. These actions cover images
+across all accounts, including archived-board and intermediate images; they do not maintain videos.
+Each action scans when requested, then requires confirmation before it runs. Execution is blocking,
+so the request waits for the operation to finish. If the inventory changed since review, InvokeAI
+asks the administrator to review again.
+
+Removing a missing image record also removes its related semantic-index entries through the
+database's image-record relationship. The image record is deleted, and its thumbnail is archived
+when present; other images and their embeddings are preserved. Archive files are placed in a unique run
+directory under `<outdir>/images-archive/gallery-maintenance/`, where `<outdir>` is the configured
+`Paths.outdir` (for example, `outputs/images-archive/gallery-maintenance/remove_missing-<id>/`).
+Before making changes, the application creates a consistent database backup through its active
+database connection under `<db_dir>/backup/` (for example,
+`databases/backup/backup-<timestamp>-gallery-maintenance-<id>.db`). The result shows the exact
+backup and archive paths. Keep those files if you may need to recover database records or archived
+media. Gallery maintenance is part of the application and does not require a standalone script or
+a separate database connection.
If you want their content gone as well, reassign or delete it before deleting the user. Back up the
database first if recovery might be needed.
@@ -277,9 +296,8 @@ cannot be checked by InvokeAI. Do not enable `allow_private_download_urls` merel
make an untrusted proxy work. The two settings are independent: `download_proxy` is
honored whether or not `allow_private_download_urls` is enabled.
-
:::note[Strict Password Checking]
-It is recommended that you enable strict password checking. This will
+It is recommended that you enable strict password checking. This will
force all users to select good passwords that follow the
"minimal requirements" below. Do this by adding `strict_password_checking` to
the `invokeai.yaml` configuration file:
@@ -287,6 +305,7 @@ the `invokeai.yaml` configuration file:
```
strict_password_checking: true
```
+
:::
### Password Policies
@@ -321,7 +340,7 @@ At the client side, tokens are stored in browser localStorage. Logging out clear
The tokens include the user's ID, email, admin status, and a revocation counter, along with an HMAC signature.
-**Revocation:** A token proves *identity* only — expiry is not the only thing that can end a session. Every authenticated request re-reads the account from the database, so administrative changes take effect on the target's next request, without waiting for their token to expire and without requiring them to log out:
+**Revocation:** A token proves _identity_ only — expiry is not the only thing that can end a session. Every authenticated request re-reads the account from the database, so administrative changes take effect on the target's next request, without waiting for their token to expire and without requiring them to log out:
- **Role changes.** The admin status carried in a token is ignored; each request uses the role currently recorded for the account. A demoted administrator loses administrative endpoints immediately, and a promoted user gains them without logging in again.
- **Deactivation and deletion.** Requests from a deactivated or deleted account are rejected, its open connections are closed, and any of its queue items are canceled — a running one stops at the next node, or is canceled rather than recorded as completed if it was already on its last one, and pending ones are rejected when they reach the front of the queue. A generation that reports its progress (image generation does) stops part-way through the node instead of running it out. Work already completed is not undone.
@@ -331,7 +350,7 @@ Changes made through the web UI apply to open connections immediately. Changes m
If that sweep cannot read the database at all — the server is under enough load that its reads keep timing out, say — it does not assume the connections it cannot check are still entitled to what they hold. After a few consecutive failures, open connections lose their administrator privileges and stop receiving other users' events, while staying connected; the privilege comes back on its own once the record can be read again. An administrator who sees admin-only updates go quiet during a period of database trouble is seeing this, not a change to their account.
-That safeguard covers administrator privileges specifically. Closing a deactivated or deleted account's connection still waits for a successful read, so while the database is unreadable such a connection keeps receiving that account's *own* events until the sweep can confirm the change — every HTTP request it makes is rejected in the meantime, and it is closed as soon as a read succeeds.
+That safeguard covers administrator privileges specifically. Closing a deactivated or deleted account's connection still waits for a successful read, so while the database is unreadable such a connection keeps receiving that account's _own_ events until the sweep can confirm the change — every HTTP request it makes is rejected in the meantime, and it is closed as soon as a read succeeds.
Two limits are worth stating plainly. Revocation is enforced by this server, so a token remains cryptographically valid until it expires — anything that accepts these tokens without consulting the database would still honor it. And a session already in flight is stopped, not rewound: media already delivered to the client and outputs already written stay written.
@@ -506,11 +525,17 @@ Include these directories/files:
<Steps>
1. Install InvokeAI on new system
+
2. Restore configuration file
+
3. Restore database directory
+
4. Restore models and outputs
+
5. Verify file permissions
+
6. Start InvokeAI and test
+
</Steps>
## Troubleshooting
@@ -566,6 +591,7 @@ sqlite3 databases/invokeai.db "PRAGMA journal_mode=WAL;"
<Steps>
1. Stop InvokeAI
+
2. Direct database access:
```bash
@@ -586,6 +612,7 @@ sqlite3 databases/invokeai.db "PRAGMA journal_mode=WAL;"
```
4. Restart InvokeAI
+
</Steps>
:::note[Alternative Step 3]
@@ -596,8 +623,8 @@ to trigger the setup process when InvokeAI restarts:
DELETE FROM users
WHERE email = '[email protected]';
```
-:::
+:::
### Performance Issues
@@ -607,9 +634,13 @@ WHERE email = '[email protected]';
<Steps>
1. Check active generation count
+
2. Review resource usage (CPU/GPU/RAM)
+
3. Check database size and performance
+
4. Review network latency
+
</Steps>
**Solutions:**
@@ -657,13 +688,13 @@ schema_version: 4.0.2
multiuser: true
# Server
-host: "0.0.0.0"
+host: '0.0.0.0'
port: 9090
# Performance
enable_partial_loading: true
precision: float16
-pytorch_cuda_alloc_conf: "backend:cudaMallocAsync"
+pytorch_cuda_alloc_conf: 'backend:cudaMallocAsync'
hashing_algorithm: blake3_multi
```
@@ -699,9 +730,13 @@ Best practice:
<Steps>
1. Deactivate the account first
+
2. Transfer ownership of shared boards
+
3. After transition period, delete the account
+
4. Or keep the account deactivated for audit purposes
+
</Steps>
### What's the licensing impact of multi-user mode?
diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.py
index 4e4acacb41..faa3ec5243 100644
--- a/invokeai/app/api/dependencies.py
+++ b/invokeai/app/api/dependencies.py
@@ -26,6 +26,7 @@ from invokeai.app.services.external_generation.providers import (
from invokeai.app.services.external_generation.startup import sync_configured_external_starter_models
from invokeai.app.services.fonts.fonts_default import FontService
from invokeai.app.services.gallery.gallery_default import SqliteGalleryService
+from invokeai.app.services.gallery_maintenance.gallery_maintenance_default import GalleryMaintenanceService
from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
from invokeai.app.services.image_index.image_index_default import ImageIndexService, warm_up_attention
from invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlite
@@ -152,6 +153,7 @@ class ApiDependencies:
videos = VideoService()
board_video_records = SqliteBoardVideoRecordStorage(db=db)
gallery = SqliteGalleryService(db=db)
+ gallery_maintenance = GalleryMaintenanceService()
invocation_cache = MemoryInvocationCache(max_cache_size=config.node_cache_size)
tensors = ObjectSerializerForwardCache(
ObjectSerializerDisk[torch.Tensor](
@@ -267,6 +269,7 @@ class ApiDependencies:
image_index=image_index,
fonts=fonts,
intermediates=intermediates,
+ gallery_maintenance=gallery_maintenance,
)
# Constructing the Invoker starts every service, including the session
diff --git a/invokeai/app/api/routers/gallery_maintenance.py b/invokeai/app/api/routers/gallery_maintenance.py
new file mode 100644
index 0000000000..277688e7e4
--- /dev/null
+++ b/invokeai/app/api/routers/gallery_maintenance.py
@@ -0,0 +1,130 @@
+import logging
+from typing import NoReturn
+
+from fastapi import HTTPException, status
+from fastapi.routing import APIRouter
+
+from invokeai.app.api.auth_dependencies import AdminUserOrDefault
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.services.gallery_maintenance.gallery_maintenance_common import (
+ GalleryMaintenanceConflict,
+ GalleryMaintenanceExecuteRequest,
+ GalleryMaintenanceOperation,
+ GalleryMaintenancePreview,
+ GalleryMaintenancePreviewChanged,
+ GalleryMaintenancePreviewRequest,
+ GalleryMaintenanceResult,
+)
+from invokeai.app.services.image_moves.image_moves_default import ImageMoveJobAlreadyRunning, ImageMoveQueueActive
+
+logger = logging.getLogger(__name__)
+
+gallery_maintenance_router = APIRouter(prefix="/v1/app/gallery/maintenance", tags=["gallery_maintenance"])
+
+
+def _get_service():
+ service = getattr(ApiDependencies.invoker.services, "gallery_maintenance", None)
+ if service is None:
+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Gallery maintenance unavailable")
+ return service
+
+
+def _raise_safe_error(error: Exception) -> NoReturn:
+ logger.exception("Gallery maintenance operation failed")
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Gallery maintenance failed"
+ ) from error
+
+
+@gallery_maintenance_router.post(
+ "/preview",
+ operation_id="preview_gallery_maintenance",
+ response_model=GalleryMaintenancePreview,
+ status_code=status.HTTP_200_OK,
+ responses={
+ 401: {"description": "Authentication required"},
+ 403: {"description": "Admin privileges required"},
+ 409: {"description": "Gallery maintenance is already active"},
+ 500: {"description": "Gallery maintenance preview failed"},
+ 503: {"description": "Gallery maintenance unavailable"},
+ },
+)
+def preview_gallery_maintenance(
+ request: GalleryMaintenancePreviewRequest, _: AdminUserOrDefault
+) -> GalleryMaintenancePreview:
+ service = _get_service()
+ try:
+ return service.preview(request.operation)
+ except (GalleryMaintenanceConflict, ImageMoveJobAlreadyRunning, ImageMoveQueueActive) as error:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Image storage is busy") from error
+ except Exception as error:
+ _raise_safe_error(error)
+
+
+def _execute_gallery_maintenance(
+ operation: GalleryMaintenanceOperation, request: GalleryMaintenanceExecuteRequest
+) -> GalleryMaintenanceResult:
+ service = _get_service()
+ try:
+ return service.execute(operation, request.fingerprint)
+ except GalleryMaintenancePreviewChanged as error:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="Gallery contents changed after preview. Preview again before continuing.",
+ ) from error
+ except (GalleryMaintenanceConflict, ImageMoveJobAlreadyRunning, ImageMoveQueueActive) as error:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Image storage is busy") from error
+ except Exception as error:
+ _raise_safe_error(error)
+
+
+@gallery_maintenance_router.post(
+ "/remove-missing",
+ operation_id="remove_missing_images",
+ response_model=GalleryMaintenanceResult,
+ responses={
+ 401: {"description": "Authentication required"},
+ 403: {"description": "Admin privileges required"},
+ 409: {"description": "Preview is stale or image storage is busy"},
+ 500: {"description": "Gallery maintenance failed"},
+ 503: {"description": "Gallery maintenance unavailable"},
+ },
+)
+def remove_missing_images(request: GalleryMaintenanceExecuteRequest, _: AdminUserOrDefault) -> GalleryMaintenanceResult:
+ return _execute_gallery_maintenance(GalleryMaintenanceOperation.REMOVE_MISSING, request)
+
+
+@gallery_maintenance_router.post(
+ "/archive-untracked",
+ operation_id="archive_untracked_images",
+ response_model=GalleryMaintenanceResult,
+ responses={
+ 401: {"description": "Authentication required"},
+ 403: {"description": "Admin privileges required"},
+ 409: {"description": "Preview is stale or image storage is busy"},
+ 500: {"description": "Gallery maintenance failed"},
+ 503: {"description": "Gallery maintenance unavailable"},
+ },
+)
+def archive_untracked_images(
+ request: GalleryMaintenanceExecuteRequest, _: AdminUserOrDefault
+) -> GalleryMaintenanceResult:
+ return _execute_gallery_maintenance(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED, request)
+
+
+@gallery_maintenance_router.post(
+ "/regenerate-thumbnails",
+ operation_id="regenerate_missing_thumbnails",
+ response_model=GalleryMaintenanceResult,
+ responses={
+ 401: {"description": "Authentication required"},
+ 403: {"description": "Admin privileges required"},
+ 409: {"description": "Preview is stale or image storage is busy"},
+ 500: {"description": "Gallery maintenance failed"},
+ 503: {"description": "Gallery maintenance unavailable"},
+ },
+)
+def regenerate_missing_thumbnails(
+ request: GalleryMaintenanceExecuteRequest, _: AdminUserOrDefault
+) -> GalleryMaintenanceResult:
+ return _execute_gallery_maintenance(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, request)
diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.py
index 89513a4104..fbffb6f3d4 100644
--- a/invokeai/app/api_app.py
+++ b/invokeai/app/api_app.py
@@ -31,6 +31,7 @@ from invokeai.app.api.routers import (
custom_nodes,
fonts,
gallery,
+ gallery_maintenance,
image_map,
image_moves,
images,
@@ -747,6 +748,7 @@ app.include_router(image_map.image_map_router, prefix="/api")
app.include_router(intermediates.intermediates_router, prefix="/api")
app.include_router(videos.videos_router, prefix="/api")
app.include_router(gallery.gallery_router, prefix="/api")
+app.include_router(gallery_maintenance.gallery_maintenance_router, prefix="/api")
app.include_router(boards.boards_router, prefix="/api")
app.include_router(board_images.board_images_router, prefix="/api")
app.include_router(virtual_boards.virtual_boards_router, prefix="/api")
diff --git a/invokeai/app/services/gallery_maintenance/__init__.py b/invokeai/app/services/gallery_maintenance/__init__.py
new file mode 100644
index 0000000000..f3799fd134
--- /dev/null
+++ b/invokeai/app/services/gallery_maintenance/__init__.py
@@ -0,0 +1,5 @@
+"""Application-owned image gallery maintenance operations."""
+
+from invokeai.app.services.gallery_maintenance.gallery_maintenance_default import GalleryMaintenanceService
+
+__all__ = ["GalleryMaintenanceService"]
diff --git a/invokeai/app/services/gallery_maintenance/gallery_maintenance_common.py b/invokeai/app/services/gallery_maintenance/gallery_maintenance_common.py
new file mode 100644
index 0000000000..4ada8fe5a7
--- /dev/null
+++ b/invokeai/app/services/gallery_maintenance/gallery_maintenance_common.py
@@ -0,0 +1,62 @@
+"""Typed contracts for application-owned gallery maintenance."""
+
+from enum import Enum
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
+
+class GalleryMaintenanceOperation(str, Enum):
+ REMOVE_MISSING = "remove_missing"
+ ARCHIVE_UNTRACKED = "archive_untracked"
+ REGENERATE_THUMBNAILS = "regenerate_thumbnails"
+
+
+class GalleryMaintenancePreviewRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ operation: GalleryMaintenanceOperation
+
+
+class GalleryMaintenanceExecuteRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ fingerprint: str = Field(min_length=64, max_length=64, pattern=r"^[0-9a-f]{64}$")
+
+
+class GalleryMaintenancePreview(BaseModel):
+ operation: GalleryMaintenanceOperation
+ fingerprint: str = Field(min_length=64, max_length=64, pattern=r"^[0-9a-f]{64}$")
+ examined_count: int = Field(ge=0)
+ affected_count: int = Field(ge=0)
+ skipped_count: int = Field(ge=0)
+ error_count: int = Field(ge=0)
+ errors: list[str] = Field(default_factory=list, max_length=20)
+ archive_path: str | None = None
+
+
+class GalleryMaintenanceResult(BaseModel):
+ operation: GalleryMaintenanceOperation
+ status: Literal["completed", "partial", "no_op", "failed"]
+ examined_count: int = Field(ge=0)
+ skipped_count: int = Field(ge=0)
+ failed_count: int = Field(ge=0)
+ records_removed: int = Field(ge=0)
+ images_archived: int = Field(ge=0)
+ thumbnails_archived: int = Field(ge=0)
+ thumbnails_regenerated: int = Field(ge=0)
+ archive_path: str | None = None
+ backup_path: str | None = None
+ errors: list[str] = Field(default_factory=list, max_length=20)
+
+
+class GalleryMaintenanceError(Exception):
+ """A maintenance scan or operation could not safely complete."""
+
+
+class GalleryMaintenancePreviewChanged(GalleryMaintenanceError):
+ """The current inventory no longer matches the preview the administrator confirmed."""
+
+
+class GalleryMaintenanceConflict(GalleryMaintenanceError):
+ """Another operation or active queue work prevents maintenance from starting."""
diff --git a/invokeai/app/services/gallery_maintenance/gallery_maintenance_default.py b/invokeai/app/services/gallery_maintenance/gallery_maintenance_default.py
new file mode 100644
index 0000000000..0eaea62a4c
--- /dev/null
+++ b/invokeai/app/services/gallery_maintenance/gallery_maintenance_default.py
@@ -0,0 +1,986 @@
+"""Application-owned image gallery maintenance operations."""
+
+import hashlib
+import json
+import os
+import shutil
+import sqlite3
+import stat
+import tempfile
+import uuid
+from collections.abc import Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import TYPE_CHECKING, Literal
+
+from invokeai.app.services.gallery_maintenance.gallery_maintenance_common import (
+ GalleryMaintenanceConflict,
+ GalleryMaintenanceError,
+ GalleryMaintenanceOperation,
+ GalleryMaintenancePreview,
+ GalleryMaintenancePreviewChanged,
+ GalleryMaintenanceResult,
+)
+from invokeai.app.services.image_moves.image_moves_default import ImageMoveJobAlreadyRunning, ImageMoveQueueActive
+from invokeai.app.util.thumbnails import get_thumbnail_name
+from invokeai.backend.util.logging import InvokeAILogger
+
+if TYPE_CHECKING:
+ from invokeai.app.services.invoker import Invoker
+
+_ENUMERATION_BATCH_SIZE = 250
+_MAX_RESULT_ERRORS = 20
+_MAX_ERROR_LENGTH = 300
+_OperationStatus = Literal["completed", "partial", "no_op", "failed"]
+_StatSignature = tuple[int, int, int, int, int, int]
+
+
+@dataclass(frozen=True)
+class _Scan:
+ fingerprint: str
+ examined_count: int
+ affected_count: int
+ skipped_count: int
+
+
+@dataclass
+class _ResultCounts:
+ examined_count: int = 0
+ skipped_count: int = 0
+ failed_count: int = 0
+ records_removed: int = 0
+ images_archived: int = 0
+ thumbnails_archived: int = 0
+ thumbnails_regenerated: int = 0
+ errors: list[str] = field(default_factory=list)
+ archive_path: str | None = None
+ backup_path: str | None = None
+
+ def add_error(self, description: str) -> None:
+ if len(self.errors) < _MAX_RESULT_ERRORS:
+ self.errors.append(description[:_MAX_ERROR_LENGTH])
+
+ def result(self, operation: GalleryMaintenanceOperation) -> GalleryMaintenanceResult:
+ affected = self.records_removed + self.images_archived + self.thumbnails_archived + self.thumbnails_regenerated
+ if self.failed_count == 0 and self.skipped_count == 0 and affected == 0:
+ status: _OperationStatus = "no_op"
+ elif self.failed_count or self.skipped_count:
+ status = "partial"
+ else:
+ status = "completed"
+ if self.failed_count and affected == 0:
+ status = "failed"
+
+ return GalleryMaintenanceResult(
+ operation=operation,
+ status=status,
+ examined_count=self.examined_count,
+ skipped_count=self.skipped_count,
+ failed_count=self.failed_count,
+ records_removed=self.records_removed,
+ images_archived=self.images_archived,
+ thumbnails_archived=self.thumbnails_archived,
+ thumbnails_regenerated=self.thumbnails_regenerated,
+ archive_path=self.archive_path,
+ backup_path=self.backup_path,
+ errors=self.errors,
+ )
+
+
+class GalleryMaintenanceService:
+ """Coordinates installation-wide maintenance through the active application services."""
+
+ def start(self, invoker: "Invoker") -> None:
+ self._invoker = invoker
+ self._logger = InvokeAILogger.get_logger(self.__class__.__name__)
+
+ def preview(self, operation: GalleryMaintenanceOperation) -> GalleryMaintenancePreview:
+ operation = self._normalize_operation(operation)
+ with self._reserve():
+ with self._inventory() as inventory:
+ scan = self._scan(operation, inventory)
+ return GalleryMaintenancePreview(
+ operation=operation,
+ fingerprint=scan.fingerprint,
+ examined_count=scan.examined_count,
+ affected_count=scan.affected_count,
+ skipped_count=scan.skipped_count,
+ error_count=0,
+ errors=[],
+ archive_path=str(self._archive_root) if self._archives(operation) else None,
+ )
+
+ def execute(self, operation: GalleryMaintenanceOperation, expected_fingerprint: str) -> GalleryMaintenanceResult:
+ operation = self._normalize_operation(operation)
+ if len(expected_fingerprint) != 64 or any(
+ character not in "0123456789abcdef" for character in expected_fingerprint
+ ):
+ raise GalleryMaintenanceError("The preview fingerprint is invalid; preview this operation again.")
+
+ with self._reserve():
+ with self._inventory() as inventory:
+ scan = self._scan(operation, inventory)
+ if scan.fingerprint != expected_fingerprint:
+ raise GalleryMaintenancePreviewChanged(
+ "The gallery changed after preview. Refresh the preview and confirm again."
+ )
+
+ counts = _ResultCounts(
+ examined_count=scan.examined_count,
+ skipped_count=scan.skipped_count,
+ archive_path=str(self._archive_root) if self._archives(operation) else None,
+ )
+ if scan.affected_count == 0:
+ return counts.result(operation)
+
+ counts.backup_path = self._create_backup()
+ if self._archives(operation):
+ try:
+ counts.archive_path = str(self._create_archive_run(operation))
+ except GalleryMaintenanceError:
+ raise
+ except Exception as e:
+ self._logger.exception("Could not prepare gallery archive storage")
+ raise GalleryMaintenanceError("Could not safely prepare archive storage.") from e
+
+ try:
+ if operation is GalleryMaintenanceOperation.REMOVE_MISSING:
+ self._remove_missing(inventory, counts)
+ elif operation is GalleryMaintenanceOperation.ARCHIVE_UNTRACKED:
+ self._archive_untracked(inventory, counts)
+ else:
+ self._regenerate_thumbnails(inventory, counts)
+ except Exception:
+ self._logger.exception("Gallery maintenance stopped after partial changes")
+ counts.failed_count += 1
+ counts.add_error("Gallery maintenance stopped after a storage or database error.")
+ return counts.result(operation)
+
+ def _normalize_operation(self, operation: GalleryMaintenanceOperation) -> GalleryMaintenanceOperation:
+ try:
+ return GalleryMaintenanceOperation(operation)
+ except ValueError as e:
+ raise GalleryMaintenanceError("Unsupported gallery maintenance operation.") from e
+
+ @contextmanager
+ def _reserve(self) -> Iterator[None]:
+ image_moves = getattr(self._invoker.services, "image_moves", None)
+ if image_moves is None:
+ raise GalleryMaintenanceError("Image storage maintenance is unavailable.")
+ try:
+ with image_moves.reserve_gallery_maintenance():
+ yield
+ except (ImageMoveJobAlreadyRunning, ImageMoveQueueActive) as e:
+ raise GalleryMaintenanceConflict("Image storage or queue work is active.") from e
+
+ @property
+ def _services(self):
+ return self._invoker.services
+
+ @property
+ def _archive_root(self) -> Path:
+ return self._services.image_files.image_root.parent / "images-archive"
+
+ @staticmethod
+ def _archives(operation: GalleryMaintenanceOperation) -> bool:
+ return operation in {
+ GalleryMaintenanceOperation.REMOVE_MISSING,
+ GalleryMaintenanceOperation.ARCHIVE_UNTRACKED,
+ }
+
+ @contextmanager
+ def _inventory(self) -> Iterator[sqlite3.Connection]:
+ """Spools the confirmed inventory to disk so execution never materializes the gallery in RAM."""
+ with tempfile.TemporaryDirectory(prefix="invokeai-gallery-maintenance-") as directory:
+ connection = sqlite3.connect(Path(directory) / "inventory.sqlite")
+ try:
+ connection.executescript(
+ """
+ CREATE TABLE records (
+ image_name TEXT PRIMARY KEY,
+ subfolder TEXT NOT NULL,
+ original_signature TEXT,
+ thumbnail_signature TEXT,
+ action INTEGER NOT NULL DEFAULT 0,
+ duplicate INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE files (
+ kind TEXT NOT NULL,
+ relative_path TEXT NOT NULL,
+ base_name TEXT NOT NULL,
+ subfolder TEXT NOT NULL,
+ signature TEXT,
+ action INTEGER NOT NULL,
+ PRIMARY KEY(kind, relative_path)
+ );
+ CREATE INDEX files_by_name ON files(kind, base_name);
+ """
+ )
+ yield connection
+ finally:
+ connection.close()
+
+ def _scan(self, operation: GalleryMaintenanceOperation, inventory: sqlite3.Connection) -> _Scan:
+ digest = hashlib.sha256()
+ try:
+ root_signatures = self._validate_storage_roots()
+ roots = self._fingerprint_roots(operation)
+ self._feed(digest, "gallery-maintenance-v2", operation.value, *roots, *root_signatures)
+ if operation is GalleryMaintenanceOperation.REMOVE_MISSING:
+ return self._scan_remove_missing(digest, inventory)
+ if operation is GalleryMaintenanceOperation.ARCHIVE_UNTRACKED:
+ return self._scan_archive_untracked(digest, inventory)
+ return self._scan_regenerate_thumbnails(digest, inventory)
+ except GalleryMaintenanceError:
+ raise
+ except Exception as e:
+ self._logger.exception("Gallery maintenance scan failed for %s", operation.value)
+ raise GalleryMaintenanceError("Could not safely inspect gallery storage.") from e
+
+ def _validate_storage_roots(self) -> tuple[str, str]:
+ signatures: list[str] = []
+ for root in (self._services.image_files.image_root, self._services.image_files.thumbnail_root):
+ try:
+ result = root.lstat()
+ if stat.S_ISLNK(result.st_mode) or not stat.S_ISDIR(result.st_mode):
+ raise GalleryMaintenanceError("A required gallery storage root is unavailable.")
+ # Opening the directory catches unreadable roots even when the operation has no
+ # file paths to enumerate (for example, an empty gallery).
+ with os.scandir(root) as entries:
+ next(entries, None)
+ except GalleryMaintenanceError:
+ raise
+ except OSError as e:
+ self._logger.warning("Could not inspect gallery storage root (%s)", e.errno)
+ raise GalleryMaintenanceError("A required gallery storage root is unavailable.") from e
+ signatures.append(json.dumps(self._signature(result), separators=(",", ":")))
+ return signatures[0], signatures[1]
+
+ def _fingerprint_roots(self, operation: GalleryMaintenanceOperation) -> tuple[str, ...]:
+ files = self._services.image_files
+ roots = [str(files.image_root.resolve()), str(files.thumbnail_root.resolve())]
+ if self._archives(operation):
+ roots.append(str(self._archive_root.resolve()))
+ return tuple(roots)
+
+ @staticmethod
+ def _feed(digest, *parts: object) -> None:
+ digest.update(json.dumps(parts, ensure_ascii=True, separators=(",", ":")).encode("utf-8"))
+ digest.update(b"\n")
+
+ def _scan_remove_missing(self, digest, inventory: sqlite3.Connection) -> _Scan:
+ examined = affected = skipped = 0
+ for image_name, subfolder in self._services.image_records.iter_all_image_locations(_ENUMERATION_BATCH_SIZE):
+ examined += 1
+ self._feed(digest, "record", image_name, subfolder)
+ original = self._record_path(image_name, subfolder)
+ thumbnail = self._record_path(image_name, subfolder, thumbnail=True)
+ original_stat = self._stat(original)
+ thumbnail_stat = self._stat(thumbnail)
+ self._feed_stat(digest, "original", image_name, subfolder, original_stat)
+ self._feed_stat(digest, "thumbnail", image_name, subfolder, thumbnail_stat)
+ inventory.execute(
+ "INSERT INTO records(image_name, subfolder, original_signature, thumbnail_signature, action) "
+ "VALUES (?, ?, ?, ?, ?)",
+ (
+ image_name,
+ subfolder,
+ self._encode_signature(original_stat),
+ self._encode_signature(thumbnail_stat),
+ int(original_stat is None),
+ ),
+ )
+
+ for paths in self._batches(self._services.image_files.iter_image_paths()):
+ for path in paths:
+ relative = self._relative(path, self._services.image_files.image_root)
+ subfolder = self._relative_parent(path, self._services.image_files.image_root)
+ signature = self._stat(path)
+ self._feed_stat(digest, "image-file", relative, signature)
+ inventory.execute(
+ "INSERT INTO files(kind, relative_path, base_name, subfolder, signature, action) "
+ "VALUES ('image', ?, ?, ?, ?, 0)",
+ (relative, path.name, subfolder, self._encode_signature(signature)),
+ )
+ inventory.execute(
+ "UPDATE records SET duplicate = 1 WHERE image_name = ? AND subfolder != ?",
+ (path.name, subfolder),
+ )
+
+ inventory.commit()
+ for (is_duplicate,) in inventory.execute("SELECT duplicate FROM records WHERE action = 1 ORDER BY image_name"):
+ if is_duplicate:
+ skipped += 1
+ else:
+ affected += 1
+ inventory.execute("UPDATE records SET action = 0 WHERE duplicate = 1")
+ return _Scan(digest.hexdigest(), examined, affected, skipped)
+
+ @staticmethod
+ def _encode_signature(signature: _StatSignature | None) -> str | None:
+ return None if signature is None else json.dumps(signature, separators=(",", ":"))
+
+ @staticmethod
+ def _decode_signature(signature: str | None) -> _StatSignature | None:
+ return None if signature is None else tuple(json.loads(signature)) # type: ignore[return-value]
+
+ def _scan_archive_untracked(self, digest, inventory: sqlite3.Connection) -> _Scan:
+ examined = affected = skipped = 0
+ self._feed_records(digest, inventory)
+
+ for paths in self._batches(self._services.image_files.iter_image_paths()):
+ locations = self._services.image_records.get_subfolders([path.name for path in paths])
+ for path in paths:
+ examined += 1
+ subfolder = self._relative_parent(path, self._services.image_files.image_root)
+ signature = self._stat(path)
+ self._feed_stat(
+ digest, "image-file", self._relative(path, self._services.image_files.image_root), signature
+ )
+ stored_subfolder = locations.get(path.name)
+ if stored_subfolder is None:
+ affected += 1
+ elif stored_subfolder != subfolder:
+ skipped += 1
+ inventory.execute(
+ "INSERT INTO files(kind, relative_path, base_name, subfolder, signature, action) "
+ "VALUES ('image', ?, ?, ?, ?, ?)",
+ (
+ self._relative(path, self._services.image_files.image_root),
+ path.name,
+ subfolder,
+ self._encode_signature(signature),
+ int(stored_subfolder is None),
+ ),
+ )
+
+ for paths in self._batches(self._services.image_files.iter_thumbnail_paths()):
+ names = [f"{path.stem}.png" for path in paths]
+ locations = self._services.image_records.get_subfolders(names)
+ for path in paths:
+ examined += 1
+ subfolder = self._relative_parent(path, self._services.image_files.thumbnail_root)
+ signature = self._stat(path)
+ self._feed_stat(
+ digest,
+ "thumbnail-file",
+ self._relative(path, self._services.image_files.thumbnail_root),
+ signature,
+ )
+ source_name = f"{path.stem}.png"
+ stored_subfolder = locations.get(source_name)
+ action = False
+ if stored_subfolder is not None:
+ if stored_subfolder != subfolder:
+ skipped += 1
+ # A thumbnail still associated with a record is recoverable even if its
+ # original is missing; remove-missing owns that record and thumbnail pair.
+ continue
+ original = self._record_path(source_name, subfolder)
+ if self._stat(original) is None:
+ affected += 1
+ action = True
+ else:
+ original_relative = (Path(subfolder) / source_name).as_posix()
+ row = inventory.execute(
+ "SELECT action FROM files WHERE kind = 'image' AND relative_path = ?",
+ (original_relative,),
+ ).fetchone()
+ action = row is not None and bool(row[0])
+ inventory.execute(
+ "INSERT INTO files(kind, relative_path, base_name, subfolder, signature, action) "
+ "VALUES ('thumbnail', ?, ?, ?, ?, ?)",
+ (
+ self._relative(path, self._services.image_files.thumbnail_root),
+ path.name,
+ subfolder,
+ self._encode_signature(signature),
+ int(action),
+ ),
+ )
+
+ inventory.commit()
+ return _Scan(digest.hexdigest(), examined, affected, skipped)
+
+ def _scan_regenerate_thumbnails(self, digest, inventory: sqlite3.Connection) -> _Scan:
+ examined = affected = skipped = 0
+ for image_name, subfolder in self._services.image_records.iter_all_image_locations(_ENUMERATION_BATCH_SIZE):
+ examined += 1
+ self._feed(digest, "record", image_name, subfolder)
+ original = self._record_path(image_name, subfolder)
+ thumbnail = self._record_path(image_name, subfolder, thumbnail=True)
+ original_stat = self._stat(original)
+ thumbnail_stat = self._stat(thumbnail)
+ self._feed_stat(digest, "original", image_name, subfolder, original_stat)
+ self._feed_stat(digest, "thumbnail", image_name, subfolder, thumbnail_stat)
+ if original_stat is None:
+ skipped += 1
+ elif thumbnail_stat is None:
+ affected += 1
+ inventory.execute(
+ "INSERT INTO records(image_name, subfolder, original_signature, thumbnail_signature, action) "
+ "VALUES (?, ?, ?, ?, ?)",
+ (
+ image_name,
+ subfolder,
+ self._encode_signature(original_stat),
+ self._encode_signature(thumbnail_stat),
+ int(original_stat is not None and thumbnail_stat is None),
+ ),
+ )
+ inventory.commit()
+ return _Scan(digest.hexdigest(), examined, affected, skipped)
+
+ def _feed_records(self, digest, inventory: sqlite3.Connection) -> None:
+ for image_name, subfolder in self._services.image_records.iter_all_image_locations(_ENUMERATION_BATCH_SIZE):
+ self._feed(digest, "record", image_name, subfolder)
+ inventory.execute(
+ "INSERT INTO records(image_name, subfolder, action) VALUES (?, ?, 0)", (image_name, subfolder)
+ )
+
+ @staticmethod
+ def _batches(paths: Iterator[Path]) -> Iterator[list[Path]]:
+ batch: list[Path] = []
+ for path in paths:
+ batch.append(path)
+ if len(batch) == _ENUMERATION_BATCH_SIZE:
+ yield batch
+ batch = []
+ if batch:
+ yield batch
+
+ def _record_path(self, image_name: str, subfolder: str, thumbnail: bool = False) -> Path:
+ files = self._services.image_files
+ root = files.thumbnail_root if thumbnail else files.image_root
+ filename = get_thumbnail_name(image_name) if thumbnail else image_name
+ relative = Path(subfolder) / filename
+ if relative.is_absolute() or ".." in relative.parts:
+ raise GalleryMaintenanceError("An image record contains an unsafe storage path.")
+
+ current = root
+ for part in relative.parts:
+ current /= part
+ try:
+ mode = current.lstat().st_mode
+ except FileNotFoundError:
+ break
+ except OSError as e:
+ raise GalleryMaintenanceError("Could not inspect an image storage path.") from e
+ if stat.S_ISLNK(mode):
+ raise GalleryMaintenanceError("Gallery maintenance does not follow symbolic links.")
+
+ try:
+ path = files.get_path(image_name, thumbnail=thumbnail, image_subfolder=subfolder)
+ except (ValueError, OSError) as e:
+ self._logger.error("Invalid recorded image path for %s", image_name)
+ raise GalleryMaintenanceError("An image record contains an unsafe storage path.") from e
+ return path
+
+ def _stat(self, path: Path) -> _StatSignature | None:
+ try:
+ result = path.lstat()
+ except FileNotFoundError:
+ return None
+ except OSError as e:
+ self._logger.warning("Could not inspect gallery path (%s)", e.errno)
+ raise GalleryMaintenanceError("Could not safely inspect gallery storage.") from e
+ if not stat.S_ISREG(result.st_mode):
+ raise GalleryMaintenanceError("Gallery storage contains a non-file at an image path.")
+ return self._signature(result)
+
+ @staticmethod
+ def _signature(result: os.stat_result) -> _StatSignature:
+ return (
+ result.st_dev,
+ result.st_ino,
+ result.st_mode,
+ result.st_size,
+ result.st_mtime_ns,
+ result.st_ctime_ns,
+ )
+
+ def _feed_stat(self, digest, *parts: object) -> None:
+ self._feed(digest, *parts)
+
+ @staticmethod
+ def _relative(path: Path, root: Path) -> str:
+ try:
+ return path.relative_to(root).as_posix()
+ except ValueError as e:
+ raise GalleryMaintenanceError("Gallery file escaped its configured storage root.") from e
+
+ def _relative_parent(self, path: Path, root: Path) -> str:
+ parent = path.parent
+ relative = self._relative(parent, root)
+ return "" if relative == "." else relative
+
+ def _create_backup(self) -> str:
+ backup_dir = self._services.configuration.db_path.parent / "backup"
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ destination = backup_dir / f"backup-{timestamp}-gallery-maintenance-{uuid.uuid4().hex}.db"
+ missing_directories: list[Path] = []
+ current = backup_dir
+ while not current.exists():
+ missing_directories.append(current)
+ current = current.parent
+ try:
+ self._services.database.backup_to(destination)
+ for directory in reversed(missing_directories):
+ self.__fsync_directory(directory.parent)
+ if not missing_directories:
+ self.__fsync_directory(backup_dir.parent)
+ self.__fsync_directory(backup_dir)
+ except Exception as e:
+ self._logger.exception("Gallery maintenance database backup failed")
+ raise GalleryMaintenanceError("The database backup failed; no gallery changes were made.") from e
+ return str(destination)
+
+ def _create_archive_run(self, operation: GalleryMaintenanceOperation) -> Path:
+ root = self._archive_root
+ self._ensure_archive_directory(root)
+ run_parent = root / "gallery-maintenance"
+ self._ensure_archive_directory(run_parent)
+ run_path = run_parent / f"{operation.value}-{uuid.uuid4().hex}"
+ run_path.mkdir(exist_ok=False)
+ self._assert_archive_root(run_path)
+ self.__fsync_directory(run_parent)
+ return run_path
+
+ def _ensure_archive_directory(self, path: Path) -> None:
+ """Create archive directories one level at a time and persist every parent entry."""
+ self._assert_archive_root(path)
+ output_root = self._services.image_files.image_root.parent.resolve()
+ current = output_root
+ for part in path.relative_to(output_root).parts:
+ current /= part
+ current.mkdir(exist_ok=True)
+ self._assert_archive_root(current)
+ if not stat.S_ISDIR(current.lstat().st_mode):
+ raise OSError("Archive path component is not a directory")
+ self.__fsync_directory(current.parent)
+
+ def _assert_archive_root(self, path: Path) -> None:
+ output_root = self._services.image_files.image_root.parent.resolve()
+ current = output_root
+ try:
+ relative = path.relative_to(output_root)
+ except ValueError as e:
+ raise GalleryMaintenanceError("Archive path escaped the configured output directory.") from e
+ for part in relative.parts:
+ current /= part
+ try:
+ mode = current.lstat().st_mode
+ except FileNotFoundError:
+ continue
+ except OSError as e:
+ raise GalleryMaintenanceError("Could not inspect the configured archive directory.") from e
+ if stat.S_ISLNK(mode):
+ raise GalleryMaintenanceError("Gallery maintenance does not follow archive symlinks.")
+
+ def _remove_missing(self, inventory: sqlite3.Connection, counts: _ResultCounts) -> None:
+ archive_run = Path(counts.archive_path) if counts.archive_path else None
+ cursor = inventory.execute(
+ "SELECT image_name, subfolder, thumbnail_signature FROM records WHERE action = 1 ORDER BY image_name"
+ )
+ while page := cursor.fetchmany(_ENUMERATION_BATCH_SIZE):
+ self._remove_missing_page(page, archive_run, counts)
+
+ def _remove_missing_page(
+ self, page: list[tuple[str, str, str | None]], archive_run: Path | None, counts: _ResultCounts
+ ) -> None:
+ files = self._services.image_files
+ records = self._services.image_records
+ locations = records.get_subfolders([image_name for image_name, _subfolder, _thumb in page])
+ delete_items: list[tuple[str, str, Path, Path, _StatSignature | None, Path | None, _StatSignature | None]] = []
+ for image_name, subfolder, encoded_thumbnail_signature in page:
+ if locations.get(image_name) != subfolder:
+ counts.skipped_count += 1
+ continue
+ original = self._record_path(image_name, subfolder)
+ thumbnail = self._record_path(image_name, subfolder, thumbnail=True)
+ thumbnail_signature = self._decode_signature(encoded_thumbnail_signature)
+ archived_thumbnail: Path | None = None
+ archive_counted = False
+ try:
+ if self._stat(original) is not None or self._stat(thumbnail) != thumbnail_signature:
+ counts.skipped_count += 1
+ continue
+ archived_signature: _StatSignature | None = None
+ if thumbnail_signature is not None:
+ if archive_run is None:
+ raise GalleryMaintenanceError("Archive destination was not prepared.")
+ archived_thumbnail = archive_run / "thumbnails" / Path(subfolder) / thumbnail.name
+ self._archive_file(thumbnail, archived_thumbnail, thumbnail_signature)
+ archived_signature = self._path_signature(archived_thumbnail)
+ if archived_signature is None:
+ raise OSError("Archived thumbnail disappeared before record removal")
+ counts.thumbnails_archived += 1
+ archive_counted = True
+ files.evict_cache_paths([thumbnail])
+ delete_items.append(
+ (
+ image_name,
+ subfolder,
+ original,
+ thumbnail,
+ thumbnail_signature,
+ archived_thumbnail,
+ archived_signature,
+ )
+ )
+ except Exception as e:
+ if archived_thumbnail is not None:
+ try:
+ archived_signature = self._path_signature(archived_thumbnail)
+ source_signature = self._path_signature(thumbnail)
+ except OSError:
+ archived_signature = None
+ source_signature = None
+ counts.add_error("Could not confirm recovery of an archived thumbnail.")
+ if archived_signature is not None and source_signature is None:
+ restored = self._restore_archived_file(archived_thumbnail, thumbnail, counts)
+ if restored:
+ if archive_counted:
+ counts.thumbnails_archived -= 1
+ elif not archive_counted:
+ counts.thumbnails_archived += 1
+ elif archived_signature is None and archive_counted:
+ counts.thumbnails_archived -= 1
+ self._record_item_failure(counts, "record", image_name, e)
+
+ if not delete_items:
+ return
+
+ still_current: list[tuple[str, str, Path, Path, _StatSignature | None, Path | None, _StatSignature | None]] = []
+ for item in delete_items:
+ image_name, subfolder, original, thumbnail, thumbnail_signature, archived_thumbnail, archived_signature = (
+ item
+ )
+ try:
+ thumbnail_unchanged = (
+ self._path_signature(archived_thumbnail) == archived_signature
+ if archived_thumbnail is not None
+ else self._stat(thumbnail) is None
+ )
+ if self._stat(original) is None and thumbnail_unchanged:
+ still_current.append(item)
+ else:
+ counts.skipped_count += 1
+ self._restore_archived_file(archived_thumbnail, thumbnail, counts)
+ if archived_thumbnail is not None and thumbnail.exists():
+ counts.thumbnails_archived -= 1
+ except Exception as e:
+ self._record_item_failure(counts, "record", image_name, e)
+ self._restore_archived_file(archived_thumbnail, thumbnail, counts)
+ if archived_thumbnail is not None and thumbnail.exists():
+ counts.thumbnails_archived -= 1
+
+ if not still_current:
+ return
+ delete_names = [item[0] for item in still_current]
+ try:
+ records.delete_many(delete_names)
+ except Exception:
+ for _name, _subfolder, _original, source, _signature, archived, _archived_signature in reversed(
+ still_current
+ ):
+ self._restore_archived_file(archived, source, counts)
+ if archived is not None and source.exists():
+ counts.thumbnails_archived -= 1
+ self._logger.exception("Failed to remove missing image records")
+ counts.failed_count += len(delete_names)
+ counts.add_error("Database record removal failed; remaining records were kept.")
+ return
+
+ # delete_many owns one transaction and returns only after its commit; count committed
+ # removals before cache, existence, or notification work can fail.
+ counts.records_removed += len(delete_names)
+ for image_name, _subfolder, original, thumbnail, _signature, _archived, _archived_signature in still_current:
+ try:
+ files.evict_cache_paths([original, thumbnail])
+ except Exception:
+ self._logger.exception("Could not evict deleted image cache entries")
+ counts.failed_count += 1
+ counts.add_error("An image was removed, but its cached file could not be cleared.")
+ try:
+ still_exists = records.exists(image_name)
+ if still_exists:
+ counts.failed_count += 1
+ counts.add_error("An image record remained after the removal transaction.")
+ except Exception:
+ self._logger.exception("Could not verify image record removal")
+ counts.failed_count += 1
+ counts.add_error("Could not confirm an image record removal.")
+ try:
+ self._services.images.notify_deleted(image_name)
+ except Exception:
+ self._logger.exception("Image deletion notification failed after gallery maintenance")
+ counts.failed_count += 1
+ counts.add_error("An image was removed, but a dependent service was not notified.")
+
+ def _archive_untracked(self, inventory: sqlite3.Connection, counts: _ResultCounts) -> None:
+ archive_run = Path(counts.archive_path) if counts.archive_path else None
+ if archive_run is None:
+ return
+ self._archive_snapshot_files(inventory, "image", archive_run, counts)
+ self._archive_snapshot_files(inventory, "thumbnail", archive_run, counts)
+
+ def _archive_snapshot_files(
+ self, inventory: sqlite3.Connection, kind: str, archive_run: Path, counts: _ResultCounts
+ ) -> None:
+ files = self._services.image_files
+ records = self._services.image_records
+ root = files.image_root if kind == "image" else files.thumbnail_root
+ cursor = inventory.execute(
+ "SELECT relative_path, base_name, subfolder, signature FROM files "
+ "WHERE kind = ? AND action = 1 ORDER BY relative_path",
+ (kind,),
+ )
+ while page := cursor.fetchmany(_ENUMERATION_BATCH_SIZE):
+ locations = records.get_subfolders(
+ [base_name if kind == "image" else f"{Path(base_name).stem}.png" for _, base_name, _, _ in page]
+ )
+ for relative_path, base_name, subfolder, encoded_signature in page:
+ source_name = base_name if kind == "image" else f"{Path(base_name).stem}.png"
+ path = root / Path(relative_path)
+ if locations.get(source_name) is not None:
+ counts.skipped_count += 1
+ continue
+ try:
+ if kind == "thumbnail":
+ original = self._record_path(source_name, subfolder)
+ if self._stat(original) is not None:
+ # Keep a thumbnail paired with an original that changed or failed to move.
+ counts.skipped_count += 1
+ continue
+ signature = self._decode_signature(encoded_signature)
+ current_signature = self._stat(path)
+ if signature is None or current_signature != signature:
+ counts.skipped_count += 1
+ continue
+ destination = archive_run / ("images" if kind == "image" else "thumbnails")
+ destination = destination / Path(subfolder) / path.name
+ self._archive_file(path, destination, signature)
+ if kind == "image":
+ counts.images_archived += 1
+ else:
+ counts.thumbnails_archived += 1
+ files.evict_cache_paths([path])
+ except Exception as e:
+ expected = self._decode_signature(encoded_signature)
+ if (
+ self._path_signature(path) is None
+ and self._path_signature(
+ archive_run / ("images" if kind == "image" else "thumbnails") / Path(subfolder) / path.name
+ )
+ == expected
+ ):
+ if kind == "image":
+ counts.images_archived += 1
+ else:
+ counts.thumbnails_archived += 1
+ self._record_item_failure(counts, kind, path.name, e)
+
+ def _regenerate_thumbnails(self, inventory: sqlite3.Connection, counts: _ResultCounts) -> None:
+ files = self._services.image_files
+ records = self._services.image_records
+ cursor = inventory.execute(
+ "SELECT image_name, subfolder, original_signature FROM records WHERE action = 1 ORDER BY image_name"
+ )
+ while page := cursor.fetchmany(_ENUMERATION_BATCH_SIZE):
+ locations = records.get_subfolders([image_name for image_name, _subfolder, _signature in page])
+ for image_name, subfolder, encoded_original_signature in page:
+ original = self._record_path(image_name, subfolder)
+ thumbnail = self._record_path(image_name, subfolder, thumbnail=True)
+ generated_thumbnail_signature: _StatSignature | None = None
+ try:
+ expected_original = self._decode_signature(encoded_original_signature)
+ if locations.get(image_name) != subfolder:
+ counts.skipped_count += 1
+ continue
+ if self._stat(original) != expected_original or self._stat(thumbnail) is not None:
+ counts.skipped_count += 1
+ continue
+ if expected_original is None:
+ counts.skipped_count += 1
+ continue
+ created = files.generate_thumbnail_if_missing(image_name, image_subfolder=subfolder)
+ if not created:
+ counts.skipped_count += 1
+ continue
+ generated_thumbnail_signature = self._path_signature(thumbnail)
+ if generated_thumbnail_signature is None:
+ raise OSError("Generated thumbnail disappeared before validation")
+ if self._stat(original) != expected_original:
+ raise OSError("An image changed while its thumbnail was regenerated")
+ size = files.get_file_size_bytes(image_name, image_subfolder=subfolder)
+ records.set_file_size_bytes(image_name, size)
+ counts.thumbnails_regenerated += 1
+ except Exception:
+ self._logger.exception("Failed to regenerate a gallery thumbnail")
+ if generated_thumbnail_signature is not None:
+ try:
+ self._remove_generated_thumbnail(thumbnail, generated_thumbnail_signature)
+ files.evict_cache_paths([thumbnail])
+ except Exception:
+ self._logger.exception("Could not remove an incomplete gallery thumbnail")
+ counts.add_error("Could not remove an incomplete image thumbnail.")
+ counts.failed_count += 1
+ counts.add_error("Could not regenerate an image thumbnail.")
+
+ def _archive_file(self, source: Path, destination: Path, expected: _StatSignature) -> None:
+ """Copy to an exclusive file, publish without overwrite, then identity-check source removal."""
+ try:
+ destination.parent.relative_to(self._archive_root)
+ except ValueError:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ else:
+ self._ensure_archive_directory(destination.parent)
+ temporary = destination.parent / f".{destination.name}.{uuid.uuid4().hex}.tmp"
+ temporary_fd: int | None = None
+ quarantine_directory: Path | None = None
+ quarantined_source: Path | None = None
+ source_quarantined = False
+ try:
+ temporary_fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with open(source, "rb") as source_file, os.fdopen(temporary_fd, "wb") as destination_file:
+ temporary_fd = None
+ before = os.fstat(source_file.fileno())
+ # Windows may report ctime differently through fstat() and path-based stat().
+ # Device, inode, type, size, and mtime remain stable identity/content checks;
+ # the full path signature (including ctime) is checked before source removal.
+ if GalleryMaintenanceService._signature(before)[:5] != expected[:5]:
+ raise OSError("Source changed after preview validation")
+ shutil.copyfileobj(source_file, destination_file, length=1024 * 1024)
+ destination_file.flush()
+ os.fsync(destination_file.fileno())
+ after = os.fstat(source_file.fileno())
+ if GalleryMaintenanceService._signature(after)[:5] != expected[:5]:
+ raise OSError("Source changed while archiving")
+ os.link(temporary, destination)
+ temporary.unlink()
+ GalleryMaintenanceService.__fsync_directory(destination.parent)
+ if GalleryMaintenanceService._path_signature(source) != expected:
+ raise OSError("Source changed before archive completion")
+ quarantine_directory = Path(tempfile.mkdtemp(prefix=".gallery-archive-", dir=source.parent))
+ GalleryMaintenanceService.__fsync_directory(source.parent)
+ quarantined_source = quarantine_directory / source.name
+ source.replace(quarantined_source)
+ source_quarantined = True
+ GalleryMaintenanceService.__fsync_directory(quarantine_directory)
+ GalleryMaintenanceService.__fsync_directory(source.parent)
+ moved_stat = quarantined_source.lstat()
+ moved_signature = GalleryMaintenanceService._signature(moved_stat)
+ # Rename may update ctime, so compare identity, type, size, and mtime. The full
+ # preview signature was checked immediately before the atomic same-directory move.
+ if moved_signature[:5] != expected[:5]:
+ raise OSError("Source changed before archive completion")
+ quarantined_source.unlink()
+ source_quarantined = False
+ GalleryMaintenanceService.__fsync_directory(quarantine_directory)
+ GalleryMaintenanceService.__fsync_directory(source.parent)
+ except Exception:
+ if source_quarantined and quarantined_source is not None:
+ try:
+ # Link is atomic and refuses to replace a source created by another writer.
+ # If restoration cannot safely claim the original name, leave the quarantined
+ # file in its hidden directory for recovery instead of deleting user data.
+ os.link(quarantined_source, source)
+ quarantined_source.unlink()
+ source_quarantined = False
+ GalleryMaintenanceService.__fsync_directory(quarantine_directory)
+ GalleryMaintenanceService.__fsync_directory(source.parent)
+ except OSError:
+ pass
+ raise
+ finally:
+ if temporary_fd is not None:
+ os.close(temporary_fd)
+ temporary.unlink(missing_ok=True)
+ if quarantine_directory is not None:
+ try:
+ quarantine_directory.rmdir()
+ except OSError:
+ pass
+
+ def _remove_generated_thumbnail(self, thumbnail: Path, expected: _StatSignature) -> None:
+ if self._path_signature(thumbnail) != expected:
+ return
+
+ quarantine_directory = Path(tempfile.mkdtemp(prefix=".thumbnail-rollback-", dir=thumbnail.parent))
+ quarantined_thumbnail = quarantine_directory / thumbnail.name
+ thumbnail_quarantined = False
+ try:
+ self.__fsync_directory(thumbnail.parent)
+ thumbnail.replace(quarantined_thumbnail)
+ thumbnail_quarantined = True
+ self.__fsync_directory(quarantine_directory)
+ self.__fsync_directory(thumbnail.parent)
+ moved_signature = self._path_signature(quarantined_thumbnail)
+ if moved_signature is None or moved_signature[:5] != expected[:5]:
+ self._restore_quarantined_thumbnail(quarantined_thumbnail, thumbnail)
+ thumbnail_quarantined = quarantined_thumbnail.exists()
+ return
+ quarantined_thumbnail.unlink()
+ thumbnail_quarantined = False
+ self.__fsync_directory(quarantine_directory)
+ self.__fsync_directory(thumbnail.parent)
+ except Exception:
+ if thumbnail_quarantined:
+ self._restore_quarantined_thumbnail(quarantined_thumbnail, thumbnail)
+ raise
+ finally:
+ try:
+ quarantine_directory.rmdir()
+ except OSError:
+ pass
+
+ def _restore_quarantined_thumbnail(self, quarantined: Path, thumbnail: Path) -> None:
+ try:
+ os.link(quarantined, thumbnail)
+ quarantined.unlink()
+ self.__fsync_directory(quarantined.parent)
+ self.__fsync_directory(thumbnail.parent)
+ except OSError:
+ # Keep the quarantined file for recovery if the canonical path was recreated or
+ # filesystem operations failed. Never overwrite a concurrent replacement.
+ pass
+
+ @staticmethod
+ def _path_signature(path: Path) -> _StatSignature | None:
+ try:
+ result = path.lstat()
+ except FileNotFoundError:
+ return None
+ return GalleryMaintenanceService._signature(result) if stat.S_ISREG(result.st_mode) else None
+
+ @staticmethod
+ def __fsync_directory(directory: Path) -> None:
+ if os.name == "nt":
+ return
+ descriptor = os.open(directory, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
+ def _restore_archived_file(self, archived: Path | None, original: Path, counts: _ResultCounts) -> bool:
+ if archived is None:
+ return True
+ try:
+ signature = self._stat(archived)
+ if signature is not None:
+ self._archive_file(archived, original, signature)
+ return original.exists()
+ except Exception:
+ self._logger.exception("Failed to restore an archived thumbnail after database failure")
+ counts.failed_count += 1
+ counts.add_error(f"Could not restore thumbnail {original.name}; it remains in the archive.")
+ return False
+
+ def _record_item_failure(self, counts: _ResultCounts, kind: str, relative_name: str, error: Exception) -> None:
+ self._logger.warning("Gallery maintenance could not archive %s %s: %s", kind, relative_name, error)
+ counts.failed_count += 1
+ counts.add_error(f"Could not archive a gallery {kind}.")
diff --git a/invokeai/app/services/image_files/image_files_base.py b/invokeai/app/services/image_files/image_files_base.py
index fe7d1a08b1..40bab0e532 100644
--- a/invokeai/app/services/image_files/image_files_base.py
+++ b/invokeai/app/services/image_files/image_files_base.py
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
-from collections.abc import Collection, Sequence
+from collections.abc import Collection, Iterator, Sequence
from pathlib import Path
from typing import Optional
@@ -19,6 +19,16 @@ class ImageFileStorageBase(ABC):
"""Gets the internal path to an image or thumbnail."""
pass
+ @abstractmethod
+ def iter_image_paths(self) -> Iterator[Path]:
+ """Yields supported image paths in stable order, excluding reserved trees and symlinks."""
+ pass
+
+ @abstractmethod
+ def iter_thumbnail_paths(self) -> Iterator[Path]:
+ """Yields thumbnail paths in stable order, excluding reserved trees and symlinks."""
+ pass
+
@property
@abstractmethod
def image_root(self) -> Path:
@@ -57,6 +67,13 @@ class ImageFileStorageBase(ABC):
"""Saves an image and a 256x256 WEBP thumbnail. Returns a tuple of the image name, thumbnail name, and created timestamp."""
pass
+ @abstractmethod
+ def generate_thumbnail_if_missing(
+ self, image_name: str, image_subfolder: str = "", thumbnail_size: int = 256
+ ) -> bool:
+ """Atomically creates a thumbnail only when absent, without rewriting the source image."""
+ pass
+
@abstractmethod
def copy(
self,
diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.py
index 55b82ed03c..0d45a70767 100644
--- a/invokeai/app/services/image_files/image_files_disk.py
+++ b/invokeai/app/services/image_files/image_files_disk.py
@@ -3,10 +3,11 @@ import io
import json
import os
import shutil
+import sqlite3
import tempfile
import threading
import zlib
-from collections.abc import Collection, Iterable, Sequence
+from collections.abc import Collection, Iterable, Iterator, Sequence
from dataclasses import dataclass
from pathlib import Path
from queue import Queue
@@ -99,6 +100,7 @@ class DiskImageFileStorage(ImageFileStorageBase):
# Guards the cache structures (__cache / __cache_ids), which are read and mutated from
# multiple session-processor worker threads in multi-GPU parallel mode.
self.__cache_lock = threading.Lock()
+ self.__cache_generation = 0
self.__output_folder = output_folder if isinstance(output_folder, Path) else Path(output_folder)
self.__thumbnails_folder = self.__output_folder / "thumbnails"
@@ -117,15 +119,106 @@ class DiskImageFileStorage(ImageFileStorageBase):
def thumbnail_root(self) -> Path:
return self.__thumbnails_folder.resolve()
+ def iter_image_paths(self) -> Iterator[Path]:
+ """Walk supported image files without following symlinks or entering journals/thumbnails."""
+ yield from self.__iter_supported_paths(self.image_root, suffixes={".png"}, skip_thumbnail_root=True)
+
+ def iter_thumbnail_paths(self) -> Iterator[Path]:
+ """Walk WEBP thumbnails without following symlinks or entering reserved journals."""
+ yield from self.__iter_supported_paths(self.thumbnail_root, suffixes={".webp"})
+
+ @staticmethod
+ def __iter_supported_paths(root: Path, suffixes: set[str], skip_thumbnail_root: bool = False) -> Iterator[Path]:
+ # Inventory and traversal state stay in a temporary SQLite database. A generated gallery
+ # can contain enough files that retaining DirEntry objects or directory paths in Python
+ # would make maintenance memory usage grow with the output tree.
+ with tempfile.TemporaryDirectory(prefix="invokeai-image-path-inventory-") as inventory_dir:
+ inventory_path = Path(inventory_dir) / "inventory.sqlite"
+ connection = sqlite3.connect(inventory_path)
+ try:
+ connection.execute("PRAGMA cache_size = -2048")
+ connection.execute("PRAGMA temp_store = FILE")
+ connection.execute("PRAGMA journal_mode = OFF")
+ connection.execute("PRAGMA synchronous = OFF")
+ connection.execute("CREATE TABLE pending_directories (id INTEGER PRIMARY KEY, path BLOB NOT NULL)")
+ connection.execute(
+ "CREATE TABLE directory_entries (path BLOB NOT NULL, sort_key BLOB NOT NULL, is_directory INTEGER NOT NULL)"
+ )
+ connection.execute("INSERT INTO pending_directories (path) VALUES (?)", (os.fsencode(root),))
+ connection.commit()
+
+ while True:
+ pending = connection.execute(
+ "SELECT id, path FROM pending_directories ORDER BY id DESC LIMIT 1"
+ ).fetchone()
+ if pending is None:
+ break
+ directory_id, directory_value = pending
+ connection.execute("DELETE FROM pending_directories WHERE id = ?", (directory_id,))
+ connection.execute("DELETE FROM directory_entries")
+ directory = Path(os.fsdecode(directory_value))
+
+ with os.scandir(directory) as scan:
+ for entry in scan:
+ if entry.name.startswith(".delete_"):
+ continue
+ if directory == root and skip_thumbnail_root and entry.name == "thumbnails":
+ continue
+ if entry.is_symlink():
+ continue
+ if entry.is_dir(follow_symlinks=False):
+ is_directory = 1
+ elif entry.is_file(follow_symlinks=False) and Path(entry.name).suffix.lower() in suffixes:
+ is_directory = 0
+ else:
+ continue
+
+ entry_path = os.fsencode(directory / entry.name)
+ sort_key = entry.name.encode("utf-32-be", "surrogatepass")
+ connection.execute(
+ "INSERT INTO directory_entries (path, sort_key, is_directory) VALUES (?, ?, ?)",
+ (entry_path, sort_key, is_directory),
+ )
+
+ connection.commit()
+
+ entries = connection.execute("SELECT path, is_directory FROM directory_entries ORDER BY sort_key")
+ for entry_path, is_directory in entries:
+ if not is_directory:
+ yield Path(os.fsdecode(entry_path))
+
+ # Push children in reverse lexical order so the disk-backed LIFO stack visits
+ # them in the same ascending order as the previous in-memory traversal.
+ connection.execute(
+ """--sql
+ INSERT INTO pending_directories (path)
+ SELECT path
+ FROM directory_entries
+ WHERE is_directory = 1
+ ORDER BY sort_key DESC
+ """
+ )
+ connection.commit()
+ finally:
+ connection.close()
+
def evict_cache_paths(self, paths: list[Path]) -> None:
+ resolved_paths = [path.resolve() for path in paths]
+ with self.__cache_lock:
+ self.__invalidate_cache_paths_locked(resolved_paths)
+
+ def __invalidate_cache_paths_locked(self, paths: list[Path]) -> None:
+ if not paths:
+ return
+ self.__cache_generation += 1
for path in paths:
- self.__cache.pop(path.resolve(), None)
+ self.__cache.pop(path, None)
def get(self, image_name: str, image_subfolder: str = "") -> PILImageType:
try:
image_path = self.get_path(image_name, image_subfolder=image_subfolder)
- cache_item = self.__get_cache(image_path)
+ cache_item, cache_generation = self.__get_cache(image_path)
if cache_item:
return cache_item
@@ -137,7 +230,7 @@ class DiskImageFileStorage(ImageFileStorageBase):
# handle and decoder state, producing "broken data stream" / "self.png is not None"
# errors. Forcing the decode here makes the cached object safe for concurrent reads.
image.load()
- self.__set_cache(image_path, image)
+ self.__set_cache(image_path, image, cache_generation)
return image
except FileNotFoundError as e:
raise ImageFileNotFoundException from e
@@ -215,6 +308,64 @@ class DiskImageFileStorage(ImageFileStorageBase):
self.evict_cache_paths([path for path in (image_path, thumbnail_path) if path is not None])
raise ImageFileSaveException from e
+ def generate_thumbnail_if_missing(
+ self, image_name: str, image_subfolder: str = "", thumbnail_size: int = 256
+ ) -> bool:
+ """Create a complete thumbnail at the canonical path without touching the source image."""
+ image_path = self.get_path(image_name, image_subfolder=image_subfolder)
+ thumbnail_path = self.get_path(image_name, thumbnail=True, image_subfolder=image_subfolder)
+ try:
+ thumbnail_path.stat()
+ return False
+ except FileNotFoundError:
+ pass
+
+ thumbnail_path.parent.mkdir(parents=True, exist_ok=True)
+ temporary_path: Path | None = None
+ thumbnail: PILImageType | None = None
+ published_identity: tuple[int, int] | None = None
+ try:
+ with Image.open(image_path) as source_image:
+ thumbnail = make_thumbnail(source_image, thumbnail_size)
+ descriptor, temporary_name = tempfile.mkstemp(
+ prefix=".thumbnail-", suffix=".webp", dir=thumbnail_path.parent
+ )
+ os.close(descriptor)
+ temporary_path = Path(temporary_name)
+ thumbnail.save(temporary_path, format="WEBP")
+ with open(temporary_path, "rb+") as completed_file:
+ os.fsync(completed_file.fileno())
+ temporary_stat = temporary_path.stat()
+ temporary_identity = (temporary_stat.st_dev, temporary_stat.st_ino)
+ try:
+ # Linking publishes the fully written temporary file atomically and refuses to
+ # replace a thumbnail another writer created after our first existence check.
+ os.link(temporary_path, thumbnail_path)
+ except FileExistsError:
+ return False
+ published_identity = temporary_identity
+ try:
+ self.__fsync_directory(thumbnail_path.parent)
+ except Exception:
+ try:
+ current_stat = thumbnail_path.lstat()
+ if (current_stat.st_dev, current_stat.st_ino) == published_identity:
+ thumbnail_path.unlink()
+ self.evict_cache_paths([thumbnail_path])
+ try:
+ self.__fsync_directory(thumbnail_path.parent)
+ except OSError:
+ pass
+ except OSError:
+ pass
+ raise
+ return True
+ finally:
+ if thumbnail is not None:
+ thumbnail.close()
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
+
def copy(
self,
source_image_name: str,
@@ -266,13 +417,15 @@ class DiskImageFileStorage(ImageFileStorageBase):
# The manifest has to be durable before the files move, or a crash can leave staged
# files in a directory that names nothing and recovery cannot put them back.
self.__persist_journal_directory(staging_dir)
- for index, source in enumerate(candidates):
- with self.__cache_lock:
- self.__cache.pop(source, None)
- if source.exists():
- destination = staging_dir / str(index)
- source.replace(destination)
- staged.append((source, destination))
+ with self.__cache_lock:
+ try:
+ for index, source in enumerate(candidates):
+ if source.exists():
+ destination = staging_dir / str(index)
+ source.replace(destination)
+ staged.append((source, destination))
+ finally:
+ self.__invalidate_cache_paths_locked(candidates)
return _StagedDelete(
directory=staging_dir, files=staged, image_name=image_name, image_subfolder=image_subfolder
)
@@ -395,8 +548,10 @@ class DiskImageFileStorage(ImageFileStorageBase):
"""Removes an image's file and thumbnail. Missing files are not an error."""
for path in self.__delete_candidates(image_name, image_subfolder):
with self.__cache_lock:
- self.__cache.pop(path, None)
- path.unlink(missing_ok=True)
+ try:
+ path.unlink(missing_ok=True)
+ finally:
+ self.__invalidate_cache_paths_locked([path])
def __purge_if_record_absent(self, image_name: str, image_subfolder: str) -> None:
try:
@@ -604,12 +759,15 @@ class DiskImageFileStorage(ImageFileStorageBase):
return [(data["image_name"], data.get("image_subfolder", ""))]
return [(entry["image_name"], entry.get("image_subfolder", "")) for entry in entries]
- def __get_cache(self, image_name: Path) -> Optional[PILImageType]:
+ def __get_cache(self, image_name: Path) -> tuple[Optional[PILImageType], int]:
with self.__cache_lock:
- return None if image_name not in self.__cache else self.__cache[image_name]
+ cache_item = None if image_name not in self.__cache else self.__cache[image_name]
+ return cache_item, self.__cache_generation
- def __set_cache(self, image_name: Path, image: PILImageType):
+ def __set_cache(self, image_name: Path, image: PILImageType, generation: int | None = None) -> None:
with self.__cache_lock:
+ if generation is not None and generation != self.__cache_generation:
+ return
if image_name not in self.__cache:
self.__cache[image_name] = image
self.__cache_ids.put(image_name) # TODO: this should refresh position for LRU cache
diff --git a/invokeai/app/services/image_moves/image_moves_default.py b/invokeai/app/services/image_moves/image_moves_default.py
index b9e3db0e06..a5e857f2eb 100644
--- a/invokeai/app/services/image_moves/image_moves_default.py
+++ b/invokeai/app/services/image_moves/image_moves_default.py
@@ -14,7 +14,6 @@ from PIL import Image, UnidentifiedImageError
from invokeai.app.services.config import InvokeAIAppConfig
from invokeai.app.services.image_files.image_files_base import ImageFileStorageBase
from invokeai.app.services.image_records.image_records_common import ImageCategory
-from invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.util.thumbnails import make_thumbnail
@@ -86,6 +85,7 @@ class ImageMoveService:
self._future_lock = threading.Lock()
self._future: Future | None = None
self._future_operation: ImageMoveBackgroundOperation | None = None
+ self._gallery_maintenance_reserved = False
self._last_background_error: str | None = None
# Serializes the move service's relocate-and-repoint units against the image delete
# units in ImageService. See image_mutation_lock() for the interleaving it prevents.
@@ -111,7 +111,7 @@ class ImageMoveService:
self._executor.shutdown(wait=True, cancel_futures=False)
@contextmanager
- def image_mutation_lock(self) -> Iterator[None]:
+ def image_mutation_lock(self, *, blocking: bool = True) -> Iterator[bool]:
"""Serializes image delete units against subfolder relocation units.
An image delete reads an image's subfolder, deletes its record, then purges its files
@@ -119,17 +119,56 @@ class ImageMoveService:
the record. If the two interleave, the delete purges the path its snapshot named while
the files sit at the new one — permanent orphans, unrecoverable because the record is
gone and a clean purge drops the journal (JPPhoto, PR #9361). ``ImageService`` holds
- this lock across each of its delete units, and the move service holds it across each
- plan-relocate-repoint cycle below, so neither can observe the other half-done.
+ this lock across each delete and copy unit, and the move service holds it across each
+ plan-relocate-repoint cycle below. Session workers hold it across the maintenance check
+ and queue claim, so maintenance either observes a claimed item or prevents the claim.
It is a reentrant lock because both sides run their units to completion in one thread;
nothing inside a unit may block on another thread that needs this lock. It is also
process-local: two Invoke processes sharing one output folder and database are not
serialized by it — the same limitation the route guard has, which the delete journal's
startup recovery re-check papers over for deletes.
+
+ Nonblocking callers receive ``False`` when another unit holds the lock and do not own
+ it. Queue workers use that path so shutdown can wake a worker even during a long scan.
+ """
+ acquired = self._image_mutation_lock.acquire(blocking=blocking)
+ try:
+ yield acquired
+ finally:
+ if acquired:
+ self._image_mutation_lock.release()
+
+ @contextmanager
+ def reserve_gallery_maintenance(self) -> Iterator[None]:
+ """Excludes image moves and queue claims while gallery maintenance runs.
+
+ This process-local reservation is visible before waiting for the mutation lock, so
+ session workers cannot claim new work while this operation waits for a claim already
+ in flight. The future lock is released before acquiring the mutation lock; workers take
+ the locks in the opposite order when they atomically check maintenance state and dequeue.
"""
- with self._image_mutation_lock:
- yield
+ with self._future_lock:
+ self._refresh_finished_future_locked()
+ if (
+ self._gallery_maintenance_reserved
+ or self._future_operation is not None
+ or (self._future is not None and not self._future.done())
+ ):
+ raise ImageMoveJobAlreadyRunning("An image storage maintenance operation is already running")
+ if self._get_active_job_id() is not None:
+ raise ImageMoveJobAlreadyRunning("An image move job is already active")
+ self._gallery_maintenance_reserved = True
+
+ try:
+ with self.image_mutation_lock():
+ self._assert_no_active_queue_work()
+ yield
+ finally:
+ # Release only after the mutation lock is gone. Queue workers acquire that lock
+ # before consulting this flag, so this order cannot deadlock with a worker claim.
+ with self._future_lock:
+ self._gallery_maintenance_reserved = False
def start_background_move_all(self) -> ImageMoveBackgroundStatus:
return self._start_background_operation("move_all", self.move_all_images, require_idle_queue=True)
@@ -147,7 +186,8 @@ class ImageMoveService:
self._refresh_finished_future_locked()
is_running = self._future is not None and not self._future.done()
operation_reserved = self._future_operation is not None
- return operation_reserved or is_running or self._get_active_job_id() is not None
+ gallery_maintenance_reserved = self._gallery_maintenance_reserved
+ return gallery_maintenance_reserved or operation_reserved or is_running or self._get_active_job_id() is not None
def _assert_no_active_queue_work(self) -> None:
session_queue = self._session_queue
@@ -155,8 +195,7 @@ class ImageMoveService:
session_queue = getattr(self._invoker.services, "session_queue", None)
if session_queue is None:
return
- queue_status = session_queue.get_queue_status(DEFAULT_QUEUE_ID)
- if queue_status.pending > 0 or queue_status.in_progress > 0:
+ if session_queue.has_active_queue_work():
raise ImageMoveQueueActive("Cannot start image move while queue work is active")
def _start_background_operation(
@@ -167,6 +206,8 @@ class ImageMoveService:
) -> ImageMoveBackgroundStatus:
with self._future_lock:
self._refresh_finished_future_locked()
+ if self._gallery_maintenance_reserved:
+ raise ImageMoveJobAlreadyRunning("An image storage maintenance operation is already running")
if self._future_operation is not None or (self._future is not None and not self._future.done()):
raise ImageMoveJobAlreadyRunning("An image move job is already running")
active_job_id = self._get_active_job_id()
diff --git a/invokeai/app/services/image_records/image_records_base.py b/invokeai/app/services/image_records/image_records_base.py
index f3161e75ca..828f1c4720 100644
--- a/invokeai/app/services/image_records/image_records_base.py
+++ b/invokeai/app/services/image_records/image_records_base.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from collections.abc import Iterator
from datetime import datetime
from typing import Optional
@@ -95,6 +96,11 @@ class ImageRecordStorageBase(ABC):
"""Maps each existing named image to its on-disk subfolder; absent names are omitted."""
pass
+ @abstractmethod
+ def iter_all_image_locations(self, batch_size: int = 500) -> Iterator[tuple[str, str]]:
+ """Yields all image name/subfolder pairs in key order using bounded keyset pages."""
+ pass
+
@abstractmethod
def delete_intermediates_by_names(
self, image_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
diff --git a/invokeai/app/services/image_records/image_records_sqlite.py b/invokeai/app/services/image_records/image_records_sqlite.py
index 16e7546ef1..a3e7ff2af8 100644
--- a/invokeai/app/services/image_records/image_records_sqlite.py
+++ b/invokeai/app/services/image_records/image_records_sqlite.py
@@ -1,4 +1,5 @@
import sqlite3
+from collections.abc import Iterator
from dataclasses import dataclass
from datetime import datetime
from typing import Optional, Union, cast
@@ -474,6 +475,37 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
subfolders[cast(str, row[0])] = cast(str, row[1])
return subfolders
+ def iter_all_image_locations(self, batch_size: int = 500) -> Iterator[tuple[str, str]]:
+ """Yields every image location through bounded keyset pages, including hidden/intermediate rows."""
+ if batch_size <= 0:
+ raise ValueError("batch_size must be positive")
+
+ last_image_name = ""
+ while True:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT image_name, image_subfolder
+ FROM images
+ WHERE image_name > ?
+ ORDER BY image_name
+ LIMIT ?;
+ """,
+ (last_image_name, batch_size),
+ )
+ rows = cursor.fetchall()
+
+ if not rows:
+ return
+
+ locations = [(cast(str, row[0]), cast(str, row[1])) for row in rows]
+ for image_name, image_subfolder in locations:
+ last_image_name = image_name
+ yield image_name, image_subfolder
+
+ if len(rows) < batch_size:
+ return
+
def delete_intermediates_by_names(
self, image_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
) -> list[str]:
diff --git a/invokeai/app/services/images/images_base.py b/invokeai/app/services/images/images_base.py
index 422e6706e8..14f98845c7 100644
--- a/invokeai/app/services/images/images_base.py
+++ b/invokeai/app/services/images/images_base.py
@@ -39,9 +39,10 @@ class ImageServiceABC(ABC):
for callback in self._on_changed_callbacks:
callback(item)
- def _on_deleted(self, item_id: str) -> None:
+ def notify_deleted(self, image_name: str) -> None:
+ """Notify registered listeners after an image record has been deleted."""
for callback in self._on_deleted_callbacks:
- callback(item_id)
+ callback(image_name)
@abstractmethod
def create(
diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.py
index 9276b3b4a5..f088f4bd56 100644
--- a/invokeai/app/services/images/images_default.py
+++ b/invokeai/app/services/images/images_default.py
@@ -45,16 +45,17 @@ class ImageService(ImageServiceABC):
@contextmanager
def _image_mutation_lock(self) -> Iterator[None]:
- """Holds the image-mutation lock across a delete unit.
+ """Holds the shared image-mutation lock across a record-and-file mutation.
Every delete here reads an image's subfolder and purges its files at that path after
the record is gone. A concurrent subfolder move that relocates files and repoints the
record mid-unit would leave the purge sweeping a path the files already left: permanent
orphans, unrecoverable because the record is gone and a clean purge drops the journal
- (JPPhoto, PR #9361). The move service takes the same lock around each of its
- plan-relocate-repoint cycles, so neither unit can observe the other half-done. With no
- move service configured there is nothing to coordinate with. The lock is process-local:
- two Invoke processes sharing one output folder and database are not serialized by it.
+ (JPPhoto, PR #9361). Copies also hold it across record creation, file copy, and rollback,
+ so maintenance cannot inspect or remove a half-created image. The move service takes
+ the same lock around each plan-relocate-repoint cycle. With no move service configured
+ there is nothing to coordinate with. The lock is process-local: two Invoke processes
+ sharing one output folder and database are not serialized by it.
"""
image_moves = getattr(self.__invoker.services, "image_moves", None)
if image_moves is None:
@@ -249,6 +250,15 @@ class ImageService(ImageServiceABC):
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.
"""
+ with self._image_mutation_lock():
+ return self._copy_with_mutation_lock(source_image_name, board_id, user_id)
+
+ def _copy_with_mutation_lock(
+ self,
+ source_image_name: str,
+ board_id: Optional[str],
+ user_id: Optional[str],
+ ) -> ImageDTO:
try:
record = self.__invoker.services.image_records.get(source_image_name)
metadata = self.__invoker.services.image_records.get_metadata(source_image_name)
@@ -527,7 +537,7 @@ class ImageService(ImageServiceABC):
# The record is committed as gone, so the delete succeeded. The journal stays
# behind and startup recovery purges the leftover files.
self.__invoker.services.logger.error(f"Failed to purge deleted image files: {cleanup_error}")
- self._on_deleted(image_name)
+ self.notify_deleted(image_name)
except ImageRecordNotFoundException:
# Already deleted by another request; nothing here failed, so nothing to log.
raise
@@ -576,7 +586,7 @@ class ImageService(ImageServiceABC):
delete_records=records.delete_many,
rollback=files.rollback_delete,
commit=files.commit_delete,
- notify_deleted=self._on_deleted,
+ notify_deleted=self.notify_deleted,
log_error=self.__invoker.services.logger.error,
),
)
@@ -609,7 +619,7 @@ class ImageService(ImageServiceABC):
delete_records=lambda names, g: records.delete_intermediates_by_names(names, guard=g),
abandon=files.abandon_delete,
commit=lambda token, names: files.commit_delete(token, image_names=names),
- notify_deleted=self._on_deleted,
+ notify_deleted=self.notify_deleted,
log_error=self.__invoker.services.logger.error,
),
)
diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.py
index 2d34fbf624..fa7abe347a 100644
--- a/invokeai/app/services/invocation_services.py
+++ b/invokeai/app/services/invocation_services.py
@@ -26,6 +26,7 @@ if TYPE_CHECKING:
from invokeai.app.services.external_generation.external_generation_base import ExternalGenerationServiceBase
from invokeai.app.services.fonts.fonts_default import FontService
from invokeai.app.services.gallery.gallery_base import GalleryServiceABC
+ from invokeai.app.services.gallery_maintenance.gallery_maintenance_default import GalleryMaintenanceService
from invokeai.app.services.image_files.image_files_base import ImageFileStorageBase
from invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase
from invokeai.app.services.image_index.image_index_records_base import ImageIndexRecordsBase
@@ -114,6 +115,7 @@ class InvocationServices:
image_moves: "ImageMoveService | None" = None,
progress_previews: "ProgressPreviewsBase | None" = None,
fonts: "FontService | None" = None,
+ gallery_maintenance: "GalleryMaintenanceService | None" = None,
):
self.board_images = board_images
self.board_image_records = board_image_records
@@ -165,3 +167,4 @@ class InvocationServices:
self.image_index = image_index
self.fonts = fonts
self.intermediates = intermediates
+ self.gallery_maintenance = gallery_maintenance
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index 3dfe6cffd0..4308e7a4f3 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -1,7 +1,7 @@
import gc
import time
import traceback
-from contextlib import contextmanager, suppress
+from contextlib import contextmanager, nullcontext, suppress
from threading import BoundedSemaphore, Thread
from threading import Event as ThreadEvent
from typing import Iterator, Optional
@@ -1063,6 +1063,27 @@ class DefaultSessionProcessor(SessionProcessorBase):
image_moves = getattr(self._invoker.services, "image_moves", None)
return image_moves is not None and image_moves.is_maintenance_active()
+ def _dequeue_if_storage_maintenance_inactive(
+ self, device: Optional[str]
+ ) -> tuple[bool, Optional[SessionQueueItem]]:
+ """Atomically check storage maintenance state and claim the next queue item.
+
+ Gallery maintenance reserves its busy flag before taking the same mutation lock. If
+ this worker wins the lock first, the subsequent reservation sees the claimed item in
+ queue status; if maintenance wins, this worker leaves queued work pending.
+ """
+ image_moves = getattr(self._invoker.services, "image_moves", None)
+ mutation_lock = (
+ image_moves.image_mutation_lock(blocking=False) if image_moves is not None else nullcontext(True)
+ )
+ with mutation_lock as lock_acquired:
+ if not lock_acquired:
+ return False, None
+ if self._is_image_move_maintenance_active():
+ return False, None
+ item = self._invoker.services.session_queue.dequeue(device=device)
+ return True, item
+
def _cancel_queue_item_if_owner_inactive(self, queue_item: SessionQueueItem) -> bool:
"""Cancel a dequeued item whose owner is deactivated, deleted, or unverifiable.
@@ -1124,11 +1145,6 @@ class DefaultSessionProcessor(SessionProcessorBase):
if stop_event.is_set():
break
- if self._is_image_move_maintenance_active():
- self._invoker.services.logger.debug("Image storage maintenance is active")
- poll_now_event.wait(self._polling_interval)
- continue
-
# Clear any stale cancel signal from the previous item BEFORE claiming the next
# one. Clearing it after dequeue (as before) could wipe a cancel that arrived for
# the item we just claimed — e.g. during the gc.collect() below — silently losing
@@ -1145,10 +1161,15 @@ class DefaultSessionProcessor(SessionProcessorBase):
# Get the next session to process. dequeue() atomically claims the item, so concurrent
# workers never receive the same item. Pass this worker's device so the item is
# tagged with the GPU that ran it (None in single-device/legacy mode).
- worker.queue_item = self._invoker.services.session_queue.dequeue(
+ maintenance_inactive, worker.queue_item = self._dequeue_if_storage_maintenance_inactive(
device=str(worker.device) if worker.device is not None else None
)
+ if not maintenance_inactive:
+ self._invoker.services.logger.debug("Image storage maintenance is active")
+ poll_now_event.wait(self._polling_interval)
+ continue
+
if worker.queue_item is None:
# The queue was empty, wait for next polling interval or event to try again
self._invoker.services.logger.debug("Waiting for next polling interval or event")
diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.py
index c35bf8b9c2..ef86078d57 100644
--- a/invokeai/app/services/session_queue/session_queue_base.py
+++ b/invokeai/app/services/session_queue/session_queue_base.py
@@ -137,6 +137,11 @@ class SessionQueueBase(ABC):
"""
pass
+ @abstractmethod
+ def has_active_queue_work(self) -> bool:
+ """Return whether any queue has pending or in-progress work."""
+ pass
+
@abstractmethod
def get_counts_by_destination(
self, queue_id: str, destination: str, user_id: Optional[str] = None
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index e182986059..6737099297 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -2133,6 +2133,18 @@ class SqliteSessionQueue(SessionQueueBase):
}
return [summaries_by_id[item_id] for item_id in item_ids if item_id in summaries_by_id]
+ def has_active_queue_work(self) -> bool:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT 1
+ FROM session_queue
+ WHERE status IN ('pending', 'in_progress')
+ LIMIT 1
+ """
+ )
+ return cursor.fetchone() is not None
+
def get_queue_status(
self,
queue_id: str,
diff --git a/invokeai/app/services/shared/sqlite/sqlite_database.py b/invokeai/app/services/shared/sqlite/sqlite_database.py
index 4cbb2e0e4c..29bd0a32ac 100644
--- a/invokeai/app/services/shared/sqlite/sqlite_database.py
+++ b/invokeai/app/services/shared/sqlite/sqlite_database.py
@@ -1,3 +1,4 @@
+import os
import sqlite3
import threading
from collections.abc import Generator
@@ -121,6 +122,31 @@ class SqliteDatabase:
self._logger.error(f"Error cleaning database: {e}")
raise
+ def backup_to(self, destination: Path) -> None:
+ """Create a consistent SQLite backup at a new destination.
+
+ The connection backup API includes committed WAL pages. The shared lock keeps this
+ connection's transaction users from interleaving with the copy, and the destination is
+ reserved exclusively so an existing backup can never be overwritten.
+ """
+ destination = Path(destination)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ descriptor = os.open(destination, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ os.close(descriptor)
+ try:
+ with self._lock:
+ backup_connection = sqlite3.connect(destination)
+ try:
+ self._conn.backup(backup_connection)
+ backup_connection.commit()
+ finally:
+ backup_connection.close()
+ except Exception:
+ destination.unlink(missing_ok=True)
+ Path(f"{destination}-wal").unlink(missing_ok=True)
+ Path(f"{destination}-shm").unlink(missing_ok=True)
+ raise
+
@contextmanager
def transaction(self) -> Generator[sqlite3.Cursor, None, None]:
"""
diff --git a/invokeai/backend/util/gallery_maintenance.py b/invokeai/backend/util/gallery_maintenance.py
deleted file mode 100644
index 43780c35db..0000000000
--- a/invokeai/backend/util/gallery_maintenance.py
+++ /dev/null
@@ -1,598 +0,0 @@
-# pylint: disable=line-too-long
-# pylint: disable=broad-exception-caught
-# pylint: disable=missing-function-docstring
-"""Script to peform db maintenance and outputs directory management."""
-
-import argparse
-import datetime
-import enum
-import glob
-import locale
-import os
-import shutil
-import sqlite3
-from pathlib import Path
-
-import PIL
-import PIL.ImageOps
-import PIL.PngImagePlugin
-import yaml
-
-
-class ConfigMapper:
- """Configuration loader."""
-
- def __init__(self): # noqa D107
- pass
-
- TIMESTAMP_STRING = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
-
- INVOKE_DIRNAME = "invokeai"
- YAML_FILENAME = "invokeai.yaml"
- DATABASE_FILENAME = "invokeai.db"
-
- DEFAULT_OUTDIR = "outputs"
- DEFAULT_DB_DIR = "databases"
-
- database_path = None
- database_backup_dir = None
- outputs_path = None
- archive_path = None
- thumbnails_path = None
- thumbnails_archive_path = None
-
- def load(self):
- """Read paths from yaml config and validate."""
- root = "."
-
- if not self.__load_from_root_config(os.path.abspath(root)):
- return False
-
- return True
-
- def __load_from_root_config(self, invoke_root):
- """Validate a yaml path exists, confirm the user wants to use it and load config."""
- yaml_path = os.path.join(invoke_root, self.YAML_FILENAME)
- if not os.path.exists(yaml_path):
- print(f"Unable to find invokeai.yaml at {yaml_path}!")
- return False
- if os.path.exists(yaml_path):
- db_dir, outdir = self.__load_paths_from_yaml_file(yaml_path)
-
- if db_dir is None:
- db_dir = self.DEFAULT_DB_DIR
- print(f"The invokeai.yaml file was found but is missing the db_dir setting! Defaulting to {db_dir}")
- if outdir is None:
- outdir = self.DEFAULT_OUTDIR
- print(f"The invokeai.yaml file was found but is missing the outdir setting! Defaulting to {outdir}")
-
- if os.path.isabs(db_dir):
- self.database_path = os.path.join(db_dir, self.DATABASE_FILENAME)
- else:
- self.database_path = os.path.join(invoke_root, db_dir, self.DATABASE_FILENAME)
-
- self.database_backup_dir = os.path.join(os.path.dirname(self.database_path), "backup")
-
- if os.path.isabs(outdir):
- self.outputs_path = os.path.join(outdir, "images")
- self.archive_path = os.path.join(outdir, "images-archive")
- else:
- self.outputs_path = os.path.join(invoke_root, outdir, "images")
- self.archive_path = os.path.join(invoke_root, outdir, "images-archive")
-
- self.thumbnails_path = os.path.join(self.outputs_path, "thumbnails")
- self.thumbnails_archive_path = os.path.join(self.archive_path, "thumbnails")
-
- db_exists = os.path.exists(self.database_path)
- outdir_exists = os.path.exists(self.outputs_path)
-
- text = f"Found {self.YAML_FILENAME} file at {yaml_path}:"
- text += f"\n Database : {self.database_path} - {'Exists!' if db_exists else 'Not Found!'}"
- text += f"\n Outputs : {self.outputs_path}- {'Exists!' if outdir_exists else 'Not Found!'}"
- print(text)
-
- if db_exists and outdir_exists:
- return True
- else:
- print(
- "\nOne or more paths specified in invoke.yaml do not exist. Please inspect/correct the configuration and ensure the script is run in the developer console mode (option 8) from an Invoke AI root directory."
- )
- return False
- else:
- print(
- f"Auto-discovery of configuration failed! Could not find ({yaml_path})!\n\nPlease ensure the script is run in the developer console mode (option 8) from an Invoke AI root directory."
- )
- return False
-
- def __load_paths_from_yaml_file(self, yaml_path):
- """Load an Invoke AI yaml file and get the database and outputs paths."""
- try:
- with open(yaml_path, "rt", encoding=locale.getpreferredencoding()) as file:
- yamlinfo = yaml.safe_load(file)
- db_dir = yamlinfo.get("InvokeAI", {}).get("Paths", {}).get("db_dir", None)
- outdir = yamlinfo.get("InvokeAI", {}).get("Paths", {}).get("outdir", None)
- return db_dir, outdir
- except Exception:
- print(f"Failed to load paths from yaml file! {yaml_path}!")
- return None, None
-
-
-class MaintenanceStats:
- """DTO for tracking work progress."""
-
- def __init__(self): # noqa D107
- pass
-
- time_start = datetime.datetime.utcnow()
- count_orphaned_db_entries_cleaned = 0
- count_orphaned_disk_files_cleaned = 0
- count_orphaned_thumbnails_cleaned = 0
- count_thumbnails_regenerated = 0
- count_errors = 0
-
- @staticmethod
- def get_elapsed_time_string():
- """Get a friendly time string for the time elapsed since processing start."""
- time_now = datetime.datetime.utcnow()
- total_seconds = (time_now - MaintenanceStats.time_start).total_seconds()
- hours = int((total_seconds) / 3600)
- minutes = int(((total_seconds) % 3600) / 60)
- seconds = total_seconds % 60
- out_str = f"{hours} hour(s) -" if hours > 0 else ""
- out_str += f"{minutes} minute(s) -" if minutes > 0 else ""
- out_str += f"{seconds:.2f} second(s)"
- return out_str
-
-
-class DatabaseMapper:
- """Class to abstract database functionality."""
-
- def __init__(self, database_path, database_backup_dir): # noqa D107
- self.database_path = database_path
- self.database_backup_dir = database_backup_dir
- self.connection = None
- self.cursor = None
-
- def backup(self, timestamp_string):
- """Take a backup of the database."""
- if not os.path.exists(self.database_backup_dir):
- print(f"Database backup directory {self.database_backup_dir} does not exist -> creating...", end="")
- os.makedirs(self.database_backup_dir)
- print("Done!")
- database_backup_path = os.path.join(self.database_backup_dir, f"backup-{timestamp_string}-invokeai.db")
- print(f"Making DB Backup at {database_backup_path}...", end="")
- shutil.copy2(self.database_path, database_backup_path)
- print("Done!")
-
- def connect(self):
- """Open connection to the database."""
- self.connection = sqlite3.connect(self.database_path)
- # FK enforcement is per-connection and off by default. Without it, the
- # image deletions below leave orphaned rows in tables that declare
- # ON DELETE CASCADE against images (board_images, image_embeddings).
- self.connection.execute("PRAGMA foreign_keys = ON;")
- self.cursor = self.connection.cursor()
-
- def get_all_image_files(self):
- """Get the full list of image file names from the database."""
- sql_get_image_by_name = "SELECT image_name FROM images"
- self.cursor.execute(sql_get_image_by_name)
- rows = self.cursor.fetchall()
- db_files = []
- for row in rows:
- db_files.append(row[0])
- return db_files
-
- def remove_image_file_record(self, filename: str):
- """Remove an image file reference from the database by filename."""
- sanitized_filename = str.replace(filename, "'", "''") # prevent injection
- sql_command = f"DELETE FROM images WHERE image_name='{sanitized_filename}'"
- self.cursor.execute(sql_command)
- self.connection.commit()
-
- def does_image_exist(self, image_filename):
- """Check database if a image name already exists and return a boolean."""
- sanitized_filename = str.replace(image_filename, "'", "''") # prevent injection
- sql_get_image_by_name = f"SELECT image_name FROM images WHERE image_name='{sanitized_filename}'"
- self.cursor.execute(sql_get_image_by_name)
- rows = self.cursor.fetchall()
- return True if len(rows) > 0 else False
-
- def disconnect(self):
- """Disconnect from the db, cleaning up connections and cursors."""
- if self.cursor is not None:
- self.cursor.close()
- if self.connection is not None:
- self.connection.close()
-
-
-class PhysicalFileMapper:
- """Containing class for script functionality."""
-
- def __init__(self, outputs_path, thumbnails_path, archive_path, thumbnails_archive_path): # noqa D107
- self.outputs_path = outputs_path
- self.archive_path = archive_path
- self.thumbnails_path = thumbnails_path
- self.thumbnails_archive_path = thumbnails_archive_path
-
- def create_archive_directories(self):
- """Create the directory for archiving orphaned image files."""
- if not os.path.exists(self.archive_path):
- print(f"Image archive directory ({self.archive_path}) does not exist -> creating...", end="")
- os.makedirs(self.archive_path)
- print("Created!")
- if not os.path.exists(self.thumbnails_archive_path):
- print(
- f"Image thumbnails archive directory ({self.thumbnails_archive_path}) does not exist -> creating...",
- end="",
- )
- os.makedirs(self.thumbnails_archive_path)
- print("Created!")
-
- def get_image_path_for_image_name(self, image_filename): # noqa D102
- return os.path.join(self.outputs_path, image_filename)
-
- def image_file_exists(self, image_filename): # noqa D102
- return os.path.exists(self.get_image_path_for_image_name(image_filename))
-
- def get_thumbnail_path_for_image(self, image_filename): # noqa D102
- return os.path.join(self.thumbnails_path, os.path.splitext(image_filename)[0]) + ".webp"
-
- def get_image_name_from_thumbnail_path(self, thumbnail_path): # noqa D102
- return os.path.splitext(os.path.basename(thumbnail_path))[0] + ".png"
-
- def thumbnail_exists_for_filename(self, image_filename): # noqa D102
- return os.path.exists(self.get_thumbnail_path_for_image(image_filename))
-
- def archive_image(self, image_filename): # noqa D102
- if self.image_file_exists(image_filename):
- image_path = self.get_image_path_for_image_name(image_filename)
- shutil.move(image_path, self.archive_path)
-
- def archive_thumbnail_by_image_filename(self, image_filename): # noqa D102
- if self.thumbnail_exists_for_filename(image_filename):
- thumbnail_path = self.get_thumbnail_path_for_image(image_filename)
- shutil.move(thumbnail_path, self.thumbnails_archive_path)
-
- def get_all_png_filenames_in_directory(self, directory_path): # noqa D102
- filepaths = glob.glob(directory_path + "/*.png", recursive=False)
- filenames = []
- for filepath in filepaths:
- filenames.append(os.path.basename(filepath))
- return filenames
-
- def get_all_image_filenames_recursive(self): # noqa D102
- """Return the set of all image filenames found anywhere under outputs_path.
-
- When an image_subfolder_strategy is configured, images are written to
- subdirectories of outputs/images (e.g. by date, type or hash). This walks
- the entire tree so that images stored in subfolders are not mistaken for
- missing files. Thumbnails are stored as .webp and so are excluded by the
- .png glob; the images-archive directory is a sibling of outputs/images and
- is therefore not traversed.
- """
- filepaths = glob.glob(os.path.join(self.outputs_path, "**", "*.png"), recursive=True)
- return {os.path.basename(filepath) for filepath in filepaths}
-
- def get_all_thumbnails_with_full_path(self, thumbnails_directory): # noqa D102
- return glob.glob(thumbnails_directory + "/*.webp", recursive=False)
-
- def generate_thumbnail_for_image_name(self, image_filename): # noqa D102
- # create thumbnail
- file_path = self.get_image_path_for_image_name(image_filename)
- thumb_path = self.get_thumbnail_path_for_image(image_filename)
- thumb_size = 256, 256
- with PIL.Image.open(file_path) as source_image:
- source_image.thumbnail(thumb_size)
- source_image.save(thumb_path, "webp")
-
-
-class MaintenanceOperation(str, enum.Enum):
- """Enum class for operations."""
-
- Ask = "ask"
- CleanOrphanedDbEntries = "clean"
- CleanOrphanedDiskFiles = "archive"
- ReGenerateThumbnails = "thumbnails"
- All = "all"
-
-
-class InvokeAIDatabaseMaintenanceApp:
- """Main processor class for the application."""
-
- _operation: MaintenanceOperation
- _headless: bool = False
- __stats: MaintenanceStats = MaintenanceStats()
-
- def __init__(self, operation: MaintenanceOperation = MaintenanceOperation.Ask):
- """Initialize maintenance app."""
- self._operation = MaintenanceOperation(operation)
- self._headless = operation != MaintenanceOperation.Ask
-
- def ask_for_operation(self) -> MaintenanceOperation:
- """Ask user to choose the operation to perform."""
- while True:
- print()
- print("It is recommennded to run these operations as ordered below to avoid additional")
- print("work being performed that will be discarded in a subsequent step.")
- print()
- print("Select maintenance operation:")
- print()
- print("1) Clean Orphaned Database Image Entries")
- print(" Cleans entries in the database where the matching file was removed from")
- print(" the outputs directory.")
- print("2) Archive Orphaned Image Files")
- print(" Files found in the outputs directory without an entry in the database are")
- print(" moved to an archive directory.")
- print("3) Re-Generate Missing Thumbnail Files")
- print(" For files found in the outputs directory, re-generate a thumbnail if it")
- print(" not found in the thumbnails directory.")
- print()
- print("(CTRL-C to quit)")
-
- try:
- input_option = int(input("Specify desired operation number (1-3): "))
-
- operations = [
- MaintenanceOperation.CleanOrphanedDbEntries,
- MaintenanceOperation.CleanOrphanedDiskFiles,
- MaintenanceOperation.ReGenerateThumbnails,
- ]
- return operations[input_option - 1]
- except (IndexError, ValueError):
- print("\nInvalid selection!")
-
- def ask_to_continue(self) -> bool:
- """Ask user whether they want to continue with the operation."""
- while True:
- input_choice = input("Do you wish to continue? (Y or N)? ")
- if str.lower(input_choice) == "y":
- return True
- if str.lower(input_choice) == "n":
- return False
-
- def clean_orphaned_db_entries(
- self, config: ConfigMapper, file_mapper: PhysicalFileMapper, db_mapper: DatabaseMapper
- ):
- """Clean dangling database entries that no longer point to a file in outputs."""
- if self._headless:
- print(f"Removing database references to images that no longer exist in {config.outputs_path}...")
- else:
- print()
- print("===============================================================================")
- print("= Clean Orphaned Database Entries")
- print()
- print("Perform this operation if you have removed files from the outputs/images")
- print("directory but the database was never updated. You may see this as empty imaages")
- print("in the app gallery, or images that only show an enlarged version of the")
- print("thumbnail.")
- print()
- print(f"Database File Path : {config.database_path}")
- print(f"Database backup will be taken at : {config.database_backup_dir}")
- print(f"Outputs/Images Directory : {config.outputs_path}")
- print(f"Outputs/Images Archive Directory : {config.archive_path}")
-
- print("\nNotes about this operation:")
- print("- This operation will find database image file entries that do not exist in the")
- print(" outputs/images dir and remove those entries from the database.")
- print("- This operation will target all image types including intermediate files.")
- print("- If a thumbnail still exists in outputs/images/thumbnails matching the")
- print(" orphaned entry, it will be moved to the archive directory.")
- print()
-
- if not self.ask_to_continue():
- raise KeyboardInterrupt
-
- file_mapper.create_archive_directories()
- db_mapper.backup(config.TIMESTAMP_STRING)
- db_mapper.connect()
- db_files = db_mapper.get_all_image_files()
- # Build an index of every image present anywhere under outputs/images, including any
- # subfolders created by an image_subfolder_strategy. A db entry is only orphaned if its
- # file is absent from this entire tree, not just the top-level outputs/images directory.
- disk_image_filenames = file_mapper.get_all_image_filenames_recursive()
- for db_file in db_files:
- try:
- if db_file not in disk_image_filenames:
- print(f"Found orphaned image db entry {db_file}. Cleaning ...", end="")
- db_mapper.remove_image_file_record(db_file)
- print("Cleaned!")
- if file_mapper.thumbnail_exists_for_filename(db_file):
- print("A thumbnail was found, archiving ...", end="")
- file_mapper.archive_thumbnail_by_image_filename(db_file)
- print("Archived!")
- self.__stats.count_orphaned_db_entries_cleaned += 1
- except Exception as ex:
- print("An error occurred cleaning db entry, error was:")
- print(ex)
- self.__stats.count_errors += 1
-
- def clean_orphaned_disk_files(
- self, config: ConfigMapper, file_mapper: PhysicalFileMapper, db_mapper: DatabaseMapper
- ):
- """Archive image files that no longer have entries in the database."""
- if self._headless:
- print(f"Archiving orphaned image files to {config.archive_path}...")
- else:
- print()
- print("===============================================================================")
- print("= Clean Orphaned Disk Files")
- print()
- print("Perform this operation if you have files that were copied into the outputs")
- print("directory which are not referenced by the database. This can happen if you")
- print("upgraded to a version with a fresh database, but re-used the outputs directory")
- print("and now new images are mixed with the files not in the db. The script will")
- print("archive these files so you can choose to delete them or re-import using the")
- print("official import script.")
- print()
- print(f"Database File Path : {config.database_path}")
- print(f"Database backup will be taken at : {config.database_backup_dir}")
- print(f"Outputs/Images Directory : {config.outputs_path}")
- print(f"Outputs/Images Archive Directory : {config.archive_path}")
-
- print("\nNotes about this operation:")
- print("- This operation will find image files not referenced by the database and move to an")
- print(" archive directory.")
- print("- This operation will target all image types including intermediate references.")
- print("- The matching thumbnail will also be archived.")
- print("- Any remaining orphaned thumbnails will also be archived.")
-
- if not self.ask_to_continue():
- raise KeyboardInterrupt
-
- print()
-
- file_mapper.create_archive_directories()
- db_mapper.backup(config.TIMESTAMP_STRING)
- db_mapper.connect()
- phys_files = file_mapper.get_all_png_filenames_in_directory(config.outputs_path)
- for phys_file in phys_files:
- try:
- if not db_mapper.does_image_exist(phys_file):
- print(f"Found orphaned file {phys_file}, archiving...", end="")
- file_mapper.archive_image(phys_file)
- print("Archived!")
- if file_mapper.thumbnail_exists_for_filename(phys_file):
- print("Related thumbnail exists, archiving...", end="")
- file_mapper.archive_thumbnail_by_image_filename(phys_file)
- print("Archived!")
- else:
- print("No matching thumbnail existed to be cleaned.")
- self.__stats.count_orphaned_disk_files_cleaned += 1
- except Exception as ex:
- print("Error found trying to archive file or thumbnail, error was:")
- print(ex)
- self.__stats.count_errors += 1
-
- thumb_filepaths = file_mapper.get_all_thumbnails_with_full_path(config.thumbnails_path)
- # archive any remaining orphaned thumbnails
- for thumb_filepath in thumb_filepaths:
- try:
- thumb_src_image_name = file_mapper.get_image_name_from_thumbnail_path(thumb_filepath)
- if not file_mapper.image_file_exists(thumb_src_image_name):
- print(f"Found orphaned thumbnail {thumb_filepath}, archiving...", end="")
- file_mapper.archive_thumbnail_by_image_filename(thumb_src_image_name)
- print("Archived!")
- self.__stats.count_orphaned_thumbnails_cleaned += 1
- except Exception as ex:
- print("Error found trying to archive thumbnail, error was:")
- print(ex)
- self.__stats.count_errors += 1
-
- def regenerate_thumbnails(self, config: ConfigMapper, file_mapper: PhysicalFileMapper, *args):
- """Create missing thumbnails for any valid general images both in the db and on disk."""
- if self._headless:
- print("Regenerating missing image thumbnails...")
- else:
- print()
- print("===============================================================================")
- print("= Regenerate Thumbnails")
- print()
- print("This operation will find files that have no matching thumbnail on disk")
- print("and regenerate those thumbnail files.")
- print("NOTE: It is STRONGLY recommended that the user first clean/archive orphaned")
- print(" disk files from the previous menu to avoid wasting time regenerating")
- print(" thumbnails for orphaned files.")
-
- print()
- print(f"Outputs/Images Directory : {config.outputs_path}")
- print(f"Outputs/Images Directory : {config.thumbnails_path}")
-
- print("\nNotes about this operation:")
- print("- This operation will find image files both referenced in the db and on disk")
- print(" that do not have a matching thumbnail on disk and re-generate the thumbnail")
- print(" file.")
-
- if not self.ask_to_continue():
- raise KeyboardInterrupt
-
- print()
-
- phys_files = file_mapper.get_all_png_filenames_in_directory(config.outputs_path)
- for phys_file in phys_files:
- try:
- if not file_mapper.thumbnail_exists_for_filename(phys_file):
- print(f"Found file without thumbnail {phys_file}...Regenerating Thumbnail...", end="")
- file_mapper.generate_thumbnail_for_image_name(phys_file)
- print("Done!")
- self.__stats.count_thumbnails_regenerated += 1
- except Exception as ex:
- print("Error found trying to regenerate thumbnail, error was:")
- print(ex)
- self.__stats.count_errors += 1
-
- def main(self): # noqa D107
- print("\n===============================================================================")
- print("Database and outputs Maintenance for Invoke AI 3.0.0 +")
- print("===============================================================================\n")
-
- config_mapper = ConfigMapper()
- if not config_mapper.load():
- print("\nInvalid configuration...exiting.\n")
- return
-
- file_mapper = PhysicalFileMapper(
- config_mapper.outputs_path,
- config_mapper.thumbnails_path,
- config_mapper.archive_path,
- config_mapper.thumbnails_archive_path,
- )
- db_mapper = DatabaseMapper(config_mapper.database_path, config_mapper.database_backup_dir)
-
- op = self._operation
- operations_to_perform = []
-
- if op == MaintenanceOperation.Ask:
- op = self.ask_for_operation()
-
- if op in [MaintenanceOperation.CleanOrphanedDbEntries, MaintenanceOperation.All]:
- operations_to_perform.append(self.clean_orphaned_db_entries)
- if op in [MaintenanceOperation.CleanOrphanedDiskFiles, MaintenanceOperation.All]:
- operations_to_perform.append(self.clean_orphaned_disk_files)
- if op in [MaintenanceOperation.ReGenerateThumbnails, MaintenanceOperation.All]:
- operations_to_perform.append(self.regenerate_thumbnails)
-
- for operation in operations_to_perform:
- operation(config_mapper, file_mapper, db_mapper)
-
- print("\n===============================================================================")
- print(f"= Maintenance Complete - Elapsed Time: {MaintenanceStats.get_elapsed_time_string()}")
- print()
- print(f"Orphaned db entries cleaned : {self.__stats.count_orphaned_db_entries_cleaned}")
- print(f"Orphaned disk files archived : {self.__stats.count_orphaned_disk_files_cleaned}")
- print(f"Orphaned thumbnail files archived : {self.__stats.count_orphaned_thumbnails_cleaned}")
- print(f"Thumbnails regenerated : {self.__stats.count_thumbnails_regenerated}")
- print(f"Errors during operation : {self.__stats.count_errors}")
-
- print()
-
-
-def main(): # noqa D107
- parser = argparse.ArgumentParser(
- description="InvokeAI image database maintenance utility",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""Operations:
- ask Choose operation from a menu [default]
- all Run all maintenance operations
- clean Clean database of dangling entries
- archive Archive orphaned image files
- thumbnails Regenerate missing image thumbnails
-""",
- )
- parser.add_argument("--root", default=".", type=Path, help="InvokeAI root directory")
- parser.add_argument(
- "--operation", default="ask", choices=[x.value for x in MaintenanceOperation], help="Operation to perform."
- )
- args = parser.parse_args()
- try:
- os.chdir(args.root)
- app = InvokeAIDatabaseMaintenanceApp(args.operation)
- app.main()
- except KeyboardInterrupt:
- print("\n\nUser cancelled execution.")
- except FileNotFoundError:
- print(f"Invalid root directory '{args.root}'.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index c9bf9f3e26..d5e413a3a7 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -10040,6 +10040,242 @@
}
}
},
+ "/api/v1/app/gallery/maintenance/preview": {
+ "post": {
+ "tags": ["gallery_maintenance"],
+ "summary": "Preview Gallery Maintenance",
+ "operationId": "preview_gallery_maintenance",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenancePreviewRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenancePreview"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Admin privileges required"
+ },
+ "409": {
+ "description": "Gallery maintenance is already active"
+ },
+ "500": {
+ "description": "Gallery maintenance preview failed"
+ },
+ "503": {
+ "description": "Gallery maintenance unavailable"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/app/gallery/maintenance/remove-missing": {
+ "post": {
+ "tags": ["gallery_maintenance"],
+ "summary": "Remove Missing Images",
+ "operationId": "remove_missing_images",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenanceExecuteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenanceResult"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Admin privileges required"
+ },
+ "409": {
+ "description": "Preview is stale or image storage is busy"
+ },
+ "500": {
+ "description": "Gallery maintenance failed"
+ },
+ "503": {
+ "description": "Gallery maintenance unavailable"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/app/gallery/maintenance/archive-untracked": {
+ "post": {
+ "tags": ["gallery_maintenance"],
+ "summary": "Archive Untracked Images",
+ "operationId": "archive_untracked_images",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenanceExecuteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenanceResult"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Admin privileges required"
+ },
+ "409": {
+ "description": "Preview is stale or image storage is busy"
+ },
+ "500": {
+ "description": "Gallery maintenance failed"
+ },
+ "503": {
+ "description": "Gallery maintenance unavailable"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
+ "/api/v1/app/gallery/maintenance/regenerate-thumbnails": {
+ "post": {
+ "tags": ["gallery_maintenance"],
+ "summary": "Regenerate Missing Thumbnails",
+ "operationId": "regenerate_missing_thumbnails",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenanceExecuteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GalleryMaintenanceResult"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Admin privileges required"
+ },
+ "409": {
+ "description": "Preview is stale or image storage is busy"
+ },
+ "500": {
+ "description": "Gallery maintenance failed"
+ },
+ "503": {
+ "description": "Gallery maintenance unavailable"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
"/api/v1/boards/": {
"post": {
"tags": ["boards"],
@@ -40353,6 +40589,183 @@
"title": "GalleryItemRef",
"description": "A thin reference to a gallery item \u2014 used for ordered name lists."
},
+ "GalleryMaintenanceExecuteRequest": {
+ "properties": {
+ "fingerprint": {
+ "type": "string",
+ "maxLength": 64,
+ "minLength": 64,
+ "pattern": "^[0-9a-f]{64}$",
+ "title": "Fingerprint"
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "required": ["fingerprint"],
+ "title": "GalleryMaintenanceExecuteRequest"
+ },
+ "GalleryMaintenanceOperation": {
+ "type": "string",
+ "enum": ["remove_missing", "archive_untracked", "regenerate_thumbnails"],
+ "title": "GalleryMaintenanceOperation"
+ },
+ "GalleryMaintenancePreview": {
+ "properties": {
+ "operation": {
+ "$ref": "#/components/schemas/GalleryMaintenanceOperation"
+ },
+ "fingerprint": {
+ "type": "string",
+ "maxLength": 64,
+ "minLength": 64,
+ "pattern": "^[0-9a-f]{64}$",
+ "title": "Fingerprint"
+ },
+ "examined_count": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Examined Count"
+ },
+ "affected_count": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Affected Count"
+ },
+ "skipped_count": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Skipped Count"
+ },
+ "error_count": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Error Count"
+ },
+ "errors": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "maxItems": 20,
+ "title": "Errors"
+ },
+ "archive_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Archive Path"
+ }
+ },
+ "type": "object",
+ "required": ["operation", "fingerprint", "examined_count", "affected_count", "skipped_count", "error_count"],
+ "title": "GalleryMaintenancePreview"
+ },
+ "GalleryMaintenancePreviewRequest": {
+ "properties": {
+ "operation": {
+ "$ref": "#/components/schemas/GalleryMaintenanceOperation"
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "required": ["operation"],
+ "title": "GalleryMaintenancePreviewRequest"
+ },
+ "GalleryMaintenanceResult": {
+ "properties": {
+ "operation": {
+ "$ref": "#/components/schemas/GalleryMaintenanceOperation"
+ },
+ "status": {
+ "type": "string",
+ "enum": ["completed", "partial", "no_op", "failed"],
+ "title": "Status"
+ },
+ "examined_count": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Examined Count"
+ },
+ "skipped_count": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Skipped Count"
+ },
+ "failed_count": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Failed Count"
+ },
+ "records_removed": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Records Removed"
+ },
+ "images_archived": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Images Archived"
+ },
+ "thumbnails_archived": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Thumbnails Archived"
+ },
+ "thumbnails_regenerated": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Thumbnails Regenerated"
+ },
+ "archive_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Archive Path"
+ },
+ "backup_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Backup Path"
+ },
+ "errors": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "maxItems": 20,
+ "title": "Errors"
+ }
+ },
+ "type": "object",
+ "required": [
+ "operation",
+ "status",
+ "examined_count",
+ "skipped_count",
+ "failed_count",
+ "records_removed",
+ "images_archived",
+ "thumbnails_archived",
+ "thumbnails_regenerated"
+ ],
+ "title": "GalleryMaintenanceResult"
+ },
"GeminiImageGenerationInvocation": {
"category": "image",
"class": "invocation",
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 5493bbd500..99724dd334 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -2335,6 +2335,74 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/app/gallery/maintenance/preview": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Preview Gallery Maintenance */
+ post: operations["preview_gallery_maintenance"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/app/gallery/maintenance/remove-missing": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Remove Missing Images */
+ post: operations["remove_missing_images"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/app/gallery/maintenance/archive-untracked": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Archive Untracked Images */
+ post: operations["archive_untracked_images"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/app/gallery/maintenance/regenerate-thumbnails": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Regenerate Missing Thumbnails */
+ post: operations["regenerate_missing_thumbnails"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/boards/": {
parameters: {
query?: never;
@@ -16254,6 +16322,67 @@ export type components = {
*/
name: string;
};
+ /** GalleryMaintenanceExecuteRequest */
+ GalleryMaintenanceExecuteRequest: {
+ /** Fingerprint */
+ fingerprint: string;
+ };
+ /**
+ * GalleryMaintenanceOperation
+ * @enum {string}
+ */
+ GalleryMaintenanceOperation: "remove_missing" | "archive_untracked" | "regenerate_thumbnails";
+ /** GalleryMaintenancePreview */
+ GalleryMaintenancePreview: {
+ operation: components["schemas"]["GalleryMaintenanceOperation"];
+ /** Fingerprint */
+ fingerprint: string;
+ /** Examined Count */
+ examined_count: number;
+ /** Affected Count */
+ affected_count: number;
+ /** Skipped Count */
+ skipped_count: number;
+ /** Error Count */
+ error_count: number;
+ /** Errors */
+ errors?: string[];
+ /** Archive Path */
+ archive_path?: string | null;
+ };
+ /** GalleryMaintenancePreviewRequest */
+ GalleryMaintenancePreviewRequest: {
+ operation: components["schemas"]["GalleryMaintenanceOperation"];
+ };
+ /** GalleryMaintenanceResult */
+ GalleryMaintenanceResult: {
+ operation: components["schemas"]["GalleryMaintenanceOperation"];
+ /**
+ * Status
+ * @enum {string}
+ */
+ status: "completed" | "partial" | "no_op" | "failed";
+ /** Examined Count */
+ examined_count: number;
+ /** Skipped Count */
+ skipped_count: number;
+ /** Failed Count */
+ failed_count: number;
+ /** Records Removed */
+ records_removed: number;
+ /** Images Archived */
+ images_archived: number;
+ /** Thumbnails Archived */
+ thumbnails_archived: number;
+ /** Thumbnails Regenerated */
+ thumbnails_regenerated: number;
+ /** Archive Path */
+ archive_path?: string | null;
+ /** Backup Path */
+ backup_path?: string | null;
+ /** Errors */
+ errors?: string[];
+ };
/**
* Gemini Image Generation
* @description Generate images using a Gemini-hosted external model.
@@ -56088,6 +56217,278 @@ export interface operations {
};
};
};
+ preview_gallery_maintenance: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenancePreviewRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenancePreview"];
+ };
+ };
+ /** @description Authentication required */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Admin privileges required */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Gallery maintenance is already active */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ /** @description Gallery maintenance preview failed */
+ 500: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Gallery maintenance unavailable */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
+ remove_missing_images: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenanceExecuteRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenanceResult"];
+ };
+ };
+ /** @description Authentication required */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Admin privileges required */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Preview is stale or image storage is busy */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ /** @description Gallery maintenance failed */
+ 500: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Gallery maintenance unavailable */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
+ archive_untracked_images: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenanceExecuteRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenanceResult"];
+ };
+ };
+ /** @description Authentication required */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Admin privileges required */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Preview is stale or image storage is busy */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ /** @description Gallery maintenance failed */
+ 500: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Gallery maintenance unavailable */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
+ regenerate_missing_thumbnails: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenanceExecuteRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["GalleryMaintenanceResult"];
+ };
+ };
+ /** @description Authentication required */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Admin privileges required */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Preview is stale or image storage is busy */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ /** @description Gallery maintenance failed */
+ 500: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Gallery maintenance unavailable */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
list_boards: {
parameters: {
query?: {
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index cc41a1a11f..3d6c1cec0c 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1793,6 +1793,41 @@
"failed": "Database VACUUM failed.",
"requestFailed": "The database could not be vacuumed."
},
+ "galleryMaintenance": {
+ "heading": "Gallery maintenance",
+ "removeMissing": "Remove records for missing images",
+ "removeMissingDescription": "Remove gallery entries whose original image files are missing. Remaining thumbnails are moved to the archive.",
+ "removeMissingTitle": "Remove records for missing images?",
+ "removeMissingConfirm": "Remove missing image records",
+ "removeMissingConsequence": "This removes the missing images from gallery boards and their related semantic-index entries.",
+ "archiveUntracked": "Archive untracked files",
+ "archiveUntrackedDescription": "Move image files that have no gallery record, and orphaned thumbnails, to the archive.",
+ "archiveUntrackedTitle": "Archive untracked image files?",
+ "archiveUntrackedConfirm": "Archive untracked files",
+ "regenerateThumbnails": "Regenerate missing thumbnails",
+ "regenerateThumbnailsDescription": "Create missing thumbnails for images in the gallery. Original images are unchanged.",
+ "regenerateThumbnailsTitle": "Regenerate missing thumbnails?",
+ "regenerateThumbnailsConfirm": "Regenerate thumbnails",
+ "installationScope": "This maintenance scans images across all accounts in this InvokeAI installation and may take time.",
+ "previewLoading": "Scanning for affected images…",
+ "previewFailed": "The gallery could not be scanned.",
+ "retryPreview": "Retry scan",
+ "previewSummary": "Examined {{examined}} items · {{affected}} affected · {{skipped}} skipped · {{errors}} scan errors",
+ "archiveLocation": "Archive location",
+ "backupLocation": "Database backup",
+ "executionRunning": "Maintenance is running…",
+ "completed": "Gallery maintenance completed.",
+ "partial": "Gallery maintenance completed with some failures.",
+ "no_op": "No gallery maintenance was needed.",
+ "failed": "Gallery maintenance failed.",
+ "operationFailed": "Gallery maintenance could not be completed.",
+ "conflict": "The maintenance preview changed or another maintenance operation is running.",
+ "reviewCurrentItems": "Scan again and review",
+ "executeFailed": "The gallery maintenance request failed.",
+ "refreshFailed": "The gallery changed, but its read models could not be refreshed.",
+ "accountChanged": "The account changed. Review a fresh scan before continuing.",
+ "resultSummary": "Examined {{examined}} · Removed records {{recordsRemoved}} · Archived images {{imagesArchived}} · Archived thumbnails {{thumbnailsArchived}} · Regenerated thumbnails {{thumbnailsRegenerated}} · Skipped {{skipped}} · Failed {{failed}}"
+ },
"catalog": {
"themeId": {
"label": "Theme",
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
index caddb59d22..268f219303 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
@@ -11,7 +11,7 @@ import type { InfiniteData, Query, QueryClient, QueryKey } from '@tanstack/react
import { toGalleryItemKey } from '@features/gallery/core/items';
import { pruneImageClusterMembers } from '@features/gallery/core/semanticImageQuery';
-import { captureAccountScope } from '@platform/state/accountLifecycle';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { rollBackUnclaimedEntries } from '@platform/state/compareAndSwapRollback';
import { hashKey } from '@tanstack/react-query';
@@ -31,6 +31,36 @@ export type GalleryItemCachePatch =
| { boardId: string; kind: 'move'; result: GalleryItemMutationResult }
| { kind: 'star'; result: GalleryItemMutationResult; starred: boolean };
+let galleryThumbnailRevision = 0;
+const galleryThumbnailRevisionListeners = new Set<() => void>();
+
+export const getGalleryThumbnailRevision = (): number => galleryThumbnailRevision;
+
+export const subscribeGalleryThumbnailRevision = (listener: () => void): (() => void) => {
+ galleryThumbnailRevisionListeners.add(listener);
+ return () => galleryThumbnailRevisionListeners.delete(listener);
+};
+
+/** Ask mounted gallery thumbnails to request their URLs again after maintenance repairs them. */
+export const refreshGalleryThumbnails = (owner: AccountScope): void => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ galleryThumbnailRevision += 1;
+ galleryThumbnailRevisionListeners.forEach((listener) => listener());
+};
+
+export const getRefreshedGalleryThumbnailUrl = (url: string, currentRevision: number): string => {
+ if (currentRevision === 0 || /^(?:blob|data):/i.test(url)) {
+ return url;
+ }
+
+ const refreshedUrl = new URL(url, window.location.href);
+ refreshedUrl.searchParams.set('gallery_thumbnail_revision', String(currentRevision));
+ return refreshedUrl.toString();
+};
+
/** A list window's pages, or the starred strip's single page. */
type GalleryItemsCacheData = InfiniteData<GalleryItemsPage, number> | GalleryItemsPage;
diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.ts
index 63f8f0dc0c..d699843506 100644
--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts
@@ -25,6 +25,10 @@ export {
invalidateGallery,
invalidateGalleryItems,
patchGalleryItemCaches,
+ getGalleryThumbnailRevision,
+ getRefreshedGalleryThumbnailUrl,
+ refreshGalleryThumbnails,
+ subscribeGalleryThumbnailRevision,
} from './data/queryCache';
export type { GalleryItemCachePatch } from './data/queryCache';
export { createGalleryRealtimeRuntime } from './data/realtimeRuntime';
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
index 2e4cef8ca7..5faac185bc 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
@@ -5,9 +5,23 @@ import { Badge, chakra } from '@chakra-ui/react';
import { useDraggable } from '@dnd-kit/core';
import { CSS } from '@dnd-kit/utilities';
import { formatGalleryVideoDuration, toGalleryItemRef } from '@features/gallery/core/items';
+import {
+ getGalleryThumbnailRevision,
+ getRefreshedGalleryThumbnailUrl,
+ subscribeGalleryThumbnailRevision,
+} from '@features/gallery/queries';
import { IconButton } from '@platform/ui/Button';
import { StarIcon } from 'lucide-react';
-import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react';
+import {
+ useCallback,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type KeyboardEvent,
+ type MouseEvent,
+} from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
@@ -81,6 +95,18 @@ const GalleryThumbnail = ({
onToggleStarred: (item: GalleryItem) => void;
}) => {
const { t } = useTranslation();
+ const thumbnailRevision = useSyncExternalStore(
+ subscribeGalleryThumbnailRevision,
+ getGalleryThumbnailRevision,
+ getGalleryThumbnailRevision
+ );
+ const thumbnailUrl = useMemo(
+ () =>
+ item.kind === 'image'
+ ? getRefreshedGalleryThumbnailUrl(item.thumbnailUrl || item.fullUrl, thumbnailRevision)
+ : item.thumbnailUrl || item.fullUrl,
+ [item.fullUrl, item.kind, item.thumbnailUrl, thumbnailRevision]
+ );
const isCompared = compareRole !== null;
const duration = item.kind === 'video' ? formatGalleryVideoDuration(item.durationSeconds) : null;
@@ -225,7 +251,7 @@ const GalleryThumbnail = ({
alt={item.name}
decoding={item.kind === 'video' ? 'async' : undefined}
draggable={false}
- src={item.thumbnailUrl || item.fullUrl}
+ src={thumbnailUrl}
style={imageStyle}
/>
</button>
@@ -279,7 +305,7 @@ const GalleryThumbnail = ({
{previewStyle
? createPortal(
<div aria-hidden="true" style={previewStyle}>
- <img alt="" src={item.thumbnailUrl || item.fullUrl} style={PREVIEW_IMAGE_STYLE} />
+ <img alt="" src={thumbnailUrl} style={PREVIEW_IMAGE_STYLE} />
</div>,
document.body
)
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
index fbd9dcf6f1..7245a1959c 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
@@ -11,6 +11,10 @@ import { closingFrames, recordDialogExit } from './dialogExit.testing';
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const noop = () => undefined;
+let confirmCalls = 0;
+const handleConfirm = () => {
+ confirmCalls += 1;
+};
let host: HTMLDivElement | null = null;
let root: Root | null = null;
@@ -23,6 +27,46 @@ afterEach(async () => {
});
describe('ConfirmDialog', () => {
+ it('keeps confirmation disabled until its owner has a valid preview', async () => {
+ confirmCalls = 0;
+ const renderDialog = async (isConfirmDisabled: boolean) => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <ConfirmDialog
+ body="Preview is still loading."
+ confirmLabel="Proceed"
+ isConfirmDisabled={isConfirmDisabled}
+ isOpen
+ title="Confirm maintenance"
+ onClose={noop}
+ onConfirm={handleConfirm}
+ />
+ </ChakraProvider>
+ )
+ );
+ };
+
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await renderDialog(true);
+
+ const confirm = [...document.querySelectorAll<HTMLButtonElement>('[role="alertdialog"] button')].find(
+ (button) => button.textContent === 'Proceed'
+ )!;
+ expect(confirm.disabled).toBe(true);
+ expect(confirmCalls).toBe(0);
+
+ await renderDialog(false);
+ const enabledConfirm = [...document.querySelectorAll<HTMLButtonElement>('[role="alertdialog"] button')].find(
+ (button) => button.textContent === 'Proceed'
+ )!;
+ expect(enabledConfirm.disabled).toBe(false);
+ await act(() => userEvent.click(enabledConfirm));
+ expect(confirmCalls).toBe(1);
+ });
+
it('keeps the text it showed while it animates out after its host clears the subject', async () => {
// The usual host shape: the subject drives the copy and is cleared the moment the dialog closes.
const Host = () => {
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
index 5f71570d32..1f44235a0b 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
@@ -10,6 +10,7 @@ export const ConfirmDialog = ({
confirmLabel,
finalFocusEl,
isDestructive = true,
+ isConfirmDisabled = false,
isOpen,
onClose,
onConfirm,
@@ -21,6 +22,8 @@ export const ConfirmDialog = ({
/** Where focus returns on close when the opener may no longer exist, e.g. a row the confirmed action deleted. */
finalFocusEl?: () => HTMLElement | null;
isDestructive?: boolean;
+ /** Keep confirmation unavailable until the caller has prepared a valid confirmation target. */
+ isConfirmDisabled?: boolean;
isOpen: boolean;
onClose: () => void;
onConfirm: () => Promise<void> | void;
@@ -44,7 +47,7 @@ export const ConfirmDialog = ({
}, [onExitComplete, release]);
const handleConfirm = useCallback(async () => {
- if (isPendingRef.current) {
+ if (isPendingRef.current || isConfirmDisabled) {
return;
}
@@ -58,7 +61,7 @@ export const ConfirmDialog = ({
setIsPending(false);
onClose();
}
- }, [onClose, onConfirm]);
+ }, [isConfirmDisabled, onClose, onConfirm]);
const handleClose = useCallback(() => {
if (!isPendingRef.current) {
@@ -108,7 +111,7 @@ export const ConfirmDialog = ({
</Button>
<Button
colorPalette={text.isDestructive ? 'red' : 'accent'}
- disabled={isPending}
+ disabled={isPending || isConfirmDisabled}
loading={isPending}
variant="solid"
onClick={handleConfirmClick}
diff --git a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
index a611faa2b4..dea145b0f6 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/CustomSettingsEditors.tsx
@@ -37,6 +37,9 @@ const DANGER_BUTTON_HOVER_STYLES = { bg: 'fg.error', color: 'bg.subtle' };
const LazyDatabaseMaintenanceDialog = lazy(() =>
import('./DatabaseMaintenanceDialog').then((module) => ({ default: module.DatabaseMaintenanceDialog }))
);
+const LazyGalleryMaintenance = lazy(() =>
+ import('./GalleryMaintenance').then((module) => ({ default: module.GalleryMaintenance }))
+);
export const ThemeSettings = () => {
const themeId = useWorkbenchPreferenceSelector((preferences) => preferences.themeId);
@@ -232,6 +235,11 @@ export const WorkspaceSettings = ({ onReveal }: Pick<SettingFieldProps, 'onRevea
Clear saved data…
</Button>
</HStack>
+ {canManageAppConfig ? (
+ <Suspense fallback={null}>
+ <LazyGalleryMaintenance />
+ </Suspense>
+ ) : null}
<ConfirmDialog
body={
scope === 'user'
diff --git a/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx
index c53e2f6421..702ef888bf 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx
@@ -6,6 +6,7 @@ import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop */
import { ChakraProvider } from '@chakra-ui/react';
import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -71,12 +72,15 @@ import { WorkspaceSettings } from './CustomSettingsEditors';
describe('database maintenance in Data & workspace settings', () => {
let host: HTMLDivElement;
let root: Root;
+ let queryClient: QueryClient;
const renderSettings = async () => {
await act(() =>
root.render(
<ChakraProvider value={system}>
- <WorkspaceSettings />
+ <QueryClientProvider client={queryClient}>
+ <WorkspaceSettings />
+ </QueryClientProvider>
</ChakraProvider>
)
);
@@ -116,6 +120,7 @@ describe('database maintenance in Data & workspace settings', () => {
mocks.notifyError.mockReset();
mocks.notifySuccess.mockReset();
accountLifecycle.activate('database-maintenance-settings-test', ':user:database-maintenance-settings-test');
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -124,6 +129,7 @@ describe('database maintenance in Data & workspace settings', () => {
afterEach(async () => {
await act(() => root.unmount());
host.remove();
+ queryClient.clear();
accountLifecycle.invalidate();
});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx
new file mode 100644
index 0000000000..3df710ed3e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx
@@ -0,0 +1,557 @@
+import type { GalleryItem } from '@features/gallery/core/items';
+import type * as GalleryQueriesModule from '@features/gallery/queries';
+import type * as IdentityModule from '@features/identity';
+import type * as HttpModule from '@platform/transport/http';
+import type * as ImageMapStoreModule from '@workbench/image-map/imageMapStore';
+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
+
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop */
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { GalleryThumbnailCell } from '@features/gallery/ui/GalleryThumbnail';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { commands, userEvent } from 'vitest/browser';
+
+import type * as SettingsStoreModule from './store';
+
+import { WorkspaceSettings } from './CustomSettingsEditors';
+
+const mocks = vi.hoisted(() => ({
+ apiFetchJson: vi.fn(),
+ canManageAppConfig: true,
+ invalidateGallery: vi.fn(),
+ refreshImageMapPoints: vi.fn(),
+ refreshGalleryThumbnails: vi.fn(),
+}));
+
+const thumbnailRouteCommands = commands as typeof commands & {
+ getThumbnailRequests: () => Promise<{ statuses: number[]; urls: string[] }>;
+ startThumbnailRoute: (pathname: string) => Promise<void>;
+ stopThumbnailRoute: () => Promise<void>;
+};
+
+vi.mock('@features/identity', async (importOriginal) => ({
+ ...(await importOriginal<typeof IdentityModule>()),
+ useCapabilities: () => ({ canManageAppConfig: mocks.canManageAppConfig }),
+}));
+vi.mock('@platform/transport/http', async (importOriginal) => ({
+ ...(await importOriginal<typeof HttpModule>()),
+ apiFetchJson: (...args: unknown[]) => mocks.apiFetchJson(...args),
+}));
+vi.mock('@features/gallery/queries', async (importOriginal) => ({
+ ...((actual) => ({
+ ...actual,
+ invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),
+ refreshGalleryThumbnails: (...args: Parameters<typeof actual.refreshGalleryThumbnails>) => {
+ mocks.refreshGalleryThumbnails(...args);
+ return actual.refreshGalleryThumbnails(...args);
+ },
+ }))(await importOriginal<typeof GalleryQueriesModule>()),
+}));
+vi.mock('@workbench/image-map/imageMapStore', async (importOriginal) => ({
+ ...(await importOriginal<typeof ImageMapStoreModule>()),
+ refreshImageMapPoints: (...args: unknown[]) => mocks.refreshImageMapPoints(...args),
+}));
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkbenchContextModule>()),
+ useActiveProjectId: () => null,
+ useActiveProjectSelector: (selector: (project: { queue: { items: never[] } }) => unknown) =>
+ selector({ queue: { items: [] } }),
+ useOptionalWorkbenchCommands: () => null,
+ useOptionalWorkbenchPersistenceService: () => null,
+}));
+vi.mock('@tanstack/react-router', () => ({ useNavigate: () => vi.fn() }));
+vi.mock('@workbench/palette/PaletteButton', () => ({ PaletteButton: () => null }));
+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));
+vi.mock('@workbench/shell/topbar/useTopbarShortcut', () => ({ useTopbarShortcut: () => null }));
+vi.mock('./store', async (importOriginal) => ({
+ ...(await importOriginal<typeof SettingsStoreModule>()),
+ useWorkbenchSettingsSelector: (selector: (snapshot: never) => unknown) => selector({ scope: 'user' } as never),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => [key, ...Object.values(values ?? {})].join(' '),
+ }),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const operations = [
+ {
+ operation: 'remove_missing',
+ button: 'settings.galleryMaintenance.removeMissing',
+ description: 'settings.galleryMaintenance.removeMissingDescription',
+ title: 'settings.galleryMaintenance.removeMissingTitle',
+ confirm: 'settings.galleryMaintenance.removeMissingConfirm',
+ route: '/api/v1/app/gallery/maintenance/remove-missing',
+ fingerprint: '1'.repeat(64),
+ },
+ {
+ operation: 'archive_untracked',
+ button: 'settings.galleryMaintenance.archiveUntracked',
+ description: 'settings.galleryMaintenance.archiveUntrackedDescription',
+ title: 'settings.galleryMaintenance.archiveUntrackedTitle',
+ confirm: 'settings.galleryMaintenance.archiveUntrackedConfirm',
+ route: '/api/v1/app/gallery/maintenance/archive-untracked',
+ fingerprint: '2'.repeat(64),
+ },
+ {
+ operation: 'regenerate_thumbnails',
+ button: 'settings.galleryMaintenance.regenerateThumbnails',
+ description: 'settings.galleryMaintenance.regenerateThumbnailsDescription',
+ title: 'settings.galleryMaintenance.regenerateThumbnailsTitle',
+ confirm: 'settings.galleryMaintenance.regenerateThumbnailsConfirm',
+ route: '/api/v1/app/gallery/maintenance/regenerate-thumbnails',
+ fingerprint: '3'.repeat(64),
+ },
+] as const;
+
+const preview = (operation: string, fingerprint: string, affectedCount = 2) => ({
+ operation,
+ fingerprint,
+ examined_count: 12,
+ affected_count: affectedCount,
+ skipped_count: 1,
+ error_count: 0,
+ errors: [],
+ archive_path: '/tmp/invokeai/gallery-archive/run-1',
+});
+
+const result = (
+ operation: string,
+ overrides: Partial<{
+ status: 'completed' | 'partial' | 'no_op' | 'failed';
+ records_removed: number;
+ images_archived: number;
+ thumbnails_archived: number;
+ thumbnails_regenerated: number;
+ failed_count: number;
+ archive_path: string | null;
+ backup_path: string | null;
+ }> = {}
+) => ({
+ operation,
+ status: 'completed' as const,
+ examined_count: 12,
+ skipped_count: 1,
+ failed_count: 0,
+ records_removed: 0,
+ images_archived: 0,
+ thumbnails_archived: 0,
+ thumbnails_regenerated: 0,
+ archive_path: null,
+ backup_path: '/tmp/invokeai/gallery-backups/run-1.sqlite',
+ errors: [],
+ ...overrides,
+});
+
+const thumbnailItem: GalleryItem = {
+ boardId: 'board-1',
+ category: 'general',
+ createdAt: '2026-10-07T12:00:00Z',
+ fullUrl: '/api/v1/images/i/repaired/full',
+ height: 64,
+ isIntermediate: false,
+ kind: 'image',
+ name: 'repaired',
+ starred: false,
+ thumbnailUrl: '/api/v1/images/i/repaired/thumbnail',
+ width: 64,
+};
+const thumbnailVideo: GalleryItem = {
+ ...thumbnailItem,
+ durationSeconds: 4,
+ kind: 'video',
+ name: 'unchanged-video',
+ thumbnailUrl: '/api/v1/videos/i/unchanged-video/thumbnail',
+};
+
+describe('gallery maintenance in Data & workspace settings', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ let queryClient: QueryClient;
+
+ const renderSettings = async () => {
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <WorkspaceSettings onReveal={() => {}} />
+ </QueryClientProvider>
+ </ChakraProvider>
+ )
+ );
+ };
+
+ const renderSettingsWithThumbnail = async () => {
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <DndContext>
+ <WorkspaceSettings onReveal={() => {}} />
+ <GalleryThumbnailCell
+ alwaysShowDimensions={false}
+ compareRole={null}
+ dragScope="maintenance-test"
+ fit="square"
+ getDragItems={() => [{ kind: 'image', name: thumbnailItem.name }]}
+ getItemLabel={null}
+ isPrimary={false}
+ isSelected={false}
+ item={thumbnailItem}
+ onClick={() => {}}
+ onContextMenu={() => {}}
+ onToggleStarred={() => {}}
+ />
+ <GalleryThumbnailCell
+ alwaysShowDimensions={false}
+ compareRole={null}
+ dragScope="maintenance-test"
+ fit="square"
+ getDragItems={() => [{ kind: 'video', name: thumbnailVideo.name }]}
+ getItemLabel={null}
+ isPrimary={false}
+ isSelected={false}
+ item={thumbnailVideo}
+ onClick={() => {}}
+ onContextMenu={() => {}}
+ onToggleStarred={() => {}}
+ />
+ </DndContext>
+ </QueryClientProvider>
+ </ChakraProvider>
+ )
+ );
+ };
+
+ const getButton = (key: string) =>
+ [...document.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent?.includes(key));
+
+ const getConfirmButton = (action: (typeof operations)[number]) =>
+ [...document.querySelectorAll<HTMLButtonElement>('[role="alertdialog"] button')].find((button) =>
+ button.textContent?.includes(action.confirm)
+ );
+
+ const openAction = async (action: (typeof operations)[number]) => {
+ await expect.poll(() => getButton(action.button)).toBeDefined();
+ await act(() => userEvent.click(getButton(action.button)!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).not.toBeNull();
+ await expect.poll(() => getConfirmButton(action)?.disabled).toBe(false);
+ const background = getComputedStyle(getConfirmButton(action)!).backgroundColor;
+ const [red = 0, green = 0, blue = 0] = background.match(/\d+/g)?.map(Number) ?? [];
+ expect(red).toBeGreaterThan(green);
+ expect(red).toBeGreaterThan(blue);
+ };
+
+ beforeEach(() => {
+ mocks.canManageAppConfig = true;
+ mocks.apiFetchJson.mockReset();
+ mocks.invalidateGallery.mockReset().mockResolvedValue(undefined);
+ mocks.refreshImageMapPoints.mockReset().mockResolvedValue(undefined);
+ mocks.refreshGalleryThumbnails.mockReset();
+ accountLifecycle.activate('gallery-maintenance-settings-test', ':user:gallery-maintenance-settings-test');
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ await thumbnailRouteCommands.stopThumbnailRoute();
+ host.remove();
+ queryClient.clear();
+ accountLifecycle.invalidate();
+ });
+
+ it('shows three described administrator actions and hides them from non-admins', async () => {
+ await renderSettings();
+
+ for (const action of operations) {
+ await expect.poll(() => getButton(action.button)).toBeDefined();
+ expect(getButton(action.button)).toBeDefined();
+ expect(host.textContent).toContain(action.description);
+ }
+ expect(host.textContent).toContain('settings.databaseMaintenance.compactDatabase');
+ expect(host.textContent).toContain('settings.catalog.manageIntermediates');
+ expect(host.textContent).toContain('Clear saved data');
+ expect(mocks.apiFetchJson).not.toHaveBeenCalled();
+
+ mocks.canManageAppConfig = false;
+ await renderSettings();
+ for (const action of operations) {
+ expect(getButton(action.button)).toBeUndefined();
+ }
+ expect(host.textContent).toContain('Clear saved data');
+ });
+
+ it.each(operations)('$operation previews before confirmation and cancel sends no execute request', async (action) => {
+ mocks.apiFetchJson.mockResolvedValueOnce(preview(action.operation, action.fingerprint));
+ await renderSettings();
+ await openAction(action);
+
+ expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain(action.title);
+ expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('2');
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/app/gallery/maintenance/preview', {
+ method: 'POST',
+ body: JSON.stringify({ operation: action.operation }),
+ signal: expect.any(AbortSignal),
+ });
+
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps confirmation disabled during preview, shows preview errors, and permits a read-only retry', async () => {
+ let resolvePreview!: (value: ReturnType<typeof preview>) => void;
+ mocks.apiFetchJson.mockRejectedValueOnce(new Error('Scan could not read the image directory')).mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolvePreview = resolve;
+ })
+ );
+ await renderSettings();
+ await act(() => userEvent.click(getButton(operations[0].button)!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).not.toBeNull();
+ await expect
+ .poll(() => document.querySelector('[role="alert"]')?.textContent)
+ .toContain('Scan could not read the image directory');
+ expect(getConfirmButton(operations[0])?.disabled).toBe(true);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+
+ await act(() => userEvent.click(getButton('settings.galleryMaintenance.retryPreview')!));
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(getConfirmButton(operations[0])?.disabled).toBe(true);
+ await act(() => resolvePreview(preview(operations[0].operation, operations[0].fingerprint, 0)));
+ await expect.poll(() => getConfirmButton(operations[0])?.disabled).toBe(false);
+ expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('0');
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ });
+
+ it('executes once, retains partial results, and refreshes gallery and map after record removal', async () => {
+ const owner = accountLifecycle.capture();
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(preview('remove_missing', operations[0].fingerprint))
+ .mockResolvedValueOnce(result('remove_missing', { status: 'partial', records_removed: 3, failed_count: 1 }));
+ await renderSettings();
+ await openAction(operations[0]);
+ await act(() => userEvent.click(getConfirmButton(operations[0])!));
+
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(mocks.apiFetchJson).toHaveBeenLastCalledWith(operations[0].route, {
+ method: 'POST',
+ body: JSON.stringify({ fingerprint: operations[0].fingerprint }),
+ signal: expect.any(AbortSignal),
+ });
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(host.textContent).toContain('settings.galleryMaintenance.partial');
+ expect(host.textContent).toContain('3');
+ expect(host.textContent).toContain('/tmp/invokeai/gallery-backups/run-1.sqlite');
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ expect(mocks.invalidateGallery).toHaveBeenCalledWith(queryClient, owner);
+ expect(mocks.refreshImageMapPoints).toHaveBeenCalledOnce();
+ });
+
+ it('refreshes the semantic map even when gallery invalidation fails after committed removals', async () => {
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(preview('remove_missing', operations[0].fingerprint))
+ .mockResolvedValueOnce(result('remove_missing', { status: 'partial', records_removed: 2, failed_count: 1 }));
+ mocks.invalidateGallery.mockRejectedValueOnce(new Error('Gallery refresh failed'));
+ await renderSettings();
+ await openAction(operations[0]);
+ await act(() => userEvent.click(getConfirmButton(operations[0])!));
+
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(mocks.refreshImageMapPoints).toHaveBeenCalledOnce();
+ expect(host.textContent).toContain('settings.galleryMaintenance.partial');
+ expect(host.textContent).toContain('Gallery refresh failed');
+ });
+
+ it('keeps execution open and blocks dismissal and duplicate actions while the server is working', async () => {
+ let resolveExecution!: (value: ReturnType<typeof result>) => void;
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(preview('archive_untracked', operations[1].fingerprint))
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveExecution = resolve;
+ })
+ );
+ await renderSettings();
+ await openAction(operations[1]);
+ const confirmButton = getConfirmButton(operations[1])!;
+ await act(() => userEvent.click(confirmButton));
+
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(confirmButton.disabled).toBe(true);
+ const cancelButton = [...document.querySelectorAll<HTMLButtonElement>('[role="alertdialog"] button')].find(
+ (button) => button.textContent?.includes('Cancel')
+ )!;
+ expect(cancelButton.disabled).toBe(true);
+ expect(getButton(operations[0].button)?.disabled).toBe(true);
+ await act(() => userEvent.keyboard('{Escape}'));
+ expect(document.querySelector('[role="alertdialog"]')).not.toBeNull();
+
+ await act(() => resolveExecution(result('archive_untracked', { images_archived: 4 })));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ });
+
+ it('fences a late preview when the account changes and requires a fresh scan', async () => {
+ let resolvePreview!: (value: ReturnType<typeof preview>) => void;
+ mocks.apiFetchJson
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolvePreview = resolve;
+ })
+ )
+ .mockResolvedValueOnce(preview('remove_missing', '5'.repeat(64)));
+ await renderSettings();
+ await expect.poll(() => getButton(operations[0].button)).toBeDefined();
+ await act(() => userEvent.click(getButton(operations[0].button)!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).not.toBeNull();
+
+ await act(() =>
+ accountLifecycle.activate('gallery-maintenance-next-account', ':user:gallery-maintenance-next-account')
+ );
+ await renderSettings();
+ await act(async () => {
+ resolvePreview(preview('remove_missing', operations[0].fingerprint));
+ await Promise.resolve();
+ });
+
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(host.textContent).not.toContain('settings.galleryMaintenance.accountChanged');
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ await act(() => userEvent.click(getButton(operations[0].button)!));
+ await expect.poll(() => getConfirmButton(operations[0])?.disabled).toBe(false);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ });
+
+ it('hides an execution result from the previous account and stays busy until that request settles', async () => {
+ let resolveExecution!: (value: ReturnType<typeof result>) => void;
+ mocks.apiFetchJson.mockResolvedValueOnce(preview('remove_missing', operations[0].fingerprint)).mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveExecution = resolve;
+ })
+ );
+ await renderSettings();
+ await openAction(operations[0]);
+ await act(() => userEvent.click(getConfirmButton(operations[0])!));
+
+ await act(() =>
+ accountLifecycle.activate('gallery-maintenance-third-account', ':user:gallery-maintenance-third-account')
+ );
+ expect(getButton(operations[0].button)?.disabled).toBe(true);
+ await act(async () => {
+ resolveExecution(result('remove_missing', { records_removed: 2 }));
+ await Promise.resolve();
+ });
+ await expect.poll(() => getButton(operations[0].button)?.disabled).toBe(false);
+
+ expect(host.querySelector('[data-testid="gallery-maintenance-result"]')).toBeNull();
+ expect(mocks.invalidateGallery).not.toHaveBeenCalled();
+ expect(mocks.refreshImageMapPoints).not.toHaveBeenCalled();
+ });
+
+ it('turns a changed-preview conflict into a new scan instead of repeating the mutation', async () => {
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(preview('remove_missing', operations[0].fingerprint))
+ .mockRejectedValueOnce(new ApiError('{"detail":"Preview has changed"}', 409))
+ .mockResolvedValueOnce(preview('remove_missing', '4'.repeat(64), 1));
+ await renderSettings();
+ await openAction(operations[0]);
+ await act(() => userEvent.click(getConfirmButton(operations[0])!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+
+ expect(host.textContent).toContain('settings.galleryMaintenance.conflict');
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ await act(() => userEvent.click(getButton('settings.galleryMaintenance.reviewCurrentItems')!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).not.toBeNull();
+ await expect.poll(() => getConfirmButton(operations[0])?.disabled).toBe(false);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(3);
+ });
+
+ it.each([operations[1], operations[2]])('$operation does not refresh embedding read models', async (action) => {
+ mocks.apiFetchJson.mockResolvedValueOnce(preview(action.operation, action.fingerprint)).mockResolvedValueOnce(
+ result(action.operation, {
+ status: action.operation === 'regenerate_thumbnails' ? 'no_op' : 'completed',
+ records_removed: 4,
+ images_archived: action.operation === 'archive_untracked' ? 4 : 0,
+ thumbnails_regenerated: 0,
+ })
+ );
+ await renderSettings();
+ await openAction(action);
+ await act(() => userEvent.click(getConfirmButton(action)!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+
+ expect(host.textContent).toContain(
+ action.operation === 'regenerate_thumbnails'
+ ? 'settings.galleryMaintenance.no_op'
+ : 'settings.galleryMaintenance.completed'
+ );
+ expect(mocks.invalidateGallery).not.toHaveBeenCalled();
+ expect(mocks.refreshImageMapPoints).not.toHaveBeenCalled();
+ });
+
+ it('refreshes mounted thumbnails after partial regeneration', async () => {
+ const owner = accountLifecycle.capture();
+ const action = operations[2];
+ await thumbnailRouteCommands.startThumbnailRoute(thumbnailItem.thumbnailUrl);
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(preview(action.operation, action.fingerprint))
+ .mockResolvedValueOnce(
+ result(action.operation, { status: 'partial', thumbnails_regenerated: 2, failed_count: 1 })
+ );
+ await renderSettingsWithThumbnail();
+ const thumbnail = host.querySelector<HTMLImageElement>('img[alt="repaired"]')!;
+ const videoThumbnail = host.querySelector<HTMLImageElement>('img[alt="unchanged-video"]')!;
+ const initialUrl = thumbnail.getAttribute('src');
+ const initialVideoUrl = videoThumbnail.getAttribute('src');
+ await expect.poll(() => thumbnail.complete).toBe(true);
+ expect(thumbnail.naturalWidth).toBe(0);
+ expect((await thumbnailRouteCommands.getThumbnailRequests()).statuses).toEqual([404]);
+ await openAction(action);
+ await act(() => userEvent.click(getConfirmButton(action)!));
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();
+
+ await expect.poll(() => thumbnail.getAttribute('src')).not.toBe(initialUrl);
+ expect(thumbnail.getAttribute('src')).toContain('gallery_thumbnail_revision=');
+ expect(videoThumbnail.getAttribute('src')).toBe(initialVideoUrl);
+ await expect.poll(async () => (await thumbnailRouteCommands.getThumbnailRequests()).statuses).toEqual([404, 200]);
+ await expect.poll(() => thumbnail.complete && thumbnail.naturalWidth > 0).toBe(true);
+ const requests = await thumbnailRouteCommands.getThumbnailRequests();
+ expect(requests.urls).toHaveLength(2);
+ expect(requests.urls[0]).not.toBe(requests.urls[1]);
+ expect(mocks.refreshGalleryThumbnails).toHaveBeenCalledOnce();
+ expect(mocks.refreshGalleryThumbnails).toHaveBeenCalledWith(owner);
+ expect(mocks.invalidateGallery).not.toHaveBeenCalled();
+ expect(mocks.refreshImageMapPoints).not.toHaveBeenCalled();
+ });
+
+ it('does not refresh thumbnails when regeneration completes for a previous account', async () => {
+ let resolveExecution!: (value: ReturnType<typeof result>) => void;
+ const action = operations[2];
+ mocks.apiFetchJson.mockResolvedValueOnce(preview(action.operation, action.fingerprint)).mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveExecution = resolve;
+ })
+ );
+ await renderSettings();
+ await openAction(action);
+ await act(() => userEvent.click(getConfirmButton(action)!));
+
+ await act(() => accountLifecycle.activate('gallery-maintenance-another-account', ':user:another-account'));
+ await act(() => resolveExecution(result(action.operation, { thumbnails_regenerated: 3 })));
+
+ expect(mocks.refreshGalleryThumbnails).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.tsx b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.tsx
new file mode 100644
index 0000000000..8fd3ab0555
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.tsx
@@ -0,0 +1,438 @@
+import type { components } from '@api/schema';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+import { Box, Flex, Stack, Text } from '@chakra-ui/react';
+import { invalidateGallery, refreshGalleryThumbnails } from '@features/gallery/queries';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
+import { apiFetchJson, getApiErrorMessage, ApiError } from '@platform/transport/http';
+import { Button, ConfirmDialog } from '@platform/ui';
+import { useQueryClient } from '@tanstack/react-query';
+import { refreshImageMapPoints } from '@workbench/image-map/imageMapStore';
+import { createElement, useCallback, useId, useMemo, useRef, useState, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+type GalleryMaintenanceOperation = components['schemas']['GalleryMaintenanceOperation'];
+type GalleryMaintenancePreview = components['schemas']['GalleryMaintenancePreview'];
+type GalleryMaintenanceResult = components['schemas']['GalleryMaintenanceResult'];
+
+const ACTIONS: Record<
+ GalleryMaintenanceOperation,
+ { label: string; confirmLabel: string; description: string; title: string }
+> = {
+ remove_missing: {
+ confirmLabel: 'removeMissingConfirm',
+ description: 'removeMissingDescription',
+ label: 'removeMissing',
+ title: 'removeMissingTitle',
+ },
+ archive_untracked: {
+ confirmLabel: 'archiveUntrackedConfirm',
+ description: 'archiveUntrackedDescription',
+ label: 'archiveUntracked',
+ title: 'archiveUntrackedTitle',
+ },
+ regenerate_thumbnails: {
+ confirmLabel: 'regenerateThumbnailsConfirm',
+ description: 'regenerateThumbnailsDescription',
+ label: 'regenerateThumbnails',
+ title: 'regenerateThumbnailsTitle',
+ },
+};
+
+type PreviewState =
+ | { kind: 'idle' }
+ | { kind: 'loading'; owner: AccountScope }
+ | { kind: 'ready'; owner: AccountScope; value: GalleryMaintenancePreview }
+ | { kind: 'error'; owner: AccountScope; message: string };
+
+type LatestOutcome =
+ | { kind: 'result'; owner: AccountScope; value: GalleryMaintenanceResult; refreshError?: string }
+ | {
+ kind: 'error';
+ owner: AccountScope;
+ operation: GalleryMaintenanceOperation;
+ message: string;
+ isConflict: boolean;
+ };
+
+const routeForOperation = (operation: GalleryMaintenanceOperation): string =>
+ `/api/v1/app/gallery/maintenance/${
+ operation === 'remove_missing'
+ ? 'remove-missing'
+ : operation === 'archive_untracked'
+ ? 'archive-untracked'
+ : 'regenerate-thumbnails'
+ }`;
+
+const tKey = (key: string): string => `settings.galleryMaintenance.${key}`;
+const ROW_ALIGN = { base: 'stretch', md: 'center' } as const;
+const ROW_DIRECTION = { base: 'column', md: 'row' } as const;
+
+export const GalleryMaintenance = () => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const resourceId = useId();
+ const requestSequence = useRef(0);
+ const executing = useRef(false);
+ const isMounted = useRef(true);
+ const [operation, setOperation] = useState<GalleryMaintenanceOperation | null>(null);
+ const [preview, setPreview] = useState<PreviewState>({ kind: 'idle' });
+ const [isExecuting, setIsExecuting] = useState(false);
+ const [latest, setLatest] = useState<LatestOutcome | null>(null);
+
+ useMountEffect(() => {
+ isMounted.current = true;
+ const unregister = registerAccountOwnedResource({
+ clear: () => {
+ requestSequence.current += 1;
+ setOperation(null);
+ setPreview({ kind: 'idle' });
+ setLatest(null);
+ },
+ name: `gallery-maintenance:${resourceId}`,
+ });
+ return () => {
+ isMounted.current = false;
+ requestSequence.current += 1;
+ unregister();
+ };
+ });
+
+ const startPreview = useCallback(
+ async (nextOperation: GalleryMaintenanceOperation) => {
+ setOperation(nextOperation);
+ const owner = captureAccountScope();
+ const sequence = ++requestSequence.current;
+ setPreview({ kind: 'loading', owner });
+
+ try {
+ const value = await apiFetchJson<GalleryMaintenancePreview>('/api/v1/app/gallery/maintenance/preview', {
+ method: 'POST',
+ body: JSON.stringify({ operation: nextOperation }),
+ signal: owner.signal,
+ });
+ if (sequence === requestSequence.current && isAccountScopeCurrent(owner)) {
+ setPreview({ kind: 'ready', owner, value });
+ }
+ } catch (error) {
+ if (sequence === requestSequence.current && isAccountScopeCurrent(owner)) {
+ setPreview({
+ kind: 'error',
+ owner,
+ message: getApiErrorMessage(error, t(tKey('previewFailed'))),
+ });
+ }
+ }
+ },
+ [t]
+ );
+
+ const closeDialog = useCallback(() => {
+ requestSequence.current += 1;
+ setOperation(null);
+ setPreview({ kind: 'idle' });
+ }, []);
+
+ const retryPreview = useCallback(() => {
+ if (operation !== null) {
+ void startPreview(operation);
+ }
+ }, [operation, startPreview]);
+
+ const previewHandlers = useMemo<Record<GalleryMaintenanceOperation, () => void>>(
+ () => ({
+ remove_missing: () => void startPreview('remove_missing'),
+ archive_untracked: () => void startPreview('archive_untracked'),
+ regenerate_thumbnails: () => void startPreview('regenerate_thumbnails'),
+ }),
+ [startPreview]
+ );
+
+ const execute = useCallback(async () => {
+ if (executing.current || operation === null || preview.kind !== 'ready' || preview.value.operation !== operation) {
+ return;
+ }
+ const owner = preview.owner;
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ executing.current = true;
+ setIsExecuting(true);
+ try {
+ const value = await apiFetchJson<GalleryMaintenanceResult>(routeForOperation(operation), {
+ method: 'POST',
+ body: JSON.stringify({ fingerprint: preview.value.fingerprint }),
+ signal: owner.signal,
+ });
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ if (operation === 'regenerate_thumbnails' && value.thumbnails_regenerated > 0) {
+ refreshGalleryThumbnails(owner);
+ }
+
+ let refreshError: string | undefined;
+ if (operation === 'remove_missing' && value.records_removed > 0) {
+ const refreshErrors: string[] = [];
+ try {
+ await invalidateGallery(queryClient, owner);
+ } catch (error) {
+ refreshErrors.push(getApiErrorMessage(error, t(tKey('refreshFailed'))));
+ }
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+ try {
+ await refreshImageMapPoints();
+ } catch (error) {
+ refreshErrors.push(getApiErrorMessage(error, t(tKey('refreshFailed'))));
+ }
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+ if (refreshErrors.length > 0) {
+ refreshError = refreshErrors.join('\n');
+ }
+ }
+ if (isMounted.current && isAccountScopeCurrent(owner)) {
+ setLatest({ kind: 'result', owner, value, refreshError });
+ }
+ } catch (error) {
+ if (isMounted.current && isAccountScopeCurrent(owner)) {
+ setLatest({
+ kind: 'error',
+ owner,
+ operation,
+ message: getApiErrorMessage(error, t(tKey('executeFailed'))),
+ isConflict: error instanceof ApiError && error.status === 409,
+ });
+ }
+ } finally {
+ executing.current = false;
+ if (isMounted.current) {
+ setIsExecuting(false);
+ }
+ }
+ }, [operation, preview, queryClient, t]);
+
+ const isCurrentPreview =
+ preview.kind === 'ready' &&
+ operation !== null &&
+ preview.value.operation === operation &&
+ isAccountScopeCurrent(preview.owner);
+ const isPreviewLoading = preview.kind === 'loading' && isAccountScopeCurrent(preview.owner);
+ const isBusy = isExecuting || isPreviewLoading;
+ const visibleLatest = latest && isAccountScopeCurrent(latest.owner) ? latest : null;
+
+ const renderPreview = useCallback(() => {
+ if (preview.kind === 'idle' || operation === null) {
+ return null;
+ }
+ const owner = preview.owner;
+ if (!isAccountScopeCurrent(owner)) {
+ return (
+ <Stack gap="2">
+ <Text>{t(tKey('accountChanged'))}</Text>
+ <Button alignSelf="start" variant="outline" onClick={retryPreview}>
+ {t(tKey('retryPreview'))}
+ </Button>
+ </Stack>
+ );
+ }
+ if (preview.kind === 'loading') {
+ return (
+ <Text aria-live="polite" role="status">
+ {t(tKey('previewLoading'))}
+ </Text>
+ );
+ }
+ if (preview.kind === 'error') {
+ return (
+ <Stack gap="2">
+ <Text color="fg.error" role="alert">
+ {preview.message}
+ </Text>
+ <Button alignSelf="start" variant="outline" onClick={retryPreview}>
+ {t(tKey('retryPreview'))}
+ </Button>
+ </Stack>
+ );
+ }
+
+ return (
+ <Stack gap="2">
+ <Text>
+ {t(tKey('previewSummary'), {
+ affected: preview.value.affected_count,
+ examined: preview.value.examined_count,
+ errors: preview.value.error_count,
+ skipped: preview.value.skipped_count,
+ })}
+ </Text>
+ {preview.value.archive_path ? (
+ <Text overflowWrap="anywhere">
+ {t(tKey('archiveLocation'))}: {preview.value.archive_path}
+ </Text>
+ ) : null}
+ {(preview.value.errors?.length ?? 0) > 0 ? (
+ <Text color="fg.warning" role="status" whiteSpace="pre-wrap">
+ {preview.value.errors?.join('\n')}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+ }, [operation, preview, retryPreview, t]);
+
+ const confirmationBody = useMemo(
+ () => createElement(GalleryMaintenanceConfirmBody, { isExecuting, operation, renderPreview }),
+ [isExecuting, operation, renderPreview]
+ );
+
+ return (
+ <Stack gap="0">
+ <Text as="h3" fontSize="lg" fontWeight="600" pb="1">
+ {t(tKey('heading'))}
+ </Text>
+ {Object.entries(ACTIONS).map(([operationId, action]) => {
+ const actionOperation = operationId as GalleryMaintenanceOperation;
+ return (
+ <Box key={actionOperation} py="4" borderBottomWidth="1px" borderColor="border.subtle">
+ <Flex align={ROW_ALIGN} direction={ROW_DIRECTION} gap="3">
+ <Stack flex="1" gap="1">
+ <Text fontSize="lg" fontWeight="500">
+ {t(tKey(action.label))}
+ </Text>
+ <Text color="fg.muted" fontSize="md">
+ {t(tKey(action.description))}
+ </Text>
+ </Stack>
+ <Button
+ disabled={isBusy}
+ flexShrink={0}
+ size="lg"
+ variant="outline"
+ onClick={previewHandlers[actionOperation]}
+ >
+ {t(tKey(action.label))}
+ </Button>
+ </Flex>
+ </Box>
+ );
+ })}
+ {visibleLatest ? <LatestOutcomeView outcome={visibleLatest} retryPreview={startPreview} /> : null}
+ {isExecuting && operation === null ? (
+ <Text aria-live="polite" color="fg.muted" role="status" py="3">
+ {t(tKey('executionRunning'))}
+ </Text>
+ ) : null}
+ <ConfirmDialog
+ body={confirmationBody}
+ confirmLabel={operation ? t(tKey(ACTIONS[operation].confirmLabel)) : t(tKey('proceed'))}
+ isConfirmDisabled={!isCurrentPreview}
+ isDestructive
+ isOpen={operation !== null}
+ title={operation ? t(tKey(ACTIONS[operation].title)) : ''}
+ onClose={closeDialog}
+ onConfirm={execute}
+ />
+ </Stack>
+ );
+};
+
+const GalleryMaintenanceConfirmBody = ({
+ isExecuting,
+ operation,
+ renderPreview,
+}: {
+ isExecuting: boolean;
+ operation: GalleryMaintenanceOperation | null;
+ renderPreview: () => ReactNode;
+}) => {
+ const { t } = useTranslation();
+
+ return (
+ <Stack gap="3">
+ <Text>{operation ? t(tKey(ACTIONS[operation].description)) : ''}</Text>
+ <Text color="fg.muted">{t(tKey('installationScope'))}</Text>
+ {operation === 'remove_missing' ? <Text color="fg.muted">{t(tKey('removeMissingConsequence'))}</Text> : null}
+ {isExecuting ? (
+ <Text aria-live="polite" role="status">
+ {t(tKey('executionRunning'))}
+ </Text>
+ ) : (
+ renderPreview()
+ )}
+ </Stack>
+ );
+};
+
+const LatestOutcomeView = ({
+ outcome,
+ retryPreview,
+}: {
+ outcome: LatestOutcome;
+ retryPreview: (operation: GalleryMaintenanceOperation) => void;
+}) => {
+ const { t } = useTranslation();
+ const retryOperation = outcome.kind === 'error' ? outcome.operation : null;
+ const handleRetryPreview = useCallback(() => {
+ if (retryOperation !== null) {
+ retryPreview(retryOperation);
+ }
+ }, [retryOperation, retryPreview]);
+
+ if (outcome.kind === 'error') {
+ return (
+ <Stack data-testid="gallery-maintenance-result" gap="2" py="4" role="status">
+ <Text fontWeight="600">{t(tKey(outcome.isConflict ? 'conflict' : 'operationFailed'))}</Text>
+ <Text color="fg.error">{outcome.message}</Text>
+ {outcome.isConflict ? (
+ <Button alignSelf="start" variant="outline" onClick={handleRetryPreview}>
+ {t(tKey('reviewCurrentItems'))}
+ </Button>
+ ) : null}
+ </Stack>
+ );
+ }
+
+ const { value } = outcome;
+ return (
+ <Stack data-testid="gallery-maintenance-result" gap="2" py="4" role="status">
+ <Text fontWeight="600">{t(tKey(value.status))}</Text>
+ <Text>
+ {t(tKey('resultSummary'), {
+ examined: value.examined_count,
+ failed: value.failed_count,
+ imagesArchived: value.images_archived,
+ recordsRemoved: value.records_removed,
+ skipped: value.skipped_count,
+ thumbnailsArchived: value.thumbnails_archived,
+ thumbnailsRegenerated: value.thumbnails_regenerated,
+ })}
+ </Text>
+ {value.archive_path ? (
+ <Text overflowWrap="anywhere">
+ {t(tKey('archiveLocation'))}: {value.archive_path}
+ </Text>
+ ) : null}
+ {value.backup_path ? (
+ <Text overflowWrap="anywhere">
+ {t(tKey('backupLocation'))}: {value.backup_path}
+ </Text>
+ ) : null}
+ {(value.errors?.length ?? 0) > 0 ? (
+ <Text color="fg.warning" whiteSpace="pre-wrap">
+ {value.errors?.join('\n')}
+ </Text>
+ ) : null}
+ {outcome.refreshError ? <Text color="fg.warning">{outcome.refreshError}</Text> : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.visual.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.visual.browser.test.tsx
new file mode 100644
index 0000000000..4928e3c4dc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.visual.browser.test.tsx
@@ -0,0 +1,172 @@
+import type * as HttpModule from '@platform/transport/http';
+
+import { Box, ChakraProvider } from '@chakra-ui/react';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { applyThemeToRoot } from '@platform/ui/theme/applyTheme';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({ apiFetchJson: vi.fn() }));
+
+vi.mock('@platform/transport/http', async (importOriginal) => ({
+ ...(await importOriginal<typeof HttpModule>()),
+ apiFetchJson: (...args: unknown[]) => mocks.apiFetchJson(...args),
+}));
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+});
+
+const preview = (operation: string) => ({
+ operation,
+ fingerprint: 'a'.repeat(64),
+ examined_count: 42,
+ affected_count: 7,
+ skipped_count: 1,
+ error_count: 0,
+ errors: [],
+ archive_path: '/var/lib/invokeai/gallery_archive/2026-10-07/run-01',
+});
+
+const settleDialogMotion = () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 250);
+ });
+
+let host: HTMLDivElement | undefined;
+let root: Root | undefined;
+let queryClient: QueryClient | undefined;
+
+const renderSettings = async (width: number, height: number): Promise<void> => {
+ await page.viewport(width, height);
+ host = document.createElement('div');
+ host.style.cssText = 'box-sizing:border-box;min-height:700px;padding:24px;width:100%;';
+ document.body.append(host);
+ root = createRoot(host);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { GalleryMaintenance } = await import('./GalleryMaintenance');
+ await act(() => {
+ root!.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <QueryClientProvider client={queryClient!}>
+ <Box bg="bg.subtle" p="4">
+ <GalleryMaintenance />
+ </Box>
+ </QueryClientProvider>
+ </I18nextProvider>
+ </ChakraProvider>
+ );
+ });
+};
+
+beforeEach(() => {
+ accountLifecycle.activate('gallery-maintenance-visual', ':user:gallery-maintenance-visual');
+ applyThemeToRoot('light');
+ mocks.apiFetchJson.mockReset().mockImplementation((path: string, init: RequestInit) => {
+ const body = JSON.parse(String(init.body)) as { operation: string };
+ return Promise.resolve(preview(body.operation));
+ });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ queryClient?.clear();
+ host?.remove();
+ accountLifecycle.invalidate();
+ applyThemeToRoot('classic');
+ root = undefined;
+ queryClient = undefined;
+ host = undefined;
+});
+
+describe('Gallery maintenance visual evidence', () => {
+ it('shows localized described rows and each destructive confirmation in the light theme', async () => {
+ await renderSettings(1280, 900);
+ await expect.element(page.getByRole('heading', { name: 'Gallery maintenance' })).toBeVisible();
+ await expect
+ .element(
+ page.getByText(
+ 'Remove gallery entries whose original image files are missing. Remaining thumbnails are moved to the archive.',
+ { exact: true }
+ )
+ )
+ .toBeVisible();
+ await page.screenshot({ path: '../../../artifacts/gallery-maintenance/settings-light-wide.png' });
+
+ for (const [label, title, confirm] of [
+ ['Remove records for missing images', 'Remove records for missing images?', 'Remove missing image records'],
+ ['Archive untracked files', 'Archive untracked image files?', 'Archive untracked files'],
+ ['Regenerate missing thumbnails', 'Regenerate missing thumbnails?', 'Regenerate thumbnails'],
+ ]) {
+ await page.getByRole('button', { name: label, exact: true }).click();
+ const dialog = page.getByRole('alertdialog');
+ await expect.poll(() => dialog.element().textContent).toContain(title);
+ await expect.poll(() => dialog.element().textContent).toContain('7 affected');
+ await expect
+ .poll(() => dialog.element().textContent)
+ .toContain('/var/lib/invokeai/gallery_archive/2026-10-07/run-01');
+ const confirmButton = page.getByRole('button', { name: confirm, exact: true });
+ await expect.element(confirmButton).toBeVisible();
+ await settleDialogMotion();
+ await page.screenshot({
+ path: `../../../artifacts/gallery-maintenance/dialog-${confirm.toLowerCase().replaceAll(' ', '-')}-light.png`,
+ });
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect.element(page.getByRole('alertdialog')).not.toBeInTheDocument();
+ }
+ });
+
+ it('shows a narrow dark-theme layout and a destructive confirmation', async () => {
+ applyThemeToRoot('ultradark');
+ await renderSettings(520, 800);
+ await page.screenshot({ path: '../../../artifacts/gallery-maintenance/settings-dark-narrow.png' });
+ await page.getByRole('button', { name: 'Remove records for missing images', exact: true }).click();
+ await settleDialogMotion();
+ await expect
+ .poll(() => page.getByRole('alertdialog').element().textContent)
+ .toContain('This maintenance scans images across all accounts');
+ await page.screenshot({ path: '../../../artifacts/gallery-maintenance/dialog-dark-narrow.png' });
+ });
+
+ it('captures preview loading and recovery error states', async () => {
+ let resolvePreview!: (value: ReturnType<typeof preview>) => void;
+ mocks.apiFetchJson
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolvePreview = resolve;
+ })
+ )
+ .mockRejectedValueOnce(new Error('The preview could not read one image folder.'));
+ await renderSettings(900, 800);
+ await page.getByRole('button', { name: 'Remove records for missing images', exact: true }).click();
+ await expect.poll(() => page.getByRole('status').element().textContent).toContain('Scanning for affected images');
+ await settleDialogMotion();
+ await page.screenshot({ path: '../../../artifacts/gallery-maintenance/preview-loading.png' });
+ await act(async () => {
+ resolvePreview(preview('remove_missing'));
+ await Promise.resolve();
+ });
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect.element(page.getByRole('alertdialog')).not.toBeInTheDocument();
+
+ await page.getByRole('button', { name: 'Archive untracked files', exact: true }).click();
+ await expect
+ .poll(() => page.getByRole('alert').element().textContent)
+ .toContain('The preview could not read one image folder');
+ await settleDialogMotion();
+ await page.screenshot({ path: '../../../artifacts/gallery-maintenance/preview-error-retry.png' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
index ff3e789efd..4195cf318f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
@@ -165,22 +165,31 @@ it.each([
// A closed menu stays in the DOM until its own exit animation ends.
const openMenu = () => document.querySelector('[role="menu"][data-state="open"]');
-/** Choose a menu's rename item, then dismiss the dialog, which is left animating out. */
+/** Choose a menu's rename item, then hold its real exit animation while a successor opens. */
const renameThenDismiss = async (id: string) => {
await act(() => openSurface({ anchor, id, kind: 'menu' }));
await act(() => page.getByRole('menuitem', { name: 'Rename layer', exact: true }).click());
await expect.element(page.getByRole('dialog', { name: 'Rename layer' })).toBeVisible();
- const dialog = document.querySelector('[role="dialog"]')!;
+ const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;
+ await Promise.all(dialog.getAnimations().map((animation) => animation.finished));
+ // Driver round trips can outlast the exit animation on CI; hold it before sending Escape.
+ dialog.style.animationPlayState = 'paused';
await act(() => userEvent.keyboard('{Escape}'));
expect(dialog.isConnected).toBe(true);
expect(dialog).toHaveAttribute('data-state', 'closed');
+ const animations = dialog.getAnimations();
+ expect(animations).not.toHaveLength(0);
+ for (const animation of animations) {
+ expect(animation.playState).toBe('paused');
+ }
return dialog;
};
it('drops a layer rename still animating out when another layer opens its menu', async () => {
- await renameThenDismiss('layer');
+ const dialog = await renameThenDismiss('layer');
await act(() => openSurface({ anchor: { ...anchor }, id: 'child', kind: 'menu' }));
await expect.poll(openMenu).not.toBeNull();
+ expect(dialog.isConnected).toBe(false);
mocks.layerMenuRender.mockClear();
await act(() => userEvent.keyboard('{Escape}'));
@@ -195,6 +204,8 @@ it('opens a group menu requested while its rename animates out, and keeps it onc
await act(() => openSurface({ anchor: { ...anchor }, id: 'group', kind: 'menu' }));
await expect.poll(openMenu).not.toBeNull();
+ expect(dialog.isConnected).toBe(true);
+ dialog.style.removeProperty('animation-play-state');
await expect.poll(() => dialog.isConnected).toBe(false);
expect(openMenu()).not.toBeNull();
diff --git a/invokeai/frontend/webv2/tsconfig.json b/invokeai/frontend/webv2/tsconfig.json
index 2c88a1a3b9..5fcd5f6c24 100644
--- a/invokeai/frontend/webv2/tsconfig.json
+++ b/invokeai/frontend/webv2/tsconfig.json
@@ -22,6 +22,7 @@
"@assets/*": ["./src/assets/*"],
"@app": ["./src/app"],
"@app/*": ["./src/app/*"],
+ "@api/*": ["../api/*"],
"@features": ["./src/features"],
"@features/*": ["./src/features/*"],
"@platform": ["./src/platform"],
diff --git a/invokeai/frontend/webv2/vitest.browser.config.mts b/invokeai/frontend/webv2/vitest.browser.config.mts
index 1cc5ab77c0..ade9c52e5a 100644
--- a/invokeai/frontend/webv2/vitest.browser.config.mts
+++ b/invokeai/frontend/webv2/vitest.browser.config.mts
@@ -1,3 +1,4 @@
+import type { BrowserContext, Route } from 'playwright';
import type { BrowserCommand } from 'vitest/node';
import { playwright } from '@vitest/browser-playwright';
@@ -35,6 +36,64 @@ const imeCompose: BrowserCommand<[steps: readonly { kind: 'commit' | 'compose';
}
};
+type ThumbnailRouteState = {
+ handler: (route: Route) => Promise<void>;
+ pattern: string;
+ statuses: number[];
+ urls: string[];
+};
+
+const thumbnailRoutes = new Map<string, ThumbnailRouteState>();
+
+const stopThumbnailRoute = async (context: BrowserContext, sessionId: string) => {
+ const state = thumbnailRoutes.get(sessionId);
+ if (state) {
+ await context.unroute(state.pattern, state.handler);
+ thumbnailRoutes.delete(sessionId);
+ }
+};
+
+const startThumbnailRoute: BrowserCommand<[pathname: string]> = async ({ context, sessionId }, pathname) => {
+ await stopThumbnailRoute(context, sessionId);
+ const path = new URL(pathname, 'http://localhost').pathname;
+ const pattern = `**${path}*`;
+ const state: ThumbnailRouteState = {
+ handler: async (route) => {
+ if (new URL(route.request().url()).pathname !== path) {
+ await route.continue();
+ return;
+ }
+
+ state.urls.push(route.request().url());
+ const status = state.urls.length === 1 ? 404 : 200;
+ state.statuses.push(status);
+ if (status === 404) {
+ await route.fulfill({ body: 'thumbnail missing', contentType: 'text/plain', status });
+ } else {
+ await route.fulfill({
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#4ade80"/></svg>',
+ contentType: 'image/svg+xml',
+ status,
+ });
+ }
+ },
+ pattern,
+ statuses: [],
+ urls: [],
+ };
+ thumbnailRoutes.set(sessionId, state);
+ await context.route(pattern, state.handler);
+};
+
+const getThumbnailRequests: BrowserCommand<[], { statuses: number[]; urls: string[] }> = ({ sessionId }) => {
+ const state = thumbnailRoutes.get(sessionId);
+ return { statuses: state?.statuses ?? [], urls: state?.urls ?? [] };
+};
+
+const stopThumbnailRouteCommand: BrowserCommand<[]> = async ({ context, sessionId }) => {
+ await stopThumbnailRoute(context, sessionId);
+};
+
export default mergeConfig(
viteConfig,
defineConfig({
@@ -57,7 +116,13 @@ export default mergeConfig(
},
test: {
browser: {
- commands: { imeCompose, resetBrowserPointer },
+ commands: {
+ getThumbnailRequests,
+ imeCompose,
+ resetBrowserPointer,
+ startThumbnailRoute,
+ stopThumbnailRoute: stopThumbnailRouteCommand,
+ },
enabled: true,
headless: true,
instances: [{ browser: 'chromium' }],
diff --git a/scripts/gallery_maintenance.py b/scripts/gallery_maintenance.py
deleted file mode 100755
index 71aed88c92..0000000000
--- a/scripts/gallery_maintenance.py
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/usr/bin/env python3
-"""
-gallery_maintenance.py
-
-Remove orphan images from the gallery directory.
-Remove orphan database entries for images that no longer exist in the gallery directory.
-Regenerate missing thumbnail images.
-"""
-
-from invokeai.backend.util.gallery_maintenance import main
-
-main()
diff --git a/tests/app/routers/test_gallery_maintenance.py b/tests/app/routers/test_gallery_maintenance.py
new file mode 100644
index 0000000000..38cef480bc
--- /dev/null
+++ b/tests/app/routers/test_gallery_maintenance.py
@@ -0,0 +1,448 @@
+import asyncio
+import os
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from threading import Event, Lock
+from typing import Any
+from unittest.mock import Mock
+
+import pytest
+from fastapi.testclient import TestClient
+
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api.routers import gallery_maintenance, image_map
+from invokeai.app.api_app import app
+from invokeai.app.services.auth.token_service import TokenData
+from invokeai.app.services.gallery_maintenance.gallery_maintenance_common import (
+ GalleryMaintenanceError,
+ GalleryMaintenancePreviewChanged,
+)
+from invokeai.app.services.image_moves.image_moves_default import ImageMoveQueueActive, ImageMoveService
+from invokeai.app.services.invoker import Invoker
+
+
+def test_gallery_maintenance_openapi_contract() -> None:
+ paths = app.openapi()["paths"]
+
+ expected_operations = {
+ "/api/v1/app/gallery/maintenance/preview": "preview_gallery_maintenance",
+ "/api/v1/app/gallery/maintenance/remove-missing": "remove_missing_images",
+ "/api/v1/app/gallery/maintenance/archive-untracked": "archive_untracked_images",
+ "/api/v1/app/gallery/maintenance/regenerate-thumbnails": "regenerate_missing_thumbnails",
+ }
+
+ for path, operation_id in expected_operations.items():
+ operation = paths[path]["post"]
+ assert operation["operationId"] == operation_id
+ assert operation["security"] == [{"HTTPBearer": []}]
+ assert {"401", "403", "409", "500", "503"}.issubset(operation["responses"])
+
+
[email protected](scope="module")
+def client(invokeai_root_dir: Path) -> TestClient:
+ os.environ["INVOKEAI_ROOT"] = invokeai_root_dir.as_posix()
+ return TestClient(app)
+
+
+class MockApiDependencies(ApiDependencies):
+ invoker: Invoker
+
+ def __init__(self, invoker: Invoker) -> None:
+ self.invoker = invoker
+
+
+def _patch_dependencies(monkeypatch: Any, mock_invoker: Invoker) -> Mock:
+ maintenance_service = Mock()
+ mock_invoker.services.gallery_maintenance = maintenance_service
+ dependencies = MockApiDependencies(mock_invoker)
+ monkeypatch.setattr(gallery_maintenance, "ApiDependencies", dependencies)
+ monkeypatch.setattr(image_map, "ApiDependencies", dependencies)
+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", dependencies)
+ monkeypatch.setattr(mock_invoker.services.configuration, "multiuser", False)
+ return maintenance_service
+
+
+def test_preview_and_execute_wait_for_service_results(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ preview = {
+ "operation": "remove_missing",
+ "fingerprint": "a" * 64,
+ "examined_count": 8,
+ "affected_count": 2,
+ "skipped_count": 0,
+ "error_count": 0,
+ "errors": [],
+ "archive_path": "/outputs/images/archive/run-1",
+ }
+ result = {
+ "operation": "remove_missing",
+ "status": "partial",
+ "examined_count": 8,
+ "skipped_count": 0,
+ "failed_count": 1,
+ "records_removed": 2,
+ "images_archived": 0,
+ "thumbnails_archived": 2,
+ "thumbnails_regenerated": 0,
+ "archive_path": "/outputs/images/archive/run-1",
+ "backup_path": "/outputs/images/archive/run-1/database.sqlite3",
+ "errors": ["Some image records were removed, but thumbnail archival failed."],
+ }
+ service.preview.return_value = preview
+ service.execute.return_value = result
+
+ preview_response = client.post("/api/v1/app/gallery/maintenance/preview", json={"operation": "remove_missing"})
+ assert preview_response.status_code == 200
+ assert preview_response.json() == preview
+ service.execute.assert_not_called()
+
+ execute_response = client.post("/api/v1/app/gallery/maintenance/remove-missing", json={"fingerprint": "a" * 64})
+
+ assert execute_response.status_code == 200
+ assert execute_response.json() == result
+ service.preview.assert_called_once_with("remove_missing")
+ service.execute.assert_called_once_with("remove_missing", "a" * 64)
+
+
+def test_multiuser_admin_can_preview(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ monkeypatch.setattr(mock_invoker.services.configuration, "multiuser", True)
+ monkeypatch.setattr(
+ "invokeai.app.api.auth_dependencies.verify_token",
+ lambda _: TokenData(user_id="admin-1", email="[email protected]", is_admin=True),
+ )
+ monkeypatch.setattr(
+ mock_invoker.services.users,
+ "get",
+ Mock(
+ return_value=Mock(
+ user_id="admin-1", email="[email protected]", is_admin=True, is_active=True, token_epoch=0
+ )
+ ),
+ )
+ service.preview.return_value = {
+ "operation": "remove_missing",
+ "fingerprint": "d" * 64,
+ "examined_count": 1,
+ "affected_count": 0,
+ "skipped_count": 0,
+ "error_count": 0,
+ "errors": [],
+ "archive_path": None,
+ }
+ result = {
+ "operation": "remove_missing",
+ "status": "no_op",
+ "examined_count": 1,
+ "skipped_count": 0,
+ "failed_count": 0,
+ "records_removed": 0,
+ "images_archived": 0,
+ "thumbnails_archived": 0,
+ "thumbnails_regenerated": 0,
+ "archive_path": None,
+ "backup_path": None,
+ "errors": [],
+ }
+ service.execute.return_value = result
+
+ response = client.post(
+ "/api/v1/app/gallery/maintenance/preview",
+ json={"operation": "remove_missing"},
+ headers={"Authorization": "Bearer admin-token"},
+ )
+ execute_response = client.post(
+ "/api/v1/app/gallery/maintenance/remove-missing",
+ json={"fingerprint": "d" * 64},
+ headers={"Authorization": "Bearer admin-token"},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["fingerprint"] == "d" * 64
+ assert execute_response.status_code == 200
+ assert execute_response.json() == result
+ service.preview.assert_called_once_with("remove_missing")
+ service.execute.assert_called_once_with("remove_missing", "d" * 64)
+
+
+def test_blocking_execute_returns_only_after_completion_while_async_route_responds(
+ monkeypatch: Any, mock_invoker: Invoker
+) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ mock_invoker.services.configuration.image_index_enabled = False
+ started = Event()
+ finish = Event()
+ result = {
+ "operation": "regenerate_thumbnails",
+ "status": "completed",
+ "examined_count": 1,
+ "skipped_count": 0,
+ "failed_count": 0,
+ "records_removed": 0,
+ "images_archived": 0,
+ "thumbnails_archived": 0,
+ "thumbnails_regenerated": 1,
+ "archive_path": None,
+ "backup_path": None,
+ "errors": [],
+ }
+
+ def wait_for_completion(operation: str, fingerprint: str) -> dict[str, Any]:
+ started.set()
+ if not finish.wait(timeout=10):
+ raise TimeoutError("test did not release gallery maintenance")
+ return result
+
+ service.execute.side_effect = wait_for_completion
+
+ from contextlib import asynccontextmanager
+
+ @asynccontextmanager
+ async def lifespanless_app(_app):
+ yield
+
+ monkeypatch.setattr(app.router, "lifespan_context", lifespanless_app)
+ with TestClient(app) as concurrent_client:
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ execute_future = executor.submit(
+ concurrent_client.post,
+ "/api/v1/app/gallery/maintenance/regenerate-thumbnails",
+ json={"fingerprint": "e" * 64},
+ )
+ assert started.wait(timeout=5)
+
+ async_response = concurrent_client.get("/api/v1/image_map/points")
+
+ assert async_response.status_code == 200
+ assert async_response.json()["state"] == "disabled"
+ assert not execute_future.done()
+ finish.set()
+ execute_response = execute_future.result(timeout=5)
+
+ assert execute_response.status_code == 200
+ assert execute_response.json() == result
+
+
+def test_disconnected_execute_keeps_reservation_until_completion_without_retry(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ """An abandoned HTTP response must not release the operation's image-storage reservation."""
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ image_moves = ImageMoveService(db=Mock(), image_files=Mock(), config=Mock(), logger=Mock())
+ image_moves._invoker = mock_invoker
+ monkeypatch.setattr(image_moves, "_get_active_job_id", lambda: None)
+ monkeypatch.setattr(image_moves, "_assert_no_active_queue_work", lambda: None)
+ mock_invoker.services.image_moves = image_moves
+ started = Event()
+ finish = Event()
+ started_count = 0
+ started_lock = Lock()
+ result = {
+ "operation": "archive_untracked",
+ "status": "completed",
+ "examined_count": 1,
+ "skipped_count": 0,
+ "failed_count": 0,
+ "records_removed": 0,
+ "images_archived": 1,
+ "thumbnails_archived": 0,
+ "thumbnails_regenerated": 0,
+ "archive_path": "/outputs/images/archive/run-1",
+ "backup_path": "/outputs/images/archive/run-1/database.sqlite3",
+ "errors": [],
+ }
+
+ def execute_with_reservation(operation: str, fingerprint: str) -> dict[str, Any]:
+ nonlocal started_count
+ with image_moves.reserve_gallery_maintenance():
+ with started_lock:
+ started_count += 1
+ is_first_execution = started_count == 1
+ if is_first_execution:
+ started.set()
+ if not finish.wait(timeout=10):
+ raise TimeoutError("test did not release gallery maintenance")
+ return result
+
+ service.execute.side_effect = execute_with_reservation
+
+ from contextlib import asynccontextmanager
+
+ @asynccontextmanager
+ async def lifespanless_app(_app):
+ yield
+
+ monkeypatch.setattr(app.router, "lifespan_context", lifespanless_app)
+
+ async def request(disconnected: bool) -> list[dict[str, Any]]:
+ request_sent = False
+ messages: list[dict[str, Any]] = []
+
+ async def receive() -> dict[str, Any]:
+ nonlocal request_sent
+ if not request_sent:
+ request_sent = True
+ return {
+ "type": "http.request",
+ "body": b'{"fingerprint":"' + b"f" * 64 + b'"}',
+ "more_body": False,
+ }
+ return {"type": "http.disconnect"}
+
+ async def send(message: dict[str, Any]) -> None:
+ if disconnected:
+ raise OSError("client disconnected before receiving the response")
+ messages.append(message)
+
+ scope = {
+ "type": "http",
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
+ "http_version": "1.1",
+ "method": "POST",
+ "scheme": "http",
+ "path": "/api/v1/app/gallery/maintenance/archive-untracked",
+ "raw_path": b"/api/v1/app/gallery/maintenance/archive-untracked",
+ "query_string": b"",
+ "root_path": "",
+ "headers": [(b"host", b"testserver"), (b"content-type", b"application/json")],
+ "client": ("127.0.0.1", 12345),
+ "server": ("testserver", 80),
+ }
+ await app(scope, receive, send)
+ return messages
+
+ try:
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ abandoned_future = executor.submit(asyncio.run, request(True))
+ assert started.wait(timeout=5)
+
+ excluded_response = client.post(
+ "/api/v1/app/gallery/maintenance/archive-untracked", json={"fingerprint": "f" * 64}
+ )
+
+ assert excluded_response.status_code == 409
+ assert started_count == 1
+ assert not abandoned_future.done()
+
+ finish.set()
+ with pytest.raises(OSError, match="client disconnected"):
+ abandoned_future.result(timeout=5)
+
+ assert started_count == 1
+ finally:
+ finish.set()
+ image_moves.stop()
+
+
+def test_non_admin_cannot_preview_or_execute(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ monkeypatch.setattr(mock_invoker.services.configuration, "multiuser", True)
+ monkeypatch.setattr(
+ "invokeai.app.api.auth_dependencies.verify_token",
+ lambda _: TokenData(user_id="user-1", email="[email protected]", is_admin=False),
+ )
+ monkeypatch.setattr(
+ mock_invoker.services.users,
+ "get",
+ Mock(
+ return_value=Mock(user_id="user-1", email="[email protected]", is_admin=False, is_active=True, token_epoch=0)
+ ),
+ )
+
+ headers = {"Authorization": "Bearer regular-user-token"}
+ preview_response = client.post(
+ "/api/v1/app/gallery/maintenance/preview",
+ json={"operation": "remove_missing"},
+ headers=headers,
+ )
+ execute_response = client.post(
+ "/api/v1/app/gallery/maintenance/remove-missing", json={"fingerprint": "b" * 64}, headers=headers
+ )
+
+ assert preview_response.status_code == 403
+ assert execute_response.status_code == 403
+ service.preview.assert_not_called()
+ service.execute.assert_not_called()
+
+
+def test_multiuser_unauthenticated_preview_is_rejected(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ monkeypatch.setattr(mock_invoker.services.configuration, "multiuser", True)
+
+ response = client.post("/api/v1/app/gallery/maintenance/preview", json={"operation": "remove_missing"})
+
+ assert response.status_code == 401
+ service.preview.assert_not_called()
+
+
+def test_unavailable_service_returns_503(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ _patch_dependencies(monkeypatch, mock_invoker)
+ mock_invoker.services.gallery_maintenance = None
+
+ response = client.post("/api/v1/app/gallery/maintenance/preview", json={"operation": "remove_missing"})
+
+ assert response.status_code == 503
+ assert response.json() == {"detail": "Gallery maintenance unavailable"}
+
+
+def test_invalid_request_is_rejected_before_service_call(
+ monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+
+ preview_response = client.post("/api/v1/app/gallery/maintenance/preview", json={"operation": "rebuild_everything"})
+ execute_response = client.post(
+ "/api/v1/app/gallery/maintenance/regenerate-thumbnails", json={"fingerprint": "not-a-fingerprint"}
+ )
+
+ assert preview_response.status_code == 422
+ assert execute_response.status_code == 422
+ service.preview.assert_not_called()
+ service.execute.assert_not_called()
+
+
+ "failure",
+ [
+ ImageMoveQueueActive("internal queue detail"),
+ GalleryMaintenancePreviewChanged("internal fingerprint detail"),
+ ],
+)
+def test_execute_conflicts_are_sanitized(
+ failure: Exception, monkeypatch: Any, mock_invoker: Invoker, client: TestClient
+) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ service.execute.side_effect = failure
+
+ response = client.post("/api/v1/app/gallery/maintenance/remove-missing", json={"fingerprint": "c" * 64})
+
+ assert response.status_code == 409
+ assert "internal" not in response.text
+ service.execute.assert_called_once_with("remove_missing", "c" * 64)
+
+
+def test_preview_busy_conflict_is_sanitized(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ service.preview.side_effect = ImageMoveQueueActive("private queue state")
+
+ response = client.post("/api/v1/app/gallery/maintenance/preview", json={"operation": "remove_missing"})
+
+ assert response.status_code == 409
+ assert "private queue state" not in response.text
+ service.preview.assert_called_once_with("remove_missing")
+
+
+def test_service_failure_returns_safe_error(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ service = _patch_dependencies(monkeypatch, mock_invoker)
+ service.preview.side_effect = GalleryMaintenanceError("private filesystem path")
+
+ response = client.post("/api/v1/app/gallery/maintenance/preview", json={"operation": "remove_missing"})
+
+ assert response.status_code == 500
+ assert response.json() == {"detail": "Gallery maintenance failed"}
+ assert "private filesystem path" not in response.text
+ service.preview.assert_called_once_with("remove_missing")
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index 7769114a4b..1594e1db7d 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -1841,6 +1841,30 @@ def test_a_new_video_makes_the_projection_stale(mock_invoker: Invoker, client: T
assert client.get("/api/v1/image_map/points").json()["stale"] is True
+def test_deleted_image_is_filtered_from_cached_projection_without_reembedding(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ _seed_embedded_image(mock_invoker, "kept.png")
+ _seed_embedded_image(mock_invoker, "removed.png")
+ _seed_projection(
+ mock_invoker,
+ SYSTEM_USER_ID,
+ imgs("kept.png", "removed.png"),
+ np.array([[0.0, 0.0], [10.0, 10.0]], dtype=np.float32),
+ )
+
+ mock_invoker.services.image_records.delete("removed.png")
+
+ response = client.get("/api/v1/image_map/points")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["stale"] is True
+ assert [point["image_name"] for point in body["points"]] == ["kept.png"]
+ assert image_index_service.embedded_images == []
+ assert image_index_service.projection_requests == [(SYSTEM_USER_ID, True)]
+
+
def test_search_by_video_reference_uses_its_stored_embedding(
image_index_service: FakeImageIndexService, mock_invoker: Invoker, client: TestClient
) -> None:
diff --git a/tests/app/services/gallery_maintenance/test_gallery_maintenance_service.py b/tests/app/services/gallery_maintenance/test_gallery_maintenance_service.py
new file mode 100644
index 0000000000..d33be313a3
--- /dev/null
+++ b/tests/app/services/gallery_maintenance/test_gallery_maintenance_service.py
@@ -0,0 +1,852 @@
+import os
+import shutil
+from contextlib import contextmanager
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage
+from invokeai.app.services.board_records.board_records_common import BoardChanges
+from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.app.services.gallery_maintenance.gallery_maintenance_common import (
+ GalleryMaintenanceError,
+ GalleryMaintenanceOperation,
+ GalleryMaintenancePreviewChanged,
+)
+from invokeai.app.services.gallery_maintenance.gallery_maintenance_default import GalleryMaintenanceService
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
+from invokeai.app.services.image_index.image_index_common import IndexedItem
+from invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlite
+from invokeai.app.services.image_records.image_records_common import (
+ ImageCategory,
+ ImageRecordNotFoundException,
+ ResourceOrigin,
+)
+from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
+from invokeai.app.services.video_records.video_records_sqlite import SqliteVideoRecordStorage
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.fixtures.sqlite_database import create_mock_sqlite_database
+
+
+class _ImageMutationGate:
+ @contextmanager
+ def reserve_gallery_maintenance(self):
+ yield
+
+
+def maintenance(
+ tmp_path: Path,
+) -> tuple[GalleryMaintenanceService, object, SqliteImageRecordStorage, DiskImageFileStorage]:
+ config = InvokeAIAppConfig(use_memory_db=True)
+ config._root = tmp_path
+ logger = InvokeAILogger.get_logger(config=config)
+ db = create_mock_sqlite_database(config, logger)
+ records = SqliteImageRecordStorage(db)
+ files = DiskImageFileStorage(config.outputs_path / "images")
+ invoker = MagicMock()
+ invoker.services.configuration = config
+ invoker.services.logger = MagicMock()
+ invoker.services.database = db
+ invoker.services.image_records = records
+ invoker.services.image_files = files
+ invoker.services.image_index_records = ImageIndexRecordsSqlite(db)
+ invoker.services.video_records = SqliteVideoRecordStorage(db)
+ invoker.services.board_records = SqliteBoardRecordStorage(db)
+ invoker.services.board_image_records = SqliteBoardImageRecordStorage(db)
+ invoker.services.images = MagicMock()
+ invoker.services.image_moves = _ImageMutationGate()
+ files.start(invoker)
+ service = GalleryMaintenanceService()
+ service.start(invoker)
+ return service, db, records, files
+
+
+def _save_image_record(
+ records: SqliteImageRecordStorage,
+ image_name: str,
+ image_subfolder: str = "",
+ *,
+ is_intermediate: bool = False,
+ user_id: str | None = None,
+) -> None:
+ records.save(
+ image_name=image_name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=8,
+ height=8,
+ has_workflow=False,
+ is_intermediate=is_intermediate,
+ image_subfolder=image_subfolder,
+ user_id=user_id,
+ )
+
+
+def _write_png(files: DiskImageFileStorage, image_name: str, subfolder: str = "") -> bytes:
+ path = files.get_path(image_name, image_subfolder=subfolder)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ image = Image.new("RGBA", (8, 8), (17, 23, 42, 101))
+ image.save(path, format="PNG")
+ image.close()
+ return path.read_bytes()
+
+
+def _embedding(invoker_services, kind: str, name: str, model_id: str = "model-a") -> None:
+ invoker_services.image_index_records.upsert_embedding(
+ IndexedItem(kind=kind, name=name), model_id, np.array([0.25, 0.75], dtype=np.float32)
+ )
+
+
+def _embedding_bytes(invoker_services, kind: str, name: str, model_id: str = "model-a") -> bytes:
+ _items, embeddings = invoker_services.image_index_records.get_embeddings(
+ [IndexedItem(kind=kind, name=name)], model_id
+ )
+ return embeddings.tobytes()
+
+
+def test_remove_missing_archives_thumbnail_and_cascades_all_image_relations(maintenance) -> None:
+ service, db, records, files = maintenance
+ invoker = service._invoker
+ _save_image_record(records, "missing.png", "archived/board", is_intermediate=True, user_id="user-a")
+ _save_image_record(records, "kept.png", "live", user_id="user-b")
+ _save_image_record(records, "archived-board-kept.png", "archived/board", user_id="user-a")
+ _write_png(files, "kept.png", "live")
+ _write_png(files, "archived-board-kept.png", "archived/board")
+ thumbnail_path = files.get_path("missing.png", thumbnail=True, image_subfolder="archived/board")
+ thumbnail_path.parent.mkdir(parents=True)
+ thumbnail_path.write_bytes(b"recoverable thumbnail")
+
+ board = invoker.services.board_records.save("Archived board", "user-a")
+ invoker.services.board_records.update(board.board_id, BoardChanges(archived=True))
+ invoker.services.board_image_records.add_image_to_board(board.board_id, "missing.png")
+ invoker.services.board_image_records.add_image_to_board(board.board_id, "archived-board-kept.png")
+ _embedding(invoker.services, "image", "missing.png", "model-a")
+ _embedding(invoker.services, "image", "missing.png", "model-b")
+ _embedding(invoker.services, "image", "kept.png", "model-a")
+ _embedding(invoker.services, "image", "archived-board-kept.png", "model-a")
+ invoker.services.video_records.save(
+ video_name="kept.mp4",
+ video_origin=ResourceOrigin.INTERNAL,
+ video_category=ImageCategory.GENERAL,
+ width=8,
+ height=8,
+ duration=1.0,
+ fps=24.0,
+ has_workflow=False,
+ )
+ _embedding(invoker.services, "video", "kept.mp4", "model-a")
+ kept_image_embedding = _embedding_bytes(invoker.services, "image", "kept.png")
+ kept_video_embedding = _embedding_bytes(invoker.services, "video", "kept.mp4")
+ archived_board_embedding = _embedding_bytes(invoker.services, "image", "archived-board-kept.png")
+
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+ assert preview.affected_count == 1
+ assert records.exists("missing.png")
+ assert thumbnail_path.read_bytes() == b"recoverable thumbnail"
+
+ result = service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert result.records_removed == 1
+ assert result.status == "completed"
+ with pytest.raises(ImageRecordNotFoundException):
+ records.get("missing.png")
+ assert not thumbnail_path.exists()
+ archived_thumbnail = Path(result.archive_path) / "thumbnails" / "archived" / "board" / "missing.webp"
+ assert archived_thumbnail.read_bytes() == b"recoverable thumbnail"
+ with db.transaction() as cursor:
+ assert cursor.execute("SELECT COUNT(*) FROM board_images WHERE image_name='missing.png';").fetchone()[0] == 0
+ assert (
+ cursor.execute("SELECT COUNT(*) FROM image_embeddings WHERE image_name='missing.png';").fetchone()[0] == 0
+ )
+ assert (
+ cursor.execute(
+ "SELECT COUNT(*) FROM image_subfolder_move_items WHERE image_name='missing.png';"
+ ).fetchone()[0]
+ == 0
+ )
+ assert cursor.execute("SELECT COUNT(*) FROM image_embeddings WHERE image_name='kept.png';").fetchone()[0] == 1
+ assert cursor.execute("SELECT COUNT(*) FROM video_embeddings WHERE video_name='kept.mp4';").fetchone()[0] == 1
+ assert IndexedItem(
+ kind="image", name="missing.png"
+ ) not in invoker.services.image_index_records.list_accessible_embedded_items(None, "model-a")
+ assert _embedding_bytes(invoker.services, "image", "kept.png") == kept_image_embedding
+ assert _embedding_bytes(invoker.services, "video", "kept.mp4") == kept_video_embedding
+ assert _embedding_bytes(invoker.services, "image", "archived-board-kept.png") == archived_board_embedding
+ invoker.services.images.notify_deleted.assert_called_once_with("missing.png")
+ assert Path(result.backup_path).is_file()
+
+
+def test_archive_untracked_preserves_nested_paths_and_never_archives_tracked_or_video_files(maintenance) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "tracked.png", "nested/tracked")
+ _embedding(service._invoker.services, "image", "tracked.png")
+ embedding_before = _embedding_bytes(service._invoker.services, "image", "tracked.png")
+ tracked_original = _write_png(files, "tracked.png", "nested/tracked")
+ tracked_thumbnail = files.get_path("tracked.png", thumbnail=True, image_subfolder="nested/tracked")
+ tracked_thumbnail.parent.mkdir(parents=True, exist_ok=True)
+ tracked_thumbnail.write_bytes(b"tracked thumbnail")
+ untracked_original = _write_png(files, "orphan.png", "nested/orphan")
+ untracked_thumbnail = files.get_path("orphan.png", thumbnail=True, image_subfolder="nested/orphan")
+ untracked_thumbnail.parent.mkdir(parents=True, exist_ok=True)
+ untracked_thumbnail.write_bytes(b"matching thumbnail")
+ orphan_thumbnail = files.get_path("thumbnail-only.png", thumbnail=True, image_subfolder="nested/only")
+ orphan_thumbnail.parent.mkdir(parents=True, exist_ok=True)
+ orphan_thumbnail.write_bytes(b"thumbnail only")
+ (files.image_root / "nested" / "orphan" / "not-a-video.png.mp4").write_bytes(b"video")
+
+ preview = service.preview(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED)
+ assert preview.affected_count == 2
+
+ result = service.execute(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED, preview.fingerprint)
+
+ archive_root = Path(result.archive_path)
+ assert result.images_archived == 1
+ assert result.thumbnails_archived == 2
+ assert not files.get_path("orphan.png", image_subfolder="nested/orphan").exists()
+ assert not untracked_thumbnail.exists()
+ assert not orphan_thumbnail.exists()
+ assert files.get_path("tracked.png", image_subfolder="nested/tracked").read_bytes() == tracked_original
+ assert tracked_thumbnail.read_bytes() == b"tracked thumbnail"
+ assert (archive_root / "images" / "nested" / "orphan" / "orphan.png").read_bytes() == untracked_original
+ assert (archive_root / "thumbnails" / "nested" / "orphan" / "orphan.webp").read_bytes() == b"matching thumbnail"
+ assert (archive_root / "thumbnails" / "nested" / "only" / "thumbnail-only.webp").read_bytes() == b"thumbnail only"
+ assert _embedding_bytes(service._invoker.services, "image", "tracked.png") == embedding_before
+
+
+def test_regenerate_missing_thumbnail_is_record_scoped_and_refreshes_cached_size(maintenance) -> None:
+ service, db, records, files = maintenance
+ _save_image_record(records, "missing-thumb.png", "nested")
+ original_bytes = _write_png(files, "missing-thumb.png", "nested")
+ _embedding(service._invoker.services, "image", "missing-thumb.png")
+ embedding_before = _embedding_bytes(service._invoker.services, "image", "missing-thumb.png")
+ records.set_file_size_bytes("missing-thumb.png", 1)
+ _write_png(files, "untracked.png", "nested")
+ _save_image_record(records, "missing-source.png", "nested")
+ existing_thumbnail = files.get_path("missing-source.png", thumbnail=True, image_subfolder="nested")
+ existing_thumbnail.parent.mkdir(parents=True, exist_ok=True)
+ existing_thumbnail.write_bytes(b"existing")
+ _save_image_record(records, "raced-thumb.png", "nested")
+ _write_png(files, "raced-thumb.png", "nested")
+
+ preview = service.preview(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS)
+ assert preview.affected_count == 2
+ assert preview.skipped_count == 1
+
+ original_backup = service._invoker.services.database.backup_to
+
+ def create_thumbnail_during_backup(destination: Path) -> None:
+ original_backup(destination)
+ raced_thumbnail = files.get_path("raced-thumb.png", thumbnail=True, image_subfolder="nested")
+ raced_thumbnail.parent.mkdir(parents=True, exist_ok=True)
+ raced_thumbnail.write_bytes(b"created after preview scan")
+
+ service._invoker.services.database.backup_to = create_thumbnail_during_backup
+
+ result = service.execute(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, preview.fingerprint)
+
+ assert result.thumbnails_regenerated == 1
+ assert result.skipped_count == 2
+ assert result.status == "partial"
+ assert files.get_path("missing-thumb.png", image_subfolder="nested").read_bytes() == original_bytes
+ assert files.get_path("missing-thumb.png", thumbnail=True, image_subfolder="nested").is_file()
+ assert files.get_path("untracked.png", thumbnail=True, image_subfolder="nested").exists() is False
+ assert existing_thumbnail.read_bytes() == b"existing"
+ assert files.get_path("raced-thumb.png", thumbnail=True, image_subfolder="nested").read_bytes() == (
+ b"created after preview scan"
+ )
+ assert records.get("missing-thumb.png").file_size_bytes == files.get_file_size_bytes(
+ "missing-thumb.png", image_subfolder="nested"
+ )
+ assert _embedding_bytes(service._invoker.services, "image", "missing-thumb.png") == embedding_before
+ with db.transaction() as cursor:
+ assert cursor.execute("SELECT COUNT(*) FROM image_embeddings;").fetchone()[0] == 1
+
+
+def test_execute_rejects_changed_preview_without_mutating_newly_untracked_file(maintenance) -> None:
+ service, _db, _records, files = maintenance
+ preview = service.preview(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED)
+ added_bytes = _write_png(files, "arrived-after-preview.png")
+
+ with pytest.raises(GalleryMaintenancePreviewChanged):
+ service.execute(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED, preview.fingerprint)
+
+ assert files.get_path("arrived-after-preview.png").read_bytes() == added_bytes
+
+
+def test_backup_failure_prevents_record_removal_and_thumbnail_archival(maintenance) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "missing.png", "recoverable")
+ thumbnail = files.get_path("missing.png", thumbnail=True, image_subfolder="recoverable")
+ thumbnail.parent.mkdir(parents=True)
+ thumbnail.write_bytes(b"recoverable thumbnail")
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+ service._invoker.services.database.backup_to = MagicMock(side_effect=OSError("disk full"))
+
+ with pytest.raises(GalleryMaintenanceError, match="database backup failed"):
+ service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert records.exists("missing.png")
+ assert thumbnail.read_bytes() == b"recoverable thumbnail"
+ service._invoker.services.images.notify_deleted.assert_not_called()
+
+
+def test_delete_failure_restores_archived_thumbnail_and_reports_failure(maintenance) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "missing.png", "recoverable")
+ thumbnail = files.get_path("missing.png", thumbnail=True, image_subfolder="recoverable")
+ thumbnail.parent.mkdir(parents=True)
+ thumbnail_bytes = b"recoverable thumbnail"
+ thumbnail.write_bytes(thumbnail_bytes)
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+ records.delete_many = MagicMock(side_effect=OSError("database unavailable"))
+
+ result = service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert records.get("missing.png").image_name == "missing.png"
+ assert thumbnail.read_bytes() == thumbnail_bytes
+ assert not (Path(result.archive_path) / "thumbnails" / "recoverable" / "missing.webp").exists()
+ assert result.records_removed == 0
+ assert result.thumbnails_archived == 0
+ assert result.failed_count == 1
+ assert result.status == "failed"
+
+
+def test_thumbnail_eviction_failure_restores_archived_thumbnail(maintenance, monkeypatch) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "missing.png", "recoverable")
+ thumbnail = files.get_path("missing.png", thumbnail=True, image_subfolder="recoverable")
+ thumbnail.parent.mkdir(parents=True)
+ thumbnail_bytes = b"recoverable thumbnail"
+ thumbnail.write_bytes(thumbnail_bytes)
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+
+ def fail_cache_eviction(paths: list[Path]) -> None:
+ assert thumbnail in paths
+ raise OSError("cache eviction failed")
+
+ monkeypatch.setattr(files, "evict_cache_paths", fail_cache_eviction)
+
+ result = service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ archived_thumbnail = Path(result.archive_path) / "thumbnails" / "recoverable" / "missing.webp"
+ assert records.exists("missing.png")
+ assert thumbnail.read_bytes() == thumbnail_bytes
+ assert not archived_thumbnail.exists()
+ assert result.records_removed == 0
+ assert result.thumbnails_archived == 0
+ assert result.failed_count == 1
+ assert result.status == "failed"
+
+
[email protected]("root_name", ["image_root", "thumbnail_root"])
+def test_preview_fails_when_required_storage_root_is_missing(maintenance, root_name: str) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "missing.png", "missing")
+ root = getattr(files, root_name)
+ shutil.rmtree(root) if root_name == "image_root" else root.rmdir()
+
+ with pytest.raises(GalleryMaintenanceError, match="storage"):
+ service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+
+ assert records.exists("missing.png")
+
+
+def test_preview_fails_when_storage_root_cannot_be_scanned(maintenance, monkeypatch: pytest.MonkeyPatch) -> None:
+ service, _db, _records, files = maintenance
+ real_scandir = os.scandir
+
+ def unavailable(path):
+ if not isinstance(path, int) and Path(path) == files.thumbnail_root:
+ raise PermissionError("unreadable thumbnail root")
+ return real_scandir(path)
+
+ monkeypatch.setattr(os, "scandir", unavailable)
+
+ with pytest.raises(GalleryMaintenanceError, match="storage"):
+ service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+
+
+def test_remove_missing_preserves_record_when_same_basename_image_exists_elsewhere(maintenance) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "duplicate.png", "recorded")
+ elsewhere = _write_png(files, "duplicate.png", "actual")
+
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+
+ assert preview.affected_count == 0
+ assert preview.skipped_count == 1
+ result = service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert result.records_removed == 0
+ assert records.exists("duplicate.png")
+ assert files.get_path("duplicate.png", image_subfolder="actual").read_bytes() == elsewhere
+
+
+def test_archive_untracked_executes_only_confirmed_files_with_unchanged_stats(maintenance) -> None:
+ service, _db, _records, files = maintenance
+ confirmed = _write_png(files, "confirmed.png")
+ changed_path = files.get_path("changed.png")
+ changed_path.parent.mkdir(parents=True, exist_ok=True)
+ changed_path.write_bytes(b"before preview")
+ preview = service.preview(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED)
+ original_backup = service._invoker.services.database.backup_to
+
+ def change_storage(destination: Path) -> None:
+ original_backup(destination)
+ changed_path.write_bytes(b"changed after preview")
+ _write_png(files, "arrived.png")
+
+ service._invoker.services.database.backup_to = change_storage
+
+ result = service.execute(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED, preview.fingerprint)
+
+ assert result.images_archived == 1
+ assert not files.get_path("confirmed.png").exists()
+ assert changed_path.read_bytes() == b"changed after preview"
+ assert files.get_path("arrived.png").is_file()
+ archived = Path(result.archive_path) / "images" / "confirmed.png"
+ assert archived.read_bytes() == confirmed
+
+
+def test_remove_missing_counts_committed_deletion_when_followup_check_fails(maintenance) -> None:
+ service, _db, records, _files = maintenance
+ _save_image_record(records, "missing.png")
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+ records.exists = MagicMock(side_effect=OSError("verification unavailable"))
+ service._invoker.services.images.notify_deleted.side_effect = OSError("notification unavailable")
+
+ result = service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert result.records_removed == 1
+ assert result.failed_count == 2
+ assert result.status == "partial"
+
+
+def test_remove_missing_keeps_record_when_original_appears_during_backup(maintenance) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "appeared.png", "during-backup")
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+ original_backup = service._invoker.services.database.backup_to
+
+ def create_original(destination: Path) -> None:
+ original_backup(destination)
+ _write_png(files, "appeared.png", "during-backup")
+
+ service._invoker.services.database.backup_to = create_original
+
+ result = service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert result.records_removed == 0
+ assert result.skipped_count == 1
+ assert records.exists("appeared.png")
+ assert files.get_path("appeared.png", image_subfolder="during-backup").is_file()
+ service._invoker.services.images.notify_deleted.assert_not_called()
+
+
+def test_archive_iterator_failure_returns_partial_result_after_prior_archive(maintenance, monkeypatch) -> None:
+ service, _db, _records, files = maintenance
+ first = _write_png(files, "first.png")
+ second = _write_png(files, "second.png")
+ preview = service.preview(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED)
+ original_stat = service._stat
+ second_stat_calls = 0
+
+ def fail_on_second_execution_stat(path: Path):
+ nonlocal second_stat_calls
+ if path == files.get_path("second.png"):
+ second_stat_calls += 1
+ if second_stat_calls == 2:
+ raise OSError("stat failed during execution")
+ return original_stat(path)
+
+ monkeypatch.setattr(service, "_stat", fail_on_second_execution_stat)
+
+ result = service.execute(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED, preview.fingerprint)
+
+ assert result.images_archived == 1
+ assert result.failed_count == 1
+ assert result.status == "partial"
+ archive_root = Path(result.archive_path) / "images"
+ assert (archive_root / "first.png").read_bytes() == first
+ assert files.get_path("second.png").read_bytes() == second
+
+
+def test_archive_thumbnail_failure_keeps_original_recoverable(maintenance, monkeypatch) -> None:
+ service, _db, _records, files = maintenance
+ original_bytes = _write_png(files, "paired.png", "nested")
+ thumbnail = files.get_path("paired.png", thumbnail=True, image_subfolder="nested")
+ thumbnail.parent.mkdir(parents=True, exist_ok=True)
+ thumbnail_bytes = b"recoverable thumbnail"
+ thumbnail.write_bytes(thumbnail_bytes)
+ preview = service.preview(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED)
+ archive_file = service._archive_file
+
+ def fail_thumbnail(source: Path, destination: Path, expected) -> None:
+ if "thumbnails" in destination.parts:
+ raise OSError("injected thumbnail archive failure")
+ archive_file(source, destination, expected)
+
+ monkeypatch.setattr(service, "_archive_file", fail_thumbnail)
+
+ result = service.execute(GalleryMaintenanceOperation.ARCHIVE_UNTRACKED, preview.fingerprint)
+
+ archive_root = Path(result.archive_path)
+ assert (archive_root / "images" / "nested" / "paired.png").read_bytes() == original_bytes
+ assert thumbnail.read_bytes() == thumbnail_bytes
+ assert result.images_archived == 1
+ assert result.thumbnails_archived == 0
+ assert result.failed_count == 1
+ assert result.status == "partial"
+
+
+def test_archive_collision_never_overwrites_destination(maintenance, tmp_path: Path) -> None:
+ service, _db, _records, _files = maintenance
+ source = tmp_path / "source.png"
+ destination = tmp_path / "archive" / "source.png"
+ source.write_bytes(b"source data")
+ destination.parent.mkdir()
+ destination.write_bytes(b"prior archive data")
+ signature = service._signature(source.lstat())
+
+ with pytest.raises(FileExistsError):
+ service._archive_file(source, destination, signature)
+
+ assert source.read_bytes() == b"source data"
+ assert destination.read_bytes() == b"prior archive data"
+
+
+def test_archive_file_preserves_replacement_after_signature_check(maintenance, tmp_path: Path, monkeypatch) -> None:
+ service, _db, _records, _files = maintenance
+ source = tmp_path / "source.png"
+ replacement = tmp_path / "replacement.png"
+ destination = tmp_path / "archive" / "source.png"
+ original_bytes = b"confirmed source bytes"
+ replacement_bytes = b"concurrent replacement bytes"
+ source.write_bytes(original_bytes)
+ replacement.write_bytes(replacement_bytes)
+ destination.parent.mkdir()
+ expected = service._signature(source.lstat())
+ path_signature = service._path_signature
+ replaced = False
+
+ def replace_after_signature(path: Path):
+ nonlocal replaced
+ signature = path_signature(path)
+ if path == source and not replaced:
+ source.unlink()
+ replacement.replace(source)
+ replaced = True
+ return signature
+
+ monkeypatch.setattr(GalleryMaintenanceService, "_path_signature", staticmethod(replace_after_signature))
+
+ with pytest.raises(OSError, match="changed"):
+ service._archive_file(source, destination, expected)
+
+ assert source.read_bytes() == replacement_bytes
+ assert destination.read_bytes() == original_bytes
+
+
+def test_archive_file_tolerates_ctime_difference_between_path_and_open_file(
+ maintenance, tmp_path: Path, monkeypatch
+) -> None:
+ service, _db, _records, _files = maintenance
+ source = tmp_path / "source.png"
+ destination = tmp_path / "archive" / "source.png"
+ source_bytes = b"confirmed source bytes"
+ source.write_bytes(source_bytes)
+ expected = service._signature(source.lstat())
+ real_fstat = os.fstat
+
+ def fstat_with_different_ctime(descriptor: int):
+ result = real_fstat(descriptor)
+ return SimpleNamespace(
+ st_dev=result.st_dev,
+ st_ino=result.st_ino,
+ st_mode=result.st_mode,
+ st_size=result.st_size,
+ st_mtime_ns=result.st_mtime_ns,
+ st_ctime_ns=result.st_ctime_ns + 1,
+ )
+
+ monkeypatch.setattr(
+ "invokeai.app.services.gallery_maintenance.gallery_maintenance_default.os.fstat", fstat_with_different_ctime
+ )
+
+ service._archive_file(source, destination, expected)
+
+ assert destination.read_bytes() == source_bytes
+ assert not source.exists()
+
+
+def test_preview_rejects_symlinked_record_subfolder(maintenance, tmp_path: Path) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "outside.png", "linked")
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ outside_image = outside / "outside.png"
+ outside_image.write_bytes(b"outside data")
+ try:
+ (files.image_root / "linked").symlink_to(outside, target_is_directory=True)
+ except (NotImplementedError, OSError) as e:
+ pytest.skip(f"directory symlinks are unavailable: {e}")
+
+ with pytest.raises(GalleryMaintenanceError, match="symbolic links"):
+ service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+
+ assert outside_image.read_bytes() == b"outside data"
+
+
+def test_repeated_thumbnail_regeneration_becomes_no_op(maintenance) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "image.png")
+ _write_png(files, "image.png")
+ first_preview = service.preview(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS)
+ service.execute(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, first_preview.fingerprint)
+
+ second_preview = service.preview(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS)
+ second_result = service.execute(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, second_preview.fingerprint)
+
+ assert second_preview.affected_count == 0
+ assert second_result.status == "no_op"
+
+
+def test_regeneration_removes_thumbnail_if_source_changes_during_generation(maintenance, monkeypatch) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "changing.png", "nested")
+ original_path = files.get_path("changing.png", image_subfolder="nested")
+ original_bytes = _write_png(files, "changing.png", "nested")
+ thumbnail = files.get_path("changing.png", thumbnail=True, image_subfolder="nested")
+ preview = service.preview(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS)
+ generate = files.generate_thumbnail_if_missing
+
+ def generate_then_change_source(image_name: str, image_subfolder: str = "") -> bool:
+ created = generate(image_name, image_subfolder=image_subfolder)
+ original_path.write_bytes(b"changed while thumbnail was generated")
+ return created
+
+ monkeypatch.setattr(files, "generate_thumbnail_if_missing", generate_then_change_source)
+
+ result = service.execute(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, preview.fingerprint)
+
+ assert original_bytes != original_path.read_bytes()
+ assert not thumbnail.exists()
+ assert result.thumbnails_regenerated == 0
+ assert result.failed_count == 1
+ assert result.status == "failed"
+
+
+def test_regeneration_removes_thumbnail_if_size_persistence_fails(maintenance, monkeypatch) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "persistence-failure.png", "nested")
+ _write_png(files, "persistence-failure.png", "nested")
+ thumbnail = files.get_path("persistence-failure.png", thumbnail=True, image_subfolder="nested")
+ preview = service.preview(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS)
+ monkeypatch.setattr(records, "set_file_size_bytes", MagicMock(side_effect=OSError("database write failed")))
+
+ result = service.execute(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, preview.fingerprint)
+
+ assert not thumbnail.exists()
+ assert result.thumbnails_regenerated == 0
+ assert result.failed_count == 1
+ assert result.status == "failed"
+
+
+def test_regeneration_cleanup_preserves_replacement_thumbnail(maintenance, monkeypatch) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "replacement.png", "nested")
+ _write_png(files, "replacement.png", "nested")
+ thumbnail = files.get_path("replacement.png", thumbnail=True, image_subfolder="nested")
+ replacement = thumbnail.with_name("replacement-copy.webp")
+ replacement_bytes = b"concurrent thumbnail replacement"
+ preview = service.preview(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS)
+ monkeypatch.setattr(records, "set_file_size_bytes", MagicMock(side_effect=OSError("database write failed")))
+ path_signature = service._path_signature
+ thumbnail_signature_checks = 0
+
+ def replace_after_cleanup_signature(path: Path):
+ nonlocal thumbnail_signature_checks
+ signature = path_signature(path)
+ if path == thumbnail:
+ thumbnail_signature_checks += 1
+ if thumbnail_signature_checks == 2:
+ replacement.write_bytes(replacement_bytes)
+ thumbnail.unlink()
+ replacement.replace(thumbnail)
+ return signature
+
+ monkeypatch.setattr(GalleryMaintenanceService, "_path_signature", staticmethod(replace_after_cleanup_signature))
+
+ result = service.execute(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, preview.fingerprint)
+
+ assert thumbnail_signature_checks == 2
+ assert thumbnail.read_bytes() == replacement_bytes
+ assert result.thumbnails_regenerated == 0
+ assert result.failed_count == 1
+ assert result.status == "failed"
+
+
+def test_result_errors_are_bounded(maintenance) -> None:
+ service, _db, records, files = maintenance
+ for index in range(25):
+ name = f"broken-{index:02}.png"
+ _save_image_record(records, name)
+ path = files.get_path(name)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"not a png")
+ preview = service.preview(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS)
+
+ result = service.execute(GalleryMaintenanceOperation.REGENERATE_THUMBNAILS, preview.fingerprint)
+
+ assert result.failed_count == 25
+ assert len(result.errors) == 20
+
+
+def test_archive_directory_entries_are_synced_before_quarantining_thumbnail(maintenance, monkeypatch) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "missing.png", "recoverable/deep")
+ thumbnail = files.get_path("missing.png", thumbnail=True, image_subfolder="recoverable/deep")
+ thumbnail.parent.mkdir(parents=True, exist_ok=True)
+ thumbnail_bytes = b"recoverable thumbnail"
+ thumbnail.write_bytes(thumbnail_bytes)
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+ archive_root = service._archive_root
+ output_root = archive_root.parent
+ events: list[tuple[str, Path]] = []
+ real_mkdir = os.mkdir
+ real_fsync_directory = GalleryMaintenanceService._GalleryMaintenanceService__fsync_directory
+ real_replace = Path.replace
+ durability_failure_injected = False
+
+ def track_mkdir(path, *args, **kwargs):
+ result = real_mkdir(path, *args, **kwargs)
+ created_path = Path(os.fsdecode(path))
+ if created_path == archive_root or archive_root in created_path.parents:
+ events.append(("mkdir", created_path))
+ return result
+
+ def fail_archive_parent_sync(directory: Path) -> None:
+ nonlocal durability_failure_injected
+ directory = Path(directory)
+ if directory == output_root or directory == archive_root or archive_root in directory.parents:
+ events.append(("fsync", directory))
+ if directory.name == "recoverable" and directory.parent.name == "thumbnails":
+ durability_failure_injected = True
+ raise OSError("injected archive directory-entry sync failure")
+ real_fsync_directory(directory)
+
+ def track_source_quarantine(path: Path, target: Path) -> Path:
+ if path == thumbnail and Path(target).parent.name.startswith(".gallery-archive-"):
+ events.append(("quarantine", path))
+ return real_replace(path, target)
+
+ monkeypatch.setattr(os, "mkdir", track_mkdir)
+ monkeypatch.setattr(
+ GalleryMaintenanceService,
+ "_GalleryMaintenanceService__fsync_directory",
+ staticmethod(fail_archive_parent_sync),
+ )
+ monkeypatch.setattr(Path, "replace", track_source_quarantine)
+
+ result = service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert durability_failure_injected
+ assert not any(kind == "quarantine" for kind, _path in events)
+ assert records.exists("missing.png")
+ assert thumbnail.read_bytes() == thumbnail_bytes
+ assert result.records_removed == 0
+ assert result.thumbnails_archived == 0
+
+ for index, (kind, directory) in enumerate(events):
+ if kind != "mkdir":
+ continue
+ parent_syncs = [
+ event_index
+ for event_index, (event_kind, synced_directory) in enumerate(events)
+ if event_kind == "fsync" and synced_directory == directory.parent
+ ]
+ assert parent_syncs and parent_syncs[0] > index
+
+
+def test_backup_directory_sync_failure_prevents_gallery_deletion(maintenance, monkeypatch) -> None:
+ service, _db, records, files = maintenance
+ _save_image_record(records, "missing.png", "recoverable")
+ thumbnail = files.get_path("missing.png", thumbnail=True, image_subfolder="recoverable")
+ thumbnail.parent.mkdir(parents=True)
+ thumbnail_bytes = b"recoverable thumbnail"
+ thumbnail.write_bytes(thumbnail_bytes)
+ _embedding(service._invoker.services, "image", "missing.png")
+ embedding_before = _embedding_bytes(service._invoker.services, "image", "missing.png")
+ preview = service.preview(GalleryMaintenanceOperation.REMOVE_MISSING)
+ backup_directory = service._invoker.services.configuration.db_path.parent / "backup"
+ database_directory = backup_directory.parent
+ backup_to = service._invoker.services.database.backup_to
+ directory_fsync = GalleryMaintenanceService._GalleryMaintenanceService__fsync_directory
+ real_mkdir = os.mkdir
+ events: list[tuple[str, Path]] = []
+ completed_backup: Path | None = None
+ sync_failure_injected = False
+
+ assert not database_directory.exists()
+ assert not backup_directory.exists()
+
+ def track_mkdir(path, *args, **kwargs):
+ result = real_mkdir(path, *args, **kwargs)
+ created_path = Path(os.fsdecode(path))
+ if created_path in {database_directory, backup_directory}:
+ events.append(("mkdir", created_path))
+ return result
+
+ def create_backup(destination: Path) -> None:
+ nonlocal completed_backup
+ backup_to(destination)
+ completed_backup = destination
+ events.append(("backup", destination))
+
+ def fail_backup_directory_sync(directory: Path) -> None:
+ nonlocal sync_failure_injected
+ directory = Path(directory)
+ events.append(("fsync", directory))
+ if directory == backup_directory:
+ sync_failure_injected = True
+ raise OSError("injected backup directory-entry sync failure")
+ directory_fsync(directory)
+
+ service._invoker.services.database.backup_to = create_backup
+ monkeypatch.setattr(os, "mkdir", track_mkdir)
+ monkeypatch.setattr(
+ GalleryMaintenanceService,
+ "_GalleryMaintenanceService__fsync_directory",
+ staticmethod(fail_backup_directory_sync),
+ )
+
+ with pytest.raises(GalleryMaintenanceError, match="database backup"):
+ service.execute(GalleryMaintenanceOperation.REMOVE_MISSING, preview.fingerprint)
+
+ assert sync_failure_injected
+ assert completed_backup is not None and completed_backup.is_file()
+ assert records.exists("missing.png")
+ assert _embedding_bytes(service._invoker.services, "image", "missing.png") == embedding_before
+ assert thumbnail.read_bytes() == thumbnail_bytes
+ assert not service._archive_root.exists()
+ service._invoker.services.images.notify_deleted.assert_not_called()
+
+ backup_index = next(index for index, (kind, _path) in enumerate(events) if kind == "backup")
+ for created_directory in (database_directory, backup_directory):
+ mkdir_index = next(
+ index
+ for index, (kind, directory) in enumerate(events)
+ if kind == "mkdir" and directory == created_directory
+ )
+ parent_sync_index = next(
+ index
+ for index, (kind, directory) in enumerate(events)
+ if kind == "fsync" and directory == created_directory.parent
+ )
+ assert mkdir_index < backup_index < parent_sync_index
diff --git a/tests/app/services/image_files/test_image_files_disk.py b/tests/app/services/image_files/test_image_files_disk.py
index 8d3eb494f2..af5d31b322 100644
--- a/tests/app/services/image_files/test_image_files_disk.py
+++ b/tests/app/services/image_files/test_image_files_disk.py
@@ -4,15 +4,20 @@ import os
import platform
import shutil
import stat
+import threading
import zlib
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
-from PIL import Image
+from PIL import Image, UnidentifiedImageError
from invokeai.app.api.extract_metadata import extract_metadata_from_image
-from invokeai.app.services.image_files.image_files_common import ImageFileDeleteException, ImageFileSaveException
+from invokeai.app.services.image_files.image_files_common import (
+ ImageFileDeleteException,
+ ImageFileNotFoundException,
+ ImageFileSaveException,
+)
from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage, _should_use_png_rle
from invokeai.app.util.thumbnails import get_thumbnail_name
@@ -99,6 +104,375 @@ def test_image_paths_relative_to_storage_dir(tmp_path: Path):
assert path.is_relative_to(tmp_path)
+def test_iter_image_and_thumbnail_paths_is_sorted_nested_and_excludes_reserved_trees(tmp_path: Path):
+ storage = DiskImageFileStorage(tmp_path)
+ (tmp_path / "z.png").write_bytes(b"z")
+ (tmp_path / "a" / "nested.png").parent.mkdir(parents=True)
+ (tmp_path / "a" / "nested.png").write_bytes(b"a")
+ (tmp_path / "thumbnails" / "a").mkdir(parents=True)
+ (tmp_path / "thumbnails" / "a" / "nested.webp").write_bytes(b"t")
+ (tmp_path / ".delete_pending").mkdir()
+ (tmp_path / ".delete_pending" / "journal.png").write_bytes(b"j")
+ (tmp_path / "clip.mp4").write_bytes(b"v")
+
+ assert [path.relative_to(tmp_path).as_posix() for path in storage.iter_image_paths()] == ["z.png", "a/nested.png"]
+ assert [path.relative_to(storage.thumbnail_root).as_posix() for path in storage.iter_thumbnail_paths()] == [
+ "a/nested.webp"
+ ]
+
+
+def test_iter_image_paths_streams_directory_entries_in_deterministic_order(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ storage = DiskImageFileStorage(tmp_path)
+ names = [f"image-{index:04d}.png" for index in reversed(range(1024))]
+ names.append("invalid-byte-\udcff.png")
+
+ class Entry:
+ active = 0
+ peak_active = 0
+
+ def __init__(self, name: str):
+ self.name = name
+ self.path = str(tmp_path / name)
+ type(self).active += 1
+ type(self).peak_active = max(type(self).peak_active, type(self).active)
+
+ def __del__(self):
+ type(self).active -= 1
+
+ def is_symlink(self) -> bool:
+ return False
+
+ def is_dir(self, *, follow_symlinks: bool = True) -> bool:
+ return False
+
+ def is_file(self, *, follow_symlinks: bool = True) -> bool:
+ return True
+
+ class Scan:
+ def __enter__(self):
+ return iter(Entry(name) for name in names)
+
+ def __exit__(self, *_exc_info):
+ return False
+
+ real_scandir = os.scandir
+ monkeypatch.setattr(
+ "invokeai.app.services.image_files.image_files_disk.os.scandir",
+ lambda path: Scan() if not isinstance(path, int) and Path(path) == tmp_path else real_scandir(path),
+ )
+
+ paths = list(storage.iter_image_paths())
+
+ assert [path.name for path in paths] == sorted(names)
+ assert Entry.peak_active <= 2
+
+
+def test_generate_thumbnail_if_missing_preserves_source_and_never_overwrites(tmp_path: Path):
+ storage = DiskImageFileStorage(tmp_path)
+ image_path = storage.get_path("test.png", image_subfolder="sub")
+ image_path.parent.mkdir(parents=True)
+ image = Image.new("RGBA", (12, 8), (20, 40, 60, 80))
+ image.save(image_path, format="PNG")
+ image.close()
+ original_bytes = image_path.read_bytes()
+ thumbnail_path = storage.get_path("test.png", thumbnail=True, image_subfolder="sub")
+
+ assert storage.generate_thumbnail_if_missing("test.png", image_subfolder="sub") is True
+ first_thumbnail = thumbnail_path.read_bytes()
+ assert first_thumbnail
+ assert image_path.read_bytes() == original_bytes
+ assert storage.generate_thumbnail_if_missing("test.png", image_subfolder="sub") is False
+ assert thumbnail_path.read_bytes() == first_thumbnail
+
+
+def test_generate_thumbnail_if_missing_does_not_publish_partial_file(tmp_path: Path):
+ storage = DiskImageFileStorage(tmp_path)
+ image_path = storage.get_path("broken.png")
+ image_path.write_bytes(b"not an image")
+ thumbnail_path = storage.get_path("broken.png", thumbnail=True)
+
+ with pytest.raises(UnidentifiedImageError):
+ storage.generate_thumbnail_if_missing("broken.png")
+
+ assert not thumbnail_path.exists()
+
+
+def test_generate_thumbnail_if_missing_fsyncs_a_writable_temporary_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ storage = DiskImageFileStorage(tmp_path)
+ image_path = storage.get_path("writable-fsync.png")
+ with Image.new("RGB", (8, 8), (20, 40, 60)) as source:
+ source.save(image_path, format="PNG")
+ real_fsync = os.fsync
+
+ def require_writable_file_and_fsync(descriptor: int) -> None:
+ file_stat = os.fstat(descriptor)
+ if stat.S_ISREG(file_stat.st_mode):
+ original_size = file_stat.st_size
+ os.lseek(descriptor, 0, os.SEEK_END)
+ os.write(descriptor, b"x")
+ os.ftruncate(descriptor, original_size)
+ real_fsync(descriptor)
+
+ monkeypatch.setattr("invokeai.app.services.image_files.image_files_disk.os.fsync", require_writable_file_and_fsync)
+
+ assert storage.generate_thumbnail_if_missing(image_path.name) is True
+ assert storage.get_path(image_path.name, thumbnail=True).is_file()
+
+
+@posix_only
+def test_generate_thumbnail_if_missing_removes_thumbnail_if_directory_fsync_fails(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ storage = DiskImageFileStorage(tmp_path)
+ image_path = storage.get_path("fsync-failure.png")
+ with Image.new("RGB", (8, 8), (20, 40, 60)) as source:
+ source.save(image_path, format="PNG")
+ original_bytes = image_path.read_bytes()
+ thumbnail_path = storage.get_path("fsync-failure.png", thumbnail=True)
+
+ def fail_directory_fsync(_directory: Path) -> None:
+ raise OSError("directory fsync failed")
+
+ monkeypatch.setattr(storage, "_DiskImageFileStorage__fsync_directory", fail_directory_fsync)
+
+ with pytest.raises(OSError, match="directory fsync failed"):
+ storage.generate_thumbnail_if_missing("fsync-failure.png")
+
+ assert image_path.read_bytes() == original_bytes
+ assert not thumbnail_path.exists()
+
+
+def test_cache_eviction_prevents_inflight_read_from_repopulating_stale_image(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ storage = DiskImageFileStorage(tmp_path)
+ invoker = MagicMock()
+ invoker.services.configuration.pil_compress_level = 6
+ storage._DiskImageFileStorage__invoker = invoker # type: ignore
+ image_path = storage.get_path("raced-cache.png")
+ storage.save(image=Image.new("RGB", (8, 8), (220, 10, 10)), image_name=image_path.name)
+ storage.evict_cache_paths([image_path])
+
+ cache_write_started = threading.Event()
+ allow_cache_write = threading.Event()
+ loaded_images: list[Image.Image] = []
+ errors: list[BaseException] = []
+ set_cache = storage._DiskImageFileStorage__set_cache
+
+ def pause_before_cache_write(path: Path, image: Image.Image, generation: int | None = None) -> None:
+ if path == image_path:
+ cache_write_started.set()
+ if not allow_cache_write.wait(timeout=5):
+ raise TimeoutError("test did not release the in-flight cache write")
+ if generation is None:
+ set_cache(path, image)
+ else:
+ set_cache(path, image, generation)
+
+ monkeypatch.setattr(storage, "_DiskImageFileStorage__set_cache", pause_before_cache_write)
+
+ def read_image() -> None:
+ try:
+ loaded_images.append(storage.get(image_path.name))
+ except BaseException as e:
+ errors.append(e)
+
+ reader = threading.Thread(target=read_image)
+ reader.start()
+ try:
+ assert cache_write_started.wait(timeout=5)
+ with Image.new("RGB", (8, 8), (10, 20, 220)) as replacement:
+ replacement.save(image_path, format="PNG")
+ storage.evict_cache_paths([image_path])
+ finally:
+ allow_cache_write.set()
+ reader.join(timeout=5)
+
+ assert not reader.is_alive()
+ assert not errors
+ try:
+ assert storage.get(image_path.name).getpixel((0, 0)) == (10, 20, 220)
+ finally:
+ for image in loaded_images:
+ image.close()
+
+
+def test_stage_delete_and_commit_prevent_inflight_read_from_caching_deleted_image(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ storage = DiskImageFileStorage(tmp_path)
+ invoker = MagicMock()
+ invoker.services.configuration.pil_compress_level = 6
+ storage._DiskImageFileStorage__invoker = invoker # type: ignore
+ image_name = "staged-race.png"
+ image_path = storage.get_path(image_name)
+ with Image.new("RGB", (8, 8), (220, 10, 10)) as source:
+ storage.save(image=source, image_name=image_name)
+ storage.evict_cache_paths([image_path])
+
+ cache_write_started = threading.Event()
+ allow_cache_write = threading.Event()
+ purge_finished = threading.Event()
+ allow_commit = threading.Event()
+ loaded_images: list[Image.Image] = []
+ errors: list[BaseException] = []
+ set_cache = storage._DiskImageFileStorage__set_cache
+
+ def pause_before_cache_write(path: Path, image: Image.Image, generation: int | None = None) -> None:
+ if path == image_path:
+ cache_write_started.set()
+ if not allow_cache_write.wait(timeout=5):
+ raise TimeoutError("test did not release the in-flight cache write")
+ if generation is None:
+ set_cache(path, image)
+ else:
+ set_cache(path, image, generation)
+
+ monkeypatch.setattr(storage, "_DiskImageFileStorage__set_cache", pause_before_cache_write)
+
+ def read_image() -> None:
+ try:
+ loaded_images.append(storage.get(image_name))
+ except BaseException as e:
+ errors.append(e)
+
+ reader = threading.Thread(target=read_image)
+ reader.start()
+ commit_errors: list[BaseException] = []
+ committer: threading.Thread | None = None
+ try:
+ assert cache_write_started.wait(timeout=5)
+ token = storage.stage_delete(image_name)
+ purge = storage._DiskImageFileStorage__purge_files
+
+ def pause_after_purge(name: str, subfolder: str) -> None:
+ purge(name, subfolder)
+ purge_finished.set()
+ if not allow_commit.wait(timeout=5):
+ raise TimeoutError("test did not release staged deletion")
+
+ monkeypatch.setattr(storage, "_DiskImageFileStorage__purge_files", pause_after_purge)
+
+ def commit() -> None:
+ try:
+ storage.commit_delete(token)
+ except BaseException as e:
+ commit_errors.append(e)
+
+ committer = threading.Thread(target=commit)
+ committer.start()
+ assert purge_finished.wait(timeout=5)
+ allow_cache_write.set()
+ reader.join(timeout=5)
+ allow_commit.set()
+ committer.join(timeout=5)
+
+ assert not reader.is_alive()
+ assert not committer.is_alive()
+ assert not errors
+ assert not commit_errors
+ with pytest.raises(ImageFileNotFoundException):
+ storage.get(image_name)
+ finally:
+ allow_cache_write.set()
+ allow_commit.set()
+ reader.join(timeout=5)
+ if committer is not None:
+ committer.join(timeout=5)
+ for image in loaded_images:
+ image.close()
+
+
+def test_pending_delete_purge_prevents_inflight_read_from_caching_deleted_image(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ storage = DiskImageFileStorage(tmp_path)
+ invoker = MagicMock()
+ invoker.services.configuration.pil_compress_level = 6
+ storage._DiskImageFileStorage__invoker = invoker # type: ignore
+ image_name = "purged-race.png"
+ image_path = storage.get_path(image_name)
+ with Image.new("RGB", (8, 8), (220, 10, 10)) as source:
+ storage.save(image=source, image_name=image_name)
+ storage.evict_cache_paths([image_path])
+ token = storage.begin_delete([(image_name, "")])
+
+ cache_write_started = threading.Event()
+ allow_cache_write = threading.Event()
+ purge_finished = threading.Event()
+ allow_persist = threading.Event()
+ loaded_images: list[Image.Image] = []
+ errors: list[BaseException] = []
+ set_cache = storage._DiskImageFileStorage__set_cache
+
+ def pause_before_cache_write(path: Path, image: Image.Image, generation: int | None = None) -> None:
+ if path == image_path:
+ cache_write_started.set()
+ if not allow_cache_write.wait(timeout=5):
+ raise TimeoutError("test did not release the in-flight cache write")
+ if generation is None:
+ set_cache(path, image)
+ else:
+ set_cache(path, image, generation)
+
+ monkeypatch.setattr(storage, "_DiskImageFileStorage__set_cache", pause_before_cache_write)
+
+ def read_image() -> None:
+ try:
+ loaded_images.append(storage.get(image_name))
+ except BaseException as e:
+ errors.append(e)
+
+ reader = threading.Thread(target=read_image)
+ reader.start()
+ commit_errors: list[BaseException] = []
+ committer: threading.Thread | None = None
+ try:
+ assert cache_write_started.wait(timeout=5)
+ persist = storage._DiskImageFileStorage__persist_purges
+
+ def pause_after_purge(images: list[tuple[str, str]]) -> None:
+ purge_finished.set()
+ if not allow_persist.wait(timeout=5):
+ raise TimeoutError("test did not release pending deletion")
+ persist(images)
+
+ monkeypatch.setattr(storage, "_DiskImageFileStorage__persist_purges", pause_after_purge)
+
+ def commit() -> None:
+ try:
+ storage.commit_delete(token)
+ except BaseException as e:
+ commit_errors.append(e)
+
+ committer = threading.Thread(target=commit)
+ committer.start()
+ assert purge_finished.wait(timeout=5)
+ allow_cache_write.set()
+ reader.join(timeout=5)
+ allow_persist.set()
+ committer.join(timeout=5)
+
+ assert not reader.is_alive()
+ assert not committer.is_alive()
+ assert not errors
+ assert not commit_errors
+ with pytest.raises(ImageFileNotFoundException):
+ storage.get(image_name)
+ finally:
+ allow_cache_write.set()
+ allow_persist.set()
+ reader.join(timeout=5)
+ if committer is not None:
+ committer.join(timeout=5)
+ for image in loaded_images:
+ image.close()
+
+
@pytest.mark.parametrize(
("compress_level", "expected_compress_type"),
[(0, None), (1, zlib.Z_RLE), (7, None)],
diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.py
index 8602c3fb86..a47efd83c9 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -1530,7 +1530,7 @@ def test_on_deleted_emits_status(
_wait_until(lambda: index_records.count_index_status(MODEL_ID).embedded == 1)
image_records.delete("a.png")
- images_service._on_deleted("a.png")
+ images_service.notify_deleted("a.png")
# Deletions give the worker nothing to embed; the dirty flag set by the
# callback is the only path to this emit, within one poll interval.
diff --git a/tests/app/services/image_moves/test_image_moves_default.py b/tests/app/services/image_moves/test_image_moves_default.py
index bbeea1cbf6..0bd7860561 100644
--- a/tests/app/services/image_moves/test_image_moves_default.py
+++ b/tests/app/services/image_moves/test_image_moves_default.py
@@ -10,13 +10,14 @@ from PIL import Image
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
from invokeai.app.services.image_moves.image_moves_default import (
+ ImageMoveJobAlreadyRunning,
ImageMoveQueueActive,
ImageMoveService,
UnreadableImageError,
)
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
-from invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID, SessionQueueStatus
+from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.shared.sqlite.sqlite_util import init_db
from invokeai.backend.util.logging import InvokeAILogger
@@ -522,19 +523,7 @@ def test_start_leaves_maintenance_active_when_recovery_remains_incomplete(tmp_pa
def test_background_move_rejects_active_queue_work(tmp_path: Path, pending: int, in_progress: int) -> None:
service, _records = _service(tmp_path, strategy="date")
invoker = MagicMock()
- invoker.services.session_queue.get_queue_status.return_value = SessionQueueStatus(
- queue_id=DEFAULT_QUEUE_ID,
- item_id=None,
- batch_id=None,
- session_id=None,
- pending=pending,
- in_progress=in_progress,
- waiting=0,
- completed=0,
- failed=0,
- canceled=0,
- total=1,
- )
+ invoker.services.session_queue.has_active_queue_work.return_value = pending > 0 or in_progress > 0
service.start(invoker)
with pytest.raises(ImageMoveQueueActive, match="queue work is active"):
@@ -545,24 +534,11 @@ def test_background_move_is_reserved_before_queue_check(tmp_path: Path) -> None:
service, _records = _service(tmp_path, strategy="date")
invoker = MagicMock()
- def get_queue_status(queue_id: str) -> SessionQueueStatus:
- assert queue_id == DEFAULT_QUEUE_ID
+ def has_active_queue_work() -> bool:
assert service.is_maintenance_active() is True
- return SessionQueueStatus(
- queue_id=DEFAULT_QUEUE_ID,
- item_id=None,
- batch_id=None,
- session_id=None,
- pending=1,
- in_progress=0,
- waiting=0,
- completed=0,
- failed=0,
- canceled=0,
- total=1,
- )
+ return True
- invoker.services.session_queue.get_queue_status.side_effect = get_queue_status
+ invoker.services.session_queue.has_active_queue_work.side_effect = has_active_queue_work
service.start(invoker)
with pytest.raises(ImageMoveQueueActive, match="queue work is active"):
@@ -571,6 +547,72 @@ def test_background_move_is_reserved_before_queue_check(tmp_path: Path) -> None:
assert service.is_maintenance_active() is False
+def test_gallery_maintenance_reservation_blocks_moves_and_releases_after_failure(tmp_path: Path) -> None:
+ service, _records = _service(tmp_path, strategy="date")
+
+ try:
+ with service.reserve_gallery_maintenance():
+ assert service.is_maintenance_active() is True
+ with pytest.raises(ImageMoveJobAlreadyRunning, match="maintenance"):
+ service.start_background_recovery()
+
+ assert service.is_maintenance_active() is False
+
+ with pytest.raises(RuntimeError, match="operation failed"):
+ with service.reserve_gallery_maintenance():
+ raise RuntimeError("operation failed")
+
+ assert service.is_maintenance_active() is False
+ finally:
+ service.stop()
+
+
+def test_gallery_maintenance_reservation_refuses_active_queue_and_releases_flag(tmp_path: Path) -> None:
+ service, _records = _service(tmp_path, strategy="date")
+ invoker = MagicMock()
+
+ def has_active_queue_work() -> bool:
+ # The operation reservation must be visible before it reads queue state.
+ assert service.is_maintenance_active() is True
+ return True
+
+ invoker.services.session_queue.has_active_queue_work.side_effect = has_active_queue_work
+ service.start(invoker)
+
+ try:
+ with pytest.raises(ImageMoveQueueActive, match="queue work is active"):
+ with service.reserve_gallery_maintenance():
+ pytest.fail("maintenance must not begin with pending queue work")
+
+ assert service.is_maintenance_active() is False
+ finally:
+ service.stop()
+
+
[email protected]("status", ["pending", "in_progress"])
+def test_gallery_maintenance_reservation_refuses_active_work_on_custom_queue(tmp_path: Path, status: str) -> None:
+ service, _records = _service(tmp_path, strategy="date")
+ queue = SqliteSessionQueue(db=service._db)
+ with service._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ INSERT INTO session_queue (batch_id, queue_id, session_id, session, status)
+ VALUES ('custom-batch', 'custom-queue', 'custom-session', '{}', ?)
+ """,
+ (status,),
+ )
+ service.set_session_queue(queue)
+
+ try:
+ with pytest.raises(ImageMoveQueueActive, match="queue work is active"):
+ with service.reserve_gallery_maintenance():
+ pytest.fail("maintenance must not begin while a custom queue has pending work")
+
+ assert service.is_maintenance_active() is False
+ finally:
+ service.stop()
+
+
def test_maintenance_is_active_while_background_job_or_uncommitted_journal_exists(tmp_path: Path) -> None:
service, records = _service(tmp_path, strategy="date")
image_name = "image-maintenance-active.png"
diff --git a/tests/app/services/image_records/test_image_records_sqlite.py b/tests/app/services/image_records/test_image_records_sqlite.py
index 3c3e841889..8606429f61 100644
--- a/tests/app/services/image_records/test_image_records_sqlite.py
+++ b/tests/app/services/image_records/test_image_records_sqlite.py
@@ -152,6 +152,27 @@ class TestGetSubfolders:
store.get("tmp.png")
+class TestIterAllImageLocations:
+ def test_keyset_pages_keep_archived_and_intermediate_records_without_offset_skips(
+ self, store: SqliteImageRecordStorage
+ ) -> None:
+ _save(store, "a.png", subfolder="nested", user_id="user-a")
+ _save(store, "b.png", subfolder="nested", is_intermediate=True, user_id="user-b")
+ _save(store, "c.png", subfolder="archived", user_id="user-a")
+ _save(store, "d.png", subfolder="", user_id="user-b")
+
+ locations = iter(store.iter_all_image_locations(batch_size=2))
+ assert next(locations) == ("a.png", "nested")
+ assert next(locations) == ("b.png", "nested")
+ store.delete_many(["a.png", "b.png"])
+
+ assert list(locations) == [("c.png", "archived"), ("d.png", "")]
+
+ def test_iteration_rejects_nonpositive_batch_size(self, store: SqliteImageRecordStorage) -> None:
+ with pytest.raises(ValueError, match="batch_size"):
+ list(store.iter_all_image_locations(batch_size=0))
+
+
class TestQueryFaultsAreNotNotFound:
"""A failing query means the database is unavailable, not that the image is missing.
diff --git a/tests/app/services/images/test_images_default.py b/tests/app/services/images/test_images_default.py
index ae6839a70a..ccb3b10ec7 100644
--- a/tests/app/services/images/test_images_default.py
+++ b/tests/app/services/images/test_images_default.py
@@ -504,6 +504,24 @@ def _unlink_always_fails(path: Path, missing_ok: bool = False) -> None:
class TestDeleteTransactional:
"""delete() journals its intent, deletes the record, then purges — never losing files on failure."""
+ def test_notify_deleted_is_public_and_callbacks_observe_removed_record(
+ self, real_image_service: tuple[ImageService, SqliteImageRecordStorage, DiskImageFileStorage]
+ ) -> None:
+ service, records, _storage = real_image_service
+ _seed_record(records, "maintenance-removed.png", is_intermediate=False)
+ notified: list[str] = []
+
+ def record_removed(image_name: str) -> None:
+ with pytest.raises(ImageRecordNotFoundException):
+ records.get(image_name)
+ notified.append(image_name)
+
+ service.on_deleted(record_removed)
+ records.delete("maintenance-removed.png")
+ service.notify_deleted("maintenance-removed.png")
+
+ assert notified == ["maintenance-removed.png"]
+
def test_delete_success_removes_files_record_and_fires_callback_once(self, disk_image_service: ImageService):
invoker = disk_image_service._ImageService__invoker # type: ignore
storage = invoker.services.image_files
@@ -1392,6 +1410,59 @@ class TestStorageAccounting:
storage.get_path("copy.png").stat().st_size + storage.get_path("copy.png", thumbnail=True).stat().st_size
)
+ def test_copy_holds_the_move_mutation_lock_across_record_and_file_creation(
+ self, wired_with_move_service, monkeypatch
+ ) -> None:
+ svc, records, storage, moves = wired_with_move_service
+ invoker = svc._ImageService__invoker # type: ignore
+ invoker.services.names.create_image_name.return_value = "copy.png"
+ invoker.services.urls.get_image_url.return_value = "/api/v1/images/i/copy.png"
+ invoker.services.board_image_records.get_board_for_image.return_value = None
+ invoker.services.configuration.image_subfolder_strategy = "flat"
+ _seed_record(records, "source.png", is_intermediate=False)
+ _save_image_file(storage, "source.png")
+
+ copy_started = threading.Event()
+ finish_copy = threading.Event()
+ real_copy = storage.copy
+
+ def pause_file_copy(*args, **kwargs):
+ # The record exists but the new original is not present yet. A concurrent missing-file
+ # maintenance scan must not be able to remove this half-written copy.
+ assert records.get("copy.png")
+ assert not storage.get_path("copy.png").exists()
+ copy_started.set()
+ assert finish_copy.wait(timeout=10), "copy was not released"
+ return real_copy(*args, **kwargs)
+
+ monkeypatch.setattr(storage, "copy", pause_file_copy)
+ copy_errors: list[Exception] = []
+
+ def copy_image() -> None:
+ try:
+ svc.copy("source.png")
+ except Exception as error:
+ copy_errors.append(error)
+
+ copy_thread = threading.Thread(target=copy_image)
+ copy_thread.start()
+ try:
+ assert copy_started.wait(timeout=10), "copy did not reach its file write"
+
+ # Probe the actual lock while the record/file pair is half-created. This is deterministic:
+ # an unlocked copy lets the probe acquire the lock, while a guarded copy does not.
+ acquired = moves._image_mutation_lock.acquire(blocking=False)
+ if acquired:
+ moves._image_mutation_lock.release()
+ assert not acquired, "copy released the shared mutation lock before its file write completed"
+ finally:
+ finish_copy.set()
+ copy_thread.join(timeout=10)
+
+ assert not copy_thread.is_alive()
+ assert copy_errors == []
+ assert storage.get_path("copy.png").exists()
+
def test_a_failed_measurement_leaves_the_size_unknown_and_the_image_intact(self, wired, monkeypatch) -> None:
svc, records, storage = wired
invoker = svc._ImageService__invoker # type: ignore
diff --git a/tests/app/services/session_processor/test_session_processor_image_maintenance.py b/tests/app/services/session_processor/test_session_processor_image_maintenance.py
new file mode 100644
index 0000000000..c08959280b
--- /dev/null
+++ b/tests/app/services/session_processor/test_session_processor_image_maintenance.py
@@ -0,0 +1,204 @@
+"""Queue claims serialize with image storage maintenance reservations."""
+
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
+from invokeai.app.services.image_moves.image_moves_default import ImageMoveQueueActive, ImageMoveService
+from invokeai.app.services.session_processor.session_processor_default import DefaultSessionProcessor, _SessionWorker
+from invokeai.app.services.shared.sqlite.sqlite_util import init_db
+from invokeai.backend.util.logging import InvokeAILogger
+
+
+class _Queue:
+ def __init__(self, pending: int) -> None:
+ self.status = SimpleNamespace(pending=pending, in_progress=0)
+ self.dequeue_started = threading.Event()
+ self.allow_dequeue = threading.Event()
+ self.dequeued = 0
+ self.item = SimpleNamespace(item_id=1, session_id="session-1", queue_id="default")
+
+ def has_active_queue_work(self) -> bool:
+ return self.status.pending > 0 or self.status.in_progress > 0
+
+ def dequeue(self, device: str | None = None):
+ self.dequeued += 1
+ self.dequeue_started.set()
+ if not self.allow_dequeue.wait(timeout=10):
+ raise AssertionError("queue claim was not released")
+ self.status = SimpleNamespace(pending=0, in_progress=1)
+ return self.item
+
+
+def _services(tmp_path: Path, queue: _Queue) -> tuple[DefaultSessionProcessor, ImageMoveService]:
+ config = InvokeAIAppConfig(use_memory_db=True)
+ config._root = tmp_path
+ logger = InvokeAILogger.get_logger(config=config)
+ image_files = DiskImageFileStorage(tmp_path / "images")
+ db = init_db(config=config, logger=logger, image_files=image_files)
+ moves = ImageMoveService(db=db, image_files=image_files, config=config, logger=logger)
+ invoker = SimpleNamespace(services=SimpleNamespace(session_queue=queue))
+ moves.start(invoker)
+
+ processor = DefaultSessionProcessor()
+ processor._invoker = SimpleNamespace( # type: ignore[attr-defined]
+ services=SimpleNamespace(session_queue=queue, image_moves=moves)
+ )
+ return processor, moves
+
+
+def test_in_flight_queue_claim_is_visible_before_gallery_maintenance_can_start(tmp_path: Path) -> None:
+ queue = _Queue(pending=1)
+ queue.allow_dequeue.clear()
+ processor, moves = _services(tmp_path, queue)
+ claimed: list[tuple[bool, object | None]] = []
+ claim_errors: list[Exception] = []
+
+ def claim() -> None:
+ try:
+ claimed.append(processor._dequeue_if_storage_maintenance_inactive(device=None))
+ except Exception as error:
+ claim_errors.append(error)
+
+ claim_thread = threading.Thread(target=claim)
+ claim_thread.start()
+ reservation_errors: list[Exception] = []
+ reservation_thread: threading.Thread | None = None
+
+ def reserve() -> None:
+ try:
+ with moves.reserve_gallery_maintenance():
+ reservation_errors.append(AssertionError("maintenance ran while a queue item was in progress"))
+ except Exception as error:
+ reservation_errors.append(error)
+
+ try:
+ assert queue.dequeue_started.wait(timeout=10), "worker did not reach dequeue"
+
+ reservation_attempted = threading.Event()
+ real_mutation_lock = moves.image_mutation_lock
+
+ def observe_reservation_lock():
+ reservation_attempted.set()
+ return real_mutation_lock()
+
+ moves.image_mutation_lock = observe_reservation_lock # type: ignore[method-assign]
+ reservation_thread = threading.Thread(target=reserve)
+ reservation_thread.start()
+ assert reservation_attempted.wait(timeout=10), "maintenance did not attempt the shared mutation lock"
+ assert moves.is_maintenance_active() is True
+ finally:
+ queue.allow_dequeue.set()
+ claim_thread.join(timeout=10)
+ if reservation_thread is not None:
+ reservation_thread.join(timeout=10)
+ moves.stop()
+
+ assert not claim_thread.is_alive()
+ assert reservation_thread is not None
+ assert not reservation_thread.is_alive()
+ assert claim_errors == []
+ assert claimed == [(True, queue.item)]
+ assert len(reservation_errors) == 1
+ assert isinstance(reservation_errors[0], ImageMoveQueueActive)
+ assert queue.status.in_progress == 1
+ assert moves.is_maintenance_active() is False
+
+
+def test_queue_work_admitted_after_reservation_waits_without_being_claimed(tmp_path: Path) -> None:
+ queue = _Queue(pending=0)
+ processor, moves = _services(tmp_path, queue)
+
+ try:
+ with moves.reserve_gallery_maintenance():
+ # The API may admit an enqueue that raced the operation reservation; workers must
+ # still leave it pending until the guarded filesystem scan is complete.
+ queue.status = SimpleNamespace(pending=1, in_progress=0)
+ allowed, item = processor._dequeue_if_storage_maintenance_inactive(device=None)
+
+ assert allowed is False
+ assert item is None
+ assert queue.dequeued == 0
+ assert queue.status.pending == 1
+ finally:
+ moves.stop()
+
+
+def test_worker_stops_while_gallery_maintenance_holds_the_mutation_lock(tmp_path: Path) -> None:
+ queue = _Queue(pending=0)
+ queue.allow_dequeue.set()
+ processor, moves = _services(tmp_path, queue)
+ maintenance_entered = threading.Event()
+ release_maintenance = threading.Event()
+ maintenance_errors: list[Exception] = []
+
+ def hold_maintenance_lock() -> None:
+ try:
+ with moves.reserve_gallery_maintenance():
+ maintenance_entered.set()
+ if not release_maintenance.wait(timeout=10):
+ maintenance_errors.append(TimeoutError("maintenance hold was not released"))
+ except Exception as error:
+ maintenance_errors.append(error)
+
+ maintenance_thread = threading.Thread(target=hold_maintenance_lock)
+ maintenance_thread.start()
+
+ stop_event = threading.Event()
+ resume_event = threading.Event()
+ resume_event.set()
+ poll_now_event = threading.Event()
+ worker = _SessionWorker(device=None, runner=object())
+ processor._invoker.services.logger = InvokeAILogger.get_logger()
+ processor._polling_interval = 5
+ processor._thread_semaphore = threading.BoundedSemaphore(1)
+ processor._stop_event = stop_event
+ processor._resume_event = resume_event
+ processor._poll_now_event = poll_now_event
+ processor._workers = [worker]
+
+ claim_attempted = threading.Event()
+ dequeue = processor._dequeue_if_storage_maintenance_inactive
+
+ def observe_claim(device: str | None):
+ claim_attempted.set()
+ return dequeue(device)
+
+ processor._dequeue_if_storage_maintenance_inactive = observe_claim # type: ignore[method-assign]
+ worker_thread = threading.Thread(
+ target=processor._process,
+ kwargs={
+ "worker": worker,
+ "stop_event": stop_event,
+ "poll_now_event": poll_now_event,
+ "resume_event": resume_event,
+ },
+ daemon=True,
+ )
+ stopped_before_release = False
+ worker_started = False
+
+ try:
+ assert maintenance_entered.wait(timeout=10), "maintenance did not acquire the mutation lock"
+ worker_thread.start()
+ worker_started = True
+ assert claim_attempted.wait(timeout=10), "worker did not attempt a queue claim"
+
+ processor.stop()
+ worker_thread.join(timeout=2)
+ stopped_before_release = not worker_thread.is_alive()
+ finally:
+ processor.stop()
+ release_maintenance.set()
+ if worker_started:
+ worker_thread.join(timeout=10)
+ maintenance_thread.join(timeout=10)
+ moves.stop()
+
+ assert stopped_before_release, "worker shutdown waited for the gallery maintenance lock"
+ assert not worker_thread.is_alive()
+ assert not maintenance_thread.is_alive()
+ assert maintenance_errors == []
+ assert queue.dequeued == 0
diff --git a/tests/app/services/shared/sqlite/test_sqlite_database.py b/tests/app/services/shared/sqlite/test_sqlite_database.py
index 271a0d30de..42d792409d 100644
--- a/tests/app/services/shared/sqlite/test_sqlite_database.py
+++ b/tests/app/services/shared/sqlite/test_sqlite_database.py
@@ -4,8 +4,11 @@ Manual VACUUM may run while services and their worker threads are live; without
the shared lock it can fail with "cannot VACUUM - SQL statements in progress".
"""
+import sqlite3
import threading
+import pytest
+
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.backend.util.logging import InvokeAILogger
@@ -44,3 +47,20 @@ def test_clean_waits_for_in_flight_transactions(tmp_path) -> None:
assert not holder.is_alive()
assert not cleaner.is_alive()
assert errors == []
+
+
+def test_backup_to_captures_committed_wal_data_and_refuses_overwrite(tmp_path) -> None:
+ source = tmp_path / "source.db"
+ backup = tmp_path / "backup.db"
+ db = SqliteDatabase(db_path=source, logger=InvokeAILogger.get_logger())
+ with db.transaction() as cursor:
+ cursor.execute("CREATE TABLE values_table (value TEXT NOT NULL);")
+ cursor.execute("INSERT INTO values_table VALUES ('committed in WAL');")
+
+ db.backup_to(backup)
+
+ with sqlite3.connect(backup) as connection:
+ assert connection.execute("SELECT value FROM values_table;").fetchall() == [("committed in WAL",)]
+
+ with pytest.raises(FileExistsError):
+ db.backup_to(backup)