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 shape = || -> Result<VectorDimension> {
98 let prefix: [u8; 4] = encoded
99 .get(..4)
100 .and_then(|bytes| bytes.try_into().ok())
101 .ok_or_else(|| invalid("truncated dimension"))?;
102 let dimension = VectorDimension::new(u32::from_le_bytes(prefix))
103 .ok_or_else(|| invalid("dimension must be positive"))?;
104 let expected = usize::try_from(dimension.get())
105 .ok()
106 .and_then(|n| n.checked_mul(4))
107 .and_then(|n| n.checked_add(4))
108 .ok_or_else(|| invalid("payload length overflow"))?;
109 if encoded.len() != expected {
110 return Err(invalid("payload length does not match dimension"));
111 }
112 Ok(dimension)
113 };
114 let dimension = shape().map_err(&map_invalid)?;
115 for block in encoded[4..].chunks(64 * 1024) {
116 let unit = start()?;
117 let finite = block
118 .as_chunks::<4>()
119 .0
120 .iter()
121 .all(|bytes| f32::from_le_bytes(*bytes).is_finite());
122 finish(unit)?;
123 if !finite {
124 return Err(map_invalid(invalid("coordinates must be finite")));
125 }
126 }
127 Ok(Self { dimension, encoded })
128 }
129
130 pub const fn dimension(self) -> VectorDimension {
131 self.dimension
132 }
133 pub const fn encoded(self) -> &'a [u8] {
134 self.encoded
135 }
136
137 pub fn coordinates(self) -> impl ExactSizeIterator<Item = f32> + 'a {
138 self.encoded[4..]
139 .as_chunks::<4>()
140 .0
141 .iter()
142 .map(|bytes| f32::from_le_bytes(*bytes))
143 }
144
145 pub fn to_owned(self) -> Vector {
147 Vector {
148 encoded: self.encoded.to_vec(),
149 }
150 }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
154pub enum VectorDistance {
155 Cosine,
156 Euclidean,
157}
158
159impl VectorDistance {
160 pub fn from_function_name(name: &str) -> Option<Self> {
161 if name.eq_ignore_ascii_case("cosine_distance") {
162 Some(Self::Cosine)
163 } else if name.eq_ignore_ascii_case("l2_distance") {
164 Some(Self::Euclidean)
165 } else {
166 None
167 }
168 }
169
170 pub const fn function_name(self) -> &'static str {
171 match self {
172 Self::Cosine => "cosine_distance",
173 Self::Euclidean => "l2_distance",
174 }
175 }
176
177 pub fn distance(self, left: VectorRef<'_>, right: VectorRef<'_>) -> Result<f64> {
178 self.distance_with_work(left, right, || Ok(()))
179 }
180
181 pub fn distance_with_work(
183 self,
184 left: VectorRef<'_>,
185 right: VectorRef<'_>,
186 checkpoint: impl FnMut() -> Result<()>,
187 ) -> Result<f64> {
188 if left.dimension != right.dimension {
189 return Err(invalid("distance dimensions must match"));
190 }
191 if distance_kernel_name(self, left.dimension.get() as usize) == "scalar" {
192 return self.scalar_distance_coordinates(
193 left.coordinates(),
194 right.coordinates(),
195 checkpoint,
196 );
197 }
198 self.distance_inputs(
199 Input::Encoded(&left.encoded[4..]),
200 Input::Encoded(&right.encoded[4..]),
201 checkpoint,
202 )
203 }
204
205 pub fn distance_slices_with_work(
208 self,
209 left: &[f32],
210 right: &[f32],
211 checkpoint: impl FnMut() -> Result<()>,
212 ) -> Result<f64> {
213 if left.len() != right.len() {
214 return Err(invalid("distance dimensions must match"));
215 }
216 if left.is_empty() || u32::try_from(left.len()).is_err() {
217 return Err(invalid("dimension must be a positive u32"));
218 }
219 if distance_kernel_name(self, left.len()) == "scalar" {
220 return self.scalar_distance_coordinates(
221 left.iter().copied(),
222 right.iter().copied(),
223 checkpoint,
224 );
225 }
226 self.distance_inputs(Input::Slice(left), Input::Slice(right), checkpoint)
227 }
228
229 pub fn distance_slice_to_vector_with_work(
232 self,
233 left: &[f32],
234 right: VectorRef<'_>,
235 checkpoint: impl FnMut() -> Result<()>,
236 ) -> Result<f64> {
237 if left.len() != right.dimension.get() as usize {
238 return Err(invalid("distance dimensions must match"));
239 }
240 if distance_kernel_name(self, left.len()) == "scalar" {
241 return self.scalar_distance_coordinates(
242 left.iter().copied(),
243 right.coordinates(),
244 checkpoint,
245 );
246 }
247 self.distance_inputs(
248 Input::Slice(left),
249 Input::Encoded(&right.encoded[4..]),
250 checkpoint,
251 )
252 }
253
254 fn distance_inputs(
255 self,
256 left: Input<'_>,
257 right: Input<'_>,
258 checkpoint: impl FnMut() -> Result<()>,
259 ) -> Result<f64> {
260 let mode = match self {
261 Self::Cosine => Mode::Cosine,
262 Self::Euclidean => Mode::Euclidean,
263 };
264 let sums = Kernel::for_mode(mode, left.len()).calculate(left, right, mode, checkpoint)?;
265 finish_distance(self, &sums, sums.left.sqrt())
266 }
267
268 fn scalar_distance_coordinates(
269 self,
270 left: impl Iterator<Item = f32>,
271 right: impl Iterator<Item = f32>,
272 mut checkpoint: impl FnMut() -> Result<()>,
273 ) -> Result<f64> {
274 let (mut dot, mut left_norm, mut right_norm, mut squared) =
275 (0.0f64, 0.0f64, 0.0f64, 0.0f64);
276 for (index, (left, right)) in left.zip(right).enumerate() {
277 if index % (64 * 1024 / (2 * std::mem::size_of::<f32>())) == 0 {
279 checkpoint()?;
280 }
281 if !left.is_finite() || !right.is_finite() {
282 return Err(invalid("coordinates must be finite"));
283 }
284 let (left, right) = (f64::from(left), f64::from(right));
285 match self {
286 Self::Euclidean => squared += (left - right).powi(2),
287 Self::Cosine => {
288 dot += left * right;
289 left_norm += left * left;
290 right_norm += right * right;
291 }
292 }
293 }
294 checkpoint()?;
295 match self {
296 Self::Euclidean => Ok(squared.sqrt()),
297 Self::Cosine if left_norm == 0.0 || right_norm == 0.0 => {
298 Err(invalid("cosine distance requires nonzero vectors"))
299 }
300 Self::Cosine => {
301 Ok(1.0 - (dot / (left_norm.sqrt() * right_norm.sqrt())).clamp(-1.0, 1.0))
302 }
303 }
304 }
305
306 pub fn evaluate(self, left: ValueRef<'_>, right: ValueRef<'_>) -> Result<Option<f64>> {
307 match (left, right) {
308 (ValueRef::Null, _) | (_, ValueRef::Null) => Ok(None),
309 (ValueRef::Vector(left), ValueRef::Vector(right)) => {
310 self.distance(left, right).map(Some)
311 }
312 _ => Err(invalid("distance arguments must be vectors")),
313 }
314 }
315}
316
317#[doc(hidden)]
319#[inline]
320pub fn distance_kernel_name(metric: VectorDistance, dimension: usize) -> &'static str {
321 Kernel::for_mode(
322 match metric {
323 VectorDistance::Cosine => Mode::Cosine,
324 VectorDistance::Euclidean => Mode::Euclidean,
325 },
326 dimension,
327 )
328 .1
329}
330
331#[doc(hidden)]
335#[derive(Clone, Copy)]
336pub struct PreparedVectorQuery<'a> {
337 coordinates: &'a [f32],
338 norm: f64,
339 kernel: Kernel,
340}
341
342impl<'a> PreparedVectorQuery<'a> {
343 pub fn new(coordinates: &'a [f32]) -> Result<Self> {
344 Self::with_work(coordinates, || Ok(()))
345 }
346
347 pub fn with_work(
348 coordinates: &'a [f32],
349 checkpoint: impl FnMut() -> Result<()>,
350 ) -> Result<Self> {
351 if coordinates.is_empty() || u32::try_from(coordinates.len()).is_err() {
352 return Err(invalid("dimension must be a positive u32"));
353 }
354 let kernel = Kernel::for_mode(Mode::PreparedCosine, coordinates.len());
355 let norm = Kernel::for_mode(Mode::Norm, coordinates.len())
356 .calculate(
357 Input::Slice(coordinates),
358 Input::Slice(coordinates),
359 Mode::Norm,
360 checkpoint,
361 )?
362 .left
363 .sqrt();
364 Ok(Self {
365 coordinates,
366 norm,
367 kernel,
368 })
369 }
370
371 pub fn for_distance(
372 metric: VectorDistance,
373 coordinates: &'a [f32],
374 checkpoint: impl FnMut() -> Result<()>,
375 ) -> Result<Self> {
376 let query = Self::with_work(coordinates, checkpoint)?;
377 if metric == VectorDistance::Cosine && query.norm == 0.0 {
378 return Err(invalid("cosine distance requires nonzero vectors"));
379 }
380 Ok(query)
381 }
382
383 pub fn coordinates(&self) -> &'a [f32] {
384 self.coordinates
385 }
386
387 pub fn distance_slices_with_work(
388 &self,
389 metric: VectorDistance,
390 right: &[f32],
391 checkpoint: impl FnMut() -> Result<()>,
392 ) -> Result<f64> {
393 if self.coordinates.len() != right.len() {
394 return Err(invalid("distance dimensions must match"));
395 }
396 if self.coordinates.len() < 16
399 || (metric == VectorDistance::Euclidean
400 && distance_kernel_name(metric, right.len()) == "scalar")
401 {
402 return metric.distance_slices_with_work(self.coordinates, right, checkpoint);
403 }
404 self.distance_input(metric, Input::Slice(right), checkpoint)
405 }
406
407 pub fn distance_to_vector_with_work(
408 &self,
409 metric: VectorDistance,
410 right: VectorRef<'_>,
411 checkpoint: impl FnMut() -> Result<()>,
412 ) -> Result<f64> {
413 if self.coordinates.len() != right.dimension.get() as usize {
414 return Err(invalid("distance dimensions must match"));
415 }
416 if self.coordinates.len() < 16
417 || (metric == VectorDistance::Euclidean
418 && distance_kernel_name(metric, self.coordinates.len()) == "scalar")
419 {
420 return metric.distance_slice_to_vector_with_work(self.coordinates, right, checkpoint);
421 }
422 self.distance_input(metric, Input::Encoded(&right.encoded[4..]), checkpoint)
423 }
424
425 fn distance_input(
426 &self,
427 metric: VectorDistance,
428 right: Input<'_>,
429 checkpoint: impl FnMut() -> Result<()>,
430 ) -> Result<f64> {
431 let mode = match metric {
432 VectorDistance::Cosine => Mode::PreparedCosine,
433 VectorDistance::Euclidean => Mode::Euclidean,
434 };
435 let kernel = match metric {
436 VectorDistance::Cosine => self.kernel,
437 VectorDistance::Euclidean => Kernel::for_mode(mode, self.coordinates.len()),
438 };
439 let sums = kernel.calculate(Input::Slice(self.coordinates), right, mode, checkpoint)?;
440 finish_distance(metric, &sums, self.norm)
441 }
442
443 pub fn positive_cosine_similarity(&self, right: &[f32]) -> Result<Option<f64>> {
446 if self.coordinates.len() != right.len() {
447 return Ok(None);
448 }
449 let sums = self.kernel.calculate(
450 Input::Slice(self.coordinates),
451 Input::Slice(right),
452 Mode::PreparedCosine,
453 || Ok(()),
454 )?;
455 if self.norm == 0.0 || sums.right == 0.0 {
456 return Ok(None);
457 }
458 Ok(Some(
459 (sums.dot / (self.norm * sums.right.sqrt())).clamp(0.0, 1.0),
460 ))
461 }
462}
463
464fn finish_distance(metric: VectorDistance, sums: &Sums, left_norm: f64) -> Result<f64> {
465 match metric {
466 VectorDistance::Euclidean => Ok(sums.squared.sqrt()),
467 VectorDistance::Cosine if left_norm == 0.0 || sums.right == 0.0 => {
468 Err(invalid("cosine distance requires nonzero vectors"))
469 }
470 VectorDistance::Cosine => {
471 Ok(1.0 - (sums.dot / (left_norm * sums.right.sqrt())).clamp(-1.0, 1.0))
472 }
473 }
474}
475
476fn invalid(reason: &str) -> HawDBError {
477 HawDBError::Semantic(format!("invalid vector: {reason}"))
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483
484 #[test]
485 fn projection_distance_preserves_signed_cosine_and_canonical_parity() {
486 let query = [1.0, 0.0];
487 let values = [[1.0, 0.0], [0.0, 1.0], [-0.6, 0.8], [-1.0, 0.0]];
488 for metric in [VectorDistance::Cosine, VectorDistance::Euclidean] {
489 for coordinates in values {
490 let canonical = metric
491 .distance(
492 Vector::new(&query).unwrap().as_ref(),
493 Vector::new(&coordinates).unwrap().as_ref(),
494 )
495 .unwrap();
496 let projection = metric
497 .distance_slices_with_work(&query, &coordinates, || Ok(()))
498 .unwrap();
499 assert_eq!(projection.to_bits(), canonical.to_bits());
500 let encoded = Vector::new(&coordinates).unwrap();
501 let mut unaligned = vec![0];
502 unaligned.extend_from_slice(encoded.encoded());
503 let mapped = metric
504 .distance_slice_to_vector_with_work(
505 &query,
506 VectorRef::from_encoded(&unaligned[1..]).unwrap(),
507 || Ok(()),
508 )
509 .unwrap();
510 assert_eq!(mapped.to_bits(), canonical.to_bits());
511 }
512 }
513 let distance = |coordinates: &[f32]| {
514 VectorDistance::Cosine
515 .distance_slices_with_work(&query, coordinates, || Ok(()))
516 .unwrap()
517 };
518 assert!(distance(&values[2]) > 1.0);
519 assert!(distance(&values[2]) < distance(&values[3]));
520 assert_eq!(distance(&values[3]), 2.0);
521 for coordinates in [&[][..], &[0.0][..], &[f32::NAN, 0.0][..], &[0.0, 0.0][..]] {
522 assert!(VectorDistance::Cosine
523 .distance_slices_with_work(&query, coordinates, || Ok(()))
524 .is_err());
525 }
526 }
527
528 #[test]
529 fn projection_distance_preserves_cooperative_failure() {
530 let coordinates = vec![1.0; 20_000];
531 let mut checkpoints = 0;
532 let error = VectorDistance::Cosine
533 .distance_slices_with_work(&coordinates, &coordinates, || {
534 checkpoints += 1;
535 if checkpoints == 2 {
536 Err(HawDBError::ProjectionBusy)
537 } else {
538 Ok(())
539 }
540 })
541 .unwrap_err();
542 assert!(matches!(error, HawDBError::ProjectionBusy));
543 assert_eq!(checkpoints, 2);
544 let encoded = Vector::new(&coordinates).unwrap();
545 let error = VectorDistance::Cosine
546 .distance_slice_to_vector_with_work(&coordinates, encoded.as_ref(), || {
547 Err(HawDBError::ProjectionBusy)
548 })
549 .unwrap_err();
550 assert!(matches!(error, HawDBError::ProjectionBusy));
551 assert!(VectorDistance::Cosine
552 .distance_slice_to_vector_with_work(&[1.0], encoded.as_ref(), || Ok(()))
553 .is_err());
554 }
555
556 #[test]
557 fn vector_encoding_rejects_malformed_and_nonfinite_payloads() {
558 let value = Vector::new(&[1.0, -2.5]).unwrap();
559 assert_eq!(value.encoded(), &[2, 0, 0, 0, 0, 0, 128, 63, 0, 0, 32, 192]);
560 assert_eq!(
561 Vector::from_encoded(value.encoded().to_vec()).unwrap(),
562 value
563 );
564 let mut unaligned = vec![0];
565 unaligned.extend_from_slice(value.encoded());
566 assert_eq!(
567 VectorRef::from_encoded(&unaligned[1..]).unwrap(),
568 value.as_ref()
569 );
570 for size in 0..value.encoded().len() {
571 assert!(VectorRef::from_encoded(&value.encoded()[..size]).is_err());
572 }
573 assert!(VectorRef::from_encoded(&[0, 0, 0, 0]).is_err());
574 assert!(VectorRef::from_encoded(&u32::MAX.to_le_bytes()).is_err());
575 for component in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
576 assert!(Vector::new(&[component]).is_err());
577 let mut encoded = 1u32.to_le_bytes().to_vec();
578 encoded.extend_from_slice(&component.to_le_bytes());
579 assert!(VectorRef::from_encoded(&encoded).is_err());
580 }
581 assert!(Vector::new(&[]).is_err());
582 }
583
584 #[test]
585 fn vector_distance_is_mathematical_and_shared() {
586 let left = Vector::new(&[1.0, 0.0]).unwrap();
587 let opposite = Vector::new(&[-1.0, 0.0]).unwrap();
588 let zero = Vector::new(&[0.0, 0.0]).unwrap();
589 assert_eq!(
590 VectorDistance::Cosine
591 .distance(left.as_ref(), opposite.as_ref())
592 .unwrap(),
593 2.0
594 );
595 assert_eq!(
596 VectorDistance::Euclidean
597 .distance(left.as_ref(), zero.as_ref())
598 .unwrap(),
599 1.0
600 );
601 assert!(VectorDistance::Cosine
602 .distance(left.as_ref(), zero.as_ref())
603 .is_err());
604 assert!(VectorDistance::Euclidean
605 .distance(left.as_ref(), Vector::new(&[1.0]).unwrap().as_ref())
606 .is_err());
607 assert_eq!(
608 VectorDistance::Cosine
609 .evaluate(ValueRef::Null, ValueRef::Vector(zero.as_ref()))
610 .unwrap(),
611 None
612 );
613 let large = Vector::new(&[f32::MAX, f32::MAX]).unwrap();
614 assert!(VectorDistance::Euclidean
615 .distance(large.as_ref(), zero.as_ref())
616 .unwrap()
617 .is_finite());
618 assert!(
619 VectorDistance::Cosine
620 .distance(large.as_ref(), large.as_ref())
621 .unwrap()
622 .abs()
623 < 1e-12
624 );
625 }
626}
627
628impl std::hash::Hash for VectorRef<'_> {
629 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
630 self.encoded.hash(state);
631 }
632}
633
634#[cfg(test)]
635mod work_tests {
636 use super::*;
637
638 #[test]
639 fn shared_vector_validation_stops_between_bounded_coordinate_blocks() {
640 let vector = Vector::new(&vec![1.0; 32769]).unwrap();
641 let calls = std::cell::Cell::new(0);
642 let error = Vector::from_encoded_with_work(
643 vector.encoded().to_vec(),
644 || {
645 calls.set(calls.get() + 1);
646 if calls.get() == 2 {
647 Err("cancelled".to_owned())
648 } else {
649 Ok(())
650 }
651 },
652 |_| Ok(()),
653 |error| error.to_string(),
654 )
655 .unwrap_err();
656 assert_eq!(error, "cancelled");
657 assert_eq!(calls.get(), 2);
658 let mut encoded = vector.encoded().to_vec();
659 let last = encoded.len() - 4;
660 encoded[last..].copy_from_slice(&f32::NAN.to_le_bytes());
661 assert!(Vector::from_encoded(encoded).is_err());
662 }
663}
664
665crate::impl_retained_heap_for_copy!(VectorDistance);