Skip to main content

ursa_engine/database/
index_file.rs

1//! One stored graph index: `club.ursa.d/indexes/<hash>.idx`.
2//!
3//! A file holds one built index, the CSR topology and the id map, under the
4//! full key it was built for (the edge plan's fingerprint and the identity of
5//! every source file), followed by optional **chunks**: parts of the index
6//! that are built later, or that only some queries need, such as the
7//! in-adjacency. Version 3, all integers little-endian.
8//!
9//! The **main part** comes first:
10//!
11//! ```text
12//! offset  size  field
13//!      0     8  magic            "URSAIDX\0"
14//!      8     4  version          3
15//!     12     4  flags            bit 0: string ids
16//!     16     8  n_nodes
17//!     24     8  n_edges
18//!     32     8  key_len          bytes of the key that follows the header
19//!     40     4  n_sections
20//!     44     4  reserved (zero)
21//!     48     8  main_len         bytes of the main part, trailer included
22//!     56     8  n_dropped        edge rows left out (see below); zero before
23//!                                #311, and for a graph with no vertex table
24//!     64     …  key              JSON: {"version": 2, "fingerprint": …, "files": [{…}, …]}
25//!      …     …  section table    at the next multiple of 8; 32 bytes a section:
26//!                                kind u32, element width u32, offset u64, count u64,
27//!                                CRC-32 of the section's bytes u32, zero u32
28//!      …     …  sections         each at a multiple of 64 from the file's start
29//!      …    16  trailer          at the next multiple of 8: main_len u64,
30//!                                CRC-32 of the header, key and section table
31//!                                (every byte before the first section) u32,
32//!                                "XDIU"
33//! ```
34//!
35//! Every byte between the table and the trailer that is not in a section
36//! (alignment padding) is zero. The trailer's CRC covers the section CRCs, so
37//! it still identifies every byte of the main part (see [`MainPart`]), while
38//! each section can be checked on its own: a reader that maps the file checks
39//! the small sections when it loads and the edge arrays only when something
40//! reads them whole (see `super::mapped`).
41//!
42//! Its sections, in this order: the out-adjacency's offsets (`u64`,
43//! `n_nodes + 1`), targets (`u32`, `n_edges`) and edge ids (`u32`, `n_edges`);
44//! then the ids, either `i64` values (`n_nodes`) or, for string ids,
45//! Arrow-style `i32` offsets (`n_nodes + 1`, from 0) and UTF-8 bytes.
46//!
47//! A graph with a vertex table leaves out the edge rows whose source or
48//! destination is not one of its keys (#311). When it left some out, the
49//! header counts them (`n_dropped`) and one more section (kind 11, bytes)
50//! says which rows of the edge plan were kept: one bit per row,
51//! `n_edges + n_dropped` of them, least significant bit first, as an Arrow
52//! boolean buffer. Its key includes the vertex table's, so no file written
53//! before #311 is ever read for such a graph; a file of a graph without one
54//! is read as before, with nothing left out.
55//!
56//! **Chunks** follow the main part, one after another, each appended in
57//! place once what it holds exists (see `IndexStore`):
58//!
59//! ```text
60//!      0    16  header           "CHNK", kind u32, end u64 (the chunk's end
61//!                                offset in the file)
62//!     16     …  sections         each at a multiple of 64 from the file's start
63//!      …     …  name             bytes naming what the chunk holds (may be empty)
64//!      …     …  section table    at the next multiple of 8, as in the main part
65//!      …    48  trailer          kind u32, n_sections u32, start u64,
66//!                                name offset u64, name length u64,
67//!                                data CRC u32 (the header and sections),
68//!                                meta CRC u32 (name, table and the 36 bytes
69//!                                of the trailer before it), "KNHC", zero u32
70//! ```
71//!
72//! Chunk kind 1 is the in-adjacency (no name; its offsets, targets and edge
73//! ids, as the out-adjacency's). Chunk kind 2 is a set of evaluated weights:
74//! its name is the weights' key (the weighted edge plan's fingerprint and the
75//! identity of the files it reads), and it holds one `f64` section (kind 10,
76//! `n_edges` values in edge-row order) per weight expression, in order. A reader of the main part never reads the
77//! chunks' arrays: it lists the chunks (their headers, names and tables, a
78//! few small reads), and reads a chunk's sections only when they are asked
79//! for, checking the main part's trailer and the chunk's data CRC first. The
80//! in-adjacency is read this way the first time an algorithm asks for it
81//! (`Topology::with_incoming_loader`).
82//!
83//! **Appending.** A chunk is written after the last chunk that checks out,
84//! so a chunk cut short by a crash is overwritten by the next append, and a
85//! reader stops listing at the first chunk that does not check out.
86//! Appending never changes the bytes of the main part or of an earlier
87//! chunk, so a reader in another process (`--readonly`) never sees them
88//! change.
89//!
90//! **Version 2** (0.10) is the same layout with 24-byte table entries (no
91//! section CRCs) and one CRC over every byte before the trailer. It is still
92//! read, whole and checked (see [`read_file`]).
93//!
94//! **Why raw arrays, not Arrow IPC.** The arrays have different lengths and
95//! no schema: an IPC stream would need one record batch per array, or padding
96//! them into one table, and its metadata says nothing a section table does
97//! not. Raw little-endian arrays at 64-byte-aligned offsets are what a later
98//! memory-mapped reader wants (each section is a ready `&[u32]`/`&[u64]` on a
99//! little-endian machine), need no dependency, and the string ids are already
100//! in Arrow's layout, so they become a `StringArray` without a copy once
101//! mapped. Where the platform allows, [`read_file`] maps the file and the
102//! arrays are borrowed from the map, never copied (`super::mapped`);
103//! elsewhere the main part is read into memory in parallel and the arrays are
104//! borrowed from that.
105//!
106//! **Corruption.** The main part is read only if its length matches the
107//! trailer, the trailer's CRC matches, the version is 2 or 3, the key matches
108//! the key asked for, every section lies within it, the padding is zero, the
109//! CRC of every section but the edge arrays matches (all of them, for a file
110//! that is not mapped), and the arrays form a valid topology and id map
111//! (`ursa_core::Topology::from_checksummed_parts`, which checks the offsets;
112//! `IdMap::from_user_ids`; a version 2 file, whose sections have no CRC of
113//! their own, is checked in full by `Topology::from_parts`). Anything else is
114//! an error, which the store treats as a miss. The edge arrays' CRCs of a
115//! mapped file are checked before a whole-graph algorithm runs
116//! (`super::mapped::Unverified`). A chunk that does not check out is ignored,
117//! and what it held is rebuilt when needed.
118//!
119//! **Version 1** files (the in-adjacency, if any, inside the main part) are
120//! not read: they are a miss like any other unreadable file, so the index is
121//! built again once and stored as version 3 in their place.
122
123use 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
139/// The first bytes of every index file.
140pub const MAGIC: [u8; 8] = *b"URSAIDX\0";
141/// The last bytes of every index file.
142const END_MAGIC: [u8; 4] = *b"XDIU";
143/// The index file version this build writes. It reads this one and
144/// [`VERSION_2`].
145pub const VERSION: u32 = 3;
146/// The version 0.10 wrote: no section CRCs, one CRC over the main part.
147pub const VERSION_2: u32 = 2;
148/// The first bytes of every chunk.
149const CHUNK_MAGIC: [u8; 4] = *b"CHNK";
150/// The last bytes but four of every chunk's trailer.
151const CHUNK_END_MAGIC: [u8; 4] = *b"KNHC";
152const CHUNK_HEADER_LEN: u64 = 16;
153const CHUNK_TRAILER_LEN: u64 = 48;
154
155/// The chunk kind of an in-adjacency.
156pub const CHUNK_INCOMING: u32 = 1;
157/// The chunk kind of a set of evaluated weights.
158pub const CHUNK_WEIGHTS: u32 = 2;
159
160const HEADER_LEN: u64 = 64;
161const TRAILER_LEN: u64 = 16;
162/// A main part's section table entry (version 3).
163const SECTION_ENTRY_LEN: u64 = 32;
164/// A chunk's section table entry, and a version 2 main part's: no CRC.
165const 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
182/// The version of the key's form. Version 2 (#327) is the portable key:
183/// paths inside the database's directory relative to it, and only the file
184/// options that change what is read (`crate::graph::index`). A key of
185/// another version is not read, so an index stored under an older key is a
186/// miss, never a wrong hit.
187pub const KEY_VERSION: u64 = 2;
188
189/// What an index is stored under: the edge plan's fingerprint and the
190/// identity of every file it reads.
191#[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    /// The key as JSON, as the file header and the manifest hold it:
203    /// `{"version": 2, "fingerprint": …, "files": […]}`.
204    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    /// The key from its JSON, or `None` if it is not one.
222    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    /// A stable 64-bit hash of the key (FNV-1a over its JSON), which names
249    /// its file. The file's header holds the full key, so a collision is
250    /// only a miss.
251    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
261/// One array of the file: borrowed from the topology being written, or a
262/// part of the id column (which the id map hands out as an `Arc`).
263enum Data<'a> {
264    U64(&'a [u64]),
265    F64(&'a [f64]),
266    U32(&'a [u32]),
267    /// The values of an `Int64Array`.
268    Ints(Int64Array),
269    /// The offsets of a `StringArray`, written less their first value so
270    /// they start at 0.
271    StrOffsets(StringArray),
272    /// The bytes of a `StringArray` its offsets span.
273    StrBytes(StringArray),
274    /// Bytes, as they are.
275    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
300/// The bytes of `strings` its offsets span.
301fn 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
311/// An index laid out for writing: its header fields, key, sections and where
312/// each goes.
313pub struct Encoded<'a> {
314    /// [`VERSION`], or [`VERSION_2`] for a test of reading what 0.10 wrote.
315    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    /// Lay out the main part of `topology` and `ids` under `key` (not the
328    /// in-adjacency: see [`EncodedChunk::incoming`]). Nothing is written yet.
329    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    /// [`Self::new`], for an index that left out `n_dropped` edge rows,
334    /// `kept` saying which it kept (see the module docs).
335    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        // Cloning an Arrow array clones `Arc`s to its buffers, not the ids.
351        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    /// Place the sections after the header, key and table of a file of
379    /// `version`.
380    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    /// This index laid out as version 2, as 0.10 wrote it: for tests of
418    /// reading such a file.
419    #[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    /// The size of the main part, in bytes.
435    pub fn file_size(&self) -> u64 {
436        self.trailer_offset + TRAILER_LEN
437    }
438
439    /// Write the main part to `out`. Returns its identity.
440    pub fn write_to(&self, out: impl Write) -> io::Result<MainPart> {
441        let v2 = self.version == VERSION_2;
442        // Each section's CRC goes in the table, before the section: one pass
443        // over the arrays first (in parallel), then one to write them.
444        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(&section_entry(*kind, data, *offset, *crc))?;
472        }
473        // Version 3's trailer CRC covers the header, key and table; the
474        // sections have their own.
475        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/// The identity of a file's main part: its length and CRC. A chunk is read
500/// from, or appended to, a file only while its main part is still this one.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
502pub struct MainPart {
503    pub len: u64,
504    pub crc: u32,
505}
506
507/// A chunk laid out for writing at a given offset of a file.
508pub 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    /// The chunk of the in-adjacency `incoming`, to be written at `start`.
519    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    /// The chunk of the weight columns `columns` (one value per edge row
533    /// each), stored under `key`, to be written at `start`.
534    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    /// The offset just past the chunk: the file's length once it is written.
574    pub fn end(&self) -> u64 {
575        self.trailer_offset() + CHUNK_TRAILER_LEN
576    }
577
578    /// The chunk's size, in bytes.
579    pub fn size(&self) -> u64 {
580        self.end() - self.start
581    }
582
583    /// Write the chunk to `out`, which is at its start.
584    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(&section_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
624/// A section table entry: with the section's CRC in a version 3 main part,
625/// without in a chunk.
626fn 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
639/// The CRC-32 of the bytes `data` is written as.
640fn data_crc(data: &Data<'_>) -> u32 {
641    /// The bytes of `values`, which are plain numbers.
642    fn bytes_of<T: Copy>(values: &[T]) -> &[u8] {
643        // SAFETY: `T` is a primitive number here (u64, u32, i64, f64): every
644        // byte of it is initialized, and the view spans the slice exactly.
645        unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), size_of_val(values)) }
646    }
647    // On a little-endian machine an array is written as it is in memory, so
648    // its CRC is computed in place, in parallel.
649    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
674/// A writer that keeps a running CRC (while `hash` is set) and position.
675struct 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    /// Write one section's array.
702    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    /// Write `values` little-endian, a block at a time.
719    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
736/// Why a file could not be read as an index.
737pub type DecodeError = String;
738
739/// The edge rows an index left out, and which it kept: nothing left out and
740/// `None` for a graph with no vertex table (see the module docs).
741#[derive(Debug, Clone, Default)]
742pub struct Dropped {
743    pub n_dropped: u64,
744    pub kept: Option<BooleanBuffer>,
745}
746
747/// An index read from its file.
748pub struct Stored {
749    /// With a loader for the in-adjacency, if the file has its chunk.
750    pub topology: Topology,
751    pub ids: IdMap,
752    /// The edge rows left out, and which were kept (see the module docs).
753    pub dropped: Dropped,
754    pub main: MainPart,
755    /// The chunks that check out, in file order.
756    pub chunks: Vec<ChunkInfo>,
757    /// The file's version: [`VERSION`], or [`VERSION_2`] for a file 0.10
758    /// wrote.
759    pub version: u32,
760    /// The checksums of a mapped file that are checked only when something
761    /// reads the arrays whole; `None` when every one was checked as it loaded.
762    pub unverified: Option<Arc<Unverified>>,
763}
764
765/// Whether `chunks` has one of `kind` named `name`.
766pub fn has_chunk(chunks: &[ChunkInfo], kind: u32, name: &[u8]) -> bool {
767    chunks.iter().any(|c| c.kind == kind && c.name == name)
768}
769
770/// How many in-adjacencies have been read from index files, in this process.
771static INCOMING_READS: AtomicU64 = AtomicU64::new(0);
772
773/// How many in-adjacencies this process has read from index files: for
774/// tests that an algorithm read one, or did not.
775pub fn incoming_reads() -> u64 {
776    INCOMING_READS.load(Ordering::Relaxed)
777}
778
779/// Read the index file at `path`, which must be stored under `key`.
780///
781/// The header, key and section table are read first, so a file for another
782/// key costs only those. Then, for a version 3 file on a platform that maps
783/// files (`super::mapped`), the file is mapped, up to the end of its last
784/// chunk that checks out: the arrays are borrowed from the map, the small
785/// sections (offsets, ids) are checked now, and the edge arrays' checksums
786/// are deferred to [`Stored::unverified`]. Otherwise the main part is read
787/// whole, in parallel, and every checksum is checked before any array is
788/// used. The chunks are only listed; the in-adjacency's is read when the
789/// topology is first asked for it.
790pub 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            // Borrowed from the map, its data CRC deferred as the edge
808            // arrays' are.
809            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
847/// Read the main part of the index in `bytes`, which must be stored under
848/// `key`, checking every checksum. Chunks are not read.
849pub fn decode(bytes: &[u8], key: &IndexKey) -> Result<(Topology, IdMap), DecodeError> {
850    decode_main(bytes, key).map(|(topology, ids, _, _)| (topology, ids))
851}
852
853/// [`decode`], with the main part's identity and the rows left out.
854fn 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    // Copied to memory aligned for 64-bit values, as a read file is.
860    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/// One chunk of a file, as listed: where it is and what it holds.
873#[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    /// The end of its header and sections, which the data CRC covers.
880    data_end: u64,
881    data_crc: u32,
882    /// (kind, width, offset, count), in file order.
883    sections: Vec<(u32, u64, u64, u64)>,
884}
885
886/// The chunks of a file of `len` bytes whose main part is `main_len` bytes,
887/// in file order, as far as they check out; and the offset where the next
888/// chunk goes (the end of the last chunk that checks out). Only the chunks'
889/// headers, names, tables and trailers are read.
890pub 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
904/// The chunk at `start` of a file of `len` bytes, if one is there whole and
905/// its header, name, table and trailer check out.
906fn 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
977/// Check that the file `file` still has the main part `main`.
978fn 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
993/// Read the sections of `chunk` from the file at `path`, whose main part
994/// must still be `main`. Every byte the data CRC covers is read and checked.
995pub 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
1024/// Read the in-adjacency in `chunk` of the file at `path`, for a topology
1025/// of `n_nodes` nodes and `n_edges` edges.
1026fn 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
1057/// Read the weight columns in `chunk` of the file at `path`, for a topology
1058/// of `n_edges` edges: one per section, in order.
1059pub 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
1074/// Append the chunk `encode` lays out (at the offset it is given) to the
1075/// file at `path`, whose main part must still be `main`, after its last
1076/// chunk that checks out; unless the file already has a chunk of `kind`
1077/// named `name`. Returns the file's new length, or `None` if the chunk was
1078/// there already.
1079pub 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    // What follows the last chunk that checks out (one cut short by a
1096    // crash) is dropped first, so the file never ends in bytes that do not.
1097    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
1108/// The most a read asks for at once, in bytes.
1109const BLOCK: usize = 1 << 20;
1110
1111/// A reader that keeps a running CRC and position.
1112struct 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    /// Read and discard up to `offset`: padding, or a section this build
1136    /// does not read.
1137    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    /// `count` little-endian values, a block at a time.
1147    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    /// The section of `kind` at `offset` (where the source is): `count`
1165    /// values of `width` bytes. A section this build does not read, or a
1166    /// known one of the wrong width, is skipped and comes back empty.
1167    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
1192/// One section, read.
1193pub 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/// A section table entry, as read.
1203#[derive(Debug, Clone, Copy)]
1204struct Entry {
1205    kind: u32,
1206    width: u64,
1207    offset: u64,
1208    count: u64,
1209    /// The section's CRC (version 3; zero in version 2).
1210    crc: u32,
1211}
1212
1213impl Entry {
1214    fn range(&self) -> Range<usize> {
1215        // Within the main part, which `read_head` checked fits in memory.
1216        self.offset as usize..(self.offset + self.width * self.count) as usize
1217    }
1218}
1219
1220/// The main part's header, key and table, read and checked.
1221struct Head {
1222    version: u32,
1223    flags: u32,
1224    n_nodes: usize,
1225    n_edges: usize,
1226    n_dropped: u64,
1227    main_len: u64,
1228    /// The end of the section table: where the sections may start.
1229    table_end: u64,
1230    /// By offset; they do not overlap.
1231    sections: Vec<Entry>,
1232    /// The trailer's CRC.
1233    crc: u32,
1234}
1235
1236/// Read and check the header, key, section table and trailer of the index
1237/// file in `file`, `len` bytes, which must be stored under `key`. Version 3's
1238/// trailer CRC (over the header, key and table) is checked here; version 2's
1239/// covers the sections, so [`parse`] checks it.
1240fn 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
1356/// The sections whose CRCs a mapped file defers (see `super::mapped`): the
1357/// `O(edges)` arrays, which only a whole-graph algorithm reads whole.
1358fn 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
1366/// The `count` values of type `T` at byte `offset` of `data`, borrowed.
1367fn 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    // `data` starts 8-aligned (a map, or a vector of `u64`s) and every
1371    // section at a multiple of 64, so the values are aligned.
1372    ScalarBuffer::new(
1373        data.clone(),
1374        entry.offset as usize / size,
1375        entry.count as usize,
1376    )
1377}
1378
1379/// What [`parse`] makes of a main part.
1380type Parsed = (Topology, IdMap, MainPart, Dropped, Vec<Region>);
1381
1382/// The index in `data`, the main part `head` describes (and maybe more),
1383/// borrowing its arrays. A `mapped` file's edge arrays are not read: their
1384/// CRCs come back to be checked later. Every other checksum is checked here.
1385fn 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        // Padding is zero, and each section's CRC matches (or is deferred).
1399        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        // No section CRCs to vouch for the arrays: check them in full.
1448        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
1500/// The in-adjacency in `chunk` of the mapped file `data`, borrowed, for a
1501/// topology of `n_nodes` nodes and `n_edges` edges. Its data CRC is not
1502/// checked here.
1503fn 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
1536/// The little-endian values in `bytes`.
1537fn 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        // The in-adjacency is never part of the main part.
1598        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        // Sections are 64-byte aligned, each with its CRC in the table.
1612        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        // Rows 0 and 3 of four were kept, rows 1 and 2 left out.
1632        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        // A file with nothing left out has no such section, as before #311.
1641        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    /// Write the main part of `topology` to `path`; its identity.
1682    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        // No chunk: the transpose is built, nothing is read.
1701        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        // Appended once; a second append finds it there.
1711        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        // Listed, not read, until asked for.
1728        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        // The main part reads the same with or without the chunk.
1736        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        // A flipped byte in the chunk's arrays: listed, but its data CRC
1757        // fails, so the transpose is built instead, the same.
1758        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        // A chunk cut short (a crash mid-append): not listed, and the next
1768        // append writes over it.
1769        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        // Another main part: nothing is appended or read.
1779        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        // The wrong edge count is an error, never a short column.
1815        assert!(read_weights(&path, main, chunk(b"w1"), 4).is_err());
1816    }
1817
1818    /// The section table entry of `kind` in the version 3 main part `bytes`:
1819    /// its offset and length in bytes.
1820    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        // Read whole, every byte checked: nothing is left to check.
1858        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        // With an in-adjacency appended, as 0.10 appended it.
1866        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        // A damaged or truncated version 2 file is an error, never a crash.
1876        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        // Cut anywhere in the main part: an error (a mapped reader never
1902        // maps past the end of the file).
1903        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        // Cut in the chunk: the main part reads, the chunk is not listed.
1908        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        // A flipped byte anywhere in the main part but the edge arrays (the
1913        // header, key, table, offsets, ids, padding, trailer) is an error at
1914        // once.
1915        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            // Still in range, so a point traversal could not tell.
1945            flipped[at] ^= 0x01;
1946            std::fs::write(&path, &flipped).unwrap();
1947            // Read whole (as on Windows, and by `decode`): an error at once.
1948            assert!(decode(&flipped, &key()).is_err());
1949            match read_file(&path, &key()) {
1950                // Mapped: the damage is found before a whole-graph read.
1951                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                // Read whole where files are not mapped: an error at once.
1959                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        // A damaged in-adjacency, read after the check: the transpose is
1967        // built instead, the same.
1968        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        // Another index replaces the file the way the store does: written to
2001        // a temporary file, then renamed over it.
2002        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        // The index loaded before reads as it was, the arrays whole, and its
2010        // checksums still match (a map keeps the replaced file's pages).
2011        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        // And after the file is removed (an eviction).
2017        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}