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(image-map): retry cluster labels through the vocabulary-build window

Lincoln Stein3f9b49d29a8c
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
index e8a10f228f..342416b72a 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
@@ -1,10 +1,20 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ ApiError: class ApiError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = 'ApiError';
+ this.status = status;
+ }
+ },
apiFetchJson: vi.fn(),
}));
vi.mock('@platform/transport/http', () => ({
+ ApiError: mocks.ApiError,
apiFetchJson: mocks.apiFetchJson,
getApiErrorMessage: (_error: unknown, fallback: string) => fallback,
}));
@@ -39,6 +49,21 @@ const BACKEND_RESPONSE = {
visible_hash: 'hash-1',
};
+// A labels response stamped for some other projection, which the store must
+// discard. Tests that exercise the points/status flows answer labels requests
+// with this: a body without a `labels` key throws a TypeError in the api
+// mapping, which the store classifies as a network failure and retries —
+// arming a real-timer chain that outlives the test.
+const FOREIGN_LABELS_RESPONSE = { labels: {}, updated_at: 'another projection', visible_hash: 'another set' };
+
+const mockPointsWithForeignLabels = (): void => {
+ mocks.apiFetchJson.mockImplementation((url: string) =>
+ url.startsWith('/api/v1/image_map/cluster_labels')
+ ? Promise.resolve(FOREIGN_LABELS_RESPONSE)
+ : Promise.resolve(BACKEND_RESPONSE)
+ );
+};
+
describe('image map api', () => {
beforeEach(() => {
mocks.apiFetchJson.mockReset();
@@ -104,8 +129,13 @@ describe('image map store', () => {
});
});
+ // Retry-schedule tests fake the clock; restore it whatever their outcome.
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
it('loads points into the snapshot', async () => {
- mocks.apiFetchJson.mockResolvedValue(BACKEND_RESPONSE);
+ mockPointsWithForeignLabels();
await refreshImageMapPoints();
@@ -244,8 +274,191 @@ describe('image map store', () => {
expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': { alternates: [], label: 'cats' } });
});
+ it('retries a labels request that raced the vocabulary build', async () => {
+ vi.useFakeTimers();
+ // After a backend restart the vocabulary embeddings are not in memory
+ // yet: the first labels request 409s while the index worker builds them.
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.reject(new mocks.ApiError('Cluster labels are still being prepared; try again shortly', 409));
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(imageMapStore.getSnapshot().clusterLabels).toBeNull();
+
+ // The build lands; the retry succeeds and the labels appear.
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.resolve({
+ labels: { '0': { label: 'cats' } },
+ updated_at: BACKEND_RESPONSE.updated_at,
+ visible_hash: BACKEND_RESPONSE.visible_hash,
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(3);
+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': { alternates: [], label: 'cats' } });
+ });
+
+ it('retires a pending retry when a newer labels request takes over', async () => {
+ vi.useFakeTimers();
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.reject(new mocks.ApiError('Cluster labels are still being prepared; try again shortly', 409));
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+ await vi.advanceTimersByTimeAsync(0);
+
+ // A newer refresh supersedes the failing chain and resolves its own labels.
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.resolve({
+ labels: { '0': { label: 'cats' } },
+ updated_at: BACKEND_RESPONSE.updated_at,
+ visible_hash: BACKEND_RESPONSE.visible_hash,
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': { alternates: [], label: 'cats' } });
+
+ // The first chain's retry timer fires: it must neither re-request nor
+ // disturb the newer chain's labels.
+ const callsBeforeRetry = mocks.apiFetchJson.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(mocks.apiFetchJson.mock.calls.length).toBe(callsBeforeRetry);
+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': { alternates: [], label: 'cats' } });
+ });
+
+ it('does not retry a labels failure the client cannot outwait', async () => {
+ vi.useFakeTimers();
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.reject(new mocks.ApiError('Forbidden', 403));
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+ await vi.advanceTimersByTimeAsync(300_000);
+
+ // One points fetch, one labels attempt, nothing after.
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(imageMapStore.getSnapshot().clusterLabels).toBeNull();
+ });
+
+ it('gives up on a persistently unavailable vocabulary after the schedule', async () => {
+ vi.useFakeTimers();
+ const labelsCalls = (): number =>
+ mocks.apiFetchJson.mock.calls.filter((call: unknown[]) =>
+ String(call[0]).startsWith('/api/v1/image_map/cluster_labels')
+ ).length;
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.reject(new mocks.ApiError('Cluster labels are still being prepared; try again shortly', 409));
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+ // The whole backoff schedule: 9 retries after the first attempt.
+ await vi.advanceTimersByTimeAsync(300_000);
+
+ expect(labelsCalls()).toBe(10);
+ expect(imageMapStore.getSnapshot().clusterLabels).toBeNull();
+ });
+
+ it('retries a labels request that failed at the network layer', async () => {
+ vi.useFakeTimers();
+ // fetch() rejects with a bare TypeError when the request never reaches a
+ // server — a backend restarting under an open map, say.
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.reject(new TypeError('Failed to fetch'));
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(imageMapStore.getSnapshot().clusterLabels).toBeNull();
+
+ // The backend comes back; the retry succeeds and the labels appear.
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.resolve({
+ labels: { '0': { label: 'cats' } },
+ updated_at: BACKEND_RESPONSE.updated_at,
+ visible_hash: BACKEND_RESPONSE.visible_hash,
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': { alternates: [], label: 'cats' } });
+ });
+
+ it('clears labels when the newest request fails outright', async () => {
+ // L1 lands labels; L2's request then fails with its sequence still
+ // current — the failure must wipe them rather than leave L1's clustering
+ // annotated over the newer point set. (L2's failure is a plain Error:
+ // non-retryable, so no timer is armed either.)
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.resolve({
+ labels: { '0': { label: 'cats' } },
+ updated_at: BACKEND_RESPONSE.updated_at,
+ visible_hash: BACKEND_RESPONSE.visible_hash,
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+ await refreshImageMapPoints();
+ await vi.waitFor(() => {
+ expect(imageMapStore.getSnapshot().clusterLabels).not.toBeNull();
+ });
+
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.reject(new Error('boom'));
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+ await refreshImageMapPoints();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ expect(imageMapStore.getSnapshot().clusterLabels).toBeNull();
+ });
+
it('records errors and keeps prior data', async () => {
- mocks.apiFetchJson.mockResolvedValue(BACKEND_RESPONSE);
+ mockPointsWithForeignLabels();
await refreshImageMapPoints();
mocks.apiFetchJson.mockRejectedValue(new Error('boom'));
@@ -376,6 +589,9 @@ describe('snapshot transitions', () => {
state: 'ready',
updated_at: null,
});
+ // The labels request this refresh fires must not hit the exhausted
+ // once-queue (an undefined body arms a retry timer — see above).
+ mocks.apiFetchJson.mockResolvedValueOnce(FOREIGN_LABELS_RESPONSE);
await refreshImageMapPoints();
@@ -473,11 +689,15 @@ describe('image index progress', () => {
it('seeds the counts from the status endpoint when the map first loads', async () => {
// Status events only fire as batches complete, so a panel opened while the
// worker is parked behind a generation would otherwise show no progress.
- mocks.apiFetchJson.mockImplementation((url: string) =>
- url.startsWith('/api/v1/image_map/status')
- ? Promise.resolve({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } })
- : Promise.resolve(BACKEND_RESPONSE)
- );
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/status')) {
+ return Promise.resolve({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });
+ }
+
+ return url.startsWith('/api/v1/image_map/cluster_labels')
+ ? Promise.resolve(FOREIGN_LABELS_RESPONSE)
+ : Promise.resolve(BACKEND_RESPONSE);
+ });
ensureImageMapLoaded();
@@ -487,13 +707,17 @@ describe('image index progress', () => {
it('does not let a slow seed rewind counts a status event already delivered', async () => {
let resolveStatus: (value: unknown) => void = () => {};
- mocks.apiFetchJson.mockImplementation((url: string) =>
- url.startsWith('/api/v1/image_map/status')
- ? new Promise((resolve) => {
- resolveStatus = resolve;
- })
- : Promise.resolve(BACKEND_RESPONSE)
- );
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/status')) {
+ return new Promise((resolve) => {
+ resolveStatus = resolve;
+ });
+ }
+
+ return url.startsWith('/api/v1/image_map/cluster_labels')
+ ? Promise.resolve(FOREIGN_LABELS_RESPONSE)
+ : Promise.resolve(BACKEND_RESPONSE);
+ });
ensureImageMapLoaded();
recordImageIndexStatus({ embedded: 90, failed: 0, pending: 10, total: 100 }, 1_000);
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
index 5e806516f3..ee2508711a 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
@@ -4,7 +4,7 @@ import {
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
-import { getApiErrorMessage } from '@platform/transport/http';
+import { ApiError, getApiErrorMessage } from '@platform/transport/http';
import type { ImageMapClusterLabelInfo, ImageMapPoints } from './api';
import type { ImageIndexCounts } from './indexProgress';
@@ -210,23 +210,39 @@ export const setClusterLabelsEnabled = (enabled: boolean): void => {
}
};
-const refreshClusterLabels = (data: ImageMapPoints): void => {
- if (!clusterLabelsEnabled) {
- return;
- }
-
- if (data.state !== 'ready') {
- // Nothing to label; a disabled index would 409 on every refresh. Bump the
- // sequence so an in-flight labels response cannot repopulate the labels
- // this clears.
- labelsSequence += 1;
- imageMapStore.patchSnapshot({ clusterLabels: null, clusterLabelsHash: null });
+/**
+ * Backoff for a labels request the server could not answer yet. The 409 the
+ * vocabulary build window answers with literally says "try again shortly":
+ * the build is already queued server-side the moment that response is sent,
+ * and the index worker lands it within seconds (a 1s poll, plus a disk-cached
+ * phrase matrix). The schedule's tail covers a cold build — minutes on a
+ * fresh install — while staying bounded; after it exhausts, the state is the
+ * old one: no labels until the next points refresh or the label toggle.
+ */
+const LABELS_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 60_000, 60_000, 60_000];
- return;
+/**
+ * Failures worth retrying: the 409s (`TextSearchUnavailableError` — the
+ * vocabulary still building, or the text tower absent), 5xx, and the network
+ * refusal of a restarting backend (`fetch` rejects with TypeError). Auth and
+ * contract failures (401, 403, 422) are permanent from this client's side and
+ * settle on the first response.
+ */
+const isRetryableLabelsFailure = (error: unknown): boolean => {
+ if (error instanceof ApiError) {
+ return error.status === 409 || error.status >= 500;
}
- labelsSequence += 1;
- const sequence = labelsSequence;
+ return error instanceof TypeError;
+};
+
+/**
+ * One attempt of the labels fetch, retrying retryable failures on the
+ * schedule above. The `sequence` is the guard every deferred step re-checks:
+ * a newer labels request, the label toggle, or an account switch bumps it and
+ * retires this attempt's callbacks outright.
+ */
+const attemptClusterLabels = (sequence: number, data: ImageMapPoints, attempt: number): void => {
// Pass the points' effective eps so both requests cluster with the same
// value — the adaptive default is derived from the visible set, which can
// drift between the two requests. Same eps alone does not pin cluster ids
@@ -247,16 +263,54 @@ const refreshClusterLabels = (data: ImageMapPoints): void => {
imageMapStore.patchSnapshot({ clusterLabels: response.labels, clusterLabelsHash: response.visibleHash });
}
})
- .catch(() => {
+ .catch((error: unknown) => {
// Same staleness rule as success: only the newest request may clear the
// labels. A slow stale request failing after a newer one already set
// fresh labels must not wipe them.
- if (sequence === labelsSequence) {
- imageMapStore.patchSnapshot({ clusterLabels: null, clusterLabelsHash: null });
+ if (sequence !== labelsSequence) {
+ return;
}
+
+ imageMapStore.patchSnapshot({ clusterLabels: null, clusterLabelsHash: null });
+
+ if (attempt >= LABELS_RETRY_DELAYS_MS.length || !isRetryableLabelsFailure(error)) {
+ return;
+ }
+
+ // Nothing else re-requests labels on its own: a plain widget activation
+ // fetches no points (the store is already loaded), and the next socket
+ // event can be minutes away. Without this retry, one 409 in the
+ // vocabulary-build window after a backend restart leaves the map
+ // label-less until the user toggles labels off and back on.
+ const delay = LABELS_RETRY_DELAYS_MS[attempt];
+ setTimeout(() => {
+ if (sequence === labelsSequence) {
+ attemptClusterLabels(sequence, data, attempt + 1);
+ }
+ }, delay);
});
};
+const refreshClusterLabels = (data: ImageMapPoints): void => {
+ if (!clusterLabelsEnabled) {
+ return;
+ }
+
+ if (data.state !== 'ready') {
+ // Nothing to label; a disabled index would 409 on every refresh. Bump the
+ // sequence so an in-flight labels response cannot repopulate the labels
+ // this clears.
+ labelsSequence += 1;
+ imageMapStore.patchSnapshot({ clusterLabels: null, clusterLabelsHash: null });
+
+ return;
+ }
+
+ labelsSequence += 1;
+ const sequence = labelsSequence;
+ attemptClusterLabels(sequence, data, 0);
+};
+
/**
* Re-fetch labels for the currently loaded points. For callers outside the
* points-refresh flow whose action changes what the labels *say* without