1use std::collections::BTreeMap;
30use std::sync::Arc;
31
32use super::VectorError;
33use super::model::{ChunkMapKey, ModelIdentity, TextDigest};
34use super::score::{ScanParams, mean, quantize};
35use crate::content::DecodeError;
36use crate::content::codec::{Decoder, Encoder};
37use crate::ids::{ContentKey, Digest128};
38use crate::le::u32_at;
39use crate::packed::{self, INDEX_ENTRY_LEN, PackedBuilder};
40use crate::segment::{
41 Alignment, BLOCK_LEN, ErrorKind, KeySpace, KnownSection, Requirement, SectionHandle, SectionId,
42 SectionKind, SectionSpec, Segment, SegmentError, SegmentWriter,
43};
44use crate::table::{UnitLocation, UnitTable, UnitTableBuilder, UnitTableParts};
45
46const FINGERPRINT: SectionKind = SectionKind::new(0x0400);
50const UNITS: SectionKind = SectionKind::new(0x0401);
51const SCAN: SectionKind = SectionKind::new(0x0402);
52const VECTORS: SectionKind = SectionKind::new(0x0403);
53const CHUNK_MAPS: SectionKind = SectionKind::new(0x0404);
54const CHUNK_MAP_DATA: SectionKind = SectionKind::new(0x0405);
55const CENTER: SectionKind = SectionKind::new(0x0406);
56const DETAILS_INDEX: SectionKind = SectionKind::new(0x0407);
57const DETAILS: SectionKind = SectionKind::new(0x0408);
58const KINDS: [SectionKind; 9] = [
59 FINGERPRINT,
60 UNITS,
61 CENTER,
62 SCAN,
63 VECTORS,
64 CHUNK_MAPS,
65 CHUNK_MAP_DATA,
66 DETAILS_INDEX,
67 DETAILS,
68];
69const VERSION: u16 = 1;
70const KEY_SPACE: KeySpace = KeySpace::new(0);
71
72const SCAN_HEADER_LEN: usize = 16;
74const CHUNK_ENTRY_LEN: usize = Digest128::LEN + 1;
76const FLAG_EXPORTED: u8 = 1;
77const FLAG_FAILED: u8 = 2;
78
79pub const MAX_DIMENSIONS: u32 = 8192;
81
82pub const KNOWN: [KnownSection; 9] = [
84 KnownSection {
85 kind: FINGERPRINT,
86 version: VERSION,
87 },
88 KnownSection {
89 kind: UNITS,
90 version: VERSION,
91 },
92 KnownSection {
93 kind: CENTER,
94 version: VERSION,
95 },
96 KnownSection {
97 kind: SCAN,
98 version: VERSION,
99 },
100 KnownSection {
101 kind: VECTORS,
102 version: VERSION,
103 },
104 KnownSection {
105 kind: CHUNK_MAPS,
106 version: VERSION,
107 },
108 KnownSection {
109 kind: CHUNK_MAP_DATA,
110 version: VERSION,
111 },
112 KnownSection {
113 kind: DETAILS_INDEX,
114 version: VERSION,
115 },
116 KnownSection {
117 kind: DETAILS,
118 version: VERSION,
119 },
120];
121
122pub(crate) const fn scan_row_len(dimensions: usize) -> usize {
124 SCAN_HEADER_LEN + dimensions.next_multiple_of(16)
125}
126
127#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
129pub struct SectionBytes {
130 pub units: u64,
132 pub scan: u64,
134 pub vectors: u64,
136 pub chunk_maps: u64,
138 pub chunk_details: u64,
140}
141
142#[derive(Clone, Copy, PartialEq, Eq, Debug)]
144pub struct Chunk {
145 pub text: TextDigest,
147 pub exported: bool,
149 pub failed: bool,
152}
153
154#[derive(Clone, PartialEq, Eq, Debug, Default)]
157pub struct ChunkDetail {
158 pub kind: u8,
160 pub start_line: u32,
161 pub end_line: u32,
162 pub name: String,
163 pub qualified_name: Option<String>,
164 pub snippet: String,
165 pub failure: Option<String>,
168}
169
170#[derive(Clone, PartialEq, Eq, Debug, Default)]
172pub struct FileDetails {
173 pub failure: Option<String>,
176 pub chunks: Vec<ChunkDetail>,
177}
178
179impl FileDetails {
180 #[must_use]
182 pub fn encode(&self) -> Vec<u8> {
183 let mut encoder = Encoder::default();
184 encoder.opt_str(self.failure.as_deref());
185 encoder.usize(self.chunks.len());
186 for chunk in &self.chunks {
187 encoder.byte(chunk.kind);
188 encoder.u32(chunk.start_line);
189 encoder.u32(chunk.end_line);
190 encoder.str(&chunk.name);
191 encoder.opt_str(chunk.qualified_name.as_deref());
192 encoder.str(&chunk.snippet);
193 encoder.opt_str(chunk.failure.as_deref());
194 }
195 encoder.finish()
196 }
197
198 pub fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
204 let mut decoder = Decoder::new(bytes)?;
205 let failure = decoder.opt_string()?;
206 let count = decoder.count_of(7)?;
209 let mut chunks = Vec::with_capacity(count);
210 for _ in 0..count {
211 chunks.push(ChunkDetail {
212 kind: decoder.byte()?,
213 start_line: decoder.u32()?,
214 end_line: decoder.u32()?,
215 name: decoder.string()?,
216 qualified_name: decoder.opt_string()?,
217 snippet: decoder.string()?,
218 failure: decoder.opt_string()?,
219 });
220 }
221 decoder.finish()?;
222 Ok(Self { failure, chunks })
223 }
224}
225
226#[derive(Debug)]
228pub struct VectorSectionsBuilder {
229 model: ModelIdentity,
230 vectors: BTreeMap<TextDigest, Vec<f32>>,
231 maps: BTreeMap<ChunkMapKey, MapEntry>,
232}
233
234type MapEntry = (Vec<u8>, Vec<Chunk>, Option<FileDetails>);
236
237impl VectorSectionsBuilder {
238 pub fn new(model: ModelIdentity) -> Result<Self, VectorError> {
244 if model.dimensions == 0 || model.dimensions > MAX_DIMENSIONS {
245 return Err(VectorError::UnsupportedDimensions(model.dimensions));
246 }
247 Ok(Self {
248 model,
249 vectors: BTreeMap::new(),
250 maps: BTreeMap::new(),
251 })
252 }
253
254 #[must_use]
255 pub fn model(&self) -> &ModelIdentity {
256 &self.model
257 }
258
259 #[must_use]
262 pub const fn bytes_per_vector(dimensions: usize) -> usize {
263 scan_row_len(dimensions) + dimensions * 4 + Digest128::LEN + 12
264 }
265
266 pub fn add_vector(&mut self, text: TextDigest, vector: &[f32]) -> Result<(), VectorError> {
275 if vector.len() != self.model.dimensions as usize {
276 return Err(VectorError::DimensionMismatch {
277 expected: self.model.dimensions,
278 found: vector.len(),
279 });
280 }
281 if vector.iter().any(|value| !value.is_finite())
282 || !super::score::vector_norm(vector).is_finite()
283 {
284 return Err(VectorError::NonFinite);
285 }
286 self.vectors.entry(text).or_insert_with(|| vector.to_vec());
287 Ok(())
288 }
289
290 pub fn add_chunk_map(&mut self, content: ContentKey, path: &[u8], chunks: &[Chunk]) {
295 self.maps
296 .entry(ChunkMapKey::new(content, path))
297 .or_insert_with(|| (path.to_vec(), chunks.to_vec(), None));
298 }
299
300 pub fn add_chunk_map_with_details(
309 &mut self,
310 content: ContentKey,
311 path: &[u8],
312 chunks: &[Chunk],
313 details: FileDetails,
314 ) -> Result<(), VectorError> {
315 let matches = details.chunks.len() == chunks.len()
316 && (details.failure.is_none() || chunks.is_empty())
317 && chunks
318 .iter()
319 .zip(&details.chunks)
320 .all(|(chunk, detail)| chunk.failed == detail.failure.is_some());
321 if !matches {
322 return Err(VectorError::DetailsMismatch);
323 }
324 self.maps
325 .entry(ChunkMapKey::new(content, path))
326 .or_insert_with(|| (path.to_vec(), chunks.to_vec(), Some(details)));
327 Ok(())
328 }
329
330 #[must_use]
332 pub fn vectors(&self) -> usize {
333 self.vectors.len()
334 }
335
336 #[must_use]
338 pub fn chunk_maps(&self) -> usize {
339 self.maps.len()
340 }
341
342 pub fn write(self, writer: &mut SegmentWriter) -> Result<(), SegmentError> {
348 let dimensions = self.model.dimensions as usize;
349 let row_bytes = dimensions * 4;
350 let row_len = scan_row_len(dimensions);
351 let count = self.vectors.len() as u64;
352
353 writer.write_section(spec(FINGERPRINT, Alignment::Word), &self.model.encode(), 1)?;
354
355 let mut table = UnitTableBuilder::new(Digest128::LEN);
356 let mut position = 0u64;
357 let row_len_u32 = u32::try_from(row_bytes).expect("dimensions are limited to 8192");
358 for text in self.vectors.keys() {
359 table.push(
360 text.digest().as_bytes(),
361 UnitLocation {
362 offset: position,
363 len: row_len_u32,
364 },
365 );
366 position += row_bytes as u64;
367 }
368 let (table, units) = table.finish();
369 writer.write_section(spec(UNITS, Alignment::Word), &table, units)?;
370
371 let center = mean(self.vectors.values().map(Vec::as_slice), dimensions);
372 let center_bytes: Vec<u8> = center
373 .iter()
374 .flat_map(|value| value.to_le_bytes())
375 .collect();
376 writer.write_section(
377 spec(CENTER, Alignment::Word),
378 ¢er_bytes,
379 dimensions as u64,
380 )?;
381
382 writer.begin_section(spec(SCAN, Alignment::Vector))?;
384 let mut row = Vec::with_capacity(row_len);
385 let mut codes = Vec::with_capacity(dimensions);
386 for vector in self.vectors.values() {
387 codes.clear();
388 let params = quantize(vector, ¢er, &mut codes);
389 row.clear();
390 for value in [
391 params.scale,
392 params.residual,
393 params.norm,
394 params.max_residual,
395 ] {
396 row.extend_from_slice(&value.to_le_bytes());
397 }
398 row.extend_from_slice(&codes);
399 row.resize(row_len, 0);
400 writer.write(&row)?;
401 }
402 writer.end_section(count)?;
403
404 writer.begin_section(spec(VECTORS, Alignment::Vector))?;
405 let mut bytes = Vec::with_capacity(row_bytes);
406 for vector in self.vectors.values() {
407 bytes.clear();
408 for value in vector {
409 bytes.extend_from_slice(&value.to_le_bytes());
410 }
411 writer.write(&bytes)?;
412 }
413 writer.end_section(count)?;
414
415 let mut table = UnitTableBuilder::new(ChunkMapKey::LEN);
416 let mut data = Vec::new();
417 let mut details = PackedBuilder::with_capacity(self.maps.len());
418 for (key, (path, chunks, file_details)) in &self.maps {
419 details.push(
420 &file_details
421 .as_ref()
422 .map_or_else(Vec::new, FileDetails::encode),
423 );
424 let start = data.len();
425 let path_len = u32::try_from(path.len()).expect("a path is shorter than 4 GiB");
426 data.extend_from_slice(&path_len.to_le_bytes());
427 data.extend_from_slice(path);
428 let chunk_count = u32::try_from(chunks.len()).expect("fewer than 2^32 chunks");
429 data.extend_from_slice(&chunk_count.to_le_bytes());
430 for chunk in chunks {
431 data.extend_from_slice(chunk.text.digest().as_bytes());
432 let mut flags = 0;
433 if chunk.exported {
434 flags |= FLAG_EXPORTED;
435 }
436 if chunk.failed {
437 flags |= FLAG_FAILED;
438 }
439 data.push(flags);
440 }
441 table.push(
442 &key.to_bytes(),
443 UnitLocation {
444 offset: start as u64,
445 len: u32::try_from(data.len() - start).expect("a chunk map is below 4 GiB"),
446 },
447 );
448 }
449 let (table, maps) = table.finish();
450 writer.write_section(spec(CHUNK_MAPS, Alignment::Word), &table, maps)?;
451 writer.write_section(spec(CHUNK_MAP_DATA, Alignment::Word), &data, maps)?;
452 let (details, index) = details.finish();
453 writer.write_section(spec(DETAILS_INDEX, Alignment::Word), &index, maps)?;
454 writer.write_section(spec(DETAILS, Alignment::Word), &details, maps)
455 }
456}
457
458fn spec(kind: SectionKind, alignment: Alignment) -> SectionSpec {
459 SectionSpec {
460 id: SectionId::new(kind, KEY_SPACE),
461 version: VERSION,
462 alignment,
463 requirement: Requirement::Required,
464 }
465}
466
467#[derive(Debug)]
469pub struct VectorSegment<'s> {
470 segment: &'s Segment,
471 model: ModelIdentity,
472 units: UnitTable<'s>,
473 center: Arc<[f32]>,
475 scan: SectionHandle,
476 vectors: SectionHandle,
477 maps: UnitTable<'s>,
478 map_data: SectionHandle,
479 details_index: SectionHandle,
480 details: SectionHandle,
481 dimensions: usize,
482}
483
484#[derive(Clone, Debug)]
488pub struct VectorSegmentParts {
489 model: ModelIdentity,
490 units: UnitTableParts,
491 center: Arc<[f32]>,
492 scan: SectionHandle,
493 vectors: SectionHandle,
494 maps: UnitTableParts,
495 map_data: SectionHandle,
496 details_index: SectionHandle,
497 details: SectionHandle,
498}
499
500impl<'s> VectorSegment<'s> {
501 pub fn open(segment: &'s Segment) -> Result<Option<Self>, SegmentError> {
508 let handles = KINDS.map(|kind| segment.section(SectionId::new(kind, KEY_SPACE)));
509 let [
510 Some(fingerprint),
511 Some(units),
512 Some(center),
513 Some(scan),
514 Some(vectors),
515 Some(maps),
516 Some(map_data),
517 Some(details_index),
518 Some(details),
519 ] = handles
520 else {
521 if handles.iter().any(Option::is_some) {
522 return Err(malformed(
523 segment,
524 "a segment has only some vector sections",
525 ));
526 }
527 return Ok(None);
528 };
529 let info = segment.info(fingerprint);
530 let len = usize::try_from(info.len)
531 .ok()
532 .filter(|len| *len <= 16 * 1024)
533 .ok_or_else(|| malformed(segment, "the model fingerprint is too long"))?;
534 let mut bytes = vec![0; len];
535 segment.read(fingerprint, 0, &mut bytes)?;
536 let model = ModelIdentity::decode(&bytes)
537 .filter(|model| (1..=MAX_DIMENSIONS).contains(&model.dimensions))
538 .ok_or_else(|| malformed(segment, "the model fingerprint does not decode"))?;
539 let dimensions = model.dimensions as usize;
540 let units = UnitTable::open(segment, units)?;
541 let center_info = segment.info(center);
542 if center_info.len != dimensions as u64 * 4 || center_info.item_count != dimensions as u64 {
543 return Err(malformed(
544 segment,
545 "the scan center does not match the model",
546 ));
547 }
548 let mut center_bytes = vec![0; dimensions * 4];
549 segment.read(center, 0, &mut center_bytes)?;
550 let center: Arc<[f32]> = f32s(¢er_bytes).into();
551 if center.iter().any(|value| !value.is_finite()) {
552 return Err(malformed(segment, "the scan center is not finite"));
553 }
554 let count = u64::from(units.len());
555 let scan_info = segment.info(scan);
556 let vectors_info = segment.info(vectors);
557 if scan_info.len != count * scan_row_len(dimensions) as u64
558 || scan_info.item_count != count
559 || vectors_info.len != count * dimensions as u64 * 4
560 || vectors_info.item_count != count
561 {
562 return Err(malformed(
563 segment,
564 "vector rows do not match the vector unit table",
565 ));
566 }
567 check_scan_rows(segment, scan, count, dimensions)?;
568 let maps = UnitTable::open(segment, maps)?;
569 if segment.info(map_data).item_count != u64::from(maps.len()) {
570 return Err(malformed(
571 segment,
572 "chunk map data does not match the chunk map table",
573 ));
574 }
575 let index_info = segment.info(details_index);
576 if index_info.item_count != u64::from(maps.len())
577 || index_info.len != u64::from(maps.len()) * INDEX_ENTRY_LEN as u64
578 || segment.info(details).item_count != u64::from(maps.len())
579 {
580 return Err(malformed(
581 segment,
582 "chunk details do not match the chunk map table",
583 ));
584 }
585 Ok(Some(Self {
586 segment,
587 model,
588 units,
589 center,
590 scan,
591 vectors,
592 maps,
593 map_data,
594 details_index,
595 details,
596 dimensions,
597 }))
598 }
599
600 #[must_use]
603 pub fn parts(&self) -> VectorSegmentParts {
604 VectorSegmentParts {
605 model: self.model.clone(),
606 units: self.units.parts(),
607 center: Arc::clone(&self.center),
608 scan: self.scan,
609 vectors: self.vectors,
610 maps: self.maps.parts(),
611 map_data: self.map_data,
612 details_index: self.details_index,
613 details: self.details,
614 }
615 }
616
617 #[must_use]
622 pub fn reopen(segment: &'s Segment, parts: &VectorSegmentParts) -> Option<Self> {
623 if segment.section(SectionId::new(UNITS, KEY_SPACE)) != Some(parts.units.section) {
626 return None;
627 }
628 Some(Self {
629 segment,
630 model: parts.model.clone(),
631 units: UnitTable::attach(segment, parts.units),
632 center: Arc::clone(&parts.center),
633 scan: parts.scan,
634 vectors: parts.vectors,
635 maps: UnitTable::attach(segment, parts.maps),
636 map_data: parts.map_data,
637 details_index: parts.details_index,
638 details: parts.details,
639 dimensions: parts.model.dimensions as usize,
640 })
641 }
642
643 #[must_use]
644 pub fn segment(&self) -> &'s Segment {
645 self.segment
646 }
647
648 #[must_use]
649 pub fn model(&self) -> &ModelIdentity {
650 &self.model
651 }
652
653 #[must_use]
654 pub fn dimensions(&self) -> usize {
655 self.dimensions
656 }
657
658 #[must_use]
660 pub fn center(&self) -> &[f32] {
661 &self.center
662 }
663
664 #[must_use]
666 pub fn len(&self) -> u32 {
667 self.units.len()
668 }
669
670 #[must_use]
671 pub fn is_empty(&self) -> bool {
672 self.units.is_empty()
673 }
674
675 #[must_use]
677 pub fn chunk_map_count(&self) -> u32 {
678 self.maps.len()
679 }
680
681 #[must_use]
683 pub fn section_bytes(&self) -> SectionBytes {
684 let len = |handle| self.segment.info(handle).len;
685 let units = self
686 .segment
687 .section(SectionId::new(UNITS, KEY_SPACE))
688 .map_or(0, len);
689 let maps = self
690 .segment
691 .section(SectionId::new(CHUNK_MAPS, KEY_SPACE))
692 .map_or(0, len);
693 let details_index = len(self.details_index);
694 SectionBytes {
695 units,
696 scan: len(self.scan),
697 vectors: len(self.vectors),
698 chunk_maps: maps + len(self.map_data),
699 chunk_details: details_index + len(self.details),
700 }
701 }
702
703 pub fn chunk_map_keys(&self) -> Result<Vec<ChunkMapKey>, SegmentError> {
709 (0..self.maps.len())
710 .map(|ordinal| {
711 let (key, _) = self.maps.entry(ordinal)?;
712 ChunkMapKey::from_bytes(&key)
713 .ok_or_else(|| self.malformed("a chunk map key is not a content and path"))
714 })
715 .collect()
716 }
717
718 pub fn texts(&self) -> Result<Vec<TextDigest>, SegmentError> {
724 (0..self.units.len())
725 .map(|ordinal| {
726 let (key, _) = self.units.entry(ordinal)?;
727 let bytes = <[u8; Digest128::LEN]>::try_from(key.as_slice())
728 .map_err(|_| self.malformed("a vector unit key is not a text digest"))?;
729 Ok(TextDigest::from_digest(Digest128::from_bytes(bytes)))
730 })
731 .collect()
732 }
733
734 pub fn find(&self, text: TextDigest) -> Result<Option<u32>, SegmentError> {
740 Ok(self
741 .units
742 .get(text.digest().as_bytes())?
743 .map(|(ordinal, _)| ordinal))
744 }
745
746 pub fn vector(&self, ordinal: u32) -> Result<Vec<f32>, SegmentError> {
752 let mut bytes = vec![0; self.dimensions * 4];
753 self.read_vector(ordinal, &mut bytes)?;
754 Ok(f32s(&bytes))
755 }
756
757 pub(crate) fn read_vector(&self, ordinal: u32, bytes: &mut [u8]) -> Result<(), SegmentError> {
760 debug_assert_eq!(bytes.len(), self.dimensions * 4);
761 self.segment.read(
762 self.vectors,
763 u64::from(ordinal) * (self.dimensions as u64 * 4),
764 bytes,
765 )
766 }
767
768 pub(crate) fn read_vectors(&self, first: u32, bytes: &mut [u8]) -> Result<(), SegmentError> {
771 self.segment.read(
772 self.vectors,
773 u64::from(first) * (self.dimensions as u64 * 4),
774 bytes,
775 )
776 }
777
778 pub(crate) fn read_scan_rows(&self, first: u32, bytes: &mut [u8]) -> Result<(), SegmentError> {
781 self.segment.read(
782 self.scan,
783 u64::from(first) * scan_row_len(self.dimensions) as u64,
784 bytes,
785 )
786 }
787
788 pub fn chunk_map(
795 &self,
796 content: ContentKey,
797 path: &[u8],
798 ) -> Result<Option<Vec<Chunk>>, SegmentError> {
799 Ok(self.locate_map(content, path)?.map(|(_, chunks)| chunks))
800 }
801
802 pub fn chunk_map_at(&self, ordinal: u32) -> Result<Vec<Chunk>, SegmentError> {
808 let (_, location) = self.maps.entry(ordinal)?;
809 let bytes = self.read_map(location)?;
810 Ok(self.decode_map(&bytes)?.1)
811 }
812
813 pub fn chunk_details(
822 &self,
823 content: ContentKey,
824 path: &[u8],
825 ) -> Result<Option<FileDetails>, SegmentError> {
826 let Some((ordinal, chunks)) = self.locate_map(content, path)? else {
827 return Ok(None);
828 };
829 let bytes = packed::read(self.segment, self.details, self.details_index, ordinal)?;
830 if bytes.is_empty() {
831 return Ok(None);
832 }
833 let details = FileDetails::decode(&bytes)
834 .map_err(|_| self.malformed("chunk details do not decode"))?;
835 let matches = details.chunks.len() == chunks.len()
836 && chunks
837 .iter()
838 .zip(&details.chunks)
839 .all(|(chunk, detail)| chunk.failed == detail.failure.is_some());
840 if !matches {
841 return Err(self.malformed("chunk details do not match their chunk map"));
842 }
843 Ok(Some(details))
844 }
845
846 fn locate_map(
849 &self,
850 content: ContentKey,
851 path: &[u8],
852 ) -> Result<Option<(u32, Vec<Chunk>)>, SegmentError> {
853 let key = ChunkMapKey::new(content, path);
854 let Some((ordinal, location)) = self.maps.get(&key.to_bytes())? else {
855 return Ok(None);
856 };
857 let bytes = self.read_map(location)?;
858 let (stored_path, chunks) = self.decode_map(&bytes)?;
859 if stored_path != path {
860 return Err(self.malformed("a chunk map is stored under another path"));
863 }
864 Ok(Some((ordinal, chunks)))
865 }
866
867 fn read_map(&self, location: UnitLocation) -> Result<Vec<u8>, SegmentError> {
868 let end = location
869 .offset
870 .checked_add(u64::from(location.len))
871 .ok_or_else(|| self.malformed("a chunk map's range overflows"))?;
872 self.segment.read_range(self.map_data, location.offset..end)
873 }
874
875 fn decode_map<'b>(&self, bytes: &'b [u8]) -> Result<(&'b [u8], Vec<Chunk>), SegmentError> {
876 let fail = || self.malformed("a chunk map does not decode");
877 if bytes.len() < 8 {
878 return Err(fail());
879 }
880 let path_len = u32_at(bytes, 0) as usize;
881 let count_at = 4usize.checked_add(path_len).ok_or_else(fail)?;
882 let entries_at = count_at
883 .checked_add(4)
884 .filter(|at| *at <= bytes.len())
885 .ok_or_else(fail)?;
886 let count = u32_at(bytes, count_at) as usize;
887 let entries = &bytes[entries_at..];
888 if Some(entries.len()) != count.checked_mul(CHUNK_ENTRY_LEN) {
889 return Err(fail());
890 }
891 let chunks = entries
892 .as_chunks::<CHUNK_ENTRY_LEN>()
893 .0
894 .iter()
895 .map(|entry| {
896 let flags = entry[Digest128::LEN];
897 if flags & !(FLAG_EXPORTED | FLAG_FAILED) != 0 {
898 return Err(fail());
899 }
900 Ok(Chunk {
901 text: TextDigest::from_digest(Digest128::from_bytes(crate::le::array(
902 entry, 0,
903 ))),
904 exported: flags & FLAG_EXPORTED != 0,
905 failed: flags & FLAG_FAILED != 0,
906 })
907 })
908 .collect::<Result<_, _>>()?;
909 Ok((&bytes[4..count_at], chunks))
910 }
911
912 fn malformed(&self, reason: &'static str) -> SegmentError {
913 malformed(self.segment, reason)
914 }
915}
916
917fn malformed(segment: &Segment, reason: &'static str) -> SegmentError {
918 SegmentError::new(segment.path(), ErrorKind::Malformed(reason))
919}
920
921fn check_scan_rows(
926 segment: &Segment,
927 scan: SectionHandle,
928 count: u64,
929 dimensions: usize,
930) -> Result<(), SegmentError> {
931 let row_len = scan_row_len(dimensions);
932 let rows_per_read = (BLOCK_LEN / row_len).max(1);
933 let mut rows = Vec::new();
934 let mut first = 0u64;
935 while first < count {
936 let take = rows_per_read.min(usize::try_from(count - first).unwrap_or(usize::MAX));
937 rows.resize(take * row_len, 0);
938 segment.read(scan, first * row_len as u64, &mut rows)?;
939 if rows
940 .chunks_exact(row_len)
941 .any(|row| !scan_params(row).is_sound())
942 {
943 return Err(malformed(
944 segment,
945 "a scan row holds a negative or non-finite value",
946 ));
947 }
948 first += take as u64;
949 }
950 Ok(())
951}
952
953pub(crate) fn scan_params(row: &[u8]) -> ScanParams {
955 let value = |at| f32::from_le_bytes(crate::le::array(row, at));
956 ScanParams {
957 scale: value(0),
958 residual: value(4),
959 norm: value(8),
960 max_residual: value(12),
961 }
962}
963
964pub(crate) fn scan_codes(row: &[u8], dimensions: usize) -> &[u8] {
966 &row[SCAN_HEADER_LEN..SCAN_HEADER_LEN + dimensions]
967}
968
969pub(crate) fn f32s(bytes: &[u8]) -> Vec<f32> {
971 bytes
972 .as_chunks::<4>()
973 .0
974 .iter()
975 .map(|chunk| f32::from_le_bytes(*chunk))
976 .collect()
977}
978
979crate::heap_bytes_of_fields!(VectorSegmentParts {
980 model,
981 units,
982 center,
983 scan,
984 vectors,
985 maps,
986 map_data,
987 details_index,
988 details,
989});
990
991#[cfg(test)]
992mod tests {
993 use std::path::Path;
994 use std::sync::Arc;
995
996 use super::*;
997 use crate::cache::BlockCache;
998 use crate::ids::{FamilyId, SegmentId, WriterIncarnation};
999 use crate::segment::SegmentMeta;
1000
1001 const DIMENSIONS: u32 = 4;
1002 const PATH: &[u8] = b"src/a.rs";
1003
1004 fn family() -> FamilyId {
1005 FamilyId::from_digest(Digest128::of(b"forged vector sections"))
1006 }
1007
1008 fn model() -> ModelIdentity {
1009 ModelIdentity {
1010 name: "test/forged".to_string(),
1011 revision: "r1".to_string(),
1012 dimensions: DIMENSIONS,
1013 normalized: true,
1014 text_template: 1,
1015 chunk_template: 1,
1016 }
1017 }
1018
1019 fn content() -> ContentKey {
1020 ContentKey::of(b"fn a() {}")
1021 }
1022
1023 fn le_bytes(values: &[f32]) -> Vec<u8> {
1024 values
1025 .iter()
1026 .flat_map(|value| value.to_le_bytes())
1027 .collect()
1028 }
1029
1030 const SOUND: [f32; 4] = [0.01, 0.001, 1.0, 0.0005];
1032
1033 fn write_forged(path: &Path, params: [f32; 4], map: Option<UnitLocation>) -> Segment {
1038 let dimensions = DIMENSIONS as usize;
1039 let mut writer = SegmentWriter::create(
1040 path,
1041 SegmentMeta {
1042 family: family(),
1043 segment: SegmentId::new(1),
1044 incarnation: WriterIncarnation::new(1),
1045 created_unix_ms: 0,
1046 },
1047 )
1048 .unwrap();
1049 writer
1050 .write_section(spec(FINGERPRINT, Alignment::Word), &model().encode(), 1)
1051 .unwrap();
1052 let mut units = UnitTableBuilder::new(Digest128::LEN);
1053 units.push(
1054 TextDigest::of(b"chunk").digest().as_bytes(),
1055 UnitLocation {
1056 offset: 0,
1057 len: DIMENSIONS * 4,
1058 },
1059 );
1060 let (units, count) = units.finish();
1061 writer
1062 .write_section(spec(UNITS, Alignment::Word), &units, count)
1063 .unwrap();
1064 writer
1065 .write_section(
1066 spec(CENTER, Alignment::Word),
1067 &le_bytes(&[0.0; DIMENSIONS as usize]),
1068 u64::from(DIMENSIONS),
1069 )
1070 .unwrap();
1071 let mut row = le_bytes(¶ms);
1072 row.resize(scan_row_len(dimensions), 0);
1073 writer
1074 .write_section(spec(SCAN, Alignment::Vector), &row, 1)
1075 .unwrap();
1076 writer
1077 .write_section(
1078 spec(VECTORS, Alignment::Vector),
1079 &le_bytes(&[1.0, 0.0, 0.0, 0.0]),
1080 1,
1081 )
1082 .unwrap();
1083 let mut data = u32::try_from(PATH.len()).unwrap().to_le_bytes().to_vec();
1085 data.extend_from_slice(PATH);
1086 data.extend_from_slice(&0u32.to_le_bytes());
1087 let mut maps = UnitTableBuilder::new(ChunkMapKey::LEN);
1088 maps.push(
1089 &ChunkMapKey::new(content(), PATH).to_bytes(),
1090 map.unwrap_or(UnitLocation {
1091 offset: 0,
1092 len: u32::try_from(data.len()).unwrap(),
1093 }),
1094 );
1095 let (maps, count) = maps.finish();
1096 writer
1097 .write_section(spec(CHUNK_MAPS, Alignment::Word), &maps, count)
1098 .unwrap();
1099 writer
1100 .write_section(spec(CHUNK_MAP_DATA, Alignment::Word), &data, count)
1101 .unwrap();
1102 let mut details = PackedBuilder::with_capacity(1);
1103 details.push(&[]);
1104 let (details, index) = details.finish();
1105 writer
1106 .write_section(spec(DETAILS_INDEX, Alignment::Word), &index, count)
1107 .unwrap();
1108 writer
1109 .write_section(spec(DETAILS, Alignment::Word), &details, count)
1110 .unwrap();
1111 writer.finish().unwrap();
1112 Segment::open(
1113 path,
1114 family(),
1115 &KNOWN,
1116 Arc::new(BlockCache::new(4 * BLOCK_LEN)),
1117 )
1118 .unwrap()
1119 }
1120
1121 #[test]
1122 fn a_scan_row_no_writer_produces_is_refused_at_open() {
1123 let dir = tempfile::tempdir().unwrap();
1124 let sound = write_forged(&dir.path().join("sound.seg"), SOUND, None);
1125 let opened = VectorSegment::open(&sound).unwrap().unwrap();
1126 assert_eq!(opened.chunk_map(content(), PATH).unwrap(), Some(Vec::new()));
1127 let mut cases = Vec::new();
1130 for field in 0..4 {
1131 for bad in [-0.5, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1132 let mut params = SOUND;
1133 params[field] = bad;
1134 cases.push(params);
1135 }
1136 }
1137 for (index, params) in cases.into_iter().enumerate() {
1138 let segment = write_forged(&dir.path().join(format!("{index}.seg")), params, None);
1139 let error = VectorSegment::open(&segment).unwrap_err();
1140 assert!(
1141 matches!(
1142 error.kind(),
1143 ErrorKind::Malformed("a scan row holds a negative or non-finite value")
1144 ),
1145 "{params:?}: {error}"
1146 );
1147 assert!(error.is_corruption(), "{params:?}");
1148 }
1149 }
1150
1151 #[test]
1152 fn a_chunk_map_range_past_u64_is_refused() {
1153 let dir = tempfile::tempdir().unwrap();
1154 let segment = write_forged(
1155 &dir.path().join("overflow.seg"),
1156 SOUND,
1157 Some(UnitLocation {
1158 offset: u64::MAX - 3,
1159 len: 16,
1160 }),
1161 );
1162 let opened = VectorSegment::open(&segment).unwrap().unwrap();
1163 let error = opened.chunk_map(content(), PATH).unwrap_err();
1164 assert!(
1165 matches!(
1166 error.kind(),
1167 ErrorKind::Malformed("a chunk map's range overflows")
1168 ),
1169 "{error}"
1170 );
1171 assert!(error.is_corruption());
1172 }
1173
1174 #[test]
1175 fn a_chunk_map_whose_path_runs_past_its_bytes_is_refused() {
1176 let dir = tempfile::tempdir().unwrap();
1177 let segment = write_forged(&dir.path().join("short.seg"), SOUND, None);
1178 let opened = VectorSegment::open(&segment).unwrap().unwrap();
1179 for path_len in [5u32, u32::MAX] {
1182 let mut bytes = path_len.to_le_bytes().to_vec();
1183 bytes.extend_from_slice(&[0; 8]);
1184 assert!(opened.decode_map(&bytes).unwrap_err().is_corruption());
1185 }
1186 }
1187}