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
//! Where each batch size's search runs: the routes an index measures when it is built (from the rates of
//! every path at each batch size timed), and the path a search of a batch takes by them. The Python package
//! times the paths and calls these to decide; the serving API ([`crate::Index`]) takes the same path on the CPU.
//!
//! The routes, as the index file keeps them (JSON): thresholds (`cpu_below`, `gpu_list_from`, `cpu_list_from`,
//! `cpu_blas_from`, `graph_from`, `cpu_ivf_from`, `exact_from`: from which batch size a path is taken),
//! `single` (the path measured fastest at one query, where it beats the thresholds' by MARGIN), and `table`: at
//! each batch size measured, the paths measured there, fastest first (the default path first unless another is
//! MARGIN times faster). A search takes the entry of the largest measured batch size at or below its own and in
//! it the first path it may use; the thresholds serve where none may (and profiles and older files, which have
//! no table).

use serde_json::{Map, Value, json};

/// A threshold no batch reaches.
pub const NEVER: u64 = 1_000_000_000;
/// A measured path replaces the default one only where it is this much faster.
pub const MARGIN: f64 = 1.1;
/// A rate below this share of what its neighbors (half and twice the batch) imply is timed again.
pub const DIP: f64 = 0.8;

/// The routes before any measurement.
pub const DEFAULTS: [(&str, u64); 6] = [
    ("cpu_below", 2),
    ("gpu_list_from", 1000),
    ("cpu_list_from", NEVER),
    ("cpu_blas_from", NEVER),
    ("graph_from", NEVER),
    ("cpu_ivf_from", 1),
];

/// One measured rate: a path ("cpu-query", "gpu-graph", ...), a batch size, queries per second.
pub type Rate = (String, u64, f64);

fn rate(rates: &[Rate], path: &str, b: u64) -> Option<f64> {
    rates
        .iter()
        .find(|(p, bb, _)| p == path && *bb == b)
        .map(|r| r.2)
}

fn has(rates: &[Rate], path: &str) -> bool {
    rates.iter().any(|(p, _, _)| p == path)
}

fn need(rates: &[Rate], path: &str, b: u64) -> Result<f64, String> {
    rate(rates, path, b).ok_or_else(|| format!("no rate measured for {path} at {b} queries"))
}

/// The batch size from which path b is taken over path a, where by default b is taken from `default` up. At a
/// measured batch, b wins from `default` up unless a is MARGIN times faster, and below it only if b is MARGIN
/// times faster. b is taken from the smallest measured batch from which it wins at every larger one; between
/// that batch and the measured one below it (or past the largest measured batch, where a wins), the default
/// decides. `a` and `b` give each measured batch's rate (b at least a's batches).
pub fn crossover_with_margin(a: &[(u64, f64)], b: &[(u64, f64)], default: u64) -> u64 {
    let mut batches: Vec<u64> = a.iter().map(|x| x.0).collect();
    batches.sort_unstable();
    let at = |s: &[(u64, f64)], x: u64| s.iter().find(|v| v.0 == x).map_or(0.0, |v| v.1);
    let wins = |x: u64| {
        let (ra, rb) = (at(a, x), at(b, x));
        if x >= default {
            rb * MARGIN >= ra
        } else {
            rb >= MARGIN * ra
        }
    };
    let i = (0..batches.len())
        .find(|&i| batches[i..].iter().all(|&y| wins(y)))
        .unwrap_or(batches.len());
    if i == 0 {
        return batches.first().copied().unwrap_or(default);
    }
    let upper = if i < batches.len() { batches[i] } else { NEVER };
    (batches[i - 1] + 1).max(upper.min(default))
}

/// The thresholds, each from the routes or the defaults.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Thresholds {
    pub cpu_below: u64,
    pub gpu_list_from: u64,
    pub cpu_list_from: u64,
    pub cpu_blas_from: u64,
    pub graph_from: u64,
    pub cpu_ivf_from: u64,
    pub exact_from: u64,
}

