hawdb-core 0.40.0

An embedded Rust graph database for local data-plane workloads
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
// Copyright 2026 Nowledge
// SPDX-License-Identifier: Apache-2.0

//! Shared finite Float32 values and exact distance operators for SQL and Cypher.
//! The canonical payload is a little-endian u32 dimension followed by f32 bits.
//! Byte-backed storage permits unaligned, allocation-free views of row pages.

use crate::{HawDBError, Result, ValueRef, VectorDimension};

mod kernel;
use kernel::{Input, Kernel, Mode, Sums};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Vector {
    encoded: Vec<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct VectorRef<'a> {
    encoded: &'a [u8],
    dimension: VectorDimension,
}

impl Vector {
    pub fn new(coordinates: &[f32]) -> Result<Self> {
        let dimension = u32::try_from(coordinates.len())
            .ok()
            .and_then(VectorDimension::new)
            .ok_or_else(|| invalid("dimension must be a positive u32"))?;
        if coordinates.iter().any(|value| !value.is_finite()) {
            return Err(invalid("coordinates must be finite"));
        }
        let bytes = coordinates
            .len()
            .checked_mul(4)
            .and_then(|n| n.checked_add(4))
            .ok_or_else(|| invalid("payload length overflow"))?;
        let mut encoded = Vec::with_capacity(bytes);
        encoded.extend_from_slice(&dimension.get().to_le_bytes());
        for value in coordinates {
            encoded.extend_from_slice(&value.to_le_bytes());
        }
        Ok(Self { encoded })
    }

    /// Takes ownership of an already admitted payload without an additional copy.
    pub fn from_encoded(encoded: Vec<u8>) -> Result<Self> {
        Self::from_encoded_with_work(encoded, || Ok(()), |_| Ok(()), std::convert::identity)
    }

    /// Validates in bounded units before taking ownership, without rescanning.
    pub fn from_encoded_with_work<T, E>(
        encoded: Vec<u8>,
        start: impl FnMut() -> std::result::Result<T, E>,
        finish: impl FnMut(T) -> std::result::Result<(), E>,
        invalid: impl Fn(HawDBError) -> E,
    ) -> std::result::Result<Self, E> {
        VectorRef::from_encoded_with_work(&encoded, start, finish, invalid)?;
        Ok(Self { encoded })
    }

    pub fn dimension(&self) -> VectorDimension {
        VectorDimension::new(u32::from_le_bytes(
            self.encoded[..4].try_into().expect("validated dimension"),
        ))
        .expect("nonzero dimension")
    }
    pub fn retained_capacity(&self) -> usize {
        self.encoded.capacity()
    }

    pub fn as_ref(&self) -> VectorRef<'_> {
        VectorRef {
            dimension: self.dimension(),
            encoded: &self.encoded,
        }
    }

    pub fn encoded(&self) -> &[u8] {
        &self.encoded
    }
}

impl<'a> VectorRef<'a> {
    /// Validates length and finite components before any caller-owned allocation.
    pub fn from_encoded(encoded: &'a [u8]) -> Result<Self> {
        Self::from_encoded_with_work(encoded, || Ok(()), |_| Ok(()), std::convert::identity)
    }

    /// Each work unit scans at most 64 KiB; callbacks own admission and cancellation.
    pub fn from_encoded_with_work<T, E>(
        encoded: &'a [u8],
        mut start: impl FnMut() -> std::result::Result<T, E>,
        mut finish: impl FnMut(T) -> std::result::Result<(), E>,
        map_invalid: impl Fn(HawDBError) -> E,
    ) -> std::result::Result<Self, E> {
        let vector = Self::from_encoded_shape(encoded).map_err(&map_invalid)?;
        for block in encoded[4..].chunks(64 * 1024) {
            let unit = start()?;
            let finite = block
                .as_chunks::<4>()
                .0
                .iter()
                .all(|bytes| f32::from_le_bytes(*bytes).is_finite());
            finish(unit)?;
            if !finite {
                return Err(map_invalid(invalid("coordinates must be finite")));
            }
        }
        Ok(vector)
    }

