1use std::fs::{File, OpenOptions};
140use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
141use std::ops::Range;
142use std::path::Path;
143use std::sync::atomic::{AtomicU64, Ordering};
144use std::sync::{Arc, OnceLock};
145
146use datafusion::arrow::array::{Array, Int64Array, StringArray};
147use datafusion::arrow::buffer::{BooleanBuffer, Buffer, OffsetBuffer, ScalarBuffer};
148use datafusion::arrow::datatypes::ArrowNativeType;
149use serde_json::{json, Value};
150use ursa_core::id_map::lookup_table_len;
151use ursa_core::{Adjacency, IdMap, Topology};
152
153use super::mapped::{Region, Unverified};
154use crate::graph::FileIdentity;
155
156pub const MAGIC: [u8; 8] = *b"URSAIDX\0";
158const END_MAGIC: [u8; 4] = *b"XDIU";
160pub const VERSION: u32 = 4;
163pub const VERSION_3: u32 = 3;
165pub const VERSION_2: u32 = 2;
167const CHUNK_MAGIC: [u8; 4] = *b"CHNK";
169const CHUNK_END_MAGIC: [u8; 4] = *b"KNHC";
171const CHUNK_HEADER_LEN: u64 = 16;
172const CHUNK_TRAILER_LEN: u64 = 48;
173
174pub const CHUNK_INCOMING: u32 = 1;
176pub const CHUNK_WEIGHTS: u32 = 2;
178
179const HEADER_LEN: u64 = 64;
180const TRAILER_LEN: u64 = 16;
181const SECTION_ENTRY_LEN: u64 = 32;
183const CHUNK_ENTRY_LEN: u64 = 24;
185const SECTION_ALIGN: u64 = 64;
186
187const FLAG_STRING_IDS: u32 = 1;
188
189const OUT_OFFSETS: u32 = 1;
190const OUT_TARGETS: u32 = 2;
191const OUT_EDGE_IDS: u32 = 3;
192const IN_OFFSETS: u32 = 4;
193const IN_TARGETS: u32 = 5;
194const IN_EDGE_IDS: u32 = 6;
195const IDS_INT64: u32 = 7;
196const IDS_STR_OFFSETS: u32 = 8;
197const IDS_STR_BYTES: u32 = 9;
198const WEIGHTS_F64: u32 = 10;
199const KEPT_ROWS: u32 = 11;
200const ID_TABLE: u32 = 12;
201
202pub const KEY_VERSION: u64 = 2;
208
209#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct IndexKey {
213 pub fingerprint: String,
214 pub files: Vec<FileIdentity>,
215}
216
217impl IndexKey {
218 pub fn new(fingerprint: String, files: Vec<FileIdentity>) -> Self {
219 Self { fingerprint, files }
220 }
221
222 pub fn to_json(&self) -> Value {
225 let files: Vec<Value> = self
226 .files
227 .iter()
228 .map(|f| {
229 json!({
230 "store": f.store,
231 "location": f.location,
232 "size": f.size,
233 "modified": f.modified,
234 "e_tag": f.e_tag,
235 })
236 })
237 .collect();
238 json!({ "version": KEY_VERSION, "fingerprint": self.fingerprint, "files": files })
239 }
240
241 pub fn from_json(value: &Value) -> Option<Self> {
243 if value.get("version")?.as_u64()? != KEY_VERSION {
244 return None;
245 }
246 let fingerprint = value.get("fingerprint")?.as_str()?.to_string();
247 let files = value
248 .get("files")?
249 .as_array()?
250 .iter()
251 .map(|f| {
252 Some(FileIdentity {
253 store: f.get("store")?.as_str()?.to_string(),
254 location: f.get("location")?.as_str()?.to_string(),
255 size: f.get("size")?.as_u64()?,
256 modified: f.get("modified")?.as_i64()?,
257 e_tag: match f.get("e_tag")? {
258 Value::Null => None,
259 Value::String(s) => Some(s.clone()),
260 _ => return None,
261 },
262 })
263 })
264 .collect::<Option<Vec<_>>>()?;
265 Some(Self { fingerprint, files })
266 }
267
268 pub fn hash(&self) -> u64 {
272 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
273 for b in self.to_json().to_string().bytes() {
274 h ^= u64::from(b);
275 h = h.wrapping_mul(0x0000_0100_0000_01b3);
276 }
277 h
278 }
279}
280
281enum Data<'a> {
284 U64(&'a [u64]),
285 F64(&'a [f64]),
286 U32(&'a [u32]),
287 Ints(Int64Array),
289 StrOffsets(StringArray),
292 StrBytes(StringArray),
294 Bytes(Buffer),
296 IdTable(IdTable<'a>),
298}
299
300struct IdTable<'a> {
304 ids: &'a IdMap,
305 slots: OnceLock<Result<ScalarBuffer<u32>, String>>,
306}
307
308impl IdTable<'_> {
309 fn build(&self) -> Result<&ScalarBuffer<u32>, String> {
310 self.slots
311 .get_or_init(|| self.ids.lookup_table().map_err(|e| e.to_string()))
312 .as_ref()
313 .map_err(Clone::clone)
314 }
315
316 fn slots(&self) -> &[u32] {
318 self.build()
319 .expect("write_to builds the lookup table before it is written")
320 }
321}
322
323impl Data<'_> {
324 fn width(&self) -> u64 {
325 match self {
326 Data::U64(_) | Data::F64(_) | Data::Ints(_) => 8,
327 Data::U32(_) | Data::StrOffsets(_) | Data::IdTable(_) => 4,
328 Data::StrBytes(_) | Data::Bytes(_) => 1,
329 }
330 }
331
332 fn count(&self) -> u64 {
333 (match self {
334 Data::U64(v) => v.len(),
335 Data::F64(v) => v.len(),
336 Data::U32(v) => v.len(),
337 Data::Ints(a) => a.len(),
338 Data::StrOffsets(a) => a.len() + 1,
339 Data::StrBytes(a) => str_bytes(a).len(),
340 Data::Bytes(b) => b.len(),
341 Data::IdTable(t) => return lookup_table_len(t.ids.len()),
342 }) as u64
343 }
344}
345
346fn str_bytes(strings: &StringArray) -> &[u8] {
348 let offsets = strings.value_offsets();
349 let (first, last) = (offsets[0] as usize, offsets[offsets.len() - 1] as usize);
350 &strings.value_data()[first..last]
351}
352
353fn align(n: u64, to: u64) -> u64 {
354 n.div_ceil(to) * to
355}
356
357pub struct Encoded<'a> {
360 version: u32,
363 flags: u32,
364 n_nodes: u64,
365 n_edges: u64,
366 n_dropped: u64,
367 key: Vec<u8>,
368 sections: Vec<(u32, Data<'a>, u64)>,
369 table_offset: u64,
370 trailer_offset: u64,
371}
372
373impl<'a> Encoded<'a> {
374 pub fn new(key: &IndexKey, topology: &'a Topology, ids: &'a IdMap) -> io::Result<Self> {
377 Self::with_dropped(key, topology, ids, 0, None)
378 }
379
380 pub fn with_dropped(
383 key: &IndexKey,
384 topology: &'a Topology,
385 ids: &'a IdMap,
386 n_dropped: u64,
387 kept: Option<&BooleanBuffer>,
388 ) -> io::Result<Self> {
389 let id_array = ids.user_id_array();
390 let mut flags = 0;
391 let out = topology.out();
392 let mut sections: Vec<(u32, Data<'a>)> = vec![
393 (OUT_OFFSETS, Data::U64(&out.offsets)),
394 (OUT_TARGETS, Data::U32(&out.targets)),
395 (OUT_EDGE_IDS, Data::U32(&out.edge_ids)),
396 ];
397 if let Some(ints) = id_array.as_any().downcast_ref::<Int64Array>() {
399 sections.push((IDS_INT64, Data::Ints(ints.clone())));
400 } else if let Some(strings) = id_array.as_any().downcast_ref::<StringArray>() {
401 flags |= FLAG_STRING_IDS;
402 sections.push((IDS_STR_OFFSETS, Data::StrOffsets(strings.clone())));
403 sections.push((IDS_STR_BYTES, Data::StrBytes(strings.clone())));
404 } else {
405 return Err(io::Error::other(format!(
406 "cannot store node ids of type {}",
407 id_array.data_type()
408 )));
409 }
410 sections.push((
411 ID_TABLE,
412 Data::IdTable(IdTable {
413 ids,
414 slots: OnceLock::new(),
415 }),
416 ));
417 let n_dropped = match kept {
418 Some(kept) if n_dropped > 0 => {
419 sections.push((KEPT_ROWS, Data::Bytes(kept.sliced())));
420 n_dropped
421 }
422 _ => 0,
423 };
424
425 let key = key.to_json().to_string().into_bytes();
426 let (n_nodes, n_edges) = (topology.n_nodes() as u64, topology.n_edges() as u64);
427 Ok(Self::laid_out(
428 VERSION, flags, n_nodes, n_edges, n_dropped, key, sections,
429 ))
430 }
431
432 fn laid_out(
435 version: u32,
436 flags: u32,
437 n_nodes: u64,
438 n_edges: u64,
439 n_dropped: u64,
440 key: Vec<u8>,
441 sections: Vec<(u32, Data<'a>)>,
442 ) -> Self {
443 let entry_len = match version {
444 VERSION_2 => CHUNK_ENTRY_LEN,
445 _ => SECTION_ENTRY_LEN,
446 };
447 let table_offset = align(HEADER_LEN + key.len() as u64, 8);
448 let mut at = table_offset + entry_len * sections.len() as u64;
449 let sections = sections
450 .into_iter()
451 .map(|(kind, data)| {
452 at = align(at, SECTION_ALIGN);
453 let offset = at;
454 at += data.width() * data.count();
455 (kind, data, offset)
456 })
457 .collect();
458 Self {
459 version,
460 flags,
461 n_nodes,
462 n_edges,
463 n_dropped,
464 key,
465 sections,
466 table_offset,
467 trailer_offset: align(at, 8),
468 }
469 }
470
471 #[doc(hidden)]
474 pub fn as_version_2(self) -> Self {
475 self.in_version(VERSION_2)
476 }
477
478 #[doc(hidden)]
481 pub fn as_version_3(self) -> Self {
482 self.in_version(VERSION_3)
483 }
484
485 fn in_version(self, version: u32) -> Self {
487 let Self {
488 flags,
489 n_nodes,
490 n_edges,
491 n_dropped,
492 key,
493 sections,
494 ..
495 } = self;
496 let sections = sections
497 .into_iter()
498 .filter(|(k, _, _)| *k != ID_TABLE)
499 .map(|(k, d, _)| (k, d))
500 .collect();
501 Self::laid_out(version, flags, n_nodes, n_edges, n_dropped, key, sections)
502 }
503
504 pub fn file_size(&self) -> u64 {
506 self.trailer_offset + TRAILER_LEN
507 }
508
509 pub fn write_to(&self, out: impl Write) -> io::Result<MainPart> {
511 let v2 = self.version == VERSION_2;
512 for (_, data, _) in &self.sections {
513 if let Data::IdTable(table) = data {
514 table.build().map_err(io::Error::other)?;
515 }
516 }
517 let crcs: Vec<Option<u32>> = self
520 .sections
521 .iter()
522 .map(|(_, data, _)| (!v2).then(|| data_crc(data)))
523 .collect();
524 let mut sink = Sink {
525 out,
526 crc: crc32fast::Hasher::new(),
527 at: 0,
528 hash: true,
529 };
530 let mut header = Vec::with_capacity(HEADER_LEN as usize);
531 header.extend_from_slice(&MAGIC);
532 header.extend_from_slice(&self.version.to_le_bytes());
533 header.extend_from_slice(&self.flags.to_le_bytes());
534 header.extend_from_slice(&self.n_nodes.to_le_bytes());
535 header.extend_from_slice(&self.n_edges.to_le_bytes());
536 header.extend_from_slice(&(self.key.len() as u64).to_le_bytes());
537 header.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
538 header.extend_from_slice(&[0; 4]);
539 header.extend_from_slice(&self.file_size().to_le_bytes());
540 header.extend_from_slice(&self.n_dropped.to_le_bytes());
541 header.resize(HEADER_LEN as usize, 0);
542 sink.put(&header)?;
543 sink.put(&self.key)?;
544 sink.pad_to(self.table_offset)?;
545 for ((kind, data, offset), crc) in self.sections.iter().zip(&crcs) {
546 sink.put(§ion_entry(*kind, data, *offset, *crc))?;
547 }
548 let meta_crc = sink.crc.clone().finalize();
551 sink.hash = v2;
552 for (_, data, offset) in &self.sections {
553 sink.pad_to(*offset)?;
554 sink.put_data(data)?;
555 }
556 sink.pad_to(self.trailer_offset)?;
557 let crc = match v2 {
558 true => sink.crc.clone().finalize(),
559 false => meta_crc,
560 };
561 let mut trailer = Vec::with_capacity(TRAILER_LEN as usize);
562 trailer.extend_from_slice(&self.file_size().to_le_bytes());
563 trailer.extend_from_slice(&crc.to_le_bytes());
564 trailer.extend_from_slice(&END_MAGIC);
565 sink.put(&trailer)?;
566 sink.out.flush()?;
567 Ok(MainPart {
568 len: self.file_size(),
569 crc,
570 })
571 }
572}
573
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
577pub struct MainPart {
578 pub len: u64,
579 pub crc: u32,
580}
581
582pub struct EncodedChunk<'a> {
584 kind: u32,
585 name: Vec<u8>,
586 start: u64,
587 sections: Vec<(u32, Data<'a>, u64)>,
588 name_offset: u64,
589 table_offset: u64,
590}
591
592impl<'a> EncodedChunk<'a> {
593 pub fn incoming(incoming: &'a Adjacency, start: u64) -> Self {
595 Self::new(
596 CHUNK_INCOMING,
597 Vec::new(),
598 vec![
599 (IN_OFFSETS, Data::U64(&incoming.offsets)),
600 (IN_TARGETS, Data::U32(&incoming.targets)),
601 (IN_EDGE_IDS, Data::U32(&incoming.edge_ids)),
602 ],
603 start,
604 )
605 }
606
607 pub fn weights(key: &str, columns: &[&'a [f64]], start: u64) -> Self {
610 Self::new(
611 CHUNK_WEIGHTS,
612 key.as_bytes().to_vec(),
613 columns
614 .iter()
615 .map(|column| (WEIGHTS_F64, Data::F64(column)))
616 .collect(),
617 start,
618 )
619 }
620
621 fn new(kind: u32, name: Vec<u8>, sections: Vec<(u32, Data<'a>)>, start: u64) -> Self {
622 let mut at = start + CHUNK_HEADER_LEN;
623 let sections = sections
624 .into_iter()
625 .map(|(kind, data)| {
626 at = align(at, SECTION_ALIGN);
627 let offset = at;
628 at += data.width() * data.count();
629 (kind, data, offset)
630 })
631 .collect();
632 let name_offset = at;
633 let table_offset = align(name_offset + name.len() as u64, 8);
634 Self {
635 kind,
636 name,
637 start,
638 sections,
639 name_offset,
640 table_offset,
641 }
642 }
643
644 fn trailer_offset(&self) -> u64 {
645 self.table_offset + CHUNK_ENTRY_LEN * self.sections.len() as u64
646 }
647
648 pub fn end(&self) -> u64 {
650 self.trailer_offset() + CHUNK_TRAILER_LEN
651 }
652
653 pub fn size(&self) -> u64 {
655 self.end() - self.start
656 }
657
658 pub fn write_to(&self, out: impl Write) -> io::Result<()> {
660 let mut sink = Sink {
661 out,
662 crc: crc32fast::Hasher::new(),
663 at: self.start,
664 hash: true,
665 };
666 let mut header = Vec::with_capacity(CHUNK_HEADER_LEN as usize);
667 header.extend_from_slice(&CHUNK_MAGIC);
668 header.extend_from_slice(&self.kind.to_le_bytes());
669 header.extend_from_slice(&self.end().to_le_bytes());
670 sink.put(&header)?;
671 for (_, data, offset) in &self.sections {
672 sink.pad_to(*offset)?;
673 sink.put_data(data)?;
674 }
675 sink.pad_to(self.name_offset)?;
676 let data_crc = std::mem::replace(&mut sink.crc, crc32fast::Hasher::new()).finalize();
677 sink.put(&self.name)?;
678 sink.pad_to(self.table_offset)?;
679 for (kind, data, offset) in &self.sections {
680 sink.put(§ion_entry(*kind, data, *offset, None))?;
681 }
682 let mut trailer = Vec::with_capacity(CHUNK_TRAILER_LEN as usize);
683 trailer.extend_from_slice(&self.kind.to_le_bytes());
684 trailer.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
685 trailer.extend_from_slice(&self.start.to_le_bytes());
686 trailer.extend_from_slice(&self.name_offset.to_le_bytes());
687 trailer.extend_from_slice(&(self.name.len() as u64).to_le_bytes());
688 trailer.extend_from_slice(&data_crc.to_le_bytes());
689 sink.crc.update(&trailer);
690 let meta_crc = sink.crc.clone().finalize();
691 trailer.extend_from_slice(&meta_crc.to_le_bytes());
692 trailer.extend_from_slice(&CHUNK_END_MAGIC);
693 trailer.extend_from_slice(&[0; 4]);
694 sink.out.write_all(&trailer)?;
695 sink.out.flush()
696 }
697}
698
699fn section_entry(kind: u32, data: &Data<'_>, offset: u64, crc: Option<u32>) -> Vec<u8> {
702 let mut entry = Vec::with_capacity(SECTION_ENTRY_LEN as usize);
703 entry.extend_from_slice(&kind.to_le_bytes());
704 entry.extend_from_slice(&(data.width() as u32).to_le_bytes());
705 entry.extend_from_slice(&offset.to_le_bytes());
706 entry.extend_from_slice(&data.count().to_le_bytes());
707 if let Some(crc) = crc {
708 entry.extend_from_slice(&crc.to_le_bytes());
709 entry.extend_from_slice(&[0; 4]);
710 }
711 entry
712}
713
714fn data_crc(data: &Data<'_>) -> u32 {
716 fn bytes_of<T: Copy>(values: &[T]) -> &[u8] {
718 unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), size_of_val(values)) }
721 }
722 if cfg!(target_endian = "little") {
725 let bytes = match data {
726 Data::U64(v) => Some(bytes_of(v)),
727 Data::F64(v) => Some(bytes_of(v)),
728 Data::U32(v) => Some(bytes_of(v)),
729 Data::Ints(a) => Some(bytes_of(a.values())),
730 Data::StrBytes(a) => Some(str_bytes(a)),
731 Data::Bytes(b) => Some(b.as_slice()),
732 Data::IdTable(t) => Some(bytes_of(t.slots())),
733 Data::StrOffsets(_) => None,
734 };
735 if let Some(bytes) = bytes {
736 return super::mapped::crc(bytes);
737 }
738 }
739 let mut sink = Sink {
740 out: io::sink(),
741 crc: crc32fast::Hasher::new(),
742 at: 0,
743 hash: true,
744 };
745 sink.put_data(data)
746 .expect("writing to io::sink does not fail");
747 sink.crc.finalize()
748}
749
750struct Sink<W> {
752 out: W,
753 crc: crc32fast::Hasher,
754 at: u64,
755 hash: bool,
756}
757
758impl<W: Write> Sink<W> {
759 fn put(&mut self, bytes: &[u8]) -> io::Result<()> {
760 if self.hash {
761 self.crc.update(bytes);
762 }
763 self.at += bytes.len() as u64;
764 self.out.write_all(bytes)
765 }
766
767 fn pad_to(&mut self, offset: u64) -> io::Result<()> {
768 debug_assert!(offset >= self.at);
769 let zeros = [0u8; SECTION_ALIGN as usize];
770 while self.at < offset {
771 let n = ((offset - self.at) as usize).min(zeros.len());
772 self.put(&zeros[..n])?;
773 }
774 Ok(())
775 }
776
777 fn put_data(&mut self, data: &Data<'_>) -> io::Result<()> {
779 match data {
780 Data::U64(v) => self.put_all(v, |x| x.to_le_bytes()),
781 Data::F64(v) => self.put_all(v, |x| x.to_le_bytes()),
782 Data::U32(v) => self.put_all(v, |x| x.to_le_bytes()),
783 Data::Ints(a) => self.put_all(a.values(), |x| x.to_le_bytes()),
784 Data::StrOffsets(a) => {
785 let offsets = a.value_offsets();
786 let base = offsets[0];
787 self.put_all(offsets, |x| (x - base).to_le_bytes())
788 }
789 Data::StrBytes(a) => self.put(str_bytes(a)),
790 Data::Bytes(b) => self.put(b.as_slice()),
791 Data::IdTable(t) => self.put_all(t.slots(), |x| x.to_le_bytes()),
792 }
793 }
794
795 fn put_all<T: Copy, const N: usize>(
797 &mut self,
798 values: &[T],
799 le: impl Fn(T) -> [u8; N],
800 ) -> io::Result<()> {
801 let mut block = Vec::with_capacity(64 * 1024);
802 for chunk in values.chunks(64 * 1024 / N) {
803 block.clear();
804 for &v in chunk {
805 block.extend_from_slice(&le(v));
806 }
807 self.put(&block)?;
808 }
809 Ok(())
810 }
811}
812
813pub type DecodeError = String;
815
816#[derive(Debug, Clone, Default)]
819pub struct Dropped {
820 pub n_dropped: u64,
821 pub kept: Option<BooleanBuffer>,
822}
823
824pub struct Stored {
826 pub topology: Topology,
828 pub ids: IdMap,
829 pub dropped: Dropped,
831 pub main: MainPart,
832 pub chunks: Vec<ChunkInfo>,
834 pub version: u32,
837 pub unverified: Option<Arc<Unverified>>,
840}
841
842pub fn has_chunk(chunks: &[ChunkInfo], kind: u32, name: &[u8]) -> bool {
844 chunks.iter().any(|c| c.kind == kind && c.name == name)
845}
846
847static INCOMING_READS: AtomicU64 = AtomicU64::new(0);
849
850pub fn incoming_reads() -> u64 {
853 INCOMING_READS.load(Ordering::Relaxed)
854}
855
856thread_local! {
857 static THREAD_INCOMING_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
862}
863
864fn count_incoming_read() {
866 INCOMING_READS.fetch_add(1, Ordering::Relaxed);
867 THREAD_INCOMING_READS.with(|n| n.set(n.get() + 1));
868}
869
870pub fn thread_incoming_reads() -> u64 {
872 THREAD_INCOMING_READS.with(std::cell::Cell::get)
873}
874
875pub fn read_file(path: &Path, key: &IndexKey) -> Result<Stored, DecodeError> {
890 let mut file = File::open(path).map_err(|e| e.to_string())?;
891 let len = file.metadata().map_err(|e| e.to_string())?.len();
892 let head = read_head(&mut file, len, key)?;
893 let (chunks, end) = list_chunks(&mut file, head.main_len, len);
894 let mapped = head.version != VERSION_2 && super::mapped::MAPS;
895 let data = match mapped {
896 true => super::mapped::map(&file, end)?,
897 false => super::mapped::read_whole(&file, head.main_len)?,
898 };
899 let (topology, ids, main, dropped, deferred) = parse(&head, &data, mapped)?;
900 let unverified = mapped.then(|| Arc::new(Unverified::new(data.clone(), deferred)));
901 let topology = match (
902 chunks.iter().find(|c| c.kind == CHUNK_INCOMING),
903 &unverified,
904 ) {
905 (Some(chunk), Some(checks)) => {
906 let (chunk, checks) = (chunk.clone(), Arc::clone(checks));
909 let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
910 topology.with_checksummed_incoming_loader(Box::new(move || {
911 let incoming = mapped_incoming(&data, &chunk, n_nodes, n_edges).ok()?;
912 checks
913 .defer(Region {
914 what: "in-adjacency",
915 range: usize::try_from(chunk.start).ok()?
916 ..usize::try_from(chunk.data_end).ok()?,
917 crc: chunk.data_crc,
918 })
919 .ok()?;
920 count_incoming_read();
921 Some(incoming)
922 }))
923 }
924 (Some(chunk), None) => {
925 let (path, chunk) = (path.to_path_buf(), chunk.clone());
926 let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
927 topology.with_incoming_loader(Box::new(move || {
928 let incoming = read_incoming(&path, main, &chunk, n_nodes, n_edges).ok()?;
929 count_incoming_read();
930 Some(incoming)
931 }))
932 }
933 (None, _) => topology,
934 };
935 Ok(Stored {
936 topology,
937 ids,
938 dropped,
939 main,
940 chunks,
941 version: head.version,
942 unverified,
943 })
944}
945
946pub fn decode(bytes: &[u8], key: &IndexKey) -> Result<(Topology, IdMap), DecodeError> {
949 decode_main(bytes, key).map(|(topology, ids, _, _)| (topology, ids))
950}
951
952fn decode_main(
954 bytes: &[u8],
955 key: &IndexKey,
956) -> Result<(Topology, IdMap, MainPart, Dropped), DecodeError> {
957 let head = read_head(&mut io::Cursor::new(bytes), bytes.len() as u64, key)?;
958 let main = &bytes[..head.main_len as usize];
960 let mut words = vec![0u64; main.len().div_ceil(8)];
961 for (word, chunk) in words.iter_mut().zip(main.chunks(8)) {
962 let mut le = [0u8; 8];
963 le[..chunk.len()].copy_from_slice(chunk);
964 *word = u64::from_ne_bytes(le);
965 }
966 let data = Buffer::from_vec(words).slice_with_length(0, main.len());
967 parse(&head, &data, false)
968 .map(|(topology, ids, main, dropped, _)| (topology, ids, main, dropped))
969}
970
971#[derive(Debug, Clone, PartialEq, Eq)]
973pub struct ChunkInfo {
974 pub kind: u32,
975 pub name: Vec<u8>,
976 pub start: u64,
977 pub end: u64,
978 data_end: u64,
980 data_crc: u32,
981 sections: Vec<(u32, u64, u64, u64)>,
983}
984
985pub fn list_chunks<R: Read + Seek>(file: &mut R, main_len: u64, len: u64) -> (Vec<ChunkInfo>, u64) {
990 let mut chunks = Vec::new();
991 let mut at = main_len;
992 while let Some(chunk) = chunk_at(file, at, len) {
993 at = chunk.end;
994 chunks.push(chunk);
995 }
996 (chunks, at)
997}
998
999fn u32_at(bytes: &[u8], at: usize) -> u32 {
1000 u32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes"))
1001}
1002
1003fn chunk_at<R: Read + Seek>(file: &mut R, start: u64, len: u64) -> Option<ChunkInfo> {
1006 let read = |file: &mut R, at: u64, n: u64| -> Option<Vec<u8>> {
1007 file.seek(SeekFrom::Start(at)).ok()?;
1008 let mut buf = vec![0; usize::try_from(n).ok()?];
1009 file.read_exact(&mut buf).ok()?;
1010 Some(buf)
1011 };
1012 if len.saturating_sub(start) < CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN {
1013 return None;
1014 }
1015 let header = read(file, start, CHUNK_HEADER_LEN)?;
1016 let end = u64_at(&header, 8);
1017 if header[..4] != CHUNK_MAGIC || end > len || end < start + CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN
1018 {
1019 return None;
1020 }
1021 let kind = u32_at(&header, 4);
1022 let trailer_offset = end - CHUNK_TRAILER_LEN;
1023 let trailer = read(file, trailer_offset, CHUNK_TRAILER_LEN)?;
1024 let n_sections = u32_at(&trailer, 4) as u64;
1025 let name_offset = u64_at(&trailer, 16);
1026 let name_len = u64_at(&trailer, 24);
1027 let table_offset = align(name_offset.checked_add(name_len)?, 8);
1028 if trailer[40..44] != CHUNK_END_MAGIC
1029 || u32_at(&trailer, 0) != kind
1030 || u64_at(&trailer, 8) != start
1031 || name_offset < start + CHUNK_HEADER_LEN
1032 || n_sections
1033 .checked_mul(CHUNK_ENTRY_LEN)?
1034 .checked_add(table_offset)?
1035 != trailer_offset
1036 {
1037 return None;
1038 }
1039 let meta = read(file, name_offset, trailer_offset - name_offset)?;
1040 let mut crc = crc32fast::Hasher::new();
1041 crc.update(&meta);
1042 crc.update(&trailer[..36]);
1043 if crc.finalize() != u32_at(&trailer, 36) {
1044 return None;
1045 }
1046 let name = meta[..name_len as usize].to_vec();
1047 let table = &meta[(table_offset - name_offset) as usize..];
1048 let mut sections = Vec::new();
1049 for entry in table.chunks_exact(CHUNK_ENTRY_LEN as usize) {
1050 let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
1051 let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
1052 width
1053 .checked_mul(count)
1054 .and_then(|n| n.checked_add(offset))
1055 .filter(|&e| offset >= start + CHUNK_HEADER_LEN && e <= name_offset)?;
1056 sections.push((kind, width, offset, count));
1057 }
1058 sections.sort_by_key(|&(_, _, offset, _)| offset);
1059 if sections
1060 .windows(2)
1061 .any(|w| w[0].2 + w[0].1 * w[0].3 > w[1].2)
1062 {
1063 return None;
1064 }
1065 Some(ChunkInfo {
1066 kind,
1067 name,
1068 start,
1069 end,
1070 data_end: name_offset,
1071 data_crc: u32_at(&trailer, 32),
1072 sections,
1073 })
1074}
1075
1076fn check_main(file: &mut File, main: MainPart) -> Result<(), DecodeError> {
1078 let len = file.metadata().map_err(|e| e.to_string())?.len();
1079 if len < main.len || main.len < HEADER_LEN + TRAILER_LEN {
1080 return Err("the file's main part has changed".into());
1081 }
1082 let mut trailer = [0u8; TRAILER_LEN as usize];
1083 file.seek(SeekFrom::Start(main.len - TRAILER_LEN))
1084 .and_then(|_| file.read_exact(&mut trailer))
1085 .map_err(|e| e.to_string())?;
1086 if u64_at(&trailer, 0) != main.len || u32_at(&trailer, 8) != main.crc {
1087 return Err("the file's main part has changed".into());
1088 }
1089 Ok(())
1090}
1091
1092pub fn read_chunk(
1095 path: &Path,
1096 main: MainPart,
1097 chunk: &ChunkInfo,
1098) -> Result<Vec<(u32, Section)>, DecodeError> {
1099 let mut file = File::open(path).map_err(|e| e.to_string())?;
1100 check_main(&mut file, main)?;
1101 if file.metadata().map_err(|e| e.to_string())?.len() < chunk.end {
1102 return Err("the file is shorter than the chunk".into());
1103 }
1104 file.seek(SeekFrom::Start(chunk.start))
1105 .map_err(|e| e.to_string())?;
1106 let mut src = Source {
1107 inner: BufReader::with_capacity(BLOCK, file),
1108 crc: crc32fast::Hasher::new(),
1109 at: chunk.start,
1110 };
1111 let mut sections = Vec::with_capacity(chunk.sections.len());
1112 for &(kind, width, offset, count) in &chunk.sections {
1113 src.skip_to(offset)?;
1114 sections.push((kind, src.section(kind, width, offset, count)?));
1115 }
1116 src.skip_to(chunk.data_end)?;
1117 if src.crc.finalize() != chunk.data_crc {
1118 return Err("the chunk's checksum does not match".into());
1119 }
1120 Ok(sections)
1121}
1122
1123fn read_incoming(
1126 path: &Path,
1127 main: MainPart,
1128 chunk: &ChunkInfo,
1129 n_nodes: usize,
1130 n_edges: usize,
1131) -> Result<Adjacency, DecodeError> {
1132 let mut sections = read_chunk(path, main, chunk)?;
1133 let mut take = |kind: u32| {
1134 let i = sections
1135 .iter()
1136 .position(|(k, _)| *k == kind)
1137 .ok_or_else(|| format!("section {kind} is missing"))?;
1138 Ok::<_, DecodeError>(sections.swap_remove(i).1)
1139 };
1140 match (take(IN_OFFSETS)?, take(IN_TARGETS)?, take(IN_EDGE_IDS)?) {
1141 (Section::U64(offsets), Section::U32(targets), Section::U32(edge_ids))
1142 if offsets.len() == n_nodes + 1
1143 && targets.len() == n_edges
1144 && edge_ids.len() == n_edges =>
1145 {
1146 Ok(Adjacency {
1147 offsets: offsets.into(),
1148 targets: targets.into(),
1149 edge_ids: edge_ids.into(),
1150 })
1151 }
1152 _ => Err("the in-adjacency is malformed".into()),
1153 }
1154}
1155
1156pub fn read_weights(
1159 path: &Path,
1160 main: MainPart,
1161 chunk: &ChunkInfo,
1162 n_edges: usize,
1163) -> Result<Vec<Vec<f64>>, DecodeError> {
1164 read_chunk(path, main, chunk)?
1165 .into_iter()
1166 .map(|(_, section)| match section {
1167 Section::F64(values) if values.len() == n_edges => Ok(values),
1168 _ => Err("the weights are malformed".to_string()),
1169 })
1170 .collect()
1171}
1172
1173pub fn append_chunk<'a>(
1179 path: &Path,
1180 main: MainPart,
1181 kind: u32,
1182 name: &[u8],
1183 encode: impl FnOnce(u64) -> EncodedChunk<'a>,
1184) -> io::Result<Option<u64>> {
1185 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
1186 check_main(&mut file, main).map_err(io::Error::other)?;
1187 let len = file.metadata()?.len();
1188 let (chunks, at) = list_chunks(&mut file, main.len, len);
1189 if has_chunk(&chunks, kind, name) {
1190 return Ok(None);
1191 }
1192 let chunk = encode(at);
1193 debug_assert_eq!((chunk.kind, chunk.name.as_slice()), (kind, name));
1194 if len > at {
1197 file.set_len(at)?;
1198 }
1199 file.seek(SeekFrom::Start(at))?;
1200 let mut out = BufWriter::with_capacity(1 << 20, &file);
1201 chunk.write_to(&mut out)?;
1202 out.into_inner().map_err(|e| e.into_error())?;
1203 file.sync_all()?;
1204 Ok(Some(chunk.end()))
1205}
1206
1207const BLOCK: usize = 1 << 20;
1209
1210struct Source<R> {
1212 inner: R,
1213 crc: crc32fast::Hasher,
1214 at: u64,
1215}
1216
1217impl<R: Read> Source<R> {
1218 fn fill(&mut self, buf: &mut [u8]) -> Result<(), DecodeError> {
1219 self.inner.read_exact(buf).map_err(|e| match e.kind() {
1220 io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1221 _ => e.to_string(),
1222 })?;
1223 self.crc.update(buf);
1224 self.at += buf.len() as u64;
1225 Ok(())
1226 }
1227
1228 fn bytes(&mut self, n: usize) -> Result<Vec<u8>, DecodeError> {
1229 let mut buf = vec![0; n];
1230 self.fill(&mut buf)?;
1231 Ok(buf)
1232 }
1233
1234 fn skip_to(&mut self, offset: u64) -> Result<(), DecodeError> {
1237 let mut buf = vec![0; BLOCK.min(offset.saturating_sub(self.at) as usize)];
1238 while self.at < offset {
1239 let n = ((offset - self.at) as usize).min(buf.len());
1240 self.fill(&mut buf[..n])?;
1241 }
1242 Ok(())
1243 }
1244
1245 fn values<T, const N: usize>(
1247 &mut self,
1248 count: usize,
1249 le: fn([u8; N]) -> T,
1250 ) -> Result<Vec<T>, DecodeError> {
1251 let mut out = Vec::with_capacity(count);
1252 let mut buf = vec![0; BLOCK.min(count * N)];
1253 while out.len() < count {
1254 let n = ((count - out.len()) * N).min(buf.len());
1255 self.fill(&mut buf[..n])?;
1256 out.extend(read(&buf[..n], le));
1257 }
1258 Ok(out)
1259 }
1260}
1261
1262impl<R: Read> Source<R> {
1263 fn section(
1267 &mut self,
1268 kind: u32,
1269 width: u64,
1270 offset: u64,
1271 count: u64,
1272 ) -> Result<Section, DecodeError> {
1273 let n = usize::try_from(count).map_err(|e| e.to_string())?;
1274 Ok(match (kind, width) {
1275 (OUT_OFFSETS | IN_OFFSETS, 8) => Section::U64(self.values(n, u64::from_le_bytes)?),
1276 (OUT_TARGETS | OUT_EDGE_IDS | IN_TARGETS | IN_EDGE_IDS, 4) => {
1277 Section::U32(self.values(n, u32::from_le_bytes)?)
1278 }
1279 (IDS_INT64, 8) => Section::I64(self.values(n, i64::from_le_bytes)?),
1280 (WEIGHTS_F64, 8) => Section::F64(self.values(n, f64::from_le_bytes)?),
1281 (IDS_STR_OFFSETS, 4) => Section::I32(self.values(n, i32::from_le_bytes)?),
1282 (IDS_STR_BYTES | KEPT_ROWS, 1) => Section::Bytes(self.bytes(n)?),
1283 _ => {
1284 self.skip_to(offset + width * count)?;
1285 Section::Bytes(Vec::new())
1286 }
1287 })
1288 }
1289}
1290
1291pub enum Section {
1293 U64(Vec<u64>),
1294 F64(Vec<f64>),
1295 U32(Vec<u32>),
1296 I64(Vec<i64>),
1297 I32(Vec<i32>),
1298 Bytes(Vec<u8>),
1299}
1300
1301#[derive(Debug, Clone, Copy)]
1303struct Entry {
1304 kind: u32,
1305 width: u64,
1306 offset: u64,
1307 count: u64,
1308 crc: u32,
1310}
1311
1312impl Entry {
1313 fn range(&self) -> Range<usize> {
1314 self.offset as usize..(self.offset + self.width * self.count) as usize
1316 }
1317}
1318
1319struct Head {
1321 version: u32,
1322 flags: u32,
1323 n_nodes: usize,
1324 n_edges: usize,
1325 n_dropped: u64,
1326 main_len: u64,
1327 table_end: u64,
1329 sections: Vec<Entry>,
1331 crc: u32,
1333}
1334
1335fn read_head<R: Read + Seek>(file: &mut R, len: u64, key: &IndexKey) -> Result<Head, DecodeError> {
1340 let read = |file: &mut R, at: u64, n: u64| -> Result<Vec<u8>, DecodeError> {
1341 file.seek(SeekFrom::Start(at)).map_err(|e| e.to_string())?;
1342 let mut buf = vec![0; usize::try_from(n).map_err(|e| e.to_string())?];
1343 file.read_exact(&mut buf).map_err(|e| match e.kind() {
1344 io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1345 _ => e.to_string(),
1346 })?;
1347 Ok(buf)
1348 };
1349 if len < HEADER_LEN + TRAILER_LEN {
1350 return Err(format!("{len} bytes is too short for an index file"));
1351 }
1352 let header = read(file, 0, HEADER_LEN)?;
1353 if header[..8] != MAGIC {
1354 return Err("not an Ursa index file".into());
1355 }
1356 let version = u32_at(&header, 8);
1357 if ![VERSION, VERSION_3, VERSION_2].contains(&version) {
1358 return Err(format!(
1359 "index format version {version}; this build reads {VERSION_2} to {VERSION}"
1360 ));
1361 }
1362 let flags = u32_at(&header, 12);
1363 let n_nodes = usize::try_from(u64_at(&header, 16)).map_err(|e| e.to_string())?;
1364 let n_edges = usize::try_from(u64_at(&header, 24)).map_err(|e| e.to_string())?;
1365 let key_len = u64_at(&header, 32);
1366 let n_sections = u32_at(&header, 40) as u64;
1367 let main_len = u64_at(&header, 48);
1368 let n_dropped = u64_at(&header, 56);
1369 if main_len > len || main_len < HEADER_LEN + TRAILER_LEN || usize::try_from(main_len).is_err() {
1370 return Err("the file is truncated".into());
1371 }
1372 let body = main_len - TRAILER_LEN;
1373 let key_end = HEADER_LEN
1374 .checked_add(key_len)
1375 .filter(|&end| end <= body)
1376 .ok_or("the key runs past the end of the file")?;
1377 let table = align(key_end, 8);
1378 let entry_len = match version {
1379 VERSION_2 => CHUNK_ENTRY_LEN,
1380 _ => SECTION_ENTRY_LEN,
1381 };
1382 let table_end = n_sections
1383 .checked_mul(entry_len)
1384 .and_then(|n| n.checked_add(table))
1385 .filter(|&end| end <= body)
1386 .ok_or("the section table runs past the end of the file")?;
1387 let rest = read(file, HEADER_LEN, table_end - HEADER_LEN)?;
1388 let trailer = read(file, body, TRAILER_LEN)?;
1389 if trailer[12..] != END_MAGIC || u64_at(&trailer, 0) != main_len {
1390 return Err("the file is truncated".into());
1391 }
1392 let crc = u32_at(&trailer, 8);
1393 if version != VERSION_2 {
1394 let mut meta = crc32fast::Hasher::new();
1395 meta.update(&header);
1396 meta.update(&rest);
1397 if meta.finalize() != crc {
1398 return Err("the checksum does not match".into());
1399 }
1400 if rest[(key_end - HEADER_LEN) as usize..(table - HEADER_LEN) as usize]
1401 .iter()
1402 .any(|&b| b != 0)
1403 {
1404 return Err("the padding is not zero".into());
1405 }
1406 }
1407 let stored: Value = serde_json::from_slice(&rest[..key_len as usize])
1408 .map_err(|e| format!("the key is not JSON: {e}"))?;
1409 if IndexKey::from_json(&stored).as_ref() != Some(key) {
1410 return Err("the file holds an index for another key".into());
1411 }
1412
1413 let entries = &rest[(table - HEADER_LEN) as usize..];
1414 let mut sections = Vec::with_capacity(n_sections as usize);
1415 for entry in entries.chunks_exact(entry_len as usize) {
1416 let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
1417 let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
1418 let crc = match version {
1419 VERSION_2 => 0,
1420 _ => u32_at(entry, 24),
1421 };
1422 width
1423 .checked_mul(count)
1424 .and_then(|n| n.checked_add(offset))
1425 .filter(|&end| offset >= table_end && end <= body)
1426 .ok_or("a section runs past the end of the file")?;
1427 sections.push(Entry {
1428 kind,
1429 width,
1430 offset,
1431 count,
1432 crc,
1433 });
1434 }
1435 sections.sort_by_key(|e| e.offset);
1436 if sections
1437 .windows(2)
1438 .any(|w| w[0].offset + w[0].width * w[0].count > w[1].offset)
1439 {
1440 return Err("the sections overlap".into());
1441 }
1442 Ok(Head {
1443 version,
1444 flags,
1445 n_nodes,
1446 n_edges,
1447 n_dropped,
1448 main_len,
1449 table_end,
1450 sections,
1451 crc,
1452 })
1453}
1454
1455fn deferred_kind(kind: u32) -> Option<&'static str> {
1458 match kind {
1459 OUT_TARGETS => Some("targets"),
1460 OUT_EDGE_IDS => Some("edge ids"),
1461 _ => None,
1462 }
1463}
1464
1465fn scalars<T: ArrowNativeType>(data: &Buffer, entry: &Entry) -> ScalarBuffer<T> {
1467 let size = std::mem::size_of::<T>();
1468 debug_assert_eq!(entry.width as usize, size);
1469 ScalarBuffer::new(
1472 data.clone(),
1473 entry.offset as usize / size,
1474 entry.count as usize,
1475 )
1476}
1477
1478type Parsed = (Topology, IdMap, MainPart, Dropped, Vec<Region>);
1480
1481fn parse(head: &Head, data: &Buffer, mapped: bool) -> Result<Parsed, DecodeError> {
1485 let main_len = head.main_len as usize;
1486 if data.len() < main_len {
1487 return Err("the file is truncated".into());
1488 }
1489 let bytes = &data.as_slice()[..main_len];
1490 let body = main_len - TRAILER_LEN as usize;
1491 let mut deferred = Vec::new();
1492 if head.version == VERSION_2 {
1493 if super::mapped::crc(&bytes[..body]) != head.crc {
1494 return Err("the checksum does not match".into());
1495 }
1496 } else {
1497 let mut at = head.table_end as usize;
1499 for entry in &head.sections {
1500 let range = entry.range();
1501 if bytes[at..range.start].iter().any(|&b| b != 0) {
1502 return Err("the padding is not zero".into());
1503 }
1504 at = range.end;
1505 match deferred_kind(entry.kind).filter(|_| mapped) {
1506 Some(what) => deferred.push(Region {
1507 what,
1508 range,
1509 crc: entry.crc,
1510 }),
1511 None => {
1512 if super::mapped::crc(&bytes[range]) != entry.crc {
1513 return Err(format!(
1514 "the checksum of section {} does not match",
1515 entry.kind
1516 ));
1517 }
1518 }
1519 }
1520 }
1521 if bytes[at..body].iter().any(|&b| b != 0) {
1522 return Err("the padding is not zero".into());
1523 }
1524 }
1525
1526 let (n_nodes, n_edges) = (head.n_nodes, head.n_edges);
1527 let take = |kind: u32, width: u64, count: Option<usize>| -> Result<Entry, DecodeError> {
1528 let mut found = head.sections.iter().filter(|e| e.kind == kind);
1529 let entry = found
1530 .next()
1531 .ok_or_else(|| format!("section {kind} is missing"))?;
1532 if found.next().is_some() || entry.width != width {
1533 return Err(format!("section {kind} is malformed"));
1534 }
1535 if count.is_some_and(|count| entry.count != count as u64) {
1536 return Err(format!("section {kind} has the wrong length"));
1537 }
1538 Ok(*entry)
1539 };
1540 let out = Adjacency {
1541 offsets: scalars(data, &take(OUT_OFFSETS, 8, Some(n_nodes + 1))?),
1542 targets: scalars(data, &take(OUT_TARGETS, 4, Some(n_edges))?),
1543 edge_ids: scalars(data, &take(OUT_EDGE_IDS, 4, Some(n_edges))?),
1544 };
1545 let topology = match head.version {
1546 VERSION_2 => Topology::from_parts(n_nodes, out, None)?,
1548 _ => Topology::from_checksummed_parts(n_nodes, out)?,
1549 };
1550
1551 let ids: Arc<dyn Array> = if head.flags & FLAG_STRING_IDS == 0 {
1552 let values = scalars::<i64>(data, &take(IDS_INT64, 8, Some(n_nodes))?);
1553 Arc::new(Int64Array::new(values, None))
1554 } else {
1555 let offsets = scalars::<i32>(data, &take(IDS_STR_OFFSETS, 4, Some(n_nodes + 1))?);
1556 let strings = take(IDS_STR_BYTES, 1, None)?;
1557 if offsets[0] != 0
1558 || offsets.windows(2).any(|w| w[0] > w[1])
1559 || offsets[n_nodes] as u64 != strings.count
1560 {
1561 return Err("the string ids' offsets are malformed".into());
1562 }
1563 let values = data.slice_with_length(strings.offset as usize, strings.count as usize);
1564 if !super::mapped::are_strings(&values, &offsets) {
1565 return Err("the string ids are malformed: they are not UTF-8".into());
1566 }
1567 Arc::new(unsafe { StringArray::new_unchecked(OffsetBuffer::new(offsets), values, None) })
1571 };
1572 let table = match head.version {
1575 VERSION => {
1576 let slots = usize::try_from(lookup_table_len(n_nodes)).map_err(|e| e.to_string())?;
1577 Some(scalars::<u32>(data, &take(ID_TABLE, 4, Some(slots))?))
1578 }
1579 _ => None,
1580 };
1581 let ids = IdMap::from_stored_ids(ids, table).map_err(|e| e.to_string())?;
1582 if ids.len() != n_nodes {
1583 return Err("the id map does not match the topology".into());
1584 }
1585 let dropped = match head.n_dropped {
1586 0 => Dropped::default(),
1587 n_dropped => {
1588 let rows = usize::try_from(n_dropped)
1589 .ok()
1590 .and_then(|d| d.checked_add(n_edges))
1591 .ok_or("the kept rows are malformed")?;
1592 let bits = take(KEPT_ROWS, 1, Some(rows.div_ceil(8)))?;
1593 let bits = data.slice_with_length(bits.offset as usize, bits.count as usize);
1594 let kept = BooleanBuffer::new(bits, 0, rows);
1595 if kept.count_set_bits() != n_edges {
1596 return Err("the kept rows do not match the edges".into());
1597 }
1598 Dropped {
1599 n_dropped,
1600 kept: Some(kept),
1601 }
1602 }
1603 };
1604 let main = MainPart {
1605 len: head.main_len,
1606 crc: head.crc,
1607 };
1608 Ok((topology, ids, main, dropped, deferred))
1609}
1610
1611fn mapped_incoming(
1615 data: &Buffer,
1616 chunk: &ChunkInfo,
1617 n_nodes: usize,
1618 n_edges: usize,
1619) -> Result<Adjacency, DecodeError> {
1620 if (data.len() as u64) < chunk.end {
1621 return Err("the file is shorter than the chunk".into());
1622 }
1623 let entry = |kind: u32, width: u64, count: usize| -> Result<Entry, DecodeError> {
1624 let mut found = chunk.sections.iter().filter(|s| s.0 == kind);
1625 match (found.next(), found.next()) {
1626 (Some(&(kind, w, offset, c)), None) if w == width && c == count as u64 => Ok(Entry {
1627 kind,
1628 width,
1629 offset,
1630 count: c,
1631 crc: 0,
1632 }),
1633 _ => Err("the in-adjacency is malformed".into()),
1634 }
1635 };
1636 Ok(Adjacency {
1637 offsets: scalars(data, &entry(IN_OFFSETS, 8, n_nodes + 1)?),
1638 targets: scalars(data, &entry(IN_TARGETS, 4, n_edges)?),
1639 edge_ids: scalars(data, &entry(IN_EDGE_IDS, 4, n_edges)?),
1640 })
1641}
1642
1643fn u64_at(bytes: &[u8], at: usize) -> u64 {
1644 u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"))
1645}
1646
1647fn read<T, const N: usize>(
1649 bytes: &[u8],
1650 le: fn([u8; N]) -> T,
1651) -> impl Iterator<Item = T> + use<'_, T, N> {
1652 bytes
1653 .chunks_exact(N)
1654 .map(move |c| le(c.try_into().expect("N bytes")))
1655}
1656
1657#[cfg(test)]
1658mod tests {
1659 use super::*;
1660 use datafusion::arrow::array::ArrayRef;
1661 use datafusion::arrow::datatypes::DataType;
1662
1663 fn key() -> IndexKey {
1664 IndexKey::new(
1665 "Projection: src, dst\n TableScan: ties".into(),
1666 vec![FileIdentity {
1667 store: "file:///".into(),
1668 location: "data/edges.parquet".into(),
1669 size: 1234,
1670 modified: 1_700_000_000_000_000_000,
1671 e_tag: Some("\"abc\"".into()),
1672 }],
1673 )
1674 }
1675
1676 fn built(src: ArrayRef, dst: ArrayRef) -> (Arc<Topology>, Arc<IdMap>) {
1677 ursa_io::build_topology_batches(&[(src.as_ref(), dst.as_ref())]).unwrap()
1678 }
1679
1680 fn encode(key: &IndexKey, topology: &Topology, ids: &IdMap) -> Vec<u8> {
1681 let encoded = Encoded::new(key, topology, ids).unwrap();
1682 let mut bytes = Vec::new();
1683 encoded.write_to(&mut bytes).unwrap();
1684 assert_eq!(bytes.len() as u64, encoded.file_size());
1685 bytes
1686 }
1687
1688 fn same(a: &Topology, b: &Topology) {
1689 assert_eq!(a.n_nodes(), b.n_nodes());
1690 assert_eq!(a.out().offsets, b.out().offsets);
1691 assert_eq!(a.out().targets, b.out().targets);
1692 assert_eq!(a.out().edge_ids, b.out().edge_ids);
1693 }
1694
1695 #[test]
1696 fn int_and_string_indexes_round_trip() {
1697 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1698 let (topology, ids) = built(ints(&[10, 20, 10, 30]), ints(&[20, 30, 30, 10]));
1699 let bytes = encode(&key(), &topology, &ids);
1700 assert_eq!(&bytes[..8], b"URSAIDX\0");
1701 let (back, back_ids) = decode(&bytes, &key()).unwrap();
1702 same(&topology, &back);
1703 assert!(back.incoming_if_built().is_none());
1704 assert_eq!(
1705 back_ids.user_id_array().as_ref(),
1706 ids.user_id_array().as_ref()
1707 );
1708
1709 topology.incoming();
1711 assert_eq!(encode(&key(), &topology, &ids), bytes);
1712
1713 let strs = |v: &[&str]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
1714 let (topology, ids) = built(strs(&["a", "bé", "a"]), strs(&["bé", "c", "c"]));
1715 let bytes = encode(&key(), &topology, &ids);
1716 let (back, back_ids) = decode(&bytes, &key()).unwrap();
1717 same(&topology, &back);
1718 assert_eq!(
1719 back_ids.user_id_array().as_ref(),
1720 ids.user_id_array().as_ref()
1721 );
1722
1723 let n_sections = u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize;
1725 let table = align(HEADER_LEN + u64_at(&bytes, 32), 8) as usize;
1726 for i in 0..n_sections {
1727 let entry = table + 32 * i;
1728 let (width, offset) = (
1729 u32_at(&bytes, entry + 4) as usize,
1730 u64_at(&bytes, entry + 8),
1731 );
1732 let count = u64_at(&bytes, entry + 16) as usize;
1733 assert_eq!(offset % 64, 0);
1734 let section = &bytes[offset as usize..offset as usize + width * count];
1735 assert_eq!(u32_at(&bytes, entry + 24), crc32fast::hash(section));
1736 }
1737 }
1738
1739 #[test]
1740 fn the_rows_a_vertex_table_left_out_round_trip() {
1741 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1742 let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
1743 let kept = BooleanBuffer::from(vec![true, false, false, true]);
1745 let encoded = Encoded::with_dropped(&key(), &topology, &ids, 2, Some(&kept)).unwrap();
1746 let mut bytes = Vec::new();
1747 encoded.write_to(&mut bytes).unwrap();
1748 let (back, _, _, dropped) = decode_main(&bytes, &key()).unwrap();
1749 same(&topology, &back);
1750 assert_eq!(dropped.n_dropped, 2);
1751 assert_eq!(dropped.kept, Some(kept));
1752 let plain = encode(&key(), &topology, &ids);
1754 let (_, _, _, none) = decode_main(&plain, &key()).unwrap();
1755 assert_eq!((none.n_dropped, none.kept), (0, None));
1756 }
1757
1758 #[test]
1759 fn an_empty_index_round_trips() {
1760 let (topology, ids) =
1761 ursa_io::topology::empty_topology(&datafusion::arrow::datatypes::DataType::Utf8);
1762 let (back, back_ids) = decode(&encode(&key(), &topology, &ids), &key()).unwrap();
1763 assert_eq!((back.n_nodes(), back.n_edges()), (0, 0));
1764 assert!(back_ids.is_empty());
1765 }
1766
1767 #[test]
1768 fn corruption_truncation_and_another_key_are_errors() {
1769 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1770 let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1771 let bytes = encode(&key(), &topology, &ids);
1772 for cut in [0, 10, 64, bytes.len() / 2, bytes.len() - 1] {
1773 assert!(decode(&bytes[..cut], &key()).is_err(), "cut at {cut}");
1774 }
1775 for at in [9, 70, bytes.len() / 2, bytes.len() - 20] {
1776 let mut flipped = bytes.clone();
1777 flipped[at] ^= 0x40;
1778 assert!(decode(&flipped, &key()).is_err(), "flipped at {at}");
1779 }
1780 let mut other = key();
1781 other.files[0].size += 1;
1782 assert_eq!(
1783 decode(&bytes, &other).unwrap_err(),
1784 "the file holds an index for another key"
1785 );
1786 assert!(decode(
1787 b"not an index at all, just some text..........................................",
1788 &key()
1789 )
1790 .is_err());
1791 }
1792
1793 fn write_main(path: &Path, topology: &Topology, ids: &IdMap) -> MainPart {
1795 let encoded = Encoded::new(&key(), topology, ids).unwrap();
1796 let mut file = File::create(path).unwrap();
1797 encoded.write_to(&mut file).unwrap()
1798 }
1799
1800 #[test]
1801 fn the_in_adjacency_is_appended_and_read_on_first_demand() {
1802 let dir = tempfile::tempdir().unwrap();
1803 let path = dir.path().join("x.idx");
1804 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1805 let (topology, ids) = built(
1806 ints(&[10, 20, 10, 30, 20, 40]),
1807 ints(&[20, 30, 30, 10, 40, 10]),
1808 );
1809 let main = write_main(&path, &topology, &ids);
1810 assert_eq!(main.len, std::fs::metadata(&path).unwrap().len());
1811
1812 let reads = thread_incoming_reads();
1814 let stored = read_file(&path, &key()).unwrap();
1815 assert!(stored.chunks.is_empty());
1816 assert_eq!(
1817 stored.topology.incoming().targets,
1818 topology.incoming().targets
1819 );
1820 assert_eq!(thread_incoming_reads(), reads);
1821
1822 let incoming = topology.incoming().clone();
1824 let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1825 EncodedChunk::incoming(&incoming, at)
1826 })
1827 .unwrap()
1828 .unwrap();
1829 assert_eq!(end, std::fs::metadata(&path).unwrap().len());
1830 let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1831 EncodedChunk::incoming(&incoming, at)
1832 });
1833 assert_eq!(again.unwrap(), None);
1834
1835 let stored = read_file(&path, &key()).unwrap();
1836 assert_eq!(stored.chunks.len(), 1);
1837 assert_eq!(stored.main, main);
1838 same(&topology, &stored.topology);
1839 assert!(stored.topology.incoming_if_built().is_none());
1841 let back = stored.topology.incoming();
1842 assert!(thread_incoming_reads() > reads);
1843 assert_eq!(
1844 (&back.offsets, &back.targets, &back.edge_ids),
1845 (&incoming.offsets, &incoming.targets, &incoming.edge_ids)
1846 );
1847 let bytes = std::fs::read(&path).unwrap();
1849 let (main_only, _) = decode(&bytes, &key()).unwrap();
1850 same(&topology, &main_only);
1851 }
1852
1853 #[test]
1854 fn a_damaged_chunk_is_ignored_and_replaced() {
1855 let dir = tempfile::tempdir().unwrap();
1856 let path = dir.path().join("x.idx");
1857 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1858 let (topology, ids) = built(ints(&[1, 2, 3, 1]), ints(&[2, 3, 1, 3]));
1859 let main = write_main(&path, &topology, &ids);
1860 let incoming = topology.incoming().clone();
1861 let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1862 EncodedChunk::incoming(&incoming, at)
1863 })
1864 .unwrap()
1865 .unwrap();
1866 let good = std::fs::read(&path).unwrap();
1867
1868 let mut bytes = good.clone();
1871 bytes[main.len as usize + 64] ^= 0x01;
1872 std::fs::write(&path, &bytes).unwrap();
1873 let stored = read_file(&path, &key()).unwrap();
1874 assert_eq!(stored.chunks.len(), 1);
1875 assert!(read_chunk(&path, main, &stored.chunks[0]).is_err());
1876 assert_eq!(stored.topology.incoming().targets, incoming.targets);
1877 assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
1878
1879 std::fs::write(&path, &good[..good.len() - 10]).unwrap();
1882 assert!(read_file(&path, &key()).unwrap().chunks.is_empty());
1883 let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1884 EncodedChunk::incoming(&incoming, at)
1885 })
1886 .unwrap();
1887 assert_eq!(again, Some(end));
1888 assert_eq!(std::fs::read(&path).unwrap(), good);
1889
1890 let other = MainPart {
1892 crc: main.crc ^ 1,
1893 ..main
1894 };
1895 assert!(append_chunk(&path, other, CHUNK_INCOMING, b"", |at| {
1896 EncodedChunk::incoming(&incoming, at)
1897 })
1898 .is_err());
1899 let chunk = &read_file(&path, &key()).unwrap().chunks[0];
1900 assert!(read_chunk(&path, other, chunk).is_err());
1901 assert!(read_chunk(&path, main, chunk).is_ok());
1902 }
1903
1904 #[test]
1905 fn weight_chunks_round_trip_by_key() {
1906 let dir = tempfile::tempdir().unwrap();
1907 let path = dir.path().join("x.idx");
1908 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1909 let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1910 let main = write_main(&path, &topology, &ids);
1911 let (a, b) = (vec![0.5, 1.0, f64::MAX], vec![2.0, 0.0, 1e-300]);
1912 for (key, columns) in [("w1", vec![&a[..]]), ("w2", vec![&a[..], &b[..]])] {
1913 let appended = append_chunk(&path, main, CHUNK_WEIGHTS, key.as_bytes(), |at| {
1914 EncodedChunk::weights(key, &columns, at)
1915 });
1916 assert!(appended.unwrap().is_some());
1917 }
1918 let stored = read_file(&path, &key()).unwrap();
1919 assert_eq!(stored.chunks.len(), 2);
1920 let chunk = |name: &[u8]| stored.chunks.iter().find(|c| c.name == name).unwrap();
1921 assert_eq!(
1922 read_weights(&path, main, chunk(b"w1"), 3).unwrap(),
1923 std::slice::from_ref(&a)
1924 );
1925 assert_eq!(read_weights(&path, main, chunk(b"w2"), 3).unwrap(), [a, b]);
1926 assert!(read_weights(&path, main, chunk(b"w1"), 4).is_err());
1928 }
1929
1930 fn section_of(bytes: &[u8], kind: u32) -> (usize, usize) {
1933 let n_sections = u32_at(bytes, 40) as usize;
1934 let table = align(HEADER_LEN + u64_at(bytes, 32), 8) as usize;
1935 (0..n_sections)
1936 .map(|i| table + 32 * i)
1937 .find(|&entry| u32_at(bytes, entry) == kind)
1938 .map(|entry| {
1939 let width = u32_at(bytes, entry + 4) as usize;
1940 let count = u64_at(bytes, entry + 16) as usize;
1941 (u64_at(bytes, entry + 8) as usize, width * count)
1942 })
1943 .unwrap()
1944 }
1945
1946 fn a_graph() -> (Arc<Topology>, Arc<IdMap>) {
1947 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1948 built(
1949 ints(&[10, 20, 10, 30, 20, 40, 40, 50]),
1950 ints(&[20, 30, 30, 10, 40, 10, 50, 10]),
1951 )
1952 }
1953
1954 #[test]
1955 fn a_version_2_file_from_0_10_is_read_whole_and_checked() {
1956 let dir = tempfile::tempdir().unwrap();
1957 let path = dir.path().join("x.idx");
1958 let (topology, ids) = a_graph();
1959 let encoded = Encoded::new(&key(), &topology, &ids)
1960 .unwrap()
1961 .as_version_2();
1962 let mut v2 = Vec::new();
1963 let main = encoded.write_to(&mut v2).unwrap();
1964 assert_eq!(u32_at(&v2, 8), VERSION_2);
1965 assert_eq!(main.crc, crc32fast::hash(&v2[..v2.len() - 16]));
1966 std::fs::write(&path, &v2).unwrap();
1967 let stored = read_file(&path, &key()).unwrap();
1968 assert_eq!(stored.version, VERSION_2);
1969 assert!(stored.unverified.is_none());
1971 assert_eq!(stored.main, main);
1972 same(&topology, &stored.topology);
1973 assert_eq!(
1974 stored.ids.user_id_array().as_ref(),
1975 ids.user_id_array().as_ref()
1976 );
1977 let incoming = topology.incoming().clone();
1979 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1980 EncodedChunk::incoming(&incoming, at)
1981 })
1982 .unwrap()
1983 .unwrap();
1984 let stored = read_file(&path, &key()).unwrap();
1985 assert_eq!(stored.topology.incoming().targets, incoming.targets);
1986
1987 for at in [9, 70, v2.len() / 2, v2.len() - 20] {
1989 let mut flipped = v2.clone();
1990 flipped[at] ^= 0x40;
1991 std::fs::write(&path, &flipped).unwrap();
1992 assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
1993 }
1994 for cut in [0, 10, 64, v2.len() / 2, v2.len() - 1] {
1995 std::fs::write(&path, &v2[..cut]).unwrap();
1996 assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
1997 }
1998 }
1999
2000 fn graphs() -> [(Arc<Topology>, Arc<IdMap>); 2] {
2002 let n = 300i64;
2003 let (src, dst): (Vec<i64>, Vec<i64>) = (0..n)
2004 .map(|i| (i * 7 - 50, ((i * 13) % n) * 7 - 50))
2005 .unzip();
2006 let name = |v: &[i64]| -> ArrayRef {
2007 Arc::new(StringArray::from(
2008 v.iter()
2009 .map(|i| format!("did:plc:{i:024}"))
2010 .collect::<Vec<_>>(),
2011 ))
2012 };
2013 [
2014 built(name(&src), name(&dst)),
2015 built(
2016 Arc::new(Int64Array::from(src)),
2017 Arc::new(Int64Array::from(dst)),
2018 ),
2019 ]
2020 }
2021
2022 fn finds_every_id(stored: &IdMap, ids: &IdMap) {
2025 let column = ids.user_id_array();
2026 assert_eq!(stored.user_id_array().as_ref(), column.as_ref());
2027 let expected: Vec<Option<u32>> = (0..ids.len() as u32).map(Some).collect();
2028 assert_eq!(stored.dense_from_array(column.as_ref()).unwrap(), expected);
2029 let missing: ArrayRef = match column.data_type() {
2030 DataType::Int64 => Arc::new(Int64Array::from(vec![i64::MAX])),
2031 _ => Arc::new(StringArray::from(vec!["nobody"])),
2032 };
2033 assert_eq!(stored.dense_from_array(&missing).unwrap(), vec![None]);
2034 }
2035
2036 #[test]
2039 fn the_id_lookup_table_is_stored_and_used_as_it_lies() {
2040 let dir = tempfile::tempdir().unwrap();
2041 let path = dir.path().join("x.idx");
2042 for (topology, ids) in graphs() {
2043 let bytes = encode(&key(), &topology, &ids);
2044 assert_eq!(u32_at(&bytes, 8), VERSION);
2045 let (at, len) = section_of(&bytes, ID_TABLE);
2046 let table = ids.lookup_table().unwrap();
2047 assert_eq!(len, 4 * table.len());
2048 assert_eq!(len as u64, 4 * lookup_table_len(ids.len()));
2049 let stored_table: Vec<u32> = read(&bytes[at..at + len], u32::from_le_bytes).collect();
2050 assert_eq!(stored_table, table.as_ref());
2051
2052 std::fs::write(&path, &bytes).unwrap();
2053 let stored = read_file(&path, &key()).unwrap();
2054 assert_eq!(stored.version, VERSION);
2055 finds_every_id(&stored.ids, &ids);
2056 let loaded = stored.ids.lookup_table().unwrap();
2059 assert_eq!(loaded, table);
2060 if super::super::mapped::MAPS {
2061 let mapped = stored.unverified.as_ref().unwrap();
2062 assert!(mapped.holds(loaded.inner().as_ptr()));
2063 let column = stored.ids.user_id_array().to_data();
2065 assert!(mapped.holds(column.buffers()[0].as_ptr()));
2066 }
2067 assert_eq!(encode(&key(), &stored.topology, &stored.ids), bytes);
2069 let mut flipped = bytes.clone();
2073 flipped[at + len / 2] ^= 1;
2074 std::fs::write(&path, &flipped).unwrap();
2075 assert!(read_file(&path, &key()).is_err());
2076 }
2077 }
2078
2079 #[test]
2082 fn a_version_3_file_from_0_11_is_read_and_its_lookup_table_built_on_demand() {
2083 let dir = tempfile::tempdir().unwrap();
2084 let path = dir.path().join("x.idx");
2085 for (topology, ids) in graphs() {
2086 let v4 = encode(&key(), &topology, &ids);
2087 let encoded = Encoded::new(&key(), &topology, &ids)
2088 .unwrap()
2089 .as_version_3();
2090 let mut v3 = Vec::new();
2091 let main = encoded.write_to(&mut v3).unwrap();
2092 assert_eq!(v3.len() as u64, encoded.file_size());
2093 assert_eq!(u32_at(&v3, 8), VERSION_3);
2094 assert!(v3.len() < v4.len());
2095 let n_sections = u32_at(&v3, 40) as usize;
2096 let table = align(HEADER_LEN + u64_at(&v3, 32), 8) as usize;
2097 assert!((0..n_sections).all(|i| u32_at(&v3, table + 32 * i) != ID_TABLE));
2098
2099 std::fs::write(&path, &v3).unwrap();
2100 let stored = read_file(&path, &key()).unwrap();
2101 assert_eq!(stored.version, VERSION_3);
2102 assert_eq!(stored.main, main);
2103 assert_eq!(stored.unverified.is_some(), super::super::mapped::MAPS);
2104 same(&topology, &stored.topology);
2105 finds_every_id(&stored.ids, &ids);
2106 assert_eq!(encode(&key(), &stored.topology, &stored.ids), v4);
2108
2109 let incoming = topology.incoming().clone();
2111 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2112 EncodedChunk::incoming(&incoming, at)
2113 })
2114 .unwrap()
2115 .unwrap();
2116 let stored = read_file(&path, &key()).unwrap();
2117 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2118 }
2119 }
2120
2121 #[test]
2125 fn an_id_stored_twice_is_an_error() {
2126 let (topology, _) = a_graph();
2127 let n = topology.n_nodes();
2128 let twice: ArrayRef = Arc::new(Int64Array::from(vec![7i64; n]));
2129 let ids = IdMap::from_stored_ids(Arc::clone(&twice), None).unwrap();
2130 let mut out = Vec::new();
2131 let err = Encoded::new(&key(), &topology, &ids)
2132 .unwrap()
2133 .write_to(&mut out)
2134 .unwrap_err();
2135 assert!(err.to_string().contains("twice"), "{err}");
2136 let mut v3 = Vec::new();
2137 Encoded::new(&key(), &topology, &ids)
2138 .unwrap()
2139 .as_version_3()
2140 .write_to(&mut v3)
2141 .unwrap();
2142 let (_, back) = decode(&v3, &key()).unwrap();
2143 assert_eq!(back.len(), n);
2144 assert!(back.dense_from_array(&twice).is_err());
2145 }
2146
2147 #[test]
2148 fn a_truncated_or_damaged_version_3_file_is_an_error_never_a_crash() {
2149 let dir = tempfile::tempdir().unwrap();
2150 let path = dir.path().join("x.idx");
2151 let (topology, ids) = a_graph();
2152 let main = write_main(&path, &topology, &ids);
2153 let incoming = topology.incoming().clone();
2154 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2155 EncodedChunk::incoming(&incoming, at)
2156 })
2157 .unwrap();
2158 let good = std::fs::read(&path).unwrap();
2159 let main_len = main.len as usize;
2160 for cut in (0..main_len).step_by(7).chain([main_len - 1]) {
2163 std::fs::write(&path, &good[..cut]).unwrap();
2164 assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
2165 }
2166 std::fs::write(&path, &good[..good.len() - 1]).unwrap();
2168 let stored = read_file(&path, &key()).unwrap();
2169 assert!(stored.chunks.is_empty());
2170 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2171 let (targets, t_len) = section_of(&good, OUT_TARGETS);
2175 let (edge_ids, e_len) = section_of(&good, OUT_EDGE_IDS);
2176 let edge_arrays = |at: usize| {
2177 (targets..targets + t_len).contains(&at) || (edge_ids..edge_ids + e_len).contains(&at)
2178 };
2179 for at in (0..main_len).filter(|&at| !edge_arrays(at)) {
2180 let mut flipped = good.clone();
2181 flipped[at] ^= 0x10;
2182 std::fs::write(&path, &flipped).unwrap();
2183 assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
2184 }
2185 }
2186
2187 #[test]
2188 fn the_edge_arrays_checksums_are_checked_before_a_whole_read() {
2189 let dir = tempfile::tempdir().unwrap();
2190 let path = dir.path().join("x.idx");
2191 let (topology, ids) = a_graph();
2192 let main = write_main(&path, &topology, &ids);
2193 let good = std::fs::read(&path).unwrap();
2194 let stored = read_file(&path, &key()).unwrap();
2195 same(&topology, &stored.topology);
2196 if let Some(checks) = &stored.unverified {
2197 checks.verify().unwrap();
2198 }
2199
2200 for kind in [OUT_TARGETS, OUT_EDGE_IDS] {
2201 let (at, _) = section_of(&good, kind);
2202 let mut flipped = good.clone();
2203 flipped[at] ^= 0x01;
2205 std::fs::write(&path, &flipped).unwrap();
2206 assert!(decode(&flipped, &key()).is_err());
2208 match read_file(&path, &key()) {
2209 Ok(stored) => {
2211 let checks = stored.unverified.expect("a mapped file defers");
2212 assert!(!checks.is_damaged());
2213 let why = checks.verify().unwrap_err();
2214 assert!(why.contains("does not match"), "{why}");
2215 assert!(checks.is_damaged());
2216 }
2217 Err(e) if !super::super::mapped::MAPS => {
2219 assert!(e.contains("does not match"), "{e}")
2220 }
2221 Err(e) => panic!("{e}"),
2222 }
2223 }
2224
2225 std::fs::write(&path, &good).unwrap();
2228 let incoming = topology.incoming().clone();
2229 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2230 EncodedChunk::incoming(&incoming, at)
2231 })
2232 .unwrap();
2233 let mut bytes = std::fs::read(&path).unwrap();
2234 let chunk = read_file(&path, &key()).unwrap().chunks[0].clone();
2235 let (_, _, edge_ids, _) = chunk.sections[2];
2236 bytes[edge_ids as usize] ^= 0x01;
2237 std::fs::write(&path, &bytes).unwrap();
2238 let stored = read_file(&path, &key()).unwrap();
2239 if let Some(checks) = &stored.unverified {
2240 checks.verify().unwrap();
2241 }
2242 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2243 assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
2244 }
2245
2246 #[test]
2247 fn a_mapped_index_survives_its_file_being_replaced_or_removed() {
2248 let dir = tempfile::tempdir().unwrap();
2249 let path = dir.path().join("x.idx");
2250 let (topology, ids) = a_graph();
2251 let main = write_main(&path, &topology, &ids);
2252 let incoming = topology.incoming().clone();
2253 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2254 EncodedChunk::incoming(&incoming, at)
2255 })
2256 .unwrap();
2257 let stored = read_file(&path, &key()).unwrap();
2258
2259 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2262 let (other, other_ids) = built(ints(&[7, 8, 9]), ints(&[8, 9, 7]));
2263 let temp = dir.path().join("x.idx.tmp");
2264 write_main(&temp, &other, &other_ids);
2265 std::fs::rename(&temp, &path).unwrap();
2266 assert_eq!(read_file(&path, &key()).unwrap().topology.n_nodes(), 3);
2267
2268 same(&topology, &stored.topology);
2271 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2272 if let Some(checks) = &stored.unverified {
2273 checks.verify().unwrap();
2274 }
2275 std::fs::remove_file(&path).unwrap();
2277 same(&topology, &stored.topology);
2278 assert_eq!(
2279 stored.ids.user_id_array().as_ref(),
2280 ids.user_id_array().as_ref()
2281 );
2282 }
2283
2284 #[test]
2285 fn a_version_1_file_is_not_read() {
2286 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2287 let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
2288 let mut bytes = encode(&key(), &topology, &ids);
2289 bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
2290 assert_eq!(
2291 decode(&bytes, &key()).unwrap_err(),
2292 "index format version 1; this build reads 2 to 4"
2293 );
2294 }
2295
2296 #[test]
2297 fn keys_round_trip_through_json() {
2298 let k = key();
2299 assert_eq!(IndexKey::from_json(&k.to_json()), Some(k.clone()));
2300 let mut no_tag = k.clone();
2301 no_tag.files[0].e_tag = None;
2302 assert_eq!(IndexKey::from_json(&no_tag.to_json()), Some(no_tag.clone()));
2303 assert_ne!(no_tag.hash(), k.hash());
2304 }
2305
2306 #[test]
2307 fn a_key_of_another_version_is_not_read() {
2308 let mut json = key().to_json();
2309 json["version"] = 1.into();
2310 assert_eq!(IndexKey::from_json(&json), None);
2311 json.as_object_mut().unwrap().remove("version");
2312 assert_eq!(IndexKey::from_json(&json), None);
2313 }
2314}