impl Thresholds {
    fn from(r: &Map<String, Value>) -> Thresholds {
        let get = |k: &str, default: u64| r.get(k).and_then(Value::as_u64).unwrap_or(default);
        let d = |k: &str| DEFAULTS.iter().find(|x| x.0 == k).map_or(NEVER, |x| x.1);
        Thresholds {
            cpu_below: get("cpu_below", d("cpu_below")),
            gpu_list_from: get("gpu_list_from", d("gpu_list_from")),
            cpu_list_from: get("cpu_list_from", d("cpu_list_from")),
            cpu_blas_from: get("cpu_blas_from", d("cpu_blas_from")),
            graph_from: get("graph_from", d("graph_from")),
            cpu_ivf_from: get("cpu_ivf_from", d("cpu_ivf_from")),
            exact_from: get("exact_from", NEVER),
        }
    }
}

/// The path the thresholds give a batch of `b` (no device given; the single-query route aside): exact search
/// from `exact_from`, else by device, graph and scan.
pub fn routed_path(t: &Thresholds, b: u64, graph_gpu: bool, graph_cpu: bool) -> &'static str {
    if b >= t.exact_from {
        return if b >= t.cpu_below {
            "gpu-exact"
        } else {
            "cpu-exact"
        };
    }
    if b >= t.cpu_below {
        if graph_gpu && b >= t.graph_from {
            return "gpu-graph";
        }
        return if b >= t.gpu_list_from {
            "gpu-list"
        } else {
            "gpu-query"
        };
    }
    if graph_cpu && b < t.cpu_ivf_from {
        return "cpu-graph";
    }
    if b == 1 {
        return "cpu-split";
    }
    if b >= t.cpu_list_from {
        return "cpu-list";
    }
    if b >= t.cpu_blas_from {
        "cpu-query-blas"
    } else {
        "cpu-query"
    }
}

fn defaults() -> Thresholds {
    Thresholds::from(&Map::new())
}

/// The table: at each batch size measured, its paths fastest first (a stable order: ties keep the order measured),
/// the default path first unless another is MARGIN times faster.
pub fn route_table(
    rates: &[Rate],
    batches: &[u64],
    graph_gpu: bool,
    graph_cpu: bool,
) -> Vec<(u64, Vec<String>)> {
    let mut table = Vec::new();
    for &b in batches {
        let here: Vec<(&str, f64)> = rates
            .iter()
            .filter(|r| r.1 == b)
            .map(|r| (r.0.as_str(), r.2))
            .collect();
        if here.is_empty() {
            continue;
        }
        let mut order: Vec<(&str, f64)> = here.clone();
        order.sort_by(|x, y| y.1.total_cmp(&x.1));
        let default = routed_path(&defaults(), b, graph_gpu, graph_cpu);
        if let Some(&(_, dr)) = here.iter().find(|x| x.0 == default)
            && order[0].1 < MARGIN * dr
        {
            order.retain(|x| x.0 != default);
            order.insert(0, (default, dr));
        }
        table.push((b, order.into_iter().map(|x| x.0.to_string()).collect()));
    }
    table
}

/// The (path, batch) rates to time again: each well below what its neighbors at half and twice the batch imply
/// (DIP of their geometric mean), the GPU's first, then by batch and path.
pub fn dips(rates: &[Rate]) -> Vec<(String, u64)> {
    let mut out: Vec<(bool, u64, String)> = Vec::new();
    for (p, b, r) in rates {
        let lo = rate(rates, p, b / 2);
        let hi = rate(rates, p, b * 2);
        if let (Some(lo), Some(hi)) = (lo, hi)
            && lo != 0.0
            && hi != 0.0
            && *r < DIP * (lo * hi).sqrt()
        {
            out.push((!p.starts_with("gpu"), *b, p.clone()));
        }
    }
    out.sort();
    out.into_iter().map(|(_, b, p)| (p, b)).collect()
}

