Skip to main content

windows_headless/
screen_knn.rs

1//! k-NN screen classifier: normalized-pixel embeddings + cosine similarity.
2//!
3//! The classifier for the 9 [`ScreenClass`] labels. No weights, no epochs,
4//! no training loop — the corpus is clustered per class and inference is
5//! cosine distance against the cluster centers.
6//!
7//! Pipeline per frame (all deterministic, bit-for-bit):
8//! 1. [`downsample_to_grid_rgb`] (brightest-pixel, so
9//!    thin text/spinners survive the shrink).
10//! 2. Luminance, then a 3x3 box blur: damps single-pixel jitter
11//!    (spinner phase, glyph placement) that exact-pixel matching would
12//!    otherwise memorize.
13//! 3. Zero-mean + unit-norm: brightness/exposure cannot dominate the
14//!    distance. A pure-black frame has norm zero and short-circuits to
15//!    `Dark` — nothing captured is a cosine over zeros.
16//!
17//! Verdict shape: top-1 + gap + top-k, where the
18//! gap is best-cosine minus best-cosine-of-any-other-class, and
19//! [`KNN_UNCERTAIN_GAP`] hedges narration — wording only, never gating. Every verdict names the matched
20//! exemplar, so a miss is a viewable cause ("matched corpus frame X at
21//! 0.992, runner-up Y at 0.991"), not a weight matrix to interrogate.
22//!
23//! Known limit, shared with every pixel-space method: near-duplicate
24//! frames with different labels (console twins, `-moved` windows) still
25//! collide. The miss list names its causes; when the pixels cannot
26//! separate two labels, that is a taxonomy problem, not a model problem.
27
28/// Shared resampling front end: every frame is
29/// resampled to this square before embedding, so any source resolution
30/// feeds the same descriptor. Motion sensing ([`crate::vision`]) reuses
31/// the same grid + downsampler — one resampling contract, not two.
32pub const GRID: usize = 128;
33
34/// Number of screen classes.
35pub const N_CLASSES: usize = 9;
36
37/// Screen classes, in index order.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum ScreenClass {
40    /// Nothing on screen (pure black).
41    Dark,
42    /// Bare color field, no UI.
43    FlatField,
44    /// UEFI shell prompt (no bootable device).
45    ErrorShell,
46    /// Windows Setup / installer / OOBE progress screens.
47    InstallerStep,
48    /// Windows Recovery screens (WinRE menus and failure text).
49    ErrorRecovery,
50    /// Error UI needing input: modal failure dialogs and bugcheck screens.
51    /// One class on purpose — the operational response is identical, and
52    /// neither has enough captures to stand alone.
53    ErrorScreen,
54    /// Anything else: lock screen, gradients. (No desktop ever appears in
55    /// this flow, so the lock screen stands in as the class name for the
56    /// remaining miscellaneous bucket.)
57    Lockscreen,
58    /// Firmware boot art: TianoCore splash, boot logos. Transient screens
59    /// between firmware handoff and the OS, visually distinct from both
60    /// text consoles and OS screens.
61    FirmwareBoot,
62    /// First-boot OOBE transitionals ("Just a moment", logo splash,
63    /// "Welcome"): post-install, pre-logon. Progress, never errors.
64    OobeStep,
65}
66
67/// Index to class. The single source of truth for index order: predictions
68/// return through this table, and the roundtrip test below fails the build
69/// if the enum order ever drifts from it again.
70pub const BY_INDEX: [ScreenClass; N_CLASSES] = [
71    ScreenClass::Dark,
72    ScreenClass::FlatField,
73    ScreenClass::ErrorShell,
74    ScreenClass::InstallerStep,
75    ScreenClass::ErrorRecovery,
76    ScreenClass::ErrorScreen,
77    ScreenClass::Lockscreen,
78    ScreenClass::FirmwareBoot,
79    ScreenClass::OobeStep,
80];
81
82/// Brightest-pixel downsample of a source region to GRID x GRID.
83/// Full-frame [`downsample_to_grid_rgb`] is this over the whole frame.
84/// Each output pixel takes the brightest source pixel in its cell (per
85/// channel) rather than the nearest neighbor: thin white text and
86/// spinner arcs on black survive the shrink instead of sampling out
87/// of existence.
88pub fn downsample_region_to_grid_rgb(
89    src: &[u8],
90    src_w: usize,
91    src_h: usize,
92    x0: usize,
93    y0: usize,
94    x1: usize,
95    y1: usize,
96) -> [u8; 3 * GRID * GRID] {
97    assert_eq!(src.len(), src_w * src_h * 3, "downsample size mismatch");
98    assert!(
99        x0 < x1 && x1 <= src_w && y0 < y1 && y1 <= src_h,
100        "crop region out of bounds"
101    );
102    let (rw, rh) = (x1 - x0, y1 - y0);
103    let mut out = [0u8; 3 * GRID * GRID];
104    for y in 0..GRID {
105        let sy0 = y0 + y * rh / GRID;
106        let sy1 = (y0 + (y + 1) * rh / GRID).max(sy0 + 1).min(y1);
107        for x in 0..GRID {
108            let sx0 = x0 + x * rw / GRID;
109            let sx1 = (x0 + (x + 1) * rw / GRID).max(sx0 + 1).min(x1);
110            let mut best = [0u8; 3];
111            for sy in sy0..sy1 {
112                for sx in sx0..sx1 {
113                    let s = (sy * src_w + sx) * 3;
114                    for c in 0..3 {
115                        if src[s + c] > best[c] {
116                            best[c] = src[s + c];
117                        }
118                    }
119                }
120            }
121            let d = (y * GRID + x) * 3;
122            out[d..d + 3].copy_from_slice(&best);
123        }
124    }
125    out
126}
127
128/// Brightest-pixel downsample of full-resolution RGB to GRID x GRID.
129/// `src` is row-major `src_w` x `src_h` RGB; resolution-independent, so any
130/// screendump size feeds the same descriptor.
131pub fn downsample_to_grid_rgb(src: &[u8], src_w: usize, src_h: usize) -> [u8; 3 * GRID * GRID] {
132    downsample_region_to_grid_rgb(src, src_w, src_h, 0, 0, src_w, src_h)
133}
134
135/// Decode a PNG file to 8-bit RGB bytes. Panicking wrapper for fixtures
136/// and tests (every test input is committed, so a decode failure is a
137/// repo problem, not a runtime one); user-supplied paths go through
138/// [`try_load_rgb_8bit`], which returns `Err` instead.
139pub fn load_rgb_8bit(path: &str) -> (Vec<u8>, u32, u32) {
140    try_load_rgb_8bit(path).unwrap_or_else(|e| panic!("fixture {path}: {e}"))
141}
142
143/// Fallible sibling of [`load_rgb_8bit`] for callers that face
144/// user-supplied paths (CLI): missing files and corrupt headers come
145/// back as `Err`, never a panic. `String` error keeps this module
146/// std-only; the CLI maps it into `anyhow`.
147pub fn try_load_rgb_8bit(path: &str) -> Result<(Vec<u8>, u32, u32), String> {
148    let file = std::fs::File::open(path).map_err(|e| format!("open: {e}"))?;
149    let decoder = png::Decoder::new(file);
150    let mut reader = decoder
151        .read_info()
152        .map_err(|e| format!("read header: {e}"))?;
153    let mut buf = vec![0; reader.output_buffer_size()];
154    let frame = reader
155        .next_frame(&mut buf)
156        .map_err(|e| format!("decode: {e}"))?;
157    if frame.bit_depth != png::BitDepth::Eight {
158        return Err("not 8-bit".to_string());
159    }
160    let (w, h) = (frame.width, frame.height);
161    let px = &buf[..frame.buffer_size()];
162    let rgb = match frame.color_type {
163        png::ColorType::Rgb => px.to_vec(),
164        png::ColorType::Rgba => px
165            .as_chunks::<4>()
166            .0
167            .iter()
168            .flat_map(|p| [p[0], p[1], p[2]])
169            .collect(),
170        png::ColorType::Grayscale => px.iter().flat_map(|&g| [g, g, g]).collect(),
171        png::ColorType::GrayscaleAlpha => px
172            .as_chunks::<2>()
173            .0
174            .iter()
175            .flat_map(|p| [p[0], p[0], p[0]])
176            .collect(),
177        png::ColorType::Indexed => {
178            let palette = reader
179                .info()
180                .palette
181                .clone()
182                .expect("indexed fixture has no palette");
183            px.iter()
184                .flat_map(|&i| {
185                    let o = i as usize * 3;
186                    [palette[o], palette[o + 1], palette[o + 2]]
187                })
188                .collect()
189        }
190    };
191    Ok((rgb, w, h))
192}
193
194/// Embedding width: one luminance float per GRID cell, plus the
195/// appended DC (spatial mean) dimension.
196pub const EMBED_DIMS: usize = GRID * GRID + 1;
197
198/// Provisional hedge threshold on the cosine gap (best minus best of any
199/// other class). Cosine gaps on near-duplicates live in the thousandths —
200/// tune this against the holdout gap distribution, never by gut feel.
201pub const KNN_UNCERTAIN_GAP: f32 = 0.01;
202
203/// How many ranked exemplars a verdict prints.
204pub const KNN_TOP_K: usize = 3;
205
206/// Corpus dir→label map. This table — not a filename list — is the
207/// corpus definition: drop new captures in, rebuild the index, re-run.
208/// The version directory itself carries no label: the classifier never
209/// sees it, it only keeps captures attributable over time.
210pub const CLASS_DIRS: [(&str, ScreenClass); 10] = [
211    ("dark", ScreenClass::Dark),
212    ("flat-field", ScreenClass::FlatField),
213    ("error-shell", ScreenClass::ErrorShell),
214    ("installer-step", ScreenClass::InstallerStep),
215    ("error-recovery", ScreenClass::ErrorRecovery),
216    ("error-modal", ScreenClass::ErrorScreen),
217    ("lockscreen", ScreenClass::Lockscreen),
218    ("firmware-boot", ScreenClass::FirmwareBoot),
219    ("oobe-step", ScreenClass::OobeStep),
220    ("error-bluescreen", ScreenClass::ErrorScreen),
221];
222
223/// Rec.601 luminance of a GRID RGB frame, in 0.0..=1.0.
224pub fn luminance(full: &[u8; 3 * GRID * GRID]) -> [f32; GRID * GRID] {
225    let mut out = [0.0f32; GRID * GRID];
226    for i in 0..GRID * GRID {
227        let r = f32::from(full[i * 3]);
228        let g = f32::from(full[i * 3 + 1]);
229        let b = f32::from(full[i * 3 + 2]);
230        out[i] = (0.299 * r + 0.587 * g + 0.114 * b) / 255.0;
231    }
232    out
233}
234
235/// 3x3 box blur with clamped edges: single-pixel content (spinner arc
236/// phase, glyph edges) contributes to its neighborhood instead of living
237/// or dying on one cell. Constant frames pass through unchanged.
238pub fn box_blur(lum: &[f32; GRID * GRID]) -> [f32; GRID * GRID] {
239    let mut out = [0.0f32; GRID * GRID];
240    for y in 0..GRID {
241        for x in 0..GRID {
242            let mut sum = 0.0f32;
243            let mut n = 0.0f32;
244            for dy in -1i32..=1 {
245                for dx in -1i32..=1 {
246                    let xx = (x as i32 + dx).clamp(0, GRID as i32 - 1) as usize;
247                    let yy = (y as i32 + dy).clamp(0, GRID as i32 - 1) as usize;
248                    sum += lum[yy * GRID + xx];
249                    n += 1.0;
250                }
251            }
252            out[y * GRID + x] = sum / n;
253        }
254    }
255    out
256}
257
258/// Zero-mean + unit-norm, with the spatial mean appended as a final
259/// dimension before scaling. The appended DC preserves absolute
260/// brightness: a uniform frame's embedding is the pure DC direction
261/// instead of the zero vector, so flat bright fields (setup blue) and
262/// flat black (no signal) separate by construction rather than
263/// collapsing onto each other. Only the exactly-zero vector (uniform
264/// black: no variance AND no light) scores as nothing — that is the
265/// sole case callers short-circuit to `Dark`.
266/// Output length is [`EMBED_DIMS`] = GRID*GRID + 1.
267pub fn normalize(lum: &[f32; GRID * GRID]) -> Vec<f32> {
268    let mean = lum.iter().sum::<f32>() / (GRID * GRID) as f32;
269    let mut centered: Vec<f32> = lum.iter().map(|v| v - mean).collect();
270    centered.push(mean);
271    let norm = centered.iter().map(|v| v * v).sum::<f32>().sqrt();
272    if norm == 0.0 {
273        return vec![0.0; EMBED_DIMS];
274    }
275    centered.iter().map(|v| v / norm).collect()
276}
277
278/// Full front end: GRID RGB → blurred unit-norm luminance embedding.
279pub fn embed(full: &[u8; 3 * GRID * GRID]) -> Vec<f32> {
280    normalize(&box_blur(&luminance(full)))
281}
282
283/// Cosine similarity. Both sides are unit-norm from [`normalize`], so
284/// this is a dot product; the denominator is skipped, never assumed —
285/// a zero vector scores 0.0 against everything instead of NaN.
286pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
287    debug_assert_eq!(a.len(), EMBED_DIMS);
288    debug_assert_eq!(b.len(), EMBED_DIMS);
289    a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
290}
291
292/// One stored corpus frame: label, display name, embedding.
293#[derive(Clone)]
294pub struct Exemplar {
295    pub label: usize,
296    pub name: String,
297    pub vec: Vec<f32>,
298}
299
300/// Shipped exemplar artifact (vectors + labels + names, no pixels):
301/// committed under `artifacts/`, baked into the binary via
302/// `include_bytes!` so installed binaries classify with no fixture
303/// checkout. Rebuilt by `src/bin/build-knn-index.rs` — corpus edits
304/// re-run the builder, exactly like retrains re-ship weights.
305pub const KNN_INDEX_REL_PATH: &str = "artifacts/knn_index.bin";
306
307/// Baked exemplar bytes: present at compile time (the builder runs
308/// before any dependents compile), absent from every runtime path —
309/// installed binaries carry the index, never the fixtures.
310static KNN_INDEX_BYTES: &[u8] = include_bytes!("../artifacts/knn_index.bin");
311
312/// Decode the baked artifact, fail-hard on stale/corrupt bytes (same
313/// contract as the weights load: never score against a misaligned
314/// index).
315pub fn bundled_index() -> KnnIndex {
316    KnnIndex {
317        exemplars: decode_index(KNN_INDEX_BYTES),
318    }
319}
320
321/// Process-shared index for the live classify tick: decoded once
322/// (7 MB of f32 at runtime from a 290 KB artifact), then borrowed by
323/// every frame. A per-tick decode would re-pay the dequantization on
324/// every 10s cadence for no reason.
325pub(crate) fn shared_index() -> &'static KnnIndex {
326    static INDEX: std::sync::OnceLock<KnnIndex> = std::sync::OnceLock::new();
327    INDEX.get_or_init(bundled_index)
328}
329
330/// Magic + version of the index encoding below (`KNN1`, 3: int8
331/// payloads with per-vector scale, DC-appended dims).
332const KNN_INDEX_MAGIC: u32 = 0x4b_4e_4e_31;
333const KNN_INDEX_VERSION: u32 = 3;
334
335/// Per-vector scale for [`quantize`]: reconstructed component =
336/// `byte as f32 * scale`. Stored beside each exemplar (4 bytes); keeps
337/// int8 steps proportional to the vector's own range instead of a
338/// global guess.
339pub fn quantize(v: &[f32]) -> (Vec<i8>, f32) {
340    debug_assert_eq!(v.len(), EMBED_DIMS);
341    let peak = v.iter().fold(0.0f32, |m, x| m.max(x.abs()));
342    if peak == 0.0 {
343        return (vec![0; EMBED_DIMS], 1.0);
344    }
345    let scale = peak / 127.0;
346    let q = v
347        .iter()
348        .map(|x| (x / scale).round().clamp(-127.0, 127.0) as i8)
349        .collect();
350    (q, scale)
351}
352
353/// Inverse of [`quantize`]: int8 payload back to the f32 the query path
354/// scores. Quantization noise is the only accuracy delta vs raw floats —
355/// measured by the holdout test, never assumed.
356pub fn dequantize(q: &[i8], scale: f32) -> Vec<f32> {
357    debug_assert_eq!(q.len(), EMBED_DIMS);
358    q.iter().map(|b| f32::from(*b) * scale).collect()
359}
360
361/// Cluster count for a class with `n` exemplars: one center per ~8
362/// frames, min 1, max 6. The artifact stores neighborhoods, not frames
363/// — kilobytes per class whether the class holds 2 captures or 200.
364pub fn clusters_for(n: usize) -> usize {
365    n.div_ceil(8).clamp(1, 6)
366}
367
368/// Deterministic k-means (fixed-seed LCG k-means++ init, 50 Lloyd
369/// iterations, ties to the lowest index): same points, same centers,
370/// every run. Squared-euclidean for assignment (standard; on unit-norm
371/// vectors it orders like cosine for close neighbors), means as
372/// centers. `k` clamps to `1..=points.len()` — a singleton class
373/// centers on itself.
374pub fn kmeans(points: &[Vec<f32>], k: usize) -> Vec<Vec<f32>> {
375    assert!(!points.is_empty(), "kmeans on empty class");
376    let k = k.clamp(1, points.len());
377    let dim = points[0].len();
378    // Fixed-seed LCG: deterministic k-means++ without a rng crate.
379    let mut state: u64 = 0xC0FFEE;
380    let mut next = || {
381        state = state
382            .wrapping_mul(6364136223846793005)
383            .wrapping_add(1442695040888963407);
384        (state >> 33) as f64 / (u32::MAX as f64 + 1.0)
385    };
386    let dist2 = |a: &[f32], b: &[f32]| {
387        a.iter()
388            .zip(b.iter())
389            .map(|(x, y)| {
390                let d = f64::from(*x) - f64::from(*y);
391                d * d
392            })
393            .sum::<f64>()
394    };
395    let mut centers: Vec<Vec<f32>> = vec![points[0].clone()];
396    while centers.len() < k {
397        let d2: Vec<f64> = points
398            .iter()
399            .map(|p| {
400                centers
401                    .iter()
402                    .map(|c| dist2(p, c))
403                    .fold(f64::INFINITY, f64::min)
404            })
405            .collect();
406        let total: f64 = d2.iter().sum();
407        if total == 0.0 {
408            // Remaining points sit on existing centers: duplicate the
409            // last one (harmless — it retrieves identically).
410            while centers.len() < k {
411                centers.push(centers.last().unwrap().clone());
412            }
413            break;
414        }
415        let mut pick = next() * total;
416        let mut idx = 0;
417        for (i, d) in d2.iter().enumerate() {
418            pick -= d;
419            if pick <= 0.0 {
420                idx = i;
421                break;
422            }
423            idx = i;
424        }
425        centers.push(points[idx].clone());
426    }
427    for _ in 0..50 {
428        let mut sums = vec![vec![0.0f64; dim]; k];
429        let mut counts = vec![0u64; k];
430        for p in points {
431            let mut best = 0;
432            let mut best_d = f64::INFINITY;
433            for (i, c) in centers.iter().enumerate() {
434                let d = dist2(p, c);
435                if d < best_d {
436                    best_d = d;
437                    best = i;
438                }
439            }
440            for (s, v) in sums[best].iter_mut().zip(p.iter()) {
441                *s += f64::from(*v);
442            }
443            counts[best] += 1;
444        }
445        for (i, c) in centers.iter_mut().enumerate() {
446            if counts[i] == 0 {
447                continue;
448            }
449            for (v, s) in c.iter_mut().zip(sums[i].iter()) {
450                *v = (s / counts[i] as f64) as f32;
451            }
452        }
453    }
454    // Unit-norm restoration: the mean of unit vectors has length < 1 for
455    // dispersed clusters, and the query path scores cosine as a plain dot
456    // product — an unnormalized center would read as artificially distant.
457    // A zero mean (members cancelling exactly) falls back to the first
458    // member rather than scoring 0.0 against everything.
459    for c in centers.iter_mut() {
460        let norm = c.iter().map(|v| *v * *v).sum::<f32>().sqrt();
461        if norm > 0.0 {
462            for v in c.iter_mut() {
463                *v /= norm;
464            }
465        } else if let Some(first) = points.first() {
466            *c = first.clone();
467        }
468    }
469    centers
470}
471
472/// Encode exemplars to little-endian bytes: 16-byte header (magic,
473/// version, dims, count), then per exemplar label u32, scale f32,
474/// name-len u32, name bytes, dims int8 payload. int8 + scale is one
475/// byte per dim (4x under raw f32): artifact growth tracks dimensions
476/// and centers, never raw frame count. The single writer behind every
477/// index producer; [`decode_index`] is the single reader.
478pub fn encode_index(exemplars: &[Exemplar]) -> Vec<u8> {
479    let mut out = Vec::new();
480    out.extend_from_slice(&KNN_INDEX_MAGIC.to_le_bytes());
481    out.extend_from_slice(&KNN_INDEX_VERSION.to_le_bytes());
482    out.extend_from_slice(&(EMBED_DIMS as u32).to_le_bytes());
483    out.extend_from_slice(&(exemplars.len() as u32).to_le_bytes());
484    for e in exemplars {
485        assert_eq!(e.vec.len(), EMBED_DIMS, "exemplar {} dims drift", e.name);
486        let (q, scale) = quantize(&e.vec);
487        out.extend_from_slice(&(e.label as u32).to_le_bytes());
488        out.extend_from_slice(&scale.to_le_bytes());
489        out.extend_from_slice(&(e.name.len() as u32).to_le_bytes());
490        out.extend_from_slice(e.name.as_bytes());
491        // i8→u8 `as` is a bit-preserving reinterpret, never a conversion.
492        out.extend(q.iter().map(|b| *b as u8));
493    }
494    out
495}
496
497/// Decode [`encode_index`] output, fail-hard like `decode_weights_le`:
498/// wrong magic/version/dims or trailing/truncated bytes panic — a stale
499/// or corrupt artifact must never silently score.
500pub fn decode_index(bytes: &[u8]) -> Vec<Exemplar> {
501    fn take<'a>(bytes: &'a [u8], off: &mut usize, n: usize) -> &'a [u8] {
502        let s = *off;
503        // Overflow saturates to a range `get` shrinks to `None`: any
504        // truncation or wraparound lands in the same loud panic.
505        let e = s.saturating_add(n);
506        let slice = bytes
507            .get(s..e)
508            .filter(|sl| sl.len() == n)
509            .unwrap_or_else(|| panic!("{KNN_INDEX_REL_PATH} corrupt: truncated at byte {s}"));
510        *off = s + slice.len();
511        slice
512    }
513    let mut off = 0usize;
514    let u32le = |s: &[u8]| u32::from_le_bytes(s.try_into().unwrap());
515    assert!(
516        bytes.len() >= 16,
517        "{KNN_INDEX_REL_PATH} corrupt: truncated header"
518    );
519    let magic = u32le(take(bytes, &mut off, 4));
520    let version = u32le(take(bytes, &mut off, 4));
521    let dims = u32le(take(bytes, &mut off, 4));
522    let count = u32le(take(bytes, &mut off, 4));
523    assert_eq!(
524        magic, KNN_INDEX_MAGIC,
525        "{KNN_INDEX_REL_PATH} corrupt: bad magic"
526    );
527    assert_eq!(
528        version, KNN_INDEX_VERSION,
529        "{KNN_INDEX_REL_PATH} stale: want version {KNN_INDEX_VERSION}, have {version}"
530    );
531    assert_eq!(
532        dims as usize, EMBED_DIMS,
533        "{KNN_INDEX_REL_PATH} stale: want dims {EMBED_DIMS}, have {dims}"
534    );
535    let mut exemplars = Vec::with_capacity(count as usize);
536    for _ in 0..count {
537        let label = u32le(take(bytes, &mut off, 4)) as usize;
538        let scale = f32::from_le_bytes(take(bytes, &mut off, 4).try_into().unwrap());
539        let name_len = u32le(take(bytes, &mut off, 4)) as usize;
540        let name = take(bytes, &mut off, name_len);
541        let name = std::str::from_utf8(name)
542            .unwrap_or_else(|_| panic!("{KNN_INDEX_REL_PATH} corrupt: bad name bytes"))
543            .to_string();
544        let raw = take(bytes, &mut off, EMBED_DIMS);
545        let q: Vec<i8> = raw.iter().map(|b| *b as i8).collect();
546        exemplars.push(Exemplar {
547            label,
548            name,
549            vec: dequantize(&q, scale),
550        });
551    }
552    assert_eq!(
553        off,
554        bytes.len(),
555        "{KNN_INDEX_REL_PATH} corrupt: {} trailing bytes",
556        bytes.len() - off
557    );
558    exemplars
559}
560
561/// The clustered corpus in memory: one center per class neighborhood
562/// (see [`clusters_for`]), each EMBED_DIMS floats. Built once
563/// per process (tests) or per CLI invocation — no cache file, no format
564/// to version, re-derivable from the fixtures in seconds.
565pub struct KnnIndex {
566    pub exemplars: Vec<Exemplar>,
567}
568
569impl KnnIndex {
570    /// Downsample + embed one decoded frame. Shared by the index build
571    /// and by queries so both sides see identical pixels.
572    pub fn embed_frame(rgb: &[u8], w: u32, h: u32) -> Vec<f32> {
573        let full = downsample_to_grid_rgb(rgb, w as usize, h as usize);
574        embed(&full)
575    }
576
577    /// Load every `*.png` under `<root>/<version>/<class-dir>/`.
578    /// Deterministic order: versions, names, and dirs all sorted — miss
579    /// lists diff cleanly across runs.
580    pub fn build(corpus_root: &str) -> Self {
581        let mut exemplars = Vec::new();
582        let mut versions: Vec<_> = std::fs::read_dir(corpus_root)
583            .unwrap_or_else(|e| panic!("read {corpus_root}: {e}"))
584            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
585            .collect();
586        versions.sort();
587        for version in versions {
588            if !std::path::Path::new(&format!("{corpus_root}/{version}")).is_dir() {
589                continue;
590            }
591            for (dir, class) in CLASS_DIRS {
592                let dir_path = format!("{corpus_root}/{version}/{dir}");
593                if !std::path::Path::new(&dir_path).is_dir() {
594                    continue;
595                }
596                let mut names: Vec<_> = std::fs::read_dir(&dir_path)
597                    .unwrap_or_else(|e| panic!("read {dir_path}: {e}"))
598                    .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
599                    .filter(|n| n.ends_with(".png"))
600                    .collect();
601                names.sort();
602                for name in names {
603                    let (rgb, w, h) = load_rgb_8bit(&format!("{dir_path}/{name}"));
604                    exemplars.push(Exemplar {
605                        label: class as usize,
606                        name: format!("{version}/{dir}/{name}"),
607                        vec: Self::embed_frame(&rgb, w, h),
608                    });
609                }
610            }
611        }
612        Self { exemplars }
613    }
614
615    /// Per-class clustered index: one [`kmeans`] run per label
616    /// ([`clusters_for`] centers), each center named after its nearest
617    /// member so verdicts still name a viewable frame (`<frame>
618    /// ~centroid`). The shipped shape: ~18 vectors for today's corpus
619    /// instead of 118, and new captures mostly land inside existing
620    /// neighborhoods — the artifact grows with variety, not volume.
621    /// Deterministic: labels in [`BY_INDEX`] order, members in build
622    /// order, fixed-seed clustering — the same corpus rebuilds the same
623    /// bytes, which `bundled_index_matches_fixtures` enforces.
624    pub fn clustered(corpus_root: &str) -> Self {
625        let full = Self::build(corpus_root);
626        let mut exemplars = Vec::new();
627        for label in 0..BY_INDEX.len() {
628            let members: Vec<&Exemplar> =
629                full.exemplars.iter().filter(|e| e.label == label).collect();
630            if members.is_empty() {
631                continue;
632            }
633            let points: Vec<Vec<f32>> = members.iter().map(|e| e.vec.clone()).collect();
634            for center in kmeans(&points, clusters_for(members.len())) {
635                let nearest = members
636                    .iter()
637                    .min_by(|a, b| {
638                        let da: f32 = a
639                            .vec
640                            .iter()
641                            .zip(center.iter())
642                            .map(|(x, y)| (x - y) * (x - y))
643                            .sum();
644                        let db: f32 = b
645                            .vec
646                            .iter()
647                            .zip(center.iter())
648                            .map(|(x, y)| (x - y) * (x - y))
649                            .sum();
650                        da.total_cmp(&db)
651                    })
652                    .unwrap()
653                    .name
654                    .clone();
655                exemplars.push(Exemplar {
656                    label,
657                    name: format!("{nearest} ~centroid"),
658                    vec: center,
659                });
660            }
661        }
662        Self { exemplars }
663    }
664
665    /// Ranked (label, cosine, exemplar name), best first. `skip` excludes
666    /// one exemplar by position (leave-one-out without rebuilding).
667    pub fn query(&self, q: &[f32], skip: Option<usize>, k: usize) -> Vec<(usize, f32, &str)> {
668        let mut ranked: Vec<(usize, f32, &str)> = self
669            .exemplars
670            .iter()
671            .enumerate()
672            .filter(|(i, _)| Some(*i) != skip)
673            .map(|(_, e)| (e.label, cosine(q, &e.vec), e.name.as_str()))
674            .collect();
675        ranked.sort_by(|a, b| b.1.total_cmp(&a.1));
676        ranked.truncate(k);
677        ranked
678    }
679
680    /// Top-1 class + gap + matched exemplar name. The gap is best cosine
681    /// minus the best cosine of any *other* class (single-class index:
682    /// the gap is the top cosine itself). Zero-vector queries (pure
683    /// black) return `Dark` committed — the only hardcoded verdict.
684    /// `None` only when the index (minus `skip`) is empty.
685    pub fn predict(&self, q: &[f32], skip: Option<usize>) -> Option<(ScreenClass, f32, String)> {
686        if q.iter().all(|v| *v == 0.0) {
687            return Some((ScreenClass::Dark, 1.0, "zero-frame".to_string()));
688        }
689        let ranked = self.query(q, skip, self.exemplars.len());
690        let (label, best, name) = ranked.first()?;
691        let runner_up = ranked
692            .iter()
693            .find(|(l, _, _)| l != label)
694            .map(|(_, c, _)| *c)
695            .unwrap_or(0.0);
696        let class = BY_INDEX.iter().find(|c| **c as usize == *label).copied()?;
697        Some((class, best - runner_up, (*name).to_string()))
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704
705    fn gradient_frame() -> [u8; 3 * GRID * GRID] {
706        let mut full = [0u8; 3 * GRID * GRID];
707        for y in 0..GRID {
708            for x in 0..GRID {
709                let v = ((x + y) % 256) as u8;
710                let i = (y * GRID + x) * 3;
711                full[i..i + 3].copy_from_slice(&[v, v, v]);
712            }
713        }
714        full
715    }
716
717    #[test]
718    fn embed_is_unit_norm() {
719        let e = embed(&gradient_frame());
720        let norm = e.iter().map(|v| v * v).sum::<f32>().sqrt();
721        assert!((norm - 1.0).abs() < 1e-5, "norm {norm}");
722    }
723
724    #[test]
725    fn cosine_self_is_one() {
726        let e = embed(&gradient_frame());
727        assert!((cosine(&e, &e) - 1.0).abs() < 1e-5);
728    }
729
730    #[test]
731    fn blur_holds_constant() {
732        // A flat field blurs to itself: no phantom structure invented.
733        let flat = [0.4f32; GRID * GRID];
734        let out = box_blur(&flat);
735        assert!(out.iter().all(|v| (v - 0.4).abs() < 1e-6));
736    }
737
738    #[test]
739    fn index_codec_roundtrips() {
740        // encode→decode preserves labels/names exactly and floats to
741        // within one quantization step: the shipped artifact scores what
742        // the fixtures built, up to int8 noise.
743        let exemplars = vec![
744            Exemplar {
745                label: 3,
746                name: "v/dir/a.png".to_string(),
747                vec: embed(&gradient_frame()),
748            },
749            Exemplar {
750                label: 7,
751                name: "v/dir/b.png".to_string(),
752                vec: vec![0.0; EMBED_DIMS],
753            },
754        ];
755        let back = decode_index(&encode_index(&exemplars));
756        assert_eq!(back.len(), 2);
757        for (a, b) in exemplars.iter().zip(back.iter()) {
758            assert_eq!(a.label, b.label);
759            assert_eq!(a.name, b.name);
760            assert_eq!(a.vec.len(), b.vec.len());
761            let peak = a.vec.iter().fold(0.0f32, |m, x| m.max(x.abs()));
762            let step = peak / 127.0;
763            assert!(
764                a.vec
765                    .iter()
766                    .zip(b.vec.iter())
767                    .all(|(x, y)| (x - y).abs() <= step + 1e-6)
768            );
769        }
770    }
771
772    #[test]
773    #[should_panic(expected = "bad magic")]
774    fn index_decode_rejects_bad_magic() {
775        let mut bytes = encode_index(&[]);
776        bytes[0] ^= 0xff;
777        let _ = decode_index(&bytes);
778    }
779
780    #[test]
781    fn bundled_index_matches_fixtures() {
782        // The baked artifact agrees with a fresh clustered build: same
783        // count, same names, vectors within one quantization step —
784        // commit drift between the artifact and the corpus fails here,
785        // not in production.
786        let root = format!("{}/tests/fixtures", env!("CARGO_MANIFEST_DIR"));
787        let fresh = KnnIndex::clustered(&root);
788        let bundled = bundled_index();
789        assert_eq!(bundled.exemplars.len(), fresh.exemplars.len());
790        for (a, b) in bundled.exemplars.iter().zip(fresh.exemplars.iter()) {
791            assert_eq!(a.label, b.label);
792            assert_eq!(a.name, b.name, "corpus order drift vs artifact");
793            let peak = b.vec.iter().fold(0.0f32, |m, x| m.max(x.abs()));
794            let step = peak / 127.0;
795            assert!(
796                a.vec
797                    .iter()
798                    .zip(b.vec.iter())
799                    .all(|(x, y)| (x - y).abs() <= step + 1e-6)
800            );
801        }
802    }
803
804    #[test]
805    fn all_black_predicts_dark() {
806        let black = [0u8; 3 * GRID * GRID];
807        let e = embed(&black);
808        assert!(e.iter().all(|v| *v == 0.0));
809        let index = KnnIndex { exemplars: vec![] };
810        assert!(matches!(
811            index.predict(&e, None),
812            Some((ScreenClass::Dark, _, _))
813        ));
814    }
815
816    #[test]
817    fn knn_corpus_leave_one_out() {
818        // Every corpus frame queries all *other* frames: the scoreboard
819        // for a pure memorizer. Prints one line per miss (matched
820        // exemplar named — the legibility win).
821        // No accuracy gate: this test reports, the promotion decision
822        // reads the report.
823        let root = format!("{}/tests/fixtures", env!("CARGO_MANIFEST_DIR"));
824        let index = KnnIndex::build(&root);
825        assert!(!index.exemplars.is_empty(), "no fixtures loaded");
826        let mut hits = 0usize;
827        for (i, e) in index.exemplars.iter().enumerate() {
828            let (got, gap, matched) = index.predict(&e.vec, Some(i)).unwrap();
829            let want = BY_INDEX
830                .iter()
831                .find(|c| **c as usize == e.label)
832                .copied()
833                .unwrap();
834            if got == want {
835                hits += 1;
836            } else {
837                println!(
838                    "KNN LOO MISS {}: want {want:?} got {got:?} gap {gap:.4} via {matched}",
839                    e.name
840                );
841            }
842        }
843        let n = index.exemplars.len();
844        println!("KNN LOO {hits}/{n}");
845    }
846
847    #[test]
848    fn knn_holdout_scores() {
849        // Corpus-built index vs tests/fixtures-holdout/<class>/*.png:
850        // unseen layouts — the class directory supplies the expected
851        // label, no lists. Misses print the matched exemplar + gap, so
852        // each one is triageable on sight.
853        let root = format!("{}/tests/fixtures", env!("CARGO_MANIFEST_DIR"));
854        let index = KnnIndex::build(&root);
855        let hold_root = format!("{}/tests/fixtures-holdout", env!("CARGO_MANIFEST_DIR"));
856        let mut hits = 0usize;
857        let mut total = 0usize;
858        for (dir, want) in CLASS_DIRS {
859            let dir_path = format!("{hold_root}/{dir}");
860            if !std::path::Path::new(&dir_path).is_dir() {
861                continue;
862            }
863            let mut names: Vec<_> = std::fs::read_dir(&dir_path)
864                .unwrap()
865                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
866                .filter(|n| n.ends_with(".png"))
867                .collect();
868            names.sort();
869            for name in names {
870                let (rgb, w, h) = load_rgb_8bit(&format!("{dir_path}/{name}"));
871                let q = KnnIndex::embed_frame(&rgb, w, h);
872                let (got, gap, matched) = index.predict(&q, None).unwrap();
873                total += 1;
874                if got == want {
875                    hits += 1;
876                } else {
877                    println!(
878                        "KNN HOLDOUT MISS {dir}/{name}: want {want:?} got {got:?} gap {gap:.4} via {matched}"
879                    );
880                }
881            }
882        }
883        println!("KNN HOLDOUT {hits}/{total}");
884    }
885
886    #[test]
887    fn knn_holdout_quantized() {
888        // The shipped path end to end: holdout frames vs the dequantized
889        // baked artifact (int8 noise included). Any delta vs KNN HOLDOUT
890        // above is the measured cost of 4x smaller shipping — report, no
891        // gate.
892        let index = bundled_index();
893        let hold_root = format!("{}/tests/fixtures-holdout", env!("CARGO_MANIFEST_DIR"));
894        let mut hits = 0usize;
895        let mut total = 0usize;
896        for (dir, want) in CLASS_DIRS {
897            let dir_path = format!("{hold_root}/{dir}");
898            if !std::path::Path::new(&dir_path).is_dir() {
899                continue;
900            }
901            let mut names: Vec<_> = std::fs::read_dir(&dir_path)
902                .unwrap()
903                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
904                .filter(|n| n.ends_with(".png"))
905                .collect();
906            names.sort();
907            for name in names {
908                let (rgb, w, h) = load_rgb_8bit(&format!("{dir_path}/{name}"));
909                let q = KnnIndex::embed_frame(&rgb, w, h);
910                let (got, gap, matched) = index.predict(&q, None).unwrap();
911                total += 1;
912                if got == want {
913                    hits += 1;
914                } else {
915                    println!(
916                        "KNN-Q HOLDOUT MISS {dir}/{name}: want {want:?} got {got:?} gap {gap:.4} via {matched}"
917                    );
918                }
919            }
920        }
921        println!("KNN-Q HOLDOUT {hits}/{total}");
922    }
923
924    #[test]
925    fn knn_holdout_clustered_float() {
926        // Float-centroid reference: same clustered index as the artifact
927        // but unquantized — separates clustering cost from quantization
928        // cost. Compare against KNN HOLDOUT (full index) and KNN-Q
929        // HOLDOUT (quantized, whatever ships).
930        let root = format!("{}/tests/fixtures", env!("CARGO_MANIFEST_DIR"));
931        let index = KnnIndex::clustered(&root);
932        println!("clustered index: {} centers", index.exemplars.len());
933        let hold_root = format!("{}/tests/fixtures-holdout", env!("CARGO_MANIFEST_DIR"));
934        let mut hits = 0usize;
935        let mut total = 0usize;
936        for (dir, want) in CLASS_DIRS {
937            let dir_path = format!("{hold_root}/{dir}");
938            if !std::path::Path::new(&dir_path).is_dir() {
939                continue;
940            }
941            let mut names: Vec<_> = std::fs::read_dir(&dir_path)
942                .unwrap()
943                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
944                .filter(|n| n.ends_with(".png"))
945                .collect();
946            names.sort();
947            for name in names {
948                let (rgb, w, h) = load_rgb_8bit(&format!("{dir_path}/{name}"));
949                let q = KnnIndex::embed_frame(&rgb, w, h);
950                let (got, gap, matched) = index.predict(&q, None).unwrap();
951                total += 1;
952                if got == want {
953                    hits += 1;
954                } else {
955                    println!(
956                        "KNN-C HOLDOUT MISS {dir}/{name}: want {want:?} got {got:?} gap {gap:.4} via {matched}"
957                    );
958                }
959            }
960        }
961        println!("KNN-C HOLDOUT {hits}/{total}");
962    }
963}