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.

fix(gallery): clean up references to images a lost delete response committed (#10368)

Lincoln Stein3adca483e0c8
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index f99a626167..783c2b8719 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -663,6 +663,31 @@ def delete_images_from_list(
raise HTTPException(status_code=500, detail="Failed to delete images")
+@images_router.post("/gone", operation_id="get_gone_images", response_model=list[str])
+def get_gone_images(
+ current_user: CurrentUserOrDefault,
+ image_names: list[ImageName] = Body(
+ description="The names of images to check", embed=True, max_length=MAX_IMAGE_BATCH_SIZE
+ ),
+) -> list[str]:
+ """Returns the requested names whose image records are positively absent.
+
+ Lets a client whose delete response was lost learn which deletions committed, so it can drop
+ its references to them. A name is listed only when the record is confirmed missing: a name
+ that exists (readable by the caller or not) or that storage could not check is left out, so
+ an unavailable database prunes nothing. Revealing absence matches the 404 the per-image
+ routes already answer for a gone image (see `_assert_image_record_exists`).
+ """
+ gone: list[str] = []
+ for image_name in dict.fromkeys(image_names):
+ try:
+ if not ApiDependencies.invoker.services.image_records.exists(image_name):
+ gone.append(image_name)
+ except Exception:
+ continue
+ return gone
+
+
@images_router.delete("/uncategorized", operation_id="delete_uncategorized_images", response_model=DeleteImagesResult)
def delete_uncategorized_images(
current_user: CurrentUserOrDefault,
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index e7bc28b787..746cc7173e 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -7997,6 +7997,55 @@
]
}
},
+ "/api/v1/images/gone": {
+ "post": {
+ "tags": ["images"],
+ "summary": "Get Gone Images",
+ "description": "Returns the requested names whose image records are positively absent.\n\nLets a client whose delete response was lost learn which deletions committed, so it can drop\nits references to them. A name is listed only when the record is confirmed missing: a name\nthat exists (readable by the caller or not) or that storage could not check is left out, so\nan unavailable database prunes nothing. Revealing absence matches the 404 the per-image\nroutes already answer for a gone image (see `_assert_image_record_exists`).",
+ "operationId": "get_gone_images",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_get_gone_images"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Response Get Gone Images"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ]
+ }
+ },
"/api/v1/images/uncategorized": {
"delete": {
"tags": ["images"],
@@ -23973,6 +24022,23 @@
"required": ["batch"],
"title": "Body_enqueue_batch"
},
+ "Body_get_gone_images": {
+ "properties": {
+ "image_names": {
+ "items": {
+ "type": "string",
+ "maxLength": 255
+ },
+ "type": "array",
+ "maxItems": 1000,
+ "title": "Image Names",
+ "description": "The names of images to check"
+ }
+ },
+ "type": "object",
+ "required": ["image_names"],
+ "title": "Body_get_gone_images"
+ },
"Body_get_images_by_names": {
"properties": {
"image_names": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index a36060fef6..10a168d170 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -1703,6 +1703,32 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/images/gone": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Get Gone Images
+ * @description Returns the requested names whose image records are positively absent.
+ *
+ * Lets a client whose delete response was lost learn which deletions committed, so it can drop
+ * its references to them. A name is listed only when the record is confirmed missing: a name
+ * that exists (readable by the caller or not) or that storage could not check is left out, so
+ * an unavailable database prunes nothing. Revealing absence matches the 404 the per-image
+ * routes already answer for a gone image (see `_assert_image_record_exists`).
+ */
+ post: operations["get_gone_images"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/images/uncategorized": {
parameters: {
query?: never;
@@ -6970,6 +6996,14 @@ export type components = {
*/
prepend?: boolean;
};
+ /** Body_get_gone_images */
+ Body_get_gone_images: {
+ /**
+ * Image Names
+ * @description The names of images to check
+ */
+ image_names: string[];
+ };
/** Body_get_images_by_names */
Body_get_images_by_names: {
/**
@@ -65822,6 +65856,39 @@ export interface operations {
};
};
};
+ get_gone_images: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["Body_get_gone_images"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": string[];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
delete_uncategorized_images: {
parameters: {
query?: never;
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index 3f7532c056..781477b451 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -579,6 +579,55 @@ describe('deleteGalleryImages partial failures', () => {
failedImageNames: ['locked.png'],
});
});
+
+ it('treats names the server confirms absent as deleted when the delete response is lost', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string) =>
+ url === '/api/v1/images/gone'
+ ? Promise.resolve(['committed.png'])
+ : Promise.reject(new TypeError('Failed to fetch'))
+ );
+
+ await expect(deleteGalleryImages(['committed.png', 'kept.png'])).resolves.toEqual({
+ deletedImageNames: ['committed.png'],
+ failedImageNames: ['kept.png'],
+ });
+ });
+
+ it('keeps the lost response’s error when the server cannot confirm any absence', async () => {
+ const lost = new TypeError('Failed to fetch');
+ mocks.apiFetchJson.mockImplementation((url: string) =>
+ url === '/api/v1/images/gone' ? Promise.resolve([]) : Promise.reject(lost)
+ );
+
+ await expect(deleteGalleryImages(['a.png'])).rejects.toBe(lost);
+
+ mocks.apiFetchJson.mockRejectedValue(lost);
+
+ await expect(deleteGalleryImages(['a.png'])).rejects.toBe(lost);
+ });
+
+ it('reports a whole-batch refusal as is, without asking what is gone', async () => {
+ const refused = new ApiError('{"detail":"Image maintenance is running"}', 409);
+ mocks.apiFetchJson.mockRejectedValue(refused);
+
+ await expect(deleteGalleryImages(['a.png'])).rejects.toBe(refused);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ });
+
+ it('counts names the route skipped as deleted once the server confirms them absent', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string, init: { body: string }) => {
+ if (url === '/api/v1/images/gone') {
+ expect(JSON.parse(init.body)).toEqual({ image_names: ['already-gone.png', 'foreign.png'] });
+ return Promise.resolve(['already-gone.png']);
+ }
+ return Promise.resolve({ affected_boards: [], deleted_images: ['live.png'], failed_images: [] });
+ });
+
+ await expect(deleteGalleryImages(['live.png', 'already-gone.png', 'foreign.png'])).resolves.toEqual({
+ deletedImageNames: ['live.png', 'already-gone.png'],
+ failedImageNames: [],
+ });
+ });
});
describe('name lists past the server’s per-request cap', () => {
@@ -631,7 +680,7 @@ describe('name lists past the server’s per-request cap', () => {
const result = await deleteGalleryImages(requested);
// The third batch is never sent, and the cause is kept in the log.
- expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(mocks.apiFetchJson.mock.calls.filter(([url]) => url === '/api/v1/images/delete')).toHaveLength(2);
expect(getLogSnapshot().entries).toContainEqual(
expect.objectContaining({ level: 'debug', name: 'gallery.batch-request-failed' })
);
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 8d8961c990..3490fbf6f0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -1319,19 +1319,74 @@ export const starGalleryImages = (imageNames: string[], signal?: AbortSignal): P
export const unstarGalleryImages = (imageNames: string[], signal?: AbortSignal): Promise<string[]> =>
setGalleryImageItemsStarred(imageNames, false, signal).then((result) => result.succeededNames);
+/** Names the server positively finds absent; storage errors and existing names are never listed. */
+const findGoneImageNames = async (names: string[], signal?: AbortSignal): Promise<Set<string>> => {
+ if (names.length === 0) {
+ return new Set();
+ }
+
+ const body = await apiFetchJson<unknown>('/api/v1/images/gone', {
+ body: JSON.stringify({ image_names: names }),
+ method: 'POST',
+ signal,
+ });
+
+ signal?.throwIfAborted();
+ return new Set(Array.isArray(body) ? body.filter((name) => typeof name === 'string') : []);
+};
+
+/**
+ * Confirmed-absent names take the normal deletion cleanup, references included, in two cases the delete response
+ * cannot report: a lost response, and names the route skips because they were already gone (deleted by another
+ * session, or by an earlier request whose response was lost), which a retry would otherwise leave failed forever.
+ */
export const deleteGalleryImageItems = (imageNames: string[], signal?: AbortSignal): Promise<GalleryNameBatchResult> =>
mutateInNameBatches(imageNames, signal, async (batch) => {
- const body = await apiFetchJson<unknown>('/api/v1/images/delete', {
- body: JSON.stringify({ image_names: batch }),
- method: 'POST',
- signal,
- });
- signal?.throwIfAborted();
+ let result: GalleryNameBatchResult;
+
+ try {
+ const body = await apiFetchJson<unknown>('/api/v1/images/delete', {
+ body: JSON.stringify({ image_names: batch }),
+ method: 'POST',
+ signal,
+ });
+ signal?.throwIfAborted();
+
+ result = {
+ ...mapGalleryItemOrganizationTransportResult(body, 'deleted_images'),
+ failedNames: getOptionalStringArray(body, 'failed_images'),
+ };
+ } catch (error: unknown) {
+ // A 4xx refused the whole batch, so nothing committed and the server's reason must reach the user.
+ if (signal?.aborted || (error instanceof ApiError && error.status >= 400 && error.status < 500)) {
+ throw error;
+ }
+
+ const gone = await findGoneImageNames(batch, signal).catch(() => new Set<string>());
+
+ if (signal?.aborted || gone.size === 0) {
+ throw error;
+ }
+ batchLogger.debug({
+ context: { gone: gone.size, unconfirmed: batch.length - gone.size },
+ error,
+ message: 'A lost gallery delete response was reconciled against the server',
+ name: 'gallery.delete-response-reconciled',
+ });
+
+ return {
+ affectedBoardIds: [],
+ failedNames: batch.filter((name) => !gone.has(name)),
+ succeededNames: batch.filter((name) => gone.has(name)),
+ };
+ }
+
+ const reported = new Set([...result.succeededNames, ...result.failedNames]);
+ const skipped = batch.filter((name) => !reported.has(name));
+ // An abort here keeps what the delete response already confirmed.
+ const gone = await findGoneImageNames(skipped, signal).catch(() => new Set<string>());
- return {
- ...mapGalleryItemOrganizationTransportResult(body, 'deleted_images'),
- failedNames: getOptionalStringArray(body, 'failed_images'),
- };
+ return { ...result, succeededNames: [...result.succeededNames, ...skipped.filter((name) => gone.has(name))] };
});
/** Evict only deletedImageNames; other names may still exist on the server. */
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
index 78ae21016d..538a1b34a8 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
@@ -210,7 +210,10 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
failed: [imageRef('gone.png'), videoRef('locked.mp4')],
succeeded: [videoRef('gone.mp4')],
});
- expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(mocks.apiFetchJson.mock.calls.map(([url]) => url).filter((url) => url.endsWith('/delete'))).toEqual([
+ '/api/v1/images/delete',
+ '/api/v1/videos/delete',
+ ]);
});
it('moves mixed media to a real board once per deduplicated item and ignores unconfirmed response effects', async () => {
diff --git a/tests/app/routers/test_images.py b/tests/app/routers/test_images.py
index 451adf88ff..5399e1b1b3 100644
--- a/tests/app/routers/test_images.py
+++ b/tests/app/routers/test_images.py
@@ -853,6 +853,7 @@ def test_every_image_names_body_is_bounded(client: TestClient) -> None:
"/api/v1/images/copy",
"/api/v1/images/delete",
"/api/v1/images/download",
+ "/api/v1/images/gone",
"/api/v1/images/images_by_names",
"/api/v1/images/star",
"/api/v1/images/unstar",
@@ -949,3 +950,23 @@ def test_image_workflow_file_missing_answers_404(monkeypatch: Any, mock_invoker:
monkeypatch.setattr(mock_invoker.services.images, "get_workflow", MagicMock(side_effect=ImageFileNotFoundException))
assert client.get("/api/v1/images/i/test.png/workflow").status_code == 404
+
+
+def test_gone_lists_only_positively_absent_names(monkeypatch: Any, mock_invoker: Invoker, client: TestClient) -> None:
+ """A storage error is "could not look", never "gone": it must not prune a client's references."""
+ prepare_image_batch_test(monkeypatch, mock_invoker)
+
+ def exists(image_name: str) -> bool:
+ if image_name == "unreadable.png":
+ raise LockTimeoutError("database is locked")
+ return image_name == "present.png"
+
+ monkeypatch.setattr(mock_invoker.services.image_records, "exists", MagicMock(side_effect=exists))
+
+ response = client.post(
+ "/api/v1/images/gone",
+ json={"image_names": ["present.png", "deleted.png", "unreadable.png", "deleted.png"]},
+ )
+
+ assert response.status_code == 200
+ assert response.json() == ["deleted.png"]