/// The routes from the measured rates (in the order measured) at `batches`, as Python's `measure_routes` decides
/// them; `gpu`: the GPU was timed. Which paths were timed is read from the rates.
pub fn from_rates(rates: &[Rate], batches: &[u64], gpu: bool) -> Result<Value, String> {
    let mut cpu_batches: Vec<u64> = rates
        .iter()
        .filter(|r| r.0.starts_with("cpu") && r.0 != "cpu-exact")
        .map(|r| r.1)
        .collect();
    cpu_batches.sort_unstable();
    cpu_batches.dedup();
    let many: Vec<u64> = cpu_batches.iter().copied().filter(|&b| b > 1).collect();
    let series = |path: &str, at: &[u64]| -> Result<Vec<(u64, f64)>, String> {
        at.iter().map(|&b| Ok((b, need(rates, path, b)?))).collect()
    };
    let mut cq = series("cpu-query", &many)?;
    let cl = series("cpu-list", &many)?;
    let mut t = defaults();
    t.cpu_blas_from = NEVER;
    if has(rates, "cpu-query-blas") && !cq.is_empty() {
        let cqb = series("cpu-query-blas", &many)?;
        t.cpu_blas_from = crossover_with_margin(&cq, &cqb, NEVER);
        cq = cq
            .iter()
            .zip(&cqb)
            .map(|(q, bq)| if q.0 >= t.cpu_blas_from { *bq } else { *q })
            .collect();
    }
    t.cpu_list_from = if cq.is_empty() {
        NEVER
    } else {
        crossover_with_margin(&cq, &cl, NEVER)
    };
    let mut cpu: Vec<(u64, f64)> = Vec::new();
    for &b in &cpu_batches {
        let r = if b == 1 {
            need(rates, "cpu-split", b)?
        } else {
            let q = cq.iter().find(|x| x.0 == b).map_or(0.0, |x| x.1);
            let l = cl.iter().find(|x| x.0 == b).map_or(0.0, |x| x.1);
            q.max(l)
        };
        cpu.push((b, r));
    }
    t.cpu_ivf_from = 1;
    let cpu_graph = has(rates, "cpu-graph");
    if cpu_graph {
        let cg = series("cpu-graph", &cpu_batches)?;
        t.cpu_ivf_from = crossover_with_margin(&cg, &cpu, 1);
        cpu = cpu
            .iter()
            .zip(&cg)
            .map(|(c, g)| if c.0 >= t.cpu_ivf_from { *c } else { *g })
            .collect();
    }
    let mut gpu_paths: Vec<&str> = vec!["gpu-query"];
    let list_major = has(rates, "gpu-list");
    if list_major {
        gpu_paths.push("gpu-list");
    }
    let graph_gpu = has(rates, "gpu-graph");
    if graph_gpu {
        gpu_paths.push("gpu-graph");
    }
    if has(rates, "gpu-plugin-graph") {
        gpu_paths.push("gpu-plugin-graph");
    }
    if gpu {
        let gq = series("gpu-query", batches)?;
        let mut ivf_gpu = gq.clone();
        t.gpu_list_from = NEVER;
        if list_major {
            let gl = series("gpu-list", batches)?;
            t.gpu_list_from = crossover_with_margin(&gq, &gl, 1000);
            ivf_gpu = gq
                .iter()
                .zip(&gl)
                .map(|(q, l)| if q.0 >= t.gpu_list_from { *l } else { *q })
                .collect();
        }
        t.graph_from = NEVER;
        if graph_gpu {
            let gg = series("gpu-graph", batches)?;
            t.graph_from = crossover_with_margin(&ivf_gpu, &gg, NEVER);
        }
        let mut best_gpu = Vec::new();
        for &b in &cpu_batches {
            let mut best = f64::NEG_INFINITY;
            for p in &gpu_paths {
                best = best.max(need(rates, p, b)?);
            }
            best_gpu.push((b, best));
        }
        t.cpu_below = crossover_with_margin(&cpu, &best_gpu, 2);
    } else {
        t.cpu_below = NEVER;
        t.gpu_list_from = NEVER;
        t.graph_from = NEVER;
    }
    t.exact_from = NEVER;
    if has(rates, "cpu-exact") || has(rates, "gpu-exact") {
        let (mut ex, mut ap) = (Vec::new(), Vec::new());
        for &b in batches {
            let e: Vec<f64> = ["gpu-exact", "cpu-exact"]
                .iter()
                .filter_map(|p| rate(rates, p, b))
                .collect();
            let a = rate(rates, routed_path(&t, b, graph_gpu, cpu_graph), b);
            if let Some(a) = a
                && !e.is_empty()
                && a != 0.0
            {
                ex.push((b, e.iter().copied().fold(f64::NEG_INFINITY, f64::max)));
                ap.push((b, a));
            }
        }
        if !ex.is_empty() {
            t.exact_from = crossover_with_margin(&ap, &ex, NEVER);
        }
    }
    let table = route_table(rates, batches, graph_gpu, cpu_graph);
    let mut out = json!({
        "cpu_blas_from": t.cpu_blas_from,
        "cpu_list_from": t.cpu_list_from,
        "cpu_ivf_from": t.cpu_ivf_from,
        "gpu_list_from": t.gpu_list_from,
        "graph_from": t.graph_from,
        "cpu_below": t.cpu_below,
        "exact_from": t.exact_from,
        "table": table.iter().map(|(b, p)| json!([b, p])).collect::<Vec<_>>(),
    });
    // single queries: the path fastest at one query (the first measured among equals), where it beats the
    // thresholds' path by MARGIN
    let one: Vec<(&str, f64)> = rates
        .iter()
        .filter(|r| r.1 == 1)
        .map(|r| (r.0.as_str(), r.2))
        .collect();
    let given = routed_path(&t, 1, graph_gpu, cpu_graph);
    let mut best: Option<(&str, f64)> = None;
    for &(p, r) in &one {
        if best.is_none_or(|b| r > b.1) {
            best = Some((p, r));
        }
    }
    if let (Some(best), Some(&(_, g))) = (best, one.iter().find(|x| x.0 == given))
        && best.0 != given
        && best.1 >= MARGIN * g
    {
        out["single"] = json!(best.0);
    }
    Ok(out)
}

