legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
//! A snapshot searched where it lies: its part files mapped into memory and scanned in place.
//!
//! With `kernel::x86` and `kernel::arm`, the only module that uses `unsafe`: mapping a file, and
//! viewing the mapped bytes as 64-bit words. Mapping rests on a promise this crate can't check,
//! that no process changes the files while they are mapped, so its constructors are `unsafe fn`s
//! and the caller makes it.

#![expect(unsafe_code, reason = "mapping a file into memory, and reading its bytes as words")]

use std::marker::PhantomData;
use std::path::Path;

use memmap2::Mmap;
use sha2::{Digest, Sha256};

use crate::cpu::Isa;
use crate::error::{Error, Result};
use crate::kernel;
use crate::scan::TILE;
use crate::search::{Clock, HitList, Memory, Search, Share, Stop, TRIM_RUN};
use crate::snapshot::{self, Fault, Manifest};
use crate::value::Value;

/// A snapshot searched in place: each part file is mapped into memory and scanned as it lies, an
/// id word and then the value's words, least significant first.
///
/// Opening costs no load and no copy: the operating system reads the files in as the first search
/// touches them, and keeps them in its page cache, shared between processes. A scan of this
/// layout reads the ids along with the values, twice the bytes of a [`Scan`](crate::Scan) at
/// 64 bits and 1.25 times at 256. AVX-512 has a kernel for 64-bit records with ids; every other
/// interleaved layout runs the `popcnt` kernel. [`path`](Self::path) says which, and
/// [`variant`](Search::variant) names it.
///
/// Needs a little-endian CPU. Opening it is `unsafe`: the map reads the files as they are on disk
/// for as long as it lives, so a check made when it was opened, a full SHA-256 included, says
/// nothing of what a later search reads. A file truncated in place while mapped ends the process
/// with a bus error at the next read; one rewritten in place changes the bytes under a borrowed
/// slice, which Rust's rules forbid. The caller promises neither happens: see
/// [`open`](Self::open). Replacing a snapshot by writing a new directory and renaming, or
/// unlinking the old one, is safe, as the old files live on until the map is dropped. The
/// [`snapshot::load`] and [`snapshot::verify`] functions own their bytes and need no promise.
///
/// Opening needs `unsafe`, so this doesn't compile:
///
/// ```compile_fail,E0133
/// let dir = std::path::Path::new("snapshot");
/// let mapped = legit_hamming::Mapped::<u64>::open(dir, legit_hamming::Verify::Full);
/// ```
#[derive(Debug)]
pub struct Mapped<V> {
    manifest: Manifest,
    parts: Vec<Mmap>,
    /// The position of each part's first record, and the total at the end.
    starts: Vec<usize>,
    stride: usize,
    isa: Isa,
    value: PhantomData<V>,
}

/// Whether [`Mapped::open`] reads every part through to check it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verify {
    /// Check each part's SHA-256 against the manifest, and that ids rise. Reads every byte once.
    Full,
    /// Check only the manifest and the part sizes. Opening is then instant, and a damaged part
    /// gives wrong results rather than an error.
    SizesOnly,
}

impl<V: Value> Mapped<V> {
    /// The path a snapshot of `V` records, with ids or without, is really scanned on when it is
    /// opened on `isa`. 64-bit values without ids are one column, scanned on whatever path is
    /// asked for. 64-bit records with ids have a kernel of their own on AVX-512. Every other layout
    /// interleaves words the vector kernels don't read, so on a vector path it runs the `popcnt`
    /// kernel, and off x86-64 the scalar one.
    #[must_use]
    pub fn path_for(isa: Isa, ids: bool) -> Isa {
        let stride = V::WORDS + usize::from(ids);
        kernel::interleaved_path(isa, stride, stride - V::WORDS, V::WORDS)
    }

    /// The path this snapshot is really scanned on: see [`path_for`](Self::path_for).
    #[must_use]
    pub fn path(&self) -> Isa {
        kernel::interleaved_path(self.isa, self.stride, self.stride - V::WORDS, V::WORDS)
    }

