turbovec 1.0.0

Fast vector quantization with 2-4 bit compression and SIMD search
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
//! Errors returned by the user-facing construct, add and search paths.
//!
//! [`AddError`] is returned by the add paths
//! ([`TurboQuantIndex::add_2d`](crate::TurboQuantIndex::add_2d),
//! [`IdMapIndex::add_with_ids_2d`](crate::IdMapIndex::add_with_ids_2d),
//! [`IdMapIndex::add_with_ids`](crate::IdMapIndex::add_with_ids)).
//!
//! [`ConstructError`] is returned by the constructors
//! ([`TurboQuantIndex::new`](crate::TurboQuantIndex::new),
//! [`TurboQuantIndex::new_lazy`](crate::TurboQuantIndex::new_lazy),
//! [`IdMapIndex::new`](crate::IdMapIndex::new),
//! [`IdMapIndex::new_lazy`](crate::IdMapIndex::new_lazy)).
//!
//! [`SearchError`] is returned by the fallible search paths
//! ([`TurboQuantIndex::try_search`](crate::TurboQuantIndex::try_search),
//! [`TurboQuantIndex::try_search_with_mask`](crate::TurboQuantIndex::try_search_with_mask),
//! [`IdMapIndex::search_with_allowlist`](crate::IdMapIndex::search_with_allowlist)).
//!
//! [`FromPartsError`] is returned by the low-level validated constructor
//! [`TurboQuantIndex::from_parts`](crate::TurboQuantIndex::from_parts),
//! which builds an index directly from already-decoded fields and checks
//! every structural invariant at that single chokepoint.
//!
//! All four are forms of user input error — wrong shape, wrong dim, wrong
//! bit_width, a non-representable coordinate, or a duplicate id — that
//! callers can recover from. Internal
//! preconditions (e.g. calling the low-level `add(&self, &[f32])` on a
//! lazy index that hasn't been committed) still panic, since that
//! signals a contract violation rather than bad input.

use std::error::Error;
use std::fmt;

// Eq dropped from the derive because `InvalidInputValue` carries an f32,
// which is not `Eq` (NaN != NaN). PartialEq still works for the
// finite-input cases tests assert against.
// `#[non_exhaustive]` so adding error variants in future releases is not a
// breaking change — downstream `match` on this enum must carry a wildcard arm.
/// Why an `add` / `add_with_ids` batch was rejected.
///
/// Every variant is raised before any row is written, so a rejected batch
/// leaves the index exactly as it was.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum AddError {
    /// Batch dim does not match the index's already-locked dim.
    DimMismatch {
        /// Dim the index is already committed to.
        existing: usize,
        /// Dim implied by this batch.
        got: usize,
    },

    /// First-add dim on a lazy index must be a multiple of 8.
    DimNotMultipleOf8(usize),

    /// First-add dim on a lazy index exceeds [`MAX_DIM`](crate::MAX_DIM).
    /// Bounds the lazily-built `dim`×`dim` rotation matrix allocation.
    DimTooLarge {
        /// Dim the batch asked for.
        dim: usize,
        /// The ceiling, [`MAX_DIM`](crate::MAX_DIM).
        max: usize,
    },

    /// `vectors.len()` is not a whole multiple of `dim`.
    VectorBufferNotMultipleOfDim {
        /// Length of the flat `vectors` slice.
        vectors_len: usize,
        /// Dim it was divided by.
        dim: usize,
    },

    /// `dim` is 0 — the batch has no columns at all. Kept distinct from
    /// [`Self::VectorBufferNotMultipleOfDim`] and
    /// [`Self::DimNotMultipleOf8`]: neither describes a zero dim
    /// truthfully (every length is a multiple of 0, and `% 0` is
    /// undefined), and the real cause is almost always an embedder that
    /// returned empty embeddings.
    ZeroDim,

    /// Number of ids does not equal number of vectors (`vectors.len() / dim`).
    IdsCountMismatch {
        /// Number of vector rows in the batch.
        expected: usize,
        /// Number of ids supplied.
        got: usize,
    },

    /// External id was already present in the index.
    IdAlreadyPresent(u64),

    /// External id appears more than once within the same batch. Kept
    /// distinct from [`Self::IdAlreadyPresent`], which would send the
    /// caller hunting for a prior insert that never happened.
    DuplicateIdInBatch(u64),

    /// A coordinate in the input vectors is not finite (NaN, +Inf, -Inf)
    /// or has magnitude `>= 1e16`. Either silently corrupts the index:
    ///   - NaN/Inf: poisons the per-vector scale via `0 * NaN = NaN`,
    ///     making the slot exist in `len()` but never reachable through
    ///     `search`.
    ///   - Huge magnitude: overflows the f32 sum-of-squares in the norm
    ///     computation to `+Inf`, so `scale[i] = Inf` and the slot
    ///     incorrectly wins top-k against every query.
    InvalidInputValue {
        /// Row within the batch (0-based), not a slot in the index.
        vector_index: usize,
        /// Coordinate within that row.
        coord_index: usize,
        /// The offending value.
        value: f32,
    },
}