/// What a search may use, for `Routes::path`.
#[derive(Clone, Copy, Debug)]
pub struct Can {
    /// The device the search is held to ("cpu" or "gpu"), if any.
    pub device: Option<&'static str>,
    /// Approximate only: exact search left out (a search given nprobe).
    pub approximate: bool,
    pub gpu: bool,
    pub graph: bool,
    pub graph_gpu: bool,
    pub plugin_graph: bool,
}

/// An index's routes, parsed.
#[derive(Clone, Debug)]
pub struct Routes {
    t: Thresholds,
    single: Option<String>,
    table: Vec<(u64, Vec<String>)>,
}

impl Routes {
    /// From the routes as the index file keeps them (a JSON object; null or empty: the defaults).
    pub fn parse(v: &Value) -> Routes {
        let empty = Map::new();
        let r = v.as_object().unwrap_or(&empty);
        let table = r
            .get("table")
            .and_then(Value::as_array)
            .map(|t| {
                t.iter()
                    .filter_map(|e| {
                        let b = e.get(0)?.as_u64()?;
                        let paths = e
                            .get(1)?
                            .as_array()?
                            .iter()
                            .filter_map(|p| p.as_str().map(String::from))
                            .collect();
                        Some((b, paths))
                    })
                    .collect()
            })
            .unwrap_or_default();
        Routes {
            t: Thresholds::from(r),
            single: r.get("single").and_then(Value::as_str).map(String::from),
            table,
        }
    }

    fn usable(path: &str, can: &Can) -> bool {
        if can.approximate && path.ends_with("exact") {
            return false;
        }
        if let Some(d) = can.device
            && !path.starts_with(d)
        {
            return false;
        }
        if path.starts_with("gpu") && !can.gpu {
            return false;
        }
        if path.ends_with("graph")
            && (!can.graph
                || (path.starts_with("gpu") && !can.graph_gpu)
                || (path == "gpu-plugin-graph" && !can.plugin_graph))
        {
            return false;
        }
        true
    }