    /// Map the snapshot in `dir`, scanning on [`Isa::best_for`].
    ///
    /// ```
    /// use legit_hamming::{Mapped, Options, Records, Verify, search, snapshot};
    ///
    /// let dir = std::env::temp_dir().join(format!("legit-hamming-mapped-doc-{}", std::process::id()));
    /// snapshot::write(&dir, &Records::from_records([(7, 0xffu64), (9, 0)])?, 1_000)?;
    /// // SAFETY: this program wrote the snapshot, and nothing truncates or rewrites its files
    /// // until the map is dropped at the end...
    /// let mapped = unsafe { Mapped::<u64>::open(&dir, Verify::Full)? };
    /// let found = search(&mapped, 0xfe, &Options::new(1));
    /// assert_eq!(found.matches[0].id, Some(7));
    /// # drop(mapped);
    /// # std::fs::remove_dir_all(&dir).ok();
    /// # Ok::<(), legit_hamming::Error>(())
    /// ```
    ///
    /// # Safety
    ///
    /// For as long as the map lives, no process, this one included, may truncate or write any of
    /// the snapshot's part files, through any name or descriptor: their bytes are read in place,
    /// and a file shortened while mapped ends the process at the next read, while one rewritten
    /// breaks the guarantee that borrowed bytes don't change. Writing a new snapshot directory
    /// and renaming it into place, or unlinking the old files, keeps the promise.
    ///
    /// # Errors
    ///
    /// What [`Manifest::read`] returns; [`Error::Io`] if a part can't be opened or mapped;
    /// [`Error::Snapshot`] on a big-endian CPU or if a part is a symbolic link, isn't a file of the
    /// size the manifest says, or is another part under a second name; and with [`Verify::Full`],
    /// [`Error::Checksum`] if a part's SHA-256 isn't what the manifest says, [`Error::IdOrder`] if
    /// an id doesn't rise, and [`Error::Snapshot`] if the ids the parts begin and end with aren't
    /// the manifest's.
    pub unsafe fn open(dir: &Path, verify: Verify) -> Result<Self> {
        // SAFETY: the caller's promise, which this passes on...
        unsafe { Self::open_with_isa(dir, verify, Isa::best_for::<V>()) }
    }

    /// Map the snapshot in `dir`, scanning on the path `isa`.
    ///
    /// # Safety
    ///
    /// As [`open`](Self::open): no process truncates or writes the part files, through any name,
    /// while the map lives.
    ///
    /// # Errors
    ///
    /// As [`open`](Self::open), and [`Error::IsaUnavailable`] if this CPU can't run `isa`.
    pub unsafe fn open_with_isa(dir: &Path, verify: Verify, isa: Isa) -> Result<Self> {
        let isa = isa.require()?;
        let manifest = Manifest::read::<V>(dir)?;
        if cfg!(target_endian = "big") {
            return Err(Fault::BigEndian.at(&dir.join(snapshot::MANIFEST), ""));
        }
        snapshot::check_parts(dir, &manifest)?;
        let mut parts = Vec::with_capacity(manifest.parts.len());
        let mut starts = vec![0];
        for part in &manifest.parts {
            // The map outlives the file handle, which closes at the end of each turn...
            let (path, file) = snapshot::open_part(dir, part)?;
            // SAFETY: mapping a file is undefined behaviour if any process changes or shortens it
            // while it is mapped; this function's caller has promised none does, for as long as
            // the map, which `Self` owns, lives...
            let map = unsafe { Mmap::map(&file) }.map_err(|error| Error::io(&path, error))?;
            if verify == Verify::Full {
                snapshot::check_sum(&path, &part.sha256, &Sha256::digest(&map[..]))?;
            }
            parts.push(map);
            starts.push(starts.last().copied().unwrap_or(0) + part.records as usize);
        }
        let stride = snapshot::record_bytes::<V>(manifest.ids) as usize / 8;
        let mapped = Self {
            manifest,
            parts,
            starts,
            stride,
            isa,
            value: PhantomData,
        };
        if verify == Verify::Full && mapped.manifest.ids {
            mapped.check_ids(&dir.join(snapshot::MANIFEST))?;
        }
        Ok(mapped)
    }