impl fmt::Display for AddError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DimMismatch { existing, got } => {
                write!(f, "dim mismatch: index dim={existing}, batch dim={got}")
            }
            Self::DimNotMultipleOf8(dim) => {
                write!(f, "dim must be a multiple of 8, got {dim}")
            }
            Self::DimTooLarge { dim, max } => {
                write!(f, "dim {dim} exceeds maximum {max}")
            }
            Self::VectorBufferNotMultipleOfDim { vectors_len, dim } => write!(
                f,
                "vector buffer length {vectors_len} not a multiple of dim {dim}",
            ),
            Self::ZeroDim => write!(
                f,
                "dim is 0: the vectors have no columns (an embedder that \
                 returned empty embeddings is the usual cause)",
            ),
            Self::IdsCountMismatch { expected, got } => {
                write!(f, "expected {expected} ids, got {got}")
            }
            Self::IdAlreadyPresent(id) => {
                write!(f, "id {id} already present in index")
            }
            Self::DuplicateIdInBatch(id) => {
                write!(f, "duplicate id {id} appears more than once in this batch")
            }
            Self::InvalidInputValue {
                vector_index,
                coord_index,
                value,
            } => write!(
                f,
                "invalid input value at vector {vector_index}, coord {coord_index}: {value} \
                 (must be finite and |value| < 1e16 to avoid f32 norm overflow)",
            ),
        }
    }
}

impl Error for AddError {}

// `#[non_exhaustive]` so adding error variants in future releases is not a
// breaking change — downstream `match` on this enum must carry a wildcard arm.
/// Why a `new` / `with_bit_width` constructor rejected its arguments.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConstructError {
    /// `bit_width` must be 2, 3, or 4.
    BitWidthOutOfRange(usize),

    /// `dim` must be a positive multiple of 8.
    DimNotPositiveMultipleOf8(usize),

    /// `dim` exceeds [`MAX_DIM`](crate::MAX_DIM). Bounds the lazily-built
    /// `dim`×`dim` rotation matrix allocation.
    DimTooLarge {
        /// Dim the caller asked for.
        dim: usize,
        /// The ceiling, [`MAX_DIM`](crate::MAX_DIM).
        max: usize,
    },
}

impl fmt::Display for ConstructError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BitWidthOutOfRange(bw) => {
                write!(f, "bit_width must be 2, 3, or 4, got {bw}")
            }
            Self::DimNotPositiveMultipleOf8(dim) => {
                write!(f, "dim must be a positive multiple of 8, got {dim}")
            }
            Self::DimTooLarge { dim, max } => {
                write!(f, "dim {dim} exceeds maximum {max}")
            }
        }
    }
}

impl Error for ConstructError {}