    /// The path a batch of `batch` queries takes (Python's `Index._ivf_path`): the first path of the measured
    /// table's entry for its size that it may use, or else by the thresholds.
    pub fn path(&self, batch: u64, can: &Can) -> String {
        let mut t = self.t;
        let mut single = self.single.clone();
        if can.approximate {
            t.exact_from = NEVER;
            if single.as_deref().is_some_and(|s| s.ends_with("exact")) {
                single = None;
            }
        }
        if !self.table.is_empty() {
            let mut entry = &self.table[0].1;
            for (b, paths) in &self.table {
                if *b > batch {
                    break;
                }
                entry = paths;
            }
            if let Some(p) = entry.iter().find(|p| Self::usable(p, can)) {
                return p.clone();
            }
            t.exact_from = NEVER;
            single = None;
        }
        if batch >= t.exact_from {
            let dev = can.device.unwrap_or(if can.gpu && batch >= t.cpu_below {
                "gpu"
            } else {
                "cpu"
            });
            if dev == "cpu" || can.gpu {
                return format!("{dev}-exact");
            }
        }
        if batch == 1
            && let Some(s) = &single
        {
            let ok = (!s.ends_with("graph") || can.graph)
                && (s.starts_with("cpu")
                    || (can.gpu
                        && (!s.ends_with("graph") || can.graph_gpu)
                        && (s != "gpu-plugin-graph" || can.plugin_graph)));
            if ok && can.device.is_none_or(|d| s.starts_with(d)) {
                return s.clone();
            }
        }
        let dev = can
            .device
            .unwrap_or(if batch < t.cpu_below { "cpu" } else { "gpu" });
        if dev == "gpu" {
            if can.graph && can.graph_gpu && batch >= t.graph_from {
                return "gpu-graph".into();
            }
            return if batch >= t.gpu_list_from {
                "gpu-list"
            } else {
                "gpu-query"
            }
            .into();
        }
        if can.graph && batch < t.cpu_ivf_from {
            return "cpu-graph".into();
        }
        if batch == 1 {
            return "cpu-split".into();
        }
        if batch >= t.cpu_list_from {
            return "cpu-list".into();
        }
        if batch >= t.cpu_blas_from {
            "cpu-query-blas"
        } else {
            "cpu-query"
        }
        .into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn crossovers() {
        // b wins from 64 up by more than the margin; between 16 and 64 the default (never b) decides, so b is
        // taken from 64 (as siann._ivf's Python version gave, against which this was checked)
        let a = [(1, 100.0), (16, 100.0), (64, 100.0), (256, 100.0)];
        let b = [(1, 50.0), (16, 50.0), (64, 200.0), (256, 300.0)];
        assert_eq!(crossover_with_margin(&a, &b, NEVER), 64);
        // with b the default from 32 up, the default decides between 16 and 64: from 32
        assert_eq!(crossover_with_margin(&a, &b, 32), 32);
        // b wins everywhere: from the smallest batch
        assert_eq!(
            crossover_with_margin(
                &a,
                &[(1, 500.0), (16, 500.0), (64, 500.0), (256, 500.0)],
                NEVER
            ),
            1
        );
        // b never wins: never
        assert_eq!(
            crossover_with_margin(&a, &[(1, 10.0), (16, 10.0), (64, 10.0), (256, 10.0)], NEVER),
            NEVER
        );
    }

    #[test]
    fn paths_from_the_table_then_the_thresholds() {
        let r = Routes::parse(&json!({
            "cpu_below": 100, "graph_from": 1, "cpu_ivf_from": 8,
            "table": [[1, ["cpu-graph", "gpu-graph"]], [64, ["gpu-graph", "cpu-query"]], [512, ["gpu-graph"]]]
        }));
        let can = Can {
            device: None,
            approximate: false,
            gpu: true,
            graph: true,
            graph_gpu: true,
            plugin_graph: false,
        };
        assert_eq!(r.path(1, &can), "cpu-graph");
        assert_eq!(r.path(100, &can), "gpu-graph");
        let cpu = Can {
            device: Some("cpu"),
            ..can
        };
        assert_eq!(r.path(100, &cpu), "cpu-query");
        // no CPU path in the entry for 512: the thresholds, held to the CPU (from 8 queries the IVF, query-major)
        assert_eq!(r.path(1000, &cpu), "cpu-query");
        assert_eq!(r.path(4, &cpu), "cpu-graph");
        let no_gpu = Can { gpu: false, ..can };
        assert_eq!(r.path(100, &no_gpu), "cpu-query");
    }

    fn thresholds(v: Value) -> Thresholds {
        Thresholds::from(v.as_object().unwrap())
    }

    #[test]
    fn the_thresholds_route() {
        let r = thresholds(json!({"cpu_below": 64, "gpu_list_from": 1000, "exact_from": 4096}));
        assert_eq!(routed_path(&r, 1, false, false), "cpu-split");
        assert_eq!(routed_path(&r, 10, false, false), "cpu-query");
        assert_eq!(routed_path(&r, 100, false, false), "gpu-query");
        assert_eq!(routed_path(&r, 2000, false, false), "gpu-list");
        assert_eq!(routed_path(&r, 5000, false, false), "gpu-exact");
        let g = thresholds(json!({"cpu_below": 64, "graph_from": 128}));
        assert_eq!(routed_path(&g, 200, true, true), "gpu-graph");
        let c = thresholds(json!({"cpu_below": 64, "cpu_ivf_from": 32}));
        assert_eq!(routed_path(&c, 10, true, true), "cpu-graph");
        // a single query by the defaults alone, and as the thresholds move
        let d = defaults();
        assert_eq!(routed_path(&d, 1, false, false), "cpu-split");
        assert_eq!(
            routed_path(&thresholds(json!({"cpu_ivf_from": 8})), 1, false, true),
            "cpu-graph"
        );
        assert_eq!(
            routed_path(&thresholds(json!({"cpu_below": 1})), 1, false, false),
            "gpu-query"
        );
        let gl = thresholds(json!({"cpu_below": 1, "gpu_list_from": 1, "graph_from": NEVER}));
        assert_eq!(routed_path(&gl, 1, true, true), "gpu-list");
    }

    #[test]
    fn the_table_takes_each_batch_to_its_measured_path() {
        let rates: Vec<Rate> = [
            ("cpu-split", 1, 100.0),
            ("cpu-graph", 1, 50.0),
            ("cpu-graph", 8, 900.0),
            ("gpu-graph", 8, 600.0),
            ("gpu-query", 8, 300.0),
            ("gpu-graph", 64, 9000.0),
            ("gpu-query", 64, 3000.0),
            ("gpu-list", 64, 4000.0),
            ("gpu-graph", 512, 20000.0),
            ("gpu-list", 512, 30000.0),
            ("gpu-query", 512, 21000.0),
        ]
        .iter()
        .map(|&(p, b, r)| (p.to_string(), b, r))
        .collect();
        let table = route_table(&rates, &[1, 8, 64, 512], true, true);
        let firsts: Vec<&str> = table.iter().map(|(_, p)| p[0].as_str()).collect();
        assert_eq!(firsts, ["cpu-split", "cpu-graph", "gpu-graph", "gpu-list"]);
        // the default path (gpu-query below 1,000) stays first unless another is 10% faster
        let close: Vec<Rate> = vec![
            ("gpu-query".into(), 64, 1000.0),
            ("gpu-graph".into(), 64, 1050.0),
        ];
        assert_eq!(route_table(&close, &[64], true, true)[0].1[0], "gpu-query");
        let json_table =
            json!({"table": table.iter().map(|(b, p)| json!([b, p])).collect::<Vec<_>>()});
        let r = Routes::parse(&json_table);
        let can = Can {
            device: None,
            approximate: false,
            gpu: true,
            graph: true,
            graph_gpu: true,
            plugin_graph: false,
        };
        assert_eq!(r.path(1, &can), "cpu-split");
        assert_eq!(r.path(7, &can), "cpu-split");
        assert_eq!(r.path(8, &can), "cpu-graph");
        assert_eq!(r.path(100, &can), "gpu-graph");
        assert_eq!(r.path(10_000, &can), "gpu-list");
    }

    #[test]
    fn dips_and_routes_from_rates() {
        let rates: Vec<Rate> = vec![
            ("cpu-split".into(), 1, 9000.0),
            ("cpu-query".into(), 1, 5000.0),
            ("cpu-query".into(), 2, 9000.0),
            ("cpu-list".into(), 2, 4000.0),
            ("cpu-query".into(), 4, 1000.0),
            ("cpu-list".into(), 4, 8000.0),
            ("cpu-query".into(), 8, 30000.0),
            ("cpu-list".into(), 8, 9000.0),
        ];
        assert_eq!(dips(&rates), vec![("cpu-query".to_string(), 4)]);
        let r = from_rates(&rates, &[1, 2, 4, 8], false).unwrap();
        assert_eq!(r["cpu_below"], NEVER);
        assert_eq!(r["table"][0], json!([1, ["cpu-split", "cpu-query"]]));
    }
}