    /// The snapshot's manifest.
    #[must_use]
    pub const fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    fn check_ids(&self, manifest_path: &Path) -> Result<()> {
        let (mut first, mut previous): (Option<u64>, Option<u64>) = (None, None);
        for part in 0..self.parts.len() {
            for &id in self.words(part).iter().step_by(self.stride) {
                if let Some(previous) = previous
                    && id <= previous
                {
                    return Err(Error::IdOrder { previous, id });
                }
                first.get_or_insert(id);
                previous = Some(id);
            }
        }
        self.manifest.check_ids(manifest_path, first, previous)
    }

    /// The words of part `part`.
    fn words(&self, part: usize) -> &[u64] {
        let bytes: &[u8] = &self.parts[part];
        // SAFETY: a map starts on a page boundary, so its address is a multiple of 8; `open` has
        // checked the file is a whole number of records, each a multiple of 8 bytes long, and
        // that the CPU is little-endian, so each 8 bytes read as a `u64` give the value the file
        // stores. Every bit pattern is a valid `u64`, and the slice borrows `self`, which owns the
        // map, so it can't outlive it...
        let (head, words, tail) = unsafe { bytes.align_to::<u64>() };
        assert!(
            head.is_empty() && tail.is_empty(),
            "a mapped part is whole aligned words"
        );
        words
    }

    /// The part holding `position`, and the record's words.
    fn record(&self, position: usize) -> &[u64] {
        let part = self.starts.partition_point(|&start| start <= position) - 1;
        let index = position - self.starts[part];
        &self.words(part)[index * self.stride..(index + 1) * self.stride]
    }
}

impl<V: Value> Search<V> for Mapped<V> {
    fn variant(&self) -> String {
        format!("mapped/{}", self.path())
    }

    fn len(&self) -> usize {
        self.starts.last().copied().unwrap_or(0)
    }

    fn has_ids(&self) -> bool {
        self.manifest.ids
    }

    fn id(&self, position: usize) -> Option<u64> {
        self.manifest.ids.then(|| self.record(position)[0])
    }

    fn value(&self, position: usize) -> V {
        let record = self.record(position);
        let mut words = [0u64; 4];
        for (word, &stored) in record[self.stride - V::WORDS..].iter().rev().enumerate() {
            words[word] = stored;
        }
        V::from_words(&words[..V::WORDS])
    }

    fn memory(&self) -> Memory {
        Memory {
            mapped: self.parts.iter().map(|map| map.len()).sum(),
            ..Memory::default()
        }
    }

    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
        let range = share.range(self.len());
        let offset = self.stride - V::WORDS;
        let file_order: Vec<Vec<u64>> = queries
            .iter()
            .map(|query| (0..V::WORDS).rev().map(|word| query.word(word)).collect())
            .collect();
        let mut clock = Clock::new(stop);
        let mut start = range.start;
        while start < range.end {
            let part = self.starts.partition_point(|&first| first <= start) - 1;
            let end = (start + TILE).min(range.end).min(self.starts[part + 1]);
            let local = start - self.starts[part]..end - self.starts[part];
            let words = &self.words(part)[local.start * self.stride..local.end * self.stride];
            for (query, list) in file_order.iter().zip(out.iter_mut()) {
                if clock.spend(end - start) {
                    return true;
                }
                // In runs, each trimmed, so a dense tile can't swell the list past its bound...
                for (run, words) in words.chunks(TRIM_RUN * self.stride).enumerate() {
                    list.prepare(words.len() / self.stride);
                    kernel::scan_interleaved(
                        self.isa,
                        words,
                        self.stride,
                        offset,
                        query,
                        radius,
                        (start + run * TRIM_RUN) as u32,
                        &mut list.hits,
                    );
                    list.trim();
                }
                list.candidates += (end - start) as u64;
            }
            start = end;
        }
        false
    }
}