Skip to main content

ursa_engine/database/
mapped.rs

1//! Loading a stored graph index without reading it whole (#382).
2//!
3//! At full scale a stored index is tens of GiB, and reading it into memory
4//! took 15 s on one core, which every query in a new process paid, even one
5//! that reads the few thousand edges around one node. So an index file is
6//! **memory-mapped** where it can be, and read **in parallel** where it
7//! cannot.
8//!
9//! **The format** (`index_file`, version 3) is the version 2 layout: raw
10//! little-endian arrays at 64-byte-aligned offsets, each a ready `&[u64]` or
11//! `&[u32]` in place, with no decode step. What changes is the checksum. A
12//! version 2 file had one CRC over the whole main part, so nothing in it could
13//! be trusted before every byte was read. Version 3 gives **each section its
14//! own CRC**, in the section table, and the trailer's CRC covers the header,
15//! key and table (so, through the section CRCs, still every byte: it remains
16//! the main part's identity, which chunks are checked against). Padding is
17//! zero, and checked.
18//!
19//! **What is resident and what is mapped.** Loading checks the header, key
20//! and table, then the `O(nodes)` sections in full: the out-adjacency's
21//! offsets (CRC, and that they rise from 0 to the edge count, so every
22//! neighbour slice is in bounds) and the node ids (CRC, then the id map is
23//! built from them, as before). The `O(edges)` sections, the targets and edge
24//! ids, are borrowed from the map as Arrow buffers (`ursa_core::Adjacency`
25//! holds `ScalarBuffer`s) and not read: their CRCs are **deferred**
26//! ([`Unverified`]). The in-adjacency chunk, when a query first asks for it,
27//! is borrowed from the same map the same way, its data CRC deferred too.
28//!
29//! **Who checks the deferred CRCs.** A whole-graph algorithm reads every byte
30//! of the arrays anyway, so before one runs (`GraphAlgorithmExec`) the engine
31//! checks every deferred CRC, in parallel, once per loaded index; a CRC that
32//! does not match drops the stored index and builds it again from its
33//! sources, with a notice, never a result from damaged arrays. A point
34//! traversal (`hop`, `bfs`, a path search) reads only the adjacency lists it
35//! visits and does not check the arrays' CRCs: that is the point of mapping.
36//! Its safety does not rest on them: the offsets are checked, so every slice
37//! is in bounds, and a damaged target or edge id can only fail a bounds check
38//! in a kernel (no kernel indexes with one unchecked), which is a query
39//! error, never undefined behaviour.
40//!
41//! **Atomic replacement, and files that change under a map.** Ursa never
42//! changes a byte of a stored index in place: a new index is written to a
43//! temporary file and renamed over the old one, an eviction unlinks the file,
44//! and a chunk is only appended after the last chunk that checks out. On
45//! Unix a rename or unlink leaves a mapped file's pages in place until the
46//! last map of them goes, so a process keeps reading the index it loaded
47//! while another replaces it. A process maps only the main part and the
48//! chunks that check out when it loads, never the bytes past them, which are
49//! the only bytes an append truncates (a chunk cut short by a crash), so
50//! nothing it maps ever shrinks under it (which would be `SIGBUS`). Editing a
51//! file in `indexes/` by other means while Ursa runs is not supported, as for
52//! any memory-mapped database.
53//!
54//! **Windows** keeps an open mapping from being renamed over or deleted, which
55//! the store relies on, so there (and on any target without `mmap`, and for a
56//! version 2 file, whose single CRC needs every byte read anyway) the file is
57//! read whole, in parallel, into memory ([`read_whole`]), and every CRC is
58//! checked as it loads.
59//!
60//! **Memory accounting.** Mapped pages are the operating system's page
61//! cache: they count in a process's RSS once touched, but they are shared
62//! between processes reading the same index, and the kernel drops clean pages
63//! under memory pressure and reads them again on demand, instead of the
64//! process being killed. A fresh process that answers a point query touches
65//! only the pages it reads. `ursa.index_storage_limit` counts the files on
66//! disk, as before.
67//!
68//! **Compatibility.** A version 2 file (written by 0.10) is read as before,
69//! whole and checked, then rewritten as version 3 by a writable database
70//! (a notice says so), so the next process maps it. Version 1 files are not
71//! read, as before: they are built again.
72
73use std::fs::File;
74use std::ops::Range;
75use std::sync::Mutex;
76
77use datafusion::arrow::buffer::Buffer;
78
79/// Whether this build maps index files: Unix, little-endian (the files are
80/// little-endian, so a mapped array is usable in place).
81pub const MAPS: bool = cfg!(all(
82    unix,
83    target_endian = "little",
84    not(target_arch = "wasm32")
85));
86
87/// The first `len` bytes of `file`, memory-mapped read-only, as an Arrow
88/// buffer that unmaps them when its last clone is dropped.
89#[cfg(all(unix, target_endian = "little", not(target_arch = "wasm32")))]
90pub fn map(file: &File, len: u64) -> Result<Buffer, String> {
91    use std::ptr::NonNull;
92    use std::sync::Arc;
93
94    use rustix::mm::{mmap, munmap, MapFlags, ProtFlags};
95
96    /// A mapping, unmapped on drop.
97    struct Mapping {
98        ptr: NonNull<u8>,
99        len: usize,
100    }
101    // SAFETY: the mapping is read-only and owned by this value alone; the
102    // bytes are only ever read, from any thread.
103    unsafe impl Send for Mapping {}
104    unsafe impl Sync for Mapping {}
105    impl std::panic::RefUnwindSafe for Mapping {}
106    impl Drop for Mapping {
107        fn drop(&mut self) {
108            // SAFETY: `ptr` and `len` are one whole mapping made by `map`,
109            // which no buffer refers to once this, their owner, is dropped.
110            let _ = unsafe { munmap(self.ptr.as_ptr().cast(), self.len) };
111        }
112    }
113
114    let len = usize::try_from(len).map_err(|e| e.to_string())?;
115    if len == 0 {
116        return Ok(Buffer::from_vec(Vec::<u8>::new()));
117    }
118    // SAFETY: a fresh read-only shared mapping of a file Ursa never changes
119    // in place (see the module docs), at an address the kernel picks.
120    let ptr = unsafe {
121        mmap(
122            std::ptr::null_mut(),
123            len,
124            ProtFlags::READ,
125            MapFlags::SHARED,
126            file,
127            0,
128        )
129    }
130    .map_err(|e| format!("cannot map the file: {e}"))?;
131    let ptr = NonNull::new(ptr.cast::<u8>()).ok_or("cannot map the file")?;
132    let owner = Arc::new(Mapping { ptr, len });
133    // SAFETY: `ptr` is valid for `len` bytes for as long as `owner` lives,
134    // which the buffer keeps alive.
135    Ok(unsafe { Buffer::from_custom_allocation(ptr, len, owner) })
136}
137
138/// Mapping is not available on this target: see [`MAPS`].
139#[cfg(not(all(unix, target_endian = "little", not(target_arch = "wasm32"))))]
140pub fn map(_file: &File, _len: u64) -> Result<Buffer, String> {
141    Err("index files are not mapped on this platform".into())
142}
143
144/// The bytes a parallel read or CRC gives each thread, at least.
145const PIECE: usize = 32 << 20;
146
147/// How many threads a parallel read or CRC uses for `len` bytes.
148fn threads_for(len: usize) -> usize {
149    let pieces = len.div_ceil(PIECE).max(1);
150    #[cfg(not(target_arch = "wasm32"))]
151    {
152        let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
153        cores.min(pieces)
154    }
155    // One thread in the browser.
156    #[cfg(target_arch = "wasm32")]
157    {
158        pieces.min(1)
159    }
160}
161
162/// The first `len` bytes of `file`, read into memory, in parallel, as an
163/// Arrow buffer aligned for 64-bit values.
164pub fn read_whole(file: &File, len: u64) -> Result<Buffer, String> {
165    let len = usize::try_from(len).map_err(|e| e.to_string())?;
166    let mut words = vec![0u64; len.div_ceil(8)];
167    {
168        // SAFETY: any bytes are valid `u64`s and the other way round; the
169        // view covers the vector's own allocation and ends before it does.
170        let bytes: &mut [u8] =
171            unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), len) };
172        read_parallel(file, bytes)?;
173    }
174    Ok(Buffer::from_vec(words).slice_with_length(0, len))
175}
176
177/// Fill `bytes` from the start of `file`, a piece per thread.
178fn read_parallel(file: &File, bytes: &mut [u8]) -> Result<(), String> {
179    let threads = threads_for(bytes.len());
180    if threads <= 1 {
181        return read_exact_at(file, bytes, 0);
182    }
183    #[cfg(not(target_arch = "wasm32"))]
184    {
185        let piece = bytes.len().div_ceil(threads);
186        std::thread::scope(|scope| {
187            let reads: Vec<_> = bytes
188                .chunks_mut(piece)
189                .enumerate()
190                .map(|(i, part)| scope.spawn(move || read_exact_at(file, part, (i * piece) as u64)))
191                .collect();
192            reads
193                .into_iter()
194                .try_for_each(|r| r.join().unwrap_or_else(|_| Err("a read failed".into())))
195        })
196    }
197    #[cfg(target_arch = "wasm32")]
198    {
199        read_exact_at(file, bytes, 0)
200    }
201}
202
203/// Fill `buf` from `file` at `offset`.
204fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> Result<(), String> {
205    let short = |e: std::io::Error| match e.kind() {
206        std::io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
207        _ => e.to_string(),
208    };
209    #[cfg(unix)]
210    {
211        std::os::unix::fs::FileExt::read_exact_at(file, buf, offset).map_err(short)
212    }
213    #[cfg(windows)]
214    {
215        let (mut buf, mut offset) = (buf, offset);
216        while !buf.is_empty() {
217            match std::os::windows::fs::FileExt::seek_read(file, buf, offset) {
218                Ok(0) => return Err("the file is truncated".into()),
219                Ok(n) => {
220                    buf = &mut buf[n..];
221                    offset += n as u64;
222                }
223                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
224                Err(e) => return Err(e.to_string()),
225            }
226        }
227        Ok(())
228    }
229    #[cfg(not(any(unix, windows)))]
230    {
231        use std::io::{Read, Seek, SeekFrom};
232        let mut file = file;
233        file.seek(SeekFrom::Start(offset)).map_err(short)?;
234        file.read_exact(buf).map_err(short)
235    }
236}
237
238/// The CRC-32 of `bytes`, computed in parallel pieces that are then combined
239/// (the same value as one pass).
240pub fn crc(bytes: &[u8]) -> u32 {
241    let threads = threads_for(bytes.len());
242    if threads <= 1 {
243        return crc32fast::hash(bytes);
244    }
245    #[cfg(not(target_arch = "wasm32"))]
246    {
247        let piece = bytes.len().div_ceil(threads);
248        let parts: Vec<crc32fast::Hasher> = std::thread::scope(|scope| {
249            let parts: Vec<_> = bytes
250                .chunks(piece)
251                .map(|part| {
252                    scope.spawn(move || {
253                        let mut hasher = crc32fast::Hasher::new();
254                        hasher.update(part);
255                        hasher
256                    })
257                })
258                .collect();
259            parts
260                .into_iter()
261                .map(|p| p.join().expect("a CRC thread does not panic"))
262                .collect()
263        });
264        let mut parts = parts.into_iter();
265        let mut all = parts.next().unwrap_or_default();
266        for part in parts {
267            all.combine(&part);
268        }
269        all.finalize()
270    }
271    #[cfg(target_arch = "wasm32")]
272    {
273        crc32fast::hash(bytes)
274    }
275}
276
277/// One deferred checksum: the bytes `range` of a mapped file, and their CRC.
278#[derive(Debug, Clone)]
279pub struct Region {
280    /// What the bytes are, as a message names them.
281    pub what: &'static str,
282    pub range: Range<usize>,
283    pub crc: u32,
284}
285
286/// The checksums of a mapped index that have not been checked yet (see the
287/// module docs): its edge arrays', and its in-adjacency's once read.
288pub struct Unverified {
289    data: Buffer,
290    state: Mutex<Checks>,
291}
292
293#[derive(Default)]
294struct Checks {
295    pending: Vec<Region>,
296    /// Whether [`Unverified::verify`] has run: a region deferred since is
297    /// checked at once.
298    verified: bool,
299    /// Why the index is damaged, once a checksum has not matched.
300    damage: Option<String>,
301    /// Said once, when the damage is found: drops the stored index.
302    on_damage: Option<Box<dyn FnOnce() + Send>>,
303}
304
305impl std::fmt::Debug for Unverified {
306    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307        let state = self.lock();
308        write!(
309            f,
310            "Unverified({} pending, verified: {}, damage: {:?})",
311            state.pending.len(),
312            state.verified,
313            state.damage
314        )
315    }
316}
317
318impl Unverified {
319    /// The deferred checksums of `regions` of the mapped bytes `data`.
320    pub fn new(data: Buffer, regions: Vec<Region>) -> Self {
321        Self {
322            data,
323            state: Mutex::new(Checks {
324                pending: regions,
325                ..Checks::default()
326            }),
327        }
328    }
329
330    fn lock(&self) -> std::sync::MutexGuard<'_, Checks> {
331        self.state.lock().unwrap_or_else(|e| e.into_inner())
332    }
333
334    /// Call `f` once, if the index is found damaged.
335    pub fn on_damage(&self, f: Box<dyn FnOnce() + Send>) {
336        self.lock().on_damage = Some(f);
337    }
338
339    /// Check every deferred checksum, in parallel, and from now on each
340    /// region as it is deferred. `Err` says what is damaged; it stays damaged.
341    pub fn verify(&self) -> Result<(), String> {
342        let mut state = self.lock();
343        state.verified = true;
344        let pending = std::mem::take(&mut state.pending);
345        for region in &pending {
346            self.check(&mut state, region)?;
347        }
348        state.damage.clone().map_or(Ok(()), Err)
349    }
350
351    /// Defer the checksum of `region`, or check it now if [`Self::verify`]
352    /// has run.
353    pub fn defer(&self, region: Region) -> Result<(), String> {
354        let mut state = self.lock();
355        if state.verified {
356            self.check(&mut state, &region)
357        } else {
358            state.pending.push(region);
359            Ok(())
360        }
361    }
362
363    fn check(&self, state: &mut Checks, region: &Region) -> Result<(), String> {
364        if let Some(damage) = &state.damage {
365            return Err(damage.clone());
366        }
367        let bytes = self.data.as_slice().get(region.range.clone());
368        if bytes.is_some_and(|bytes| crc(bytes) == region.crc) {
369            return Ok(());
370        }
371        let damage = format!("the checksum of its {} does not match", region.what);
372        state.damage = Some(damage.clone());
373        if let Some(f) = state.on_damage.take() {
374            f();
375        }
376        Err(damage)
377    }
378
379    /// Whether a checksum has been found not to match.
380    pub fn is_damaged(&self) -> bool {
381        self.lock().damage.is_some()
382    }
383
384    /// Whether every checksum deferred so far has been checked.
385    pub fn is_verified(&self) -> bool {
386        let state = self.lock();
387        state.verified && state.pending.is_empty()
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394    use std::sync::Arc;
395
396    #[test]
397    fn a_parallel_crc_is_the_serial_one() {
398        let bytes: Vec<u8> = (0..(3 * PIECE + 12345))
399            .map(|i| (i * 31 % 251) as u8)
400            .collect();
401        assert_eq!(crc(&bytes), crc32fast::hash(&bytes));
402        assert_eq!(crc(&bytes[..10]), crc32fast::hash(&bytes[..10]));
403        assert_eq!(crc(&[]), crc32fast::hash(&[]));
404    }
405
406    #[test]
407    fn a_whole_read_is_the_file() {
408        let dir = tempfile::tempdir().unwrap();
409        let path = dir.path().join("x");
410        let bytes: Vec<u8> = (0..(2 * PIECE + 77)).map(|i| (i % 253) as u8).collect();
411        std::fs::write(&path, &bytes).unwrap();
412        let file = File::open(&path).unwrap();
413        let read = read_whole(&file, bytes.len() as u64).unwrap();
414        assert_eq!(read.as_slice(), &bytes[..]);
415        assert_eq!(read.as_ptr() as usize % 8, 0);
416        assert!(read_whole(&file, bytes.len() as u64 + 1).is_err());
417        if MAPS {
418            let mapped = map(&file, bytes.len() as u64).unwrap();
419            assert_eq!(mapped.as_slice(), &bytes[..]);
420        }
421    }
422
423    #[test]
424    fn a_deferred_checksum_is_checked_once_verified() {
425        let data = Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
426        let good = Region {
427            what: "targets",
428            range: 0..4,
429            crc: crc32fast::hash(&[1, 2, 3, 4]),
430        };
431        let bad = Region {
432            what: "in-adjacency",
433            range: 4..8,
434            crc: 0,
435        };
436        let checks = Unverified::new(data, vec![good.clone()]);
437        let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
438        let flag = Arc::clone(&dropped);
439        checks.on_damage(Box::new(move || {
440            flag.store(true, std::sync::atomic::Ordering::SeqCst)
441        }));
442        // Deferred, not checked, before `verify`.
443        checks.defer(bad.clone()).unwrap();
444        assert!(!checks.is_damaged());
445        let err = checks.verify().unwrap_err();
446        assert!(err.contains("in-adjacency"), "{err}");
447        assert!(checks.is_damaged() && dropped.load(std::sync::atomic::Ordering::SeqCst));
448        assert!(checks.verify().is_err());
449
450        let checks = Unverified::new(Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]), vec![good]);
451        checks.verify().unwrap();
452        assert!(checks.is_verified());
453        // Checked at once after `verify`.
454        assert!(checks.defer(bad).is_err());
455    }
456}