siann 1.0.0

Serve nearest-neighbor indexes built by the siann Python package (exact, IVF, CAGRA graphs) from Rust, on the CPU, with the same results
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! Serving an index that the siann Python package built and saved: [`Index::load`] reads the file
//! `index.save(path)` wrote, and [`Index::search`] returns the same neighbors, in the same order, as the Python
//! package's search on the CPU (`index.search(xq, k, device="cpu")`): the same path for each batch size (the
//! routes measured when the index was built), the same calibrated widths (nprobe, the graph's ef), the same
//! ranking by exact score, ties by row, and the index's own ids. It is also the Python package's CPU core: the
//! package builds one from its parts ([`Index::new`], [`Index::set_ivf`], [`Index::set_graph`]), searches the CPU's
//! paths through [`Index::rows`] and finishes every search, the GPU's included, through [`Index::finish`].

use std::path::Path;
use std::sync::{Arc, OnceLock};

use serde_json::Value;

use super::blas;
use super::flat::Flat;
use super::graph::{Graph, Rows};
use super::ivf::{Ivf, Options, Stored};
use super::metric::Kind;
use super::npz::Npz;
use super::products::{BLAS_FROM, exact_blas};
use super::routes::{Can, Routes};
use super::{Mat, ops};

/// An error loading or searching an index.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Error(String);

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Error {}

impl From<String> for Error {
    fn from(s: String) -> Self {
        Error(s)
    }
}

impl From<&str> for Error {
    fn from(s: &str) -> Self {
        Error(s.to_string())
    }
}

/// The index file's format, as `siann.Index.save` writes it.
const FORMAT: &str = "siann-index";
/// Queries per coarse-step multiply through the BLAS: products of at most 2,048 x nlist floats.
const COARSE_CHUNK: usize = 2048;
/// The latest format version this crate reads.
const FORMAT_VERSION: u64 = 3;

/// Each query's k nearest: `ids` and `scores`, row-major (`queries * k`), best first; -1 and the metric's
/// worst score (infinity for a distance, minus infinity for a similarity) where fewer than k were found.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Neighbors {
    pub ids: Vec<i64>,
    pub scores: Vec<f32>,
    pub k: usize,
}

/// How a search runs: as the index routes its batch size on the CPU (`Auto`), or by one method.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Method {
    /// The path the index measured fastest on the CPU for the batch's size, as the Python package takes it.
    Auto,
    /// Exact search.
    Exact,
    /// The IVF, probing `nprobe` lists (the calibrated number where None), by the scan the index routes the
    /// batch's size to.
    Ivf { nprobe: Option<usize> },
    /// The graph, `ef` candidates wide (the calibrated width where None).
    Graph { ef: Option<usize> },
    /// One path, whatever the batch's size: `width` the IVF's nprobe or the graph's ef (the calibrated one
    /// where None; exact search takes none). `Index::paths` lists an index's paths.
    Path {
        path: SearchPath,
        width: Option<usize>,
    },
}

/// A search path on the CPU, as the Python package names them in `index.paths` and takes them in
/// `search(path=...)`: exact search ("cpu-exact"), the graph ("cpu-graph"), and the IVF's scans, which find the
/// same neighbors by different loops: query-major ("cpu-query"), query-major with each query's lists found
/// through BLAS ("cpu-query-blas"), a single query split over 4 threads ("cpu-split"), list-major ("cpu-list").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SearchPath {
    Exact,
    Graph,
    Query,
    QueryBlas,
    Split,
    List,
}

impl SearchPath {
    /// The path's name, as the Python package gives it ("cpu-list" and so on).
    pub fn name(self) -> &'static str {
        match self {
            SearchPath::Exact => "cpu-exact",
            SearchPath::Graph => "cpu-graph",
            SearchPath::Query => "cpu-query",
            SearchPath::QueryBlas => "cpu-query-blas",
            SearchPath::Split => "cpu-split",
            SearchPath::List => "cpu-list",
        }
    }

    /// The path a name names ("cpu-exact", "cpu-graph", "cpu-query", "cpu-query-blas", "cpu-split", "cpu-list").
    pub fn parse(path: &str) -> Result<SearchPath, Error> {
        Ok(match path {
            "cpu-exact" => SearchPath::Exact,
            "cpu-graph" => SearchPath::Graph,
            "cpu-query" => SearchPath::Query,
            "cpu-query-blas" => SearchPath::QueryBlas,
            "cpu-split" => SearchPath::Split,
            "cpu-list" => SearchPath::List,
            other => return Err(Error(format!("{other} is not a CPU path"))),
        })
    }
}