/// Error returned by the crate's fallible search paths:
/// [`TurboQuantIndex::try_search`](crate::TurboQuantIndex::try_search),
/// [`TurboQuantIndex::try_search_with_mask`](crate::TurboQuantIndex::try_search_with_mask)
/// and
/// [`IdMapIndex::search_with_allowlist`](crate::IdMapIndex::search_with_allowlist).
///
/// Every variant describes *caller-supplied data* that the index cannot
/// score: a query buffer whose length disagrees with the index dim, a
/// coordinate the scoring kernel cannot represent, a mask sized for a
/// different index, or an allowlist that drifted out of step with the
/// index's contents. All four arrive from outside the process in a real
/// service — an embedding endpoint, a metadata store, an HTTP body — so
/// they are reported rather than panicked. The Python binding already
/// maps them to `ValueError` / `KeyError`.
///
/// Which variants a given method can produce:
///
/// | variant | `try_search` | `try_search_with_mask` | `search_with_allowlist` |
/// |---|---|---|---|
/// | [`QueryBufferNotMultipleOfDim`](Self::QueryBufferNotMultipleOfDim) | yes | yes | yes |
/// | [`InvalidQueryValue`](Self::InvalidQueryValue) | yes | yes | yes |
/// | [`MaskLengthMismatch`](Self::MaskLengthMismatch) | no | yes | no |
/// | [`AllowlistEmpty`](Self::AllowlistEmpty) | no | no | yes |
/// | [`UnknownId`](Self::UnknownId) | no | no | yes |
///
/// `#[non_exhaustive]` so adding variants in future releases is not a
/// breaking change — downstream `match` must carry a wildcard arm.
// Eq is not derived because `InvalidQueryValue` carries an f32, which is
// not `Eq` (NaN != NaN) — the same reason `AddError` and `FromPartsError`
// drop it. PartialEq still works for the finite values tests assert
// against, and every other variant compares as before.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SearchError {
    /// The allowlist was `Some` but empty. An empty allowlist selects no
    /// slots, which is almost always a caller-side filter bug rather than
    /// a request for zero results; pass `None` to search everything.
    AllowlistEmpty,

    /// An allowlist id is not present in the index.
    UnknownId(u64),

    /// `queries.len()` is not a whole multiple of the index dim, so the
    /// buffer does not describe a whole number of query rows.
    QueryBufferNotMultipleOfDim {
        /// Length of the flat `queries` slice.
        queries_len: usize,
        /// Index dim it was divided by.
        dim: usize,
    },

    /// A query coordinate is not finite (NaN, +Inf, -Inf) or has
    /// magnitude `>= 1e16`. Such a value poisons the SIMD scoring kernel:
    /// the accumulator goes to NaN/Inf and the query's top-`k` becomes
    /// arbitrary indices with meaningless scores, silently.
    InvalidQueryValue {
        /// Query row within the batch (0-based).
        query_index: usize,
        /// Coordinate within that row.
        coord_index: usize,
        /// The offending value.
        value: f32,
    },

    /// The search mask's length does not equal the index's vector count,
    /// so slot `i` of the mask does not name slot `i` of the index.
    MaskLengthMismatch {
        /// The index's `len()`, which the mask must match.
        expected: usize,
        /// The mask length supplied.
        got: usize,
    },
}

impl fmt::Display for SearchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AllowlistEmpty => write!(f, "allowlist is empty"),
            Self::UnknownId(id) => {
                write!(f, "id {id} in allowlist is not present in index")
            }
            Self::QueryBufferNotMultipleOfDim { queries_len, dim } => write!(
                f,
                "query buffer length {queries_len} not a multiple of dim {dim}",
            ),
            Self::InvalidQueryValue {
                query_index,
                coord_index,
                value,
            } => write!(
                f,
                "invalid query value at query {query_index}, coord {coord_index}: {value} \
                 (must be finite and |value| < 1e16 to avoid f32 overflow)",
            ),
            Self::MaskLengthMismatch { expected, got } => write!(
                f,
                "mask length {got} does not match index size {expected}",
            ),
        }
    }
}

impl Error for SearchError {}

