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