/// The IVF and its graph, where the index has them.
struct Approx {
    ivf: Ivf,
    centroids: Vec<f32>,
    metric: Kind,
    bytes: bool,
    nprobe: usize,
    graph: Option<(Graph, usize)>,
    routes: Routes,
}

/// An index searched on the CPU: loaded from a file the siann Python package saved, or built from its parts.
pub struct Index {
    x: Arc<[f32]>,
    n: usize,
    d: usize,
    metric: String,
    kernel: Kind,
    ids: Option<Vec<i64>>,
    flat: OnceLock<Flat>,
    norms: OnceLock<Vec<f32>>,
    approx: Option<Approx>,
    recall: Option<f64>,
}

fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, Error> {
    v.get(key)
        .ok_or_else(|| Error(format!("the index file's metadata has no {key}")))
}

impl Index {
    /// An exact index over `x` (rows of `d`; normalized already for cosine), searched by `metric` ("l2", "l1",
    /// "linf", "cosine" or "ip"), its rows known by `ids` (one each; their row numbers where None).
    #[doc(hidden)] // the Python package's: it builds the index from its parts; not part of the crate's API
    pub fn new(x: Vec<f32>, d: usize, metric: &str, ids: Option<Vec<i64>>) -> Result<Index, Error> {
        if d == 0 || !x.len().is_multiple_of(d) {
            return Err("x must hold rows of d values".into());
        }
        let n = x.len() / d;
        if ids.as_ref().is_some_and(|i| i.len() != n) {
            return Err("ids must hold one id per row".into());
        }
        let kernel = Kind::parse(if metric == "cosine" { "ip" } else { metric })?;
        Ok(Index {
            x: x.into(),
            n,
            d,
            metric: metric.to_string(),
            kernel,
            ids,
            flat: OnceLock::new(), // exact search's copy, made when a search first needs it
            norms: OnceLock::new(),
            approx: None,
            recall: None,
        })
    }

    /// Adds the IVF: its `centroids` (rows of d), each row's list (`assign`), searched by `ivf_metric` (cosine as
    /// "l2" on unit vectors), its lists stored as bytes where `bytes`; probing `nprobe` lists by default.
    #[doc(hidden)] // the Python package's: it builds the index from its parts; not part of the crate's API
    pub fn set_ivf(
        &mut self,
        centroids: &[f32],
        assign: &[i64],
        ivf_metric: &str,
        bytes: bool,
        nprobe: usize,
    ) -> Result<(), Error> {
        let metric = Kind::parse(ivf_metric)?;
        let stored = if bytes {
            Stored::U8(self.x.iter().map(|&v| v as u8).collect())
        } else {
            Stored::F32
        };
        let assign_metric = if matches!(metric, Kind::Ip) {
            Kind::L2
        } else {
            metric
        };
        let ivf = Ivf::new(
            self.x.to_vec(),
            centroids,
            self.d,
            metric,
            assign_metric,
            stored,
            Some(assign),
        )?;
        self.approx = Some(Approx {
            ivf,
            centroids: centroids.to_vec(),
            metric,
            bytes,
            nprobe,
            graph: None,
            routes: Routes::parse(&Value::Null),
        });
        Ok(())
    }

    /// Adds the graph to the IVF: `links` (n x `degree`, rows or -1), searched `ef` candidates wide by default;
    /// its search reads float16 copies of the rows where `half` (bytes where the IVF stores bytes, else f32).
    #[doc(hidden)] // the Python package's: it builds the index from its parts; not part of the crate's API
    pub fn set_graph(
        &mut self,
        links: &[i64],
        degree: usize,
        ef: usize,
        half: bool,
    ) -> Result<(), Error> {
        let x = Arc::clone(&self.x);
        let d = self.d;
        let a = self
            .approx
            .as_mut()
            .ok_or("a graph needs the IVF first (set_ivf)")?;
        let rows = if a.bytes {
            Rows::U8(x.iter().map(|&v| v as u8).collect())
        } else if half {
            Rows::half(&x).ok_or("float16 rows need every coordinate within float16's range")?
        } else {
            Rows::F32(Arc::clone(&x))
        };
        a.graph = Some((Graph::new(&x, d, a.metric, rows, links, degree)?, ef));
        Ok(())
    }

