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): cool down automatic projection refits (#10129)

Lincoln Stein08b39d554a78
diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.py
index 1d55931b14..8237e7e37d 100644
--- a/invokeai/app/services/image_index/image_index_base.py
+++ b/invokeai/app/services/image_index/image_index_base.py
@@ -179,6 +179,11 @@ class ImageIndexServiceBase(ABC):
pending embedding work, and an `image_map_projection_ready` event is
emitted when the cache is updated.
+ A refit of a scope that was fit before waits out a cooldown measured
+ from that fit (a floor, or a multiple of how long the fit took), so a
+ busy server cannot keep the worker refitting one scope back to back.
+ The request stays queued meanwhile.
+
Args:
user_id: The user whose projection cache to update.
all_images: Compute over every embedded item (admin scope)
@@ -189,8 +194,10 @@ class ImageIndexServiceBase(ABC):
every poll cannot drive an endless request/event cycle.
user_initiated: This request came from a person rather than from
polling, so a spent retry budget is cleared and the failed
- scope gets another fit. Callers driven by a timer, an event, or
- a staleness check must leave this False.
+ scope gets another fit, and the refit cooldown is bypassed.
+ Pass it only for a person's explicit request: callers driven by
+ a timer, an event, or a staleness check must leave this False,
+ or every fit would chain straight into the next (#9635).
Returns:
True if the request was accepted (or already pending); False if
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index b74dbb6816..f83fa29722 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -80,6 +80,14 @@ _MAX_BACKOFF_SECONDS = 60.0
# everything in between, at one rebuild attempt per window rather than one per points refresh.
_VOCAB_FAILURE_RETRY_SECONDS = 600.0
+# A refit nobody asked for (a /points staleness check) waits this long after the scope's last fit:
+# the floor, or the multiplier times that fit's duration. On a busy server something embeds during
+# almost every fit, so without it one scope refits back to back forever; the multiplier caps it at
+# about a third of the worker's time. The floor stays short because a small gallery's map waits
+# it out after every generation. /refresh is exempt.
+_PROJECTION_REFIT_COOLDOWN_FLOOR_SECONDS = 10.0
+_PROJECTION_REFIT_COOLDOWN_MULTIPLIER = 2.0
+
def _normalize_query_vector(vector: np.ndarray) -> np.ndarray:
"""L2-normalize one query embedding, refusing anything that would poison a search.
@@ -283,6 +291,12 @@ class ImageIndexService(ImageIndexServiceBase):
# user_id -> the scope hash whose failed fit has already been retried
# this process; see _failed_scope_retry_available.
self._failed_projection_scopes: dict[str, str] = {}
+ # user_id -> time.monotonic() before which a queued request for that
+ # scope may not start a fit; set once a fit's result is cached.
+ self._projection_not_before: dict[str, float] = {}
+ # Users whose queued request came from a person (/refresh). Kept apart
+ # from _projection_requests so a later poll cannot downgrade it.
+ self._projection_user_initiated: set[str] = set()
self._projection_lock = threading.Lock()
self._invoker: Optional["Invoker"] = None
@@ -796,6 +810,7 @@ class ImageIndexService(ImageIndexServiceBase):
# and is driven by polling, so clearing there would hand a
# poller the unlimited retries the budget exists to deny.
self._failed_projection_scopes.pop(user_id, None)
+ self._projection_user_initiated.add(user_id)
# Last writer wins: the scope reflects the requester's most recent
# admin status, so a promotion/demotion between requests cannot
# pin a stale scope.
@@ -820,6 +835,8 @@ class ImageIndexService(ImageIndexServiceBase):
with self._projection_lock:
self._failed_projection_scopes.clear()
self._projection_requests.clear()
+ self._projection_not_before.clear()
+ self._projection_user_initiated.clear()
device_override = config.image_index_device
if device_override and not _is_cpu_override(device_override):
@@ -1020,6 +1037,8 @@ class ImageIndexService(ImageIndexServiceBase):
with self._projection_lock:
self._projection_requests.clear()
self._failed_projection_scopes.clear()
+ self._projection_not_before.clear()
+ self._projection_user_initiated.clear()
self._attempts.clear()
self._failed.clear()
self._pending_pokes.clear()
@@ -1602,11 +1621,17 @@ class ImageIndexService(ImageIndexServiceBase):
return self._failed_projection_scopes.get(user_id) != current_hash
def _next_projection_job(self) -> Optional[tuple[str, bool]]:
+ """Take the first queued job that is not cooling down; jobs that are stay queued (/points still reports them
+ stale) and are taken once due."""
+ now = time.monotonic()
with self._projection_lock:
- if not self._projection_requests:
- return None
- user_id = next(iter(self._projection_requests))
- return user_id, self._projection_requests.pop(user_id)
+ for user_id in self._projection_requests:
+ if user_id in self._projection_user_initiated or now >= self._projection_not_before.get(user_id, now):
+ # The cooldown stays: a taken job that short-circuits on an
+ # unchanged scope must not free the next poll to refit.
+ self._projection_user_initiated.discard(user_id)
+ return user_id, self._projection_requests.pop(user_id)
+ return None
def _process_projection(self, user_id: str, all_images: bool) -> None:
assert self._invoker is not None
@@ -1661,6 +1686,7 @@ class ImageIndexService(ImageIndexServiceBase):
)
return
+ fit_started = time.monotonic()
try:
# Read after the short-circuit, not before: this materializes every
# accessible embedding (hundreds of MB on a large gallery), which is
@@ -1698,6 +1724,7 @@ class ImageIndexService(ImageIndexServiceBase):
# per process, and the next gallery change flips the hash anyway.
found_items = []
coords = np.empty((0, 2), dtype=EMBEDDING_DTYPE)
+ fit_finished = time.monotonic()
# Hash the scope the projection was computed against (on failure the
# empty cache still claims the current scope, so staleness detection —
@@ -1740,6 +1767,10 @@ class ImageIndexService(ImageIndexServiceBase):
self._failed_projection_scopes.pop(user_id, None)
elif retrying_failed_scope:
self._failed_projection_scopes[user_id] = current_hash
+ self._projection_not_before[user_id] = fit_finished + max(
+ _PROJECTION_REFIT_COOLDOWN_FLOOR_SECONDS,
+ _PROJECTION_REFIT_COOLDOWN_MULTIPLIER * (fit_finished - fit_started),
+ )
try:
self._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=len(found_items))
except Exception:
@@ -1762,9 +1793,13 @@ class ImageIndexService(ImageIndexServiceBase):
self._invoker.services.events.emit_image_map_projection_ready(user_id=user_id, point_count=point_count)
def _requeue_projection(self, user_id: str, all_images: bool) -> None:
- """Put a popped job back, without clobbering a newer request for that user."""
+ """Put a popped job back, without clobbering a newer request for that user.
+
+ The cooldown is dropped so the retry is immediate: every caller's fit either never ran or its result was not
+ cached, and a user-initiated job lost its exemption when it was taken."""
with self._projection_lock:
self._projection_requests.setdefault(user_id, all_images)
+ self._projection_not_before.pop(user_id, None)
def _wait_for_idle_generation(self) -> None:
"""Block until no generation is in progress, unless embedding on CPU.
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 adf13274ac..df6230ba6e 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
@@ -32,6 +32,7 @@ import {
recordImageIndexStatus,
refreshImageIndexStatus,
refreshImageMapPoints,
+ requestImageMapRecompute,
setClusterEps,
attachImageMapViewer,
setImageMapMediaKind,
@@ -741,6 +742,37 @@ describe('image map store', () => {
expect(imageMapStore.getSnapshot().loadState).toBe('loaded');
});
+ it('asks for a refit and fetches the points when a person requests a fresh map', async () => {
+ mockPointsWithForeignLabels();
+
+ await requestImageMapRecompute();
+
+ const calls = mocks.apiFetchJson.mock.calls;
+
+ expect(calls).toContainEqual(['/api/v1/image_map/refresh', { method: 'POST' }]);
+ expect(calls.some((call) => String(call[0]).startsWith('/api/v1/image_map/points'))).toBe(true);
+ expect(imageMapStore.getSnapshot().loadState).toBe('loaded');
+ });
+
+ it('still fetches the points when the refit request fails, and keeps that failure out of the store', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url === '/api/v1/image_map/refresh') {
+ return Promise.reject(new Error('refresh failed'));
+ }
+
+ return Promise.resolve(url.startsWith('/api/v1/image_map/points') ? BACKEND_RESPONSE : FOREIGN_LABELS_RESPONSE);
+ });
+
+ await requestImageMapRecompute();
+ // Vitest fails the run on an unhandled rejection, which Node reports once the microtask queue drains.
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ expect(imageMapStore.getSnapshot()).toMatchObject({ error: null, loadState: 'loaded' });
+ expect(imageMapStore.getSnapshot().data?.pointCount).toBe(BACKEND_RESPONSE.point_count);
+ });
+
it('still runs the queued rerun when the in-flight fetch fails', async () => {
// A refresh admitted during 'loading' must not be lost to the first fetch
// failing: the rerun runs anyway and can still recover the map.
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
index 719ab6f50c..a02e01d327 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
@@ -11,7 +11,7 @@ import { ApiError, getApiErrorMessage } from '@platform/transport/http';
import type { ImageMapClusterLabelInfo, ImageMapPoints } from './api';
import type { ImageIndexCounts } from './indexProgress';
-import { fetchImageMapClusterLabels, fetchImageMapPoints, fetchImageMapStatus } from './api';
+import { fetchImageMapClusterLabels, fetchImageMapPoints, fetchImageMapStatus, requestImageMapRefresh } from './api';
import { hasProgressed } from './indexProgress';
/** Shared image-map read model with one in-flight fetch and refreshes from user actions and socket events. */
@@ -243,6 +243,18 @@ export const refreshImageMapPoints = (): Promise<void> => {
return refresh;
};
+/**
+ * A person asked for a fresh map: POST /refresh is what bypasses the backend's refit cooldown. Automatic callers stay
+ * on `refreshImageMapPoints`, since passing through here would bring the refit loop back.
+ */
+export const requestImageMapRecompute = (): Promise<void> => {
+ void requestImageMapRefresh().catch(() => {
+ // The refit is best effort; the points fetch below reports connectivity errors.
+ });
+
+ return refreshImageMapPoints();
+};
+
let labelsSequence = 0;
const areLabelMapsEqual = (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx
index d4b137fe19..8794bf7cba 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx
@@ -8,10 +8,23 @@ import i18next from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { initReactI18next } from 'react-i18next';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
import { ImageMapWidgetFooter } from './ImageMapWidgetFooter';
+const api = vi.hoisted(() => ({
+ fetchImageMapClusterLabels: vi.fn(),
+ fetchImageMapPoints: vi.fn(),
+ fetchImageMapStatus: vi.fn(),
+ requestImageMapRefresh: vi.fn(),
+}));
+
+vi.mock('@workbench/image-map/api', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ...api,
+}));
+
// The components read the global instance; give it the English catalog.
await i18next.use(initReactI18next).init({
interpolation: { escapeValue: false },
@@ -141,6 +154,23 @@ describe('ImageMapWidgetFooter', () => {
expect(tooltip?.textContent).toBe('Cluster count: 2, largest cluster: 3 media points, unclustered: 1 media point');
});
+ it('asks the server for a refit when Refresh is clicked, not only for the current points', async () => {
+ await renderFooter([0, 1]);
+ const { data } = imageMapStore.getSnapshot();
+ api.requestImageMapRefresh.mockResolvedValue(true);
+ api.fetchImageMapPoints.mockResolvedValue(data);
+ api.fetchImageMapStatus.mockResolvedValue({ index: null, modelId: null, modelName: null, state: 'ready' });
+ api.fetchImageMapClusterLabels.mockResolvedValue({ labels: {}, updatedAt: null, visibleHash: null });
+
+ await act(async () => {
+ (page.getByRole('button', { name: 'Refresh map' }).element() as HTMLElement).click();
+ await vi.waitFor(() => expect(imageMapStore.getSnapshot().loadState).toBe('loaded'));
+ });
+
+ expect(api.requestImageMapRefresh).toHaveBeenCalledTimes(1);
+ expect(api.fetchImageMapPoints).toHaveBeenCalledTimes(1);
+ });
+
it('says so when nothing clustered', async () => {
// The symptom being diagnosed: a drawn map where every point is noise.
await renderFooter([-1, -1, -1]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
index b290fee28b..84ccce5cad 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
@@ -3,7 +3,7 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';
import { HStack, Icon, Text } from '@chakra-ui/react';
import { IconButton, Tooltip } from '@platform/ui';
import { describeClusters, summarizeClusters } from '@workbench/image-map/clusterStats';
-import { imageMapStore, refreshImageIndexStatus, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';
+import { imageMapStore, refreshImageIndexStatus, requestImageMapRecompute } from '@workbench/image-map/imageMapStore';
import { isIndexing } from '@workbench/image-map/indexProgress';
import { RefreshCwIcon } from 'lucide-react';
import { useMemo } from 'react';
@@ -15,7 +15,7 @@ import { ImageIndexProgressInline } from './ImageIndexProgress';
const NO_POINTS: never[] = [];
const handleRefresh = () => {
- void refreshImageMapPoints();
+ void requestImageMapRecompute();
// Refresh counts too, recovering final status events missed while offline.
refreshImageIndexStatus();
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
index bb65e0cf9d..8232310a23 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
@@ -124,6 +124,7 @@ vi.mock('@workbench/image-map/imageMapStore', async (importOriginal) => {
ensureImageMapLoaded: vi.fn(),
refreshImageIndexStatus: vi.fn(),
refreshImageMapPoints: vi.fn(),
+ requestImageMapRecompute: vi.fn(),
setClusterLabelsEnabled: vi.fn(),
setImageMapMediaKind: vi.fn(),
};
@@ -135,6 +136,7 @@ import {
imageMapStore,
refreshImageIndexStatus,
refreshImageMapPoints,
+ requestImageMapRecompute,
setImageMapMediaKind,
} from '@workbench/image-map/imageMapStore';
@@ -182,7 +184,7 @@ const viewProps = makeViewProps('project-a');
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const dataFor = (
- state: Extract<ImageMapState, 'disabled' | 'model_missing'>,
+ state: Extract<ImageMapState, 'computing' | 'disabled' | 'model_missing'>,
modelName = 'clip-vit-large-patch14'
) => ({
clusterEps: null,
@@ -196,7 +198,10 @@ const dataFor = (
visibleHash: null,
});
-const renderState = async (state: Extract<ImageMapState, 'disabled' | 'model_missing'>, modelName?: string) => {
+const renderState = async (
+ state: Extract<ImageMapState, 'computing' | 'disabled' | 'model_missing'>,
+ modelName?: string
+) => {
imageMapStore.setSnapshot({
clusterLabels: null,
clusterLabelsEps: null,
@@ -285,6 +290,21 @@ describe('Image Map unavailable states', () => {
);
});
+describe('Image Map computing state', () => {
+ it('lets Check again bypass the refit cooldown a failed fit waits behind', async () => {
+ await renderState('computing');
+
+ await act(() => {
+ Array.from(host?.querySelectorAll('button') ?? [])
+ .find((button) => button.textContent === 'Check again')
+ ?.click();
+ });
+
+ expect(requestImageMapRecompute).toHaveBeenCalledTimes(1);
+ expect(refreshImageIndexStatus).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('Image Map for a session that cannot change the server', () => {
it('says whom to ask instead of naming a configuration file', async () => {
models.canManageAppConfig = false;
@@ -456,6 +476,8 @@ describe('Image Map missing-model link', () => {
// what starts indexing without a restart.
expect(refreshImageMapPoints).toHaveBeenCalledTimes(1);
expect(refreshImageIndexStatus).toHaveBeenCalledTimes(1);
+ // An automatic refresh must never bypass the refit cooldown.
+ expect(requestImageMapRecompute).not.toHaveBeenCalled();
});
it('keeps the message and the in-flight install mounted while a refresh runs', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
index 98d5d39aac..f60eecafd8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
@@ -26,6 +26,7 @@ import {
imageMapStore,
refreshImageIndexStatus,
refreshImageMapPoints,
+ requestImageMapRecompute,
setClusterEps,
setClusterLabelsEnabled,
setImageMapMediaKind,
@@ -54,6 +55,11 @@ const handleRefresh = () => {
refreshImageIndexStatus();
};
+const handleRecompute = () => {
+ void requestImageMapRecompute();
+ refreshImageIndexStatus();
+};
+
// Use the configured default model name when older/empty responses cannot name the missing encoder.
const DEFAULT_IMAGE_INDEX_MODEL = 'DFN2B-CLIP-ViT-L-14-39B';
@@ -286,7 +292,8 @@ export const ImageMapWidgetView = ({ runtime }: WidgetViewProps) => {
<Text color="fg.muted" fontSize="lg">
{t('widgets.imageMap.computing')}
</Text>
- <Button onClick={handleRefresh} variant="outline">
+ {/* A failed fit also sits here during the cooldown, so this has to be able to bypass it. */}
+ <Button onClick={handleRecompute} variant="outline">
{t('widgets.imageMap.checkAgain')}
</Button>
</Stack>
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 d698ee152d..3870361406 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -2521,6 +2521,184 @@ def test_projection_job_is_popped_before_running(service: ImageIndexService) ->
assert service._next_projection_job() is None
+class _CoolingScope:
+ """A started service whose "system" scope has had one fit, on a clock the test moves (`skew`)."""
+
+ def __init__(self, image_records, images_service, index_records, monkeypatch, fit_seconds: float = 0.0) -> None:
+ self.skew = 0.0
+ self.fits = 0
+ self.image_records = image_records
+ self.images_service = images_service
+ self.index_records = index_records
+
+ def counting_umap(matrix: np.ndarray) -> np.ndarray:
+ # A stub, as in test_unchanged_scope_does_not_recompute_the_projection. It takes
+ # `fit_seconds` of the service's clock.
+ self.fits += 1
+ self.skew += fit_seconds
+ return np.zeros((matrix.shape[0], 2), dtype=np.float32)
+
+ # The module's own clock only: patching time.monotonic itself would skew every thread in the process.
+ monkeypatch.setattr(
+ image_index_default, "time", SimpleNamespace(monotonic=lambda: time.monotonic() + self.skew)
+ )
+ monkeypatch.setattr(image_index_default, "compute_umap", counting_umap)
+ self.service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)
+ for i in range(3):
+ _save_image(image_records, f"img-{i}.png")
+ self.invoker = _make_invoker(images_service, index_records)
+ self.service.start(self.invoker)
+ _wait_until(lambda: not self.service._backfill_pending.is_set())
+ # The first fit of a scope has nothing to cool down from.
+ self.service.request_projection("system")
+ _wait_until(lambda: "system" in self.service._projection_not_before, timeout=30.0)
+ assert self.fits == 1
+
+ def ready_count(self) -> int:
+ from invokeai.app.services.events.events_common import ImageMapProjectionReadyEvent
+
+ return sum(isinstance(e, ImageMapProjectionReadyEvent) for e in self.invoker.services.events.events)
+
+ def change_scope(self) -> None:
+ _save_image(self.image_records, "new.png")
+ self.images_service._on_changed(_dto_for(self.image_records, "new.png"))
+ _wait_until(
+ lambda: self.index_records.get_embeddings(imgs("new.png"), MODEL_ID)[0] == imgs("new.png"), timeout=30.0
+ )
+
+ def refit_stored(self) -> bool:
+ record = self.index_records.get_projection("system", MODEL_ID)
+ return record is not None and record.point_count == 4
+
+
+ ("floor", "multiplier", "fit_seconds", "still_cooling_at", "due_at"),
+ [(100.0, 0.0, 0.0, 50.0, 101.0), (0.0, 2.0, 100.0, 250.0, 301.0)],
+ ids=["floor", "multiplier"],
+)
+def test_a_polled_refit_waits_out_the_cooldown_of_the_last_fit(
+ image_records: ImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ monkeypatch: pytest.MonkeyPatch,
+ floor: float,
+ multiplier: float,
+ fit_seconds: float,
+ still_cooling_at: float,
+ due_at: float,
+) -> None:
+ """On a busy server something embeds during almost every fit, so a client refetching /points on
+ projection_ready would otherwise queue the next full fit at once, and the worker would fit forever.
+ The multiplier case's fit ends at clock 100, so its cooldown runs to 300."""
+ monkeypatch.setattr(image_index_default, "_PROJECTION_REFIT_COOLDOWN_FLOOR_SECONDS", floor)
+ monkeypatch.setattr(image_index_default, "_PROJECTION_REFIT_COOLDOWN_MULTIPLIER", multiplier)
+ scope = _CoolingScope(image_records, images_service, index_records, monkeypatch, fit_seconds)
+ try:
+ scope.change_scope()
+ scope.service.request_projection("system")
+ scope.skew = still_cooling_at
+ time.sleep(0.2) # Ten worker polls.
+ assert scope.fits == 1, "a refit nobody asked for must wait out the cooldown"
+ assert "system" in scope.service._projection_requests, "the deferred refit stays promised"
+
+ scope.skew = due_at
+ _wait_until(scope.refit_stored, timeout=30.0)
+ assert scope.fits == 2
+ finally:
+ scope.service.stop()
+
+
+def test_a_short_circuited_refresh_keeps_the_cooldown(
+ image_records: ImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A refresh over an unchanged scope fits nothing, so it must not free the next poll to refit at once."""
+ monkeypatch.setattr(image_index_default, "_PROJECTION_REFIT_COOLDOWN_FLOOR_SECONDS", 100.0)
+ scope = _CoolingScope(image_records, images_service, index_records, monkeypatch)
+ try:
+ cooldown = scope.service._projection_not_before["system"]
+ _wait_until(lambda: scope.ready_count() == 1)
+
+ scope.service.request_projection("system", user_initiated=True)
+ _wait_until(lambda: scope.ready_count() == 2)
+ assert scope.service._projection_not_before == {"system": cooldown}
+
+ scope.change_scope()
+ scope.service.request_projection("system")
+ time.sleep(0.2) # Ten worker polls.
+ assert scope.fits == 1
+ finally:
+ scope.service.stop()
+
+
+def test_a_refresh_whose_read_fails_during_a_cooldown_is_retried_at_once(
+ image_records: ImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecords,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The refresh lost its exemption when it was taken; the requeue must not leave it to the cooldown."""
+ monkeypatch.setattr(image_index_default, "_PROJECTION_REFIT_COOLDOWN_FLOOR_SECONDS", 100.0)
+ scope = _CoolingScope(image_records, images_service, index_records, monkeypatch)
+ try:
+ scope.change_scope()
+ real_list = index_records.list_accessible_embedded_items
+ failures = {"n": 0}
+
+ def fails_once(user_id, model_id):
+ if failures["n"] == 0:
+ failures["n"] += 1
+ raise LockTimeoutError("database is locked")
+ return real_list(user_id, model_id)
+
+ index_records.list_accessible_embedded_items = fails_once # type: ignore[method-assign]
+ scope.service.request_projection("system", user_initiated=True)
+ _wait_until(scope.refit_stored, timeout=30.0)
+ assert failures["n"] == 1
+ assert scope.fits == 2
+ finally:
+ scope.service.stop()
+
+
+def _fake_running_worker(service: ImageIndexService) -> None:
+ """Make request_projection accept jobs without a worker that would take them. It lives until the
+ service fixture's stop()."""
+ service._model_id = MODEL_ID
+ service._worker = threading.Thread(target=service._stop_event.wait, daemon=True)
+ service._worker.start()
+
+
+def test_a_user_requested_refit_skips_the_cooldown_even_when_a_poll_follows(service: ImageIndexService) -> None:
+ _fake_running_worker(service)
+ service._projection_not_before["u1"] = time.monotonic() + 1000
+
+ assert service.request_projection("u1")
+ assert service._next_projection_job() is None
+
+ assert service.request_projection("u1", user_initiated=True)
+ # A poll landing before the worker takes the job must not turn it back into a deferred one.
+ assert service.request_projection("u1")
+ assert service._next_projection_job() == ("u1", False)
+
+ # The exemption went with the job it came with.
+ assert service.request_projection("u1")
+ assert service._next_projection_job() is None
+
+
+def test_a_cooling_scope_does_not_block_another_users_due_refit(service: ImageIndexService) -> None:
+ _fake_running_worker(service)
+ service._projection_not_before["a"] = time.monotonic() + 1000
+
+ assert service.request_projection("a", all_images=True)
+ assert service.request_projection("b")
+
+ assert service._next_projection_job() == ("b", False)
+ assert service._projection_requests == {"a": True}, "the deferred job stays queued"
+ assert service._next_projection_job() is None
+
+
def test_embed_text_unavailable_without_model_config(
images_service: ImageService, index_records: ImageIndexRecords, service: ImageIndexService
) -> None:
diff --git a/tests/conftest.py b/tests/conftest.py
index dadf66d749..36877e5894 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -218,6 +218,9 @@ def _fast_service_polling(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(download_default, "_QUEUE_POLL_SECONDS", 0.02)
monkeypatch.setattr(model_install_default, "_INSTALL_QUEUE_POLL_SECONDS", 0.02)
monkeypatch.setattr(image_index_default, "_POLL_SECONDS", 0.02)
+ # Tests drive back-to-back fits of one scope; the refit cooldown would park them.
+ monkeypatch.setattr(image_index_default, "_PROJECTION_REFIT_COOLDOWN_FLOOR_SECONDS", 0.0)
+ monkeypatch.setattr(image_index_default, "_PROJECTION_REFIT_COOLDOWN_MULTIPLIER", 0.0)
@pytest.fixture(autouse=True)