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: harden vocabulary rebuild paths found by adversarial review

Lincoln Steinc8a481c69b6c
diff --git a/invokeai/app/services/image_index/cluster_labels.py b/invokeai/app/services/image_index/cluster_labels.py
index 74cf6acfab..3f9800ef20 100644
--- a/invokeai/app/services/image_index/cluster_labels.py
+++ b/invokeai/app/services/image_index/cluster_labels.py
@@ -52,7 +52,13 @@ def normalize_custom_vocab_terms(raw: list[str]) -> list[str]:
terms: list[str] = []
seen: set[str] = set()
for entry in raw:
- term = " ".join(entry.split()).lower()
+ # Control characters are dropped before the whitespace collapse: they
+ # cannot be part of a meaningful label, and NUL specifically would make
+ # the fingerprint's NUL-joined phrase stream ambiguous — two different
+ # term lists could hash identically and serve each other's cached
+ # embeddings.
+ cleaned = "".join(ch for ch in entry if ch.isprintable() or ch.isspace())
+ term = " ".join(cleaned.split()).lower()
if not term:
continue
if len(term) > MAX_CUSTOM_VOCAB_TERM_LENGTH:
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index f11b362a48..4bcbf3c18c 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -485,7 +485,19 @@ class ImageIndexService(ImageIndexServiceBase):
# truncates this very file on a fingerprint mismatch.
with np.load(cache_path, allow_pickle=False) as cached:
if str(cached["fingerprint"]) == fingerprint:
- return cached["embeddings"].astype(EMBEDDING_DTYPE)
+ embeddings = cached["embeddings"].astype(EMBEDDING_DTYPE)
+
+ # A row-count mismatch means the file does not describe
+ # these phrases no matter what its fingerprint claims
+ # (corruption, or a hash collision) — and it would not
+ # fail here: it row-misaligns the merged matrix, and
+ # label_clusters then indexes past the vocabulary on
+ # every labels request.
+ if embeddings.shape[0] == len(phrases):
+ return embeddings
+ self._invoker.services.logger.warning(
+ f"Discarding cluster vocabulary cache with mismatched row count at {cache_path}"
+ )
except Exception:
self._invoker.services.logger.warning("Discarding unreadable cluster vocabulary cache")
@@ -853,7 +865,19 @@ class ImageIndexService(ImageIndexServiceBase):
with self._vocab_lock:
self._vocab_cache = None
self._vocab_failure = None
- self._build_vocab_embeddings()
+ try:
+ self._build_vocab_embeddings()
+ except Exception:
+ # The build memoizes encoder failures itself; what
+ # raises here is its pre-build state read (the bundled
+ # file, the custom-terms table) — transient-class
+ # failures. Keep the request queued so the next pass
+ # retries it: with the flag already cleared and the
+ # caches dropped, letting it escape would strand the
+ # rebuild in 'idle' with no spinner, no error, and no
+ # retry until something next asks for labels.
+ self._vocab_build_requested.set()
+ raise
continue
projection_job = self._next_projection_job()
if projection_job is not None:
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts
new file mode 100644
index 0000000000..41d49d10a4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.test.ts
@@ -0,0 +1,104 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ apiFetchJson: vi.fn(),
+ refetchClusterLabels: vi.fn(),
+}));
+
+vi.mock('@platform/transport/http', () => ({
+ apiFetchJson: mocks.apiFetchJson,
+}));
+
+vi.mock('./imageMapStore', () => ({
+ refetchClusterLabels: mocks.refetchClusterLabels,
+}));
+
+import { updateImageMapVocab } from './vocabulary';
+
+const backendVocab = (state: string, terms: string[] = ['zebra']) => ({
+ error: null,
+ max_term_length: 64,
+ max_terms: 500,
+ state,
+ terms,
+});
+
+/** Walk the watcher's backed-off poll schedule far enough to cover `polls` iterations. */
+const advancePolls = async (polls: number): Promise<void> => {
+ for (let i = 0; i < polls; i += 1) {
+ // The interval doubles from 2s and caps at 30s; 30s covers every step.
+ await vi.advanceTimersByTimeAsync(30_000);
+ }
+};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.apiFetchJson.mockReset();
+ mocks.refetchClusterLabels.mockReset();
+});
+
+afterEach(async () => {
+ // Let any live watcher observe a terminal state so it cannot leak into the
+ // next test through the module-level dedup flag.
+ mocks.apiFetchJson.mockResolvedValue(backendVocab('ready'));
+ await advancePolls(3);
+ vi.useRealTimers();
+});
+
+describe('updateImageMapVocab rebuild watcher', () => {
+ it('re-fetches map labels once the rebuild lands, even with no component mounted', async () => {
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(backendVocab('building')) // the PUT
+ .mockResolvedValueOnce(backendVocab('building')) // first poll
+ .mockResolvedValueOnce(backendVocab('ready')); // second poll
+
+ const vocab = await updateImageMapVocab(['zebra']);
+
+ expect(vocab.state).toBe('building');
+ expect(mocks.refetchClusterLabels).not.toHaveBeenCalled();
+
+ await advancePolls(2);
+
+ expect(mocks.refetchClusterLabels).toHaveBeenCalledTimes(1);
+ // The polls hit the GET endpoint, not the PUT.
+ expect(mocks.apiFetchJson.mock.calls[1]).toEqual(['/api/v1/image_map/vocab']);
+ });
+
+ it('does not re-fetch labels when the rebuild fails', async () => {
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(backendVocab('building')) // the PUT
+ .mockResolvedValueOnce({ ...backendVocab('error'), error: 'no text encoder' });
+
+ await updateImageMapVocab(['zebra']);
+ await advancePolls(1);
+
+ expect(mocks.refetchClusterLabels).not.toHaveBeenCalled();
+ });
+
+ it('starts no watcher when the save needs no rebuild', async () => {
+ mocks.apiFetchJson.mockResolvedValueOnce(backendVocab('unavailable'));
+
+ await updateImageMapVocab(['zebra']);
+ await advancePolls(1);
+
+ // Only the PUT itself; no polling followed.
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ expect(mocks.refetchClusterLabels).not.toHaveBeenCalled();
+ });
+
+ it('coalesces overlapping saves into one watcher', async () => {
+ mocks.apiFetchJson
+ .mockResolvedValueOnce(backendVocab('building')) // PUT 1
+ .mockResolvedValueOnce(backendVocab('building')) // PUT 2
+ .mockResolvedValue(backendVocab('ready')); // every poll thereafter
+
+ await updateImageMapVocab(['zebra']);
+ await updateImageMapVocab(['zebra', 'okapi']);
+ await advancePolls(2);
+
+ // Two PUTs, one poll: the second save reused the live watcher, which acts
+ // on the final state rather than on which save produced it.
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(3);
+ expect(mocks.refetchClusterLabels).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts
index b7236cfe92..686113e16c 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts
@@ -8,10 +8,16 @@
* always holds the full list, and replace semantics keep the API idempotent.
*/
-import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { apiFetchJson } from '@platform/transport/http';
import { queryOptions } from '@tanstack/react-query';
+import { refetchClusterLabels } from './imageMapStore';
+
/** Mirrors the backend's VocabBuildState literal. */
export type ImageMapVocabState = 'unavailable' | 'idle' | 'building' | 'ready' | 'error';
@@ -69,12 +75,85 @@ export const imageMapVocabQueryOptions = () =>
* Replace the whole term list. The server normalizes (lowercase, collapsed
* whitespace), dedupes, and rejects over-limit input with a 422 whose detail
* names the offending term; the response carries the stored list.
+ *
+ * When the response reports a background embedding rebuild, a module-level
+ * watcher is started so any open map's labels are re-fetched when it lands —
+ * a vocabulary edit changes what the labels say without moving a single
+ * point, so nothing in the map's own flow would notice, and the watcher must
+ * outlive the settings dialog the save was made from.
*/
export const updateImageMapVocab = async (terms: string[]): Promise<ImageMapVocab> => {
const body = await apiFetchJson<BackendImageMapVocabResponse>('/api/v1/image_map/vocab', {
body: JSON.stringify({ terms }),
method: 'PUT',
});
+ const vocab = mapVocab(body);
+
+ if (vocab.state === 'building') {
+ watchRebuild();
+ }
+
+ return vocab;
+};
+
+// The rebuild usually lands in seconds, but the index worker parks during
+// generations, so it can also take a long while: back the poll off rather
+// than holding a 2s cadence indefinitely.
+const REBUILD_POLL_MIN_MS = 2_000;
+const REBUILD_POLL_MAX_MS = 30_000;
+
+let rebuildWatchActive = false;
+
+const delay = (ms: number): Promise<void> =>
+ new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
+
+const watchRebuild = (): void => {
+ // One watcher covers every save it overlaps: it acts on the final state,
+ // not on which save produced it.
+ if (rebuildWatchActive) {
+ return;
+ }
- return mapVocab(body);
+ rebuildWatchActive = true;
+ const owner = captureAccountScope();
+
+ void (async () => {
+ try {
+ let interval = REBUILD_POLL_MIN_MS;
+
+ for (;;) {
+ await delay(interval);
+ interval = Math.min(interval * 2, REBUILD_POLL_MAX_MS);
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ const body = await apiFetchJson<BackendImageMapVocabResponse>('/api/v1/image_map/vocab');
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ if (body.state === 'building') {
+ continue;
+ }
+
+ if (body.state === 'ready') {
+ refetchClusterLabels();
+ }
+
+ // 'error', 'unavailable', and 'idle' all mean no new labels are
+ // coming from this rebuild; the settings UI reports those itself.
+ return;
+ }
+ } catch {
+ // Label refresh is best-effort decoration; the next points refresh
+ // fetches labels anyway.
+ } finally {
+ rebuildWatchActive = false;
+ }
+ })();
};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx
index 69a3648db5..0019ccac93 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx
@@ -10,7 +10,6 @@ import { userEvent } from 'vitest/browser';
const mocks = vi.hoisted(() => ({
canManage: true,
- refetchClusterLabels: vi.fn(),
updateImageMapVocab: vi.fn((_terms: string[]) => Promise.resolve(null as unknown as ImageMapVocab)),
vocab: null as ImageMapVocab | null,
}));
@@ -19,10 +18,6 @@ vi.mock('@features/identity', () => ({
useCapabilities: () => ({ canManageImageMapVocabulary: mocks.canManage }),
}));
-vi.mock('@workbench/image-map/imageMapStore', () => ({
- refetchClusterLabels: () => mocks.refetchClusterLabels(),
-}));
-
vi.mock('@workbench/image-map/vocabulary', () => ({
imageMapVocabKeys: { all: ['image-map', 'vocab'] },
imageMapVocabQueryOptions: () => ({
@@ -103,7 +98,6 @@ const chipCloseTriggers = (): HTMLElement[] =>
beforeEach(() => {
mocks.canManage = true;
- mocks.refetchClusterLabels.mockClear();
mocks.updateImageMapVocab.mockClear();
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
host = document.createElement('div');
@@ -192,22 +186,31 @@ describe('ImageMapVocabularySettings', () => {
expect(chipCloseTriggers()).toHaveLength(0);
});
- it('re-fetches any open map labels when the rebuild lands', async () => {
- await render({ state: 'building', terms: ['zebra'] });
+ it('surfaces a failed embedding build with its message and offers a retry', async () => {
+ mocks.updateImageMapVocab.mockImplementation((terms: string[]) =>
+ Promise.resolve({ ...BASE_VOCAB, state: 'building' as const, terms })
+ );
+ await render({ error: 'no text encoder installed', state: 'error', terms: ['zebra'] });
+
+ expect(host?.textContent).toContain('The vocabulary could not be prepared: no text encoder installed');
- expect(mocks.refetchClusterLabels).not.toHaveBeenCalled();
+ const retry = Array.from(host!.querySelectorAll('button')).find((button) => button.textContent === 'Retry');
- await act(async () => {
- queryClient!.setQueryData(['image-map', 'vocab'], { ...BASE_VOCAB, state: 'ready', terms: ['zebra'] });
- await Promise.resolve();
- });
+ await userEvent.click(retry!);
+ await flushQueries();
- expect(mocks.refetchClusterLabels).toHaveBeenCalledTimes(1);
+ // Re-saving the same list is the retry path: it re-triggers the
+ // server-side invalidation that clears the memoized failure.
+ expect(mocks.updateImageMapVocab).toHaveBeenCalledWith(['zebra']);
});
- it('surfaces a failed embedding build with its message', async () => {
- await render({ error: 'no text encoder installed', state: 'error' });
+ it('hides the retry affordance from a non-admin', async () => {
+ mocks.canManage = false;
+ await render({ error: 'no text encoder installed', state: 'error', terms: ['zebra'] });
expect(host?.textContent).toContain('The vocabulary could not be prepared: no text encoder installed');
+ expect(
+ Array.from(host!.querySelectorAll('button')).find((button) => button.textContent === 'Retry')
+ ).toBeUndefined();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
index 6b8a6d74c2..e7896a2134 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
@@ -8,10 +8,9 @@ import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
import { Button, Field } from '@platform/ui';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { refetchClusterLabels } from '@workbench/image-map/imageMapStore';
import { imageMapVocabKeys, imageMapVocabQueryOptions, updateImageMapVocab } from '@workbench/image-map/vocabulary';
import { PlusIcon } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
/**
@@ -41,7 +40,9 @@ const parseDraft = (draft: string): string[] => {
* Editor for the supplementary cluster-label vocabulary. Each add/remove
* persists immediately (the whole list is replaced server-side); after a save
* the server rebuilds the label embeddings in the background, so the query
- * polls while that runs and re-fetches any open map's labels when it lands.
+ * polls while that runs to keep the status line honest. Re-fetching an open
+ * map's labels when the rebuild lands is NOT this component's job — the data
+ * module's watcher does it, because the dialog may well be closed by then.
*/
export const ImageMapVocabularySettings = () => {
const { t } = useTranslation();
@@ -56,20 +57,6 @@ export const ImageMapVocabularySettings = () => {
const [saveError, setSaveError] = useState<string | null>(null);
const { isBusy: isSaving, run } = useScopedAction();
- // A vocabulary edit changes what the labels say without moving a single
- // point, so nothing in the map's own flow would re-fetch them: do it here,
- // on the rebuild's building -> ready edge.
- const buildState = query.data?.state;
- const previousBuildState = useRef(buildState);
-
- useEffect(() => {
- if (previousBuildState.current === 'building' && buildState === 'ready') {
- refetchClusterLabels();
- }
-
- previousBuildState.current = buildState;
- }, [buildState]);
-
const persist = (nextTerms: string[]): Promise<boolean> => {
setSaveError(null);
@@ -77,6 +64,13 @@ export const ImageMapVocabularySettings = () => {
async (owner) => {
const updated = await updateImageMapVocab(nextTerms);
+ assertAccountScopeCurrent(owner);
+ // Cancel first: a poll that was issued before the PUT can resolve
+ // after it, and TanStack Query would write that older list over the
+ // response — resurrecting a removed chip and, worse, overwriting
+ // 'building' with a stale 'ready' so the status line goes quiet while
+ // the server is still rebuilding.
+ await queryClient.cancelQueries({ queryKey: imageMapVocabKeys.all });
assertAccountScopeCurrent(owner);
queryClient.setQueryData(imageMapVocabKeys.all, updated);
},
@@ -217,6 +211,10 @@ export const ImageMapVocabularySettings = () => {
<Tag.EndElement>
<Tag.CloseTrigger
aria-label={t('settings.imageMapVocabulary.removeTerm', { term })}
+ // Disabled while a save is in flight: the busy guard would
+ // silently drop a second removal, resurrecting the chip
+ // with no feedback.
+ disabled={isSaving}
onClick={() => {
void persist(vocab.terms.filter((existing) => existing !== term));
}}
@@ -231,12 +229,23 @@ export const ImageMapVocabularySettings = () => {
{t('settings.imageMapVocabulary.noTermsYet')}
</Text>
)}
- <VocabularyStatusLine vocab={vocab} />
+ <VocabularyStatusLine
+ vocab={vocab}
+ onRetry={
+ canManageImageMapVocabulary
+ ? () => {
+ // Re-saving the same list re-triggers the invalidation, which
+ // is the server's retry path for a failed embedding build.
+ void persist(vocab.terms);
+ }
+ : undefined
+ }
+ />
</Stack>
);
};
-const VocabularyStatusLine = ({ vocab }: { vocab: ImageMapVocab }) => {
+const VocabularyStatusLine = ({ onRetry, vocab }: { onRetry?: () => void; vocab: ImageMapVocab }) => {
const { t } = useTranslation();
return (
@@ -253,9 +262,16 @@ const VocabularyStatusLine = ({ vocab }: { vocab: ImageMapVocab }) => {
</HStack>
) : null}
{vocab.state === 'error' && vocab.error ? (
- <Text color="fg.error" fontSize="2xs" role="alert">
- {t('settings.imageMapVocabulary.buildFailed', { message: vocab.error })}
- </Text>
+ <HStack gap="2">
+ <Text color="fg.error" fontSize="2xs" role="alert">
+ {t('settings.imageMapVocabulary.buildFailed', { message: vocab.error })}
+ </Text>
+ {onRetry ? (
+ <Button size="2xs" variant="outline" onClick={onRetry}>
+ {t('common.retry')}
+ </Button>
+ ) : null}
+ </HStack>
) : null}
{vocab.state === 'unavailable' ? (
<Text color="fg.subtle" fontSize="2xs">
diff --git a/tests/app/services/image_index/test_cluster_labels.py b/tests/app/services/image_index/test_cluster_labels.py
index a740b32e77..46b7d48bd4 100644
--- a/tests/app/services/image_index/test_cluster_labels.py
+++ b/tests/app/services/image_index/test_cluster_labels.py
@@ -27,6 +27,14 @@ def test_normalize_custom_vocab_terms_lowercases_collapses_and_dedupes() -> None
assert normalized == ["golden retriever", "zebra"]
+def test_normalize_custom_vocab_terms_strips_control_characters() -> None:
+ # A NUL inside a term would make the fingerprint's NUL-joined phrase
+ # stream ambiguous: vocab_fingerprint(["cat", "dog"]) equals
+ # vocab_fingerprint(["cat\x00dog"]), so two different term lists could
+ # serve each other's cached embeddings.
+ assert normalize_custom_vocab_terms(["cat\x00dog", "tab\there"]) == ["catdog", "tab here"]
+
+
def test_normalize_custom_vocab_terms_rejects_an_overlong_term() -> None:
# Rejected rather than truncated: a silently shortened phrase would embed
# as something the user never wrote.
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 20ccddc664..cbd59556ee 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -2259,3 +2259,66 @@ def test_invalidate_vocab_retries_a_failed_build(
_wait_until(lambda: service.get_vocab_build_state() == ("ready", None))
assert service.get_vocab_embeddings()[0] == ["a cat"]
+
+
+def test_a_cache_with_a_mismatched_row_count_is_discarded_and_re_embedded(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The fingerprint alone cannot be trusted to prove the file describes these
+ # phrases (corruption, hash collision): a wrong row count would misalign
+ # the merged matrix and break every labels request.
+ from invokeai.app.services.image_index.cluster_labels import vocab_fingerprint
+
+ service = _vocab_service_with_custom_terms(tmp_path, monkeypatch, ["okapi"])
+ tag = MODEL_ID.replace(":", "_")[:24]
+ custom_cache = tmp_path / f"cluster_vocab_custom_{tag}.npz"
+ np.savez(
+ custom_cache,
+ embeddings=np.zeros((2, DIM), dtype=EMBEDDING_DTYPE),
+ fingerprint=np.str_(vocab_fingerprint(["okapi"])),
+ )
+
+ service._build_vocab_embeddings()
+
+ assert service._vocab_cache is not None
+ vocabulary, matrix = service._vocab_cache
+ assert vocabulary == ["a cat", "a dog", "a car", "okapi"]
+ assert matrix.shape == (4, DIM)
+ # Re-embedded, not served from the bogus file.
+ assert np.array_equal(matrix[3], np.full(DIM, float(len("okapi")), dtype=EMBEDDING_DTYPE))
+
+
+def test_a_transient_custom_terms_read_failure_keeps_the_rebuild_queued(
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ tmp_path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The worker clears the request flag and drops the caches before the build
+ # reads its state; a transient DB failure there must not strand the
+ # rebuild in 'idle' — the flag is re-set so the next pass retries.
+ from invokeai.app.services.image_index import cluster_labels
+
+ monkeypatch.setattr(cluster_labels, "load_vocabulary", lambda: ["a cat"])
+ monkeypatch.setattr(cluster_labels, "ensemble_phrase_embeddings", lambda embed_fn, phrases: _phrase_matrix(phrases))
+ monkeypatch.setattr(InvokeAIAppConfig, "db_path", property(lambda self: tmp_path / "invokeai.db"))
+ index_records.set_custom_vocab_terms(["dog"])
+
+ calls = {"count": 0}
+ original_read = index_records.get_custom_vocab_terms
+
+ def _flaky() -> list[str]:
+ calls["count"] += 1
+ if calls["count"] == 1:
+ raise RuntimeError("simulated: database is locked")
+ return original_read()
+
+ monkeypatch.setattr(index_records, "get_custom_vocab_terms", _flaky)
+
+ service.start(_make_invoker(images_service, index_records))
+ service.invalidate_vocab()
+
+ _wait_until(lambda: service.get_vocab_build_state() == ("ready", None), timeout=15)
+ assert calls["count"] >= 2
+ assert service.get_vocab_embeddings()[0] == ["a cat", "dog"]