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