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 5, 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          5
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; then
46//! the ids' **lookup table** (kind 12, `u32`): the open-addressing table
47//! that finds an id's node, `n_nodes + n_nodes / 2 + 1` slots, each a node or
48//! `u32::MAX` for an empty one. Its layout and the hashes it places ids by
49//! are fixed (`ursa_core::id_map`, `StoredTable`). With it a process that
50//! has just mapped the file finds a seed's node by reading a slot or two and
51//! comparing the id there, where before it hashed every id of the graph into
52//! a table of its own first (#421).
53//!
54//! An index whose nodes were relabelled for locality (#172,
55//! `ursa_core::NodeOrder`) has one more section, the nodes' **original ids**
56//! (kind 13, `u32`, `n_nodes`): the first-seen number of each node, which
57//! component labels and the seeded community kernels are defined on. The id
58//! column is in the relabelled order. Without the section the nodes are in
59//! their original order.
60//!
61//! A graph with a vertex table leaves out the edge rows whose source or
62//! destination is not one of its keys (#311). When it left some out, the
63//! header counts them (`n_dropped`) and one more section (kind 11, bytes)
64//! says which rows of the edge plan were kept: one bit per row,
65//! `n_edges + n_dropped` of them, least significant bit first, as an Arrow
66//! boolean buffer. Its key includes the vertex table's, so no file written
67//! before #311 is ever read for such a graph; a file of a graph without one
68//! is read as before, with nothing left out.
69//!
70//! **Chunks** follow the main part, one after another, each appended in
71//! place once what it holds exists (see `IndexStore`):
72//!
73//! ```text
74//!      0    16  header           "CHNK", kind u32, end u64 (the chunk's end
75//!                                offset in the file)
76//!     16     …  sections         each at a multiple of 64 from the file's start
77//!      …     …  name             bytes naming what the chunk holds (may be empty)
78//!      …     …  section table    at the next multiple of 8, as in the main part
79//!      …    48  trailer          kind u32, n_sections u32, start u64,
80//!                                name offset u64, name length u64,
81//!                                data CRC u32 (the header and sections),
82//!                                meta CRC u32 (name, table and the 36 bytes
83//!                                of the trailer before it), "KNHC", zero u32
84//! ```
85//!
86//! Chunk kind 1 is the in-adjacency (no name; its offsets, targets and edge
87//! ids, as the out-adjacency's). Chunk kind 2 is a set of evaluated weights:
88//! its name is the weights' key (the weighted edge plan's fingerprint and the
89//! identity of the files it reads), and it holds one `f64` section (kind 10,
90//! `n_edges` values in edge-row order) per weight expression, in order. A reader of the main part never reads the
91//! chunks' arrays: it lists the chunks (their headers, names and tables, a
92//! few small reads), and reads a chunk's sections only when they are asked
93//! for, checking the main part's trailer and the chunk's data CRC first. The
94//! in-adjacency is read this way the first time an algorithm asks for it
95//! (`Topology::with_incoming_loader`).
96//!
97//! **Appending.** A chunk is written after the last chunk that checks out,
98//! so a chunk cut short by a crash is overwritten by the next append, and a
99//! reader stops listing at the first chunk that does not check out.
100//! Appending never changes the bytes of the main part or of an earlier
101//! chunk, so a reader in another process (`--readonly`) never sees them
102//! change.
103//!
104//! **Version 4** (0.12) is version 5 without the original ids: its nodes
105//! were never relabelled, and they keep their numbering when it is read. It is
106//! still read, and mapped as version 5 is.
107//!
108//! **Version 3** (0.11) is version 4 without the lookup table. It is still
109//! read, and mapped as version 5 is; the table is then built in memory, the
110//! first time a query looks an id up (one that runs an algorithm over the
111//! whole graph and names no node never does). **Version 2** (0.10) is the
112//! same layout with 24-byte table entries (no section CRCs) and one CRC over
113//! every byte before the trailer. It is still read, whole and checked (see
114//! [`read_file`]), and its lookup table built in the same way. A writer
115//! stores any of them again as version 5 (`IndexStore`).
116//!
117//! **Why raw arrays, not Arrow IPC.** The arrays have different lengths and
118//! no schema: an IPC stream would need one record batch per array, or padding
119//! them into one table, and its metadata says nothing a section table does
120//! not. Raw little-endian arrays at 64-byte-aligned offsets are what a later
121//! memory-mapped reader wants (each section is a ready `&[u32]`/`&[u64]` on a
122//! little-endian machine), need no dependency, and the string ids are already
123//! in Arrow's layout, so they become a `StringArray` without a copy once
124//! mapped. Where the platform allows, [`read_file`] maps the file and the
125//! arrays are borrowed from the map, never copied (`super::mapped`);
126//! elsewhere the main part is read into memory in parallel and the arrays are
127//! borrowed from that.
128//!
129//! **Corruption.** The main part is read only if its length matches the
130//! trailer, the trailer's CRC matches, the version is 2, 3 or 4, the key matches
131//! the key asked for, every section lies within it, the padding is zero, the
132//! CRC of every section but the edge arrays matches (all of them, for a file
133//! that is not mapped), and the arrays form a valid topology and id map
134//! (`ursa_core::Topology::from_checksummed_parts`, which checks the offsets;
135//! `IdMap::from_stored_ids`, which takes the ids and their table as they
136//! lie, the table's CRC vouching that it is the one written for them; a
137//! version 2 file, whose sections have no CRC of their own, is checked in
138//! full by `Topology::from_parts`). An id stored twice, which no writer
139//! stores, is found when a version 2 or 3 file's table is built, and is then
140//! the error of the query that looked an id up. Anything else is
141//! an error, which the store treats as a miss. The edge arrays' CRCs of a
142//! mapped file are checked before a whole-graph algorithm runs
143//! (`super::mapped::Unverified`). A chunk that does not check out is ignored,
144//! and what it held is rebuilt when needed.
145//!
146//! **Version 1** files (the in-adjacency, if any, inside the main part) are
147//! not read: they are a miss like any other unreadable file, so the index is
148//! built again once and stored as version 5 in their place.
149
150use std::fs::{File, OpenOptions};
151use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
152use std::ops::Range;
153use std::path::Path;
154use std::sync::atomic::{AtomicU64, Ordering};
155use std::sync::{Arc, OnceLock};
156
157use datafusion::arrow::array::{Array, Int64Array, StringArray};
158use datafusion::arrow::buffer::{BooleanBuffer, Buffer, OffsetBuffer, ScalarBuffer};
159use datafusion::arrow::datatypes::ArrowNativeType;
160use serde_json::{json, Value};
161use ursa_core::id_map::lookup_table_len;
162use ursa_core::{Adjacency, EdgeIds, IdMap, Topology};
163
164use super::mapped::{Region, Unverified};
165use crate::graph::FileIdentity;
166
167/// The first bytes of every index file.
168pub const MAGIC: [u8; 8] = *b"URSAIDX\0";
169/// The last bytes of every index file.
170const END_MAGIC: [u8; 4] = *b"XDIU";
171/// The index file version this build writes. It reads this one and
172/// [`VERSION_4`] to [`VERSION_2`].
173pub const VERSION: u32 = 5;
174/// The version 0.12 wrote: version 5 without the original node ids (its
175/// nodes are never relabelled, #172).
176pub const VERSION_4: u32 = 4;
177/// The version 0.11 wrote: version 4 without the ids' lookup table.
178pub const VERSION_3: u32 = 3;
179/// The version 0.10 wrote: no section CRCs, one CRC over the main part.
180pub const VERSION_2: u32 = 2;
181/// The first bytes of every chunk.
182const CHUNK_MAGIC: [u8; 4] = *b"CHNK";
183/// The last bytes but four of every chunk's trailer.
184const CHUNK_END_MAGIC: [u8; 4] = *b"KNHC";
185const CHUNK_HEADER_LEN: u64 = 16;
186const CHUNK_TRAILER_LEN: u64 = 48;
187
188/// The chunk kind of an in-adjacency.
189pub const CHUNK_INCOMING: u32 = 1;
190/// The chunk kind of a set of evaluated weights.
191pub const CHUNK_WEIGHTS: u32 = 2;
192
193const HEADER_LEN: u64 = 64;
194const TRAILER_LEN: u64 = 16;
195/// A main part's section table entry (version 3).
196const SECTION_ENTRY_LEN: u64 = 32;
197/// A chunk's section table entry, and a version 2 main part's: no CRC.
198const CHUNK_ENTRY_LEN: u64 = 24;
199const SECTION_ALIGN: u64 = 64;
200
201const FLAG_STRING_IDS: u32 = 1;
202
203const OUT_OFFSETS: u32 = 1;
204const OUT_TARGETS: u32 = 2;
205const OUT_EDGE_IDS: u32 = 3;
206const IN_OFFSETS: u32 = 4;
207const IN_TARGETS: u32 = 5;
208const IN_EDGE_IDS: u32 = 6;
209const IDS_INT64: u32 = 7;
210const IDS_STR_OFFSETS: u32 = 8;
211const IDS_STR_BYTES: u32 = 9;
212const WEIGHTS_F64: u32 = 10;
213const KEPT_ROWS: u32 = 11;
214const ID_TABLE: u32 = 12;
215const ORIGINAL_IDS: u32 = 13;
216
217/// The version of the key's form. Version 2 (#327) is the portable key:
218/// paths inside the database's directory relative to it, and only the file
219/// options that change what is read (`crate::graph::index`). A key of
220/// another version is not read, so an index stored under an older key is a
221/// miss, never a wrong hit.
222pub const KEY_VERSION: u64 = 2;
223
224/// What an index is stored under: the edge plan's fingerprint and the
225/// identity of every file it reads.
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct IndexKey {
228    pub fingerprint: String,
229    pub files: Vec<FileIdentity>,
230}
231
232impl IndexKey {
233    pub fn new(fingerprint: String, files: Vec<FileIdentity>) -> Self {
234        Self { fingerprint, files }
235    }
236
237    /// The key as JSON, as the file header and the manifest hold it:
238    /// `{"version": 2, "fingerprint": …, "files": […]}`.
239    pub fn to_json(&self) -> Value {
240        let files: Vec<Value> = self
241            .files
242            .iter()
243            .map(|f| {
244                json!({
245                    "store": f.store,
246                    "location": f.location,
247                    "size": f.size,
248                    "modified": f.modified,
249                    "e_tag": f.e_tag,
250                })
251            })
252            .collect();
253        json!({ "version": KEY_VERSION, "fingerprint": self.fingerprint, "files": files })
254    }
255
256    /// The key from its JSON, or `None` if it is not one.
257    pub fn from_json(value: &Value) -> Option<Self> {
258        if value.get("version")?.as_u64()? != KEY_VERSION {
259            return None;
260        }
261        let fingerprint = value.get("fingerprint")?.as_str()?.to_string();
262        let files = value
263            .get("files")?
264            .as_array()?
265            .iter()
266            .map(|f| {
267                Some(FileIdentity {
268                    store: f.get("store")?.as_str()?.to_string(),
269                    location: f.get("location")?.as_str()?.to_string(),
270                    size: f.get("size")?.as_u64()?,
271                    modified: f.get("modified")?.as_i64()?,
272                    e_tag: match f.get("e_tag")? {
273                        Value::Null => None,
274                        Value::String(s) => Some(s.clone()),
275                        _ => return None,
276                    },
277                })
278            })
279            .collect::<Option<Vec<_>>>()?;
280        Some(Self { fingerprint, files })
281    }
282
283    /// A stable 64-bit hash of the key (FNV-1a over its JSON), which names
284    /// its file. The file's header holds the full key, so a collision is
285    /// only a miss.
286    pub fn hash(&self) -> u64 {
287        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
288        for b in self.to_json().to_string().bytes() {
289            h ^= u64::from(b);
290            h = h.wrapping_mul(0x0000_0100_0000_01b3);
291        }
292        h
293    }
294}
295
296/// One array of the file: borrowed from the topology being written, or a
297/// part of the id column (which the id map hands out as an `Arc`).
298enum Data<'a> {
299    U64(&'a [u64]),
300    F64(&'a [f64]),
301    U32(&'a [u32]),
302    /// The values of an `Int64Array`.
303    Ints(Int64Array),
304    /// The offsets of a `StringArray`, written less their first value so
305    /// they start at 0.
306    StrOffsets(StringArray),
307    /// The bytes of a `StringArray` its offsets span.
308    StrBytes(StringArray),
309    /// Bytes, as they are.
310    Bytes(Buffer),
311    /// The lookup table of an id map.
312    IdTable(IdTable<'a>),
313    /// An adjacency's edge ids: read as they are when held, else built for
314    /// the write (once, kept until the write is done) and not kept on the
315    /// adjacency, so storing an index does not make it hold them (#170).
316    EdgeIds(&'a EdgeIds, OnceLock<ScalarBuffer<u32>>),
317}
318
319impl<'a> Data<'a> {
320    /// The edge ids `ids`, as a section.
321    fn edge_ids(ids: &'a EdgeIds) -> Self {
322        Data::EdgeIds(ids, OnceLock::new())
323    }
324}
325
326/// The edge ids of a [`Data::EdgeIds`] section.
327fn ids_of<'d>(ids: &'d EdgeIds, built: &'d OnceLock<ScalarBuffer<u32>>) -> &'d [u32] {
328    built.get_or_init(|| ids.detached())
329}
330
331/// The lookup table of `ids`, built when the file is written (not when it is
332/// laid out, which only needs its length, and happens in the query that built
333/// the index).
334struct IdTable<'a> {
335    ids: &'a IdMap,
336    slots: OnceLock<Result<ScalarBuffer<u32>, String>>,
337}
338
339impl IdTable<'_> {
340    fn build(&self) -> Result<&ScalarBuffer<u32>, String> {
341        self.slots
342            .get_or_init(|| self.ids.lookup_table().map_err(|e| e.to_string()))
343            .as_ref()
344            .map_err(Clone::clone)
345    }
346
347    /// The table, which [`Encoded::write_to`] has built by now.
348    fn slots(&self) -> &[u32] {
349        self.build()
350            .expect("write_to builds the lookup table before it is written")
351    }
352}
353
354impl Data<'_> {
355    fn width(&self) -> u64 {
356        match self {
357            Data::U64(_) | Data::F64(_) | Data::Ints(_) => 8,
358            Data::U32(_) | Data::StrOffsets(_) | Data::IdTable(_) | Data::EdgeIds(..) => 4,
359            Data::StrBytes(_) | Data::Bytes(_) => 1,
360        }
361    }
362
363    fn count(&self) -> u64 {
364        (match self {
365            Data::U64(v) => v.len(),
366            Data::F64(v) => v.len(),
367            Data::U32(v) => v.len(),
368            Data::Ints(a) => a.len(),
369            Data::StrOffsets(a) => a.len() + 1,
370            Data::StrBytes(a) => str_bytes(a).len(),
371            Data::Bytes(b) => b.len(),
372            Data::IdTable(t) => return lookup_table_len(t.ids.len()),
373            Data::EdgeIds(ids, _) => ids.len(),
374        }) as u64
375    }
376}
377
378/// The bytes of `strings` its offsets span.
379fn str_bytes(strings: &StringArray) -> &[u8] {
380    let offsets = strings.value_offsets();
381    let (first, last) = (offsets[0] as usize, offsets[offsets.len() - 1] as usize);
382    &strings.value_data()[first..last]
383}
384
385fn align(n: u64, to: u64) -> u64 {
386    n.div_ceil(to) * to
387}
388
389/// An index laid out for writing: its header fields, key, sections and where
390/// each goes.
391pub struct Encoded<'a> {
392    /// [`VERSION`]; or [`VERSION_4`], [`VERSION_3`] or [`VERSION_2`], for a
393    /// test of reading what 0.12, 0.11 or 0.10 wrote.
394    version: u32,
395    flags: u32,
396    n_nodes: u64,
397    n_edges: u64,
398    n_dropped: u64,
399    key: Vec<u8>,
400    sections: Vec<(u32, Data<'a>, u64)>,
401    table_offset: u64,
402    trailer_offset: u64,
403}
404
405impl<'a> Encoded<'a> {
406    /// Lay out the main part of `topology` and `ids` under `key` (not the
407    /// in-adjacency: see [`EncodedChunk::incoming`]). Nothing is written yet.
408    pub fn new(key: &IndexKey, topology: &'a Topology, ids: &'a IdMap) -> io::Result<Self> {
409        Self::with_dropped(key, topology, ids, 0, None)
410    }
411
412    /// [`Self::new`], for an index that left out `n_dropped` edge rows,
413    /// `kept` saying which it kept (see the module docs).
414    pub fn with_dropped(
415        key: &IndexKey,
416        topology: &'a Topology,
417        ids: &'a IdMap,
418        n_dropped: u64,
419        kept: Option<&BooleanBuffer>,
420    ) -> io::Result<Self> {
421        let id_array = ids.user_id_array();
422        let mut flags = 0;
423        let out = topology.out();
424        let mut sections: Vec<(u32, Data<'a>)> = vec![
425            (OUT_OFFSETS, Data::U64(&out.offsets)),
426            (OUT_TARGETS, Data::U32(&out.targets)),
427            (OUT_EDGE_IDS, Data::edge_ids(&out.edge_ids)),
428        ];
429        // Cloning an Arrow array clones `Arc`s to its buffers, not the ids.
430        if let Some(ints) = id_array.as_any().downcast_ref::<Int64Array>() {
431            sections.push((IDS_INT64, Data::Ints(ints.clone())));
432        } else if let Some(strings) = id_array.as_any().downcast_ref::<StringArray>() {
433            flags |= FLAG_STRING_IDS;
434            sections.push((IDS_STR_OFFSETS, Data::StrOffsets(strings.clone())));
435            sections.push((IDS_STR_BYTES, Data::StrBytes(strings.clone())));
436        } else {
437            return Err(io::Error::other(format!(
438                "cannot store node ids of type {}",
439                id_array.data_type()
440            )));
441        }
442        sections.push((
443            ID_TABLE,
444            Data::IdTable(IdTable {
445                ids,
446                slots: OnceLock::new(),
447            }),
448        ));
449        // The original id of each node, if the build relabelled them (#172).
450        if let Some(original) = topology.original_ids() {
451            sections.push((ORIGINAL_IDS, Data::U32(original)));
452        }
453        let n_dropped = match kept {
454            Some(kept) if n_dropped > 0 => {
455                sections.push((KEPT_ROWS, Data::Bytes(kept.sliced())));
456                n_dropped
457            }
458            _ => 0,
459        };
460
461        let key = key.to_json().to_string().into_bytes();
462        let (n_nodes, n_edges) = (topology.n_nodes() as u64, topology.n_edges() as u64);
463        Ok(Self::laid_out(
464            VERSION, flags, n_nodes, n_edges, n_dropped, key, sections,
465        ))
466    }
467
468    /// Place the sections after the header, key and table of a file of
469    /// `version`.
470    fn laid_out(
471        version: u32,
472        flags: u32,
473        n_nodes: u64,
474        n_edges: u64,
475        n_dropped: u64,
476        key: Vec<u8>,
477        sections: Vec<(u32, Data<'a>)>,
478    ) -> Self {
479        let entry_len = match version {
480            VERSION_2 => CHUNK_ENTRY_LEN,
481            _ => SECTION_ENTRY_LEN,
482        };
483        let table_offset = align(HEADER_LEN + key.len() as u64, 8);
484        let mut at = table_offset + entry_len * sections.len() as u64;
485        let sections = sections
486            .into_iter()
487            .map(|(kind, data)| {
488                at = align(at, SECTION_ALIGN);
489                let offset = at;
490                at += data.width() * data.count();
491                (kind, data, offset)
492            })
493            .collect();
494        Self {
495            version,
496            flags,
497            n_nodes,
498            n_edges,
499            n_dropped,
500            key,
501            sections,
502            table_offset,
503            trailer_offset: align(at, 8),
504        }
505    }
506
507    /// This index laid out as version 2, as 0.10 wrote it: for tests of
508    /// reading such a file.
509    #[doc(hidden)]
510    pub fn as_version_2(self) -> Self {
511        self.in_version(VERSION_2)
512    }
513
514    /// This index laid out as version 3, as 0.11 wrote it: for tests of
515    /// reading such a file.
516    #[doc(hidden)]
517    pub fn as_version_3(self) -> Self {
518        self.in_version(VERSION_3)
519    }
520
521    /// This index laid out as version 4, as 0.12 wrote it (no original
522    /// node ids): for tests of reading such a file. Its nodes must not have
523    /// been relabelled, as 0.12 never relabelled them.
524    #[doc(hidden)]
525    pub fn as_version_4(self) -> Self {
526        self.in_version(VERSION_4)
527    }
528
529    /// This index laid out as an older `version`, which has no original node
530    /// ids and, before version 4, no lookup table.
531    fn in_version(self, version: u32) -> Self {
532        let Self {
533            flags,
534            n_nodes,
535            n_edges,
536            n_dropped,
537            key,
538            sections,
539            ..
540        } = self;
541        let sections = sections
542            .into_iter()
543            .filter(|(k, _, _)| *k != ORIGINAL_IDS)
544            .filter(|(k, _, _)| version == VERSION_4 || *k != ID_TABLE)
545            .map(|(k, d, _)| (k, d))
546            .collect();
547        Self::laid_out(version, flags, n_nodes, n_edges, n_dropped, key, sections)
548    }
549
550    /// The size of the main part, in bytes.
551    pub fn file_size(&self) -> u64 {
552        self.trailer_offset + TRAILER_LEN
553    }
554
555    /// Write the main part to `out`. Returns its identity.
556    pub fn write_to(&self, out: impl Write) -> io::Result<MainPart> {
557        let v2 = self.version == VERSION_2;
558        for (_, data, _) in &self.sections {
559            if let Data::IdTable(table) = data {
560                table.build().map_err(io::Error::other)?;
561            }
562        }
563        // Each section's CRC goes in the table, before the section: one pass
564        // over the arrays first (in parallel), then one to write them.
565        let crcs: Vec<Option<u32>> = self
566            .sections
567            .iter()
568            .map(|(_, data, _)| (!v2).then(|| data_crc(data)))
569            .collect();
570        let mut sink = Sink {
571            out,
572            crc: crc32fast::Hasher::new(),
573            at: 0,
574            hash: true,
575        };
576        let mut header = Vec::with_capacity(HEADER_LEN as usize);
577        header.extend_from_slice(&MAGIC);
578        header.extend_from_slice(&self.version.to_le_bytes());
579        header.extend_from_slice(&self.flags.to_le_bytes());
580        header.extend_from_slice(&self.n_nodes.to_le_bytes());
581        header.extend_from_slice(&self.n_edges.to_le_bytes());
582        header.extend_from_slice(&(self.key.len() as u64).to_le_bytes());
583        header.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
584        header.extend_from_slice(&[0; 4]);
585        header.extend_from_slice(&self.file_size().to_le_bytes());
586        header.extend_from_slice(&self.n_dropped.to_le_bytes());
587        header.resize(HEADER_LEN as usize, 0);
588        sink.put(&header)?;
589        sink.put(&self.key)?;
590        sink.pad_to(self.table_offset)?;
591        for ((kind, data, offset), crc) in self.sections.iter().zip(&crcs) {
592            sink.put(&section_entry(*kind, data, *offset, *crc))?;
593        }
594        // The trailer CRC (but version 2's) covers the header, key and
595        // table; the sections have their own.
596        let meta_crc = sink.crc.clone().finalize();
597        sink.hash = v2;
598        for (_, data, offset) in &self.sections {
599            sink.pad_to(*offset)?;
600            sink.put_data(data)?;
601        }
602        sink.pad_to(self.trailer_offset)?;
603        let crc = match v2 {
604            true => sink.crc.clone().finalize(),
605            false => meta_crc,
606        };
607        let mut trailer = Vec::with_capacity(TRAILER_LEN as usize);
608        trailer.extend_from_slice(&self.file_size().to_le_bytes());
609        trailer.extend_from_slice(&crc.to_le_bytes());
610        trailer.extend_from_slice(&END_MAGIC);
611        sink.put(&trailer)?;
612        sink.out.flush()?;
613        Ok(MainPart {
614            len: self.file_size(),
615            crc,
616        })
617    }
618}
619
620/// The identity of a file's main part: its length and CRC. A chunk is read
621/// from, or appended to, a file only while its main part is still this one.
622#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
623pub struct MainPart {
624    pub len: u64,
625    pub crc: u32,
626}
627
628/// A chunk laid out for writing at a given offset of a file.
629pub struct EncodedChunk<'a> {
630    kind: u32,
631    name: Vec<u8>,
632    start: u64,
633    sections: Vec<(u32, Data<'a>, u64)>,
634    name_offset: u64,
635    table_offset: u64,
636}
637
638impl<'a> EncodedChunk<'a> {
639    /// The chunk of the in-adjacency `incoming`, to be written at `start`.
640    pub fn incoming(incoming: &'a Adjacency, start: u64) -> Self {
641        Self::new(
642            CHUNK_INCOMING,
643            Vec::new(),
644            vec![
645                (IN_OFFSETS, Data::U64(&incoming.offsets)),
646                (IN_TARGETS, Data::U32(&incoming.targets)),
647                (IN_EDGE_IDS, Data::edge_ids(&incoming.edge_ids)),
648            ],
649            start,
650        )
651    }
652
653    /// The chunk of the weight columns `columns` (one value per edge row
654    /// each), stored under `key`, to be written at `start`.
655    pub fn weights(key: &str, columns: &[&'a [f64]], start: u64) -> Self {
656        Self::new(
657            CHUNK_WEIGHTS,
658            key.as_bytes().to_vec(),
659            columns
660                .iter()
661                .map(|column| (WEIGHTS_F64, Data::F64(column)))
662                .collect(),
663            start,
664        )
665    }
666
667    fn new(kind: u32, name: Vec<u8>, sections: Vec<(u32, Data<'a>)>, start: u64) -> Self {
668        let mut at = start + CHUNK_HEADER_LEN;
669        let sections = sections
670            .into_iter()
671            .map(|(kind, data)| {
672                at = align(at, SECTION_ALIGN);
673                let offset = at;
674                at += data.width() * data.count();
675                (kind, data, offset)
676            })
677            .collect();
678        let name_offset = at;
679        let table_offset = align(name_offset + name.len() as u64, 8);
680        Self {
681            kind,
682            name,
683            start,
684            sections,
685            name_offset,
686            table_offset,
687        }
688    }
689
690    fn trailer_offset(&self) -> u64 {
691        self.table_offset + CHUNK_ENTRY_LEN * self.sections.len() as u64
692    }
693
694    /// The offset just past the chunk: the file's length once it is written.
695    pub fn end(&self) -> u64 {
696        self.trailer_offset() + CHUNK_TRAILER_LEN
697    }
698
699    /// The chunk's size, in bytes.
700    pub fn size(&self) -> u64 {
701        self.end() - self.start
702    }
703
704    /// Write the chunk to `out`, which is at its start.
705    pub fn write_to(&self, out: impl Write) -> io::Result<()> {
706        let mut sink = Sink {
707            out,
708            crc: crc32fast::Hasher::new(),
709            at: self.start,
710            hash: true,
711        };
712        let mut header = Vec::with_capacity(CHUNK_HEADER_LEN as usize);
713        header.extend_from_slice(&CHUNK_MAGIC);
714        header.extend_from_slice(&self.kind.to_le_bytes());
715        header.extend_from_slice(&self.end().to_le_bytes());
716        sink.put(&header)?;
717        for (_, data, offset) in &self.sections {
718            sink.pad_to(*offset)?;
719            sink.put_data(data)?;
720        }
721        sink.pad_to(self.name_offset)?;
722        let data_crc = std::mem::replace(&mut sink.crc, crc32fast::Hasher::new()).finalize();
723        sink.put(&self.name)?;
724        sink.pad_to(self.table_offset)?;
725        for (kind, data, offset) in &self.sections {
726            sink.put(&section_entry(*kind, data, *offset, None))?;
727        }
728        let mut trailer = Vec::with_capacity(CHUNK_TRAILER_LEN as usize);
729        trailer.extend_from_slice(&self.kind.to_le_bytes());
730        trailer.extend_from_slice(&(self.sections.len() as u32).to_le_bytes());
731        trailer.extend_from_slice(&self.start.to_le_bytes());
732        trailer.extend_from_slice(&self.name_offset.to_le_bytes());
733        trailer.extend_from_slice(&(self.name.len() as u64).to_le_bytes());
734        trailer.extend_from_slice(&data_crc.to_le_bytes());
735        sink.crc.update(&trailer);
736        let meta_crc = sink.crc.clone().finalize();
737        trailer.extend_from_slice(&meta_crc.to_le_bytes());
738        trailer.extend_from_slice(&CHUNK_END_MAGIC);
739        trailer.extend_from_slice(&[0; 4]);
740        sink.out.write_all(&trailer)?;
741        sink.out.flush()
742    }
743}
744
745/// A section table entry: with the section's CRC in a main part (but
746/// version 2's), without in a chunk.
747fn section_entry(kind: u32, data: &Data<'_>, offset: u64, crc: Option<u32>) -> Vec<u8> {
748    let mut entry = Vec::with_capacity(SECTION_ENTRY_LEN as usize);
749    entry.extend_from_slice(&kind.to_le_bytes());
750    entry.extend_from_slice(&(data.width() as u32).to_le_bytes());
751    entry.extend_from_slice(&offset.to_le_bytes());
752    entry.extend_from_slice(&data.count().to_le_bytes());
753    if let Some(crc) = crc {
754        entry.extend_from_slice(&crc.to_le_bytes());
755        entry.extend_from_slice(&[0; 4]);
756    }
757    entry
758}
759
760/// The CRC-32 of the bytes `data` is written as.
761fn data_crc(data: &Data<'_>) -> u32 {
762    /// The bytes of `values`, which are plain numbers.
763    fn bytes_of<T: Copy>(values: &[T]) -> &[u8] {
764        // SAFETY: `T` is a primitive number here (u64, u32, i64, f64): every
765        // byte of it is initialized, and the view spans the slice exactly.
766        unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), size_of_val(values)) }
767    }
768    // On a little-endian machine an array is written as it is in memory, so
769    // its CRC is computed in place, in parallel.
770    if cfg!(target_endian = "little") {
771        let bytes = match data {
772            Data::U64(v) => Some(bytes_of(v)),
773            Data::F64(v) => Some(bytes_of(v)),
774            Data::U32(v) => Some(bytes_of(v)),
775            Data::Ints(a) => Some(bytes_of(a.values())),
776            Data::StrBytes(a) => Some(str_bytes(a)),
777            Data::Bytes(b) => Some(b.as_slice()),
778            Data::IdTable(t) => Some(bytes_of(t.slots())),
779            Data::EdgeIds(ids, built) => Some(bytes_of(ids_of(ids, built))),
780            Data::StrOffsets(_) => None,
781        };
782        if let Some(bytes) = bytes {
783            return super::mapped::crc(bytes);
784        }
785    }
786    let mut sink = Sink {
787        out: io::sink(),
788        crc: crc32fast::Hasher::new(),
789        at: 0,
790        hash: true,
791    };
792    sink.put_data(data)
793        .expect("writing to io::sink does not fail");
794    sink.crc.finalize()
795}
796
797/// A writer that keeps a running CRC (while `hash` is set) and position.
798struct Sink<W> {
799    out: W,
800    crc: crc32fast::Hasher,
801    at: u64,
802    hash: bool,
803}
804
805impl<W: Write> Sink<W> {
806    fn put(&mut self, bytes: &[u8]) -> io::Result<()> {
807        if self.hash {
808            self.crc.update(bytes);
809        }
810        self.at += bytes.len() as u64;
811        self.out.write_all(bytes)
812    }
813
814    fn pad_to(&mut self, offset: u64) -> io::Result<()> {
815        debug_assert!(offset >= self.at);
816        let zeros = [0u8; SECTION_ALIGN as usize];
817        while self.at < offset {
818            let n = ((offset - self.at) as usize).min(zeros.len());
819            self.put(&zeros[..n])?;
820        }
821        Ok(())
822    }
823
824    /// Write one section's array.
825    fn put_data(&mut self, data: &Data<'_>) -> io::Result<()> {
826        match data {
827            Data::U64(v) => self.put_all(v, |x| x.to_le_bytes()),
828            Data::F64(v) => self.put_all(v, |x| x.to_le_bytes()),
829            Data::U32(v) => self.put_all(v, |x| x.to_le_bytes()),
830            Data::Ints(a) => self.put_all(a.values(), |x| x.to_le_bytes()),
831            Data::StrOffsets(a) => {
832                let offsets = a.value_offsets();
833                let base = offsets[0];
834                self.put_all(offsets, |x| (x - base).to_le_bytes())
835            }
836            Data::StrBytes(a) => self.put(str_bytes(a)),
837            Data::Bytes(b) => self.put(b.as_slice()),
838            Data::IdTable(t) => self.put_all(t.slots(), |x| x.to_le_bytes()),
839            Data::EdgeIds(ids, built) => self.put_all(ids_of(ids, built), |x| x.to_le_bytes()),
840        }
841    }
842
843    /// Write `values` little-endian, a block at a time.
844    fn put_all<T: Copy, const N: usize>(
845        &mut self,
846        values: &[T],
847        le: impl Fn(T) -> [u8; N],
848    ) -> io::Result<()> {
849        let mut block = Vec::with_capacity(64 * 1024);
850        for chunk in values.chunks(64 * 1024 / N) {
851            block.clear();
852            for &v in chunk {
853                block.extend_from_slice(&le(v));
854            }
855            self.put(&block)?;
856        }
857        Ok(())
858    }
859}
860
861/// Why a file could not be read as an index.
862pub type DecodeError = String;
863
864/// The edge rows an index left out, and which it kept: nothing left out and
865/// `None` for a graph with no vertex table (see the module docs).
866#[derive(Debug, Clone, Default)]
867pub struct Dropped {
868    pub n_dropped: u64,
869    pub kept: Option<BooleanBuffer>,
870}
871
872/// An index read from its file.
873pub struct Stored {
874    /// With a loader for the in-adjacency, if the file has its chunk.
875    pub topology: Topology,
876    pub ids: IdMap,
877    /// The edge rows left out, and which were kept (see the module docs).
878    pub dropped: Dropped,
879    pub main: MainPart,
880    /// The chunks that check out, in file order.
881    pub chunks: Vec<ChunkInfo>,
882    /// The file's version: [`VERSION`], or [`VERSION_4`], [`VERSION_3`] or
883    /// [`VERSION_2`] for a file 0.12, 0.11 or 0.10 wrote.
884    pub version: u32,
885    /// The checksums of a mapped file that are checked only when something
886    /// reads the arrays whole; `None` when every one was checked as it loaded.
887    pub unverified: Option<Arc<Unverified>>,
888}
889
890/// Whether `chunks` has one of `kind` named `name`.
891pub fn has_chunk(chunks: &[ChunkInfo], kind: u32, name: &[u8]) -> bool {
892    chunks.iter().any(|c| c.kind == kind && c.name == name)
893}
894
895/// How many in-adjacencies have been read from index files, in this process.
896static INCOMING_READS: AtomicU64 = AtomicU64::new(0);
897
898/// How many in-adjacencies this process has read from index files: for
899/// tests that an algorithm read one, or did not.
900pub fn incoming_reads() -> u64 {
901    INCOMING_READS.load(Ordering::Relaxed)
902}
903
904thread_local! {
905    /// How many in-adjacencies this thread has read. Tests run in parallel
906    /// in one process, so a test that must see *no* read counts its own
907    /// thread's: the loader runs on the thread that asks for the
908    /// in-adjacency.
909    static THREAD_INCOMING_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
910}
911
912/// Count one in-adjacency read, for the process and for this thread.
913fn count_incoming_read() {
914    INCOMING_READS.fetch_add(1, Ordering::Relaxed);
915    THREAD_INCOMING_READS.with(|n| n.set(n.get() + 1));
916}
917
918/// How many in-adjacencies this thread has read from index files.
919pub fn thread_incoming_reads() -> u64 {
920    THREAD_INCOMING_READS.with(std::cell::Cell::get)
921}
922
923/// Read the index file at `path`, which must be stored under `key`.
924///
925/// The header, key and section table are read first, so a file for another
926/// key costs only those. Then, for a version 3 or 4 file on a platform that
927/// maps files (`super::mapped`), the file is mapped, up to the end of its
928/// last chunk that checks out: the arrays are borrowed from the map, the
929/// small sections (offsets, ids, the ids' lookup table) are checked now, and
930/// the edge arrays' checksums are deferred to [`Stored::unverified`]. The
931/// ids are not hashed: a version 4 file's lookup table is used as it lies,
932/// and an older file's is built when a query first looks an id up
933/// (`IdMap::from_stored_ids`). Otherwise the main part is read
934/// whole, in parallel, and every checksum is checked before any array is
935/// used. The chunks are only listed; the in-adjacency's is read when the
936/// topology is first asked for it.
937pub fn read_file(path: &Path, key: &IndexKey) -> Result<Stored, DecodeError> {
938    let mut file = File::open(path).map_err(|e| e.to_string())?;
939    let len = file.metadata().map_err(|e| e.to_string())?.len();
940    let head = read_head(&mut file, len, key)?;
941    let (chunks, end) = list_chunks(&mut file, head.main_len, len);
942    let mapped = head.version != VERSION_2 && super::mapped::MAPS;
943    let data = match mapped {
944        true => super::mapped::map(&file, end)?,
945        false => super::mapped::read_whole(&file, head.main_len)?,
946    };
947    let (topology, ids, main, dropped, deferred) = parse(&head, &data, mapped)?;
948    let unverified = mapped.then(|| Arc::new(Unverified::new(data.clone(), deferred)));
949    let topology = match (
950        chunks.iter().find(|c| c.kind == CHUNK_INCOMING),
951        &unverified,
952    ) {
953        (Some(chunk), Some(checks)) => {
954            // Borrowed from the map, its data CRC deferred as the edge
955            // arrays' are.
956            let (chunk, checks) = (chunk.clone(), Arc::clone(checks));
957            let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
958            topology.with_checksummed_incoming_loader(Box::new(move || {
959                let incoming = mapped_incoming(&data, &chunk, n_nodes, n_edges).ok()?;
960                checks
961                    .defer(Region {
962                        what: "in-adjacency",
963                        range: usize::try_from(chunk.start).ok()?
964                            ..usize::try_from(chunk.data_end).ok()?,
965                        crc: chunk.data_crc,
966                    })
967                    .ok()?;
968                count_incoming_read();
969                Some(incoming)
970            }))
971        }
972        (Some(chunk), None) => {
973            let (path, chunk) = (path.to_path_buf(), chunk.clone());
974            let (n_nodes, n_edges) = (topology.n_nodes(), topology.n_edges());
975            topology.with_incoming_loader(Box::new(move || {
976                let incoming = read_incoming(&path, main, &chunk, n_nodes, n_edges).ok()?;
977                count_incoming_read();
978                Some(incoming)
979            }))
980        }
981        (None, _) => topology,
982    };
983    Ok(Stored {
984        topology,
985        ids,
986        dropped,
987        main,
988        chunks,
989        version: head.version,
990        unverified,
991    })
992}
993
994/// Read the main part of the index in `bytes`, which must be stored under
995/// `key`, checking every checksum. Chunks are not read.
996pub fn decode(bytes: &[u8], key: &IndexKey) -> Result<(Topology, IdMap), DecodeError> {
997    decode_main(bytes, key).map(|(topology, ids, _, _)| (topology, ids))
998}
999
1000/// [`decode`], with the main part's identity and the rows left out.
1001fn decode_main(
1002    bytes: &[u8],
1003    key: &IndexKey,
1004) -> Result<(Topology, IdMap, MainPart, Dropped), DecodeError> {
1005    let head = read_head(&mut io::Cursor::new(bytes), bytes.len() as u64, key)?;
1006    // Copied to memory aligned for 64-bit values, as a read file is.
1007    let main = &bytes[..head.main_len as usize];
1008    let mut words = vec![0u64; main.len().div_ceil(8)];
1009    for (word, chunk) in words.iter_mut().zip(main.chunks(8)) {
1010        let mut le = [0u8; 8];
1011        le[..chunk.len()].copy_from_slice(chunk);
1012        *word = u64::from_ne_bytes(le);
1013    }
1014    let data = Buffer::from_vec(words).slice_with_length(0, main.len());
1015    parse(&head, &data, false)
1016        .map(|(topology, ids, main, dropped, _)| (topology, ids, main, dropped))
1017}
1018
1019/// One chunk of a file, as listed: where it is and what it holds.
1020#[derive(Debug, Clone, PartialEq, Eq)]
1021pub struct ChunkInfo {
1022    pub kind: u32,
1023    pub name: Vec<u8>,
1024    pub start: u64,
1025    pub end: u64,
1026    /// The end of its header and sections, which the data CRC covers.
1027    data_end: u64,
1028    data_crc: u32,
1029    /// (kind, width, offset, count), in file order.
1030    sections: Vec<(u32, u64, u64, u64)>,
1031}
1032
1033/// The chunks of a file of `len` bytes whose main part is `main_len` bytes,
1034/// in file order, as far as they check out; and the offset where the next
1035/// chunk goes (the end of the last chunk that checks out). Only the chunks'
1036/// headers, names, tables and trailers are read.
1037pub fn list_chunks<R: Read + Seek>(file: &mut R, main_len: u64, len: u64) -> (Vec<ChunkInfo>, u64) {
1038    let mut chunks = Vec::new();
1039    let mut at = main_len;
1040    while let Some(chunk) = chunk_at(file, at, len) {
1041        at = chunk.end;
1042        chunks.push(chunk);
1043    }
1044    (chunks, at)
1045}
1046
1047fn u32_at(bytes: &[u8], at: usize) -> u32 {
1048    u32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes"))
1049}
1050
1051/// The chunk at `start` of a file of `len` bytes, if one is there whole and
1052/// its header, name, table and trailer check out.
1053fn chunk_at<R: Read + Seek>(file: &mut R, start: u64, len: u64) -> Option<ChunkInfo> {
1054    let read = |file: &mut R, at: u64, n: u64| -> Option<Vec<u8>> {
1055        file.seek(SeekFrom::Start(at)).ok()?;
1056        let mut buf = vec![0; usize::try_from(n).ok()?];
1057        file.read_exact(&mut buf).ok()?;
1058        Some(buf)
1059    };
1060    if len.saturating_sub(start) < CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN {
1061        return None;
1062    }
1063    let header = read(file, start, CHUNK_HEADER_LEN)?;
1064    let end = u64_at(&header, 8);
1065    if header[..4] != CHUNK_MAGIC || end > len || end < start + CHUNK_HEADER_LEN + CHUNK_TRAILER_LEN
1066    {
1067        return None;
1068    }
1069    let kind = u32_at(&header, 4);
1070    let trailer_offset = end - CHUNK_TRAILER_LEN;
1071    let trailer = read(file, trailer_offset, CHUNK_TRAILER_LEN)?;
1072    let n_sections = u32_at(&trailer, 4) as u64;
1073    let name_offset = u64_at(&trailer, 16);
1074    let name_len = u64_at(&trailer, 24);
1075    let table_offset = align(name_offset.checked_add(name_len)?, 8);
1076    if trailer[40..44] != CHUNK_END_MAGIC
1077        || u32_at(&trailer, 0) != kind
1078        || u64_at(&trailer, 8) != start
1079        || name_offset < start + CHUNK_HEADER_LEN
1080        || n_sections
1081            .checked_mul(CHUNK_ENTRY_LEN)?
1082            .checked_add(table_offset)?
1083            != trailer_offset
1084    {
1085        return None;
1086    }
1087    let meta = read(file, name_offset, trailer_offset - name_offset)?;
1088    let mut crc = crc32fast::Hasher::new();
1089    crc.update(&meta);
1090    crc.update(&trailer[..36]);
1091    if crc.finalize() != u32_at(&trailer, 36) {
1092        return None;
1093    }
1094    let name = meta[..name_len as usize].to_vec();
1095    let table = &meta[(table_offset - name_offset) as usize..];
1096    let mut sections = Vec::new();
1097    for entry in table.chunks_exact(CHUNK_ENTRY_LEN as usize) {
1098        let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
1099        let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
1100        width
1101            .checked_mul(count)
1102            .and_then(|n| n.checked_add(offset))
1103            .filter(|&e| offset >= start + CHUNK_HEADER_LEN && e <= name_offset)?;
1104        sections.push((kind, width, offset, count));
1105    }
1106    sections.sort_by_key(|&(_, _, offset, _)| offset);
1107    if sections
1108        .windows(2)
1109        .any(|w| w[0].2 + w[0].1 * w[0].3 > w[1].2)
1110    {
1111        return None;
1112    }
1113    Some(ChunkInfo {
1114        kind,
1115        name,
1116        start,
1117        end,
1118        data_end: name_offset,
1119        data_crc: u32_at(&trailer, 32),
1120        sections,
1121    })
1122}
1123
1124/// Check that the file `file` still has the main part `main`.
1125fn check_main(file: &mut File, main: MainPart) -> Result<(), DecodeError> {
1126    let len = file.metadata().map_err(|e| e.to_string())?.len();
1127    if len < main.len || main.len < HEADER_LEN + TRAILER_LEN {
1128        return Err("the file's main part has changed".into());
1129    }
1130    let mut trailer = [0u8; TRAILER_LEN as usize];
1131    file.seek(SeekFrom::Start(main.len - TRAILER_LEN))
1132        .and_then(|_| file.read_exact(&mut trailer))
1133        .map_err(|e| e.to_string())?;
1134    if u64_at(&trailer, 0) != main.len || u32_at(&trailer, 8) != main.crc {
1135        return Err("the file's main part has changed".into());
1136    }
1137    Ok(())
1138}
1139
1140/// Read the sections of `chunk` from the file at `path`, whose main part
1141/// must still be `main`. Every byte the data CRC covers is read and checked.
1142pub fn read_chunk(
1143    path: &Path,
1144    main: MainPart,
1145    chunk: &ChunkInfo,
1146) -> Result<Vec<(u32, Section)>, DecodeError> {
1147    let mut file = File::open(path).map_err(|e| e.to_string())?;
1148    check_main(&mut file, main)?;
1149    if file.metadata().map_err(|e| e.to_string())?.len() < chunk.end {
1150        return Err("the file is shorter than the chunk".into());
1151    }
1152    file.seek(SeekFrom::Start(chunk.start))
1153        .map_err(|e| e.to_string())?;
1154    let mut src = Source {
1155        inner: BufReader::with_capacity(BLOCK, file),
1156        crc: crc32fast::Hasher::new(),
1157        at: chunk.start,
1158    };
1159    let mut sections = Vec::with_capacity(chunk.sections.len());
1160    for &(kind, width, offset, count) in &chunk.sections {
1161        src.skip_to(offset)?;
1162        sections.push((kind, src.section(kind, width, offset, count)?));
1163    }
1164    src.skip_to(chunk.data_end)?;
1165    if src.crc.finalize() != chunk.data_crc {
1166        return Err("the chunk's checksum does not match".into());
1167    }
1168    Ok(sections)
1169}
1170
1171/// Read the in-adjacency in `chunk` of the file at `path`, for a topology
1172/// of `n_nodes` nodes and `n_edges` edges.
1173fn read_incoming(
1174    path: &Path,
1175    main: MainPart,
1176    chunk: &ChunkInfo,
1177    n_nodes: usize,
1178    n_edges: usize,
1179) -> Result<Adjacency, DecodeError> {
1180    let mut sections = read_chunk(path, main, chunk)?;
1181    let mut take = |kind: u32| {
1182        let i = sections
1183            .iter()
1184            .position(|(k, _)| *k == kind)
1185            .ok_or_else(|| format!("section {kind} is missing"))?;
1186        Ok::<_, DecodeError>(sections.swap_remove(i).1)
1187    };
1188    match (take(IN_OFFSETS)?, take(IN_TARGETS)?, take(IN_EDGE_IDS)?) {
1189        (Section::U64(offsets), Section::U32(targets), Section::U32(edge_ids))
1190            if offsets.len() == n_nodes + 1
1191                && targets.len() == n_edges
1192                && edge_ids.len() == n_edges =>
1193        {
1194            Ok(Adjacency {
1195                offsets: offsets.into(),
1196                targets: targets.into(),
1197                edge_ids: edge_ids.into(),
1198            })
1199        }
1200        _ => Err("the in-adjacency is malformed".into()),
1201    }
1202}
1203
1204/// Read the weight columns in `chunk` of the file at `path`, for a topology
1205/// of `n_edges` edges: one per section, in order.
1206pub fn read_weights(
1207    path: &Path,
1208    main: MainPart,
1209    chunk: &ChunkInfo,
1210    n_edges: usize,
1211) -> Result<Vec<Vec<f64>>, DecodeError> {
1212    read_chunk(path, main, chunk)?
1213        .into_iter()
1214        .map(|(_, section)| match section {
1215            Section::F64(values) if values.len() == n_edges => Ok(values),
1216            _ => Err("the weights are malformed".to_string()),
1217        })
1218        .collect()
1219}
1220
1221/// Append the chunk `encode` lays out (at the offset it is given) to the
1222/// file at `path`, whose main part must still be `main`, after its last
1223/// chunk that checks out; unless the file already has a chunk of `kind`
1224/// named `name`. Returns the file's new length, or `None` if the chunk was
1225/// there already.
1226pub fn append_chunk<'a>(
1227    path: &Path,
1228    main: MainPart,
1229    kind: u32,
1230    name: &[u8],
1231    encode: impl FnOnce(u64) -> EncodedChunk<'a>,
1232) -> io::Result<Option<u64>> {
1233    let mut file = OpenOptions::new().read(true).write(true).open(path)?;
1234    check_main(&mut file, main).map_err(io::Error::other)?;
1235    let len = file.metadata()?.len();
1236    let (chunks, at) = list_chunks(&mut file, main.len, len);
1237    if has_chunk(&chunks, kind, name) {
1238        return Ok(None);
1239    }
1240    let chunk = encode(at);
1241    debug_assert_eq!((chunk.kind, chunk.name.as_slice()), (kind, name));
1242    // What follows the last chunk that checks out (one cut short by a
1243    // crash) is dropped first, so the file never ends in bytes that do not.
1244    if len > at {
1245        file.set_len(at)?;
1246    }
1247    file.seek(SeekFrom::Start(at))?;
1248    let mut out = BufWriter::with_capacity(1 << 20, &file);
1249    chunk.write_to(&mut out)?;
1250    out.into_inner().map_err(|e| e.into_error())?;
1251    file.sync_all()?;
1252    Ok(Some(chunk.end()))
1253}
1254
1255/// The most a read asks for at once, in bytes.
1256const BLOCK: usize = 1 << 20;
1257
1258/// A reader that keeps a running CRC and position.
1259struct Source<R> {
1260    inner: R,
1261    crc: crc32fast::Hasher,
1262    at: u64,
1263}
1264
1265impl<R: Read> Source<R> {
1266    fn fill(&mut self, buf: &mut [u8]) -> Result<(), DecodeError> {
1267        self.inner.read_exact(buf).map_err(|e| match e.kind() {
1268            io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1269            _ => e.to_string(),
1270        })?;
1271        self.crc.update(buf);
1272        self.at += buf.len() as u64;
1273        Ok(())
1274    }
1275
1276    fn bytes(&mut self, n: usize) -> Result<Vec<u8>, DecodeError> {
1277        let mut buf = vec![0; n];
1278        self.fill(&mut buf)?;
1279        Ok(buf)
1280    }
1281
1282    /// Read and discard up to `offset`: padding, or a section this build
1283    /// does not read.
1284    fn skip_to(&mut self, offset: u64) -> Result<(), DecodeError> {
1285        let mut buf = vec![0; BLOCK.min(offset.saturating_sub(self.at) as usize)];
1286        while self.at < offset {
1287            let n = ((offset - self.at) as usize).min(buf.len());
1288            self.fill(&mut buf[..n])?;
1289        }
1290        Ok(())
1291    }
1292
1293    /// `count` little-endian values, a block at a time.
1294    fn values<T, const N: usize>(
1295        &mut self,
1296        count: usize,
1297        le: fn([u8; N]) -> T,
1298    ) -> Result<Vec<T>, DecodeError> {
1299        let mut out = Vec::with_capacity(count);
1300        let mut buf = vec![0; BLOCK.min(count * N)];
1301        while out.len() < count {
1302            let n = ((count - out.len()) * N).min(buf.len());
1303            self.fill(&mut buf[..n])?;
1304            out.extend(read(&buf[..n], le));
1305        }
1306        Ok(out)
1307    }
1308}
1309
1310impl<R: Read> Source<R> {
1311    /// The section of `kind` at `offset` (where the source is): `count`
1312    /// values of `width` bytes. A section this build does not read, or a
1313    /// known one of the wrong width, is skipped and comes back empty.
1314    fn section(
1315        &mut self,
1316        kind: u32,
1317        width: u64,
1318        offset: u64,
1319        count: u64,
1320    ) -> Result<Section, DecodeError> {
1321        let n = usize::try_from(count).map_err(|e| e.to_string())?;
1322        Ok(match (kind, width) {
1323            (OUT_OFFSETS | IN_OFFSETS, 8) => Section::U64(self.values(n, u64::from_le_bytes)?),
1324            (OUT_TARGETS | OUT_EDGE_IDS | IN_TARGETS | IN_EDGE_IDS, 4) => {
1325                Section::U32(self.values(n, u32::from_le_bytes)?)
1326            }
1327            (IDS_INT64, 8) => Section::I64(self.values(n, i64::from_le_bytes)?),
1328            (WEIGHTS_F64, 8) => Section::F64(self.values(n, f64::from_le_bytes)?),
1329            (IDS_STR_OFFSETS, 4) => Section::I32(self.values(n, i32::from_le_bytes)?),
1330            (IDS_STR_BYTES | KEPT_ROWS, 1) => Section::Bytes(self.bytes(n)?),
1331            _ => {
1332                self.skip_to(offset + width * count)?;
1333                Section::Bytes(Vec::new())
1334            }
1335        })
1336    }
1337}
1338
1339/// One section, read.
1340pub enum Section {
1341    U64(Vec<u64>),
1342    F64(Vec<f64>),
1343    U32(Vec<u32>),
1344    I64(Vec<i64>),
1345    I32(Vec<i32>),
1346    Bytes(Vec<u8>),
1347}
1348
1349/// A section table entry, as read.
1350#[derive(Debug, Clone, Copy)]
1351struct Entry {
1352    kind: u32,
1353    width: u64,
1354    offset: u64,
1355    count: u64,
1356    /// The section's CRC (zero in version 2, which has none).
1357    crc: u32,
1358}
1359
1360impl Entry {
1361    fn range(&self) -> Range<usize> {
1362        // Within the main part, which `read_head` checked fits in memory.
1363        self.offset as usize..(self.offset + self.width * self.count) as usize
1364    }
1365}
1366
1367/// The main part's header, key and table, read and checked.
1368struct Head {
1369    version: u32,
1370    flags: u32,
1371    n_nodes: usize,
1372    n_edges: usize,
1373    n_dropped: u64,
1374    main_len: u64,
1375    /// The end of the section table: where the sections may start.
1376    table_end: u64,
1377    /// By offset; they do not overlap.
1378    sections: Vec<Entry>,
1379    /// The trailer's CRC.
1380    crc: u32,
1381}
1382
1383/// Read and check the header, key, section table and trailer of the index
1384/// file in `file`, `len` bytes, which must be stored under `key`. The
1385/// trailer CRC (over the header, key and table) is checked here; version 2's
1386/// covers the sections, so [`parse`] checks it.
1387fn read_head<R: Read + Seek>(file: &mut R, len: u64, key: &IndexKey) -> Result<Head, DecodeError> {
1388    let read = |file: &mut R, at: u64, n: u64| -> Result<Vec<u8>, DecodeError> {
1389        file.seek(SeekFrom::Start(at)).map_err(|e| e.to_string())?;
1390        let mut buf = vec![0; usize::try_from(n).map_err(|e| e.to_string())?];
1391        file.read_exact(&mut buf).map_err(|e| match e.kind() {
1392            io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
1393            _ => e.to_string(),
1394        })?;
1395        Ok(buf)
1396    };
1397    if len < HEADER_LEN + TRAILER_LEN {
1398        return Err(format!("{len} bytes is too short for an index file"));
1399    }
1400    let header = read(file, 0, HEADER_LEN)?;
1401    if header[..8] != MAGIC {
1402        return Err("not an Ursa index file".into());
1403    }
1404    let version = u32_at(&header, 8);
1405    if ![VERSION, VERSION_4, VERSION_3, VERSION_2].contains(&version) {
1406        return Err(format!(
1407            "index format version {version}; this build reads {VERSION_2} to {VERSION}"
1408        ));
1409    }
1410    let flags = u32_at(&header, 12);
1411    let n_nodes = usize::try_from(u64_at(&header, 16)).map_err(|e| e.to_string())?;
1412    let n_edges = usize::try_from(u64_at(&header, 24)).map_err(|e| e.to_string())?;
1413    let key_len = u64_at(&header, 32);
1414    let n_sections = u32_at(&header, 40) as u64;
1415    let main_len = u64_at(&header, 48);
1416    let n_dropped = u64_at(&header, 56);
1417    if main_len > len || main_len < HEADER_LEN + TRAILER_LEN || usize::try_from(main_len).is_err() {
1418        return Err("the file is truncated".into());
1419    }
1420    let body = main_len - TRAILER_LEN;
1421    let key_end = HEADER_LEN
1422        .checked_add(key_len)
1423        .filter(|&end| end <= body)
1424        .ok_or("the key runs past the end of the file")?;
1425    let table = align(key_end, 8);
1426    let entry_len = match version {
1427        VERSION_2 => CHUNK_ENTRY_LEN,
1428        _ => SECTION_ENTRY_LEN,
1429    };
1430    let table_end = n_sections
1431        .checked_mul(entry_len)
1432        .and_then(|n| n.checked_add(table))
1433        .filter(|&end| end <= body)
1434        .ok_or("the section table runs past the end of the file")?;
1435    let rest = read(file, HEADER_LEN, table_end - HEADER_LEN)?;
1436    let trailer = read(file, body, TRAILER_LEN)?;
1437    if trailer[12..] != END_MAGIC || u64_at(&trailer, 0) != main_len {
1438        return Err("the file is truncated".into());
1439    }
1440    let crc = u32_at(&trailer, 8);
1441    if version != VERSION_2 {
1442        let mut meta = crc32fast::Hasher::new();
1443        meta.update(&header);
1444        meta.update(&rest);
1445        if meta.finalize() != crc {
1446            return Err("the checksum does not match".into());
1447        }
1448        if rest[(key_end - HEADER_LEN) as usize..(table - HEADER_LEN) as usize]
1449            .iter()
1450            .any(|&b| b != 0)
1451        {
1452            return Err("the padding is not zero".into());
1453        }
1454    }
1455    let stored: Value = serde_json::from_slice(&rest[..key_len as usize])
1456        .map_err(|e| format!("the key is not JSON: {e}"))?;
1457    if IndexKey::from_json(&stored).as_ref() != Some(key) {
1458        return Err("the file holds an index for another key".into());
1459    }
1460
1461    let entries = &rest[(table - HEADER_LEN) as usize..];
1462    let mut sections = Vec::with_capacity(n_sections as usize);
1463    for entry in entries.chunks_exact(entry_len as usize) {
1464        let (kind, width) = (u32_at(entry, 0), u32_at(entry, 4) as u64);
1465        let (offset, count) = (u64_at(entry, 8), u64_at(entry, 16));
1466        let crc = match version {
1467            VERSION_2 => 0,
1468            _ => u32_at(entry, 24),
1469        };
1470        width
1471            .checked_mul(count)
1472            .and_then(|n| n.checked_add(offset))
1473            .filter(|&end| offset >= table_end && end <= body)
1474            .ok_or("a section runs past the end of the file")?;
1475        sections.push(Entry {
1476            kind,
1477            width,
1478            offset,
1479            count,
1480            crc,
1481        });
1482    }
1483    sections.sort_by_key(|e| e.offset);
1484    if sections
1485        .windows(2)
1486        .any(|w| w[0].offset + w[0].width * w[0].count > w[1].offset)
1487    {
1488        return Err("the sections overlap".into());
1489    }
1490    Ok(Head {
1491        version,
1492        flags,
1493        n_nodes,
1494        n_edges,
1495        n_dropped,
1496        main_len,
1497        table_end,
1498        sections,
1499        crc,
1500    })
1501}
1502
1503/// The sections whose CRCs a mapped file defers (see `super::mapped`): the
1504/// `O(edges)` arrays, which only a whole-graph algorithm reads whole.
1505fn deferred_kind(kind: u32) -> Option<&'static str> {
1506    match kind {
1507        OUT_TARGETS => Some("targets"),
1508        OUT_EDGE_IDS => Some("edge ids"),
1509        _ => None,
1510    }
1511}
1512
1513/// The `count` values of type `T` at byte `offset` of `data`, borrowed.
1514fn scalars<T: ArrowNativeType>(data: &Buffer, entry: &Entry) -> ScalarBuffer<T> {
1515    let size = std::mem::size_of::<T>();
1516    debug_assert_eq!(entry.width as usize, size);
1517    // `data` starts 8-aligned (a map, or a vector of `u64`s) and every
1518    // section at a multiple of 64, so the values are aligned.
1519    ScalarBuffer::new(
1520        data.clone(),
1521        entry.offset as usize / size,
1522        entry.count as usize,
1523    )
1524}
1525
1526/// What [`parse`] makes of a main part.
1527type Parsed = (Topology, IdMap, MainPart, Dropped, Vec<Region>);
1528
1529/// The index in `data`, the main part `head` describes (and maybe more),
1530/// borrowing its arrays. A `mapped` file's edge arrays are not read: their
1531/// CRCs come back to be checked later. Every other checksum is checked here.
1532fn parse(head: &Head, data: &Buffer, mapped: bool) -> Result<Parsed, DecodeError> {
1533    let main_len = head.main_len as usize;
1534    if data.len() < main_len {
1535        return Err("the file is truncated".into());
1536    }
1537    let bytes = &data.as_slice()[..main_len];
1538    let body = main_len - TRAILER_LEN as usize;
1539    let mut deferred = Vec::new();
1540    if head.version == VERSION_2 {
1541        if super::mapped::crc(&bytes[..body]) != head.crc {
1542            return Err("the checksum does not match".into());
1543        }
1544    } else {
1545        // Padding is zero, and each section's CRC matches (or is deferred).
1546        let mut at = head.table_end as usize;
1547        for entry in &head.sections {
1548            let range = entry.range();
1549            if bytes[at..range.start].iter().any(|&b| b != 0) {
1550                return Err("the padding is not zero".into());
1551            }
1552            at = range.end;
1553            match deferred_kind(entry.kind).filter(|_| mapped) {
1554                Some(what) => deferred.push(Region {
1555                    what,
1556                    range,
1557                    crc: entry.crc,
1558                }),
1559                None => {
1560                    if super::mapped::crc(&bytes[range]) != entry.crc {
1561                        return Err(format!(
1562                            "the checksum of section {} does not match",
1563                            entry.kind
1564                        ));
1565                    }
1566                }
1567            }
1568        }
1569        if bytes[at..body].iter().any(|&b| b != 0) {
1570            return Err("the padding is not zero".into());
1571        }
1572    }
1573
1574    let (n_nodes, n_edges) = (head.n_nodes, head.n_edges);
1575    let take = |kind: u32, width: u64, count: Option<usize>| -> Result<Entry, DecodeError> {
1576        let mut found = head.sections.iter().filter(|e| e.kind == kind);
1577        let entry = found
1578            .next()
1579            .ok_or_else(|| format!("section {kind} is missing"))?;
1580        if found.next().is_some() || entry.width != width {
1581            return Err(format!("section {kind} is malformed"));
1582        }
1583        if count.is_some_and(|count| entry.count != count as u64) {
1584            return Err(format!("section {kind} has the wrong length"));
1585        }
1586        Ok(*entry)
1587    };
1588    let out = Adjacency {
1589        offsets: scalars(data, &take(OUT_OFFSETS, 8, Some(n_nodes + 1))?),
1590        targets: scalars(data, &take(OUT_TARGETS, 4, Some(n_edges))?),
1591        edge_ids: scalars(data, &take(OUT_EDGE_IDS, 4, Some(n_edges))?).into(),
1592    };
1593    let topology = match head.version {
1594        // No section CRCs to vouch for the arrays: check them in full.
1595        VERSION_2 => Topology::from_parts(n_nodes, out, None)?,
1596        _ => Topology::from_checksummed_parts(n_nodes, out)?,
1597    };
1598    // The nodes' original ids, if the build relabelled them (#172): only a
1599    // version 5 file has them, and only when it was relabelled.
1600    let topology = match head.sections.iter().any(|e| e.kind == ORIGINAL_IDS) {
1601        true if head.version == VERSION => {
1602            let original = scalars::<u32>(data, &take(ORIGINAL_IDS, 4, Some(n_nodes))?);
1603            topology.with_original_ids(original)?
1604        }
1605        true => return Err(format!("section {ORIGINAL_IDS} is not in this version")),
1606        false => topology,
1607    };
1608
1609    let ids: Arc<dyn Array> = if head.flags & FLAG_STRING_IDS == 0 {
1610        let values = scalars::<i64>(data, &take(IDS_INT64, 8, Some(n_nodes))?);
1611        Arc::new(Int64Array::new(values, None))
1612    } else {
1613        let offsets = scalars::<i32>(data, &take(IDS_STR_OFFSETS, 4, Some(n_nodes + 1))?);
1614        let strings = take(IDS_STR_BYTES, 1, None)?;
1615        if offsets[0] != 0
1616            || offsets.windows(2).any(|w| w[0] > w[1])
1617            || offsets[n_nodes] as u64 != strings.count
1618        {
1619            return Err("the string ids' offsets are malformed".into());
1620        }
1621        let values = data.slice_with_length(strings.offset as usize, strings.count as usize);
1622        if !super::mapped::are_strings(&values, &offsets) {
1623            return Err("the string ids are malformed: they are not UTF-8".into());
1624        }
1625        // SAFETY: the offsets start at 0, never decrease and end at
1626        // `values.len()` (checked above), and they bound valid UTF-8 strings
1627        // (`are_strings`); there are no nulls.
1628        Arc::new(unsafe { StringArray::new_unchecked(OffsetBuffer::new(offsets), values, None) })
1629    };
1630    // The ids' lookup table, as it lies in the file; an older file has none,
1631    // and the id map builds it if a query looks an id up.
1632    let table = match head.version {
1633        VERSION | VERSION_4 => {
1634            let slots = usize::try_from(lookup_table_len(n_nodes)).map_err(|e| e.to_string())?;
1635            Some(scalars::<u32>(data, &take(ID_TABLE, 4, Some(slots))?))
1636        }
1637        _ => None,
1638    };
1639    let ids = IdMap::from_stored_ids(ids, table).map_err(|e| e.to_string())?;
1640    if ids.len() != n_nodes {
1641        return Err("the id map does not match the topology".into());
1642    }
1643    let dropped = match head.n_dropped {
1644        0 => Dropped::default(),
1645        n_dropped => {
1646            let rows = usize::try_from(n_dropped)
1647                .ok()
1648                .and_then(|d| d.checked_add(n_edges))
1649                .ok_or("the kept rows are malformed")?;
1650            let bits = take(KEPT_ROWS, 1, Some(rows.div_ceil(8)))?;
1651            let bits = data.slice_with_length(bits.offset as usize, bits.count as usize);
1652            let kept = BooleanBuffer::new(bits, 0, rows);
1653            if kept.count_set_bits() != n_edges {
1654                return Err("the kept rows do not match the edges".into());
1655            }
1656            Dropped {
1657                n_dropped,
1658                kept: Some(kept),
1659            }
1660        }
1661    };
1662    let main = MainPart {
1663        len: head.main_len,
1664        crc: head.crc,
1665    };
1666    Ok((topology, ids, main, dropped, deferred))
1667}
1668
1669/// The in-adjacency in `chunk` of the mapped file `data`, borrowed, for a
1670/// topology of `n_nodes` nodes and `n_edges` edges. Its data CRC is not
1671/// checked here.
1672fn mapped_incoming(
1673    data: &Buffer,
1674    chunk: &ChunkInfo,
1675    n_nodes: usize,
1676    n_edges: usize,
1677) -> Result<Adjacency, DecodeError> {
1678    if (data.len() as u64) < chunk.end {
1679        return Err("the file is shorter than the chunk".into());
1680    }
1681    let entry = |kind: u32, width: u64, count: usize| -> Result<Entry, DecodeError> {
1682        let mut found = chunk.sections.iter().filter(|s| s.0 == kind);
1683        match (found.next(), found.next()) {
1684            (Some(&(kind, w, offset, c)), None) if w == width && c == count as u64 => Ok(Entry {
1685                kind,
1686                width,
1687                offset,
1688                count: c,
1689                crc: 0,
1690            }),
1691            _ => Err("the in-adjacency is malformed".into()),
1692        }
1693    };
1694    Ok(Adjacency {
1695        offsets: scalars(data, &entry(IN_OFFSETS, 8, n_nodes + 1)?),
1696        targets: scalars(data, &entry(IN_TARGETS, 4, n_edges)?),
1697        edge_ids: scalars(data, &entry(IN_EDGE_IDS, 4, n_edges)?).into(),
1698    })
1699}
1700
1701fn u64_at(bytes: &[u8], at: usize) -> u64 {
1702    u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"))
1703}
1704
1705/// The little-endian values in `bytes`.
1706fn read<T, const N: usize>(
1707    bytes: &[u8],
1708    le: fn([u8; N]) -> T,
1709) -> impl Iterator<Item = T> + use<'_, T, N> {
1710    bytes
1711        .chunks_exact(N)
1712        .map(move |c| le(c.try_into().expect("N bytes")))
1713}
1714
1715#[cfg(test)]
1716mod tests {
1717    use super::*;
1718    use datafusion::arrow::array::ArrayRef;
1719    use datafusion::arrow::datatypes::DataType;
1720
1721    fn key() -> IndexKey {
1722        IndexKey::new(
1723            "Projection: src, dst\n  TableScan: ties".into(),
1724            vec![FileIdentity {
1725                store: "file:///".into(),
1726                location: "data/edges.parquet".into(),
1727                size: 1234,
1728                modified: 1_700_000_000_000_000_000,
1729                e_tag: Some("\"abc\"".into()),
1730            }],
1731        )
1732    }
1733
1734    fn built(src: ArrayRef, dst: ArrayRef) -> (Arc<Topology>, Arc<IdMap>) {
1735        ursa_io::build_topology_batches(&[(src.as_ref(), dst.as_ref())]).unwrap()
1736    }
1737
1738    fn encode(key: &IndexKey, topology: &Topology, ids: &IdMap) -> Vec<u8> {
1739        let encoded = Encoded::new(key, topology, ids).unwrap();
1740        let mut bytes = Vec::new();
1741        encoded.write_to(&mut bytes).unwrap();
1742        assert_eq!(bytes.len() as u64, encoded.file_size());
1743        bytes
1744    }
1745
1746    fn same(a: &Topology, b: &Topology) {
1747        assert_eq!(a.n_nodes(), b.n_nodes());
1748        assert_eq!(a.out().offsets, b.out().offsets);
1749        assert_eq!(a.out().targets, b.out().targets);
1750        assert_eq!(a.out().edge_ids, b.out().edge_ids);
1751    }
1752
1753    #[test]
1754    fn int_and_string_indexes_round_trip() {
1755        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1756        let (topology, ids) = built(ints(&[10, 20, 10, 30]), ints(&[20, 30, 30, 10]));
1757        let bytes = encode(&key(), &topology, &ids);
1758        assert_eq!(&bytes[..8], b"URSAIDX\0");
1759        let (back, back_ids) = decode(&bytes, &key()).unwrap();
1760        same(&topology, &back);
1761        assert!(back.incoming_if_built().is_none());
1762        assert_eq!(
1763            back_ids.user_id_array().as_ref(),
1764            ids.user_id_array().as_ref()
1765        );
1766
1767        // The in-adjacency is never part of the main part.
1768        topology.incoming();
1769        assert_eq!(encode(&key(), &topology, &ids), bytes);
1770
1771        let strs = |v: &[&str]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
1772        let (topology, ids) = built(strs(&["a", "bé", "a"]), strs(&["bé", "c", "c"]));
1773        let bytes = encode(&key(), &topology, &ids);
1774        let (back, back_ids) = decode(&bytes, &key()).unwrap();
1775        same(&topology, &back);
1776        assert_eq!(
1777            back_ids.user_id_array().as_ref(),
1778            ids.user_id_array().as_ref()
1779        );
1780
1781        // Sections are 64-byte aligned, each with its CRC in the table.
1782        let n_sections = u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize;
1783        let table = align(HEADER_LEN + u64_at(&bytes, 32), 8) as usize;
1784        for i in 0..n_sections {
1785            let entry = table + 32 * i;
1786            let (width, offset) = (
1787                u32_at(&bytes, entry + 4) as usize,
1788                u64_at(&bytes, entry + 8),
1789            );
1790            let count = u64_at(&bytes, entry + 16) as usize;
1791            assert_eq!(offset % 64, 0);
1792            let section = &bytes[offset as usize..offset as usize + width * count];
1793            assert_eq!(u32_at(&bytes, entry + 24), crc32fast::hash(section));
1794        }
1795    }
1796
1797    #[test]
1798    fn the_rows_a_vertex_table_left_out_round_trip() {
1799        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1800        let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
1801        // Rows 0 and 3 of four were kept, rows 1 and 2 left out.
1802        let kept = BooleanBuffer::from(vec![true, false, false, true]);
1803        let encoded = Encoded::with_dropped(&key(), &topology, &ids, 2, Some(&kept)).unwrap();
1804        let mut bytes = Vec::new();
1805        encoded.write_to(&mut bytes).unwrap();
1806        let (back, _, _, dropped) = decode_main(&bytes, &key()).unwrap();
1807        same(&topology, &back);
1808        assert_eq!(dropped.n_dropped, 2);
1809        assert_eq!(dropped.kept, Some(kept));
1810        // A file with nothing left out has no such section, as before #311.
1811        let plain = encode(&key(), &topology, &ids);
1812        let (_, _, _, none) = decode_main(&plain, &key()).unwrap();
1813        assert_eq!((none.n_dropped, none.kept), (0, None));
1814    }
1815
1816    #[test]
1817    fn an_empty_index_round_trips() {
1818        let (topology, ids) =
1819            ursa_io::topology::empty_topology(&datafusion::arrow::datatypes::DataType::Utf8);
1820        let (back, back_ids) = decode(&encode(&key(), &topology, &ids), &key()).unwrap();
1821        assert_eq!((back.n_nodes(), back.n_edges()), (0, 0));
1822        assert!(back_ids.is_empty());
1823    }
1824
1825    #[test]
1826    fn corruption_truncation_and_another_key_are_errors() {
1827        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1828        let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1829        let bytes = encode(&key(), &topology, &ids);
1830        for cut in [0, 10, 64, bytes.len() / 2, bytes.len() - 1] {
1831            assert!(decode(&bytes[..cut], &key()).is_err(), "cut at {cut}");
1832        }
1833        for at in [9, 70, bytes.len() / 2, bytes.len() - 20] {
1834            let mut flipped = bytes.clone();
1835            flipped[at] ^= 0x40;
1836            assert!(decode(&flipped, &key()).is_err(), "flipped at {at}");
1837        }
1838        let mut other = key();
1839        other.files[0].size += 1;
1840        assert_eq!(
1841            decode(&bytes, &other).unwrap_err(),
1842            "the file holds an index for another key"
1843        );
1844        assert!(decode(
1845            b"not an index at all, just some text..........................................",
1846            &key()
1847        )
1848        .is_err());
1849    }
1850
1851    /// Write the main part of `topology` to `path`; its identity.
1852    fn write_main(path: &Path, topology: &Topology, ids: &IdMap) -> MainPart {
1853        let encoded = Encoded::new(&key(), topology, ids).unwrap();
1854        let mut file = File::create(path).unwrap();
1855        encoded.write_to(&mut file).unwrap()
1856    }
1857
1858    #[test]
1859    fn the_in_adjacency_is_appended_and_read_on_first_demand() {
1860        let dir = tempfile::tempdir().unwrap();
1861        let path = dir.path().join("x.idx");
1862        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1863        let (topology, ids) = built(
1864            ints(&[10, 20, 10, 30, 20, 40]),
1865            ints(&[20, 30, 30, 10, 40, 10]),
1866        );
1867        let main = write_main(&path, &topology, &ids);
1868        assert_eq!(main.len, std::fs::metadata(&path).unwrap().len());
1869
1870        // No chunk: the transpose is built, nothing is read.
1871        let reads = thread_incoming_reads();
1872        let stored = read_file(&path, &key()).unwrap();
1873        assert!(stored.chunks.is_empty());
1874        assert_eq!(
1875            stored.topology.incoming().targets,
1876            topology.incoming().targets
1877        );
1878        assert_eq!(thread_incoming_reads(), reads);
1879
1880        // Appended once; a second append finds it there.
1881        let incoming = topology.incoming().clone();
1882        let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1883            EncodedChunk::incoming(&incoming, at)
1884        })
1885        .unwrap()
1886        .unwrap();
1887        assert_eq!(end, std::fs::metadata(&path).unwrap().len());
1888        let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1889            EncodedChunk::incoming(&incoming, at)
1890        });
1891        assert_eq!(again.unwrap(), None);
1892
1893        let stored = read_file(&path, &key()).unwrap();
1894        assert_eq!(stored.chunks.len(), 1);
1895        assert_eq!(stored.main, main);
1896        same(&topology, &stored.topology);
1897        // Listed, not read, until asked for.
1898        assert!(stored.topology.incoming_if_built().is_none());
1899        let back = stored.topology.incoming();
1900        assert!(thread_incoming_reads() > reads);
1901        assert_eq!(
1902            (&back.offsets, &back.targets, &back.edge_ids),
1903            (&incoming.offsets, &incoming.targets, &incoming.edge_ids)
1904        );
1905        // The main part reads the same with or without the chunk.
1906        let bytes = std::fs::read(&path).unwrap();
1907        let (main_only, _) = decode(&bytes, &key()).unwrap();
1908        same(&topology, &main_only);
1909    }
1910
1911    #[test]
1912    fn a_damaged_chunk_is_ignored_and_replaced() {
1913        let dir = tempfile::tempdir().unwrap();
1914        let path = dir.path().join("x.idx");
1915        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1916        let (topology, ids) = built(ints(&[1, 2, 3, 1]), ints(&[2, 3, 1, 3]));
1917        let main = write_main(&path, &topology, &ids);
1918        let incoming = topology.incoming().clone();
1919        let end = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1920            EncodedChunk::incoming(&incoming, at)
1921        })
1922        .unwrap()
1923        .unwrap();
1924        let good = std::fs::read(&path).unwrap();
1925
1926        // A flipped byte in the chunk's arrays: listed, but its data CRC
1927        // fails, so the transpose is built instead, the same.
1928        let mut bytes = good.clone();
1929        bytes[main.len as usize + 64] ^= 0x01;
1930        std::fs::write(&path, &bytes).unwrap();
1931        let stored = read_file(&path, &key()).unwrap();
1932        assert_eq!(stored.chunks.len(), 1);
1933        assert!(read_chunk(&path, main, &stored.chunks[0]).is_err());
1934        assert_eq!(stored.topology.incoming().targets, incoming.targets);
1935        assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
1936
1937        // A chunk cut short (a crash mid-append): not listed, and the next
1938        // append writes over it.
1939        std::fs::write(&path, &good[..good.len() - 10]).unwrap();
1940        assert!(read_file(&path, &key()).unwrap().chunks.is_empty());
1941        let again = append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
1942            EncodedChunk::incoming(&incoming, at)
1943        })
1944        .unwrap();
1945        assert_eq!(again, Some(end));
1946        assert_eq!(std::fs::read(&path).unwrap(), good);
1947
1948        // Another main part: nothing is appended or read.
1949        let other = MainPart {
1950            crc: main.crc ^ 1,
1951            ..main
1952        };
1953        assert!(append_chunk(&path, other, CHUNK_INCOMING, b"", |at| {
1954            EncodedChunk::incoming(&incoming, at)
1955        })
1956        .is_err());
1957        let chunk = &read_file(&path, &key()).unwrap().chunks[0];
1958        assert!(read_chunk(&path, other, chunk).is_err());
1959        assert!(read_chunk(&path, main, chunk).is_ok());
1960    }
1961
1962    #[test]
1963    fn weight_chunks_round_trip_by_key() {
1964        let dir = tempfile::tempdir().unwrap();
1965        let path = dir.path().join("x.idx");
1966        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
1967        let (topology, ids) = built(ints(&[1, 2, 3]), ints(&[2, 3, 1]));
1968        let main = write_main(&path, &topology, &ids);
1969        let (a, b) = (vec![0.5, 1.0, f64::MAX], vec![2.0, 0.0, 1e-300]);
1970        for (key, columns) in [("w1", vec![&a[..]]), ("w2", vec![&a[..], &b[..]])] {
1971            let appended = append_chunk(&path, main, CHUNK_WEIGHTS, key.as_bytes(), |at| {
1972                EncodedChunk::weights(key, &columns, at)
1973            });
1974            assert!(appended.unwrap().is_some());
1975        }
1976        let stored = read_file(&path, &key()).unwrap();
1977        assert_eq!(stored.chunks.len(), 2);
1978        let chunk = |name: &[u8]| stored.chunks.iter().find(|c| c.name == name).unwrap();
1979        assert_eq!(
1980            read_weights(&path, main, chunk(b"w1"), 3).unwrap(),
1981            std::slice::from_ref(&a)
1982        );
1983        assert_eq!(read_weights(&path, main, chunk(b"w2"), 3).unwrap(), [a, b]);
1984        // The wrong edge count is an error, never a short column.
1985        assert!(read_weights(&path, main, chunk(b"w1"), 4).is_err());
1986    }
1987
1988    /// The section table entry of `kind` in the main part `bytes` (version
1989    /// 3 or 4): its offset and length in bytes.
1990    fn section_of(bytes: &[u8], kind: u32) -> (usize, usize) {
1991        let n_sections = u32_at(bytes, 40) as usize;
1992        let table = align(HEADER_LEN + u64_at(bytes, 32), 8) as usize;
1993        (0..n_sections)
1994            .map(|i| table + 32 * i)
1995            .find(|&entry| u32_at(bytes, entry) == kind)
1996            .map(|entry| {
1997                let width = u32_at(bytes, entry + 4) as usize;
1998                let count = u64_at(bytes, entry + 16) as usize;
1999                (u64_at(bytes, entry + 8) as usize, width * count)
2000            })
2001            .unwrap()
2002    }
2003
2004    fn a_graph() -> (Arc<Topology>, Arc<IdMap>) {
2005        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2006        built(
2007            ints(&[10, 20, 10, 30, 20, 40, 40, 50]),
2008            ints(&[20, 30, 30, 10, 40, 10, 50, 10]),
2009        )
2010    }
2011
2012    #[test]
2013    fn a_version_2_file_from_0_10_is_read_whole_and_checked() {
2014        let dir = tempfile::tempdir().unwrap();
2015        let path = dir.path().join("x.idx");
2016        let (topology, ids) = a_graph();
2017        let encoded = Encoded::new(&key(), &topology, &ids)
2018            .unwrap()
2019            .as_version_2();
2020        let mut v2 = Vec::new();
2021        let main = encoded.write_to(&mut v2).unwrap();
2022        assert_eq!(u32_at(&v2, 8), VERSION_2);
2023        assert_eq!(main.crc, crc32fast::hash(&v2[..v2.len() - 16]));
2024        std::fs::write(&path, &v2).unwrap();
2025        let stored = read_file(&path, &key()).unwrap();
2026        assert_eq!(stored.version, VERSION_2);
2027        // Read whole, every byte checked: nothing is left to check.
2028        assert!(stored.unverified.is_none());
2029        assert_eq!(stored.main, main);
2030        same(&topology, &stored.topology);
2031        assert_eq!(
2032            stored.ids.user_id_array().as_ref(),
2033            ids.user_id_array().as_ref()
2034        );
2035        // With an in-adjacency appended, as 0.10 appended it.
2036        let incoming = topology.incoming().clone();
2037        append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2038            EncodedChunk::incoming(&incoming, at)
2039        })
2040        .unwrap()
2041        .unwrap();
2042        let stored = read_file(&path, &key()).unwrap();
2043        assert_eq!(stored.topology.incoming().targets, incoming.targets);
2044
2045        // A damaged or truncated version 2 file is an error, never a crash.
2046        for at in [9, 70, v2.len() / 2, v2.len() - 20] {
2047            let mut flipped = v2.clone();
2048            flipped[at] ^= 0x40;
2049            std::fs::write(&path, &flipped).unwrap();
2050            assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
2051        }
2052        for cut in [0, 10, 64, v2.len() / 2, v2.len() - 1] {
2053            std::fs::write(&path, &v2[..cut]).unwrap();
2054            assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
2055        }
2056    }
2057
2058    /// Graphs with integer and with string ids, each id on several edges.
2059    fn graphs() -> [(Arc<Topology>, Arc<IdMap>); 2] {
2060        let n = 300i64;
2061        let (src, dst): (Vec<i64>, Vec<i64>) = (0..n)
2062            .map(|i| (i * 7 - 50, ((i * 13) % n) * 7 - 50))
2063            .unzip();
2064        let name = |v: &[i64]| -> ArrayRef {
2065            Arc::new(StringArray::from(
2066                v.iter()
2067                    .map(|i| format!("did:plc:{i:024}"))
2068                    .collect::<Vec<_>>(),
2069            ))
2070        };
2071        [
2072            built(name(&src), name(&dst)),
2073            built(
2074                Arc::new(Int64Array::from(src)),
2075                Arc::new(Int64Array::from(dst)),
2076            ),
2077        ]
2078    }
2079
2080    /// Every id of `ids` is found at its own node in `stored`, and one that
2081    /// is not there is not found.
2082    fn finds_every_id(stored: &IdMap, ids: &IdMap) {
2083        let column = ids.user_id_array();
2084        assert_eq!(stored.user_id_array().as_ref(), column.as_ref());
2085        let expected: Vec<Option<u32>> = (0..ids.len() as u32).map(Some).collect();
2086        assert_eq!(stored.dense_from_array(column.as_ref()).unwrap(), expected);
2087        let missing: ArrayRef = match column.data_type() {
2088            DataType::Int64 => Arc::new(Int64Array::from(vec![i64::MAX])),
2089            _ => Arc::new(StringArray::from(vec!["nobody"])),
2090        };
2091        assert_eq!(stored.dense_from_array(&missing).unwrap(), vec![None]);
2092    }
2093
2094    /// #421: the ids' lookup table is a section of the file, and a loaded
2095    /// index finds ids through it as it lies there.
2096    #[test]
2097    fn the_id_lookup_table_is_stored_and_used_as_it_lies() {
2098        let dir = tempfile::tempdir().unwrap();
2099        let path = dir.path().join("x.idx");
2100        for (topology, ids) in graphs() {
2101            let bytes = encode(&key(), &topology, &ids);
2102            assert_eq!(u32_at(&bytes, 8), VERSION);
2103            let (at, len) = section_of(&bytes, ID_TABLE);
2104            let table = ids.lookup_table().unwrap();
2105            assert_eq!(len, 4 * table.len());
2106            assert_eq!(len as u64, 4 * lookup_table_len(ids.len()));
2107            let stored_table: Vec<u32> = read(&bytes[at..at + len], u32::from_le_bytes).collect();
2108            assert_eq!(stored_table, table.as_ref());
2109
2110            std::fs::write(&path, &bytes).unwrap();
2111            let stored = read_file(&path, &key()).unwrap();
2112            assert_eq!(stored.version, VERSION);
2113            finds_every_id(&stored.ids, &ids);
2114            // The loaded map's table is the file's: borrowed from the map
2115            // (or the read buffer), never built.
2116            let loaded = stored.ids.lookup_table().unwrap();
2117            assert_eq!(loaded, table);
2118            if super::super::mapped::MAPS {
2119                let mapped = stored.unverified.as_ref().unwrap();
2120                assert!(mapped.holds(loaded.inner().as_ptr()));
2121                // And so are the ids themselves.
2122                let column = stored.ids.user_id_array().to_data();
2123                assert!(mapped.holds(column.buffers()[0].as_ptr()));
2124            }
2125            // Stored again from the loaded index: the same file.
2126            assert_eq!(encode(&key(), &stored.topology, &stored.ids), bytes);
2127            // A table that is not the ids' cannot be told from theirs by its
2128            // CRC alone, so the CRC is what vouches for it: a flipped bit is
2129            // an error when the file loads.
2130            let mut flipped = bytes.clone();
2131            flipped[at + len / 2] ^= 1;
2132            std::fs::write(&path, &flipped).unwrap();
2133            assert!(read_file(&path, &key()).is_err());
2134        }
2135    }
2136
2137    /// #421: a file 0.11 wrote has no lookup table. It is mapped all the
2138    /// same, and its ids are found through a table built on demand.
2139    #[test]
2140    fn a_version_3_file_from_0_11_is_read_and_its_lookup_table_built_on_demand() {
2141        let dir = tempfile::tempdir().unwrap();
2142        let path = dir.path().join("x.idx");
2143        for (topology, ids) in graphs() {
2144            let v4 = encode(&key(), &topology, &ids);
2145            let encoded = Encoded::new(&key(), &topology, &ids)
2146                .unwrap()
2147                .as_version_3();
2148            let mut v3 = Vec::new();
2149            let main = encoded.write_to(&mut v3).unwrap();
2150            assert_eq!(v3.len() as u64, encoded.file_size());
2151            assert_eq!(u32_at(&v3, 8), VERSION_3);
2152            assert!(v3.len() < v4.len());
2153            let n_sections = u32_at(&v3, 40) as usize;
2154            let table = align(HEADER_LEN + u64_at(&v3, 32), 8) as usize;
2155            assert!((0..n_sections).all(|i| u32_at(&v3, table + 32 * i) != ID_TABLE));
2156
2157            std::fs::write(&path, &v3).unwrap();
2158            let stored = read_file(&path, &key()).unwrap();
2159            assert_eq!(stored.version, VERSION_3);
2160            assert_eq!(stored.main, main);
2161            assert_eq!(stored.unverified.is_some(), super::super::mapped::MAPS);
2162            same(&topology, &stored.topology);
2163            finds_every_id(&stored.ids, &ids);
2164            // Stored again, it is the version 4 file.
2165            assert_eq!(encode(&key(), &stored.topology, &stored.ids), v4);
2166
2167            // With an in-adjacency appended, as 0.11 appended it.
2168            let incoming = topology.incoming().clone();
2169            append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2170                EncodedChunk::incoming(&incoming, at)
2171            })
2172            .unwrap()
2173            .unwrap();
2174            let stored = read_file(&path, &key()).unwrap();
2175            assert_eq!(stored.topology.incoming().targets, incoming.targets);
2176        }
2177    }
2178
2179    /// An id stored twice, which no writer stores: a version 4 file cannot
2180    /// be written with one, and an older file with one is an error when an
2181    /// id is first looked up.
2182    #[test]
2183    fn an_id_stored_twice_is_an_error() {
2184        let (topology, _) = a_graph();
2185        let n = topology.n_nodes();
2186        let twice: ArrayRef = Arc::new(Int64Array::from(vec![7i64; n]));
2187        let ids = IdMap::from_stored_ids(Arc::clone(&twice), None).unwrap();
2188        let mut out = Vec::new();
2189        let err = Encoded::new(&key(), &topology, &ids)
2190            .unwrap()
2191            .write_to(&mut out)
2192            .unwrap_err();
2193        assert!(err.to_string().contains("twice"), "{err}");
2194        let mut v3 = Vec::new();
2195        Encoded::new(&key(), &topology, &ids)
2196            .unwrap()
2197            .as_version_3()
2198            .write_to(&mut v3)
2199            .unwrap();
2200        let (_, back) = decode(&v3, &key()).unwrap();
2201        assert_eq!(back.len(), n);
2202        assert!(back.dense_from_array(&twice).is_err());
2203    }
2204
2205    #[test]
2206    fn a_truncated_or_damaged_version_3_file_is_an_error_never_a_crash() {
2207        let dir = tempfile::tempdir().unwrap();
2208        let path = dir.path().join("x.idx");
2209        let (topology, ids) = a_graph();
2210        let main = write_main(&path, &topology, &ids);
2211        let incoming = topology.incoming().clone();
2212        append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2213            EncodedChunk::incoming(&incoming, at)
2214        })
2215        .unwrap();
2216        let good = std::fs::read(&path).unwrap();
2217        let main_len = main.len as usize;
2218        // Cut anywhere in the main part: an error (a mapped reader never
2219        // maps past the end of the file).
2220        for cut in (0..main_len).step_by(7).chain([main_len - 1]) {
2221            std::fs::write(&path, &good[..cut]).unwrap();
2222            assert!(read_file(&path, &key()).is_err(), "cut at {cut}");
2223        }
2224        // Cut in the chunk: the main part reads, the chunk is not listed.
2225        std::fs::write(&path, &good[..good.len() - 1]).unwrap();
2226        let stored = read_file(&path, &key()).unwrap();
2227        assert!(stored.chunks.is_empty());
2228        assert_eq!(stored.topology.incoming().targets, incoming.targets);
2229        // A flipped byte anywhere in the main part but the edge arrays (the
2230        // header, key, table, offsets, ids, padding, trailer) is an error at
2231        // once.
2232        let (targets, t_len) = section_of(&good, OUT_TARGETS);
2233        let (edge_ids, e_len) = section_of(&good, OUT_EDGE_IDS);
2234        let edge_arrays = |at: usize| {
2235            (targets..targets + t_len).contains(&at) || (edge_ids..edge_ids + e_len).contains(&at)
2236        };
2237        for at in (0..main_len).filter(|&at| !edge_arrays(at)) {
2238            let mut flipped = good.clone();
2239            flipped[at] ^= 0x10;
2240            std::fs::write(&path, &flipped).unwrap();
2241            assert!(read_file(&path, &key()).is_err(), "flipped at {at}");
2242        }
2243    }
2244
2245    #[test]
2246    fn the_edge_arrays_checksums_are_checked_before_a_whole_read() {
2247        let dir = tempfile::tempdir().unwrap();
2248        let path = dir.path().join("x.idx");
2249        let (topology, ids) = a_graph();
2250        let main = write_main(&path, &topology, &ids);
2251        let good = std::fs::read(&path).unwrap();
2252        let stored = read_file(&path, &key()).unwrap();
2253        same(&topology, &stored.topology);
2254        if let Some(checks) = &stored.unverified {
2255            checks.verify().unwrap();
2256        }
2257
2258        for kind in [OUT_TARGETS, OUT_EDGE_IDS] {
2259            let (at, _) = section_of(&good, kind);
2260            let mut flipped = good.clone();
2261            // Still in range, so a point traversal could not tell.
2262            flipped[at] ^= 0x01;
2263            std::fs::write(&path, &flipped).unwrap();
2264            // Read whole (as on Windows, and by `decode`): an error at once.
2265            assert!(decode(&flipped, &key()).is_err());
2266            match read_file(&path, &key()) {
2267                // Mapped: the damage is found before a whole-graph read.
2268                Ok(stored) => {
2269                    let checks = stored.unverified.expect("a mapped file defers");
2270                    assert!(!checks.is_damaged());
2271                    let why = checks.verify().unwrap_err();
2272                    assert!(why.contains("does not match"), "{why}");
2273                    assert!(checks.is_damaged());
2274                }
2275                // Read whole where files are not mapped: an error at once.
2276                Err(e) if !super::super::mapped::MAPS => {
2277                    assert!(e.contains("does not match"), "{e}")
2278                }
2279                Err(e) => panic!("{e}"),
2280            }
2281        }
2282
2283        // A damaged in-adjacency, read after the check: the transpose is
2284        // built instead, the same.
2285        std::fs::write(&path, &good).unwrap();
2286        let incoming = topology.incoming().clone();
2287        append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2288            EncodedChunk::incoming(&incoming, at)
2289        })
2290        .unwrap();
2291        let mut bytes = std::fs::read(&path).unwrap();
2292        let chunk = read_file(&path, &key()).unwrap().chunks[0].clone();
2293        let (_, _, edge_ids, _) = chunk.sections[2];
2294        bytes[edge_ids as usize] ^= 0x01;
2295        std::fs::write(&path, &bytes).unwrap();
2296        let stored = read_file(&path, &key()).unwrap();
2297        if let Some(checks) = &stored.unverified {
2298            checks.verify().unwrap();
2299        }
2300        assert_eq!(stored.topology.incoming().targets, incoming.targets);
2301        assert_eq!(stored.topology.incoming().edge_ids, incoming.edge_ids);
2302    }
2303
2304    #[test]
2305    fn a_mapped_index_survives_its_file_being_replaced_or_removed() {
2306        let dir = tempfile::tempdir().unwrap();
2307        let path = dir.path().join("x.idx");
2308        let (topology, ids) = a_graph();
2309        let main = write_main(&path, &topology, &ids);
2310        let incoming = topology.incoming().clone();
2311        append_chunk(&path, main, CHUNK_INCOMING, b"", |at| {
2312            EncodedChunk::incoming(&incoming, at)
2313        })
2314        .unwrap();
2315        let stored = read_file(&path, &key()).unwrap();
2316
2317        // Another index replaces the file the way the store does: written to
2318        // a temporary file, then renamed over it.
2319        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2320        let (other, other_ids) = built(ints(&[7, 8, 9]), ints(&[8, 9, 7]));
2321        let temp = dir.path().join("x.idx.tmp");
2322        write_main(&temp, &other, &other_ids);
2323        std::fs::rename(&temp, &path).unwrap();
2324        assert_eq!(read_file(&path, &key()).unwrap().topology.n_nodes(), 3);
2325
2326        // The index loaded before reads as it was, the arrays whole, and its
2327        // checksums still match (a map keeps the replaced file's pages).
2328        same(&topology, &stored.topology);
2329        assert_eq!(stored.topology.incoming().targets, incoming.targets);
2330        if let Some(checks) = &stored.unverified {
2331            checks.verify().unwrap();
2332        }
2333        // And after the file is removed (an eviction).
2334        std::fs::remove_file(&path).unwrap();
2335        same(&topology, &stored.topology);
2336        assert_eq!(
2337            stored.ids.user_id_array().as_ref(),
2338            ids.user_id_array().as_ref()
2339        );
2340    }
2341
2342    #[test]
2343    fn a_version_1_file_is_not_read() {
2344        let ints = |v: &[i64]| Arc::new(Int64Array::from(v.to_vec())) as ArrayRef;
2345        let (topology, ids) = built(ints(&[1, 2]), ints(&[2, 3]));
2346        let mut bytes = encode(&key(), &topology, &ids);
2347        bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
2348        assert_eq!(
2349            decode(&bytes, &key()).unwrap_err(),
2350            "index format version 1; this build reads 2 to 5"
2351        );
2352    }
2353
2354    #[test]
2355    fn keys_round_trip_through_json() {
2356        let k = key();
2357        assert_eq!(IndexKey::from_json(&k.to_json()), Some(k.clone()));
2358        let mut no_tag = k.clone();
2359        no_tag.files[0].e_tag = None;
2360        assert_eq!(IndexKey::from_json(&no_tag.to_json()), Some(no_tag.clone()));
2361        assert_ne!(no_tag.hash(), k.hash());
2362    }
2363
2364    #[test]
2365    fn a_key_of_another_version_is_not_read() {
2366        let mut json = key().to_json();
2367        json["version"] = 1.into();
2368        assert_eq!(IndexKey::from_json(&json), None);
2369        json.as_object_mut().unwrap().remove("version");
2370        assert_eq!(IndexKey::from_json(&json), None);
2371    }
2372
2373    /// A relabelled index (#172), with string and with integer ids: a
2374    /// topology built in in-degree order, with its id map renumbered to match.
2375    fn relabelled() -> [(Topology, IdMap); 2] {
2376        let n = 200i64;
2377        // Every node points at a few low ids, so in-degrees fall with the id
2378        // and the first-seen order is not the in-degree order.
2379        let (src, dst): (Vec<i64>, Vec<i64>) = (0..4 * n)
2380            .map(|i| ((i * 37) % n, ((i % n) * (i % n)) % (n / 3 + 1 + i % 7)))
2381            .unzip();
2382        let strings = |v: &[i64]| -> ArrayRef {
2383            Arc::new(StringArray::from(
2384                v.iter().map(|i| format!("user-{i}")).collect::<Vec<_>>(),
2385            ))
2386        };
2387        let ints = |v: &[i64]| -> ArrayRef { Arc::new(Int64Array::from(v.to_vec())) };
2388        let build = |column: &dyn Fn(&[i64]) -> ArrayRef| {
2389            let (map, s, d) =
2390                IdMap::from_edge_arrays(column(&src).as_ref(), column(&dst).as_ref()).unwrap();
2391            let topology = Topology::build_ordered(map.len(), s, d, ursa_core::NodeOrder::InDegree);
2392            let original = topology.original_ids().expect("relabelled").to_vec();
2393            let ids = map.reordered(&original);
2394            (topology, ids)
2395        };
2396        [build(&strings), build(&ints)]
2397    }
2398
2399    /// #172: a relabelled index stores its nodes' original ids, and reads
2400    /// them back; its components keep their labels.
2401    #[test]
2402    fn a_relabelled_index_round_trips_with_its_original_ids() {
2403        let dir = tempfile::tempdir().unwrap();
2404        let path = dir.path().join("x.idx");
2405        for (topology, ids) in relabelled() {
2406            let bytes = encode(&key(), &topology, &ids);
2407            assert_eq!(u32_at(&bytes, 8), VERSION);
2408            let (at, len) = section_of(&bytes, ORIGINAL_IDS);
2409            let stored: Vec<u32> = read(&bytes[at..at + len], u32::from_le_bytes).collect();
2410            assert_eq!(stored, topology.original_ids().unwrap());
2411            std::fs::write(&path, &bytes).unwrap();
2412            let back = read_file(&path, &key()).unwrap();
2413            assert_eq!(back.version, VERSION);
2414            same(&topology, &back.topology);
2415            assert_eq!(back.topology.original_ids(), topology.original_ids());
2416            finds_every_id(&back.ids, &ids);
2417            assert_eq!(
2418                ursa_core::algo::connected_components_weak(&back.topology, None),
2419                ursa_core::algo::connected_components_weak(&topology, None)
2420            );
2421            // Stored again from the loaded index: the same file.
2422            assert_eq!(encode(&key(), &back.topology, &back.ids), bytes);
2423            // A damaged order is an error when the file loads.
2424            let mut flipped = bytes.clone();
2425            flipped[at] ^= 1;
2426            std::fs::write(&path, &flipped).unwrap();
2427            assert!(read_file(&path, &key()).is_err());
2428        }
2429        // An index that was not relabelled has no such section.
2430        for (topology, ids) in graphs() {
2431            let bytes = encode(&key(), &topology, &ids);
2432            let n_sections = u32_at(&bytes, 40) as usize;
2433            let table = align(HEADER_LEN + u64_at(&bytes, 32), 8) as usize;
2434            assert!((0..n_sections).all(|i| u32_at(&bytes, table + 32 * i) != ORIGINAL_IDS));
2435        }
2436    }
2437
2438    /// #172: a file 0.12 wrote (version 4: no original ids, its nodes in
2439    /// first-seen order) still opens, keeps its numbering and finds its ids,
2440    /// and is written again as version 5.
2441    #[test]
2442    fn a_version_4_file_from_0_12_is_read_with_its_numbering() {
2443        let dir = tempfile::tempdir().unwrap();
2444        let path = dir.path().join("x.idx");
2445        for (topology, ids) in graphs() {
2446            let v5 = encode(&key(), &topology, &ids);
2447            let encoded = Encoded::new(&key(), &topology, &ids)
2448                .unwrap()
2449                .as_version_4();
2450            let mut v4 = Vec::new();
2451            encoded.write_to(&mut v4).unwrap();
2452            assert_eq!(u32_at(&v4, 8), VERSION_4);
2453            // Version 5 adds no section for an index that is not relabelled:
2454            // the files differ in the version and the header's CRC only.
2455            assert_eq!(v4.len(), v5.len());
2456            let differ: Vec<usize> = (0..v4.len()).filter(|&i| v4[i] != v5[i]).collect();
2457            assert!(
2458                differ.iter().all(|&i| i < 12 || i >= v4.len() - 8),
2459                "{differ:?}"
2460            );
2461            std::fs::write(&path, &v4).unwrap();
2462            let stored = read_file(&path, &key()).unwrap();
2463            assert_eq!(stored.version, VERSION_4);
2464            same(&topology, &stored.topology);
2465            assert!(stored.topology.original_ids().is_none());
2466            finds_every_id(&stored.ids, &ids);
2467            assert_eq!(
2468                stored.ids.lookup_table().unwrap(),
2469                ids.lookup_table().unwrap()
2470            );
2471            assert_eq!(encode(&key(), &stored.topology, &stored.ids), v5);
2472        }
2473    }
2474}