1use crate::{HawDBError, Result, ValueRef, VectorDimension};
9
10mod kernel;
11use kernel::{Input, Kernel, Mode, Sums};
12
13#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Vector {
15 encoded: Vec<u8>,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
19pub struct VectorRef<'a> {
20 encoded: &'a [u8],
21 dimension: VectorDimension,
22}
23
24impl Vector {
25 pub fn new(coordinates: &[f32]) -> Result<Self> {
26 let dimension = u32::try_from(coordinates.len())
27 .ok()
28 .and_then(VectorDimension::new)
29 .ok_or_else(|| invalid("dimension must be a positive u32"))?;
30 if coordinates.iter().any(|value| !value.is_finite()) {
31 return Err(invalid("coordinates must be finite"));
32 }
33 let bytes = coordinates
34 .len()
35 .checked_mul(4)
36 .and_then(|n| n.checked_add(4))
37 .ok_or_else(|| invalid("payload length overflow"))?;
38 let mut encoded = Vec::with_capacity(bytes);
39 encoded.extend_from_slice(&dimension.get().to_le_bytes());
40 for value in coordinates {
41 encoded.extend_from_slice(&value.to_le_bytes());
42 }
43 Ok(Self { encoded })
44 }
45
46 pub fn from_encoded(encoded: Vec<u8>) -> Result<Self> {
48 Self::from_encoded_with_work(encoded, || Ok(()), |_| Ok(()), std::convert::identity)
49 }
50
51 pub fn from_encoded_with_work<T, E>(
53 encoded: Vec<u8>,
54 start: impl FnMut() -> std::result::Result<T, E>,
55 finish: impl FnMut(T) -> std::result::Result<(), E>,
56 invalid: impl Fn(HawDBError) -> E,
57 ) -> std::result::Result<Self, E> {
58 VectorRef::from_encoded_with_work(&encoded, start, finish, invalid)?;
59 Ok(Self { encoded })
60 }
61
62 pub fn dimension(&self) -> VectorDimension {
63 VectorDimension::new(u32::from_le_bytes(
64 self.encoded[..4].try_into().expect("validated dimension"),
65 ))
66 .expect("nonzero dimension")
67 }
68 pub fn retained_capacity(&self) -> usize {
69 self.encoded.capacity()
70 }
71
72 pub fn as_ref(&self) -> VectorRef<'_> {
73 VectorRef {
74 dimension: self.dimension(),
75 encoded: &self.encoded,
76 }
77 }
78
79 pub fn encoded(&self) -> &[u8] {
80 &self.encoded
81 }
82}
83
84impl<'a> VectorRef<'a> {
85 pub fn from_encoded(encoded: &'a [u8]) -> Result<Self> {
87 Self::from_encoded_with_work(encoded, || Ok(()), |_| Ok(()), std::convert::identity)
88 }
89
90 pub fn from_encoded_with_work<T, E>(
92 encoded: &'a [u8],
93 mut start: impl FnMut() -> std::result::Result<T, E>,
94 mut finish: impl FnMut(T) -> std::result::Result<(), E>,
95 map_invalid: impl Fn(HawDBError) -> E,
96 ) -> std::result::Result<Self, E> {
97 let vector = Self::from_encoded_shape(encoded).map_err(&map_invalid)?;
98 for block in encoded[4..].chunks(64 * 1024) {
99 let unit = start()?;
100 let finite = block
101 .as_chunks::<4>()
102 .0
103 .iter()
104 .all(|bytes| f32::from_le_bytes(*bytes).is_finite());
105 finish(unit)?;
106 if !finite {
107 return Err(map_invalid(invalid("coordinates must be finite")));
108 }
109 }
110 Ok(vector)
111 }
112
113 fn from_encoded_shape(encoded: &'a [u8]) -> Result<Self> {
116 let prefix: [u8; 4] = encoded
117 .get(..4)
118 .and_then(|bytes| bytes.try_into().ok())
119 .ok_or_else(|| invalid("truncated dimension"))?;
120 let dimension = VectorDimension::new(u32::from_le_bytes(prefix))
121 .ok_or_else(|| invalid("dimension must be positive"))?;
122 let expected = usize::try_from(dimension.get())
123 .ok()
124 .and_then(|n| n.checked_mul(4))
125 .and_then(|n| n.checked_add(4))
126 .ok_or_else(|| invalid("payload length overflow"))?;
127 if encoded.len() != expected {
128 return Err(invalid("payload length does not match dimension"));
129 }
130 Ok(Self { dimension, encoded })
131 }
132
133 pub const fn dimension(self) -> VectorDimension {
134 self.dimension
135 }
136 pub const fn encoded(self) -> &'a [u8] {
137 self.encoded
138 }
139
140 pub fn coordinates(self) -> impl ExactSizeIterator<Item = f32> + 'a {
141 self.encoded[4..]
142 .as_chunks::<4>()
143 .0
144 .iter()
145 .map(|bytes| f32::from_le_bytes(*bytes))
146 }
147
148 pub fn to_owned(self) -> Vector {
150 Vector {
151 encoded: self.encoded.to_vec(),
152 }
153 }
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
157pub enum VectorDistance {
158 Cosine,
159 Euclidean,
160}
161
162impl VectorDistance {
163 pub fn from_function_name(name: &str) -> Option<Self> {
164 if name.eq_ignore_ascii_case("cosine_distance") {
165 Some(Self::Cosine)
166 } else if name.eq_ignore_ascii_case("l2_distance") {
167 Some(Self::Euclidean)
168 } else {
169 None
170 }
171 }
172
173 pub const fn function_name(self) -> &'static str {
174 match self {
175 Self::Cosine => "cosine_distance",
176 Self::Euclidean => "l2_distance",
177 }
178 }
179
180 pub fn distance(self, left: VectorRef<'_>, right: VectorRef<'_>) -> Result<f64> {
181 self.distance_with_work(left, right, || Ok(()))
182 }
183
184 pub fn distance_with_work(
186 self,
187 left: VectorRef<'_>,
188 right: VectorRef<'_>,
189 checkpoint: impl FnMut() -> Result<()>,
190 ) -> Result<f64> {
191 if left.dimension != right.dimension {
192 return Err(invalid("distance dimensions must match"));
193 }
194 if distance_kernel_name(self, left.dimension.get() as usize) == "scalar" {
195 return self.scalar_distance_coordinates(
196 left.coordinates(),
197 right.coordinates(),
198 checkpoint,
199 );
200 }
201 self.distance_inputs(
202 Input::Encoded(&left.encoded[4..]),
203 Input::Encoded(&right.encoded[4..]),
204 checkpoint,
205 )
206 }
207
208 pub fn distance_slices_with_work(
211 self,
212 left: &[f32],
213 right: &[f32],
214 checkpoint: impl FnMut() -> Result<()>,
215 ) -> Result<f64> {
216 if left.len() != right.len() {
217 return Err(invalid("distance dimensions must match"));
218 }
219 if left.is_empty() || u32::try_from(left.len()).is_err() {
220 return Err(invalid("dimension must be a positive u32"));
221 }
222 if distance_kernel_name(self, left.len()) == "scalar" {
223 return self.scalar_distance_coordinates(
224 left.iter().copied(),
225 right.iter().copied(),
226 checkpoint,
227 );
228 }
229 self.distance_inputs(Input::Slice(left), Input::Slice(right), checkpoint)
230 }
231
232 pub fn distance_slice_to_vector_with_work(
235 self,
236 left: &[f32],
237 right: VectorRef<'_>,
238 checkpoint: impl FnMut() -> Result<()>,
239 ) -> Result<f64> {
240 if left.len() != right.dimension.get() as usize {
241 return Err(invalid("distance dimensions must match"));
242 }
243 if distance_kernel_name(self, left.len()) == "scalar" {
244 return self.scalar_distance_coordinates(
245 left.iter().copied(),
246 right.coordinates(),
247 checkpoint,
248 );
249 }
250 self.distance_inputs(
251 Input::Slice(left),
252 Input::Encoded(&right.encoded[4..]),
253 checkpoint,
254 )
255 }
256
257 fn distance_inputs(
258 self,
259 left: Input<'_>,
260 right: Input<'_>,
261 checkpoint: impl FnMut() -> Result<()>,
262 ) -> Result<f64> {
263 let mode = match self {
264 Self::Cosine => Mode::Cosine,
265 Self::Euclidean => Mode::Euclidean,
266 };
267 let sums = Kernel::for_mode(mode, left.len()).calculate(left, right, mode, checkpoint)?;
268 finish_distance(self, &sums, sums.left.sqrt())
269 }
270
271 fn scalar_distance_coordinates(
272 self,
273 left: impl Iterator<Item = f32>,
274 right: impl Iterator<Item = f32>,
275 mut checkpoint: impl FnMut() -> Result<()>,
276 ) -> Result<f64> {
277 let (mut dot, mut left_norm, mut right_norm, mut squared) =
278 (0.0f64, 0.0f64, 0.0f64, 0.0f64);
279 for (index, (left, right)) in left.zip(right).enumerate() {
280 if index % (64 * 1024 / (2 * std::mem::size_of::<f32>())) == 0 {
282 checkpoint()?;
283 }
284 if !left.is_finite() || !right.is_finite() {
285 return Err(invalid("coordinates must be finite"));
286 }
287 let (left, right) = (f64::from(left), f64::from(right));
288 match self {
289 Self::Euclidean => squared += (left - right).powi(2),
290 Self::Cosine => {
291 dot += left * right;
292 left_norm += left * left;
293 right_norm += right * right;
294 }
295 }
296 }
297 checkpoint()?;
298 match self {
299 Self::Euclidean => Ok(squared.sqrt()),
300 Self::Cosine if left_norm == 0.0 || right_norm == 0.0 => {
301 Err(invalid("cosine distance requires nonzero vectors"))
302 }
303 Self::Cosine => {
304 Ok(1.0 - (dot / (left_norm.sqrt() * right_norm.sqrt())).clamp(-1.0, 1.0))
305 }
306 }
307 }
308
309 pub fn evaluate(self, left: ValueRef<'_>, right: ValueRef<'_>) -> Result<Option<f64>> {
310 match (left, right) {
311 (ValueRef::Null, _) | (_, ValueRef::Null) => Ok(None),
312 (ValueRef::Vector(left), ValueRef::Vector(right)) => {
313 self.distance(left, right).map(Some)
314 }
315 _ => Err(invalid("distance arguments must be vectors")),
316 }
317 }
318}
319
320#[doc(hidden)]
322#[inline]
323pub fn distance_kernel_name(metric: VectorDistance, dimension: usize) -> &'static str {
324 Kernel::for_mode(
325 match metric {
326 VectorDistance::Cosine => Mode::Cosine,
327 VectorDistance::Euclidean => Mode::Euclidean,
328 },
329 dimension,
330 )
331 .1
332}
333
334#[doc(hidden)]
338#[derive(Clone, Copy)]
339pub struct PreparedVectorQuery<'a> {
340 coordinates: &'a [f32],
341 norm: f64,
342 kernel: Kernel,
343}
344
345impl<'a> PreparedVectorQuery<'a> {
346 pub fn new(coordinates: &'a [f32]) -> Result<Self> {
347 Self::with_work(coordinates, || Ok(()))
348 }
349
350 pub fn with_work(
351 coordinates: &'a [f32],
352 checkpoint: impl FnMut() -> Result<()>,
353 ) -> Result<Self> {
354 if coordinates.is_empty() || u32::try_from(coordinates.len()).is_err() {
355 return Err(invalid("dimension must be a positive u32"));
356 }
357 let kernel = Kernel::for_mode(Mode::PreparedCosine, coordinates.len());
358 let norm = Kernel::for_mode(Mode::Norm, coordinates.len())
359 .calculate(
360 Input::Slice(coordinates),
361 Input::Slice(coordinates),
362 Mode::Norm,
363 checkpoint,
364 )?
365 .left
366 .sqrt();
367 Ok(Self {
368 coordinates,
369 norm,
370 kernel,
371 })
372 }
373
374 pub fn for_distance(
375 metric: VectorDistance,
376 coordinates: &'a [f32],
377 checkpoint: impl FnMut() -> Result<()>,
378 ) -> Result<Self> {
379 let query = Self::with_work(coordinates, checkpoint)?;
380 if metric == VectorDistance::Cosine && query.norm == 0.0 {
381 return Err(invalid("cosine distance requires nonzero vectors"));
382 }
383 Ok(query)
384 }
385
386 pub fn coordinates(&self) -> &'a [f32] {
387 self.coordinates
388 }
389
390 pub fn distance_slices_with_work(
391 &self,
392 metric: VectorDistance,
393 right: &[f32],
394 checkpoint: impl FnMut() -> Result<()>,
395 ) -> Result<f64> {
396 if self.coordinates.len() != right.len() {
397 return Err(invalid("distance dimensions must match"));
398 }
399 if self.coordinates.len() < 16
402 || (metric == VectorDistance::Euclidean
403 && distance_kernel_name(metric, right.len()) == "scalar")
404 {
405 return metric.distance_slices_with_work(self.coordinates, right, checkpoint);
406 }
407 self.distance_input(metric, Input::Slice(right), checkpoint)
408 }
409
410 pub fn distance_to_vector_with_work(
411 &self,
412 metric: VectorDistance,
413 right: VectorRef<'_>,
414 checkpoint: impl FnMut() -> Result<()>,
415 ) -> Result<f64> {
416 if self.coordinates.len() != right.dimension.get() as usize {
417 return Err(invalid("distance dimensions must match"));
418 }
419 if self.coordinates.len() < 16
420 || (metric == VectorDistance::Euclidean
421 && distance_kernel_name(metric, self.coordinates.len()) == "scalar")
422 {
423 return metric.distance_slice_to_vector_with_work(self.coordinates, right, checkpoint);
424 }
425 self.distance_input(metric, Input::Encoded(&right.encoded[4..]), checkpoint)
426 }
427
428 pub fn distance_to_encoded_with_work(
432 &self,
433 metric: VectorDistance,
434 encoded: &[u8],
435 mut checkpoint: impl FnMut() -> Result<()>,
436 ) -> Result<f64> {
437 if self.coordinates.len() < 16 {
438 let right = VectorRef::from_encoded_with_work(
439 encoded,
440 &mut checkpoint,
441 |_| Ok(()),
442 std::convert::identity,
443 )?;
444 return self.distance_to_vector_with_work(metric, right, checkpoint);
445 }
446 let right = VectorRef::from_encoded_shape(encoded)?;
447 self.distance_to_vector_with_work(metric, right, checkpoint)
448 }
449
450 pub fn distances_to_encoded_with_work(
453 &self,
454 metric: VectorDistance,
455 encoded: [&[u8]; 4],
456 mut checkpoint: impl FnMut() -> Result<()>,
457 ) -> Result<[f64; 4]> {
458 let dimension = self.coordinates.len();
459 let shaped = encoded.iter().all(|bytes| {
460 VectorRef::from_encoded_shape(bytes)
461 .is_ok_and(|vector| vector.dimension.get() as usize == dimension)
462 });
463 if shaped {
464 let mode = match metric {
465 VectorDistance::Cosine => Mode::PreparedCosine,
466 VectorDistance::Euclidean => Mode::Euclidean,
467 };
468 let rows = encoded.map(|bytes| Input::Encoded(&bytes[4..]));
469 if let Some(sums) =
470 kernel::calculate_four(self.coordinates, rows, mode, &mut checkpoint)?
471 {
472 let mut distances = [0.0; 4];
473 for (distance, sums) in distances.iter_mut().zip(&sums) {
474 *distance = finish_distance(metric, sums, self.norm)?;
475 }
476 return Ok(distances);
477 }
478 }
479 let mut distances = [0.0; 4];
480 for (distance, bytes) in distances.iter_mut().zip(encoded) {
481 *distance = self.distance_to_encoded_with_work(metric, bytes, &mut checkpoint)?;
482 }
483 Ok(distances)
484 }
485
486 fn distance_input(
487 &self,
488 metric: VectorDistance,
489 right: Input<'_>,
490 checkpoint: impl FnMut() -> Result<()>,
491 ) -> Result<f64> {
492 let mode = match metric {
493 VectorDistance::Cosine => Mode::PreparedCosine,
494 VectorDistance::Euclidean => Mode::Euclidean,
495 };
496 let kernel = match metric {
497 VectorDistance::Cosine => self.kernel,
498 VectorDistance::Euclidean => Kernel::for_mode(mode, self.coordinates.len()),
499 };
500 let sums = kernel.calculate(Input::Slice(self.coordinates), right, mode, checkpoint)?;
501 finish_distance(metric, &sums, self.norm)
502 }
503
504 pub fn positive_cosine_similarity(&self, right: &[f32]) -> Result<Option<f64>> {
507 if self.coordinates.len() != right.len() {
508 return Ok(None);
509 }
510 let sums = self.kernel.calculate(
511 Input::Slice(self.coordinates),
512 Input::Slice(right),
513 Mode::PreparedCosine,
514 || Ok(()),
515 )?;
516 if self.norm == 0.0 || sums.right == 0.0 {
517 return Ok(None);
518 }
519 Ok(Some(
520 (sums.dot / (self.norm * sums.right.sqrt())).clamp(0.0, 1.0),
521 ))
522 }
523}
524
525fn finish_distance(metric: VectorDistance, sums: &Sums, left_norm: f64) -> Result<f64> {
526 match metric {
527 VectorDistance::Euclidean => Ok(sums.squared.sqrt()),
528 VectorDistance::Cosine if left_norm == 0.0 || sums.right == 0.0 => {
529 Err(invalid("cosine distance requires nonzero vectors"))
530 }
531 VectorDistance::Cosine => {
532 Ok(1.0 - (sums.dot / (left_norm * sums.right.sqrt())).clamp(-1.0, 1.0))
533 }
534 }
535}
536
537fn invalid(reason: &str) -> HawDBError {
538 HawDBError::Semantic(format!("invalid vector: {reason}"))
539}
540
541#[cfg(test)]
542mod tests {
543 use super::*;
544
545 #[test]
546 fn projection_distance_preserves_signed_cosine_and_canonical_parity() {
547 let query = [1.0, 0.0];
548 let values = [[1.0, 0.0], [0.0, 1.0], [-0.6, 0.8], [-1.0, 0.0]];
549 for metric in [VectorDistance::Cosine, VectorDistance::Euclidean] {
550 for coordinates in values {
551 let canonical = metric
552 .distance(
553 Vector::new(&query).unwrap().as_ref(),
554 Vector::new(&coordinates).unwrap().as_ref(),
555 )
556 .unwrap();
557 let projection = metric
558 .distance_slices_with_work(&query, &coordinates, || Ok(()))
559 .unwrap();
560 assert_eq!(projection.to_bits(), canonical.to_bits());
561 let encoded = Vector::new(&coordinates).unwrap();
562 let mut unaligned = vec![0];
563 unaligned.extend_from_slice(encoded.encoded());
564 let mapped = metric
565 .distance_slice_to_vector_with_work(
566 &query,
567 VectorRef::from_encoded(&unaligned[1..]).unwrap(),
568 || Ok(()),
569 )
570 .unwrap();
571 assert_eq!(mapped.to_bits(), canonical.to_bits());
572 }
573 }
574 let distance = |coordinates: &[f32]| {
575 VectorDistance::Cosine
576 .distance_slices_with_work(&query, coordinates, || Ok(()))
577 .unwrap()
578 };
579 assert!(distance(&values[2]) > 1.0);
580 assert!(distance(&values[2]) < distance(&values[3]));
581 assert_eq!(distance(&values[3]), 2.0);
582 for coordinates in [&[][..], &[0.0][..], &[f32::NAN, 0.0][..], &[0.0, 0.0][..]] {
583 assert!(VectorDistance::Cosine
584 .distance_slices_with_work(&query, coordinates, || Ok(()))
585 .is_err());
586 }
587 }
588
589 #[test]
590 fn projection_distance_preserves_cooperative_failure() {
591 let coordinates = vec![1.0; 20_000];
592 let mut checkpoints = 0;
593 let error = VectorDistance::Cosine
594 .distance_slices_with_work(&coordinates, &coordinates, || {
595 checkpoints += 1;
596 if checkpoints == 2 {
597 Err(HawDBError::ProjectionBusy)
598 } else {
599 Ok(())
600 }
601 })
602 .unwrap_err();
603 assert!(matches!(error, HawDBError::ProjectionBusy));
604 assert_eq!(checkpoints, 2);
605 let encoded = Vector::new(&coordinates).unwrap();
606 let error = VectorDistance::Cosine
607 .distance_slice_to_vector_with_work(&coordinates, encoded.as_ref(), || {
608 Err(HawDBError::ProjectionBusy)
609 })
610 .unwrap_err();
611 assert!(matches!(error, HawDBError::ProjectionBusy));
612 assert!(VectorDistance::Cosine
613 .distance_slice_to_vector_with_work(&[1.0], encoded.as_ref(), || Ok(()))
614 .is_err());
615 }
616
617 #[test]
618 fn prepared_encoded_distance_matches_validated_vectors_and_refuses_malformed_input() {
619 for dimension in [2usize, 15, 16, 17, 37, 128] {
620 let left: Vec<f32> = (0..dimension).map(|i| i as f32 * 0.37 - 3.0).collect();
621 let right: Vec<f32> = (0..dimension).map(|i| 1.5 - i as f32 * 0.11).collect();
622 let encoded = Vector::new(&right).unwrap().encoded().to_vec();
623 for metric in [VectorDistance::Cosine, VectorDistance::Euclidean] {
624 let query = PreparedVectorQuery::for_distance(metric, &left, || Ok(())).unwrap();
625 let expected = query
626 .distance_to_vector_with_work(
627 metric,
628 VectorRef::from_encoded(&encoded).unwrap(),
629 || Ok(()),
630 )
631 .unwrap();
632 let score =
633 |bytes: &[u8]| query.distance_to_encoded_with_work(metric, bytes, || Ok(()));
634 assert_eq!(score(&encoded).unwrap().to_bits(), expected.to_bits());
635 for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
636 for position in 0..dimension {
637 let mut damaged = encoded.clone();
638 damaged[4 + position * 4..8 + position * 4]
639 .copy_from_slice(&value.to_le_bytes());
640 assert!(score(&damaged).is_err(), "{dimension} {position}");
641 }
642 }
643 assert!(score(&encoded[..encoded.len() - 1]).is_err());
644 assert!(score(&encoded[..3]).is_err());
645 assert!(score(Vector::new(&[1.0; 3]).unwrap().encoded()).is_err());
646 assert!(query
647 .distance_to_encoded_with_work(metric, &encoded, || Err(invalid("stop")))
648 .is_err());
649 }
650 }
651 }
652
653 #[test]
654 fn four_encoded_distances_match_single_bits_errors_and_work() {
655 for dimension in [
656 2usize, 15, 16, 17, 18, 19, 20, 37, 128, 1024, 3275, 3276, 3277, 9001,
657 ] {
658 let left: Vec<f32> = (0..dimension)
659 .map(|i| ((i * 173 + 19) as f32).sin())
660 .collect();
661 let rows: Vec<Vec<u8>> = (0..4usize)
663 .map(|row| {
664 let mut values: Vec<f32> = (0..dimension)
665 .map(|i| ((i * 97 + row * 31 + 3) as f32).cos() * 10f32.powi(row as i32))
666 .collect();
667 values[dimension / 2] =
668 [f32::MAX, -0.0, f32::MIN_POSITIVE, f32::from_bits(1)][row];
669 let mut bytes = vec![7u8; row];
670 bytes.extend_from_slice(Vector::new(&values).unwrap().encoded());
671 bytes
672 })
673 .collect();
674 let encoded: [&[u8]; 4] = std::array::from_fn(|row| &rows[row][row..]);
675 for metric in [VectorDistance::Cosine, VectorDistance::Euclidean] {
676 let query = PreparedVectorQuery::for_distance(metric, &left, || Ok(())).unwrap();
677 let four = |rows: [&[u8]; 4]| {
678 query.distances_to_encoded_with_work(metric, rows, || Ok(()))
679 };
680 let one = |row: &[u8]| query.distance_to_encoded_with_work(metric, row, || Ok(()));
681 assert_eq!(
682 four(encoded).unwrap().map(f64::to_bits),
683 encoded.map(|row| one(row).unwrap().to_bits()),
684 "{metric:?} {dimension}"
685 );
686 for lane in 0..4 {
687 for (position, value) in [
688 (0, f32::NAN),
689 (dimension / 2, f32::INFINITY),
690 (dimension - 1, f32::NEG_INFINITY),
691 ] {
692 let mut damaged = encoded[lane].to_vec();
693 damaged[4 + position * 4..8 + position * 4]
694 .copy_from_slice(&value.to_le_bytes());
695 let mut rows = encoded;
696 rows[lane] = &damaged;
697 assert_eq!(
698 four(rows).unwrap_err().to_string(),
699 one(&damaged).unwrap_err().to_string()
700 );
701 }
702 let short = &encoded[lane][..encoded[lane].len() - 1];
703 let zero = Vector::new(&vec![0.0; dimension]).unwrap();
704 for bad in [short, zero.encoded()] {
705 let mut rows = encoded;
706 rows[lane] = bad;
707 assert_eq!(
708 four(rows).map_err(|error| error.to_string()).err(),
709 one(bad).map_err(|error| error.to_string()).err()
710 );
711 }
712 }
713 let mut checks = 0;
715 query
716 .distances_to_encoded_with_work(metric, encoded, || {
717 checks += 1;
718 Ok(())
719 })
720 .unwrap();
721 for stop in 0..checks {
722 let mut seen = 0;
723 assert!(query
724 .distances_to_encoded_with_work(metric, encoded, || {
725 seen += 1;
726 if seen > stop {
727 Err(invalid("stop"))
728 } else {
729 Ok(())
730 }
731 })
732 .is_err());
733 }
734 }
735 }
736 }
737
738 #[test]
739 fn vector_encoding_rejects_malformed_and_nonfinite_payloads() {
740 let value = Vector::new(&[1.0, -2.5]).unwrap();
741 assert_eq!(value.encoded(), &[2, 0, 0, 0, 0, 0, 128, 63, 0, 0, 32, 192]);
742 assert_eq!(
743 Vector::from_encoded(value.encoded().to_vec()).unwrap(),
744 value
745 );
746 let mut unaligned = vec![0];
747 unaligned.extend_from_slice(value.encoded());
748 assert_eq!(
749 VectorRef::from_encoded(&unaligned[1..]).unwrap(),
750 value.as_ref()
751 );
752 for size in 0..value.encoded().len() {
753 assert!(VectorRef::from_encoded(&value.encoded()[..size]).is_err());
754 }
755 assert!(VectorRef::from_encoded(&[0, 0, 0, 0]).is_err());
756 assert!(VectorRef::from_encoded(&u32::MAX.to_le_bytes()).is_err());
757 for component in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
758 assert!(Vector::new(&[component]).is_err());
759 let mut encoded = 1u32.to_le_bytes().to_vec();
760 encoded.extend_from_slice(&component.to_le_bytes());
761 assert!(VectorRef::from_encoded(&encoded).is_err());
762 }
763 assert!(Vector::new(&[]).is_err());
764 }
765
766 #[test]
767 fn vector_distance_is_mathematical_and_shared() {
768 let left = Vector::new(&[1.0, 0.0]).unwrap();
769 let opposite = Vector::new(&[-1.0, 0.0]).unwrap();
770 let zero = Vector::new(&[0.0, 0.0]).unwrap();
771 assert_eq!(
772 VectorDistance::Cosine
773 .distance(left.as_ref(), opposite.as_ref())
774 .unwrap(),
775 2.0
776 );
777 assert_eq!(
778 VectorDistance::Euclidean
779 .distance(left.as_ref(), zero.as_ref())
780 .unwrap(),
781 1.0
782 );
783 assert!(VectorDistance::Cosine
784 .distance(left.as_ref(), zero.as_ref())
785 .is_err());
786 assert!(VectorDistance::Euclidean
787 .distance(left.as_ref(), Vector::new(&[1.0]).unwrap().as_ref())
788 .is_err());
789 assert_eq!(
790 VectorDistance::Cosine
791 .evaluate(ValueRef::Null, ValueRef::Vector(zero.as_ref()))
792 .unwrap(),
793 None
794 );
795 let large = Vector::new(&[f32::MAX, f32::MAX]).unwrap();
796 assert!(VectorDistance::Euclidean
797 .distance(large.as_ref(), zero.as_ref())
798 .unwrap()
799 .is_finite());
800 assert!(
801 VectorDistance::Cosine
802 .distance(large.as_ref(), large.as_ref())
803 .unwrap()
804 .abs()
805 < 1e-12
806 );
807 }
808}
809
810impl std::hash::Hash for VectorRef<'_> {
811 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
812 self.encoded.hash(state);
813 }
814}
815
816#[cfg(test)]
817mod work_tests {
818 use super::*;
819
820 #[test]
821 fn shared_vector_validation_stops_between_bounded_coordinate_blocks() {
822 let vector = Vector::new(&vec![1.0; 32769]).unwrap();
823 let calls = std::cell::Cell::new(0);
824 let error = Vector::from_encoded_with_work(
825 vector.encoded().to_vec(),
826 || {
827 calls.set(calls.get() + 1);
828 if calls.get() == 2 {
829 Err("cancelled".to_owned())
830 } else {
831 Ok(())
832 }
833 },
834 |_| Ok(()),
835 |error| error.to_string(),
836 )
837 .unwrap_err();
838 assert_eq!(error, "cancelled");
839 assert_eq!(calls.get(), 2);
840 let mut encoded = vector.encoded().to_vec();
841 let last = encoded.len() - 4;
842 encoded[last..].copy_from_slice(&f32::NAN.to_le_bytes());
843 assert!(Vector::from_encoded(encoded).is_err());
844 }
845}
846
847crate::impl_retained_heap_for_copy!(VectorDistance);