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`, versions 3 and 4) 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), the node ids (CRC, and that the strings are
23//! UTF-8) and, in version 4, the ids' lookup table (CRC). The id map is those
24//! two arrays as they lie in the map (`IdMap::from_stored_ids`): no id is
25//! hashed or copied when the file loads (#421). A version 3 file has no
26//! table, so one is built in memory, the first time a query looks an id up.
27//! The `O(edges)` sections, the targets and edge
28//! ids, are borrowed from the map as Arrow buffers (`ursa_core::Adjacency`
29//! holds `ScalarBuffer`s) and not read: their CRCs are **deferred**
30//! ([`Unverified`]). The in-adjacency chunk, when a query first asks for it,
31//! is borrowed from the same map the same way, its data CRC deferred too.
32//!
33//! **Who checks the deferred CRCs.** A whole-graph algorithm reads every byte
34//! of the arrays anyway, so before one runs (`GraphAlgorithmExec`) the engine
35//! checks every deferred CRC, in parallel, once per loaded index; a CRC that
36//! does not match drops the stored index and builds it again from its
37//! sources, with a notice, never a result from damaged arrays. A point
38//! traversal (`hop`, `bfs`, a path search) reads only the adjacency lists it
39//! visits and does not check the arrays' CRCs: that is the point of mapping.
40//! Its safety does not rest on them: the offsets are checked, so every slice
41//! is in bounds, and a damaged target or edge id can only fail a bounds check
42//! in a kernel (no kernel indexes with one unchecked), which is a query
43//! error, never undefined behaviour.
44//!
45//! **Atomic replacement, and files that change under a map.** Ursa never
46//! changes a byte of a stored index in place: a new index is written to a
47//! temporary file and renamed over the old one, an eviction unlinks the file,
48//! and a chunk is only appended after the last chunk that checks out. On
49//! Unix a rename or unlink leaves a mapped file's pages in place until the
50//! last map of them goes, so a process keeps reading the index it loaded
51//! while another replaces it. A process maps only the main part and the
52//! chunks that check out when it loads, never the bytes past them, which are
53//! the only bytes an append truncates (a chunk cut short by a crash), so
54//! nothing it maps ever shrinks under it (which would be `SIGBUS`). Editing a
55//! file in `indexes/` by other means while Ursa runs is not supported, as for
56//! any memory-mapped database.
57//!
58//! **Windows** keeps an open mapping from being renamed over or deleted, which
59//! the store relies on, so there (and on any target without `mmap`, and for a
60//! version 2 file, whose single CRC needs every byte read anyway) the file is
61//! read whole, in parallel, into memory ([`read_whole`]), and every CRC is
62//! checked as it loads.
63//!
64//! **Memory accounting.** Mapped pages are the operating system's page
65//! cache: they count in a process's RSS once touched, but they are shared
66//! between processes reading the same index, and the kernel drops clean pages
67//! under memory pressure and reads them again on demand, instead of the
68//! process being killed. A fresh process that answers a point query touches
69//! only the pages it reads. `ursa.index_storage_limit` counts the files on
70//! disk, as before.
71//!
72//! **Compatibility.** A version 2 file (written by 0.10) is read as before,
73//! whole and checked, and a version 3 file (0.11) is mapped; a writable
74//! database then rewrites either as version 4 (a notice says so), so the
75//! next process maps it and finds its ids' lookup table in it. Version 1
76//! files are not read, as before: they are built again.
77
78use std::fs::File;
79use std::ops::Range;
80use std::sync::Mutex;
81
82use datafusion::arrow::buffer::Buffer;
83
84/// Whether this build maps index files: Unix, little-endian (the files are
85/// little-endian, so a mapped array is usable in place).
86pub const MAPS: bool = cfg!(all(
87    unix,
88    target_endian = "little",
89    not(target_arch = "wasm32")
90));
91
92/// The first `len` bytes of `file`, memory-mapped read-only, as an Arrow
93/// buffer that unmaps them when its last clone is dropped.
94#[cfg(all(unix, target_endian = "little", not(target_arch = "wasm32")))]
95pub fn map(file: &File, len: u64) -> Result<Buffer, String> {
96    use std::ptr::NonNull;
97    use std::sync::Arc;
98
99    use rustix::mm::{mmap, munmap, MapFlags, ProtFlags};
100
101    /// A mapping, unmapped on drop.
102    struct Mapping {
103        ptr: NonNull<u8>,
104        len: usize,
105    }
106    // SAFETY: the mapping is read-only and owned by this value alone; the
107    // bytes are only ever read, from any thread.
108    unsafe impl Send for Mapping {}
109    unsafe impl Sync for Mapping {}
110    impl std::panic::RefUnwindSafe for Mapping {}
111    impl Drop for Mapping {
112        fn drop(&mut self) {
113            // SAFETY: `ptr` and `len` are one whole mapping made by `map`,
114            // which no buffer refers to once this, their owner, is dropped.
115            let _ = unsafe { munmap(self.ptr.as_ptr().cast(), self.len) };
116        }
117    }
118
119    let len = usize::try_from(len).map_err(|e| e.to_string())?;
120    if len == 0 {
121        return Ok(Buffer::from_vec(Vec::<u8>::new()));
122    }
123    // SAFETY: a fresh read-only shared mapping of a file Ursa never changes
124    // in place (see the module docs), at an address the kernel picks.
125    let ptr = unsafe {
126        mmap(
127            std::ptr::null_mut(),
128            len,
129            ProtFlags::READ,
130            MapFlags::SHARED,
131            file,
132            0,
133        )
134    }
135    .map_err(|e| format!("cannot map the file: {e}"))?;
136    let ptr = NonNull::new(ptr.cast::<u8>()).ok_or("cannot map the file")?;
137    let owner = Arc::new(Mapping { ptr, len });
138    // SAFETY: `ptr` is valid for `len` bytes for as long as `owner` lives,
139    // which the buffer keeps alive.
140    Ok(unsafe { Buffer::from_custom_allocation(ptr, len, owner) })
141}
142
143/// Mapping is not available on this target: see [`MAPS`].
144#[cfg(not(all(unix, target_endian = "little", not(target_arch = "wasm32"))))]
145pub fn map(_file: &File, _len: u64) -> Result<Buffer, String> {
146    Err("index files are not mapped on this platform".into())
147}
148
149/// The bytes a parallel read or CRC gives each thread, at least.
150const PIECE: usize = 32 << 20;
151
152/// How many threads a parallel read or CRC uses for `len` bytes.
153fn threads_for(len: usize) -> usize {
154    let pieces = len.div_ceil(PIECE).max(1);
155    #[cfg(not(target_arch = "wasm32"))]
156    {
157        let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
158        cores.min(pieces)
159    }
160    // One thread in the browser.
161    #[cfg(target_arch = "wasm32")]
162    {
163        pieces.min(1)
164    }
165}
166
167/// The first `len` bytes of `file`, read into memory, in parallel, as an
168/// Arrow buffer aligned for 64-bit values.
169pub fn read_whole(file: &File, len: u64) -> Result<Buffer, String> {
170    let len = usize::try_from(len).map_err(|e| e.to_string())?;
171    let mut words = vec![0u64; len.div_ceil(8)];
172    {
173        // SAFETY: any bytes are valid `u64`s and the other way round; the
174        // view covers the vector's own allocation and ends before it does.
175        let bytes: &mut [u8] =
176            unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), len) };
177        read_parallel(file, bytes)?;
178    }
179    Ok(Buffer::from_vec(words).slice_with_length(0, len))
180}
181
182/// Fill `bytes` from the start of `file`, a piece per thread.
183fn read_parallel(file: &File, bytes: &mut [u8]) -> Result<(), String> {
184    let threads = threads_for(bytes.len());
185    if threads <= 1 {
186        return read_exact_at(file, bytes, 0);
187    }
188    #[cfg(not(target_arch = "wasm32"))]
189    {
190        let piece = bytes.len().div_ceil(threads);
191        std::thread::scope(|scope| {
192            let reads: Vec<_> = bytes
193                .chunks_mut(piece)
194                .enumerate()
195                .map(|(i, part)| scope.spawn(move || read_exact_at(file, part, (i * piece) as u64)))
196                .collect();
197            reads
198                .into_iter()
199                .try_for_each(|r| r.join().unwrap_or_else(|_| Err("a read failed".into())))
200        })
201    }
202    #[cfg(target_arch = "wasm32")]
203    {
204        read_exact_at(file, bytes, 0)
205    }
206}
207
208/// Fill `buf` from `file` at `offset`.
209fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> Result<(), String> {
210    let short = |e: std::io::Error| match e.kind() {
211        std::io::ErrorKind::UnexpectedEof => "the file is truncated".to_string(),
212        _ => e.to_string(),
213    };
214    #[cfg(unix)]
215    {
216        std::os::unix::fs::FileExt::read_exact_at(file, buf, offset).map_err(short)
217    }
218    #[cfg(windows)]
219    {
220        let (mut buf, mut offset) = (buf, offset);
221        while !buf.is_empty() {
222            match std::os::windows::fs::FileExt::seek_read(file, buf, offset) {
223                Ok(0) => return Err("the file is truncated".into()),
224                Ok(n) => {
225                    buf = &mut buf[n..];
226                    offset += n as u64;
227                }
228                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
229                Err(e) => return Err(e.to_string()),
230            }
231        }
232        Ok(())
233    }
234    #[cfg(not(any(unix, windows)))]
235    {
236        use std::io::{Read, Seek, SeekFrom};
237        let mut file = file;
238        file.seek(SeekFrom::Start(offset)).map_err(short)?;
239        file.read_exact(buf).map_err(short)
240    }
241}
242
243/// The CRC-32 of `bytes`, computed in parallel pieces that are then combined
244/// (the same value as one pass).
245pub fn crc(bytes: &[u8]) -> u32 {
246    let threads = threads_for(bytes.len());
247    if threads <= 1 {
248        return crc32fast::hash(bytes);
249    }
250    #[cfg(not(target_arch = "wasm32"))]
251    {
252        let piece = bytes.len().div_ceil(threads);
253        let parts: Vec<crc32fast::Hasher> = std::thread::scope(|scope| {
254            let parts: Vec<_> = bytes
255                .chunks(piece)
256                .map(|part| {
257                    scope.spawn(move || {
258                        let mut hasher = crc32fast::Hasher::new();
259                        hasher.update(part);
260                        hasher
261                    })
262                })
263                .collect();
264            parts
265                .into_iter()
266                .map(|p| p.join().expect("a CRC thread does not panic"))
267                .collect()
268        });
269        let mut parts = parts.into_iter();
270        let mut all = parts.next().unwrap_or_default();
271        for part in parts {
272            all.combine(&part);
273        }
274        all.finalize()
275    }
276    #[cfg(target_arch = "wasm32")]
277    {
278        crc32fast::hash(bytes)
279    }
280}
281
282/// Whether `values` and `offsets` are the bytes and offsets of valid strings:
283/// string `i` is `values[offsets[i]..offsets[i + 1]]`, and each is UTF-8.
284/// This is what makes them a `StringArray` (`StringArray::new_unchecked`),
285/// checked in parallel pieces: the ids of a stored index are read once here,
286/// on all cores, when it loads.
287///
288/// The offsets must rise (not strictly) and end within `values`, which the
289/// caller has checked.
290pub fn are_strings(values: &[u8], offsets: &[i32]) -> bool {
291    /// The strings `offsets` bounds, a run of them at a time.
292    fn piece(values: &[u8], offsets: &[i32]) -> bool {
293        const RUN: usize = 1 << 12;
294        // One element is shared between runs: the end of one and the start
295        // of the next.
296        let mut at = 0;
297        while at + 1 < offsets.len() {
298            let run = &offsets[at..(at + RUN + 1).min(offsets.len())];
299            let (first, last) = (run[0] as usize, run[run.len() - 1] as usize);
300            let bytes = &values[first..last];
301            // ASCII is UTF-8 wherever it is cut. Otherwise the run must be
302            // UTF-8 as a whole, and cut only between characters.
303            if !bytes.is_ascii() {
304                let Ok(text) = std::str::from_utf8(bytes) else {
305                    return false;
306                };
307                if !run
308                    .iter()
309                    .all(|&o| text.is_char_boundary(o as usize - first))
310                {
311                    return false;
312                }
313            }
314            at += RUN;
315        }
316        true
317    }
318    let Some(strings) = offsets.len().checked_sub(1) else {
319        return false;
320    };
321    let threads = threads_for(values.len()).min(strings.max(1));
322    if threads <= 1 {
323        return piece(values, offsets);
324    }
325    #[cfg(not(target_arch = "wasm32"))]
326    {
327        let each = strings.div_ceil(threads);
328        std::thread::scope(|scope| {
329            let pieces: Vec<_> = (0..threads)
330                .map(|t| {
331                    let from = (t * each).min(strings);
332                    let to = ((t + 1) * each).min(strings);
333                    scope.spawn(move || piece(values, &offsets[from..=to]))
334                })
335                .collect();
336            // A piece left unjoined here is joined as the scope ends.
337            pieces
338                .into_iter()
339                .all(|p| p.join().expect("a string check does not panic"))
340        })
341    }
342    #[cfg(target_arch = "wasm32")]
343    {
344        piece(values, offsets)
345    }
346}
347
348/// One deferred checksum: the bytes `range` of a mapped file, and their CRC.
349#[derive(Debug, Clone)]
350pub struct Region {
351    /// What the bytes are, as a message names them.
352    pub what: &'static str,
353    pub range: Range<usize>,
354    pub crc: u32,
355}
356
357/// The checksums of a mapped index that have not been checked yet (see the
358/// module docs): its edge arrays', and its in-adjacency's once read.
359pub struct Unverified {
360    data: Buffer,
361    state: Mutex<Checks>,
362}
363
364#[derive(Default)]
365struct Checks {
366    pending: Vec<Region>,
367    /// Whether [`Unverified::verify`] has run: a region deferred since is
368    /// checked at once.
369    verified: bool,
370    /// Why the index is damaged, once a checksum has not matched.
371    damage: Option<String>,
372    /// Said once, when the damage is found: drops the stored index.
373    on_damage: Option<Box<dyn FnOnce() + Send>>,
374}
375
376impl std::fmt::Debug for Unverified {
377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378        let state = self.lock();
379        write!(
380            f,
381            "Unverified({} pending, verified: {}, damage: {:?})",
382            state.pending.len(),
383            state.verified,
384            state.damage
385        )
386    }
387}
388
389impl Unverified {
390    /// The deferred checksums of `regions` of the mapped bytes `data`.
391    pub fn new(data: Buffer, regions: Vec<Region>) -> Self {
392        Self {
393            data,
394            state: Mutex::new(Checks {
395                pending: regions,
396                ..Checks::default()
397            }),
398        }
399    }
400
401    fn lock(&self) -> std::sync::MutexGuard<'_, Checks> {
402        self.state.lock().unwrap_or_else(|e| e.into_inner())
403    }
404
405    /// Call `f` once, if the index is found damaged.
406    pub fn on_damage(&self, f: Box<dyn FnOnce() + Send>) {
407        self.lock().on_damage = Some(f);
408    }
409
410    /// Check every deferred checksum, in parallel, and from now on each
411    /// region as it is deferred. `Err` says what is damaged; it stays damaged.
412    pub fn verify(&self) -> Result<(), String> {
413        let mut state = self.lock();
414        state.verified = true;
415        let pending = std::mem::take(&mut state.pending);
416        for region in &pending {
417            self.check(&mut state, region)?;
418        }
419        state.damage.clone().map_or(Ok(()), Err)
420    }
421
422    /// Defer the checksum of `region`, or check it now if [`Self::verify`]
423    /// has run.
424    pub fn defer(&self, region: Region) -> Result<(), String> {
425        let mut state = self.lock();
426        if state.verified {
427            self.check(&mut state, &region)
428        } else {
429            state.pending.push(region);
430            Ok(())
431        }
432    }
433
434    fn check(&self, state: &mut Checks, region: &Region) -> Result<(), String> {
435        if let Some(damage) = &state.damage {
436            return Err(damage.clone());
437        }
438        let bytes = self.data.as_slice().get(region.range.clone());
439        if bytes.is_some_and(|bytes| crc(bytes) == region.crc) {
440            return Ok(());
441        }
442        let damage = format!("the checksum of its {} does not match", region.what);
443        state.damage = Some(damage.clone());
444        if let Some(f) = state.on_damage.take() {
445            f();
446        }
447        Err(damage)
448    }
449
450    /// Whether `ptr` points into the mapped bytes: for tests that an array
451    /// is borrowed from the map, not built or copied.
452    #[cfg(test)]
453    pub fn holds(&self, ptr: *const u8) -> bool {
454        self.data.as_slice().as_ptr_range().contains(&ptr)
455    }
456
457    /// Whether a checksum has been found not to match.
458    pub fn is_damaged(&self) -> bool {
459        self.lock().damage.is_some()
460    }
461
462    /// Whether every checksum deferred so far has been checked.
463    pub fn is_verified(&self) -> bool {
464        let state = self.lock();
465        state.verified && state.pending.is_empty()
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472    use std::sync::Arc;
473
474    #[test]
475    fn strings_are_checked_as_arrow_checks_them() {
476        use datafusion::arrow::array::StringArray;
477        use datafusion::arrow::buffer::{Buffer, OffsetBuffer, ScalarBuffer};
478        // What `StringArray::try_new` accepts is what `are_strings` accepts.
479        let agree = |values: &[u8], offsets: &[i32]| {
480            let arrow = StringArray::try_new(
481                OffsetBuffer::new(ScalarBuffer::from(offsets.to_vec())),
482                Buffer::from(values.to_vec()),
483                None,
484            )
485            .is_ok();
486            assert_eq!(
487                are_strings(values, offsets),
488                arrow,
489                "{values:?} {offsets:?}"
490            );
491            arrow
492        };
493        assert!(agree(b"", &[0]));
494        assert!(agree(b"abc", &[0, 1, 1, 3]));
495        assert!(agree("h\u{e9}llo".as_bytes(), &[0, 3, 6]));
496        // Cut inside a character, and bytes that are no character.
497        assert!(!agree("h\u{e9}llo".as_bytes(), &[0, 2, 6]));
498        assert!(!agree(&[b'a', 0xff, b'b'], &[0, 1, 3]));
499        assert!(!agree(&[0xe2, 0x82], &[0, 2]));
500        // Bytes past the last offset are not part of any string.
501        assert!(are_strings(&[b'a', 0xff], &[0, 1]));
502
503        // Long enough for several threads and many runs, with the one
504        // damaged byte or offset anywhere.
505        let n = 300_000usize;
506        let mut values = Vec::new();
507        let mut offsets = vec![0i32];
508        for i in 0..n {
509            let id = match i % 5 {
510                0 => format!("n\u{e9}-{i:0200}"),
511                _ => format!("did:plc:{i:0300}"),
512            };
513            values.extend_from_slice(id.as_bytes());
514            offsets.push(values.len() as i32);
515        }
516        assert!(threads_for(values.len()) > 1 || cfg!(target_arch = "wasm32"));
517        assert!(are_strings(&values, &offsets));
518        for at in [
519            0,
520            1,
521            values.len() / 3,
522            values.len() / 2 + 7,
523            values.len() - 1,
524        ] {
525            let mut damaged = values.clone();
526            damaged[at] = 0xff;
527            assert!(!are_strings(&damaged, &offsets), "byte {at}");
528        }
529        for i in [0, n / 4, n / 2, n - 5] {
530            // The first id of each five starts "n\u{e9}": one byte further
531            // is inside the character.
532            let i = i - i % 5;
533            let mut cut = offsets.clone();
534            cut[i] += 2;
535            assert!(!are_strings(&values, &cut), "offset {i}");
536        }
537    }
538
539    #[test]
540    fn a_parallel_crc_is_the_serial_one() {
541        let bytes: Vec<u8> = (0..(3 * PIECE + 12345))
542            .map(|i| (i * 31 % 251) as u8)
543            .collect();
544        assert_eq!(crc(&bytes), crc32fast::hash(&bytes));
545        assert_eq!(crc(&bytes[..10]), crc32fast::hash(&bytes[..10]));
546        assert_eq!(crc(&[]), crc32fast::hash(&[]));
547    }
548
549    #[test]
550    fn a_whole_read_is_the_file() {
551        let dir = tempfile::tempdir().unwrap();
552        let path = dir.path().join("x");
553        let bytes: Vec<u8> = (0..(2 * PIECE + 77)).map(|i| (i % 253) as u8).collect();
554        std::fs::write(&path, &bytes).unwrap();
555        let file = File::open(&path).unwrap();
556        let read = read_whole(&file, bytes.len() as u64).unwrap();
557        assert_eq!(read.as_slice(), &bytes[..]);
558        assert_eq!(read.as_ptr() as usize % 8, 0);
559        assert!(read_whole(&file, bytes.len() as u64 + 1).is_err());
560        if MAPS {
561            let mapped = map(&file, bytes.len() as u64).unwrap();
562            assert_eq!(mapped.as_slice(), &bytes[..]);
563        }
564    }
565
566    #[test]
567    fn a_deferred_checksum_is_checked_once_verified() {
568        let data = Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]);
569        let good = Region {
570            what: "targets",
571            range: 0..4,
572            crc: crc32fast::hash(&[1, 2, 3, 4]),
573        };
574        let bad = Region {
575            what: "in-adjacency",
576            range: 4..8,
577            crc: 0,
578        };
579        let checks = Unverified::new(data, vec![good.clone()]);
580        let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
581        let flag = Arc::clone(&dropped);
582        checks.on_damage(Box::new(move || {
583            flag.store(true, std::sync::atomic::Ordering::SeqCst)
584        }));
585        // Deferred, not checked, before `verify`.
586        checks.defer(bad.clone()).unwrap();
587        assert!(!checks.is_damaged());
588        let err = checks.verify().unwrap_err();
589        assert!(err.contains("in-adjacency"), "{err}");
590        assert!(checks.is_damaged() && dropped.load(std::sync::atomic::Ordering::SeqCst));
591        assert!(checks.verify().is_err());
592
593        let checks = Unverified::new(Buffer::from_vec(vec![1u8, 2, 3, 4, 5, 6, 7, 8]), vec![good]);
594        checks.verify().unwrap();
595        assert!(checks.is_verified());
596        // Checked at once after `verify`.
597        assert!(checks.defer(bad).is_err());
598    }
599}