    /// Sets the routes (the JSON the index file keeps), for [`Index::search`]'s own choice of path.
    #[doc(hidden)] // the Python package's: it builds the index from its parts; not part of the crate's API
    pub fn set_routes(&mut self, routes: &Value) {
        if let Some(a) = self.approx.as_mut() {
            a.routes = Routes::parse(routes);
        }
    }

    /// Reads an index file that the siann Python package wrote (`index.save(path)`, format version 3 or
    /// earlier). Added vectors are merged and removed ones dropped when Python saves, so the file is searched
    /// as it is.
    pub fn load(path: impl AsRef<Path>) -> Result<Index, Error> {
        let mut z = Npz::open(path.as_ref())?;
        let meta: Value = serde_json::from_str(&z.array("meta")?.text("meta")?)
            .map_err(|e| Error(format!("the index file's metadata is not JSON: {e}")))?;
        if field(&meta, "format")?.as_str() != Some(FORMAT) {
            return Err("not a saved siann index".into());
        }
        let version = field(&meta, "format_version")?.as_u64().unwrap_or(0);
        if version > FORMAT_VERSION {
            return Err(Error(format!(
                "saved in format {version}; this crate reads format {FORMAT_VERSION} and earlier: upgrade it"
            )));
        }
        let x = z.array("x")?;
        let (n, d) = match x.shape[..] {
            [n, d] => (n, d),
            _ => return Err("x is not a matrix".into()),
        };
        let x = x.f32s("x")?;
        let metric = field(&meta, "metric")?
            .as_str()
            .ok_or("metric is not text")?
            .to_string();
        let ids = if z.has("ids") {
            Some(z.array("ids")?.i64s("ids")?)
        } else {
            None
        };
        let mut index = Index::new(x, d, &metric, ids)?;
        index.recall = meta.get("recall").and_then(Value::as_f64);
        if meta.get("kind").and_then(Value::as_str) == Some("ivf") && n > 0 {
            let ivf_metric = field(&meta, "ivf_metric")?
                .as_str()
                .ok_or("ivf_metric is not text")?;
            let bytes = meta.get("storage").and_then(Value::as_str) == Some("uint8");
            let centroids = z.array("centroids")?.f32s("centroids")?;
            let assign = z.array("assign")?.i64s("assign")?;
            let nprobe = field(&meta, "nprobe")?
                .as_u64()
                .ok_or("nprobe is not a number")? as usize;
            index.set_ivf(&centroids, &assign, ivf_metric, bytes, nprobe)?;
            if let (Some(g), true) = (meta.get("graph"), z.has("graph"))
                && !g.is_null()
            {
                let links = z.array("graph")?;
                let degree = *links.shape.get(1).ok_or("graph is not a matrix")?;
                let links = links.i64s("graph")?;
                let ef = g
                    .get("ef")
                    .and_then(Value::as_u64)
                    .ok_or("the graph has no calibrated ef")? as usize;
                let half = g.get("rows").and_then(Value::as_str) == Some("float16");
                index.set_graph(&links, degree, ef, half)?;
            }
            index.set_routes(meta.get("routes").unwrap_or(&Value::Null));
        }
        Ok(index)
    }

    /// The number of vectors.
    pub fn len(&self) -> usize {
        self.n
    }

    /// Whether the index holds no vectors.
    pub fn is_empty(&self) -> bool {
        self.n == 0
    }

    /// The vectors' dimension.
    pub fn dim(&self) -> usize {
        self.d
    }

    /// The metric: "l2", "l1", "linf", "cosine" or "ip".
    pub fn metric(&self) -> &str {
        &self.metric
    }

    /// "exact" or "ivf" (an IVF, perhaps with a graph), as the index was built.
    pub fn kind(&self) -> &str {
        if self.approx.is_some() {
            "ivf"
        } else {
            "exact"
        }
    }

    /// Whether the index has a graph.
    pub fn has_graph(&self) -> bool {
        self.approx.as_ref().is_some_and(|a| a.graph.is_some())
    }