/// Error returned by
/// [`TurboQuantIndex::from_parts`](crate::TurboQuantIndex::from_parts) when
/// the supplied fields violate one of the index's structural invariants.
///
/// `from_parts` is the single validated entry point for constructing an
/// index directly from already-decoded bytes (the low-level API a
/// database-storage embedder builds against — see the crate docs). Every
/// invariant it checks maps to one variant here, so a caller passing a
/// mismatched buffer, an out-of-range `bit_width`, or an inconsistent lazy
/// state gets a named error instead of a panic, an out-of-bounds read, or a
/// silently-wrong index.
///
/// `#[non_exhaustive]` so adding variants in future releases is not a
/// breaking change — downstream `match` must carry a wildcard arm.
// Eq is not derived because the value-validation variants carry an f32,
// which is not `Eq` (NaN != NaN). PartialEq still works for the finite
// values tests assert against.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FromPartsError {
    /// `bit_width` must be 2, 3, or 4.
    BitWidthOutOfRange(usize),

    /// `dim` (when committed, i.e. `Some`) must be a positive multiple of 8.
    /// The packed layout allocates `dim / 8` bytes per bit-plane, so no
    /// other dim has a valid layout.
    DimNotPositiveMultipleOf8(usize),

    /// `dim` exceeds [`MAX_DIM`](crate::MAX_DIM). Bounds the lazily-built
    /// `dim`×`dim` rotation matrix and the `bit_width`/`dim` codebook
    /// allocation (guards the unbounded-allocation DoS class).
    DimTooLarge {
        /// Dim supplied.
        dim: usize,
        /// The ceiling, [`MAX_DIM`](crate::MAX_DIM).
        max: usize,
    },

    /// `n_vectors * dim * bit_width / 8` overflows `usize`, so no
    /// `packed_codes` buffer of the implied length can exist. Mirrors the
    /// loader's checked size arithmetic.
    PackedCodesSizeOverflow {
        /// Row count supplied.
        n_vectors: usize,
        /// Dim supplied.
        dim: usize,
        /// Bit width supplied.
        bit_width: usize,
    },

    /// `packed_codes.len()` does not equal the length implied by
    /// `n_vectors * dim * bit_width / 8`.
    PackedCodesLengthMismatch {
        /// Byte length implied by `n_vectors`, `dim` and `bit_width`.
        expected: usize,
        /// Byte length of the `packed_codes` supplied.
        got: usize,
    },

    /// `scales.len()` does not equal `n_vectors`.
    ScalesLengthMismatch {
        /// `n_vectors`, which `scales` must match.
        expected: usize,
        /// Length of the `scales` supplied.
        got: usize,
    },

    /// The two TQ+ calibration arrays disagree in length
    /// (`tqplus_shift.len() != tqplus_scale.len()`).
    TqplusLengthMismatch {
        /// Length of `tqplus_shift`.
        shift_len: usize,
        /// Length of `tqplus_scale`.
        scale_len: usize,
    },

    /// A non-empty TQ+ calibration array has a length that is not `dim`.
    TqplusLengthNotDim {
        /// Length of the offending calibration array.
        got: usize,
        /// The dim it had to equal.
        dim: usize,
    },

    /// A per-vector scale is not finite or is negative. The encoder only
    /// ever emits finite, non-negative scales; an Inf slot would win every
    /// top-1 and a NaN slot would vanish from all results. Mirrors the
    /// loader's value validation, so a `from_parts`-accepted index always
    /// survives its own `write` → `load` round-trip.
    InvalidScaleValue {
        /// Index into `scales` (equivalently, the index slot).
        slot: usize,
        /// The offending value.
        value: f32,
    },

    /// A TQ+ shift coordinate is not finite. Mirrors the loader's value
    /// validation.
    InvalidTqplusShiftValue {
        /// Coordinate index into `tqplus_shift`.
        coord: usize,
        /// The offending value.
        value: f32,
    },

    /// A TQ+ scale coordinate is not finite or is `<= 0`. Search divides
    /// by `tqplus_scale`, so such a value silently turns every query's
    /// scores into NaN/Inf. Mirrors the loader's value validation.
    InvalidTqplusScaleValue {
        /// Coordinate index into `tqplus_scale`.
        coord: usize,
        /// The offending value.
        value: f32,
    },

    /// Lazy (uncommitted, `dim == None`) index must have `n_vectors == 0`.
    LazyMustHaveZeroVectors(usize),

    /// Lazy index must have empty `packed_codes`.
    LazyMustHaveEmptyPackedCodes(usize),

    /// Lazy index must have empty `scales`.
    LazyMustHaveEmptyScales(usize),

    /// Lazy index must have empty TQ+ calibration arrays.
    LazyMustHaveEmptyTqplus(usize),
}