    /// Validates the length only. The result must not leave this module: its
    /// components may be non-finite until a distance kernel checks them.
    fn from_encoded_shape(encoded: &'a [u8]) -> Result<Self> {
        let prefix: [u8; 4] = encoded
            .get(..4)
            .and_then(|bytes| bytes.try_into().ok())
            .ok_or_else(|| invalid("truncated dimension"))?;
        let dimension = VectorDimension::new(u32::from_le_bytes(prefix))
            .ok_or_else(|| invalid("dimension must be positive"))?;
        let expected = usize::try_from(dimension.get())
            .ok()
            .and_then(|n| n.checked_mul(4))
            .and_then(|n| n.checked_add(4))
            .ok_or_else(|| invalid("payload length overflow"))?;
        if encoded.len() != expected {
            return Err(invalid("payload length does not match dimension"));
        }
        Ok(Self { dimension, encoded })
    }

    pub const fn dimension(self) -> VectorDimension {
        self.dimension
    }
    pub const fn encoded(self) -> &'a [u8] {
        self.encoded
    }

    pub fn coordinates(self) -> impl ExactSizeIterator<Item = f32> + 'a {
        self.encoded[4..]
            .as_chunks::<4>()
            .0
            .iter()
            .map(|bytes| f32::from_le_bytes(*bytes))
    }

    /// The caller must admit the payload before materializing a borrowed value.
    pub fn to_owned(self) -> Vector {
        Vector {
            encoded: self.encoded.to_vec(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VectorDistance {
    Cosine,
    Euclidean,
}

impl VectorDistance {
    pub fn from_function_name(name: &str) -> Option<Self> {
        if name.eq_ignore_ascii_case("cosine_distance") {
            Some(Self::Cosine)
        } else if name.eq_ignore_ascii_case("l2_distance") {
            Some(Self::Euclidean)
        } else {
            None
        }
    }

    pub const fn function_name(self) -> &'static str {
        match self {
            Self::Cosine => "cosine_distance",
            Self::Euclidean => "l2_distance",
        }
    }

    pub fn distance(self, left: VectorRef<'_>, right: VectorRef<'_>) -> Result<f64> {
        self.distance_with_work(left, right, || Ok(()))
    }

    /// Cooperatively scores canonical values without copying their payloads.
    pub fn distance_with_work(
        self,
        left: VectorRef<'_>,
        right: VectorRef<'_>,
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        if left.dimension != right.dimension {
            return Err(invalid("distance dimensions must match"));
        }
        if distance_kernel_name(self, left.dimension.get() as usize) == "scalar" {
            return self.scalar_distance_coordinates(
                left.coordinates(),
                right.coordinates(),
                checkpoint,
            );
        }
        self.distance_inputs(
            Input::Encoded(&left.encoded[4..]),
            Input::Encoded(&right.encoded[4..]),
            checkpoint,
        )
    }

    /// Scores admitted raw projection vectors with the same mathematical
    /// contract as SQL/Cypher, without creating canonical payload copies.
    pub fn distance_slices_with_work(
        self,
        left: &[f32],
        right: &[f32],
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        if left.len() != right.len() {
            return Err(invalid("distance dimensions must match"));
        }
        if left.is_empty() || u32::try_from(left.len()).is_err() {
            return Err(invalid("dimension must be a positive u32"));
        }
        if distance_kernel_name(self, left.len()) == "scalar" {
            return self.scalar_distance_coordinates(
                left.iter().copied(),
                right.iter().copied(),
                checkpoint,
            );
        }
        self.distance_inputs(Input::Slice(left), Input::Slice(right), checkpoint)
    }

    /// Scores a raw query against a validated, byte-backed immutable vector
    /// without allocating an aligned coordinate copy.
    pub fn distance_slice_to_vector_with_work(
        self,
        left: &[f32],
        right: VectorRef<'_>,
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        if left.len() != right.dimension.get() as usize {
            return Err(invalid("distance dimensions must match"));
        }
        if distance_kernel_name(self, left.len()) == "scalar" {
            return self.scalar_distance_coordinates(
                left.iter().copied(),
                right.coordinates(),
                checkpoint,
            );
        }
        self.distance_inputs(
            Input::Slice(left),
            Input::Encoded(&right.encoded[4..]),
            checkpoint,
        )
    }

    fn distance_inputs(
        self,
        left: Input<'_>,
        right: Input<'_>,
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        let mode = match self {
            Self::Cosine => Mode::Cosine,
            Self::Euclidean => Mode::Euclidean,
        };
        let sums = Kernel::for_mode(mode, left.len()).calculate(left, right, mode, checkpoint)?;
        finish_distance(self, &sums, sums.left.sqrt())
    }

    fn scalar_distance_coordinates(
        self,
        left: impl Iterator<Item = f32>,
        right: impl Iterator<Item = f32>,
        mut checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        let (mut dot, mut left_norm, mut right_norm, mut squared) =
            (0.0f64, 0.0f64, 0.0f64, 0.0f64);
        for (index, (left, right)) in left.zip(right).enumerate() {
            // Read at most 64 KiB across both operands between checkpoints.
            if index % (64 * 1024 / (2 * std::mem::size_of::<f32>())) == 0 {
                checkpoint()?;
            }
            if !left.is_finite() || !right.is_finite() {
                return Err(invalid("coordinates must be finite"));
            }
            let (left, right) = (f64::from(left), f64::from(right));
            match self {
                Self::Euclidean => squared += (left - right).powi(2),
                Self::Cosine => {
                    dot += left * right;
                    left_norm += left * left;
                    right_norm += right * right;
                }
            }
        }
        checkpoint()?;
        match self {
            Self::Euclidean => Ok(squared.sqrt()),
            Self::Cosine if left_norm == 0.0 || right_norm == 0.0 => {
                Err(invalid("cosine distance requires nonzero vectors"))
            }
            Self::Cosine => {
                Ok(1.0 - (dot / (left_norm.sqrt() * right_norm.sqrt())).clamp(-1.0, 1.0))
            }
        }
    }

    pub fn evaluate(self, left: ValueRef<'_>, right: ValueRef<'_>) -> Result<Option<f64>> {
        match (left, right) {
            (ValueRef::Null, _) | (_, ValueRef::Null) => Ok(None),
            (ValueRef::Vector(left), ValueRef::Vector(right)) => {
                self.distance(left, right).map(Some)
            }
            _ => Err(invalid("distance arguments must be vectors")),
        }
    }
}

/// Selected exact-arithmetic implementation, independent of ANN backend selection.
#[doc(hidden)]
#[inline]
pub fn distance_kernel_name(metric: VectorDistance, dimension: usize) -> &'static str {
    Kernel::for_mode(
        match metric {
            VectorDistance::Cosine => Mode::Cosine,
            VectorDistance::Euclidean => Mode::Euclidean,
        },
        dimension,
    )
    .1
}

/// Borrowed, validated query state shared by exact projection scoring and reranking.
/// Preparation retains no coordinate copies. Each distance keeps f64 arithmetic,
/// coordinate-order sums and the same bounded work callbacks as `VectorDistance`.
#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct PreparedVectorQuery<'a> {
    coordinates: &'a [f32],
    norm: f64,
    kernel: Kernel,
}

impl<'a> PreparedVectorQuery<'a> {
    pub fn new(coordinates: &'a [f32]) -> Result<Self> {
        Self::with_work(coordinates, || Ok(()))
    }

    pub fn with_work(
        coordinates: &'a [f32],
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<Self> {
        if coordinates.is_empty() || u32::try_from(coordinates.len()).is_err() {
            return Err(invalid("dimension must be a positive u32"));
        }
        let kernel = Kernel::for_mode(Mode::PreparedCosine, coordinates.len());
        let norm = Kernel::for_mode(Mode::Norm, coordinates.len())
            .calculate(
                Input::Slice(coordinates),
                Input::Slice(coordinates),
                Mode::Norm,
                checkpoint,
            )?
            .left
            .sqrt();
        Ok(Self {
            coordinates,
            norm,
            kernel,
        })
    }

    pub fn for_distance(
        metric: VectorDistance,
        coordinates: &'a [f32],
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<Self> {
        let query = Self::with_work(coordinates, checkpoint)?;
        if metric == VectorDistance::Cosine && query.norm == 0.0 {
            return Err(invalid("cosine distance requires nonzero vectors"));
        }
        Ok(query)
    }

    pub fn coordinates(&self) -> &'a [f32] {
        self.coordinates
    }

    pub fn distance_slices_with_work(
        &self,
        metric: VectorDistance,
        right: &[f32],
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        if self.coordinates.len() != right.len() {
            return Err(invalid("distance dimensions must match"));
        }
        // Tiny vectors cannot amortize the prepared-kernel wrapper. Keep the
        // direct ordered scalar path even when a query norm is available.
        if self.coordinates.len() < 16
            || (metric == VectorDistance::Euclidean
                && distance_kernel_name(metric, right.len()) == "scalar")
        {
            return metric.distance_slices_with_work(self.coordinates, right, checkpoint);
        }
        self.distance_input(metric, Input::Slice(right), checkpoint)
    }

    pub fn distance_to_vector_with_work(
        &self,
        metric: VectorDistance,
        right: VectorRef<'_>,
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        if self.coordinates.len() != right.dimension.get() as usize {
            return Err(invalid("distance dimensions must match"));
        }
        if self.coordinates.len() < 16
            || (metric == VectorDistance::Euclidean
                && distance_kernel_name(metric, self.coordinates.len()) == "scalar")
        {
            return metric.distance_slice_to_vector_with_work(self.coordinates, right, checkpoint);
        }
        self.distance_input(metric, Input::Encoded(&right.encoded[4..]), checkpoint)
    }

    /// Scores an encoded vector whose components were not validated beforehand.
    /// Validates its shape; every distance kernel refuses non-finite components,
    /// so a separate component pass would only repeat that check.
    pub fn distance_to_encoded_with_work(
        &self,
        metric: VectorDistance,
        encoded: &[u8],
        mut checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        if self.coordinates.len() < 16 {
            let right = VectorRef::from_encoded_with_work(
                encoded,
                &mut checkpoint,
                |_| Ok(()),
                std::convert::identity,
            )?;
            return self.distance_to_vector_with_work(metric, right, checkpoint);
        }
        let right = VectorRef::from_encoded_shape(encoded)?;
        self.distance_to_vector_with_work(metric, right, checkpoint)
    }

    /// Scores four encoded vectors as `distance_to_encoded_with_work` would, with
    /// the same bits. Errors are those of the first failing vector.
    pub fn distances_to_encoded_with_work(
        &self,
        metric: VectorDistance,
        encoded: [&[u8]; 4],
        mut checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<[f64; 4]> {
        let dimension = self.coordinates.len();
        let shaped = encoded.iter().all(|bytes| {
            VectorRef::from_encoded_shape(bytes)
                .is_ok_and(|vector| vector.dimension.get() as usize == dimension)
        });
        if shaped {
            let mode = match metric {
                VectorDistance::Cosine => Mode::PreparedCosine,
                VectorDistance::Euclidean => Mode::Euclidean,
            };
            let rows = encoded.map(|bytes| Input::Encoded(&bytes[4..]));
            if let Some(sums) =
                kernel::calculate_four(self.coordinates, rows, mode, &mut checkpoint)?
            {
                let mut distances = [0.0; 4];
                for (distance, sums) in distances.iter_mut().zip(&sums) {
                    *distance = finish_distance(metric, sums, self.norm)?;
                }
                return Ok(distances);
            }
        }
        let mut distances = [0.0; 4];
        for (distance, bytes) in distances.iter_mut().zip(encoded) {
            *distance = self.distance_to_encoded_with_work(metric, bytes, &mut checkpoint)?;
        }
        Ok(distances)
    }

    fn distance_input(
        &self,
        metric: VectorDistance,
        right: Input<'_>,
        checkpoint: impl FnMut() -> Result<()>,
    ) -> Result<f64> {
        let mode = match metric {
            VectorDistance::Cosine => Mode::PreparedCosine,
            VectorDistance::Euclidean => Mode::Euclidean,
        };
        let kernel = match metric {
            VectorDistance::Cosine => self.kernel,
            VectorDistance::Euclidean => Kernel::for_mode(mode, self.coordinates.len()),
        };
        let sums = kernel.calculate(Input::Slice(self.coordinates), right, mode, checkpoint)?;
        finish_distance(metric, &sums, self.norm)
    }

    /// Search's positive-only relevance, computed directly rather than as 1-distance
    /// so subtraction cannot change final score bits. Zero vectors have no score.
    pub fn positive_cosine_similarity(&self, right: &[f32]) -> Result<Option<f64>> {
        if self.coordinates.len() != right.len() {
            return Ok(None);
        }
        let sums = self.kernel.calculate(
            Input::Slice(self.coordinates),
            Input::Slice(right),
            Mode::PreparedCosine,
            || Ok(()),
        )?;
        if self.norm == 0.0 || sums.right == 0.0 {
            return Ok(None);
        }
        Ok(Some(
            (sums.dot / (self.norm * sums.right.sqrt())).clamp(0.0, 1.0),
        ))
    }
}

fn finish_distance(metric: VectorDistance, sums: &Sums, left_norm: f64) -> Result<f64> {
    match metric {
        VectorDistance::Euclidean => Ok(sums.squared.sqrt()),
        VectorDistance::Cosine if left_norm == 0.0 || sums.right == 0.0 => {
            Err(invalid("cosine distance requires nonzero vectors"))
        }
        VectorDistance::Cosine => {
            Ok(1.0 - (sums.dot / (left_norm * sums.right.sqrt())).clamp(-1.0, 1.0))
        }
    }
}

fn invalid(reason: &str) -> HawDBError {
    HawDBError::Semantic(format!("invalid vector: {reason}"))
}

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

    #[test]
    fn projection_distance_preserves_signed_cosine_and_canonical_parity() {
        let query = [1.0, 0.0];
        let values = [[1.0, 0.0], [0.0, 1.0], [-0.6, 0.8], [-1.0, 0.0]];
        for metric in [VectorDistance::Cosine, VectorDistance::Euclidean] {
            for coordinates in values {
                let canonical = metric
                    .distance(
                        Vector::new(&query).unwrap().as_ref(),
                        Vector::new(&coordinates).unwrap().as_ref(),
                    )
                    .unwrap();
                let projection = metric
                    .distance_slices_with_work(&query, &coordinates, || Ok(()))
                    .unwrap();
                assert_eq!(projection.to_bits(), canonical.to_bits());
                let encoded = Vector::new(&coordinates).unwrap();
                let mut unaligned = vec![0];
                unaligned.extend_from_slice(encoded.encoded());
                let mapped = metric
                    .distance_slice_to_vector_with_work(
                        &query,
                        VectorRef::from_encoded(&unaligned[1..]).unwrap(),
                        || Ok(()),
                    )
                    .unwrap();
                assert_eq!(mapped.to_bits(), canonical.to_bits());
            }
        }
        let distance = |coordinates: &[f32]| {
            VectorDistance::Cosine
                .distance_slices_with_work(&query, coordinates, || Ok(()))
                .unwrap()
        };
        assert!(distance(&values[2]) > 1.0);
        assert!(distance(&values[2]) < distance(&values[3]));
        assert_eq!(distance(&values[3]), 2.0);
        for coordinates in [&[][..], &[0.0][..], &[f32::NAN, 0.0][..], &[0.0, 0.0][..]] {
            assert!(VectorDistance::Cosine
                .distance_slices_with_work(&query, coordinates, || Ok(()))
                .is_err());
        }
    }

    #[test]
    fn projection_distance_preserves_cooperative_failure() {
        let coordinates = vec![1.0; 20_000];
        let mut checkpoints = 0;
        let error = VectorDistance::Cosine
            .distance_slices_with_work(&coordinates, &coordinates, || {
                checkpoints += 1;
                if checkpoints == 2 {
                    Err(HawDBError::ProjectionBusy)
                } else {
                    Ok(())
                }
            })
            .unwrap_err();
        assert!(matches!(error, HawDBError::ProjectionBusy));
        assert_eq!(checkpoints, 2);
        let encoded = Vector::new(&coordinates).unwrap();
        let error = VectorDistance::Cosine
            .distance_slice_to_vector_with_work(&coordinates, encoded.as_ref(), || {
                Err(HawDBError::ProjectionBusy)
            })
            .unwrap_err();
        assert!(matches!(error, HawDBError::ProjectionBusy));
        assert!(VectorDistance::Cosine
            .distance_slice_to_vector_with_work(&[1.0], encoded.as_ref(), || Ok(()))
            .is_err());
    }

    #[test]
    fn prepared_encoded_distance_matches_validated_vectors_and_refuses_malformed_input() {
        for dimension in [2usize, 15, 16, 17, 37, 128] {
            let left: Vec<f32> = (0..dimension).map(|i| i as f32 * 0.37 - 3.0).collect();
            let right: Vec<f32> = (0..dimension).map(|i| 1.5 - i as f32 * 0.11).collect();
            let encoded = Vector::new(&right).unwrap().encoded().to_vec();
            for metric in [VectorDistance::Cosine, VectorDistance::Euclidean] {
                let query = PreparedVectorQuery::for_distance(metric, &left, || Ok(())).unwrap();
                let expected = query
                    .distance_to_vector_with_work(
                        metric,
                        VectorRef::from_encoded(&encoded).unwrap(),
                        || Ok(()),
                    )
                    .unwrap();
                let score =
                    |bytes: &[u8]| query.distance_to_encoded_with_work(metric, bytes, || Ok(()));
                assert_eq!(score(&encoded).unwrap().to_bits(), expected.to_bits());
                for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
                    for position in 0..dimension {
                        let mut damaged = encoded.clone();
                        damaged[4 + position * 4..8 + position * 4]
                            .copy_from_slice(&value.to_le_bytes());
                        assert!(score(&damaged).is_err(), "{dimension} {position}");
                    }
                }
                assert!(score(&encoded[..encoded.len() - 1]).is_err());
                assert!(score(&encoded[..3]).is_err());
                assert!(score(Vector::new(&[1.0; 3]).unwrap().encoded()).is_err());
                assert!(query
                    .distance_to_encoded_with_work(metric, &encoded, || Err(invalid("stop")))
                    .is_err());
            }
        }
    }

    #[test]
    fn four_encoded_distances_match_single_bits_errors_and_work() {
        for dimension in [
            2usize, 15, 16, 17, 18, 19, 20, 37, 128, 1024, 3275, 3276, 3277, 9001,
        ] {
            let left: Vec<f32> = (0..dimension)
                .map(|i| ((i * 173 + 19) as f32).sin())
                .collect();
            // Unaligned rows with cancellation, signed zero and extreme values.
            let rows: Vec<Vec<u8>> = (0..4usize)
                .map(|row| {
                    let mut values: Vec<f32> = (0..dimension)
                        .map(|i| ((i * 97 + row * 31 + 3) as f32).cos() * 10f32.powi(row as i32))
                        .collect();
                    values[dimension / 2] =
                        [f32::MAX, -0.0, f32::MIN_POSITIVE, f32::from_bits(1)][row];
                    let mut bytes = vec![7u8; row];
                    bytes.extend_from_slice(Vector::new(&values).unwrap().encoded());
                    bytes
                })
                .collect();
            let encoded: [&[u8]; 4] = std::array::from_fn(|row| &rows[row][row..]);
            for metric in [VectorDistance::Cosine, VectorDistance::Euclidean] {
                let query = PreparedVectorQuery::for_distance(metric, &left, || Ok(())).unwrap();
                let four = |rows: [&[u8]; 4]| {
                    query.distances_to_encoded_with_work(metric, rows, || Ok(()))
                };
                let one = |row: &[u8]| query.distance_to_encoded_with_work(metric, row, || Ok(()));
                assert_eq!(
                    four(encoded).unwrap().map(f64::to_bits),
                    encoded.map(|row| one(row).unwrap().to_bits()),
                    "{metric:?} {dimension}"
                );
                for lane in 0..4 {
                    for (position, value) in [
                        (0, f32::NAN),
                        (dimension / 2, f32::INFINITY),
                        (dimension - 1, f32::NEG_INFINITY),
                    ] {
                        let mut damaged = encoded[lane].to_vec();
                        damaged[4 + position * 4..8 + position * 4]
                            .copy_from_slice(&value.to_le_bytes());
                        let mut rows = encoded;
                        rows[lane] = &damaged;
                        assert_eq!(
                            four(rows).unwrap_err().to_string(),
                            one(&damaged).unwrap_err().to_string()
                        );
                    }
                    let short = &encoded[lane][..encoded[lane].len() - 1];
                    let zero = Vector::new(&vec![0.0; dimension]).unwrap();
                    for bad in [short, zero.encoded()] {
                        let mut rows = encoded;
                        rows[lane] = bad;
                        assert_eq!(
                            four(rows).map_err(|error| error.to_string()).err(),
                            one(bad).map_err(|error| error.to_string()).err()
                        );
                    }
                }
                // Cancellation at every checkpoint refuses without a result.
                let mut checks = 0;
                query
                    .distances_to_encoded_with_work(metric, encoded, || {
                        checks += 1;
                        Ok(())
                    })
                    .unwrap();
                for stop in 0..checks {
                    let mut seen = 0;
                    assert!(query
                        .distances_to_encoded_with_work(metric, encoded, || {
                            seen += 1;
                            if seen > stop {
                                Err(invalid("stop"))
                            } else {
                                Ok(())
                            }
                        })
                        .is_err());
                }
            }
        }
    }

    #[test]
    fn vector_encoding_rejects_malformed_and_nonfinite_payloads() {
        let value = Vector::new(&[1.0, -2.5]).unwrap();
        assert_eq!(value.encoded(), &[2, 0, 0, 0, 0, 0, 128, 63, 0, 0, 32, 192]);
        assert_eq!(
            Vector::from_encoded(value.encoded().to_vec()).unwrap(),
            value
        );
        let mut unaligned = vec![0];
        unaligned.extend_from_slice(value.encoded());
        assert_eq!(
            VectorRef::from_encoded(&unaligned[1..]).unwrap(),
            value.as_ref()
        );
        for size in 0..value.encoded().len() {
            assert!(VectorRef::from_encoded(&value.encoded()[..size]).is_err());
        }
        assert!(VectorRef::from_encoded(&[0, 0, 0, 0]).is_err());
        assert!(VectorRef::from_encoded(&u32::MAX.to_le_bytes()).is_err());
        for component in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            assert!(Vector::new(&[component]).is_err());
            let mut encoded = 1u32.to_le_bytes().to_vec();
            encoded.extend_from_slice(&component.to_le_bytes());
            assert!(VectorRef::from_encoded(&encoded).is_err());
        }
        assert!(Vector::new(&[]).is_err());
    }

    #[test]
    fn vector_distance_is_mathematical_and_shared() {
        let left = Vector::new(&[1.0, 0.0]).unwrap();
        let opposite = Vector::new(&[-1.0, 0.0]).unwrap();
        let zero = Vector::new(&[0.0, 0.0]).unwrap();
        assert_eq!(
            VectorDistance::Cosine
                .distance(left.as_ref(), opposite.as_ref())
                .unwrap(),
            2.0
        );
        assert_eq!(
            VectorDistance::Euclidean
                .distance(left.as_ref(), zero.as_ref())
                .unwrap(),
            1.0
        );
        assert!(VectorDistance::Cosine
            .distance(left.as_ref(), zero.as_ref())
            .is_err());
        assert!(VectorDistance::Euclidean
            .distance(left.as_ref(), Vector::new(&[1.0]).unwrap().as_ref())
            .is_err());
        assert_eq!(
            VectorDistance::Cosine
                .evaluate(ValueRef::Null, ValueRef::Vector(zero.as_ref()))
                .unwrap(),
            None
        );
        let large = Vector::new(&[f32::MAX, f32::MAX]).unwrap();
        assert!(VectorDistance::Euclidean
            .distance(large.as_ref(), zero.as_ref())
            .unwrap()
            .is_finite());
        assert!(
            VectorDistance::Cosine
                .distance(large.as_ref(), large.as_ref())
                .unwrap()
                .abs()
                < 1e-12
        );
    }
}

impl std::hash::Hash for VectorRef<'_> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.encoded.hash(state);
    }
}

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

    #[test]
    fn shared_vector_validation_stops_between_bounded_coordinate_blocks() {
        let vector = Vector::new(&vec![1.0; 32769]).unwrap();
        let calls = std::cell::Cell::new(0);
        let error = Vector::from_encoded_with_work(
            vector.encoded().to_vec(),
            || {
                calls.set(calls.get() + 1);
                if calls.get() == 2 {
                    Err("cancelled".to_owned())
                } else {
                    Ok(())
                }
            },
            |_| Ok(()),
            |error| error.to_string(),
        )
        .unwrap_err();
        assert_eq!(error, "cancelled");
        assert_eq!(calls.get(), 2);
        let mut encoded = vector.encoded().to_vec();
        let last = encoded.len() - 4;
        encoded[last..].copy_from_slice(&f32::NAN.to_le_bytes());
        assert!(Vector::from_encoded(encoded).is_err());
    }
}

// Retained query ownership: VectorDistance.
crate::impl_retained_heap_for_copy!(VectorDistance);