    /// The recall target the index was calibrated to (None for exact search).
    pub fn recall_target(&self) -> Option<f64> {
        self.recall
    }

    /// The calibrated number of lists each query probes (None for exact search).
    pub fn nprobe(&self) -> Option<usize> {
        self.approx.as_ref().map(|a| a.nprobe)
    }

    /// The graph's calibrated search width on the CPU (None without a graph).
    pub fn ef(&self) -> Option<usize> {
        self.approx
            .as_ref()
            .and_then(|a| a.graph.as_ref().map(|g| g.1))
    }

    /// The paths this index can search by (`Method::Path`): exact search, and the IVF's scans and the graph
    /// where it has them, in the order the Python package's `index.paths` lists them.
    pub fn paths(&self) -> Vec<SearchPath> {
        let mut out = vec![SearchPath::Exact];
        if let Some(a) = &self.approx {
            out.extend([
                SearchPath::Split,
                SearchPath::Query,
                SearchPath::QueryBlas,
                SearchPath::List,
            ]);
            if a.graph.is_some() {
                out.push(SearchPath::Graph);
            }
        }
        out
    }

    /// Each query's k nearest; `queries` holds them row by row (a multiple of `dim()` values). The path is the
    /// one the index routes the batch's size to on the CPU.
    pub fn search(&self, queries: &[f32], k: usize) -> Result<Neighbors, Error> {
        self.search_with(queries, k, Method::Auto)
    }

    /// Each query's k nearest by `method`.
    pub fn search_with(
        &self,
        queries: &[f32],
        k: usize,
        method: Method,
    ) -> Result<Neighbors, Error> {
        if k == 0 {
            return Err("k must be positive".into());
        }
        if self.d == 0 || !queries.len().is_multiple_of(self.d) {
            return Err(Error(format!(
                "queries must hold a multiple of {} values",
                self.d
            )));
        }
        if queries.iter().any(|v| !v.is_finite()) {
            return Err("the queries hold infinity or NaN".into());
        }
        let nq = queries.len() / self.d;
        let kk = k.min(self.n);
        if nq == 0 || kk == 0 {
            return self.finish(&[], &[], 0, k).map(|mut f| {
                f.ids = vec![-1; nq * k];
                f.scores = vec![self.worst(); nq * k];
                f
            });
        }
        let q = if self.metric == "cosine" {
            let (v, zeros) = ops::normalize(queries, self.d);
            if zeros > 0 {
                return Err(Error(format!(
                    "cosine is undefined for a zero vector, and the queries hold {zeros}"
                )));
            }
            v
        } else {
            queries.to_vec()
        };
        let (path, width) = self.path(nq, method)?;
        let blas_coarse = matches!(path, SearchPath::QueryBlas | SearchPath::List);
        let rows = self.rows_on(&q, kk, path, width, blas_coarse)?;
        self.finish(&q, &rows, kk, k)
    }

    /// The candidate rows of each query's k nearest (k at most `len()`) by one CPU path ("cpu-exact", "cpu-graph",
    /// "cpu-query", "cpu-query-blas", "cpu-split", "cpu-list"), `width` the IVF's nprobe or the graph's ef: row
    /// numbers, nq x k, -1 where fewer were found, nearest first by the path's own distances. `queries` are as the
    /// index ranks them (normalized already for cosine). `coarse` is how the IVF's batch paths find each query's
    /// lists: "auto" (as the path says: "cpu-query-blas" and "cpu-list" through the BLAS, for L2 and inner product,
    /// where one is linked), "blas" or "rust" (siann's own coarse step).
    #[doc(hidden)] // the Python package's: it builds the index from its parts; not part of the crate's API
    pub fn rows(
        &self,
        queries: &[f32],
        k: usize,
        path: &str,
        width: usize,
        coarse: &str,
    ) -> Result<Vec<i64>, Error> {
        if self.d == 0 || !queries.len().is_multiple_of(self.d) || k == 0 || k > self.n {
            return Err("queries must hold rows of d values, and 0 < k <= len()".into());
        }
        let route = SearchPath::parse(path)?;
        let blas_coarse = match coarse {
            "auto" => matches!(route, SearchPath::QueryBlas | SearchPath::List),
            "blas" => route != SearchPath::Split,
            "rust" => false,
            other => {
                return Err(Error(format!(
                    "coarse must be 'auto', 'blas' or 'rust', not {other}"
                )));
            }
        };
        self.rows_on(queries, k, route, width, blas_coarse)
    }

