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.

diag: report why an image map came back unclustered

Lincoln Steinea7629247809
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
index f8cf9760c1..aac7ad2d4e 100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@ -27,11 +27,10 @@ from invokeai.app.services.image_index.image_index_common import (
)
from invokeai.app.services.image_index.projection import (
DEFAULT_CLUSTER_MIN_SAMPLES,
- MAX_CLUSTERED_POINTS,
MIN_BUDGETED_EPS,
- cluster_at_eps,
+ ClusterDiagnostics,
+ cluster_with_diagnostics,
compute_clusters,
- resolve_cluster_eps,
scope_hash,
)
from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundException
@@ -174,8 +173,8 @@ def _release_refresh_slot(user_id: str) -> None:
# clustering it repeats is usually identical work. Caching the labels turns the
# steady state into a dict lookup; entries are int64 label arrays, bounded at
# ~400KB each by the 50k-point clustering cap (only a clustering that actually
-# ran is stored, so the all-noise array returned above the cap — which is free
-# to recompute and unbounded in size — never lands here).
+# ran is stored, so the all-noise array a skipped clustering returns — free to
+# recompute and unbounded in size — never lands here).
#
# ONE entry per user, rather than a shared pool of N. A shared pool made the
# cache worse than none: with more concurrent map users than slots, strict LRU
@@ -203,6 +202,62 @@ def _cluster_cache_put(user_id: str, key: _ClusterCacheKey, labels: np.ndarray,
_cluster_cache.popitem(last=False)
+# An all-noise map — every point "unclustered" — is the one clustering outcome
+# the response cannot explain, and it has four separate causes (see
+# ClusterDiagnostics). Reporting the diagnostics turns a user report into a
+# single greppable line.
+#
+# Only that outcome is logged at INFO; a clustering that found clusters
+# explains itself and goes to debug. The map refreshes on every gallery change
+# (socket-driven, not polled), and each refresh moves the cache key, so
+# without a guard a gallery stuck above the point cap would emit a line per
+# refresh forever.
+#
+# The guard is per-user and keyed on the diagnostics minus their timing, so a
+# repeat of the same outcome stays quiet while any change to the point set,
+# the parameters or the resulting clustering speaks up. It also expires: the
+# useful thing to be able to say is "open the map again while I watch the
+# log", and a once-per-process line cannot be reproduced without a restart.
+# Bounded like the cluster cache, under the same lock.
+_CLUSTER_DIAGNOSTICS_USERS = 32
+_CLUSTER_DIAGNOSTICS_REPEAT_AFTER_SECONDS = 600.0
+_cluster_diagnostics_logged: "OrderedDict[str, tuple[str, float]]" = OrderedDict()
+
+
+def _log_cluster_diagnostics(services, user_id: str, diagnostics: ClusterDiagnostics) -> None:
+ """Report why this clustering came out as it did, at most once per outcome."""
+ if diagnostics.n_points == 0:
+ # Nothing was clustered because there was nothing to cluster; the
+ # response already says `empty`.
+ return
+
+ explains_an_all_noise_map = diagnostics.skipped is not None or diagnostics.cluster_count == 0
+ signature = diagnostics.signature()
+ now = time.monotonic()
+ with _state_lock:
+ previous = _cluster_diagnostics_logged.get(user_id)
+ # Recorded and moved to the end even when this request is about to be
+ # suppressed: recency has to mean "last seen", not "last logged", or
+ # the quiet users — the ones whose entry is doing its job — are the
+ # first evicted, and eviction is what re-arms the line.
+ _cluster_diagnostics_logged[user_id] = (signature, now)
+ _cluster_diagnostics_logged.move_to_end(user_id)
+ while len(_cluster_diagnostics_logged) > _CLUSTER_DIAGNOSTICS_USERS:
+ _cluster_diagnostics_logged.popitem(last=False)
+ if previous is not None and previous[0] == signature:
+ if now - previous[1] < _CLUSTER_DIAGNOSTICS_REPEAT_AFTER_SECONDS:
+ # Keep the ORIGINAL timestamp: refreshing it on every
+ # suppressed request would hold the line off indefinitely.
+ _cluster_diagnostics_logged[user_id] = (signature, previous[1])
+ return
+
+ message = f"Image map: clustered user '{user_id}': {diagnostics.summary()}"
+ if explains_an_all_noise_map:
+ services.logger.info(message)
+ else:
+ services.logger.debug(message)
+
+
def _active_model_id(services) -> Optional[str]:
"""The running indexer's model id, activating it if the encoder was installed since startup.
@@ -377,22 +432,19 @@ async def get_image_map_points(
scope_hash(model_id, visible_items),
)
+ diagnostics = None
try:
- if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:
- resolved_eps = resolve_cluster_eps(visible_coords, eps, min_samples)
- # cluster_at_eps, not compute_clusters: the latter re-resolves
- # what was just resolved, and the second pass re-applies the
- # 0.01 floor to a budget-shrunk eps — so the value reported
- # here would not be the value DBSCAN used.
- labels = cluster_at_eps(visible_coords, resolved_eps, min_samples)
- # Cached only here. The other branch's labels are a constant
- # -1 array sized to the full point count — free to recompute,
- # unbounded in size, and above the cap that is the only array
- # large enough to matter.
+ labels, diagnostics = cluster_with_diagnostics(visible_coords, eps=eps, min_samples=min_samples)
+ resolved_eps = diagnostics.resolved_eps
+ # eps was resolved exactly when the point cap let the clustering
+ # proceed, so this is "the label array is bounded by the cap" —
+ # asked of the diagnostics rather than re-derived from a second
+ # copy of the constant, which can drift from the one the
+ # clustering actually applied. Above the cap the labels are a
+ # constant -1 array sized to the full point count: free to
+ # recompute, unbounded in size, and never worth storing.
+ if diagnostics.eps is not None:
_cluster_cache_put(user_id, cache_key, labels, resolved_eps)
- else:
- resolved_eps = None
- labels = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)
except Exception:
# Clustering is a presentation detail; the coordinates are the
# data. sklearn raises on a non-finite cached row (which a build
@@ -403,6 +455,10 @@ async def get_image_map_points(
services.logger.exception(f"Image map: clustering failed for user '{user_id}'; serving points unclustered")
resolved_eps = None
labels = np.full((visible_coords.shape[0],), -1, dtype=np.int64)
+ if diagnostics is not None:
+ # Outside the try: a logging failure must not be reported as a
+ # clustering failure, nor cost the caller their cached labels.
+ _log_cluster_diagnostics(services, user_id, diagnostics)
return (
[
ImageMapPoint(x=float(x), y=float(y), image_name=item.name, kind=item.kind, cluster=int(label))
@@ -837,16 +893,11 @@ async def get_image_map_cluster_labels(
return {}, visible_hash
visible_coords = record.coords[mask]
try:
- if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:
- # cluster_at_eps on a resolved eps, matching /points: passing an
- # already-resolved eps to compute_clusters re-resolves it, so
- # the labels here could come from a different eps than the
- # cluster_eps /points reported and the client passed back.
- cluster_ids = cluster_at_eps(
- visible_coords, resolve_cluster_eps(visible_coords, eps, min_samples), min_samples
- )
- else:
- cluster_ids = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)
+ # Resolves the client-supplied eps exactly once, as /points does, so
+ # both endpoints agree on the clustering these labels describe. The
+ # diagnostics /points reports cover this call too: same points, same
+ # parameters, same result.
+ cluster_ids = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)
except Exception:
# /points degrades to unclustered rather than 500ing; labels over no
# clusters is the same degradation, and the client already discards
diff --git a/invokeai/app/services/image_index/projection.py b/invokeai/app/services/image_index/projection.py
index ecadd0963a..d45f074f22 100644
--- a/invokeai/app/services/image_index/projection.py
+++ b/invokeai/app/services/image_index/projection.py
@@ -14,7 +14,9 @@ map labels a small gallery as all noise.
import hashlib
import json
+import time
import warnings
+from dataclasses import dataclass
from typing import Optional
import numpy as np
@@ -126,47 +128,81 @@ MAX_NEIGHBOR_PAIRS = 50_000_000
MIN_BUDGETED_EPS = 1e-6
-def _shrink_eps_to_pair_budget(coords: np.ndarray, eps: float) -> float:
+def _shrink_eps_to_pair_budget(coords: np.ndarray, eps: float) -> tuple[float, Optional[int]]:
"""Shrink eps until DBSCAN's neighbor-pair count fits MAX_NEIGHBOR_PAIRS.
The span clamp alone cannot bound memory: a dense blob concentrates most
pairs in a small region, so a modest eps on a wide map can still
materialize billions of pairs. Counting pairs with a KD-tree is cheap.
+
+ Returns the eps and the pair count AT that eps (None when there is nothing
+ to count), so a caller reporting diagnostics does not repeat the walk.
"""
if coords.shape[0] < 2:
- return eps
+ return eps, None
from sklearn.neighbors import KDTree
tree = KDTree(coords)
+ pairs = int(tree.query_radius(coords, r=eps, count_only=True).sum())
# Iterate until the budget is met rather than a fixed count: 12 rounds of
# 0.7 only covers a 71x reduction, and a tight blob can need far more.
# Bounded below by MIN_BUDGETED_EPS so a fully coincident map terminates.
- while eps > MIN_BUDGETED_EPS:
- pairs = int(tree.query_radius(coords, r=eps, count_only=True).sum())
- if pairs <= MAX_NEIGHBOR_PAIRS:
- return eps
+ while pairs > MAX_NEIGHBOR_PAIRS and eps > MIN_BUDGETED_EPS:
eps *= 0.7
- return eps
+ pairs = int(tree.query_radius(coords, r=eps, count_only=True).sum())
+ return eps, pairs
+
+
+@dataclass(frozen=True)
+class EpsResolution:
+ """Every step of `resolve_cluster_eps`, for callers that report why.
+
+ Each field is a gate that can silently turn a real clustering into an
+ all-noise map, so the resolution keeps them rather than only its result.
+ """
+
+ requested_eps: Optional[float]
+ """What the caller asked for; None means the adaptive default was used."""
+ adaptive_eps: Optional[float]
+ """Median k-distance, before the 2.0 cap. Only computed when requested_eps is None."""
+ coord_span: float
+ """Widest coordinate extent of the projection; 0.0 for a single point."""
+ span_clamped_eps: float
+ """After the MAX_EPS_SPAN_FRACTION clamp, before the floor."""
+ floored_eps: float
+ """After the 0.01 floor. Reported apart from the clamp because the two are
+ separate causes of an over-tight eps, and a single number cannot say which
+ one produced it."""
+ resolved_eps: float
+ """What DBSCAN will actually run with, after the neighbor-pair budget."""
+ neighbor_pairs: Optional[int]
+ """Pair count at resolved_eps; None when there was nothing to count."""
def resolve_cluster_eps(
coords: np.ndarray,
eps: Optional[float] = None,
min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES,
-) -> float:
- """The eps compute_clusters will actually use for these coordinates.
+) -> EpsResolution:
+ """The eps clustering will actually use for these coordinates, and every
+ intermediate value it passed through.
Resolution order: adaptive default when eps is None, then the span clamp,
- then the neighbor-pair budget. Exposed so callers (the /points endpoint)
- can report the effective eps and other callers can reuse it verbatim.
+ then the 0.01 floor, then the neighbor-pair budget. The intermediates are
+ returned rather than discarded because each one is a gate that can leave a
+ map entirely unclustered, and the resolved value alone does not say which
+ one bound it.
"""
+ requested_eps = eps
+ adaptive_eps: Optional[float] = None
if eps is None:
# Cap at the API's own upper bound (le=2.0) so a reported adaptive
# eps can always be passed back explicitly. Values that large only
# arise on sparse structureless maps, where a smaller eps just means
# more (correct) noise.
- eps = min(adaptive_cluster_eps(coords, min_samples), 2.0)
+ adaptive_eps = adaptive_cluster_eps(coords, min_samples)
+ eps = min(adaptive_eps, 2.0)
span = float(np.ptp(coords, axis=0).max()) if coords.shape[0] > 1 else 0.0
if span > 0:
eps = min(eps, span * MAX_EPS_SPAN_FRACTION)
@@ -176,7 +212,18 @@ def resolve_cluster_eps(
# computed, which is how a near-coincident map reached 400M pairs against
# a 50M budget (~4GB). The budget bounds memory and therefore wins; an eps
# below the API's floor is a cosmetic pass-back wart, an OOM is not.
- return _shrink_eps_to_pair_budget(coords, max(eps, 0.01))
+ span_clamped_eps = eps
+ floored_eps = max(span_clamped_eps, 0.01)
+ resolved_eps, neighbor_pairs = _shrink_eps_to_pair_budget(coords, floored_eps)
+ return EpsResolution(
+ requested_eps=requested_eps,
+ adaptive_eps=adaptive_eps,
+ coord_span=span,
+ span_clamped_eps=span_clamped_eps,
+ floored_eps=floored_eps,
+ resolved_eps=resolved_eps,
+ neighbor_pairs=neighbor_pairs,
+ )
def compute_clusters(
@@ -190,47 +237,125 @@ def compute_clusters(
live-adjustable without recomputing the UMAP. When eps is None it is
derived from the data with adaptive_cluster_eps; see resolve_cluster_eps
for the clamps applied either way. Clustering is skipped entirely above
- MAX_CLUSTERED_POINTS.
+ MAX_CLUSTERED_POINTS. Callers that need to know WHY the labels came out as
+ they did call cluster_with_diagnostics, which this delegates to.
"""
- if coords.shape[0] == 0:
- return np.empty((0,), dtype=np.int64)
- if coords.shape[0] > MAX_CLUSTERED_POINTS:
- return np.full((coords.shape[0],), -1, dtype=np.int64)
+ return cluster_with_diagnostics(coords, eps, min_samples)[0]
+
+
+def _g(value: Optional[float]) -> str:
+ """One float format for the whole diagnostic line, so its columns line up."""
+ return "None" if value is None else f"{value:.6g}"
+
- return cluster_at_eps(coords, resolve_cluster_eps(coords, eps, min_samples), min_samples)
+@dataclass(frozen=True)
+class ClusterDiagnostics:
+ """Why a clustering came out the way it did.
+ Four gates can turn a real clustering into an all-noise map — the point
+ cap, the span clamp, the pair budget, and an eps floored at 0.01 — and the
+ served response shows none of them: every point simply reads
+ "unclustered". This records what each gate saw, so that outcome can be
+ explained from a log line instead of a reproduction.
+ """
-def cluster_at_eps(
+ n_points: int
+ min_samples: int
+ skipped: Optional[str]
+ """Why DBSCAN did not run at all; None when it did."""
+ eps: Optional[EpsResolution]
+ """None when the run was skipped before eps was resolved."""
+ cluster_count: int
+ largest_cluster: int
+ smallest_cluster: int
+ unclustered: int
+ duration_ms: float
+
+ @property
+ def resolved_eps(self) -> Optional[float]:
+ return self.eps.resolved_eps if self.eps is not None else None
+
+ def signature(self) -> str:
+ """Greppable key=value line, timing excluded.
+
+ Timing is what changes between two otherwise identical runs, so a
+ caller that logs one line per distinct outcome compares this.
+ """
+ fields = [f"points={self.n_points}", f"min_samples={self.min_samples}"]
+ if self.eps is None:
+ fields.append("eps=unresolved")
+ else:
+ fields += [
+ f"requested_eps={_g(self.eps.requested_eps)}",
+ f"adaptive_eps={_g(self.eps.adaptive_eps)}",
+ f"coord_span={_g(self.eps.coord_span)}",
+ f"span_clamped_eps={_g(self.eps.span_clamped_eps)}",
+ f"floored_eps={_g(self.eps.floored_eps)}",
+ f"resolved_eps={_g(self.eps.resolved_eps)}",
+ f"neighbor_pairs={self.eps.neighbor_pairs}",
+ ]
+ fields += [
+ f"clusters={self.cluster_count}",
+ f"largest={self.largest_cluster}",
+ f"smallest={self.smallest_cluster}",
+ f"unclustered={self.unclustered}",
+ ]
+ if self.skipped is not None:
+ fields.append(f"skipped={self.skipped!r}")
+ return " ".join(fields)
+
+ def summary(self) -> str:
+ return f"{self.signature()} took={self.duration_ms:.1f}ms"
+
+
+def cluster_with_diagnostics(
coords: np.ndarray,
- eps: float,
+ eps: Optional[float] = None,
min_samples: int = DEFAULT_CLUSTER_MIN_SAMPLES,
-) -> np.ndarray:
- """DBSCAN at an eps `resolve_cluster_eps` has ALREADY produced.
+) -> tuple[np.ndarray, ClusterDiagnostics]:
+ """`compute_clusters`, plus a record of every gate the run passed through.
- Split out so a caller that needs to report the effective eps can resolve it
- once and cluster at exactly that value. Passing a resolved eps back into
- compute_clusters instead would re-resolve it — and since resolution floors
- at 0.01 before applying the neighbour-pair budget, a budget-shrunk eps comes
- back out different, so the reported value would not be the one used.
+ The single implementation of the resolve-then-cluster sequence, so the
+ pair count the eps resolution already produced is also the one that
+ decides the pair-budget skip rather than being measured a second time.
"""
- if coords.shape[0] == 0:
- return np.empty((0,), dtype=np.int64)
- if coords.shape[0] > MAX_CLUSTERED_POINTS:
- return np.full((coords.shape[0],), -1, dtype=np.int64)
+ started = time.perf_counter()
+ n_points = coords.shape[0]
- from sklearn.cluster import DBSCAN
- from sklearn.neighbors import KDTree
+ def finish(labels: np.ndarray, resolution: Optional[EpsResolution], skipped: Optional[str]):
+ _, sizes = np.unique(labels[labels >= 0], return_counts=True)
+ return labels, ClusterDiagnostics(
+ n_points=n_points,
+ min_samples=min_samples,
+ skipped=skipped,
+ eps=resolution,
+ cluster_count=int(sizes.size),
+ largest_cluster=int(sizes.max()) if sizes.size else 0,
+ smallest_cluster=int(sizes.min()) if sizes.size else 0,
+ unclustered=int((labels < 0).sum()),
+ duration_ms=(time.perf_counter() - started) * 1000.0,
+ )
+
+ if n_points == 0:
+ return finish(np.empty((0,), dtype=np.int64), None, None)
+ if n_points > MAX_CLUSTERED_POINTS:
+ return finish(
+ np.full((n_points,), -1, dtype=np.int64),
+ None,
+ f"point count above MAX_CLUSTERED_POINTS={MAX_CLUSTERED_POINTS}",
+ )
- if coords.shape[0] > 1:
- # The shrink bottoms out at MIN_BUDGETED_EPS, which a fully coincident
- # map cannot satisfy at any positive radius. Skip clustering rather
- # than hand DBSCAN a neighborhood it would materialize into GBs — same
- # response shape as the MAX_CLUSTERED_POINTS skip above.
- pairs = int(KDTree(coords).query_radius(coords, r=eps, count_only=True).sum())
- if pairs > MAX_NEIGHBOR_PAIRS:
- return np.full((coords.shape[0],), -1, dtype=np.int64)
+ resolution = resolve_cluster_eps(coords, eps, min_samples)
+ if resolution.neighbor_pairs is not None and resolution.neighbor_pairs > MAX_NEIGHBOR_PAIRS:
+ return finish(
+ np.full((n_points,), -1, dtype=np.int64),
+ resolution,
+ f"neighbor pairs above MAX_NEIGHBOR_PAIRS={MAX_NEIGHBOR_PAIRS} at the pair budget's floor",
+ )
+
+ from sklearn.cluster import DBSCAN
- return DBSCAN(eps=eps, min_samples=min_samples).fit(coords).labels_
+ return finish(DBSCAN(eps=resolution.resolved_eps, min_samples=min_samples).fit(coords).labels_, resolution, None)
def scope_hash(model_id: str, items: list[IndexedItem]) -> str:
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterStats.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterStats.test.ts
new file mode 100644
index 0000000000..b3cdde9986
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterStats.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ImageMapPoint } from './api';
+
+import { describeClusters, summarizeClusters } from './clusterStats';
+
+const points = (...clusters: number[]): ImageMapPoint[] =>
+ clusters.map((cluster, index) => ({
+ cluster,
+ item: { kind: 'image', name: `${index}.png` },
+ key: `image:${index}.png` as ImageMapPoint['key'],
+ x: index,
+ y: index,
+ }));
+
+describe('summarizeClusters', () => {
+ it('sizes each cluster and counts noise apart from them', () => {
+ expect(summarizeClusters(points(0, 0, 0, 1, 1, 2, -1, -1))).toEqual({
+ clusterCount: 3,
+ largestCluster: 3,
+ smallestCluster: 1,
+ unclustered: 2,
+ });
+ });
+
+ it('reports no clusters rather than one when DBSCAN labelled everything noise', () => {
+ // The 170k-gallery symptom: the map draws, and every point is noise.
+ expect(summarizeClusters(points(-1, -1, -1))).toEqual({
+ clusterCount: 0,
+ largestCluster: 0,
+ smallestCluster: 0,
+ unclustered: 3,
+ });
+ });
+
+ it('does not assume cluster ids are dense or start at zero', () => {
+ // DBSCAN renumbers between runs and the map serves only the points the
+ // user can still see, so served ids can skip values entirely.
+ expect(summarizeClusters(points(7, 7, 42))).toEqual({
+ clusterCount: 2,
+ largestCluster: 2,
+ smallestCluster: 1,
+ unclustered: 0,
+ });
+ });
+
+ it('handles an empty map', () => {
+ expect(summarizeClusters([])).toEqual({
+ clusterCount: 0,
+ largestCluster: 0,
+ smallestCluster: 0,
+ unclustered: 0,
+ });
+ });
+});
+
+describe('describeClusters', () => {
+ it('agrees with the noun it is counting', () => {
+ expect(describeClusters(summarizeClusters(points(0, 0, 1, -1)))).toBe(
+ 'Cluster count: 2, Largest cluster: 2 media points, Smallest cluster: 1 media point, Unclustered: 1 media point'
+ );
+ });
+
+ it('groups digits, so it reads consistently beside the index progress in the same row', () => {
+ const noise: number[] = Array.from({ length: 1500 }, () => -1);
+
+ expect(describeClusters(summarizeClusters(points(...noise)))).toContain('Unclustered: 1,500 media points');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterStats.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterStats.ts
new file mode 100644
index 0000000000..a22166d2d4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterStats.ts
@@ -0,0 +1,68 @@
+import type { ImageMapPoint } from './api';
+
+export interface ClusterStats {
+ clusterCount: number;
+ /** Size of the biggest cluster, or 0 when nothing clustered. */
+ largestCluster: number;
+ /** Size of the smallest cluster, or 0 when nothing clustered. */
+ smallestCluster: number;
+ /** Points DBSCAN labelled noise (cluster -1). */
+ unclustered: number;
+}
+
+const count = (value: number, noun: string): string => `${value.toLocaleString()} ${noun}${value === 1 ? '' : 's'}`;
+
+/**
+ * The footer's one-line readout of a clustering.
+ *
+ * Lives beside the arithmetic so the sentence and the numbers cannot drift,
+ * and so a test can assert the wording without mounting a widget.
+ */
+export const describeClusters = (stats: ClusterStats): string =>
+ [
+ `Cluster count: ${stats.clusterCount.toLocaleString()}`,
+ `Largest cluster: ${count(stats.largestCluster, 'media point')}`,
+ `Smallest cluster: ${count(stats.smallestCluster, 'media point')}`,
+ `Unclustered: ${count(stats.unclustered, 'media point')}`,
+ ].join(', ');
+
+/**
+ * Cluster sizes over the points as drawn, for the footer's readout.
+ *
+ * Derived from the served points rather than reported alongside them so the
+ * numbers cannot disagree with the map: these are exactly the points the plot
+ * colours. Noise (cluster -1) is counted apart from the clusters, never as
+ * one of them — an all-noise map is the shape that needs explaining, and
+ * calling it "1 cluster" would hide it.
+ *
+ * One pass, no allocation per point: the map serves hundreds of thousands of
+ * them and this runs whenever the point set changes.
+ */
+export const summarizeClusters = (points: readonly ImageMapPoint[]): ClusterStats => {
+ const sizes = new Map<number, number>();
+ let unclustered = 0;
+
+ for (const point of points) {
+ if (point.cluster < 0) {
+ unclustered += 1;
+ continue;
+ }
+
+ sizes.set(point.cluster, (sizes.get(point.cluster) ?? 0) + 1);
+ }
+
+ let largestCluster = 0;
+ let smallestCluster = Infinity;
+
+ for (const size of sizes.values()) {
+ largestCluster = Math.max(largestCluster, size);
+ smallestCluster = Math.min(smallestCluster, size);
+ }
+
+ return {
+ clusterCount: sizes.size,
+ largestCluster,
+ smallestCluster: sizes.size > 0 ? smallestCluster : 0,
+ unclustered,
+ };
+};
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
new file mode 100644
index 0000000000..550289f0c6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.browser.test.tsx
@@ -0,0 +1,143 @@
+import type { ImageMapPoint } from '@workbench/image-map/api';
+import type { WidgetViewProps } from '@workbench/widgetContracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { imageMapStore } from '@workbench/image-map/imageMapStore';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { ImageMapWidgetFooter } from './ImageMapWidgetFooter';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const points = (...clusters: number[]): ImageMapPoint[] =>
+ clusters.map((cluster, index) => ({
+ cluster,
+ item: { kind: 'image', name: `${index}.png` },
+ key: `image:${index}.png` as ImageMapPoint['key'],
+ x: index,
+ y: index,
+ }));
+
+/** The narrowest a floating window gets (`workbench/floatingWindows.ts`). */
+const NARROW_HOST = '280px';
+
+/** Every other segment the row can show at once, to squeeze the readout hardest. */
+const CROWDED = { embedded: 123456, failed: 12, pending: 60544, total: 184012 };
+
+const renderFooter = async (clusters: number[], width?: string, crowded = false) => {
+ imageMapStore.setSnapshot({
+ clusterLabels: null,
+ clusterLabelsHash: null,
+ data: {
+ clusterEps: 0.2,
+ modelName: null,
+ pointCount: clusters.length,
+ points: points(...clusters),
+ stale: crowded,
+ state: 'ready',
+ updatedAt: null,
+ visibleHash: null,
+ },
+ error: null,
+ indexCounts: crowded ? CROWDED : null,
+ indexUpdatedAt: crowded ? Date.now() : null,
+ loadState: 'loaded',
+ renderError: null,
+ });
+
+ if (width && host) {
+ host.style.width = width;
+ }
+
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <ImageMapWidgetFooter {...({} as WidgetViewProps)} />
+ </ChakraProvider>
+ )
+ );
+};
+
+const readout = (): HTMLElement => {
+ const found = Array.from(host?.querySelectorAll('p, span, div') ?? []).find((element) =>
+ element.textContent?.startsWith('· Cluster count:')
+ );
+
+ if (!(found instanceof HTMLElement)) {
+ throw new Error('the cluster readout is not in the document');
+ }
+
+ return found;
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('ImageMapWidgetFooter', () => {
+ it('reports the clustering beside the point count', async () => {
+ await renderFooter([0, 0, 0, 1, 1, -1]);
+
+ expect(host?.textContent).toContain('6 points');
+ expect(host?.textContent).toContain(
+ 'Cluster count: 2, Largest cluster: 3 media points, Smallest cluster: 2 media points, Unclustered: 1 media point'
+ );
+ });
+
+ it('stays readable in a narrow widget, where the text itself cannot be', async () => {
+ // This segment is the only shrinkable item in the row, so it absorbs all
+ // the overflow: at 280px the numbers are clipped out of the page and the
+ // tooltip is the only way left to read them.
+ // Crowded: stale, indexing and skipped all showing, so every other
+ // segment is competing for the row. They are all nowrap and refuse to
+ // shrink, which is what makes this one absorb the whole overflow.
+ await renderFooter([0, 0, 0, 1, 1, -1], NARROW_HOST, true);
+
+ const element = readout();
+
+ expect(host?.scrollWidth).toBeLessThanOrEqual((host?.clientWidth ?? 0) + 1);
+ expect(element.scrollWidth).toBeGreaterThan(element.clientWidth);
+ // What is left of the readout is the tooltip's only hover target, so the
+ // row has to leave it a usable one. It survives on flex leftover alone —
+ // every sibling refuses to shrink — which is what this pins: a sibling
+ // that starts growing greedily would take the target away.
+ expect(element.clientWidth).toBeGreaterThanOrEqual(40);
+
+ await act(() => {
+ element.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' }));
+ element.dispatchEvent(new PointerEvent('pointerenter', { bubbles: true, pointerType: 'mouse' }));
+ });
+ await new Promise((resolve) => {
+ globalThis.setTimeout(resolve, 500);
+ });
+
+ const tooltip = document.querySelector('[role="tooltip"]');
+
+ expect(tooltip?.textContent).toBe(
+ 'Cluster count: 2, Largest cluster: 3 media points, Smallest cluster: 2 media points, Unclustered: 1 media point'
+ );
+ });
+
+ it('says so when nothing clustered', async () => {
+ // The symptom being diagnosed: a drawn map where every point is noise.
+ await renderFooter([-1, -1, -1]);
+
+ expect(host?.textContent).toContain(
+ 'Cluster count: 0, Largest cluster: 0 media points, Smallest cluster: 0 media points, Unclustered: 3 media points'
+ );
+ });
+});
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 08972677e0..17b513f2f1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
@@ -2,12 +2,17 @@ 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 { isIndexing } from '@workbench/image-map/indexProgress';
import { RefreshCwIcon } from 'lucide-react';
+import { useMemo } from 'react';
import { ImageIndexProgressInline } from './ImageIndexProgress';
+/** Stable identity for the pre-`ready` renders, so the memo below never re-runs on null. */
+const NO_POINTS: never[] = [];
+
const handleRefresh = () => {
void refreshImageMapPoints();
// The counts too: this footer is the surface that shows them once the map
@@ -17,12 +22,18 @@ const handleRefresh = () => {
};
/**
- * Widget-chrome footer: point count, a stale hint while a recompute is
- * pending, embedding-index progress (admins only receive those events), and
- * a manual refresh.
+ * Widget-chrome footer: point count, how those points clustered, a stale hint
+ * while a recompute is pending, embedding-index progress (admins only receive
+ * those events), and a manual refresh.
*/
export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {
const { data, indexCounts, indexUpdatedAt, loadState } = imageMapStore.useSnapshot();
+ // Before the early return, and keyed on the array the store swaps wholesale.
+ // The footer re-renders on every index-progress tick, and those patch other
+ // snapshot keys and leave `data` identity intact — so the count runs once per
+ // points refresh rather than once per tick, which matters at 170k points.
+ const points = data?.points ?? NO_POINTS;
+ const clusterSummary = useMemo(() => describeClusters(summarizeClusters(points)), [points]);
// Only the states that actually show a map. `disabled`, `model_missing` and
// `empty` all carry data too, and each renders its own explanation — a
@@ -41,7 +52,14 @@ export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {
return (
<HStack borderTopWidth="1px" color="fg.muted" fontSize="2xs" gap="2" justify="space-between" px="3" py="1" w="full">
<HStack gap="2" minW="0">
- <Text whiteSpace="nowrap">{data.pointCount} points</Text>
+ <Text whiteSpace="nowrap">{data.pointCount.toLocaleString()} points</Text>
+ {/* Every sibling in this row is nowrap, so this is the only segment
+ flex can shrink and it absorbs all of the row's overflow: below
+ roughly 500px the numbers are clipped off the page and the tooltip
+ is the only way left to read them. */}
+ <Tooltip content={clusterSummary}>
+ <Text truncate>· {clusterSummary}</Text>
+ </Tooltip>
{data.stale ? <Text whiteSpace="nowrap">· updating…</Text> : null}
{indexing ? (
<>
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index fb96d97585..3e52d2144e 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -1,6 +1,7 @@
"""Tests for the /v1/image_map endpoints: serving, staleness, and user scoping."""
import logging
+import time
from pathlib import Path
from types import SimpleNamespace
@@ -19,7 +20,11 @@ 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_index.projection import scope_hash
+from invokeai.app.services.image_index.projection import (
+ DEFAULT_CLUSTER_MIN_SAMPLES,
+ cluster_with_diagnostics,
+ scope_hash,
+)
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.invocation_services import InvocationServices
@@ -639,14 +644,16 @@ def test_cluster_labels_computed_only_over_accessible_points(
@pytest.fixture(autouse=True)
def _reset_image_map_router_state():
- """The throttle and cluster cache are module state, so they outlive a test."""
+ """The throttle, cluster cache and diagnostics log are module state, so they outlive a test."""
from invokeai.app.api.routers import image_map as image_map_router_module
image_map_router_module._refresh_claims.clear()
image_map_router_module._cluster_cache.clear()
+ image_map_router_module._cluster_diagnostics_logged.clear()
yield
image_map_router_module._refresh_claims.clear()
image_map_router_module._cluster_cache.clear()
+ image_map_router_module._cluster_diagnostics_logged.clear()
def test_refresh_is_throttled_per_user(
@@ -704,13 +711,17 @@ def test_repeat_points_requests_reuse_the_clustering(monkeypatch, mock_invoker:
from invokeai.app.api.routers import image_map as image_map_router_module
calls = {"n": 0}
- real_cluster = image_map_router_module.cluster_at_eps
+ served: list[float | None] = []
+ real_cluster = image_map_router_module.cluster_with_diagnostics
- def counting_cluster(coords, eps, min_samples):
+ def counting_cluster(coords, eps=None, min_samples=DEFAULT_CLUSTER_MIN_SAMPLES):
calls["n"] += 1
- return real_cluster(coords, eps, min_samples)
+ labels, diagnostics = real_cluster(coords, eps, min_samples)
+ served.append(diagnostics.resolved_eps)
+
+ return labels, diagnostics
- monkeypatch.setattr(image_map_router_module, "cluster_at_eps", counting_cluster)
+ monkeypatch.setattr(image_map_router_module, "cluster_with_diagnostics", counting_cluster)
names = ["a.png", "b.png", "c.png", "d.png"]
for name in names:
@@ -724,6 +735,11 @@ def test_repeat_points_requests_reuse_the_clustering(monkeypatch, mock_invoker:
assert repeat["points"] == first["points"]
assert repeat["cluster_eps"] == first["cluster_eps"]
assert calls["n"] == 1, "identical repeat polls must not recluster"
+ # The eps the client is told to pass back has to be the one that produced
+ # these labels. Resolving it a second time anywhere in the endpoint would
+ # re-apply the 0.01 floor to a budget-shrunk value and report a different
+ # number than DBSCAN ran at.
+ assert first["cluster_eps"] == served[0]
# Every clustering input is part of the key.
client.get("/api/v1/image_map/points", params={"eps": 0.05, "min_samples": 2}).json()
@@ -739,6 +755,146 @@ def test_repeat_points_requests_reuse_the_clustering(monkeypatch, mock_invoker:
assert reprojected["points"] != first["points"]
+def test_points_logs_why_a_map_came_back_unclustered(
+ caplog, monkeypatch, mock_invoker: Invoker, client: TestClient
+) -> None:
+ """An all-noise map is indistinguishable from a working one in the response.
+
+ The point cap is the gate a large gallery hits, and nothing the client
+ receives mentions it: every point simply arrives with cluster -1.
+ """
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ monkeypatch.setattr("invokeai.app.services.image_index.projection.MAX_CLUSTERED_POINTS", 1)
+ names = ["a.png", "b.png"]
+ for name in names:
+ _seed_embedded_image(mock_invoker, name)
+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs(*names), np.zeros((2, 2), dtype=np.float32))
+
+ with caplog.at_level(logging.DEBUG):
+ body = client.get("/api/v1/image_map/points").json()
+
+ assert [point["cluster"] for point in body["points"]] == [-1, -1]
+ assert _diagnostics_levels(caplog) == ["INFO"], "a skipped clustering must be reported, and at INFO"
+ line = _diagnostics_records(caplog)[0].getMessage()
+ assert "MAX_CLUSTERED_POINTS" in line
+ assert "points=2" in line and "unclustered=2" in line and "clusters=0" in line
+
+ # A second request re-clusters (a skipped clustering is never cached, so
+ # this is not a cache hit) and must stay quiet: the map refreshes on every
+ # gallery change, and a gallery stuck above the cap would otherwise emit a
+ # line per refresh forever.
+ caplog.clear()
+ with caplog.at_level(logging.DEBUG):
+ client.get("/api/v1/image_map/points")
+ assert image_map_router_module._cluster_cache == {}, "the repeat must have re-clustered, not read a cache"
+ assert _diagnostics_levels(caplog) == []
+
+ # Enough time passing re-arms it, so "open the map again while I watch the
+ # log" works without restarting the server.
+ caplog.clear()
+ stale = time.monotonic() - image_map_router_module._CLUSTER_DIAGNOSTICS_REPEAT_AFTER_SECONDS - 1
+ signature = image_map_router_module._cluster_diagnostics_logged[SYSTEM_USER_ID][0]
+ image_map_router_module._cluster_diagnostics_logged[SYSTEM_USER_ID] = (signature, stale)
+ with caplog.at_level(logging.DEBUG):
+ client.get("/api/v1/image_map/points")
+ assert _diagnostics_levels(caplog) == ["INFO"]
+
+ # A clustering that found clusters explains itself, so it goes to debug.
+ caplog.clear()
+ monkeypatch.setattr("invokeai.app.services.image_index.projection.MAX_CLUSTERED_POINTS", 50_000)
+ with caplog.at_level(logging.DEBUG):
+ client.get("/api/v1/image_map/points", params={"min_samples": 2})
+ assert _diagnostics_levels(caplog) == ["DEBUG"]
+ healthy = _diagnostics_records(caplog)[0].getMessage()
+ assert "MAX_CLUSTERED_POINTS" not in healthy and "resolved_eps=" in healthy
+
+
+def test_a_map_with_no_visible_points_is_not_reported_as_a_clustering(
+ caplog, mock_invoker: Invoker, client: TestClient
+) -> None:
+ """Nothing clustered because there was nothing to cluster; `state` says so already."""
+ _seed_embedded_image(mock_invoker, "a.png")
+ # A projection whose only row is not in the accessible set: the visible
+ # mask empties, and clustering is handed zero points.
+ _seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("gone.png"), np.zeros((1, 2), dtype=np.float32))
+
+ with caplog.at_level(logging.DEBUG):
+ client.get("/api/v1/image_map/points")
+
+ assert _diagnostics_levels(caplog) == []
+
+
+def test_cluster_diagnostics_log_is_bounded_and_kept_per_user() -> None:
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ services = SimpleNamespace(logger=logging)
+ diagnostics = cluster_with_diagnostics(np.zeros((4, 2), dtype=np.float32), eps=0.5, min_samples=2)[1]
+ for index in range(image_map_router_module._CLUSTER_DIAGNOSTICS_USERS + 3):
+ image_map_router_module._log_cluster_diagnostics(services, f"user{index}", diagnostics)
+
+ logged = image_map_router_module._cluster_diagnostics_logged
+ assert len(logged) == image_map_router_module._CLUSTER_DIAGNOSTICS_USERS
+ assert "user0" not in logged, "the oldest user must be evicted, not the newest"
+ assert f"user{image_map_router_module._CLUSTER_DIAGNOSTICS_USERS + 2}" in logged
+ # Per user: one user's line must never silence another's.
+ assert len({entry[0] for entry in logged.values()}) == 1
+
+
+def test_a_suppressed_repeat_does_not_push_back_the_re_arm() -> None:
+ """The line re-arms 600s after it was last EMITTED, not last suppressed.
+
+ Refreshing the stored timestamp on every quiet request would hold the line
+ off for as long as the user keeps the map open — which is exactly when
+ they are trying to reproduce it.
+ """
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ services = SimpleNamespace(logger=logging)
+ diagnostics = cluster_with_diagnostics(np.zeros((4, 2), dtype=np.float32), eps=0.5, min_samples=2)[1]
+ image_map_router_module._log_cluster_diagnostics(services, "user", diagnostics)
+ emitted_at = image_map_router_module._cluster_diagnostics_logged["user"][1]
+
+ for _ in range(3):
+ image_map_router_module._log_cluster_diagnostics(services, "user", diagnostics)
+
+ assert image_map_router_module._cluster_diagnostics_logged["user"][1] == emitted_at
+
+
+def test_cluster_diagnostics_log_keeps_the_users_it_keeps_hearing_from() -> None:
+ """Recency has to mean "last seen", not "last logged".
+
+ A user whose clustering never changes is the quiet path, and it is exactly
+ the entry worth keeping: evict it and their next request logs again, which
+ is the repetition the guard exists to prevent.
+ """
+ from invokeai.app.api.routers import image_map as image_map_router_module
+
+ services = SimpleNamespace(logger=logging)
+ diagnostics = cluster_with_diagnostics(np.zeros((4, 2), dtype=np.float32), eps=0.5, min_samples=2)[1]
+ cap = image_map_router_module._CLUSTER_DIAGNOSTICS_USERS
+ for index in range(cap):
+ image_map_router_module._log_cluster_diagnostics(services, f"user{index}", diagnostics)
+
+ # user0 says the same thing again — suppressed, but still active.
+ image_map_router_module._log_cluster_diagnostics(services, "user0", diagnostics)
+ image_map_router_module._log_cluster_diagnostics(services, "newcomer", diagnostics)
+
+ logged = image_map_router_module._cluster_diagnostics_logged
+ assert len(logged) == cap
+ assert "user0" in logged, "a suppressed repeat must refresh the entry's recency"
+ assert "user1" not in logged, "the genuinely least recent user is the one to evict"
+
+
+def _diagnostics_records(caplog) -> list[logging.LogRecord]:
+ """The clustering-diagnostics lines captured so far."""
+ return [record for record in caplog.records if "Image map: clustered" in record.getMessage()]
+
+
+def _diagnostics_levels(caplog) -> list[str]:
+ return [record.levelname for record in _diagnostics_records(caplog)]
+
+
def test_cluster_cache_is_bounded(monkeypatch, mock_invoker: Invoker, client: TestClient) -> None:
from invokeai.app.api.routers import image_map as image_map_router_module
@@ -983,10 +1139,7 @@ def test_cluster_labels_skips_the_embedding_gather_when_nothing_clustered(
_seed_embedded_image(mock_invoker, "a.png")
_seed_projection(mock_invoker, SYSTEM_USER_ID, imgs("a.png"), np.zeros((1, 2), dtype=np.float32))
- monkeypatch.setattr(
- "invokeai.app.api.routers.image_map.compute_clusters",
- lambda coords, eps=None, min_samples=None: np.full((coords.shape[0],), -1, dtype=np.int64),
- )
+ monkeypatch.setattr("invokeai.app.services.image_index.projection.MAX_CLUSTERED_POINTS", 0)
gathered = []
original = image_index_service.get_accessible_embeddings
diff --git a/tests/app/services/image_index/test_projection.py b/tests/app/services/image_index/test_projection.py
index 6233ef6fb3..b3f41f8446 100644
--- a/tests/app/services/image_index/test_projection.py
+++ b/tests/app/services/image_index/test_projection.py
@@ -7,7 +7,10 @@ import numpy as np
from invokeai.app.services.image_index.image_index_common import IndexedItem
from invokeai.app.services.image_index.projection import (
DEFAULT_CLUSTER_EPS,
+ MAX_CLUSTERED_POINTS,
+ MAX_EPS_SPAN_FRACTION,
adaptive_cluster_eps,
+ cluster_with_diagnostics,
compute_clusters,
compute_umap,
projection_params,
@@ -119,9 +122,9 @@ def test_eps_shrinks_to_fit_neighbor_pair_budget(monkeypatch) -> None:
sparse = rng.uniform(-50.0, 50.0, size=(120, 2))
coords = np.vstack([dense, sparse]).astype(np.float32)
- unbudgeted = resolve_cluster_eps(coords)
+ unbudgeted = resolve_cluster_eps(coords).resolved_eps
monkeypatch.setattr(projection, "MAX_NEIGHBOR_PAIRS", 5_000)
- budgeted = resolve_cluster_eps(coords)
+ budgeted = resolve_cluster_eps(coords).resolved_eps
assert budgeted < unbudgeted
# And the budgeted eps is what the default clustering path actually uses:
@@ -134,8 +137,8 @@ def test_resolve_cluster_eps_is_idempotent() -> None:
# clustering; resolving an already-resolved eps must not change it.
rng = np.random.default_rng(5)
coords = rng.normal(size=(200, 2)).astype(np.float32) * 10
- resolved = resolve_cluster_eps(coords)
- assert resolve_cluster_eps(coords, eps=resolved) == resolved
+ resolved = resolve_cluster_eps(coords).resolved_eps
+ assert resolve_cluster_eps(coords, eps=resolved).resolved_eps == resolved
def test_compute_clusters_clamps_eps_to_span_fraction() -> None:
@@ -148,8 +151,6 @@ def test_compute_clusters_clamps_eps_to_span_fraction() -> None:
def test_compute_clusters_skips_huge_point_sets() -> None:
- from invokeai.app.services.image_index.projection import MAX_CLUSTERED_POINTS
-
coords = np.zeros((MAX_CLUSTERED_POINTS + 1, 2), dtype=np.float32)
labels = compute_clusters(coords, eps=0.2, min_samples=2)
assert set(labels) == {-1}
@@ -180,14 +181,16 @@ def test_projection_params_is_stable_json() -> None:
assert projection_params(n_points=100) == projection_params(n_points=100)
-def test_cluster_at_eps_clusters_at_exactly_the_eps_it_is_given(monkeypatch) -> None:
- """The router resolves eps once so it can report the effective value, then clusters.
+def test_clustering_reports_the_eps_dbscan_actually_ran_at(monkeypatch) -> None:
+ """One clustering resolves eps once, and reports the value it used.
- Routing that value back through compute_clusters would resolve it a SECOND time —
- re-running the k-distance fit and the whole KD-tree budget shrink (measured at ~65%
- of a 50k-point request), and re-applying the 0.01 floor, which re-inflates a
- budget-shrunk eps onto a different shrink grid so the number reported to the client
- is not the number DBSCAN used.
+ The endpoints report `cluster_eps` out of this call so a later request can
+ reproduce the clustering. Resolving a second time — which routing the
+ reported value back through the entry point would do — re-runs the
+ k-distance fit and the whole KD-tree budget shrink (measured at ~65% of a
+ 50k-point request), and re-applies the 0.01 floor, which re-inflates a
+ budget-shrunk eps onto a different shrink grid: the number reported would
+ not be the number DBSCAN used.
"""
import invokeai.app.services.image_index.projection as projection
@@ -212,15 +215,120 @@ def test_cluster_at_eps_clusters_at_exactly_the_eps_it_is_given(monkeypatch) ->
monkeypatch.setattr(sklearn.cluster, "DBSCAN", recording_dbscan)
coords = _blob_coords()
- resolved = real_resolve(coords, None, 2)
+ _, diagnostics = cluster_with_diagnostics(coords, eps=None, min_samples=2)
+
+ assert calls["resolve"] == 1, "one clustering must resolve eps exactly once"
+ assert captured["eps"] == diagnostics.resolved_eps, "DBSCAN must run at exactly the eps reported"
+
+
+def test_diagnostics_count_the_clusters_that_were_found() -> None:
+ coords = _blob_coords()
+ labels, diagnostics = cluster_with_diagnostics(coords, min_samples=2)
+
+ sizes = sorted(int((labels == cluster).sum()) for cluster in set(labels) if cluster >= 0)
+ assert sizes, "the blob fixture must cluster, or this asserts nothing"
+ assert diagnostics.cluster_count == len(sizes)
+ assert diagnostics.largest_cluster == sizes[-1]
+ assert diagnostics.smallest_cluster == sizes[0]
+ assert diagnostics.unclustered == int((labels < 0).sum())
+ assert diagnostics.skipped is None
+ assert diagnostics.eps is not None and diagnostics.eps.adaptive_eps is not None
+
+
+def test_diagnostics_name_the_point_cap_that_left_a_map_unclustered() -> None:
+ """The gate a 170k-image gallery hits: every point noise, nothing in the response saying why."""
+ coords = np.zeros((MAX_CLUSTERED_POINTS + 1, 2), dtype=np.float32)
+ labels, diagnostics = cluster_with_diagnostics(coords, eps=0.2, min_samples=2)
+
+ assert set(labels) == {-1}
+ assert diagnostics.skipped is not None and "MAX_CLUSTERED_POINTS" in diagnostics.skipped
+ assert diagnostics.unclustered == coords.shape[0]
+ assert diagnostics.cluster_count == 0
+ # Nothing was resolved, so nothing about eps may be reported as if it had been.
+ assert diagnostics.eps is None and diagnostics.resolved_eps is None
+ assert "MAX_CLUSTERED_POINTS" in diagnostics.summary()
+
- projection.cluster_at_eps(coords, resolved, 2)
- assert calls["resolve"] == 0, "clustering at an already-resolved eps must not resolve again"
- assert captured["eps"] == resolved, "DBSCAN must run at exactly the eps the caller reports"
+def test_diagnostics_name_the_pair_budget_when_the_shrink_bottoms_out(monkeypatch) -> None:
+ # Coincident points are every other point's neighbor at any radius, so no
+ # eps meets the budget and the shrink stops at its floor.
+ import invokeai.app.services.image_index.projection as projection
+
+ monkeypatch.setattr(projection, "MAX_NEIGHBOR_PAIRS", 100)
+ coords = np.zeros((100, 2), dtype=np.float32)
+ labels, diagnostics = cluster_with_diagnostics(coords, min_samples=2)
+
+ assert set(labels) == {-1}
+ assert diagnostics.skipped is not None and "MAX_NEIGHBOR_PAIRS" in diagnostics.skipped
+ # eps resolution DID run here, so the shrink it bottomed out on is reported.
+ assert diagnostics.eps is not None
+ assert diagnostics.eps.neighbor_pairs == coords.shape[0] ** 2
+ assert diagnostics.resolved_eps is not None and diagnostics.resolved_eps <= projection.MIN_BUDGETED_EPS
+
+
+def test_diagnostics_report_each_link_of_the_eps_chain() -> None:
+ """A wrong chain is worse than none: it misdirects the next investigation."""
+ # Span 30, so the clamp (5% of span = 1.5) binds an eps of 5.0.
+ coords = np.array([[0.0, 0.0], [30.0, 30.0], [10.0, 10.0], [20.0, 20.0]], dtype=np.float32)
+ resolution = resolve_cluster_eps(coords, eps=5.0, min_samples=2)
+
+ assert resolution.requested_eps == 5.0
+ assert resolution.adaptive_eps is None, "an explicit eps must not be reported as an adaptive one"
+ assert resolution.coord_span == 30.0
+ assert resolution.span_clamped_eps == 30.0 * MAX_EPS_SPAN_FRACTION
+ assert resolution.floored_eps == resolution.span_clamped_eps, "1.5 is above the floor; the floor must not move it"
+ assert resolution.resolved_eps == resolution.floored_eps, "6 pairs is under any budget"
+
+
+def test_diagnostics_separate_the_span_clamp_from_the_eps_floor() -> None:
+ """Both can produce a too-tight eps, and the log has to say which one did."""
+ # Span 0.08, so the clamp gives 0.004 and the 0.01 floor then lifts it.
+ coords = np.array([[0.0, 0.0], [0.08, 0.0], [0.04, 0.0]], dtype=np.float32)
+ resolution = resolve_cluster_eps(coords, eps=2.0, min_samples=2)
+
+ assert resolution.span_clamped_eps < 0.01
+ assert resolution.floored_eps == 0.01
+ assert (
+ "span_clamped_eps=0.004 floored_eps=0.01"
+ in cluster_with_diagnostics(coords, eps=2.0, min_samples=2)[1].signature()
+ )
+
+
+def test_the_pair_budget_shrink_can_succeed_short_of_its_floor(monkeypatch) -> None:
+ """The shrink's successful exit — clusters at a reduced eps, rather than giving up."""
+ import invokeai.app.services.image_index.projection as projection
+
+ rng = np.random.default_rng(11)
+ coords = np.concatenate([rng.normal(scale=0.05, size=(200, 2)) + c for c in ([0.0, 0.0], [10.0, 10.0])]).astype(
+ np.float32
+ )
+ monkeypatch.setattr(projection, "MAX_NEIGHBOR_PAIRS", 20_000)
+ labels, diagnostics = cluster_with_diagnostics(coords, eps=2.0, min_samples=2)
+
+ assert diagnostics.skipped is None, "the shrink met the budget, so DBSCAN must have run"
+ assert diagnostics.eps is not None
+ assert diagnostics.resolved_eps < diagnostics.eps.floored_eps, "the budget must have shrunk eps"
+ assert diagnostics.resolved_eps > projection.MIN_BUDGETED_EPS, "it must have stopped short of the floor"
+ assert diagnostics.eps.neighbor_pairs <= 20_000
+ assert diagnostics.cluster_count > 0, "a met budget must still cluster, not degrade to noise"
+ # The reported histogram describes the labels that were actually served.
+ sizes = sorted(int((labels == cluster).sum()) for cluster in set(labels) if cluster >= 0)
+ assert [diagnostics.cluster_count, diagnostics.largest_cluster, diagnostics.smallest_cluster] == [
+ len(sizes),
+ sizes[-1],
+ sizes[0],
+ ]
+
+
+def test_diagnostics_signature_is_stable_across_identical_runs() -> None:
+ """The endpoint logs one line per distinct outcome, so timing must stay out of the key."""
+ coords = _blob_coords()
+ first = cluster_with_diagnostics(coords, min_samples=2)[1]
+ second = cluster_with_diagnostics(coords, min_samples=2)[1]
- # compute_clusters keeps resolving for callers that pass a raw/None eps.
- projection.compute_clusters(coords, eps=None, min_samples=2)
- assert calls["resolve"] == 1
+ assert first.signature() == second.signature()
+ assert first.signature() in first.summary()
+ assert cluster_with_diagnostics(coords, min_samples=3)[1].signature() != first.signature()
def _blob_coords() -> np.ndarray: