1use std::fs::{File, OpenOptions};
151use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
152use std::ops::Range;
153use std::path::Path;
154use std::sync::atomic::{AtomicU64, Ordering};
155use std::sync::{Arc, OnceLock};
156
157use datafusion::arrow::array::{Array, Int64Array, StringArray};
158use datafusion::arrow::buffer::{BooleanBuffer, Buffer, OffsetBuffer, ScalarBuffer};
159use datafusion::arrow::datatypes::ArrowNativeType;
160use serde_json::{json, Value};
161use ursa_core::id_map::lookup_table_len;
162use ursa_core::{Adjacency, EdgeIds, IdMap, Topology};
163
164use super::mapped::{Region, Unverified};
165use crate::graph::FileIdentity;
166
167pub const MAGIC: [u8; 8] = *b"URSAIDX\0";
169const END_MAGIC: [u8; 4] = *b"XDIU";
171pub const VERSION: u32 = 5;
174pub const VERSION_4: u32 = 4;
177pub const VERSION_3: u32 = 3;
179pub const VERSION_2: u32 = 2;
181const CHUNK_MAGIC: [u8; 4] = *b"CHNK";
183const CHUNK_END_MAGIC: [u8; 4] = *b"KNHC";
185const CHUNK_HEADER_LEN: u64 = 16;
186const CHUNK_TRAILER_LEN: u64 = 48;
187
188pub const CHUNK_INCOMING: u32 = 1;
190pub const CHUNK_WEIGHTS: u32 = 2;
192
193const HEADER_LEN: u64 = 64;
194const TRAILER_LEN: u64 = 16;
195const SECTION_ENTRY_LEN: u64 = 32;
197const CHUNK_ENTRY_LEN: u64 = 24;
199const SECTION_ALIGN: u64 = 64;
200
201const FLAG_STRING_IDS: u32 = 1;
202
203const OUT_OFFSETS: u32 = 1;
204const OUT_TARGETS: u32 = 2;
205const OUT_EDGE_IDS: u32 = 3;
206const IN_OFFSETS: u32 = 4;
207const IN_TARGETS: u32 = 5;
208const IN_EDGE_IDS: u32 = 6;
209const IDS_INT64: u32 = 7;
210const IDS_STR_OFFSETS: u32 = 8;
211const IDS_STR_BYTES: u32 = 9;
212const WEIGHTS_F64: u32 = 10;
213const KEPT_ROWS: u32 = 11;
214const ID_TABLE: u32 = 12;
215const ORIGINAL_IDS: u32 = 13;
216
217pub const KEY_VERSION: u64 = 2;
223
224#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct IndexKey {
228 pub fingerprint: String,
229 pub files: Vec<FileIdentity>,
230}
231
232impl IndexKey {
233 pub fn new(fingerprint: String, files: Vec<FileIdentity>) -> Self {
234 Self { fingerprint, files }
235 }
236
237 pub fn to_json(&self) -> Value {
240 let files: Vec<Value> = self
241 .files
242 .iter()
243 .map(|f| {
244 json!({
245 "store": f.store,
246 "location": f.location,
247 "size": f.size,
248 "modified": f.modified,
249 "e_tag": f.e_tag,
250 })
251 })
252 .collect();
253 json!({ "version": KEY_VERSION, "fingerprint": self.fingerprint, "files": files })
254 }
255
256 pub fn from_json(value: &Value) -> Option<Self> {
258 if value.get("version")?.as_u64()? != KEY_VERSION {
259 return None;
260 }
261 let fingerprint = value.get("fingerprint")?.as_str()?.to_string();
262 let files = value
263 .get("files")?
264 .as_array()?
265 .iter()
266 .map(|f| {
267 Some(FileIdentity {
268 store: f.get("store")?.as_str()?.to_string(),
269 location: f.get("location")?.as_str()?.to_string(),
270 size: f.get("size")?.as_u64()?,
271 modified: f.get("modified")?.as_i64()?,
272 e_tag: match f.get("e_tag")? {
273 Value::Null => None,
274 Value::String(s) => Some(s.clone()),
275 _ => return None,
276 },
277 })
278 })
279 .collect::<Option<Vec<_>>>()?;
280 Some(Self { fingerprint, files })
281 }
282
283 pub fn hash(&self) -> u64 {
287 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
288 for b in self.to_json().to_string().bytes() {
289 h ^= u64::from(b);
290 h = h.wrapping_mul(0x0000_0100_0000_01b3);
291 }
292 h
293 }
294}
295
296enum Data<'a> {
299 U64(&'a [u64]),
300 F64(&'a [f64]),
301 U32(&'a [u32]),
302 Ints(Int64Array),
304 StrOffsets(StringArray),
307 StrBytes(StringArray),
309 Bytes(Buffer),
311 IdTable(IdTable<'a>),
313 EdgeIds(&'a EdgeIds, OnceLock<ScalarBuffer<u32>>),
317}
318
319impl<'a> Data<'a> {
320 fn edge_ids(ids: &'a EdgeIds) -> Self {
322 Data::EdgeIds(ids, OnceLock::new())
323 }
324}
325
326fn ids_of<'d>(ids: &'d EdgeIds, built: &'d OnceLock<ScalarBuffer<u32>>) -> &'d [u32] {
328 built.get_or_init(|| ids.detached())
329}
330
331struct IdTable<'a> {
335 ids: &'a IdMap,
336 slots: OnceLock<Result<ScalarBuffer<u32>, String>>,
337}
338
339impl IdTable<'_> {
340 fn build(&self) -> Result<&ScalarBuffer<u32>, String> {
341 self.slots
342 .get_or_init(|| self.ids.lookup_table().map_err(|e| e.to_string()))
343 .as_ref()
344 .map_err(Clone::clone)
345 }
346
347 fn slots(&self) -> &[u32] {
349 self.build()
350 .expect("write_to builds the lookup table before it is written")
351 }
352}
353
354impl Data<'_> {
355 fn width(&self) -> u64 {
356 match self {
357 Data::U64(_) | Data::F64(_) | Data::Ints(_) => 8,
358 Data::U32(_) | Data::StrOffsets(_) | Data::IdTable(_) | Data::EdgeIds(..) => 4,
359 Data::StrBytes(_) | Data::Bytes(_) => 1,
360 }
361 }
362
363 fn count(&self) -> u64 {
364 (match self {
365 Data::U64(v) => v.len(),
366 Data::F64(v) => v.len(),
367 Data::U32(v) => v.len(),
368 Data::Ints(a) => a.len(),
369 Data::StrOffsets(a) => a.len() + 1,
370 Data::StrBytes(a) => str_bytes(a).len(),
371 Data::Bytes(b) => b.len(),
372 Data::IdTable(t) => return lookup_table_len(t.ids.len()),
373 Data::EdgeIds(ids, _) => ids.len(),
374 }) as u64
375 }
376}
377
378fn str_bytes(strings: &StringArray) -> &[u8] {
380 let offsets = strings.value_offsets();
381 let (first, last) = (offsets[0] as usize, offsets[offsets.len() - 1] as usize);
382 &strings.value_data()[first..last]
383}
384
385fn align(n: u64, to: u64) -> u64 {
386 n.div_ceil(to) * to
387}
388
389pub struct Encoded<'a> {
392 version: u32,
395 flags: u32,
396 n_nodes: u64,
397 n_edges: u64,
398 n_dropped: u64,
399 key: Vec<u8>,
400 sections: Vec<(u32, Data<'a>, u64)>,
401 table_offset: u64,
402 trailer_offset: u64,
403}
404
405impl<'a> Encoded<'a> {
406 pub fn new(key: &IndexKey, topology: &'a Topology, ids: &'a IdMap) -> io::Result<Self> {
409 Self::with_dropped(key, topology, ids, 0, None)
410 }
411
412 pub fn with_dropped(
415 key: &IndexKey,
416 topology: &'a Topology,
417 ids: &'a IdMap,
418 n_dropped: u64,
419 kept: Option<&BooleanBuffer>,
420 ) -> io::Result<Self> {
421 let id_array = ids.user_id_array();
422 let mut flags = 0;
423 let out = topology.out();
424 let mut sections: Vec<(u32, Data<'a>)> = vec![
425 (OUT_OFFSETS, Data::U64(&out.offsets)),
426 (OUT_TARGETS, Data::U32(&out.targets)),
427 (OUT_EDGE_IDS, Data::edge_ids(&out.edge_ids)),
428 ];
429 if let Some(ints) = id_array.as_any().downcast_ref::<Int64Array>() {
431 sections.push((IDS_INT64, Data::Ints(ints.clone())));
432 } else if let Some(strings) = id_array.as_any().downcast_ref::<StringArray>() {
433 flags |= FLAG_STRING_IDS;
434 sections.push((IDS_STR_OFFSETS, Data::StrOffsets(strings.clone())));
435 sections.push((IDS_STR_BYTES, Data::StrBytes(strings.clone())));
436 } else {
437 return Err(io::Error::other(format!(
438 "cannot store node ids of type {}",
439 id_array.data_type()
440 )));
441 }
442 sections.push((
443 ID_TABLE,
444 Data::IdTable(IdTable {
445 ids,
446 slots: OnceLock::new(),
447 }),
448 ));
449 if let Some(original) = topology.original_ids() {
451 sections.push((ORIGINAL_IDS, Data::U32(original)));
452 }
453 let n_dropped = match kept {
454 Some(kept) if n_dropped > 0 => {
455 sections.push((KEPT_ROWS, Data::Bytes(kept.sliced())));
456 n_dropped
457 }
458 _ => 0,
459 };
460
461 let key = key.to_json().to_string().into_bytes();
462 let (n_nodes, n_edges) = (topology.n_nodes() as u64, topology.n_edges() as u64);
463 Ok(Self::laid_out(
464 VERSION, flags, n_nodes, n_edges, n_dropped, key, sections,
465 ))
466 }
467
468 fn laid_out(
471 version: u32,
472 flags: u32,
473 n_nodes: u64,
474 n_edges: u64,
475 n_dropped: u64,
476 key: Vec<u8>,
477 sections: Vec<(u32, Data<'a>)>,
478 ) -> Self {
479 let entry_len = match version {
480 VERSION_2 => CHUNK_ENTRY_LEN,
481 _ => SECTION_ENTRY_LEN,
482 };
483 let table_offset = align(HEADER_LEN + key.len() as u64, 8);
484 let mut at = table_offset + entry_len * sections.len() as u64;
485 let sections = sections
486 .into_iter()
487 .map(|(kind, data)| {
488 at = align(at, SECTION_ALIGN);
489 let offset = at;
490 at += data.width() * data.count();
491 (kind, data, offset)
492 })
493 .collect();
494 Self {
495 version,
496 flags,
497 n_nodes,
498 n_edges,
499 n_dropped,
500 key,
501 sections,
502 table_offset,
503 trailer_offset: align(at, 8),
504 }
505 }
506
507 #[doc(hidden)]
510 pub fn as_version_2(self) -> Self {
511 self.in_version(VERSION_2)
512 }
513
514 #[doc(hidden)]
517 pub fn as_version_3(self) -> Self {
518 self.in_version(VERSION_3)
519 }
520
521 #[doc(hidden)]
525 pub fn as_version_4(self) -> Self {
526 self.in_version(VERSION_4)
527 }
528
529 fn in_version(self, version: u32) -> Self {
532 let Self {
533 flags,
534 n_nodes,
535 n_edges,
536 n_dropped,
537 key,
538 sections,
539 ..
540 } = self;
541 let sections = sections
542 .into_iter()
543 .filter(|(k, _, _)| *k != ORIGINAL_IDS)
544 .filter(|(k, _, _)| version == VERSION_4 || *k != ID_TABLE)
545 .map(|(k, d, _)| (k, d))
546 .collect();
547 Self::laid_out(version, flags, n_nodes, n_edges, n_dropped, key, sections)
548 }
549
550 pub fn file_size(&self) -> u64 {
552 self.trailer_offset + TRAILER_LEN
553 }
554
555 pub fn write_to(&self, out: impl Write) -> io::Result<MainPart> {
557 let v2 = self.version == VERSION_2;
558 for (_, data, _) in &self.sections {
559 if let Data::IdTable(table) = data {
560 table.build().map_err(io::Error::other)?;
561 }
562 }
563 let crcs: Vec<Option<u32>> = self
566 .sections
567 .iter()
568 .map(|(_, data, _)| (!v2).then(|| data_crc(data)))
569 .collect();
570 let mut sink = Sink {
571 out,
572 crc: crc32fast::Hasher::new(),
573 at: 0,
574 hash: true,
575 };
576 let mut header = Vec::with_capacity(HEADER_LEN as usize);
577 header.extend_from_slice(&MAGIC);
578 header.extend_from_slice(&self.version.to_le_bytes());
579 header.extend_from_slice(&self.flags.to_le_bytes());
580 header.extend_from_slice(&self.n_nodes.to_le_bytes());
581 header.extend_from_slice(&self.n_edges.to_le_bytes());
582 header.extend_from_slice(&(self.key.len() as u64).to_le_bytes());
583 header.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
584 header.extend_from_slice(&[0; 4]);
585 header.extend_from_slice(&self.file_size().to_le_bytes());
586 header.extend_from_slice(&self.n_dropped.to_le_bytes());
587 header.resize(HEADER_LEN as usize, 0);
588 sink.put(&header)?;
589 sink.put(&self.key)?;
590 sink.pad_to(self.table_offset)?;
591 for ((kind, data, offset), crc) in self.sections.iter().zip(&crcs) {
592 sink.put(§ion_entry(*kind, data, *offset, *crc))?;
593 }
594 let meta_crc = sink.crc.clone().finalize();
597 sink.hash = v2;
598 for (_, data, offset) in &self.sections {
599 sink.pad_to(*offset)?;
600 sink.put_data(data)?;
601 }
602 sink.pad_to(self.trailer_offset)?;
603 let crc = match v2 {
604 true => sink.crc.clone().finalize(),
605 false => meta_crc,
606 };
607 let mut trailer = Vec::with_capacity(TRAILER_LEN as usize);
608 trailer.extend_from_slice(&self.file_size().to_le_bytes());
609 trailer.extend_from_slice(&crc.to_le_bytes());
610 trailer.extend_from_slice(&END_MAGIC);
611 sink.put(&trailer)?;
612 sink.out.flush()?;
613 Ok(MainPart {
614 len: self.file_size(),
615 crc,
616 })
617 }
618}
619
620#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
623pub struct MainPart {
624 pub len: u64,
625 pub crc: u32,
626}
627
628pub struct EncodedChunk<'a> {
630 kind: u32,
631 name: Vec<u8>,
632 start: u64,
633 sections: Vec<(u32, Data<'a>, u64)>,
634 name_offset: u64,
635 table_offset: u64,
636}
637
638impl<'a> EncodedChunk<'a> {
639 pub fn incoming(incoming: &'a Adjacency, start: u64) -> Self {
641 Self::new(
642 CHUNK_INCOMING,
643 Vec::new(),
644 vec![
645 (IN_OFFSETS, Data::U64(&incoming.offsets)),
646 (IN_TARGETS, Data::U32(&incoming.targets)),
647 (IN_EDGE_IDS, Data::edge_ids(&incoming.edge_ids)),
648 ],
649 start,
650 )
651 }
652
653 pub fn weights(key: &str, columns: &[&'a [f64]], start: u64) -> Self {
656 Self::new(
657 CHUNK_WEIGHTS,
658 key.as_bytes().to_vec(),
659 columns
660 .iter()
661 .map(|column| (WEIGHTS_F64, Data::F64(column)))
662 .collect(),
663 start,
664 )
665 }
666
667 fn new(kind: u32, name: Vec<u8>, sections: Vec<(u32, Data<'a>)>, start: u64) -> Self {
668 let mut at = start + CHUNK_HEADER_LEN;
669 let sections = sections
670 .into_iter()
671 .map(|(kind, data)| {
672 at = align(at, SECTION_ALIGN);
673 let offset = at;
674 at += data.width() * data.count();
675 (kind, data, offset)
676 })
677 .collect();
678 let name_offset = at;
679 let table_offset = align(name_offset + name.len() as u64, 8);
680 Self {
681 kind,
682 name,
683 start,
684 sections,
685 name_offset,
686 table_offset,
687 }
688 }
689
690 fn trailer_offset(&self) -> u64 {
691 self.table_offset + CHUNK_ENTRY_LEN * self.sections.len() as u64
692 }
693
694 pub fn end(&self) -> u64 {
696 self.trailer_offset() + CHUNK_TRAILER_LEN
697 }
698
699 pub fn size(&self) -> u64 {
701 self.end() - self.start
702 }
703
704 pub fn write_to(&self, out: impl Write) -> io::Result<()> {
706 let mut sink = Sink {
707 out,
708 crc: crc32fast::Hasher::new(),
709 at: self.start,
710 hash: true,
711 };
712 let mut header = Vec::with_capacity(CHUNK_HEADER_LEN as usize);
713 header.extend_from_slice(&CHUNK_MAGIC);
714 header.extend_from_slice(&self.kind.to_le_bytes());
715 header.extend_from_slice(&self.end().to_le_bytes());
716 sink.put(&header)?;
717 for (_, data, offset) in &self.sections {
718 sink.pad_to(*offset)?;
719 sink.put_data(data)?;
720 }
721 sink.pad_to(self.name_offset)?;
722 let data_crc = std::mem::replace(&mut sink.crc, crc32fast::Hasher::new()).finalize();
723 sink.put(&self.name)?;
724 sink.pad_to(self.table_offset)?;
725 for (kind, data, offset) in &self.sections {
726 sink.put(§ion_entry(*kind, data, *offset, None))?;
727 }
728 let mut trailer = Vec::with_capacity(CHUNK_TRAILER_LEN as usize);
729 trailer.extend_from_slice(&self.kind.to_le_bytes());
730 trailer.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
731 trailer.extend_from_slice(&self.start.to_le_bytes());
732 trailer.extend_from_slice(&self.name_offset.to_le_bytes());
733 trailer.extend_from_slice(&(self.name.len() as u64).to_le_bytes());
734 trailer.extend_from_slice(&data_crc.to_le_bytes());
735 sink.crc.update(&trailer);
736 let meta_crc = sink.crc.clone().finalize();
737 trailer.extend_from_slice(&meta_crc.to_le_bytes());
738 trailer.extend_from_slice(&CHUNK_END_MAGIC);
739 trailer.extend_from_slice(&[0; 4]);
740 sink.out.write_all(&trailer)?;
741 sink.out.flush()
742 }
743}
744
745fn section_entry(kind: u32, data: &Data<'_>, offset: u64, crc: Option<u32>) -> Vec<u8> {
748 let mut entry = Vec::with_capacity(SECTION_ENTRY_LEN as usize);
749 entry.extend_from_slice(&kind.to_le_bytes());
750 entry.extend_from_slice(&(data.width() as u32).to_le_bytes());
751 entry.extend_from_slice(&offset.to_le_bytes());
752 entry.extend_from_slice(&data.count().to_le_bytes());
753 if let Some(crc) = crc {
754 entry.extend_from_slice(&crc.to_le_bytes());
755 entry.extend_from_slice(&[0; 4]);
756 }
757 entry
758}
759
760fn data_crc(data: &Data<'_>) -> u32 {
762 fn bytes_of<T: Copy>(values: &[T]) -> &[u8] {
764 unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), size_of_val(values)) }
767 }
768 if cfg!(target_endian = "little") {
771 let bytes = match data {
772 Data::U64(v) => Some(bytes_of(v)),
773 Data::F64(v) => Some(bytes_of(v)),
774 Data::U32(v) => Some(bytes_of(v)),
775 Data::Ints(a) => Some(bytes_of(a.values())),
776 Data::StrBytes(a) => Some(str_bytes(a)),
777 Data::Bytes(b) => Some(b.as_slice()),
778 Data::IdTable(t) => Some(bytes_of(t.slots())),
779 Data::EdgeIds(ids, built) => Some(bytes_of(ids_of(ids, built))),
780 Data::StrOffsets(_) => None,
781 };
782 if let Some(bytes) = bytes {
783 return super::mapped::crc(bytes);
784 }
785 }
786 let mut sink = Sink {
787 out: io::sink(),
788 crc: crc32fast::Hasher::new(),
789 at: 0,
790 hash: true,
791 };
792 sink.put_data(data)
793 .expect("writing to io::sink does not fail");
794 sink.crc.finalize()
795}
796
797struct Sink<W> {
799 out: W,
800 crc: crc32fast::Hasher,
801 at: u64,
802 hash: bool,
803}
804
805impl<W: Write> Sink<W> {
806 fn put(&mut self, bytes: &[u8]) -> io::Result<()> {
807 if self.hash {
808 self.crc.update(bytes);
809 }
810 self.at += bytes.len() as u64;
811 self.out.write_all(bytes)
812 }
813
814 fn pad_to(&mut self, offset: u64) -> io::Result<()> {
815 debug_assert!(offset >= self.at);
816 let zeros = [0u8; SECTION_ALIGN as usize];
817 while self.at < offset {
818 let n = ((offset - self.at) as usize).min(zeros.len());
819 self.put(&zeros[..n])?;
820 }
821 Ok(())
822 }
823
824 fn put_data(&mut self, data: &Data<'_>) -> io::Result<()> {
826 match data {
827 Data::U64(v) => self.put_all(v, |x| x.to_le_bytes()),
828 Data::F64(v) => self.put_all(v, |x| x.to_le_bytes()),
829 Data::U32(v) => self.put_all(v, |x| x.to_le_bytes()),
830 Data::Ints(a) => self.put_all(a.values(), |x| x.to_le_bytes()),
831 Data::StrOffsets(a) => {
832 let offsets = a.value_offsets();
833 let base = offsets[0];
834 self.put_all(offsets, |x| (x - base).to_le_bytes())
835 }
836 Data::StrBytes(a) => self.put(str_bytes(a)),
837 Data::Bytes(b) => self.put(b.as_slice()),
838 Data::IdTable(t) => self.put_all(t.slots(), |x| x.to_le_bytes()),
839 Data::EdgeIds(ids, built) => self.put_all(ids_of(ids, built), |x| x.to_le_bytes()),
840 }
841 }
842
843 fn put_all<T: Copy, const N: usize>(
845 &mut self,
846 values: &[T],
847 le: impl Fn(T) -> [u8; N],
848 ) -> io::Result<()> {
849 let mut block = Vec::with_capacity(64 * 1024);
850 for chunk in values.chunks(64 * 1024 / N) {
851 block.clear();
852 for &v in chunk {
853 block.extend_from_slice(&le(v));
854 }
855 self.put(&block)?;
856 }
857 Ok(())
858 }
859}
860
861pub type DecodeError = String;
863
864#[derive(Debug, Clone, Default)]
867pub struct Dropped {
868 pub n_dropped: u64,
869 pub kept: Option<BooleanBuffer>,
870}
871
872pub struct Stored {
874 pub topology: Topology,
876 pub ids: IdMap,
877 pub dropped: Dropped,
879 pub main: MainPart,
880 pub chunks: Vec<ChunkInfo>,
882 pub version: u32,
885 pub unverified: Option<Arc<Unverified>>,
888}
889
890pub fn has_chunk(chunks: &[ChunkInfo], kind: u32, name: &[u8]) -> bool {
892 chunks.iter().any(|c| c.kind == kind && c.name == name)
893}
894
895static INCOMING_READS: AtomicU64 = AtomicU64::new(0);
897
898pub fn incoming_reads() -> u64 {
901 INCOMING_READS.load(Ordering::Relaxed)
902}
903
904thread_local! {
905 static THREAD_INCOMING_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
910}
911
912fn count_incoming_read() {
914 INCOMING_READS.fetch_add(1, Ordering::Relaxed);
915 THREAD_INCOMING_READS.with(|n| n.set(n.get() + 1));
916}
917
918pub fn thread_incoming_reads() -> u64 {
920 THREAD_INCOMING_READS.with(std::cell::Cell::get)
921}
922
923pub fn read_file(path: &Path, key: &IndexKey) -> Result<Stored, DecodeError> {
938 let mut file = File::open(path).map_err(|e| e.to_string())?;
939 let len = file.metadata().map_err(|e| e.to_string())?.len();
940 let head = read_head(&mut file, len, key)?;
941 let (chunks, end) = list_chunks(&mut file, head.main_len, len);
942 let mapped = head.version != VERSION_2 && super::mapped::MAPS;
943 let data = match mapped {
944 true => super::mapped::map(&file, end)?,
945 false => super::mapped::read_whole(&file, head.main_len)?,
946 };
947 let (topology, ids, main, dropped, deferred) = parse(&head, &data, mapped)?;
948 let unverified = mapped.then(|| Arc::new(Unverified::new(data.clone(), deferred)));
949 let topology = match (
950 chunks.iter().find(|c| c.kind == CHUNK_INCOMING),
951 &unverified,
952 ) {
953 (Some(chunk), Some(checks)) => {
954 let (chunk, checks) = (chunk.clone(), Arc::clone(checks));
957 let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
958 topology.with_checksummed_incoming_loader(Box::new(move || {
959 let incoming = mapped_incoming(&data, &chunk, n_nodes, n_edges).ok()?;
960 checks
961 .defer(Region {
962 what: "in-adjacency",
963 range: usize::try_from(chunk.start).ok()?
964 ..usize::try_from(chunk.data_end).ok()?,
965 crc: chunk.data_crc,
966 })
967 .ok()?;
968 count_incoming_read();
969 Some(incoming)
970 }))
971 }
972 (Some(chunk), None) => {
973 let (path, chunk) = (path.to_path_buf(), chunk.clone());
974 let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
975 topology.with_incoming_loader(Box::new(move || {
976 let incoming = read_incoming(&path, main, &chunk, n_nodes, n_edges).ok()?;
977 count_incoming_read();
978 Some(incoming)
979 }))
980 }
981 (None, _) => topology,
982 };
983 Ok(Stored {
984 topology,
985 ids,
986 dropped,
987 main,
988 chunks,
989 version: head.version,
990 unverified,
991 })
992}
993
994pub fn decode(bytes: &[u8], key: &IndexKey) -> Result<(Topology, IdMap), DecodeError> {
997 decode_main(bytes, key).map(|(topology, ids, _, _)| (topology, ids))
998}
999
1000fn decode_main(
1002 bytes: &[u8],
1003 key: &IndexKey,
1004) -> Result<(Topology, IdMap, MainPart, Dropped), DecodeError> {
1005 let head = read_head(&mut io::Cursor::new(bytes), bytes.len() as u64, key)?;
1006 let main = &bytes[..head.main_len as usize];
1008 let mut words = vec![0u64; main.len().div_ceil(8)];
1009 for (word, chunk) in words.iter_mut().zip(main.chunks(8)) {
1010 let mut le = [0u8; 8];
1011 le[..chunk.len()].copy_from_slice(chunk);
1012 *word = u64::from_ne_bytes(le);
1013 }
1014 let data = Buffer::from_vec(words).slice_with_length(0, main.len());
1015 parse(&head, &data, false)
1016 .map(|(topology, ids, main, dropped, _)| (topology, ids, main, dropped))
1017}
1018
1019#[derive(Debug, Clone, PartialEq, Eq)]
1021pub struct ChunkInfo {
1022 pub kind: u32,
1023 pub name: Vec<u8>,
1024 pub start: u64,
1025 pub end: u64,
1026 data_end: u64,
1028 data_crc: u32,
1029 sections: Vec<(u32, u64, u64, u64)>,
1031}
1032
1033pub fn list_chunks<R: Read + Seek>(file: &mut R, main_len: u64, len: u64) -> (Vec<ChunkInfo>, u64) {
1038 let mut chunks = Vec::new();
1039 let mut at = main_len;
1040 while let Some(chunk) = chunk_at(file, at, len) {
1041 at = chunk.end;
1042 chunks.push(chunk);
1043 }
1044 (chunks, at)
1045}
1046
1047fn u32_at(bytes: &[u8], at: usize) -> u32 {
1048 u32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes"))
1049}
1050
1051fn chunk_at<R: Read + Seek>(file: &mut R, start: u64, len: u64) -> Option<ChunkInfo> {
1054 let read = |file: &mut R, at: u64, n: u64| -> Option<Vec<u8>> {
1055 file.seek(SeekFrom::Start(at)).ok()?;
1056 let mut buf = vec![0; usize::try_from(n).ok()?];
1057 file.read_exact(&mut buf).ok()?;
1058 Some(buf)
1059 };
1060 if len.saturating_sub(start) < CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN {
1061 return None;
1062 }
1063 let header = read(file, start, CHUNK_HEADER_LEN)?;
1064 let end = u64_at(&header, 8);
1065 if header[..4] != CHUNK_MAGIC || end > len || end < start + CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN
1066 {
1067 return None;
1068 }
1069 let kind = u32_at(&header, 4);
1070 let trailer_offset = end - CHUNK_TRAILER_LEN;
1071 let trailer = read(file, trailer_offset, CHUNK_TRAILER_LEN)?;
1072 let n_sections = u32_at(&trailer, 4) as u64;
1073 let name_offset = u64_at(&trailer, 16);
1074 let name_len = u64_at(&trailer, 24);
1075 let table_offset = align(name_offset.checked_add(name_len)?, 8);
1076 if trailer[40..44] != CHUNK_END_MAGIC
1077 || u32_at(&trailer, 0) != kind
1078 || u64_at(&trailer, 8) != start
1079 || name_offset < start + CHUNK_HEADER_LEN
1080 || n_sections
1081 .checked_mul(CHUNK_ENTRY_LEN)?
1082 .checked_add(table_offset)?
1083 != trailer_offset
1084 {
1085 return None;
1086 }
1087 let meta = read(file, name_offset, trailer_offset - name_offset)?;
1088 let mut crc = crc32fast::Hasher::new();
1089 crc.update(&meta);
1090 crc.update(&trailer[..36]);
1091 if crc.finalize() != u32_at(&trailer, 36) {
1092 return None;
1093 }
1094 let name = meta[..name_len as usize].to_vec();
1095 let table = &meta[(table_offset - name_offset) as usize..];
1096 let mut sections = Vec::new();
1097 for entry in table.chunks_exact(CHUNK_ENTRY_LEN as usize) {
1098 let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
1099 let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
1100 width
1101 .checked_mul(count)
1102 .and_then(|n| n.checked_add(offset))
1103 .filter(|&e| offset >= start + CHUNK_HEADER_LEN && e <= name_offset)?;
1104 sections.push((kind, width, offset, count));
1105 }
1106 sections.sort_by_key(|&(_, _, offset, _)| offset);
1107 if sections
1108 .windows(2)
1109 .any(|w| w[0].2 + w[0].1 * w[0].3 > w[1].2)
1110 {
1111 return None;
1112 }
1113 Some(ChunkInfo {
1114 kind,
1115 name,
1116 start,
1117 end,
1118 data_end: name_offset,
1119 data_crc: u32_at(&trailer, 32),
1120 sections,
1121 })
1122}
1123
1124fn check_main(file: &mut File, main: MainPart) -> Result<(), DecodeError> {
1126 let len = file.metadata().map_err(|e| e.to_string())?.len();
1127 if len < main.len || main.len < HEADER_LEN + TRAILER_LEN {
1128 return Err("the file's main part has changed".into());
1129 }
1130 let mut trailer = [0u8; TRAILER_LEN as usize];
1131 file.seek(SeekFrom::Start(main.len - TRAILER_LEN))
1132 .and_then(|_| file.read_exact(&mut trailer))
1133 .map_err(|e| e.to_string())?;
1134 if u64_at(&trailer, 0) != main.len || u32_at(&trailer, 8) != main.crc {
1135 return Err("the file's main part has changed".into());
1136 }
1137 Ok(())
1138}
1139
1140pub fn read_chunk(
1143 path: &Path,
1144 main: MainPart,
1145 chunk: &ChunkInfo,
1146) -> Result<Vec<(u32, Section)>, DecodeError> {
1147 let mut file = File::open(path).map_err(|e| e.to_string())?;
1148 check_main(&mut file, main)?;
1149 if file.metadata().map_err(|e| e.to_string())?.len() < chunk.end {
1150 return Err("the file is shorter than the chunk".into());
1151 }
1152 file.seek(SeekFrom::Start(chunk.start))
1153 .map_err(|e| e.to_string())?;
1154 let mut src = Source {
1155 inner: BufReader::with_capacity(BLOCK, file),
1156 crc: crc32fast::Hasher::new(),
1157 at: chunk.start,
1158 };
1159 let mut sections = Vec::with_capacity(chunk.sections.len());
1160 for &(kind, width, offset, count) in &chunk.sections {
1161 src.skip_to(offset)?;
1162 sections.push((kind, src.section(kind, width, offset, count)?));
1163 }
1164 src.skip_to(chunk.data_end)?;
1165 if src.crc.finalize() != chunk.data_crc {
1166 return Err("the chunk's checksum does not match".into());
1167 }
1168 Ok(sections)
1169}
1170
1171fn read_incoming(
1174 path: &Path,
1175 main: MainPart,
1176 chunk: &ChunkInfo,
1177 n_nodes: usize,
1178 n_edges: usize,
1179) -> Result<Adjacency, DecodeError> {
1180 let mut sections = read_chunk(path, main, chunk)?;
1181 let mut take = |kind: u32| {
1182 let i = sections
1183 .iter()
1184 .position(|(k, _)| *k == kind)
1185 .ok_or_else(|| format!("section {kind} is missing"))?;
1186 Ok::<_, DecodeError>(sections.swap_remove(i).1)
1187 };
1188 match (take(IN_OFFSETS)?, take(IN_TARGETS)?, take(IN_EDGE_IDS)?) {
1189 (Section::U64(offsets), Section::U32(targets), Section::U32(edge_ids))
1190 if offsets.len() == n_nodes + 1
1191 && targets.len() == n_edges
1192 && edge_ids.len() == n_edges =>
1193 {
1194 Ok(Adjacency {
1195 offsets: offsets.into(),
1196 targets: targets.into(),
1197 edge_ids: edge_ids.into(),
1198 })
1199 }
1200 _ => Err("the in-adjacency is malformed".into()),
1201 }
1202}
1203
1204pub fn read_weights(
1207 path: &Path,
1208 main: MainPart,
1209 chunk: &ChunkInfo,
1210 n_edges: usize,
1211) -> Result<Vec<Vec<f64>>, DecodeError> {
1212 read_chunk(path, main, chunk)?
1213 .into_iter()
1214 .map(|(_, section)| match section {
1215 Section::F64(values) if values.len() == n_edges => Ok(values),
1216 _ => Err("the weights are malformed".to_string()),
1217 })
1218 .collect()
1219}
1220
1221pub fn append_chunk<'a>(
1227 path: &Path,
1228 main: MainPart,
1229 kind: u32,
1230 name: &[u8],
1231 encode: impl FnOnce(u64) -> EncodedChunk<'a>,
1232) -> io::Result<Option<u64>> {
1233 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
1234 check_main(&mut file, main).map_err(io::Error::other)?;
1235 let len = file.metadata()?.len();
1236 let (chunks, at) = list_chunks(&mut file, main.len, len);
1237 if has_chunk(&chunks, kind, name) {
1238 return Ok(None);
1239 }
1240 let chunk = encode(at);
1241 debug_assert_eq!((chunk.kind, chunk.name.as_slice()), (kind, name));
1242 if len > at {
1245 file.set_len(at)?;
1246 }
1247 file.seek(SeekFrom::Start(at))?;
1248 let mut out = BufWriter::with_capacity(1 << 20, &file);
1249 chunk.write_to(&mut out)?;
1250 out.into_inner().map_err(|e| e.into_error())?;
1251 file.sync_all()?;
1252 Ok(Some(chunk.end()))
1253}
1254
1255const BLOCK: usize = 1 << 20;
1257
1258struct Source<R> {
1260 inner: R,
1261 crc: crc32fast::Hasher,
1262 at: u64,
1263}
1264
1265impl<R: Read> Source<R> {
1266 fn fill(&mut self, buf: &mut [u8]) -> Result<(), DecodeError> {
1267 self.inner.read_exact(buf).map_err(|e| match e.kind() {
1268 io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1269 _ => e.to_string(),
1270 })?;
1271 self.crc.update(buf);
1272 self.at += buf.len() as u64;
1273 Ok(())
1274 }
1275
1276 fn bytes(&mut self, n: usize) -> Result<Vec<u8>, DecodeError> {
1277 let mut buf = vec![0; n];
1278 self.fill(&mut buf)?;
1279 Ok(buf)
1280 }
1281
1282 fn skip_to(&mut self, offset: u64) -> Result<(), DecodeError> {
1285 let mut buf = vec![0; BLOCK.min(offset.saturating_sub(self.at) as usize)];
1286 while self.at < offset {
1287 let n = ((offset - self.at) as usize).min(buf.len());
1288 self.fill(&mut buf[..n])?;
1289 }
1290 Ok(())
1291 }
1292
1293 fn values<T, const N: usize>(
1295 &mut self,
1296 count: usize,
1297 le: fn([u8; N]) -> T,
1298 ) -> Result<Vec<T>, DecodeError> {
1299 let mut out = Vec::with_capacity(count);
1300 let mut buf = vec![0; BLOCK.min(count * N)];
1301 while out.len() < count {
1302 let n = ((count - out.len()) * N).min(buf.len());
1303 self.fill(&mut buf[..n])?;
1304 out.extend(read(&buf[..n], le));
1305 }
1306 Ok(out)
1307 }
1308}
1309
1310impl<R: Read> Source<R> {
1311 fn section(
1315 &mut self,
1316 kind: u32,
1317 width: u64,
1318 offset: u64,
1319 count: u64,
1320 ) -> Result<Section, DecodeError> {
1321 let n = usize::try_from(count).map_err(|e| e.to_string())?;
1322 Ok(match (kind, width) {
1323 (OUT_OFFSETS | IN_OFFSETS, 8) => Section::U64(self.values(n, u64::from_le_bytes)?),
1324 (OUT_TARGETS | OUT_EDGE_IDS | IN_TARGETS | IN_EDGE_IDS, 4) => {
1325 Section::U32(self.values(n, u32::from_le_bytes)?)
1326 }
1327 (IDS_INT64, 8) => Section::I64(self.values(n, i64::from_le_bytes)?),
1328 (WEIGHTS_F64, 8) => Section::F64(self.values(n, f64::from_le_bytes)?),
1329 (IDS_STR_OFFSETS, 4) => Section::I32(self.values(n, i32::from_le_bytes)?),
1330 (IDS_STR_BYTES | KEPT_ROWS, 1) => Section::Bytes(self.bytes(n)?),
1331 _ => {
1332 self.skip_to(offset + width * count)?;
1333 Section::Bytes(Vec::new())
1334 }
1335 })
1336 }
1337}
1338
1339pub enum Section {
1341 U64(Vec<u64>),
1342 F64(Vec<f64>),
1343 U32(Vec<u32>),
1344 I64(Vec<i64>),
1345 I32(Vec<i32>),
1346 Bytes(Vec<u8>),
1347}
1348
1349#[derive(Debug, Clone, Copy)]
1351struct Entry {
1352 kind: u32,
1353 width: u64,
1354 offset: u64,
1355 count: u64,
1356 crc: u32,
1358}
1359
1360impl Entry {
1361 fn range(&self) -> Range<usize> {
1362 self.offset as usize..(self.offset + self.width * self.count) as usize
1364 }
1365}
1366
1367struct Head {
1369 version: u32,
1370 flags: u32,
1371 n_nodes: usize,
1372 n_edges: usize,
1373 n_dropped: u64,
1374 main_len: u64,
1375 table_end: u64,
1377 sections: Vec<Entry>,
1379 crc: u32,
1381}
1382
1383fn read_head<R: Read + Seek>(file: &mut R, len: u64, key: &IndexKey) -> Result<Head, DecodeError> {
1388 let read = |file: &mut R, at: u64, n: u64| -> Result<Vec<u8>, DecodeError> {
1389 file.seek(SeekFrom::Start(at)).map_err(|e| e.to_string())?;
1390 let mut buf = vec![0; usize::try_from(n).map_err(|e| e.to_string())?];
1391 file.read_exact(&mut buf).map_err(|e| match e.kind() {
1392 io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1393 _ => e.to_string(),
1394 })?;
1395 Ok(buf)
1396 };
1397 if len < HEADER_LEN + TRAILER_LEN {
1398 return Err(format!("{len} bytes is too short for an index file"));
1399 }
1400 let header = read(file, 0, HEADER_LEN)?;
1401 if header[..8] != MAGIC {
1402 return Err("not an Ursa index file".into());
1403 }
1404 let version = u32_at(&header, 8);
1405 if ![VERSION, VERSION_4, VERSION_3, VERSION_2].contains(&version) {
1406 return Err(format!(
1407 "index format version {version}; this build reads {VERSION_2} to {VERSION}"
1408 ));
1409 }
1410 let flags = u32_at(&header, 12);
1411 let n_nodes = usize::try_from(u64_at(&header, 16)).map_err(|e| e.to_string())?;
1412 let n_edges = usize::try_from(u64_at(&header, 24)).map_err(|e| e.to_string())?;
1413 let key_len = u64_at(&header, 32);
1414 let n_sections = u32_at(&header, 40) as u64;
1415 let main_len = u64_at(&header, 48);
1416 let n_dropped = u64_at(&header, 56);
1417 if main_len > len || main_len < HEADER_LEN + TRAILER_LEN || usize::try_from(main_len).is_err() {
1418 return Err("the file is truncated".into());
1419 }
1420 let body = main_len - TRAILER_LEN;
1421 let key_end = HEADER_LEN
1422 .checked_add(key_len)
1423 .filter(|&end| end <= body)
1424 .ok_or("the key runs past the end of the file")?;
1425 let table = align(key_end, 8);
1426 let entry_len = match version {
1427 VERSION_2 => CHUNK_ENTRY_LEN,
1428 _ => SECTION_ENTRY_LEN,
1429 };
1430 let table_end = n_sections
1431 .checked_mul(entry_len)
1432 .and_then(|n| n.checked_add(table))
1433 .filter(|&end| end <= body)
1434 .ok_or("the section table runs past the end of the file")?;
1435 let rest = read(file, HEADER_LEN, table_end - HEADER_LEN)?;
1436 let trailer = read(file, body, TRAILER_LEN)?;
1437 if trailer[12..] != END_MAGIC || u64_at(&trailer, 0) != main_len {
1438 return Err("the file is truncated".into());
1439 }
1440 let crc = u32_at(&trailer, 8);
1441 if version != VERSION_2 {
1442 let mut meta = crc32fast::Hasher::new();
1443 meta.update(&header);
1444 meta.update(&rest);
1445 if meta.finalize() != crc {
1446 return Err("the checksum does not match".into());
1447 }
1448 if rest[(key_end - HEADER_LEN) as usize..(table - HEADER_LEN) as usize]
1449 .iter()
1450 .any(|&b| b != 0)
1451 {
1452 return Err("the padding is not zero".into());
1453 }
1454 }
1455 let stored: Value = serde_json::from_slice(&rest[..key_len as usize])
1456 .map_err(|e| format!("the key is not JSON: {e}"))?;
1457 if IndexKey::from_json(&stored).as_ref() != Some(key) {
1458 return Err("the file holds an index for another key".into());
1459 }
1460
1461 let entries = &rest[(table - HEADER_LEN) as usize..];
1462 let mut sections = Vec::with_capacity(n_sections as usize);
1463 for entry in entries.chunks_exact(entry_len as usize) {
1464 let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
1465 let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
1466 let crc = match version {
1467 VERSION_2 => 0,
1468 _ => u32_at(entry, 24),
1469 };
1470 width
1471 .checked_mul(count)
1472 .and_then(|n| n.checked_add(offset))
1473 .filter(|&end| offset >= table_end && end <= body)
1474 .ok_or("a section runs past the end of the file")?;
1475 sections.push(Entry {
1476 kind,
1477 width,
1478 offset,
1479 count,
1480 crc,
1481 });
1482 }
1483 sections.sort_by_key(|e| e.offset);
1484 if sections
1485 .windows(2)
1486 .any(|w| w[0].offset + w[0].width * w[0].count > w[1].offset)
1487 {
1488 return Err("the sections overlap".into());
1489 }
1490 Ok(Head {
1491 version,
1492 flags,
1493 n_nodes,
1494 n_edges,
1495 n_dropped,
1496 main_len,
1497 table_end,
1498 sections,
1499 crc,
1500 })
1501}
1502
1503fn deferred_kind(kind: u32) -> Option<&'static str> {
1506 match kind {
1507 OUT_TARGETS => Some("targets"),
1508 OUT_EDGE_IDS => Some("edge ids"),
1509 _ => None,
1510 }
1511}
1512
1513fn scalars<T: ArrowNativeType>(data: &Buffer, entry: &Entry) -> ScalarBuffer<T> {
1515 let size = std::mem::size_of::<T>();
1516 debug_assert_eq!(entry.width as usize, size);
1517 ScalarBuffer::new(
1520 data.clone(),
1521 entry.offset as usize / size,
1522 entry.count as usize,
1523 )
1524}
1525
1526type Parsed = (Topology, IdMap, MainPart, Dropped, Vec<Region>);
1528
1529fn parse(head: &Head, data: &Buffer, mapped: bool) -> Result<Parsed, DecodeError> {
1533 let main_len = head.main_len as usize;
1534 if data.len() < main_len {
1535 return Err("the file is truncated".into());
1536 }
1537 let bytes = &data.as_slice()[..main_len];
1538 let body = main_len - TRAILER_LEN as usize;
1539 let mut deferred = Vec::new();
1540 if head.version == VERSION_2 {
1541 if super::mapped::crc(&bytes[..body]) != head.crc {
1542 return Err("the checksum does not match".into());
1543 }
1544 } else {
1545 let mut at = head.table_end as usize;
1547 for entry in &head.sections {
1548 let range = entry.range();
1549 if bytes[at..range.start].iter().any(|&b| b != 0) {
1550 return Err("the padding is not zero".into());
1551 }
1552 at = range.end;
1553 match deferred_kind(entry.kind).filter(|_| mapped) {
1554 Some(what) => deferred.push(Region {
1555 what,
1556 range,
1557 crc: entry.crc,
1558 }),
1559 None => {
1560 if super::mapped::crc(&bytes[range]) != entry.crc {
1561 return Err(format!(
1562 "the checksum of section {} does not match",
1563 entry.kind
1564 ));
1565 }
1566 }
1567 }
1568 }
1569 if bytes[at..body].iter().any(|&b| b != 0) {
1570 return Err("the padding is not zero".into());
1571 }
1572 }
1573
1574 let (n_nodes, n_edges) = (head.n_nodes, head.n_edges);
1575 let take = |kind: u32, width: u64, count: Option<usize>| -> Result<Entry, DecodeError> {
1576 let mut found = head.sections.iter().filter(|e| e.kind == kind);
1577 let entry = found
1578 .next()
1579 .ok_or_else(|| format!("section {kind} is missing"))?;
1580 if found.next().is_some() || entry.width != width {
1581 return Err(format!("section {kind} is malformed"));
1582 }
1583 if count.is_some_and(|count| entry.count != count as u64) {
1584 return Err(format!("section {kind} has the wrong length"));
1585 }
1586 Ok(*entry)
1587 };
1588 let out = Adjacency {
1589 offsets: scalars(data, &take(OUT_OFFSETS, 8, Some(n_nodes + 1))?),
1590 targets: scalars(data, &take(OUT_TARGETS, 4, Some(n_edges))?),
1591 edge_ids: scalars(data, &take(OUT_EDGE_IDS, 4, Some(n_edges))?).into(),
1592 };
1593 let topology = match head.version {
1594 VERSION_2 => Topology::from_parts(n_nodes, out, None)?,
1596 _ => Topology::from_checksummed_parts(n_nodes, out)?,
1597 };
1598 let topology = match head.sections.iter().any(|e| e.kind == ORIGINAL_IDS) {
1601 true if head.version == VERSION => {
1602 let original = scalars::<u32>(data, &take(ORIGINAL_IDS, 4, Some(n_nodes))?);
1603 topology.with_original_ids(original)?
1604 }
1605 true => return Err(format!("section {ORIGINAL_IDS} is not in this version")),
1606 false => topology,
1607 };
1608
1609 let ids: Arc<dyn Array> = if head.flags & FLAG_STRING_IDS == 0 {
1610 let values = scalars::<i64>(data, &take(IDS_INT64, 8, Some(n_nodes))?);
1611 Arc::new(Int64Array::new(values, None))
1612 } else {
1613 let offsets = scalars::<i32>(data, &take(IDS_STR_OFFSETS, 4, Some(n_nodes + 1))?);
1614 let strings = take(IDS_STR_BYTES, 1, None)?;
1615 if offsets[0] != 0
1616 || offsets.windows(2).any(|w| w[0] > w[1])
1617 || offsets[n_nodes] as u64 != strings.count
1618 {
1619 return Err("the string ids' offsets are malformed".into());
1620 }
1621 let values = data.slice_with_length(strings.offset as usize, strings.count as usize);
1622 if !super::mapped::are_strings(&values, &offsets) {
1623 return Err("the string ids are malformed: they are not UTF-8".into());
1624 }
1625 Arc::new(unsafe { StringArray::new_unchecked(OffsetBuffer::new(offsets), values, None) })
1629 };
1630 let table = match head.version {
1633 VERSION | VERSION_4 => {
1634 let slots = usize::try_from(lookup_table_len(n_nodes)).map_err(|e| e.to_string())?;
1635 Some(scalars::<u32>(data, &take(ID_TABLE, 4, Some(slots))?))
1636 }
1637 _ => None,
1638 };
1639 let ids = IdMap::from_stored_ids(ids, table).map_err(|e| e.to_string())?;
1640 if ids.len() != n_nodes {
1641 return Err("the id map does not match the topology".into());
1642 }
1643 let dropped = match head.n_dropped {
1644 0 => Dropped::default(),
1645 n_dropped => {
1646 let rows = usize::try_from(n_dropped)
1647 .ok()
1648 .and_then(|d| d.checked_add(n_edges))
1649 .ok_or("the kept rows are malformed")?;
1650 let bits = take(KEPT_ROWS, 1, Some(rows.div_ceil(8)))?;
1651 let bits = data.slice_with_length(bits.offset as usize, bits.count as usize);
1652 let kept = BooleanBuffer::new(bits, 0, rows);
1653 if kept.count_set_bits() != n_edges {
1654 return Err("the kept rows do not match the edges".into());
1655 }
1656 Dropped {
1657 n_dropped,
1658 kept: Some(kept),
1659 }
1660 }
1661 };
1662 let main = MainPart {
1663 len: head.main_len,
1664 crc: head.crc,
1665 };
1666 Ok((topology, ids, main, dropped, deferred))
1667}
1668
1669fn mapped_incoming(
1673 data: &Buffer,
1674 chunk: &ChunkInfo,
1675 n_nodes: usize,
1676 n_edges: usize,
1677) -> Result<Adjacency, DecodeError> {
1678 if (data.len() as u64) < chunk.end {
1679 return Err("the file is shorter than the chunk".into());
1680 }
1681 let entry = |kind: u32, width: u64, count: usize| -> Result<Entry, DecodeError> {
1682 let mut found = chunk.sections.iter().filter(|s| s.0 == kind);
1683 match (found.next(), found.next()) {
1684 (Some(&(kind, w, offset, c)), None) if w == width && c == count as u64 => Ok(Entry {
1685 kind,
1686 width,
1687 offset,
1688 count: c,
1689 crc: 0,
1690 }),
1691 _ => Err("the in-adjacency is malformed".into()),
1692 }
1693 };
1694 Ok(Adjacency {
1695 offsets: scalars(data, &entry(IN_OFFSETS, 8, n_nodes + 1)?),
1696 targets: scalars(data, &entry(IN_TARGETS, 4, n_edges)?),
1697 edge_ids: scalars(data, &entry(IN_EDGE_IDS, 4, n_edges)?).into(),
1698 })
1699}
1700
1701fn u64_at(bytes: &[u8], at: usize) -> u64 {
1702 u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"))
1703}
1704
1705fn read<T, const N: usize>(
1707 bytes: &[u8],
1708 le: fn([u8; N]) -> T,
1709) -> impl Iterator<Item = T> + use<'_, T, N> {
1710 bytes
1711 .chunks_exact(N)
1712 .map(move |c| le(c.try_into().expect("N bytes")))
1713}
1714
1715#[cfg(test)]
1716mod tests {
1717 use super::*;
1718 use datafusion::arrow::array::ArrayRef;
1719 use datafusion::arrow::datatypes::DataType;
1720
1721 fn key() -> IndexKey {
1722 IndexKey::new(
1723 "Projection: src, dst\n TableScan: ties".into(),
1724 vec![FileIdentity {
1725 store: "file:///".into(),
1726 location: "data/edges.parquet".into(),
1727 size: 1234,
1728 modified: 1_700_000_000_000_000_000,
1729 e_tag: Some("\"abc\"".into()),
1730 }],
1731 )
1732 }
1733
1734 fn built(src: ArrayRef, dst: ArrayRef) -> (Arc<Topology>, Arc<IdMap>) {
1735 ursa_io::build_topology_batches(&[(src.as_ref(), dst.as_ref())]).unwrap()
1736 }
1737
1738 fn encode(key: &IndexKey, topology: &Topology, ids: &IdMap) -> Vec<u8> {
1739 let encoded = Encoded::new(key, topology, ids).unwrap();
1740 let mut bytes = Vec::new();
1741 encoded.write_to(&mut bytes).unwrap();
1742 assert_eq!(bytes.len() as u64, encoded.file_size());
1743 bytes
1744 }
1745
1746 fn same(a: &Topology, b: &Topology) {
1747 assert_eq!(a.n_nodes(), b.n_nodes());
1748 assert_eq!(a.out().offsets, b.out().offsets);
1749 assert_eq!(a.out().targets, b.out().targets);
1750 assert_eq!(a.out().edge_ids, b.out().edge_ids);
1751 }
1752
1753 #[test]
1754 fn int_and_string_indexes_round_trip() {
1755 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1756 let (topology, ids) = built(ints(&[10, 20, 10, 30]), ints(&[20, 30, 30, 10]));
1757 let bytes = encode(&key(), &topology, &ids);
1758 assert_eq!(&bytes[..8], b"URSAIDX\0");
1759 let (back, back_ids) = decode(&bytes, &key()).unwrap();
1760 same(&topology, &back);
1761 assert!(back.incoming_if_built().is_none());
1762 assert_eq!(
1763 back_ids.user_id_array().as_ref(),
1764 ids.user_id_array().as_ref()
1765 );
1766
1767 topology.incoming();
1769 assert_eq!(encode(&key(), &topology, &ids), bytes);
1770
1771 let strs = |v: &[&str]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
1772 let (topology, ids) = built(strs(&["a", "bé", "a"]), strs(&["bé", "c", "c"]));
1773 let bytes = encode(&key(), &topology, &ids);
1774 let (back, back_ids) = decode(&bytes, &key()).unwrap();
1775 same(&topology, &back);
1776 assert_eq!(
1777 back_ids.user_id_array().as_ref(),
1778 ids.user_id_array().as_ref()
1779 );
1780
1781 let n_sections = u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize;
1783 let table = align(HEADER_LEN + u64_at(&bytes, 32), 8) as usize;
1784 for i in 0..n_sections {
1785 let entry = table + 32 * i;
1786 let (width, offset) = (
1787 u32_at(&bytes, entry + 4) as usize,
1788 u64_at(&bytes, entry + 8),
1789 );
1790 let count = u64_at(&bytes, entry + 16) as usize;
1791 assert_eq!(offset % 64, 0);
1792 let section = &bytes[offset as usize..offset as usize + width * count];
1793 assert_eq!(u32_at(&bytes, entry + 24), crc32fast::hash(section));
1794 }
1795 }
1796
1797 #[test]
1798 fn the_rows_a_vertex_table_left_out_round_trip() {
1799 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1800 let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
1801 let kept = BooleanBuffer::from(vec![true, false, false, true]);
1803 let encoded = Encoded::with_dropped(&key(), &topology, &ids, 2, Some(&kept)).unwrap();
1804 let mut bytes = Vec::new();
1805 encoded.write_to(&mut bytes).unwrap();
1806 let (back, _, _, dropped) = decode_main(&bytes, &key()).unwrap();
1807 same(&topology, &back);
1808 assert_eq!(dropped.n_dropped, 2);
1809 assert_eq!(dropped.kept, Some(kept));
1810 let plain = encode(&key(), &topology, &ids);
1812 let (_, _, _, none) = decode_main(&plain, &key()).unwrap();
1813 assert_eq!((none.n_dropped, none.kept), (0, None));
1814 }
1815
1816 #[test]
1817 fn an_empty_index_round_trips() {
1818 let (topology, ids) =
1819 ursa_io::topology::empty_topology(&datafusion::arrow::datatypes::DataType::Utf8);
1820 let (back, back_ids) = decode(&encode(&key(), &topology, &ids), &key()).unwrap();
1821 assert_eq!((back.n_nodes(), back.n_edges()), (0, 0));
1822 assert!(back_ids.is_empty());
1823 }
1824
1825 #[test]
1826 fn corruption_truncation_and_another_key_are_errors() {
1827 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1828 let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1829 let bytes = encode(&key(), &topology, &ids);
1830 for cut in [0, 10, 64, bytes.len() / 2, bytes.len() - 1] {
1831 assert!(decode(&bytes[..cut], &key()).is_err(), "cut at {cut}");
1832 }
1833 for at in [9, 70, bytes.len() / 2, bytes.len() - 20] {
1834 let mut flipped = bytes.clone();
1835 flipped[at] ^= 0x40;
1836 assert!(decode(&flipped, &key()).is_err(), "flipped at {at}");
1837 }
1838 let mut other = key();
1839 other.files[0].size += 1;
1840 assert_eq!(
1841 decode(&bytes, &other).unwrap_err(),
1842 "the file holds an index for another key"
1843 );
1844 assert!(decode(
1845 b"not an index at all, just some text..........................................",
1846 &key()
1847 )
1848 .is_err());
1849 }
1850
1851 fn write_main(path: &Path, topology: &Topology, ids: &IdMap) -> MainPart {
1853 let encoded = Encoded::new(&key(), topology, ids).unwrap();
1854 let mut file = File::create(path).unwrap();
1855 encoded.write_to(&mut file).unwrap()
1856 }
1857
1858 #[test]
1859 fn the_in_adjacency_is_appended_and_read_on_first_demand() {
1860 let dir = tempfile::tempdir().unwrap();
1861 let path = dir.path().join("x.idx");
1862 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1863 let (topology, ids) = built(
1864 ints(&[10, 20, 10, 30, 20, 40]),
1865 ints(&[20, 30, 30, 10, 40, 10]),
1866 );
1867 let main = write_main(&path, &topology, &ids);
1868 assert_eq!(main.len, std::fs::metadata(&path).unwrap().len());
1869
1870 let reads = thread_incoming_reads();
1872 let stored = read_file(&path, &key()).unwrap();
1873 assert!(stored.chunks.is_empty());
1874 assert_eq!(
1875 stored.topology.incoming().targets,
1876 topology.incoming().targets
1877 );
1878 assert_eq!(thread_incoming_reads(), reads);
1879
1880 let incoming = topology.incoming().clone();
1882 let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1883 EncodedChunk::incoming(&incoming, at)
1884 })
1885 .unwrap()
1886 .unwrap();
1887 assert_eq!(end, std::fs::metadata(&path).unwrap().len());
1888 let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1889 EncodedChunk::incoming(&incoming, at)
1890 });
1891 assert_eq!(again.unwrap(), None);
1892
1893 let stored = read_file(&path, &key()).unwrap();
1894 assert_eq!(stored.chunks.len(), 1);
1895 assert_eq!(stored.main, main);
1896 same(&topology, &stored.topology);
1897 assert!(stored.topology.incoming_if_built().is_none());
1899 let back = stored.topology.incoming();
1900 assert!(thread_incoming_reads() > reads);
1901 assert_eq!(
1902 (&back.offsets, &back.targets, &back.edge_ids),
1903 (&incoming.offsets, &incoming.targets, &incoming.edge_ids)
1904 );
1905 let bytes = std::fs::read(&path).unwrap();
1907 let (main_only, _) = decode(&bytes, &key()).unwrap();
1908 same(&topology, &main_only);
1909 }
1910
1911 #[test]
1912 fn a_damaged_chunk_is_ignored_and_replaced() {
1913 let dir = tempfile::tempdir().unwrap();
1914 let path = dir.path().join("x.idx");
1915 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1916 let (topology, ids) = built(ints(&[1, 2, 3, 1]), ints(&[2, 3, 1, 3]));
1917 let main = write_main(&path, &topology, &ids);
1918 let incoming = topology.incoming().clone();
1919 let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1920 EncodedChunk::incoming(&incoming, at)
1921 })
1922 .unwrap()
1923 .unwrap();
1924 let good = std::fs::read(&path).unwrap();
1925
1926 let mut bytes = good.clone();
1929 bytes[main.len as usize + 64] ^= 0x01;
1930 std::fs::write(&path, &bytes).unwrap();
1931 let stored = read_file(&path, &key()).unwrap();
1932 assert_eq!(stored.chunks.len(), 1);
1933 assert!(read_chunk(&path, main, &stored.chunks[0]).is_err());
1934 assert_eq!(stored.topology.incoming().targets, incoming.targets);
1935 assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
1936
1937 std::fs::write(&path, &good[..good.len() - 10]).unwrap();
1940 assert!(read_file(&path, &key()).unwrap().chunks.is_empty());
1941 let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1942 EncodedChunk::incoming(&incoming, at)
1943 })
1944 .unwrap();
1945 assert_eq!(again, Some(end));
1946 assert_eq!(std::fs::read(&path).unwrap(), good);
1947
1948 let other = MainPart {
1950 crc: main.crc ^ 1,
1951 ..main
1952 };
1953 assert!(append_chunk(&path, other, CHUNK_INCOMING, b"", |at| {
1954 EncodedChunk::incoming(&incoming, at)
1955 })
1956 .is_err());
1957 let chunk = &read_file(&path, &key()).unwrap().chunks[0];
1958 assert!(read_chunk(&path, other, chunk).is_err());
1959 assert!(read_chunk(&path, main, chunk).is_ok());
1960 }
1961
1962 #[test]
1963 fn weight_chunks_round_trip_by_key() {
1964 let dir = tempfile::tempdir().unwrap();
1965 let path = dir.path().join("x.idx");
1966 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1967 let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1968 let main = write_main(&path, &topology, &ids);
1969 let (a, b) = (vec![0.5, 1.0, f64::MAX], vec![2.0, 0.0, 1e-300]);
1970 for (key, columns) in [("w1", vec![&a[..]]), ("w2", vec![&a[..], &b[..]])] {
1971 let appended = append_chunk(&path, main, CHUNK_WEIGHTS, key.as_bytes(), |at| {
1972 EncodedChunk::weights(key, &columns, at)
1973 });
1974 assert!(appended.unwrap().is_some());
1975 }
1976 let stored = read_file(&path, &key()).unwrap();
1977 assert_eq!(stored.chunks.len(), 2);
1978 let chunk = |name: &[u8]| stored.chunks.iter().find(|c| c.name == name).unwrap();
1979 assert_eq!(
1980 read_weights(&path, main, chunk(b"w1"), 3).unwrap(),
1981 std::slice::from_ref(&a)
1982 );
1983 assert_eq!(read_weights(&path, main, chunk(b"w2"), 3).unwrap(), [a, b]);
1984 assert!(read_weights(&path, main, chunk(b"w1"), 4).is_err());
1986 }
1987
1988 fn section_of(bytes: &[u8], kind: u32) -> (usize, usize) {
1991 let n_sections = u32_at(bytes, 40) as usize;
1992 let table = align(HEADER_LEN + u64_at(bytes, 32), 8) as usize;
1993 (0..n_sections)
1994 .map(|i| table + 32 * i)
1995 .find(|&entry| u32_at(bytes, entry) == kind)
1996 .map(|entry| {
1997 let width = u32_at(bytes, entry + 4) as usize;
1998 let count = u64_at(bytes, entry + 16) as usize;
1999 (u64_at(bytes, entry + 8) as usize, width * count)
2000 })
2001 .unwrap()
2002 }
2003
2004 fn a_graph() -> (Arc<Topology>, Arc<IdMap>) {
2005 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2006 built(
2007 ints(&[10, 20, 10, 30, 20, 40, 40, 50]),
2008 ints(&[20, 30, 30, 10, 40, 10, 50, 10]),
2009 )
2010 }
2011
2012 #[test]
2013 fn a_version_2_file_from_0_10_is_read_whole_and_checked() {
2014 let dir = tempfile::tempdir().unwrap();
2015 let path = dir.path().join("x.idx");
2016 let (topology, ids) = a_graph();
2017 let encoded = Encoded::new(&key(), &topology, &ids)
2018 .unwrap()
2019 .as_version_2();
2020 let mut v2 = Vec::new();
2021 let main = encoded.write_to(&mut v2).unwrap();
2022 assert_eq!(u32_at(&v2, 8), VERSION_2);
2023 assert_eq!(main.crc, crc32fast::hash(&v2[..v2.len() - 16]));
2024 std::fs::write(&path, &v2).unwrap();
2025 let stored = read_file(&path, &key()).unwrap();
2026 assert_eq!(stored.version, VERSION_2);
2027 assert!(stored.unverified.is_none());
2029 assert_eq!(stored.main, main);
2030 same(&topology, &stored.topology);
2031 assert_eq!(
2032 stored.ids.user_id_array().as_ref(),
2033 ids.user_id_array().as_ref()
2034 );
2035 let incoming = topology.incoming().clone();
2037 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2038 EncodedChunk::incoming(&incoming, at)
2039 })
2040 .unwrap()
2041 .unwrap();
2042 let stored = read_file(&path, &key()).unwrap();
2043 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2044
2045 for at in [9, 70, v2.len() / 2, v2.len() - 20] {
2047 let mut flipped = v2.clone();
2048 flipped[at] ^= 0x40;
2049 std::fs::write(&path, &flipped).unwrap();
2050 assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
2051 }
2052 for cut in [0, 10, 64, v2.len() / 2, v2.len() - 1] {
2053 std::fs::write(&path, &v2[..cut]).unwrap();
2054 assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
2055 }
2056 }
2057
2058 fn graphs() -> [(Arc<Topology>, Arc<IdMap>); 2] {
2060 let n = 300i64;
2061 let (src, dst): (Vec<i64>, Vec<i64>) = (0..n)
2062 .map(|i| (i * 7 - 50, ((i * 13) % n) * 7 - 50))
2063 .unzip();
2064 let name = |v: &[i64]| -> ArrayRef {
2065 Arc::new(StringArray::from(
2066 v.iter()
2067 .map(|i| format!("did:plc:{i:024}"))
2068 .collect::<Vec<_>>(),
2069 ))
2070 };
2071 [
2072 built(name(&src), name(&dst)),
2073 built(
2074 Arc::new(Int64Array::from(src)),
2075 Arc::new(Int64Array::from(dst)),
2076 ),
2077 ]
2078 }
2079
2080 fn finds_every_id(stored: &IdMap, ids: &IdMap) {
2083 let column = ids.user_id_array();
2084 assert_eq!(stored.user_id_array().as_ref(), column.as_ref());
2085 let expected: Vec<Option<u32>> = (0..ids.len() as u32).map(Some).collect();
2086 assert_eq!(stored.dense_from_array(column.as_ref()).unwrap(), expected);
2087 let missing: ArrayRef = match column.data_type() {
2088 DataType::Int64 => Arc::new(Int64Array::from(vec![i64::MAX])),
2089 _ => Arc::new(StringArray::from(vec!["nobody"])),
2090 };
2091 assert_eq!(stored.dense_from_array(&missing).unwrap(), vec![None]);
2092 }
2093
2094 #[test]
2097 fn the_id_lookup_table_is_stored_and_used_as_it_lies() {
2098 let dir = tempfile::tempdir().unwrap();
2099 let path = dir.path().join("x.idx");
2100 for (topology, ids) in graphs() {
2101 let bytes = encode(&key(), &topology, &ids);
2102 assert_eq!(u32_at(&bytes, 8), VERSION);
2103 let (at, len) = section_of(&bytes, ID_TABLE);
2104 let table = ids.lookup_table().unwrap();
2105 assert_eq!(len, 4 * table.len());
2106 assert_eq!(len as u64, 4 * lookup_table_len(ids.len()));
2107 let stored_table: Vec<u32> = read(&bytes[at..at + len], u32::from_le_bytes).collect();
2108 assert_eq!(stored_table, table.as_ref());
2109
2110 std::fs::write(&path, &bytes).unwrap();
2111 let stored = read_file(&path, &key()).unwrap();
2112 assert_eq!(stored.version, VERSION);
2113 finds_every_id(&stored.ids, &ids);
2114 let loaded = stored.ids.lookup_table().unwrap();
2117 assert_eq!(loaded, table);
2118 if super::super::mapped::MAPS {
2119 let mapped = stored.unverified.as_ref().unwrap();
2120 assert!(mapped.holds(loaded.inner().as_ptr()));
2121 let column = stored.ids.user_id_array().to_data();
2123 assert!(mapped.holds(column.buffers()[0].as_ptr()));
2124 }
2125 assert_eq!(encode(&key(), &stored.topology, &stored.ids), bytes);
2127 let mut flipped = bytes.clone();
2131 flipped[at + len / 2] ^= 1;
2132 std::fs::write(&path, &flipped).unwrap();
2133 assert!(read_file(&path, &key()).is_err());
2134 }
2135 }
2136
2137 #[test]
2140 fn a_version_3_file_from_0_11_is_read_and_its_lookup_table_built_on_demand() {
2141 let dir = tempfile::tempdir().unwrap();
2142 let path = dir.path().join("x.idx");
2143 for (topology, ids) in graphs() {
2144 let v4 = encode(&key(), &topology, &ids);
2145 let encoded = Encoded::new(&key(), &topology, &ids)
2146 .unwrap()
2147 .as_version_3();
2148 let mut v3 = Vec::new();
2149 let main = encoded.write_to(&mut v3).unwrap();
2150 assert_eq!(v3.len() as u64, encoded.file_size());
2151 assert_eq!(u32_at(&v3, 8), VERSION_3);
2152 assert!(v3.len() < v4.len());
2153 let n_sections = u32_at(&v3, 40) as usize;
2154 let table = align(HEADER_LEN + u64_at(&v3, 32), 8) as usize;
2155 assert!((0..n_sections).all(|i| u32_at(&v3, table + 32 * i) != ID_TABLE));
2156
2157 std::fs::write(&path, &v3).unwrap();
2158 let stored = read_file(&path, &key()).unwrap();
2159 assert_eq!(stored.version, VERSION_3);
2160 assert_eq!(stored.main, main);
2161 assert_eq!(stored.unverified.is_some(), super::super::mapped::MAPS);
2162 same(&topology, &stored.topology);
2163 finds_every_id(&stored.ids, &ids);
2164 assert_eq!(encode(&key(), &stored.topology, &stored.ids), v4);
2166
2167 let incoming = topology.incoming().clone();
2169 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2170 EncodedChunk::incoming(&incoming, at)
2171 })
2172 .unwrap()
2173 .unwrap();
2174 let stored = read_file(&path, &key()).unwrap();
2175 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2176 }
2177 }
2178
2179 #[test]
2183 fn an_id_stored_twice_is_an_error() {
2184 let (topology, _) = a_graph();
2185 let n = topology.n_nodes();
2186 let twice: ArrayRef = Arc::new(Int64Array::from(vec![7i64; n]));
2187 let ids = IdMap::from_stored_ids(Arc::clone(&twice), None).unwrap();
2188 let mut out = Vec::new();
2189 let err = Encoded::new(&key(), &topology, &ids)
2190 .unwrap()
2191 .write_to(&mut out)
2192 .unwrap_err();
2193 assert!(err.to_string().contains("twice"), "{err}");
2194 let mut v3 = Vec::new();
2195 Encoded::new(&key(), &topology, &ids)
2196 .unwrap()
2197 .as_version_3()
2198 .write_to(&mut v3)
2199 .unwrap();
2200 let (_, back) = decode(&v3, &key()).unwrap();
2201 assert_eq!(back.len(), n);
2202 assert!(back.dense_from_array(&twice).is_err());
2203 }
2204
2205 #[test]
2206 fn a_truncated_or_damaged_version_3_file_is_an_error_never_a_crash() {
2207 let dir = tempfile::tempdir().unwrap();
2208 let path = dir.path().join("x.idx");
2209 let (topology, ids) = a_graph();
2210 let main = write_main(&path, &topology, &ids);
2211 let incoming = topology.incoming().clone();
2212 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2213 EncodedChunk::incoming(&incoming, at)
2214 })
2215 .unwrap();
2216 let good = std::fs::read(&path).unwrap();
2217 let main_len = main.len as usize;
2218 for cut in (0..main_len).step_by(7).chain([main_len - 1]) {
2221 std::fs::write(&path, &good[..cut]).unwrap();
2222 assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
2223 }
2224 std::fs::write(&path, &good[..good.len() - 1]).unwrap();
2226 let stored = read_file(&path, &key()).unwrap();
2227 assert!(stored.chunks.is_empty());
2228 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2229 let (targets, t_len) = section_of(&good, OUT_TARGETS);
2233 let (edge_ids, e_len) = section_of(&good, OUT_EDGE_IDS);
2234 let edge_arrays = |at: usize| {
2235 (targets..targets + t_len).contains(&at) || (edge_ids..edge_ids + e_len).contains(&at)
2236 };
2237 for at in (0..main_len).filter(|&at| !edge_arrays(at)) {
2238 let mut flipped = good.clone();
2239 flipped[at] ^= 0x10;
2240 std::fs::write(&path, &flipped).unwrap();
2241 assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
2242 }
2243 }
2244
2245 #[test]
2246 fn the_edge_arrays_checksums_are_checked_before_a_whole_read() {
2247 let dir = tempfile::tempdir().unwrap();
2248 let path = dir.path().join("x.idx");
2249 let (topology, ids) = a_graph();
2250 let main = write_main(&path, &topology, &ids);
2251 let good = std::fs::read(&path).unwrap();
2252 let stored = read_file(&path, &key()).unwrap();
2253 same(&topology, &stored.topology);
2254 if let Some(checks) = &stored.unverified {
2255 checks.verify().unwrap();
2256 }
2257
2258 for kind in [OUT_TARGETS, OUT_EDGE_IDS] {
2259 let (at, _) = section_of(&good, kind);
2260 let mut flipped = good.clone();
2261 flipped[at] ^= 0x01;
2263 std::fs::write(&path, &flipped).unwrap();
2264 assert!(decode(&flipped, &key()).is_err());
2266 match read_file(&path, &key()) {
2267 Ok(stored) => {
2269 let checks = stored.unverified.expect("a mapped file defers");
2270 assert!(!checks.is_damaged());
2271 let why = checks.verify().unwrap_err();
2272 assert!(why.contains("does not match"), "{why}");
2273 assert!(checks.is_damaged());
2274 }
2275 Err(e) if !super::super::mapped::MAPS => {
2277 assert!(e.contains("does not match"), "{e}")
2278 }
2279 Err(e) => panic!("{e}"),
2280 }
2281 }
2282
2283 std::fs::write(&path, &good).unwrap();
2286 let incoming = topology.incoming().clone();
2287 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2288 EncodedChunk::incoming(&incoming, at)
2289 })
2290 .unwrap();
2291 let mut bytes = std::fs::read(&path).unwrap();
2292 let chunk = read_file(&path, &key()).unwrap().chunks[0].clone();
2293 let (_, _, edge_ids, _) = chunk.sections[2];
2294 bytes[edge_ids as usize] ^= 0x01;
2295 std::fs::write(&path, &bytes).unwrap();
2296 let stored = read_file(&path, &key()).unwrap();
2297 if let Some(checks) = &stored.unverified {
2298 checks.verify().unwrap();
2299 }
2300 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2301 assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
2302 }
2303
2304 #[test]
2305 fn a_mapped_index_survives_its_file_being_replaced_or_removed() {
2306 let dir = tempfile::tempdir().unwrap();
2307 let path = dir.path().join("x.idx");
2308 let (topology, ids) = a_graph();
2309 let main = write_main(&path, &topology, &ids);
2310 let incoming = topology.incoming().clone();
2311 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2312 EncodedChunk::incoming(&incoming, at)
2313 })
2314 .unwrap();
2315 let stored = read_file(&path, &key()).unwrap();
2316
2317 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2320 let (other, other_ids) = built(ints(&[7, 8, 9]), ints(&[8, 9, 7]));
2321 let temp = dir.path().join("x.idx.tmp");
2322 write_main(&temp, &other, &other_ids);
2323 std::fs::rename(&temp, &path).unwrap();
2324 assert_eq!(read_file(&path, &key()).unwrap().topology.n_nodes(), 3);
2325
2326 same(&topology, &stored.topology);
2329 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2330 if let Some(checks) = &stored.unverified {
2331 checks.verify().unwrap();
2332 }
2333 std::fs::remove_file(&path).unwrap();
2335 same(&topology, &stored.topology);
2336 assert_eq!(
2337 stored.ids.user_id_array().as_ref(),
2338 ids.user_id_array().as_ref()
2339 );
2340 }
2341
2342 #[test]
2343 fn a_version_1_file_is_not_read() {
2344 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2345 let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
2346 let mut bytes = encode(&key(), &topology, &ids);
2347 bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
2348 assert_eq!(
2349 decode(&bytes, &key()).unwrap_err(),
2350 "index format version 1; this build reads 2 to 5"
2351 );
2352 }
2353
2354 #[test]
2355 fn keys_round_trip_through_json() {
2356 let k = key();
2357 assert_eq!(IndexKey::from_json(&k.to_json()), Some(k.clone()));
2358 let mut no_tag = k.clone();
2359 no_tag.files[0].e_tag = None;
2360 assert_eq!(IndexKey::from_json(&no_tag.to_json()), Some(no_tag.clone()));
2361 assert_ne!(no_tag.hash(), k.hash());
2362 }
2363
2364 #[test]
2365 fn a_key_of_another_version_is_not_read() {
2366 let mut json = key().to_json();
2367 json["version"] = 1.into();
2368 assert_eq!(IndexKey::from_json(&json), None);
2369 json.as_object_mut().unwrap().remove("version");
2370 assert_eq!(IndexKey::from_json(&json), None);
2371 }
2372
2373 fn relabelled() -> [(Topology, IdMap); 2] {
2376 let n = 200i64;
2377 let (src, dst): (Vec<i64>, Vec<i64>) = (0..4 * n)
2380 .map(|i| ((i * 37) % n, ((i % n) * (i % n)) % (n / 3 + 1 + i % 7)))
2381 .unzip();
2382 let strings = |v: &[i64]| -> ArrayRef {
2383 Arc::new(StringArray::from(
2384 v.iter().map(|i| format!("user-{i}")).collect::<Vec<_>>(),
2385 ))
2386 };
2387 let ints = |v: &[i64]| -> ArrayRef { Arc::new(Int64Array::from(v.to_vec())) };
2388 let build = |column: &dyn Fn(&[i64]) -> ArrayRef| {
2389 let (map, s, d) =
2390 IdMap::from_edge_arrays(column(&src).as_ref(), column(&dst).as_ref()).unwrap();
2391 let topology = Topology::build_ordered(map.len(), s, d, ursa_core::NodeOrder::InDegree);
2392 let original = topology.original_ids().expect("relabelled").to_vec();
2393 let ids = map.reordered(&original);
2394 (topology, ids)
2395 };
2396 [build(&strings), build(&ints)]
2397 }
2398
2399 #[test]
2402 fn a_relabelled_index_round_trips_with_its_original_ids() {
2403 let dir = tempfile::tempdir().unwrap();
2404 let path = dir.path().join("x.idx");
2405 for (topology, ids) in relabelled() {
2406 let bytes = encode(&key(), &topology, &ids);
2407 assert_eq!(u32_at(&bytes, 8), VERSION);
2408 let (at, len) = section_of(&bytes, ORIGINAL_IDS);
2409 let stored: Vec<u32> = read(&bytes[at..at + len], u32::from_le_bytes).collect();
2410 assert_eq!(stored, topology.original_ids().unwrap());
2411 std::fs::write(&path, &bytes).unwrap();
2412 let back = read_file(&path, &key()).unwrap();
2413 assert_eq!(back.version, VERSION);
2414 same(&topology, &back.topology);
2415 assert_eq!(back.topology.original_ids(), topology.original_ids());
2416 finds_every_id(&back.ids, &ids);
2417 assert_eq!(
2418 ursa_core::algo::connected_components_weak(&back.topology, None),
2419 ursa_core::algo::connected_components_weak(&topology, None)
2420 );
2421 assert_eq!(encode(&key(), &back.topology, &back.ids), bytes);
2423 let mut flipped = bytes.clone();
2425 flipped[at] ^= 1;
2426 std::fs::write(&path, &flipped).unwrap();
2427 assert!(read_file(&path, &key()).is_err());
2428 }
2429 for (topology, ids) in graphs() {
2431 let bytes = encode(&key(), &topology, &ids);
2432 let n_sections = u32_at(&bytes, 40) as usize;
2433 let table = align(HEADER_LEN + u64_at(&bytes, 32), 8) as usize;
2434 assert!((0..n_sections).all(|i| u32_at(&bytes, table + 32 * i) != ORIGINAL_IDS));
2435 }
2436 }
2437
2438 #[test]
2442 fn a_version_4_file_from_0_12_is_read_with_its_numbering() {
2443 let dir = tempfile::tempdir().unwrap();
2444 let path = dir.path().join("x.idx");
2445 for (topology, ids) in graphs() {
2446 let v5 = encode(&key(), &topology, &ids);
2447 let encoded = Encoded::new(&key(), &topology, &ids)
2448 .unwrap()
2449 .as_version_4();
2450 let mut v4 = Vec::new();
2451 encoded.write_to(&mut v4).unwrap();
2452 assert_eq!(u32_at(&v4, 8), VERSION_4);
2453 assert_eq!(v4.len(), v5.len());
2456 let differ: Vec<usize> = (0..v4.len()).filter(|&i| v4[i] != v5[i]).collect();
2457 assert!(
2458 differ.iter().all(|&i| i < 12 || i >= v4.len() - 8),
2459 "{differ:?}"
2460 );
2461 std::fs::write(&path, &v4).unwrap();
2462 let stored = read_file(&path, &key()).unwrap();
2463 assert_eq!(stored.version, VERSION_4);
2464 same(&topology, &stored.topology);
2465 assert!(stored.topology.original_ids().is_none());
2466 finds_every_id(&stored.ids, &ids);
2467 assert_eq!(
2468 stored.ids.lookup_table().unwrap(),
2469 ids.lookup_table().unwrap()
2470 );
2471 assert_eq!(encode(&key(), &stored.topology, &stored.ids), v5);
2472 }
2473 }
2474}