    fn rows_on(
        &self,
        q: &[f32],
        k: usize,
        route: SearchPath,
        width: usize,
        blas_coarse: bool,
    ) -> Result<Vec<i64>, Error> {
        let nq = q.len() / self.d;
        let found: Vec<u32> = match route {
            SearchPath::Exact => self.exact(q, nq, k)?,
            SearchPath::Graph => {
                let (g, _) = self
                    .approx
                    .as_ref()
                    .and_then(|a| a.graph.as_ref())
                    .ok_or("the index has no graph")?;
                g.search(q, k, width.max(k))?
            }
            SearchPath::Query | SearchPath::QueryBlas | SearchPath::Split | SearchPath::List => {
                let a = self.approx.as_ref().ok_or("the index has no IVF")?;
                let nprobe = width.max(1);
                let split = if route == SearchPath::Split { 4 } else { 1 };
                let scan = |qs: &[f32], p: Option<Mat<'_, f32>>| -> Result<Vec<u32>, Error> {
                    Ok(if route == SearchPath::List {
                        a.ivf.search_list_major(qs, k, nprobe, p)?
                    } else {
                        a.ivf.search(
                            qs,
                            k,
                            nprobe,
                            Options {
                                split,
                                gprobe: 0,
                                threads: 0,
                            },
                            p,
                        )?
                    })
                };
                if blas_coarse && blas::available() && matches!(a.metric, Kind::L2 | Kind::Ip) {
                    // the coarse step's products through the BLAS, COARSE_CHUNK queries at a time (each query's
                    // lists depend on it alone), ranked in Rust as its own coarse step ranks distances
                    let nlist = a.centroids.len() / self.d;
                    let mut out = Vec::with_capacity(nq * k);
                    let mut p = vec![0.0f32; COARSE_CHUNK.min(nq) * nlist];
                    for qs in q.chunks(COARSE_CHUNK * self.d) {
                        let rows = qs.len() / self.d;
                        let buf = &mut p[..rows * nlist];
                        blas::products(qs, &a.centroids, self.d, buf)?;
                        out.extend(scan(
                            qs,
                            Some(Mat {
                                data: buf,
                                rows,
                                cols: nlist,
                            }),
                        )?);
                    }
                    out
                } else {
                    scan(q, None)?
                }
            }
        };
        Ok(found
            .iter()
            .map(|&i| {
                if (i as usize) < self.n {
                    i64::from(i)
                } else {
                    -1
                }
            })
            .collect())
    }

    /// Finishes a search: each query's candidate `rows` (nq x `kk`, -1 for none; any path's, the GPU's included)
    /// ranked by their exact scores, ties by row, mapped to the index's ids, and padded to k with -1 and the
    /// metric's worst score. `queries` as the index ranks them (normalized already for cosine).
    #[doc(hidden)] // the Python package's: it builds the index from its parts; not part of the crate's API
    pub fn finish(
        &self,
        queries: &[f32],
        rows: &[i64],
        kk: usize,
        k: usize,
    ) -> Result<Neighbors, Error> {
        let nq = queries.len().checked_div(self.d).unwrap_or(0);
        if rows.len() != nq * kk || kk > k {
            return Err("rows must be (nq, kk), kk at most k".into());
        }
        if rows.iter().any(|&r| r >= self.n as i64) {
            return Err("a row beyond the index".into());
        }
        let (ids, scores) = if nq == 0 || kk == 0 {
            (Vec::new(), Vec::new())
        } else {
            ops::rank(
                Mat {
                    data: &self.x,
                    rows: self.n,
                    cols: self.d,
                },
                Mat {
                    data: queries,
                    rows: nq,
                    cols: self.d,
                },
                Mat {
                    data: rows,
                    rows: nq,
                    cols: kk,
                },
                self.kernel,
            )?
        };
        let ids: Vec<i64> = match &self.ids {
            Some(own) => ids
                .iter()
                .map(|&i| if i >= 0 { own[i as usize] } else { -1 })
                .collect(),
            None => ids,
        };
        if kk == k {
            return Ok(Neighbors { ids, scores, k });
        }
        let worst = self.worst();
        let mut out = Neighbors {
            ids: Vec::with_capacity(nq * k),
            scores: Vec::with_capacity(nq * k),
            k,
        };
        for r in 0..nq {
            out.ids.extend_from_slice(&ids[r * kk..(r + 1) * kk]);
            out.ids.extend(std::iter::repeat_n(-1, k - kk));
            out.scores.extend_from_slice(&scores[r * kk..(r + 1) * kk]);
            out.scores.extend(std::iter::repeat_n(worst, k - kk));
        }
        Ok(out)
    }

    /// The metric's worst score: infinity for a distance, minus infinity for a similarity.
    fn worst(&self) -> f32 {
        if self.kernel.similarity() {
            f32::NEG_INFINITY
        } else {
            f32::INFINITY
        }
    }

    /// Exact search, as the Python package's search on the CPU runs it: L2 and inner product through the BLAS
    /// from `BLAS_FROM` queries where one is linked, siann's own kernel otherwise.
    fn exact(&self, q: &[f32], nq: usize, k: usize) -> Result<Vec<u32>, Error> {
        if blas::available() && matches!(self.kernel, Kind::L2 | Kind::Ip) && nq >= BLAS_FROM {
            let norms = self.norms.get_or_init(|| {
                if matches!(self.kernel, Kind::L2) {
                    ops::sq_norms(&self.x, self.d)
                } else {
                    vec![0.0; self.n]
                }
            });
            return Ok(exact_blas(&self.x, norms, self.d, q, k)?);
        }
        Ok(self
            .flat
            .get_or_init(|| Flat::new(&self.x, self.d, self.kernel))
            .search(q, k, 32, true)?)
    }

    /// The path and width (nprobe or ef) a batch of `batch` queries takes by `method`.
    fn path(&self, batch: usize, method: Method) -> Result<(SearchPath, usize), Error> {
        let Some(a) = &self.approx else {
            return match method {
                Method::Auto | Method::Exact => Ok((SearchPath::Exact, 0)),
                Method::Path { path, width } => self.given(path, width),
                _ => Err("an exact index has no IVF or graph".into()),
            };
        };
        let ef = a.graph.as_ref().map_or(0, |g| g.1);
        match method {
            Method::Exact => Ok((SearchPath::Exact, 0)),
            Method::Graph { ef: given } => {
                if a.graph.is_none() {
                    return Err("the index has no graph".into());
                }
                Ok((SearchPath::Graph, given.unwrap_or(ef)))
            }
            Method::Ivf { nprobe } => Ok((self.routed(a, batch, true), nprobe.unwrap_or(a.nprobe))),
            Method::Auto => {
                let r = self.routed(a, batch, false);
                Ok((r, if r == SearchPath::Graph { ef } else { a.nprobe }))
            }
            Method::Path { path, width } => self.given(path, width),
        }
    }

    /// The path given by `Method::Path`, checked against the index's paths, with its width (the calibrated one
    /// where None).
    fn given(&self, path: SearchPath, width: Option<usize>) -> Result<(SearchPath, usize), Error> {
        if !self.paths().contains(&path) {
            return Err(Error(format!(
                "{} is not one of this index's paths",
                path.name()
            )));
        }
        let a = self.approx.as_ref();
        match path {
            SearchPath::Exact if width.is_some() => Err("exact search takes no width".into()),
            SearchPath::Exact => Ok((SearchPath::Exact, 0)),
            SearchPath::Graph => Ok((
                path,
                width.unwrap_or_else(|| a.and_then(|a| a.graph.as_ref()).map_or(0, |g| g.1)),
            )),
            _ => Ok((path, width.unwrap_or_else(|| a.map_or(0, |a| a.nprobe)))),
        }
    }

    /// The CPU path the Python package's search on the CPU takes (siann::routes::Routes::path, held to the CPU);
    /// ``ivf_only``: the IVF's paths only (exact search and the graph left out).
    fn routed(&self, a: &Approx, batch: usize, ivf_only: bool) -> SearchPath {
        let can = Can {
            device: Some("cpu"),
            approximate: ivf_only,
            gpu: false,
            graph: a.graph.is_some() && !ivf_only,
            graph_gpu: false,
            plugin_graph: false,
        };
        SearchPath::parse(&a.routes.path(batch as u64, &can)).unwrap_or(SearchPath::Query)
    }
}