impl fmt::Display for FromPartsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BitWidthOutOfRange(bw) => {
                write!(f, "bit_width must be 2, 3, or 4, got {bw}")
            }
            Self::DimNotPositiveMultipleOf8(dim) => {
                write!(f, "dim must be a positive multiple of 8, got {dim}")
            }
            Self::DimTooLarge { dim, max } => {
                write!(f, "dim {dim} exceeds maximum {max}")
            }
            Self::PackedCodesSizeOverflow { n_vectors, dim, bit_width } => write!(
                f,
                "packed code size n_vectors({n_vectors}) * dim({dim}) * \
                 bit_width({bit_width}) / 8 overflows usize",
            ),
            Self::PackedCodesLengthMismatch { expected, got } => write!(
                f,
                "packed_codes length {got} != n_vectors * dim * bit_width / 8 = {expected}",
            ),
            Self::ScalesLengthMismatch { expected, got } => {
                write!(f, "scales length {got} != n_vectors {expected}")
            }
            Self::TqplusLengthMismatch { shift_len, scale_len } => write!(
                f,
                "tqplus_shift length {shift_len} != tqplus_scale length {scale_len}",
            ),
            Self::TqplusLengthNotDim { got, dim } => {
                write!(f, "non-empty TQ+ calibration length {got} must equal dim {dim}")
            }
            Self::InvalidScaleValue { slot, value } => write!(
                f,
                "invalid per-vector scale at slot {slot}: {value} (must be finite, \
                 non-negative, and small enough not to drive a score to infinity)",
            ),
            Self::InvalidTqplusShiftValue { coord, value } => {
                write!(
                    f,
                    "invalid TQ+ shift at coord {coord}: {value} (must be finite and \
                     small enough that the dim-long bias dot product stays finite)"
                )
            }
            Self::InvalidTqplusScaleValue { coord, value } => write!(
                f,
                "invalid TQ+ scale at coord {coord}: {value} (must be finite and large \
                 enough that a query divided by it stays finite when summed \
                 across every coordinate)",
            ),
            Self::LazyMustHaveZeroVectors(n) => {
                write!(f, "lazy (uncommitted-dim) index must have n_vectors=0, got {n}")
            }
            Self::LazyMustHaveEmptyPackedCodes(len) => {
                write!(f, "lazy index must have empty packed_codes, got length {len}")
            }
            Self::LazyMustHaveEmptyScales(len) => {
                write!(f, "lazy index must have empty scales, got length {len}")
            }
            Self::LazyMustHaveEmptyTqplus(len) => {
                write!(f, "lazy index must have empty TQ+ calibration, got length {len}")
            }
        }
    }
}

impl Error for FromPartsError {}

