1use std::fs::{File, OpenOptions};
124use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
125use std::ops::Range;
126use std::path::Path;
127use std::sync::atomic::{AtomicU64, Ordering};
128use std::sync::Arc;
129
130use datafusion::arrow::array::{Array, Int64Array, StringArray};
131use datafusion::arrow::buffer::{BooleanBuffer, Buffer, OffsetBuffer, ScalarBuffer};
132use datafusion::arrow::datatypes::ArrowNativeType;
133use serde_json::{json, Value};
134use ursa_core::{Adjacency, IdMap, Topology};
135
136use super::mapped::{Region, Unverified};
137use crate::graph::FileIdentity;
138
139pub const MAGIC: [u8; 8] = *b"URSAIDX\0";
141const END_MAGIC: [u8; 4] = *b"XDIU";
143pub const VERSION: u32 = 3;
146pub const VERSION_2: u32 = 2;
148const CHUNK_MAGIC: [u8; 4] = *b"CHNK";
150const CHUNK_END_MAGIC: [u8; 4] = *b"KNHC";
152const CHUNK_HEADER_LEN: u64 = 16;
153const CHUNK_TRAILER_LEN: u64 = 48;
154
155pub const CHUNK_INCOMING: u32 = 1;
157pub const CHUNK_WEIGHTS: u32 = 2;
159
160const HEADER_LEN: u64 = 64;
161const TRAILER_LEN: u64 = 16;
162const SECTION_ENTRY_LEN: u64 = 32;
164const CHUNK_ENTRY_LEN: u64 = 24;
166const SECTION_ALIGN: u64 = 64;
167
168const FLAG_STRING_IDS: u32 = 1;
169
170const OUT_OFFSETS: u32 = 1;
171const OUT_TARGETS: u32 = 2;
172const OUT_EDGE_IDS: u32 = 3;
173const IN_OFFSETS: u32 = 4;
174const IN_TARGETS: u32 = 5;
175const IN_EDGE_IDS: u32 = 6;
176const IDS_INT64: u32 = 7;
177const IDS_STR_OFFSETS: u32 = 8;
178const IDS_STR_BYTES: u32 = 9;
179const WEIGHTS_F64: u32 = 10;
180const KEPT_ROWS: u32 = 11;
181
182pub const KEY_VERSION: u64 = 2;
188
189#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct IndexKey {
193 pub fingerprint: String,
194 pub files: Vec<FileIdentity>,
195}
196
197impl IndexKey {
198 pub fn new(fingerprint: String, files: Vec<FileIdentity>) -> Self {
199 Self { fingerprint, files }
200 }
201
202 pub fn to_json(&self) -> Value {
205 let files: Vec<Value> = self
206 .files
207 .iter()
208 .map(|f| {
209 json!({
210 "store": f.store,
211 "location": f.location,
212 "size": f.size,
213 "modified": f.modified,
214 "e_tag": f.e_tag,
215 })
216 })
217 .collect();
218 json!({ "version": KEY_VERSION, "fingerprint": self.fingerprint, "files": files })
219 }
220
221 pub fn from_json(value: &Value) -> Option<Self> {
223 if value.get("version")?.as_u64()? != KEY_VERSION {
224 return None;
225 }
226 let fingerprint = value.get("fingerprint")?.as_str()?.to_string();
227 let files = value
228 .get("files")?
229 .as_array()?
230 .iter()
231 .map(|f| {
232 Some(FileIdentity {
233 store: f.get("store")?.as_str()?.to_string(),
234 location: f.get("location")?.as_str()?.to_string(),
235 size: f.get("size")?.as_u64()?,
236 modified: f.get("modified")?.as_i64()?,
237 e_tag: match f.get("e_tag")? {
238 Value::Null => None,
239 Value::String(s) => Some(s.clone()),
240 _ => return None,
241 },
242 })
243 })
244 .collect::<Option<Vec<_>>>()?;
245 Some(Self { fingerprint, files })
246 }
247
248 pub fn hash(&self) -> u64 {
252 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
253 for b in self.to_json().to_string().bytes() {
254 h ^= u64::from(b);
255 h = h.wrapping_mul(0x0000_0100_0000_01b3);
256 }
257 h
258 }
259}
260
261enum Data<'a> {
264 U64(&'a [u64]),
265 F64(&'a [f64]),
266 U32(&'a [u32]),
267 Ints(Int64Array),
269 StrOffsets(StringArray),
272 StrBytes(StringArray),
274 Bytes(Buffer),
276}
277
278impl Data<'_> {
279 fn width(&self) -> u64 {
280 match self {
281 Data::U64(_) | Data::F64(_) | Data::Ints(_) => 8,
282 Data::U32(_) | Data::StrOffsets(_) => 4,
283 Data::StrBytes(_) | Data::Bytes(_) => 1,
284 }
285 }
286
287 fn count(&self) -> u64 {
288 (match self {
289 Data::U64(v) => v.len(),
290 Data::F64(v) => v.len(),
291 Data::U32(v) => v.len(),
292 Data::Ints(a) => a.len(),
293 Data::StrOffsets(a) => a.len() + 1,
294 Data::StrBytes(a) => str_bytes(a).len(),
295 Data::Bytes(b) => b.len(),
296 }) as u64
297 }
298}
299
300fn str_bytes(strings: &StringArray) -> &[u8] {
302 let offsets = strings.value_offsets();
303 let (first, last) = (offsets[0] as usize, offsets[offsets.len() - 1] as usize);
304 &strings.value_data()[first..last]
305}
306
307fn align(n: u64, to: u64) -> u64 {
308 n.div_ceil(to) * to
309}
310
311pub struct Encoded<'a> {
314 version: u32,
316 flags: u32,
317 n_nodes: u64,
318 n_edges: u64,
319 n_dropped: u64,
320 key: Vec<u8>,
321 sections: Vec<(u32, Data<'a>, u64)>,
322 table_offset: u64,
323 trailer_offset: u64,
324}
325
326impl<'a> Encoded<'a> {
327 pub fn new(key: &IndexKey, topology: &'a Topology, ids: &'a IdMap) -> io::Result<Self> {
330 Self::with_dropped(key, topology, ids, 0, None)
331 }
332
333 pub fn with_dropped(
336 key: &IndexKey,
337 topology: &'a Topology,
338 ids: &'a IdMap,
339 n_dropped: u64,
340 kept: Option<&BooleanBuffer>,
341 ) -> io::Result<Self> {
342 let id_array = ids.user_id_array();
343 let mut flags = 0;
344 let out = topology.out();
345 let mut sections: Vec<(u32, Data<'a>)> = vec![
346 (OUT_OFFSETS, Data::U64(&out.offsets)),
347 (OUT_TARGETS, Data::U32(&out.targets)),
348 (OUT_EDGE_IDS, Data::U32(&out.edge_ids)),
349 ];
350 if let Some(ints) = id_array.as_any().downcast_ref::<Int64Array>() {
352 sections.push((IDS_INT64, Data::Ints(ints.clone())));
353 } else if let Some(strings) = id_array.as_any().downcast_ref::<StringArray>() {
354 flags |= FLAG_STRING_IDS;
355 sections.push((IDS_STR_OFFSETS, Data::StrOffsets(strings.clone())));
356 sections.push((IDS_STR_BYTES, Data::StrBytes(strings.clone())));
357 } else {
358 return Err(io::Error::other(format!(
359 "cannot store node ids of type {}",
360 id_array.data_type()
361 )));
362 }
363 let n_dropped = match kept {
364 Some(kept) if n_dropped > 0 => {
365 sections.push((KEPT_ROWS, Data::Bytes(kept.sliced())));
366 n_dropped
367 }
368 _ => 0,
369 };
370
371 let key = key.to_json().to_string().into_bytes();
372 let (n_nodes, n_edges) = (topology.n_nodes() as u64, topology.n_edges() as u64);
373 Ok(Self::laid_out(
374 VERSION, flags, n_nodes, n_edges, n_dropped, key, sections,
375 ))
376 }
377
378 fn laid_out(
381 version: u32,
382 flags: u32,
383 n_nodes: u64,
384 n_edges: u64,
385 n_dropped: u64,
386 key: Vec<u8>,
387 sections: Vec<(u32, Data<'a>)>,
388 ) -> Self {
389 let entry_len = match version {
390 VERSION_2 => CHUNK_ENTRY_LEN,
391 _ => SECTION_ENTRY_LEN,
392 };
393 let table_offset = align(HEADER_LEN + key.len() as u64, 8);
394 let mut at = table_offset + entry_len * sections.len() as u64;
395 let sections = sections
396 .into_iter()
397 .map(|(kind, data)| {
398 at = align(at, SECTION_ALIGN);
399 let offset = at;
400 at += data.width() * data.count();
401 (kind, data, offset)
402 })
403 .collect();
404 Self {
405 version,
406 flags,
407 n_nodes,
408 n_edges,
409 n_dropped,
410 key,
411 sections,
412 table_offset,
413 trailer_offset: align(at, 8),
414 }
415 }
416
417 #[doc(hidden)]
420 pub fn as_version_2(self) -> Self {
421 let Self {
422 flags,
423 n_nodes,
424 n_edges,
425 n_dropped,
426 key,
427 sections,
428 ..
429 } = self;
430 let sections = sections.into_iter().map(|(k, d, _)| (k, d)).collect();
431 Self::laid_out(VERSION_2, flags, n_nodes, n_edges, n_dropped, key, sections)
432 }
433
434 pub fn file_size(&self) -> u64 {
436 self.trailer_offset + TRAILER_LEN
437 }
438
439 pub fn write_to(&self, out: impl Write) -> io::Result<MainPart> {
441 let v2 = self.version == VERSION_2;
442 let crcs: Vec<Option<u32>> = self
445 .sections
446 .iter()
447 .map(|(_, data, _)| (!v2).then(|| data_crc(data)))
448 .collect();
449 let mut sink = Sink {
450 out,
451 crc: crc32fast::Hasher::new(),
452 at: 0,
453 hash: true,
454 };
455 let mut header = Vec::with_capacity(HEADER_LEN as usize);
456 header.extend_from_slice(&MAGIC);
457 header.extend_from_slice(&self.version.to_le_bytes());
458 header.extend_from_slice(&self.flags.to_le_bytes());
459 header.extend_from_slice(&self.n_nodes.to_le_bytes());
460 header.extend_from_slice(&self.n_edges.to_le_bytes());
461 header.extend_from_slice(&(self.key.len() as u64).to_le_bytes());
462 header.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
463 header.extend_from_slice(&[0; 4]);
464 header.extend_from_slice(&self.file_size().to_le_bytes());
465 header.extend_from_slice(&self.n_dropped.to_le_bytes());
466 header.resize(HEADER_LEN as usize, 0);
467 sink.put(&header)?;
468 sink.put(&self.key)?;
469 sink.pad_to(self.table_offset)?;
470 for ((kind, data, offset), crc) in self.sections.iter().zip(&crcs) {
471 sink.put(§ion_entry(*kind, data, *offset, *crc))?;
472 }
473 let meta_crc = sink.crc.clone().finalize();
476 sink.hash = v2;
477 for (_, data, offset) in &self.sections {
478 sink.pad_to(*offset)?;
479 sink.put_data(data)?;
480 }
481 sink.pad_to(self.trailer_offset)?;
482 let crc = match v2 {
483 true => sink.crc.clone().finalize(),
484 false => meta_crc,
485 };
486 let mut trailer = Vec::with_capacity(TRAILER_LEN as usize);
487 trailer.extend_from_slice(&self.file_size().to_le_bytes());
488 trailer.extend_from_slice(&crc.to_le_bytes());
489 trailer.extend_from_slice(&END_MAGIC);
490 sink.put(&trailer)?;
491 sink.out.flush()?;
492 Ok(MainPart {
493 len: self.file_size(),
494 crc,
495 })
496 }
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
502pub struct MainPart {
503 pub len: u64,
504 pub crc: u32,
505}
506
507pub struct EncodedChunk<'a> {
509 kind: u32,
510 name: Vec<u8>,
511 start: u64,
512 sections: Vec<(u32, Data<'a>, u64)>,
513 name_offset: u64,
514 table_offset: u64,
515}
516
517impl<'a> EncodedChunk<'a> {
518 pub fn incoming(incoming: &'a Adjacency, start: u64) -> Self {
520 Self::new(
521 CHUNK_INCOMING,
522 Vec::new(),
523 vec![
524 (IN_OFFSETS, Data::U64(&incoming.offsets)),
525 (IN_TARGETS, Data::U32(&incoming.targets)),
526 (IN_EDGE_IDS, Data::U32(&incoming.edge_ids)),
527 ],
528 start,
529 )
530 }
531
532 pub fn weights(key: &str, columns: &[&'a [f64]], start: u64) -> Self {
535 Self::new(
536 CHUNK_WEIGHTS,
537 key.as_bytes().to_vec(),
538 columns
539 .iter()
540 .map(|column| (WEIGHTS_F64, Data::F64(column)))
541 .collect(),
542 start,
543 )
544 }
545
546 fn new(kind: u32, name: Vec<u8>, sections: Vec<(u32, Data<'a>)>, start: u64) -> Self {
547 let mut at = start + CHUNK_HEADER_LEN;
548 let sections = sections
549 .into_iter()
550 .map(|(kind, data)| {
551 at = align(at, SECTION_ALIGN);
552 let offset = at;
553 at += data.width() * data.count();
554 (kind, data, offset)
555 })
556 .collect();
557 let name_offset = at;
558 let table_offset = align(name_offset + name.len() as u64, 8);
559 Self {
560 kind,
561 name,
562 start,
563 sections,
564 name_offset,
565 table_offset,
566 }
567 }
568
569 fn trailer_offset(&self) -> u64 {
570 self.table_offset + CHUNK_ENTRY_LEN * self.sections.len() as u64
571 }
572
573 pub fn end(&self) -> u64 {
575 self.trailer_offset() + CHUNK_TRAILER_LEN
576 }
577
578 pub fn size(&self) -> u64 {
580 self.end() - self.start
581 }
582
583 pub fn write_to(&self, out: impl Write) -> io::Result<()> {
585 let mut sink = Sink {
586 out,
587 crc: crc32fast::Hasher::new(),
588 at: self.start,
589 hash: true,
590 };
591 let mut header = Vec::with_capacity(CHUNK_HEADER_LEN as usize);
592 header.extend_from_slice(&CHUNK_MAGIC);
593 header.extend_from_slice(&self.kind.to_le_bytes());
594 header.extend_from_slice(&self.end().to_le_bytes());
595 sink.put(&header)?;
596 for (_, data, offset) in &self.sections {
597 sink.pad_to(*offset)?;
598 sink.put_data(data)?;
599 }
600 sink.pad_to(self.name_offset)?;
601 let data_crc = std::mem::replace(&mut sink.crc, crc32fast::Hasher::new()).finalize();
602 sink.put(&self.name)?;
603 sink.pad_to(self.table_offset)?;
604 for (kind, data, offset) in &self.sections {
605 sink.put(§ion_entry(*kind, data, *offset, None))?;
606 }
607 let mut trailer = Vec::with_capacity(CHUNK_TRAILER_LEN as usize);
608 trailer.extend_from_slice(&self.kind.to_le_bytes());
609 trailer.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
610 trailer.extend_from_slice(&self.start.to_le_bytes());
611 trailer.extend_from_slice(&self.name_offset.to_le_bytes());
612 trailer.extend_from_slice(&(self.name.len() as u64).to_le_bytes());
613 trailer.extend_from_slice(&data_crc.to_le_bytes());
614 sink.crc.update(&trailer);
615 let meta_crc = sink.crc.clone().finalize();
616 trailer.extend_from_slice(&meta_crc.to_le_bytes());
617 trailer.extend_from_slice(&CHUNK_END_MAGIC);
618 trailer.extend_from_slice(&[0; 4]);
619 sink.out.write_all(&trailer)?;
620 sink.out.flush()
621 }
622}
623
624fn section_entry(kind: u32, data: &Data<'_>, offset: u64, crc: Option<u32>) -> Vec<u8> {
627 let mut entry = Vec::with_capacity(SECTION_ENTRY_LEN as usize);
628 entry.extend_from_slice(&kind.to_le_bytes());
629 entry.extend_from_slice(&(data.width() as u32).to_le_bytes());
630 entry.extend_from_slice(&offset.to_le_bytes());
631 entry.extend_from_slice(&data.count().to_le_bytes());
632 if let Some(crc) = crc {
633 entry.extend_from_slice(&crc.to_le_bytes());
634 entry.extend_from_slice(&[0; 4]);
635 }
636 entry
637}
638
639fn data_crc(data: &Data<'_>) -> u32 {
641 fn bytes_of<T: Copy>(values: &[T]) -> &[u8] {
643 unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), size_of_val(values)) }
646 }
647 if cfg!(target_endian = "little") {
650 let bytes = match data {
651 Data::U64(v) => Some(bytes_of(v)),
652 Data::F64(v) => Some(bytes_of(v)),
653 Data::U32(v) => Some(bytes_of(v)),
654 Data::Ints(a) => Some(bytes_of(a.values())),
655 Data::StrBytes(a) => Some(str_bytes(a)),
656 Data::Bytes(b) => Some(b.as_slice()),
657 Data::StrOffsets(_) => None,
658 };
659 if let Some(bytes) = bytes {
660 return super::mapped::crc(bytes);
661 }
662 }
663 let mut sink = Sink {
664 out: io::sink(),
665 crc: crc32fast::Hasher::new(),
666 at: 0,
667 hash: true,
668 };
669 sink.put_data(data)
670 .expect("writing to io::sink does not fail");
671 sink.crc.finalize()
672}
673
674struct Sink<W> {
676 out: W,
677 crc: crc32fast::Hasher,
678 at: u64,
679 hash: bool,
680}
681
682impl<W: Write> Sink<W> {
683 fn put(&mut self, bytes: &[u8]) -> io::Result<()> {
684 if self.hash {
685 self.crc.update(bytes);
686 }
687 self.at += bytes.len() as u64;
688 self.out.write_all(bytes)
689 }
690
691 fn pad_to(&mut self, offset: u64) -> io::Result<()> {
692 debug_assert!(offset >= self.at);
693 let zeros = [0u8; SECTION_ALIGN as usize];
694 while self.at < offset {
695 let n = ((offset - self.at) as usize).min(zeros.len());
696 self.put(&zeros[..n])?;
697 }
698 Ok(())
699 }
700
701 fn put_data(&mut self, data: &Data<'_>) -> io::Result<()> {
703 match data {
704 Data::U64(v) => self.put_all(v, |x| x.to_le_bytes()),
705 Data::F64(v) => self.put_all(v, |x| x.to_le_bytes()),
706 Data::U32(v) => self.put_all(v, |x| x.to_le_bytes()),
707 Data::Ints(a) => self.put_all(a.values(), |x| x.to_le_bytes()),
708 Data::StrOffsets(a) => {
709 let offsets = a.value_offsets();
710 let base = offsets[0];
711 self.put_all(offsets, |x| (x - base).to_le_bytes())
712 }
713 Data::StrBytes(a) => self.put(str_bytes(a)),
714 Data::Bytes(b) => self.put(b.as_slice()),
715 }
716 }
717
718 fn put_all<T: Copy, const N: usize>(
720 &mut self,
721 values: &[T],
722 le: impl Fn(T) -> [u8; N],
723 ) -> io::Result<()> {
724 let mut block = Vec::with_capacity(64 * 1024);
725 for chunk in values.chunks(64 * 1024 / N) {
726 block.clear();
727 for &v in chunk {
728 block.extend_from_slice(&le(v));
729 }
730 self.put(&block)?;
731 }
732 Ok(())
733 }
734}
735
736pub type DecodeError = String;
738
739#[derive(Debug, Clone, Default)]
742pub struct Dropped {
743 pub n_dropped: u64,
744 pub kept: Option<BooleanBuffer>,
745}
746
747pub struct Stored {
749 pub topology: Topology,
751 pub ids: IdMap,
752 pub dropped: Dropped,
754 pub main: MainPart,
755 pub chunks: Vec<ChunkInfo>,
757 pub version: u32,
760 pub unverified: Option<Arc<Unverified>>,
763}
764
765pub fn has_chunk(chunks: &[ChunkInfo], kind: u32, name: &[u8]) -> bool {
767 chunks.iter().any(|c| c.kind == kind && c.name == name)
768}
769
770static INCOMING_READS: AtomicU64 = AtomicU64::new(0);
772
773pub fn incoming_reads() -> u64 {
776 INCOMING_READS.load(Ordering::Relaxed)
777}
778
779pub fn read_file(path: &Path, key: &IndexKey) -> Result<Stored, DecodeError> {
791 let mut file = File::open(path).map_err(|e| e.to_string())?;
792 let len = file.metadata().map_err(|e| e.to_string())?.len();
793 let head = read_head(&mut file, len, key)?;
794 let (chunks, end) = list_chunks(&mut file, head.main_len, len);
795 let mapped = head.version == VERSION && super::mapped::MAPS;
796 let data = match mapped {
797 true => super::mapped::map(&file, end)?,
798 false => super::mapped::read_whole(&file, head.main_len)?,
799 };
800 let (topology, ids, main, dropped, deferred) = parse(&head, &data, mapped)?;
801 let unverified = mapped.then(|| Arc::new(Unverified::new(data.clone(), deferred)));
802 let topology = match (
803 chunks.iter().find(|c| c.kind == CHUNK_INCOMING),
804 &unverified,
805 ) {
806 (Some(chunk), Some(checks)) => {
807 let (chunk, checks) = (chunk.clone(), Arc::clone(checks));
810 let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
811 topology.with_checksummed_incoming_loader(Box::new(move || {
812 let incoming = mapped_incoming(&data, &chunk, n_nodes, n_edges).ok()?;
813 checks
814 .defer(Region {
815 what: "in-adjacency",
816 range: usize::try_from(chunk.start).ok()?
817 ..usize::try_from(chunk.data_end).ok()?,
818 crc: chunk.data_crc,
819 })
820 .ok()?;
821 INCOMING_READS.fetch_add(1, Ordering::Relaxed);
822 Some(incoming)
823 }))
824 }
825 (Some(chunk), None) => {
826 let (path, chunk) = (path.to_path_buf(), chunk.clone());
827 let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
828 topology.with_incoming_loader(Box::new(move || {
829 let incoming = read_incoming(&path, main, &chunk, n_nodes, n_edges).ok()?;
830 INCOMING_READS.fetch_add(1, Ordering::Relaxed);
831 Some(incoming)
832 }))
833 }
834 (None, _) => topology,
835 };
836 Ok(Stored {
837 topology,
838 ids,
839 dropped,
840 main,
841 chunks,
842 version: head.version,
843 unverified,
844 })
845}
846
847pub fn decode(bytes: &[u8], key: &IndexKey) -> Result<(Topology, IdMap), DecodeError> {
850 decode_main(bytes, key).map(|(topology, ids, _, _)| (topology, ids))
851}
852
853fn decode_main(
855 bytes: &[u8],
856 key: &IndexKey,
857) -> Result<(Topology, IdMap, MainPart, Dropped), DecodeError> {
858 let head = read_head(&mut io::Cursor::new(bytes), bytes.len() as u64, key)?;
859 let main = &bytes[..head.main_len as usize];
861 let mut words = vec![0u64; main.len().div_ceil(8)];
862 for (word, chunk) in words.iter_mut().zip(main.chunks(8)) {
863 let mut le = [0u8; 8];
864 le[..chunk.len()].copy_from_slice(chunk);
865 *word = u64::from_ne_bytes(le);
866 }
867 let data = Buffer::from_vec(words).slice_with_length(0, main.len());
868 parse(&head, &data, false)
869 .map(|(topology, ids, main, dropped, _)| (topology, ids, main, dropped))
870}
871
872#[derive(Debug, Clone, PartialEq, Eq)]
874pub struct ChunkInfo {
875 pub kind: u32,
876 pub name: Vec<u8>,
877 pub start: u64,
878 pub end: u64,
879 data_end: u64,
881 data_crc: u32,
882 sections: Vec<(u32, u64, u64, u64)>,
884}
885
886pub fn list_chunks<R: Read + Seek>(file: &mut R, main_len: u64, len: u64) -> (Vec<ChunkInfo>, u64) {
891 let mut chunks = Vec::new();
892 let mut at = main_len;
893 while let Some(chunk) = chunk_at(file, at, len) {
894 at = chunk.end;
895 chunks.push(chunk);
896 }
897 (chunks, at)
898}
899
900fn u32_at(bytes: &[u8], at: usize) -> u32 {
901 u32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes"))
902}
903
904fn chunk_at<R: Read + Seek>(file: &mut R, start: u64, len: u64) -> Option<ChunkInfo> {
907 let read = |file: &mut R, at: u64, n: u64| -> Option<Vec<u8>> {
908 file.seek(SeekFrom::Start(at)).ok()?;
909 let mut buf = vec![0; usize::try_from(n).ok()?];
910 file.read_exact(&mut buf).ok()?;
911 Some(buf)
912 };
913 if len.saturating_sub(start) < CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN {
914 return None;
915 }
916 let header = read(file, start, CHUNK_HEADER_LEN)?;
917 let end = u64_at(&header, 8);
918 if header[..4] != CHUNK_MAGIC || end > len || end < start + CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN
919 {
920 return None;
921 }
922 let kind = u32_at(&header, 4);
923 let trailer_offset = end - CHUNK_TRAILER_LEN;
924 let trailer = read(file, trailer_offset, CHUNK_TRAILER_LEN)?;
925 let n_sections = u32_at(&trailer, 4) as u64;
926 let name_offset = u64_at(&trailer, 16);
927 let name_len = u64_at(&trailer, 24);
928 let table_offset = align(name_offset.checked_add(name_len)?, 8);
929 if trailer[40..44] != CHUNK_END_MAGIC
930 || u32_at(&trailer, 0) != kind
931 || u64_at(&trailer, 8) != start
932 || name_offset < start + CHUNK_HEADER_LEN
933 || n_sections
934 .checked_mul(CHUNK_ENTRY_LEN)?
935 .checked_add(table_offset)?
936 != trailer_offset
937 {
938 return None;
939 }
940 let meta = read(file, name_offset, trailer_offset - name_offset)?;
941 let mut crc = crc32fast::Hasher::new();
942 crc.update(&meta);
943 crc.update(&trailer[..36]);
944 if crc.finalize() != u32_at(&trailer, 36) {
945 return None;
946 }
947 let name = meta[..name_len as usize].to_vec();
948 let table = &meta[(table_offset - name_offset) as usize..];
949 let mut sections = Vec::new();
950 for entry in table.chunks_exact(CHUNK_ENTRY_LEN as usize) {
951 let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
952 let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
953 width
954 .checked_mul(count)
955 .and_then(|n| n.checked_add(offset))
956 .filter(|&e| offset >= start + CHUNK_HEADER_LEN && e <= name_offset)?;
957 sections.push((kind, width, offset, count));
958 }
959 sections.sort_by_key(|&(_, _, offset, _)| offset);
960 if sections
961 .windows(2)
962 .any(|w| w[0].2 + w[0].1 * w[0].3 > w[1].2)
963 {
964 return None;
965 }
966 Some(ChunkInfo {
967 kind,
968 name,
969 start,
970 end,
971 data_end: name_offset,
972 data_crc: u32_at(&trailer, 32),
973 sections,
974 })
975}
976
977fn check_main(file: &mut File, main: MainPart) -> Result<(), DecodeError> {
979 let len = file.metadata().map_err(|e| e.to_string())?.len();
980 if len < main.len || main.len < HEADER_LEN + TRAILER_LEN {
981 return Err("the file's main part has changed".into());
982 }
983 let mut trailer = [0u8; TRAILER_LEN as usize];
984 file.seek(SeekFrom::Start(main.len - TRAILER_LEN))
985 .and_then(|_| file.read_exact(&mut trailer))
986 .map_err(|e| e.to_string())?;
987 if u64_at(&trailer, 0) != main.len || u32_at(&trailer, 8) != main.crc {
988 return Err("the file's main part has changed".into());
989 }
990 Ok(())
991}
992
993pub fn read_chunk(
996 path: &Path,
997 main: MainPart,
998 chunk: &ChunkInfo,
999) -> Result<Vec<(u32, Section)>, DecodeError> {
1000 let mut file = File::open(path).map_err(|e| e.to_string())?;
1001 check_main(&mut file, main)?;
1002 if file.metadata().map_err(|e| e.to_string())?.len() < chunk.end {
1003 return Err("the file is shorter than the chunk".into());
1004 }
1005 file.seek(SeekFrom::Start(chunk.start))
1006 .map_err(|e| e.to_string())?;
1007 let mut src = Source {
1008 inner: BufReader::with_capacity(BLOCK, file),
1009 crc: crc32fast::Hasher::new(),
1010 at: chunk.start,
1011 };
1012 let mut sections = Vec::with_capacity(chunk.sections.len());
1013 for &(kind, width, offset, count) in &chunk.sections {
1014 src.skip_to(offset)?;
1015 sections.push((kind, src.section(kind, width, offset, count)?));
1016 }
1017 src.skip_to(chunk.data_end)?;
1018 if src.crc.finalize() != chunk.data_crc {
1019 return Err("the chunk's checksum does not match".into());
1020 }
1021 Ok(sections)
1022}
1023
1024fn read_incoming(
1027 path: &Path,
1028 main: MainPart,
1029 chunk: &ChunkInfo,
1030 n_nodes: usize,
1031 n_edges: usize,
1032) -> Result<Adjacency, DecodeError> {
1033 let mut sections = read_chunk(path, main, chunk)?;
1034 let mut take = |kind: u32| {
1035 let i = sections
1036 .iter()
1037 .position(|(k, _)| *k == kind)
1038 .ok_or_else(|| format!("section {kind} is missing"))?;
1039 Ok::<_, DecodeError>(sections.swap_remove(i).1)
1040 };
1041 match (take(IN_OFFSETS)?, take(IN_TARGETS)?, take(IN_EDGE_IDS)?) {
1042 (Section::U64(offsets), Section::U32(targets), Section::U32(edge_ids))
1043 if offsets.len() == n_nodes + 1
1044 && targets.len() == n_edges
1045 && edge_ids.len() == n_edges =>
1046 {
1047 Ok(Adjacency {
1048 offsets: offsets.into(),
1049 targets: targets.into(),
1050 edge_ids: edge_ids.into(),
1051 })
1052 }
1053 _ => Err("the in-adjacency is malformed".into()),
1054 }
1055}
1056
1057pub fn read_weights(
1060 path: &Path,
1061 main: MainPart,
1062 chunk: &ChunkInfo,
1063 n_edges: usize,
1064) -> Result<Vec<Vec<f64>>, DecodeError> {
1065 read_chunk(path, main, chunk)?
1066 .into_iter()
1067 .map(|(_, section)| match section {
1068 Section::F64(values) if values.len() == n_edges => Ok(values),
1069 _ => Err("the weights are malformed".to_string()),
1070 })
1071 .collect()
1072}
1073
1074pub fn append_chunk<'a>(
1080 path: &Path,
1081 main: MainPart,
1082 kind: u32,
1083 name: &[u8],
1084 encode: impl FnOnce(u64) -> EncodedChunk<'a>,
1085) -> io::Result<Option<u64>> {
1086 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
1087 check_main(&mut file, main).map_err(io::Error::other)?;
1088 let len = file.metadata()?.len();
1089 let (chunks, at) = list_chunks(&mut file, main.len, len);
1090 if has_chunk(&chunks, kind, name) {
1091 return Ok(None);
1092 }
1093 let chunk = encode(at);
1094 debug_assert_eq!((chunk.kind, chunk.name.as_slice()), (kind, name));
1095 if len > at {
1098 file.set_len(at)?;
1099 }
1100 file.seek(SeekFrom::Start(at))?;
1101 let mut out = BufWriter::with_capacity(1 << 20, &file);
1102 chunk.write_to(&mut out)?;
1103 out.into_inner().map_err(|e| e.into_error())?;
1104 file.sync_all()?;
1105 Ok(Some(chunk.end()))
1106}
1107
1108const BLOCK: usize = 1 << 20;
1110
1111struct Source<R> {
1113 inner: R,
1114 crc: crc32fast::Hasher,
1115 at: u64,
1116}
1117
1118impl<R: Read> Source<R> {
1119 fn fill(&mut self, buf: &mut [u8]) -> Result<(), DecodeError> {
1120 self.inner.read_exact(buf).map_err(|e| match e.kind() {
1121 io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1122 _ => e.to_string(),
1123 })?;
1124 self.crc.update(buf);
1125 self.at += buf.len() as u64;
1126 Ok(())
1127 }
1128
1129 fn bytes(&mut self, n: usize) -> Result<Vec<u8>, DecodeError> {
1130 let mut buf = vec![0; n];
1131 self.fill(&mut buf)?;
1132 Ok(buf)
1133 }
1134
1135 fn skip_to(&mut self, offset: u64) -> Result<(), DecodeError> {
1138 let mut buf = vec![0; BLOCK.min(offset.saturating_sub(self.at) as usize)];
1139 while self.at < offset {
1140 let n = ((offset - self.at) as usize).min(buf.len());
1141 self.fill(&mut buf[..n])?;
1142 }
1143 Ok(())
1144 }
1145
1146 fn values<T, const N: usize>(
1148 &mut self,
1149 count: usize,
1150 le: fn([u8; N]) -> T,
1151 ) -> Result<Vec<T>, DecodeError> {
1152 let mut out = Vec::with_capacity(count);
1153 let mut buf = vec![0; BLOCK.min(count * N)];
1154 while out.len() < count {
1155 let n = ((count - out.len()) * N).min(buf.len());
1156 self.fill(&mut buf[..n])?;
1157 out.extend(read(&buf[..n], le));
1158 }
1159 Ok(out)
1160 }
1161}
1162
1163impl<R: Read> Source<R> {
1164 fn section(
1168 &mut self,
1169 kind: u32,
1170 width: u64,
1171 offset: u64,
1172 count: u64,
1173 ) -> Result<Section, DecodeError> {
1174 let n = usize::try_from(count).map_err(|e| e.to_string())?;
1175 Ok(match (kind, width) {
1176 (OUT_OFFSETS | IN_OFFSETS, 8) => Section::U64(self.values(n, u64::from_le_bytes)?),
1177 (OUT_TARGETS | OUT_EDGE_IDS | IN_TARGETS | IN_EDGE_IDS, 4) => {
1178 Section::U32(self.values(n, u32::from_le_bytes)?)
1179 }
1180 (IDS_INT64, 8) => Section::I64(self.values(n, i64::from_le_bytes)?),
1181 (WEIGHTS_F64, 8) => Section::F64(self.values(n, f64::from_le_bytes)?),
1182 (IDS_STR_OFFSETS, 4) => Section::I32(self.values(n, i32::from_le_bytes)?),
1183 (IDS_STR_BYTES | KEPT_ROWS, 1) => Section::Bytes(self.bytes(n)?),
1184 _ => {
1185 self.skip_to(offset + width * count)?;
1186 Section::Bytes(Vec::new())
1187 }
1188 })
1189 }
1190}
1191
1192pub enum Section {
1194 U64(Vec<u64>),
1195 F64(Vec<f64>),
1196 U32(Vec<u32>),
1197 I64(Vec<i64>),
1198 I32(Vec<i32>),
1199 Bytes(Vec<u8>),
1200}
1201
1202#[derive(Debug, Clone, Copy)]
1204struct Entry {
1205 kind: u32,
1206 width: u64,
1207 offset: u64,
1208 count: u64,
1209 crc: u32,
1211}
1212
1213impl Entry {
1214 fn range(&self) -> Range<usize> {
1215 self.offset as usize..(self.offset + self.width * self.count) as usize
1217 }
1218}
1219
1220struct Head {
1222 version: u32,
1223 flags: u32,
1224 n_nodes: usize,
1225 n_edges: usize,
1226 n_dropped: u64,
1227 main_len: u64,
1228 table_end: u64,
1230 sections: Vec<Entry>,
1232 crc: u32,
1234}
1235
1236fn read_head<R: Read + Seek>(file: &mut R, len: u64, key: &IndexKey) -> Result<Head, DecodeError> {
1241 let read = |file: &mut R, at: u64, n: u64| -> Result<Vec<u8>, DecodeError> {
1242 file.seek(SeekFrom::Start(at)).map_err(|e| e.to_string())?;
1243 let mut buf = vec![0; usize::try_from(n).map_err(|e| e.to_string())?];
1244 file.read_exact(&mut buf).map_err(|e| match e.kind() {
1245 io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1246 _ => e.to_string(),
1247 })?;
1248 Ok(buf)
1249 };
1250 if len < HEADER_LEN + TRAILER_LEN {
1251 return Err(format!("{len} bytes is too short for an index file"));
1252 }
1253 let header = read(file, 0, HEADER_LEN)?;
1254 if header[..8] != MAGIC {
1255 return Err("not an Ursa index file".into());
1256 }
1257 let version = u32_at(&header, 8);
1258 if version != VERSION && version != VERSION_2 {
1259 return Err(format!(
1260 "index format version {version}; this build reads {VERSION_2} and {VERSION}"
1261 ));
1262 }
1263 let flags = u32_at(&header, 12);
1264 let n_nodes = usize::try_from(u64_at(&header, 16)).map_err(|e| e.to_string())?;
1265 let n_edges = usize::try_from(u64_at(&header, 24)).map_err(|e| e.to_string())?;
1266 let key_len = u64_at(&header, 32);
1267 let n_sections = u32_at(&header, 40) as u64;
1268 let main_len = u64_at(&header, 48);
1269 let n_dropped = u64_at(&header, 56);
1270 if main_len > len || main_len < HEADER_LEN + TRAILER_LEN || usize::try_from(main_len).is_err() {
1271 return Err("the file is truncated".into());
1272 }
1273 let body = main_len - TRAILER_LEN;
1274 let key_end = HEADER_LEN
1275 .checked_add(key_len)
1276 .filter(|&end| end <= body)
1277 .ok_or("the key runs past the end of the file")?;
1278 let table = align(key_end, 8);
1279 let entry_len = match version {
1280 VERSION_2 => CHUNK_ENTRY_LEN,
1281 _ => SECTION_ENTRY_LEN,
1282 };
1283 let table_end = n_sections
1284 .checked_mul(entry_len)
1285 .and_then(|n| n.checked_add(table))
1286 .filter(|&end| end <= body)
1287 .ok_or("the section table runs past the end of the file")?;
1288 let rest = read(file, HEADER_LEN, table_end - HEADER_LEN)?;
1289 let trailer = read(file, body, TRAILER_LEN)?;
1290 if trailer[12..] != END_MAGIC || u64_at(&trailer, 0) != main_len {
1291 return Err("the file is truncated".into());
1292 }
1293 let crc = u32_at(&trailer, 8);
1294 if version == VERSION {
1295 let mut meta = crc32fast::Hasher::new();
1296 meta.update(&header);
1297 meta.update(&rest);
1298 if meta.finalize() != crc {
1299 return Err("the checksum does not match".into());
1300 }
1301 if rest[(key_end - HEADER_LEN) as usize..(table - HEADER_LEN) as usize]
1302 .iter()
1303 .any(|&b| b != 0)
1304 {
1305 return Err("the padding is not zero".into());
1306 }
1307 }
1308 let stored: Value = serde_json::from_slice(&rest[..key_len as usize])
1309 .map_err(|e| format!("the key is not JSON: {e}"))?;
1310 if IndexKey::from_json(&stored).as_ref() != Some(key) {
1311 return Err("the file holds an index for another key".into());
1312 }
1313
1314 let entries = &rest[(table - HEADER_LEN) as usize..];
1315 let mut sections = Vec::with_capacity(n_sections as usize);
1316 for entry in entries.chunks_exact(entry_len as usize) {
1317 let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
1318 let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
1319 let crc = match version {
1320 VERSION_2 => 0,
1321 _ => u32_at(entry, 24),
1322 };
1323 width
1324 .checked_mul(count)
1325 .and_then(|n| n.checked_add(offset))
1326 .filter(|&end| offset >= table_end && end <= body)
1327 .ok_or("a section runs past the end of the file")?;
1328 sections.push(Entry {
1329 kind,
1330 width,
1331 offset,
1332 count,
1333 crc,
1334 });
1335 }
1336 sections.sort_by_key(|e| e.offset);
1337 if sections
1338 .windows(2)
1339 .any(|w| w[0].offset + w[0].width * w[0].count > w[1].offset)
1340 {
1341 return Err("the sections overlap".into());
1342 }
1343 Ok(Head {
1344 version,
1345 flags,
1346 n_nodes,
1347 n_edges,
1348 n_dropped,
1349 main_len,
1350 table_end,
1351 sections,
1352 crc,
1353 })
1354}
1355
1356fn deferred_kind(kind: u32) -> Option<&'static str> {
1359 match kind {
1360 OUT_TARGETS => Some("targets"),
1361 OUT_EDGE_IDS => Some("edge ids"),
1362 _ => None,
1363 }
1364}
1365
1366fn scalars<T: ArrowNativeType>(data: &Buffer, entry: &Entry) -> ScalarBuffer<T> {
1368 let size = std::mem::size_of::<T>();
1369 debug_assert_eq!(entry.width as usize, size);
1370 ScalarBuffer::new(
1373 data.clone(),
1374 entry.offset as usize / size,
1375 entry.count as usize,
1376 )
1377}
1378
1379type Parsed = (Topology, IdMap, MainPart, Dropped, Vec<Region>);
1381
1382fn parse(head: &Head, data: &Buffer, mapped: bool) -> Result<Parsed, DecodeError> {
1386 let main_len = head.main_len as usize;
1387 if data.len() < main_len {
1388 return Err("the file is truncated".into());
1389 }
1390 let bytes = &data.as_slice()[..main_len];
1391 let body = main_len - TRAILER_LEN as usize;
1392 let mut deferred = Vec::new();
1393 if head.version == VERSION_2 {
1394 if super::mapped::crc(&bytes[..body]) != head.crc {
1395 return Err("the checksum does not match".into());
1396 }
1397 } else {
1398 let mut at = head.table_end as usize;
1400 for entry in &head.sections {
1401 let range = entry.range();
1402 if bytes[at..range.start].iter().any(|&b| b != 0) {
1403 return Err("the padding is not zero".into());
1404 }
1405 at = range.end;
1406 match deferred_kind(entry.kind).filter(|_| mapped) {
1407 Some(what) => deferred.push(Region {
1408 what,
1409 range,
1410 crc: entry.crc,
1411 }),
1412 None => {
1413 if super::mapped::crc(&bytes[range]) != entry.crc {
1414 return Err(format!(
1415 "the checksum of section {} does not match",
1416 entry.kind
1417 ));
1418 }
1419 }
1420 }
1421 }
1422 if bytes[at..body].iter().any(|&b| b != 0) {
1423 return Err("the padding is not zero".into());
1424 }
1425 }
1426
1427 let (n_nodes, n_edges) = (head.n_nodes, head.n_edges);
1428 let take = |kind: u32, width: u64, count: Option<usize>| -> Result<Entry, DecodeError> {
1429 let mut found = head.sections.iter().filter(|e| e.kind == kind);
1430 let entry = found
1431 .next()
1432 .ok_or_else(|| format!("section {kind} is missing"))?;
1433 if found.next().is_some() || entry.width != width {
1434 return Err(format!("section {kind} is malformed"));
1435 }
1436 if count.is_some_and(|count| entry.count != count as u64) {
1437 return Err(format!("section {kind} has the wrong length"));
1438 }
1439 Ok(*entry)
1440 };
1441 let out = Adjacency {
1442 offsets: scalars(data, &take(OUT_OFFSETS, 8, Some(n_nodes + 1))?),
1443 targets: scalars(data, &take(OUT_TARGETS, 4, Some(n_edges))?),
1444 edge_ids: scalars(data, &take(OUT_EDGE_IDS, 4, Some(n_edges))?),
1445 };
1446 let topology = match head.version {
1447 VERSION_2 => Topology::from_parts(n_nodes, out, None)?,
1449 _ => Topology::from_checksummed_parts(n_nodes, out)?,
1450 };
1451
1452 let ids: Arc<dyn Array> = if head.flags & FLAG_STRING_IDS == 0 {
1453 let values = scalars::<i64>(data, &take(IDS_INT64, 8, Some(n_nodes))?);
1454 Arc::new(Int64Array::new(values, None))
1455 } else {
1456 let offsets = scalars::<i32>(data, &take(IDS_STR_OFFSETS, 4, Some(n_nodes + 1))?);
1457 let strings = take(IDS_STR_BYTES, 1, None)?;
1458 if offsets[0] != 0
1459 || offsets.windows(2).any(|w| w[0] > w[1])
1460 || offsets[n_nodes] as u64 != strings.count
1461 {
1462 return Err("the string ids' offsets are malformed".into());
1463 }
1464 let values = data.slice_with_length(strings.offset as usize, strings.count as usize);
1465 Arc::new(
1466 StringArray::try_new(OffsetBuffer::new(offsets), values, None)
1467 .map_err(|e| format!("the string ids are malformed: {e}"))?,
1468 )
1469 };
1470 let ids = IdMap::from_user_ids(ids.as_ref()).map_err(|e| e.to_string())?;
1471 if ids.len() != n_nodes {
1472 return Err("the id map does not match the topology".into());
1473 }
1474 let dropped = match head.n_dropped {
1475 0 => Dropped::default(),
1476 n_dropped => {
1477 let rows = usize::try_from(n_dropped)
1478 .ok()
1479 .and_then(|d| d.checked_add(n_edges))
1480 .ok_or("the kept rows are malformed")?;
1481 let bits = take(KEPT_ROWS, 1, Some(rows.div_ceil(8)))?;
1482 let bits = data.slice_with_length(bits.offset as usize, bits.count as usize);
1483 let kept = BooleanBuffer::new(bits, 0, rows);
1484 if kept.count_set_bits() != n_edges {
1485 return Err("the kept rows do not match the edges".into());
1486 }
1487 Dropped {
1488 n_dropped,
1489 kept: Some(kept),
1490 }
1491 }
1492 };
1493 let main = MainPart {
1494 len: head.main_len,
1495 crc: head.crc,
1496 };
1497 Ok((topology, ids, main, dropped, deferred))
1498}
1499
1500fn mapped_incoming(
1504 data: &Buffer,
1505 chunk: &ChunkInfo,
1506 n_nodes: usize,
1507 n_edges: usize,
1508) -> Result<Adjacency, DecodeError> {
1509 if (data.len() as u64) < chunk.end {
1510 return Err("the file is shorter than the chunk".into());
1511 }
1512 let entry = |kind: u32, width: u64, count: usize| -> Result<Entry, DecodeError> {
1513 let mut found = chunk.sections.iter().filter(|s| s.0 == kind);
1514 match (found.next(), found.next()) {
1515 (Some(&(kind, w, offset, c)), None) if w == width && c == count as u64 => Ok(Entry {
1516 kind,
1517 width,
1518 offset,
1519 count: c,
1520 crc: 0,
1521 }),
1522 _ => Err("the in-adjacency is malformed".into()),
1523 }
1524 };
1525 Ok(Adjacency {
1526 offsets: scalars(data, &entry(IN_OFFSETS, 8, n_nodes + 1)?),
1527 targets: scalars(data, &entry(IN_TARGETS, 4, n_edges)?),
1528 edge_ids: scalars(data, &entry(IN_EDGE_IDS, 4, n_edges)?),
1529 })
1530}
1531
1532fn u64_at(bytes: &[u8], at: usize) -> u64 {
1533 u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"))
1534}
1535
1536fn read<T, const N: usize>(
1538 bytes: &[u8],
1539 le: fn([u8; N]) -> T,
1540) -> impl Iterator<Item = T> + use<'_, T, N> {
1541 bytes
1542 .chunks_exact(N)
1543 .map(move |c| le(c.try_into().expect("N bytes")))
1544}
1545
1546#[cfg(test)]
1547mod tests {
1548 use super::*;
1549 use datafusion::arrow::array::ArrayRef;
1550
1551 fn key() -> IndexKey {
1552 IndexKey::new(
1553 "Projection: src, dst\n TableScan: ties".into(),
1554 vec![FileIdentity {
1555 store: "file:///".into(),
1556 location: "data/edges.parquet".into(),
1557 size: 1234,
1558 modified: 1_700_000_000_000_000_000,
1559 e_tag: Some("\"abc\"".into()),
1560 }],
1561 )
1562 }
1563
1564 fn built(src: ArrayRef, dst: ArrayRef) -> (Arc<Topology>, Arc<IdMap>) {
1565 ursa_io::build_topology_batches(&[(src.as_ref(), dst.as_ref())]).unwrap()
1566 }
1567
1568 fn encode(key: &IndexKey, topology: &Topology, ids: &IdMap) -> Vec<u8> {
1569 let encoded = Encoded::new(key, topology, ids).unwrap();
1570 let mut bytes = Vec::new();
1571 encoded.write_to(&mut bytes).unwrap();
1572 assert_eq!(bytes.len() as u64, encoded.file_size());
1573 bytes
1574 }
1575
1576 fn same(a: &Topology, b: &Topology) {
1577 assert_eq!(a.n_nodes(), b.n_nodes());
1578 assert_eq!(a.out().offsets, b.out().offsets);
1579 assert_eq!(a.out().targets, b.out().targets);
1580 assert_eq!(a.out().edge_ids, b.out().edge_ids);
1581 }
1582
1583 #[test]
1584 fn int_and_string_indexes_round_trip() {
1585 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1586 let (topology, ids) = built(ints(&[10, 20, 10, 30]), ints(&[20, 30, 30, 10]));
1587 let bytes = encode(&key(), &topology, &ids);
1588 assert_eq!(&bytes[..8], b"URSAIDX\0");
1589 let (back, back_ids) = decode(&bytes, &key()).unwrap();
1590 same(&topology, &back);
1591 assert!(back.incoming_if_built().is_none());
1592 assert_eq!(
1593 back_ids.user_id_array().as_ref(),
1594 ids.user_id_array().as_ref()
1595 );
1596
1597 topology.incoming();
1599 assert_eq!(encode(&key(), &topology, &ids), bytes);
1600
1601 let strs = |v: &[&str]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
1602 let (topology, ids) = built(strs(&["a", "bé", "a"]), strs(&["bé", "c", "c"]));
1603 let bytes = encode(&key(), &topology, &ids);
1604 let (back, back_ids) = decode(&bytes, &key()).unwrap();
1605 same(&topology, &back);
1606 assert_eq!(
1607 back_ids.user_id_array().as_ref(),
1608 ids.user_id_array().as_ref()
1609 );
1610
1611 let n_sections = u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize;
1613 let table = align(HEADER_LEN + u64_at(&bytes, 32), 8) as usize;
1614 for i in 0..n_sections {
1615 let entry = table + 32 * i;
1616 let (width, offset) = (
1617 u32_at(&bytes, entry + 4) as usize,
1618 u64_at(&bytes, entry + 8),
1619 );
1620 let count = u64_at(&bytes, entry + 16) as usize;
1621 assert_eq!(offset % 64, 0);
1622 let section = &bytes[offset as usize..offset as usize + width * count];
1623 assert_eq!(u32_at(&bytes, entry + 24), crc32fast::hash(section));
1624 }
1625 }
1626
1627 #[test]
1628 fn the_rows_a_vertex_table_left_out_round_trip() {
1629 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1630 let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
1631 let kept = BooleanBuffer::from(vec![true, false, false, true]);
1633 let encoded = Encoded::with_dropped(&key(), &topology, &ids, 2, Some(&kept)).unwrap();
1634 let mut bytes = Vec::new();
1635 encoded.write_to(&mut bytes).unwrap();
1636 let (back, _, _, dropped) = decode_main(&bytes, &key()).unwrap();
1637 same(&topology, &back);
1638 assert_eq!(dropped.n_dropped, 2);
1639 assert_eq!(dropped.kept, Some(kept));
1640 let plain = encode(&key(), &topology, &ids);
1642 let (_, _, _, none) = decode_main(&plain, &key()).unwrap();
1643 assert_eq!((none.n_dropped, none.kept), (0, None));
1644 }
1645
1646 #[test]
1647 fn an_empty_index_round_trips() {
1648 let (topology, ids) =
1649 ursa_io::topology::empty_topology(&datafusion::arrow::datatypes::DataType::Utf8);
1650 let (back, back_ids) = decode(&encode(&key(), &topology, &ids), &key()).unwrap();
1651 assert_eq!((back.n_nodes(), back.n_edges()), (0, 0));
1652 assert!(back_ids.is_empty());
1653 }
1654
1655 #[test]
1656 fn corruption_truncation_and_another_key_are_errors() {
1657 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1658 let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1659 let bytes = encode(&key(), &topology, &ids);
1660 for cut in [0, 10, 64, bytes.len() / 2, bytes.len() - 1] {
1661 assert!(decode(&bytes[..cut], &key()).is_err(), "cut at {cut}");
1662 }
1663 for at in [9, 70, bytes.len() / 2, bytes.len() - 20] {
1664 let mut flipped = bytes.clone();
1665 flipped[at] ^= 0x40;
1666 assert!(decode(&flipped, &key()).is_err(), "flipped at {at}");
1667 }
1668 let mut other = key();
1669 other.files[0].size += 1;
1670 assert_eq!(
1671 decode(&bytes, &other).unwrap_err(),
1672 "the file holds an index for another key"
1673 );
1674 assert!(decode(
1675 b"not an index at all, just some text..........................................",
1676 &key()
1677 )
1678 .is_err());
1679 }
1680
1681 fn write_main(path: &Path, topology: &Topology, ids: &IdMap) -> MainPart {
1683 let encoded = Encoded::new(&key(), topology, ids).unwrap();
1684 let mut file = File::create(path).unwrap();
1685 encoded.write_to(&mut file).unwrap()
1686 }
1687
1688 #[test]
1689 fn the_in_adjacency_is_appended_and_read_on_first_demand() {
1690 let dir = tempfile::tempdir().unwrap();
1691 let path = dir.path().join("x.idx");
1692 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1693 let (topology, ids) = built(
1694 ints(&[10, 20, 10, 30, 20, 40]),
1695 ints(&[20, 30, 30, 10, 40, 10]),
1696 );
1697 let main = write_main(&path, &topology, &ids);
1698 assert_eq!(main.len, std::fs::metadata(&path).unwrap().len());
1699
1700 let reads = incoming_reads();
1702 let stored = read_file(&path, &key()).unwrap();
1703 assert!(stored.chunks.is_empty());
1704 assert_eq!(
1705 stored.topology.incoming().targets,
1706 topology.incoming().targets
1707 );
1708 assert_eq!(incoming_reads(), reads);
1709
1710 let incoming = topology.incoming().clone();
1712 let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1713 EncodedChunk::incoming(&incoming, at)
1714 })
1715 .unwrap()
1716 .unwrap();
1717 assert_eq!(end, std::fs::metadata(&path).unwrap().len());
1718 let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1719 EncodedChunk::incoming(&incoming, at)
1720 });
1721 assert_eq!(again.unwrap(), None);
1722
1723 let stored = read_file(&path, &key()).unwrap();
1724 assert_eq!(stored.chunks.len(), 1);
1725 assert_eq!(stored.main, main);
1726 same(&topology, &stored.topology);
1727 assert!(stored.topology.incoming_if_built().is_none());
1729 let back = stored.topology.incoming();
1730 assert!(incoming_reads() > reads);
1731 assert_eq!(
1732 (&back.offsets, &back.targets, &back.edge_ids),
1733 (&incoming.offsets, &incoming.targets, &incoming.edge_ids)
1734 );
1735 let bytes = std::fs::read(&path).unwrap();
1737 let (main_only, _) = decode(&bytes, &key()).unwrap();
1738 same(&topology, &main_only);
1739 }
1740
1741 #[test]
1742 fn a_damaged_chunk_is_ignored_and_replaced() {
1743 let dir = tempfile::tempdir().unwrap();
1744 let path = dir.path().join("x.idx");
1745 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1746 let (topology, ids) = built(ints(&[1, 2, 3, 1]), ints(&[2, 3, 1, 3]));
1747 let main = write_main(&path, &topology, &ids);
1748 let incoming = topology.incoming().clone();
1749 let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1750 EncodedChunk::incoming(&incoming, at)
1751 })
1752 .unwrap()
1753 .unwrap();
1754 let good = std::fs::read(&path).unwrap();
1755
1756 let mut bytes = good.clone();
1759 bytes[main.len as usize + 64] ^= 0x01;
1760 std::fs::write(&path, &bytes).unwrap();
1761 let stored = read_file(&path, &key()).unwrap();
1762 assert_eq!(stored.chunks.len(), 1);
1763 assert!(read_chunk(&path, main, &stored.chunks[0]).is_err());
1764 assert_eq!(stored.topology.incoming().targets, incoming.targets);
1765 assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
1766
1767 std::fs::write(&path, &good[..good.len() - 10]).unwrap();
1770 assert!(read_file(&path, &key()).unwrap().chunks.is_empty());
1771 let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1772 EncodedChunk::incoming(&incoming, at)
1773 })
1774 .unwrap();
1775 assert_eq!(again, Some(end));
1776 assert_eq!(std::fs::read(&path).unwrap(), good);
1777
1778 let other = MainPart {
1780 crc: main.crc ^ 1,
1781 ..main
1782 };
1783 assert!(append_chunk(&path, other, CHUNK_INCOMING, b"", |at| {
1784 EncodedChunk::incoming(&incoming, at)
1785 })
1786 .is_err());
1787 let chunk = &read_file(&path, &key()).unwrap().chunks[0];
1788 assert!(read_chunk(&path, other, chunk).is_err());
1789 assert!(read_chunk(&path, main, chunk).is_ok());
1790 }
1791
1792 #[test]
1793 fn weight_chunks_round_trip_by_key() {
1794 let dir = tempfile::tempdir().unwrap();
1795 let path = dir.path().join("x.idx");
1796 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1797 let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1798 let main = write_main(&path, &topology, &ids);
1799 let (a, b) = (vec![0.5, 1.0, f64::MAX], vec![2.0, 0.0, 1e-300]);
1800 for (key, columns) in [("w1", vec![&a[..]]), ("w2", vec![&a[..], &b[..]])] {
1801 let appended = append_chunk(&path, main, CHUNK_WEIGHTS, key.as_bytes(), |at| {
1802 EncodedChunk::weights(key, &columns, at)
1803 });
1804 assert!(appended.unwrap().is_some());
1805 }
1806 let stored = read_file(&path, &key()).unwrap();
1807 assert_eq!(stored.chunks.len(), 2);
1808 let chunk = |name: &[u8]| stored.chunks.iter().find(|c| c.name == name).unwrap();
1809 assert_eq!(
1810 read_weights(&path, main, chunk(b"w1"), 3).unwrap(),
1811 std::slice::from_ref(&a)
1812 );
1813 assert_eq!(read_weights(&path, main, chunk(b"w2"), 3).unwrap(), [a, b]);
1814 assert!(read_weights(&path, main, chunk(b"w1"), 4).is_err());
1816 }
1817
1818 fn section_of(bytes: &[u8], kind: u32) -> (usize, usize) {
1821 let n_sections = u32_at(bytes, 40) as usize;
1822 let table = align(HEADER_LEN + u64_at(bytes, 32), 8) as usize;
1823 (0..n_sections)
1824 .map(|i| table + 32 * i)
1825 .find(|&entry| u32_at(bytes, entry) == kind)
1826 .map(|entry| {
1827 let width = u32_at(bytes, entry + 4) as usize;
1828 let count = u64_at(bytes, entry + 16) as usize;
1829 (u64_at(bytes, entry + 8) as usize, width * count)
1830 })
1831 .unwrap()
1832 }
1833
1834 fn a_graph() -> (Arc<Topology>, Arc<IdMap>) {
1835 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1836 built(
1837 ints(&[10, 20, 10, 30, 20, 40, 40, 50]),
1838 ints(&[20, 30, 30, 10, 40, 10, 50, 10]),
1839 )
1840 }
1841
1842 #[test]
1843 fn a_version_2_file_from_0_10_is_read_whole_and_checked() {
1844 let dir = tempfile::tempdir().unwrap();
1845 let path = dir.path().join("x.idx");
1846 let (topology, ids) = a_graph();
1847 let encoded = Encoded::new(&key(), &topology, &ids)
1848 .unwrap()
1849 .as_version_2();
1850 let mut v2 = Vec::new();
1851 let main = encoded.write_to(&mut v2).unwrap();
1852 assert_eq!(u32_at(&v2, 8), VERSION_2);
1853 assert_eq!(main.crc, crc32fast::hash(&v2[..v2.len() - 16]));
1854 std::fs::write(&path, &v2).unwrap();
1855 let stored = read_file(&path, &key()).unwrap();
1856 assert_eq!(stored.version, VERSION_2);
1857 assert!(stored.unverified.is_none());
1859 assert_eq!(stored.main, main);
1860 same(&topology, &stored.topology);
1861 assert_eq!(
1862 stored.ids.user_id_array().as_ref(),
1863 ids.user_id_array().as_ref()
1864 );
1865 let incoming = topology.incoming().clone();
1867 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1868 EncodedChunk::incoming(&incoming, at)
1869 })
1870 .unwrap()
1871 .unwrap();
1872 let stored = read_file(&path, &key()).unwrap();
1873 assert_eq!(stored.topology.incoming().targets, incoming.targets);
1874
1875 for at in [9, 70, v2.len() / 2, v2.len() - 20] {
1877 let mut flipped = v2.clone();
1878 flipped[at] ^= 0x40;
1879 std::fs::write(&path, &flipped).unwrap();
1880 assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
1881 }
1882 for cut in [0, 10, 64, v2.len() / 2, v2.len() - 1] {
1883 std::fs::write(&path, &v2[..cut]).unwrap();
1884 assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
1885 }
1886 }
1887
1888 #[test]
1889 fn a_truncated_or_damaged_version_3_file_is_an_error_never_a_crash() {
1890 let dir = tempfile::tempdir().unwrap();
1891 let path = dir.path().join("x.idx");
1892 let (topology, ids) = a_graph();
1893 let main = write_main(&path, &topology, &ids);
1894 let incoming = topology.incoming().clone();
1895 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1896 EncodedChunk::incoming(&incoming, at)
1897 })
1898 .unwrap();
1899 let good = std::fs::read(&path).unwrap();
1900 let main_len = main.len as usize;
1901 for cut in (0..main_len).step_by(7).chain([main_len - 1]) {
1904 std::fs::write(&path, &good[..cut]).unwrap();
1905 assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
1906 }
1907 std::fs::write(&path, &good[..good.len() - 1]).unwrap();
1909 let stored = read_file(&path, &key()).unwrap();
1910 assert!(stored.chunks.is_empty());
1911 assert_eq!(stored.topology.incoming().targets, incoming.targets);
1912 let (targets, t_len) = section_of(&good, OUT_TARGETS);
1916 let (edge_ids, e_len) = section_of(&good, OUT_EDGE_IDS);
1917 let edge_arrays = |at: usize| {
1918 (targets..targets + t_len).contains(&at) || (edge_ids..edge_ids + e_len).contains(&at)
1919 };
1920 for at in (0..main_len).filter(|&at| !edge_arrays(at)) {
1921 let mut flipped = good.clone();
1922 flipped[at] ^= 0x10;
1923 std::fs::write(&path, &flipped).unwrap();
1924 assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
1925 }
1926 }
1927
1928 #[test]
1929 fn the_edge_arrays_checksums_are_checked_before_a_whole_read() {
1930 let dir = tempfile::tempdir().unwrap();
1931 let path = dir.path().join("x.idx");
1932 let (topology, ids) = a_graph();
1933 let main = write_main(&path, &topology, &ids);
1934 let good = std::fs::read(&path).unwrap();
1935 let stored = read_file(&path, &key()).unwrap();
1936 same(&topology, &stored.topology);
1937 if let Some(checks) = &stored.unverified {
1938 checks.verify().unwrap();
1939 }
1940
1941 for kind in [OUT_TARGETS, OUT_EDGE_IDS] {
1942 let (at, _) = section_of(&good, kind);
1943 let mut flipped = good.clone();
1944 flipped[at] ^= 0x01;
1946 std::fs::write(&path, &flipped).unwrap();
1947 assert!(decode(&flipped, &key()).is_err());
1949 match read_file(&path, &key()) {
1950 Ok(stored) => {
1952 let checks = stored.unverified.expect("a mapped file defers");
1953 assert!(!checks.is_damaged());
1954 let why = checks.verify().unwrap_err();
1955 assert!(why.contains("does not match"), "{why}");
1956 assert!(checks.is_damaged());
1957 }
1958 Err(e) if !super::super::mapped::MAPS => {
1960 assert!(e.contains("does not match"), "{e}")
1961 }
1962 Err(e) => panic!("{e}"),
1963 }
1964 }
1965
1966 std::fs::write(&path, &good).unwrap();
1969 let incoming = topology.incoming().clone();
1970 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1971 EncodedChunk::incoming(&incoming, at)
1972 })
1973 .unwrap();
1974 let mut bytes = std::fs::read(&path).unwrap();
1975 let chunk = read_file(&path, &key()).unwrap().chunks[0].clone();
1976 let (_, _, edge_ids, _) = chunk.sections[2];
1977 bytes[edge_ids as usize] ^= 0x01;
1978 std::fs::write(&path, &bytes).unwrap();
1979 let stored = read_file(&path, &key()).unwrap();
1980 if let Some(checks) = &stored.unverified {
1981 checks.verify().unwrap();
1982 }
1983 assert_eq!(stored.topology.incoming().targets, incoming.targets);
1984 assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
1985 }
1986
1987 #[test]
1988 fn a_mapped_index_survives_its_file_being_replaced_or_removed() {
1989 let dir = tempfile::tempdir().unwrap();
1990 let path = dir.path().join("x.idx");
1991 let (topology, ids) = a_graph();
1992 let main = write_main(&path, &topology, &ids);
1993 let incoming = topology.incoming().clone();
1994 append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1995 EncodedChunk::incoming(&incoming, at)
1996 })
1997 .unwrap();
1998 let stored = read_file(&path, &key()).unwrap();
1999
2000 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2003 let (other, other_ids) = built(ints(&[7, 8, 9]), ints(&[8, 9, 7]));
2004 let temp = dir.path().join("x.idx.tmp");
2005 write_main(&temp, &other, &other_ids);
2006 std::fs::rename(&temp, &path).unwrap();
2007 assert_eq!(read_file(&path, &key()).unwrap().topology.n_nodes(), 3);
2008
2009 same(&topology, &stored.topology);
2012 assert_eq!(stored.topology.incoming().targets, incoming.targets);
2013 if let Some(checks) = &stored.unverified {
2014 checks.verify().unwrap();
2015 }
2016 std::fs::remove_file(&path).unwrap();
2018 same(&topology, &stored.topology);
2019 assert_eq!(
2020 stored.ids.user_id_array().as_ref(),
2021 ids.user_id_array().as_ref()
2022 );
2023 }
2024
2025 #[test]
2026 fn a_version_1_file_is_not_read() {
2027 let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2028 let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
2029 let mut bytes = encode(&key(), &topology, &ids);
2030 bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
2031 assert_eq!(
2032 decode(&bytes, &key()).unwrap_err(),
2033 "index format version 1; this build reads 2 and 3"
2034 );
2035 }
2036
2037 #[test]
2038 fn keys_round_trip_through_json() {
2039 let k = key();
2040 assert_eq!(IndexKey::from_json(&k.to_json()), Some(k.clone()));
2041 let mut no_tag = k.clone();
2042 no_tag.files[0].e_tag = None;
2043 assert_eq!(IndexKey::from_json(&no_tag.to_json()), Some(no_tag.clone()));
2044 assert_ne!(no_tag.hash(), k.hash());
2045 }
2046
2047 #[test]
2048 fn a_key_of_another_version_is_not_read() {
2049 let mut json = key().to_json();
2050 json["version"] = 1.into();
2051 assert_eq!(IndexKey::from_json(&json), None);
2052 json.as_object_mut().unwrap().remove("version");
2053 assert_eq!(IndexKey::from_json(&json), None);
2054 }
2055}