// PartialEq (not Eq) for the same reason `AddError` drops it: the
// `InvalidInputValue` variant carries an f32.
// `#[non_exhaustive]` so adding variants later is not a breaking change.
/// Why an explicit TQ+ calibration request was rejected.
///
/// Returned by
/// [`TurboQuantIndex::calibrate_2d`](crate::TurboQuantIndex::calibrate_2d),
/// [`TurboQuantIndex::calibrate`](crate::TurboQuantIndex::calibrate),
/// [`IdMapIndex::calibrate_2d`](crate::IdMapIndex::calibrate_2d) and
/// [`IdMapIndex::calibrate`](crate::IdMapIndex::calibrate).
///
/// Every variant is raised before anything in the index is touched, so a
/// rejected call leaves the index exactly as it was — same calibration,
/// same stored rows, same (possibly still uncommitted) dim.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum CalibrateError {
    /// The sample has fewer rows than a stable quantile fit needs. Below
    /// this floor the fit would come out as identity, which — once
    /// committed — would silently cost the index TQ+ for the rest of its
    /// life, so it is refused instead.
    SampleTooSmall {
        /// Rows supplied (`sample.len() / dim`).
        rows: usize,
        /// The floor, [`MIN_CALIBRATION_ROWS`](crate::MIN_CALIBRATION_ROWS).
        min: usize,
    },

    /// Sample dim does not match the index's already-locked dim.
    DimMismatch {
        /// Dim the index is already committed to.
        existing: usize,
        /// Dim implied by this sample.
        got: usize,
    },

    /// `dim` is 0 — the sample has no columns at all. Kept distinct from
    /// [`Self::SampleBufferNotMultipleOfDim`] for the reason
    /// [`AddError::ZeroDim`] is.
    ZeroDim,

    /// First-dim commit on a lazy index must be a multiple of 8.
    DimNotMultipleOf8(usize),

    /// First-dim commit on a lazy index exceeds [`MAX_DIM`](crate::MAX_DIM).
    DimTooLarge {
        /// Dim the sample asked for.
        dim: usize,
        /// The ceiling, [`MAX_DIM`](crate::MAX_DIM).
        max: usize,
    },

    /// `sample.len()` is not a whole multiple of `dim`. Unlike the add
    /// paths — where a ragged buffer panics as a caller-side bug — this
    /// is a typed error: the calibration sample is often assembled by
    /// the caller from a reservoir or a random draw, where an off-by-one
    /// is data-shaped rather than a contract violation.
    SampleBufferNotMultipleOfDim {
        /// Length of the flat `sample` slice.
        sample_len: usize,
        /// Dim it was divided by.
        dim: usize,
    },

    /// The fit came out as exact identity: every coordinate's anchor
    /// quantiles coincide, which happens when the sample carries no
    /// per-coordinate spread — all-equal rows (however many), or
    /// all-zero rows. Committing it would report
    /// [`CalibrationState::Calibrated`](crate::CalibrationState) while
    /// behaving exactly as `Uncalibrated` — and not even round-trip,
    /// since serialization canonicalizes an identity pair to the empty
    /// (uncalibrated) representation. Refused instead, before anything
    /// is committed: hand over a sample with real spread.
    DegenerateSample,

    /// A coordinate in the sample is not finite (NaN, +Inf, -Inf) or has
    /// magnitude `>= 1e16`. Rejected for the reasons
    /// [`AddError::InvalidInputValue`] documents.
    InvalidInputValue {
        /// Row within the sample (0-based).
        vector_index: usize,
        /// Coordinate within that row.
        coord_index: usize,
        /// The offending value.
        value: f32,
    },
}

impl fmt::Display for CalibrateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DegenerateSample => write!(
                f,
                "calibration sample has no per-coordinate spread (the fit \
                 came out as exact identity); a committed identity would \
                 report Calibrated while behaving as Uncalibrated. Pass a \
                 representative sample with real variation."
            ),
            Self::SampleTooSmall { rows, min } => write!(
                f,
                "calibration sample has {rows} rows, need at least {min}"
            ),
            Self::DimMismatch { existing, got } => write!(
                f,
                "dim mismatch: index dim={existing}, sample dim={got}"
            ),
            Self::ZeroDim => write!(f, "dim is 0: the calibration sample has no columns"),
            Self::DimNotMultipleOf8(dim) => {
                write!(f, "dim must be a multiple of 8, got {dim}")
            }
            Self::DimTooLarge { dim, max } => {
                write!(f, "dim {dim} exceeds the maximum supported dim {max}")
            }
            Self::SampleBufferNotMultipleOfDim { sample_len, dim } => write!(
                f,
                "sample length {sample_len} is not a multiple of dim {dim}"
            ),
            Self::InvalidInputValue {
                vector_index,
                coord_index,
                value,
            } => write!(
                f,
                "invalid input value at vector {vector_index}, coord \
                 {coord_index}: {value} (must be finite and |value| < 1e16 \
                 to avoid f32 norm overflow)"
            ),
        }
    }
}

impl Error for CalibrateError {}