Skip to main content

malware_modeler/
ngram.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use crate::dataset::Dataset;
4use crate::ftype::FileType;
5use crate::hash::{FxBuildHasher, FxHashMap, hash_bytes};
6use crate::{Bytes, MAX_RECURSION_DEPTH};
7
8use std::fs::File;
9use std::io::{self, BufRead, BufReader, Lines, Read, Write};
10use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicUsize, Ordering};
12
13use crate::model::LogisticRegression;
14use anyhow::{Result, anyhow, bail, ensure};
15use dashmap::DashMap;
16use rayon::prelude::*;
17use walkdir::WalkDir;
18
19/// Largest chunk read when walking a file's n-gram windows.
20///
21/// The buffer is sized to the file when the file is smaller. Reading 4 KiB at a time, as this
22/// used to, costs a syscall per 4 KiB — millions of them over a large corpus.
23pub(crate) const WINDOW_BUFFER_SIZE: u32 = 1 << 20;
24
25/// Visit every `n`-byte window of a file, in order.
26///
27/// Reads in large chunks, carrying the last `n - 1` bytes of each chunk forward so the windows
28/// straddling a chunk boundary are still seen. The three copies of this logic that preceded it
29/// each read 4 KiB at a time and re-seeked backwards to overlap the chunks, costing three
30/// syscalls per 4 KiB, and two of them dropped the final window of the file.
31///
32/// # Errors
33///
34/// Returns an error if the file can't be read, or if `visit` fails.
35pub(crate) fn for_each_window<F>(path: &Path, n: u16, mut visit: F) -> Result<()>
36where
37    F: FnMut(&[u8]) -> Result<()>,
38{
39    ensure!(n > 0, "N-gram size must be greater than zero.");
40
41    let file_size = path.metadata()?.len();
42    if file_size < u64::from(n) {
43        // Nothing to look at: the file is shorter than one window.
44        return Ok(());
45    }
46
47    let n_usize = n as usize;
48    let capacity = usize::try_from(file_size)
49        .unwrap_or(WINDOW_BUFFER_SIZE as usize)
50        .min(WINDOW_BUFFER_SIZE as usize)
51        .max(n_usize);
52    let mut buffer = vec![0u8; capacity];
53    let mut reader = BufReader::with_capacity(capacity, File::open(path)?);
54    let mut filled = 0usize;
55
56    loop {
57        let read = reader.read(&mut buffer[filled..])?;
58        if read == 0 {
59            break;
60        }
61        filled += read;
62
63        if filled < n_usize {
64            continue;
65        }
66
67        for window in buffer[..filled].windows(n_usize) {
68            visit(window)?;
69        }
70
71        // Keep the tail that could still begin a window spanning into the next chunk.
72        let carry = n_usize - 1;
73        buffer.copy_within(filled - carry..filled, 0);
74        filled = carry;
75    }
76
77    Ok(())
78}
79
80// The output is wrapped in a Result to allow matching on errors.
81// Returns an Iterator to the Reader of the lines of the file.
82// https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html
83fn read_lines<P: AsRef<Path>>(filename: P) -> io::Result<Lines<BufReader<File>>> {
84    let file = File::open(filename)?;
85    Ok(BufReader::new(file).lines())
86}
87
88pub(crate) fn stride_from_line(line: &str) -> Result<u16> {
89    line.split(':')
90        .nth(1)
91        .ok_or_else(|| anyhow!("Invalid stride"))?
92        .trim()
93        .parse()
94        .map_err(Into::into)
95}
96
97/// N-grams as read from a file
98#[derive(Clone)]
99pub struct NgramsFile {
100    /// N-grams and their index position
101    ///
102    /// Keyed with [`crate::hash::FxHasher`]: this map is probed once per byte of every sample
103    /// during featurization, where SipHash costs more than the lookup itself.
104    pub ngrams: FxHashMap<Bytes, usize>,
105
106    /// File type represented by the n-grams
107    pub ftype: FileType,
108
109    /// Convenience: keep track of the size of the n-grams (value of `n`)
110    pub n: u16,
111
112    /// Stride
113    pub s: u16,
114}
115
116impl NgramsFile {
117    /// Load the n-grams from an existing model or from a plain text file.
118    ///
119    /// # Errors
120    ///
121    /// An error results if:
122    /// * The file cannot be read
123    /// * The file type is not specified
124    /// * The n-grams aren't hexidecimal
125    /// * The n-grams are different sizes
126    pub fn load<P: AsRef<Path>>(ngrams_file: P) -> Result<Self> {
127        if let Ok(model) = LogisticRegression::load(ngrams_file.as_ref()) {
128            return Ok(model.into());
129        }
130
131        let mut file_type = FileType::NotSet;
132        let mut n = 0;
133        let mut s = 0;
134        let mut ngrams = FxHashMap::default();
135
136        let lines = read_lines(&ngrams_file)?;
137        let mut ngram_counter = 0;
138        let mut line_counter = 0u32;
139        for line in lines.map_while(Result::ok) {
140            if line.starts_with("# File type:") {
141                if let Ok(ftype) = Dataset::file_type_from_line(&line) {
142                    file_type = ftype;
143                }
144                line_counter += 1;
145                continue;
146            }
147
148            if line.starts_with("# Stride:") {
149                s = stride_from_line(&line)?;
150                line_counter += 1;
151                continue;
152            }
153
154            // Ignore other metadata
155            if line.starts_with('#') {
156                line_counter += 1;
157                continue;
158            }
159
160            let line = if let Some(l) = line.split(',').next() {
161                l
162            } else {
163                &line
164            };
165
166            if !line.len().is_multiple_of(2) {
167                bail!("Line {line_counter} {line} has odd number of characters.");
168            }
169
170            if n == 0 {
171                n = u16::try_from(line.len())? / 2;
172            } else if u16::try_from(line.len())? / 2 != n {
173                bail!(
174                    "Line {line_counter} {line} has unexpected length of {} bytes, expected {n}",
175                    line.len() / 2
176                );
177            }
178
179            match hex::decode(line) {
180                Ok(ngram) => {
181                    ngrams.insert(ngram, ngram_counter);
182                    ngram_counter += 1;
183                }
184                Err(e) => bail!("Line {line_counter} has non-hexidecimal ngram {line}: {e}"),
185            }
186            line_counter += 1;
187        }
188
189        ensure!(
190            !ngrams.is_empty(),
191            "No n-grams read from {}.",
192            ngrams_file.as_ref().display()
193        );
194        ensure!(
195            file_type != FileType::NotSet,
196            "No file type specified in n-grams file."
197        );
198
199        Ok(Self {
200            ngrams,
201            ftype: file_type,
202            n,
203            s,
204        })
205    }
206
207    /// Convert the n-gram map into a vector, preserving their order
208    #[must_use]
209    pub fn into_vec(self) -> Vec<Bytes> {
210        let mut ngrams_vec = vec![Vec::new(); self.ngrams.len()];
211        for (ngram, index) in self.ngrams {
212            ngrams_vec[index] = ngram;
213        }
214        ngrams_vec
215    }
216
217    /// Borrow the n-grams in index order.
218    ///
219    /// Unlike [`NgramsFile::into_vec`] this clones nothing, which matters when there are a
220    /// million of them: cloning the map to consume it costs tens of megabytes and as long as
221    /// writing the header it feeds.
222    #[must_use]
223    pub fn as_vec(&self) -> Vec<&Bytes> {
224        let mut ngrams_vec: Vec<&Bytes> = Vec::new();
225        ngrams_vec.resize(self.ngrams.len(), &EMPTY_NGRAM);
226        for (ngram, index) in &self.ngrams {
227            if let Some(slot) = ngrams_vec.get_mut(*index) {
228                *slot = ngram;
229            }
230        }
231        ngrams_vec
232    }
233}
234
235/// Placeholder for an index no n-gram claims, which [`NgramsFile::load`] never leaves behind.
236static EMPTY_NGRAM: Bytes = Vec::new();
237
238/// N-gramming object
239pub struct Ngrammer {
240    /// Size of the byte sequence
241    pub(crate) n: u16,
242
243    /// Number of n-grams to keep
244    pub(crate) k: usize,
245
246    /// N-gram stride: roughly one n-gram in `s` is sampled
247    pub(crate) s: u16,
248
249    /// Largest hash an n-gram can have and still be sampled, `u64::MAX / s`
250    pub(crate) keep_below: u64,
251
252    /// File paths to be viewed
253    pub(crate) paths: Vec<PathBuf>,
254
255    /// Expected file type
256    pub(crate) ftype: FileType,
257
258    /// N-grams discovered, keyed with [`crate::hash::FxHasher`] like the rest of the n-gram maps
259    pub(crate) ngrams: DashMap<Bytes, usize, FxBuildHasher>,
260}
261
262impl Ngrammer {
263    /// The size of the array for storing hashes of found n-grams
264    #[cfg(not(feature = "low-memory"))]
265    pub const COUNTS: usize = 2_000_000;
266
267    /// The size of the array for storing hashes of found n-grams on low-memory systems
268    #[cfg(feature = "low-memory")]
269    pub const COUNTS: usize = 100_000;
270
271    /// Number of `u64` words needed for a bitset with one bit per [`Self::COUNTS`] bucket
272    const BITSET_WORDS: usize = Self::COUNTS.div_ceil(u64::BITS as usize);
273
274    /// The hash bucket of an n-gram, or `None` if the stride leaves it out.
275    ///
276    /// The n-gram is sampled when its hash is in the lowest `1 / stride` of the range. The
277    /// survivors are then stretched back over the whole range and mapped onto [`Self::COUNTS`]
278    /// by multiply-shift, so every bucket is used whatever the stride. Choosing on
279    /// `bucket % stride` instead, as this used to, left all but one bucket in `stride` empty.
280    #[inline]
281    #[allow(clippy::cast_possible_truncation)]
282    fn select_hash(hash: u64, stride: u16, keep_below: u64) -> Option<usize> {
283        if hash > keep_below {
284            return None;
285        }
286        // Cannot overflow: `hash <= u64::MAX / stride`.
287        let stretched = hash * u64::from(stride);
288        Some(((u128::from(stretched) * Self::COUNTS as u128) >> u64::BITS) as usize)
289    }
290
291    /// The hash bucket of an n-gram, or `None` if the stride leaves it out.
292    #[inline]
293    fn select(&self, window: &[u8]) -> Option<usize> {
294        Self::select_hash(hash_bytes(window), self.s, self.keep_below)
295    }
296
297    /// Return an n-gram calculation object and the number of files skipped if their types
298    /// didn't match, if the `skip_unknown` variable was true.
299    ///
300    /// # Errors
301    ///
302    /// An error will occur if:
303    /// * the provided directory path doesn't exist, isn't a directory, or can't be traversed,
304    /// * the n-gram size `n` is less than 2,
305    /// * the n-grams to keep `k` is less than 10,
306    /// * the stride `s` is less than 1,
307    /// * the file type isn't provided and the file types observed aren't the same without the
308    ///   `skip_unknown` parameter being true
309    /// * the file type isn't provided and it can't be detected
310    pub fn new(
311        ftype: Option<FileType>,
312        dir: &Path,
313        n: u16,
314        k: usize,
315        s: u16,
316        verbose: bool,
317        skip_unknowns: bool,
318    ) -> Result<(Self, u32)> {
319        ensure!(s > 0, "N-gram stride must be greater than zero.");
320        ensure!(n > 1, "N-gram size must be greater than one.");
321        ensure!(k > 9, "N-grams to keep must be ten or greater.");
322        ensure!(
323            dir.exists(),
324            "Provided path {} does not exist.",
325            dir.display()
326        );
327        ensure!(
328            dir.is_dir(),
329            "Provided path {} is not a directory.",
330            dir.display()
331        );
332
333        let mut paths = Vec::new();
334        let mut skipped = 0u32;
335        let allow_downgrade = ftype.is_none();
336        let mut ftype = ftype.unwrap_or(FileType::NotSet);
337
338        for entry in WalkDir::new(dir)
339            .max_depth(MAX_RECURSION_DEPTH)
340            .follow_links(true)
341            .into_iter()
342            .flatten()
343        {
344            if entry.file_type().is_file() {
345                if ftype != FileType::NotSet && !ftype.matches_path(entry.path())? {
346                    if let Ok(Some(detected)) = FileType::from_path(entry.path()) {
347                        if detected == FileType::DsStore {
348                            continue;
349                        }
350
351                        // User had entered `None`, so we can see if a downgrade is possible.
352                        if allow_downgrade {
353                            let new_type = ftype.downgrade(detected)?;
354                            if verbose {
355                                println!(
356                                    "{}: Downgrading from {ftype} to {new_type}",
357                                    entry.path().display()
358                                );
359                            }
360                            ftype = new_type;
361                        } else if skip_unknowns {
362                            skipped += 1;
363                        } else {
364                            bail!(
365                                "File {} detected as {detected} which does not match expected type {ftype:?}",
366                                entry.path().display()
367                            );
368                        }
369                    } else if skip_unknowns {
370                        skipped += 1;
371                    } else {
372                        // The encountered file doesn't match the expected type, and we
373                        // couldn't figure out this file's type
374                        bail!(
375                            "File {} does not match expected type {ftype:?}",
376                            entry.path().display()
377                        );
378                    }
379                } else if ftype == FileType::NotSet {
380                    if let Some(detected_type) = FileType::from_path(entry.path())? {
381                        if detected_type == FileType::DsStore {
382                            continue;
383                        }
384
385                        ftype = detected_type;
386                        if verbose {
387                            println!(
388                                "{}: Detected file type {detected_type}",
389                                entry.path().display()
390                            );
391                        }
392                    } else if skip_unknowns {
393                        skipped += 1;
394                    } else {
395                        bail!("Unknown file type for {}", entry.path().display());
396                    }
397                }
398
399                // If we're here, all type checks have passed.
400                paths.push(entry.into_path());
401            }
402        }
403
404        ensure!(!paths.is_empty(), "No files found!");
405        ensure!(
406            ftype != FileType::NotSet,
407            "No file type specified in n-grams file."
408        );
409
410        Ok((
411            Self {
412                n,
413                k,
414                s,
415                keep_below: u64::MAX / u64::from(s),
416                paths,
417                ftype,
418                ngrams: DashMap::default(),
419            },
420            skipped,
421        ))
422    }
423
424    /// Find the n-grams storing the results internally
425    ///
426    /// N-grams are only held for the `k` fullest hash buckets, and no more than [`Self::COUNTS`] of
427    /// them in all, so that is the most that are ever found, even if `k` asks for more.
428    #[allow(clippy::cast_possible_truncation)]
429    pub fn find(&mut self) {
430        let data: Vec<AtomicUsize> = (0..Self::COUNTS).map(|_| AtomicUsize::new(0)).collect();
431
432        self.paths.par_iter().for_each(|p| {
433            // Each file contributes one count per bucket it touches. The stride was already
434            // applied when the bitset was built, so every set bit is counted.
435            for (word_index, word) in self.find_ngram(p).unwrap_or_default().iter().enumerate() {
436                let mut word = *word;
437                while word != 0 {
438                    let bucket = word_index * u64::BITS as usize + word.trailing_zeros() as usize;
439                    data[bucket].fetch_add(1, Ordering::Relaxed);
440                    // Clear the lowest set bit.
441                    word &= word - 1;
442                }
443            }
444        });
445
446        // Keep the counts of the `k` fullest buckets and zero the rest, so that a non-zero count
447        // is what marks a bucket as kept. A bucket's count is at most the number of files, so a
448        // histogram that size finds the k-th largest without copying the counts to sort them.
449        if self.k < Self::COUNTS {
450            let mut histogram = vec![0usize; self.paths.len() + 1];
451            for count in &data {
452                histogram[count.load(Ordering::Relaxed)] += 1;
453            }
454
455            // Walk down from the fullest buckets to the count the k-th one has. Buckets above
456            // it are all kept; those level with it only until `k` is reached.
457            let mut min_count = 0;
458            let mut ties_left = self.k;
459            for (count, buckets) in histogram.iter().enumerate().rev() {
460                min_count = count;
461                if *buckets >= ties_left {
462                    break;
463                }
464                ties_left -= buckets;
465            }
466
467            for count in &data {
468                let value = count.load(Ordering::Relaxed);
469                if value == min_count && ties_left > 0 {
470                    ties_left -= 1;
471                } else if value <= min_count {
472                    count.store(0, Ordering::Relaxed);
473                }
474            }
475        }
476
477        // Candidates are every n-gram of a kept bucket, collisions included, up to `COUNTS` of
478        // them: past that no more are taken, so the map can't outgrow the counts however large
479        // `n` or `k` are. A slot is reserved in `held` before an n-gram is inserted, which makes
480        // the limit exact rather than something the threads can race past.
481        //
482        // This used to have no limit, which for a `k` at or past `COUNTS` meant every distinct
483        // n-gram in the corpus, and ran out of memory.
484        let candidates: DashMap<Bytes, usize, FxBuildHasher> = DashMap::default();
485        let held = AtomicUsize::new(0);
486        self.paths.par_iter().for_each(|p| {
487            let walked = for_each_window(p, self.n, |window| {
488                // Buckets are shared with n-grams the stride left out, so those have to be
489                // turned away here too, not just left uncounted.
490                let Some(bucket) = self.select(window) else {
491                    return Ok(());
492                };
493                let count = data[bucket].load(Ordering::Relaxed);
494                // Nothing is allocated or looked up past this point unless the bucket was
495                // kept, which keeps the per-window cost to a hash and a load.
496                if count == 0 || candidates.contains_key(window) {
497                    return Ok(());
498                }
499                // The count only ever overshoots by threads about to back out, so the n-grams
500                // actually inserted stay within the limit.
501                if held.fetch_add(1, Ordering::Relaxed) >= Self::COUNTS
502                    || candidates.insert(window.to_vec(), count).is_some()
503                {
504                    // Full, or another thread inserted the same n-gram first: hand the slot back.
505                    held.fetch_sub(1, Ordering::Relaxed);
506                }
507                Ok(())
508            });
509
510            if let Err(e) = walked {
511                eprintln!("Failed to read {}: {e}", p.display());
512            }
513        });
514
515        // Only `k` buckets were kept, but n-grams that share one are all candidates, so there
516        // can be more than `k` of them. Take the k most frequent, which is what "top k n-grams"
517        // means and what the caller asked for.
518        let mut ranked: Vec<(Bytes, usize)> = candidates.into_iter().collect();
519        if ranked.len() > self.k {
520            // Partition around the k-th highest count rather than sorting all of them, breaking
521            // ties on the n-gram itself so the same candidates always yield the same n-grams.
522            ranked.select_nth_unstable_by(self.k, |(a_ngram, a), (b_ngram, b)| {
523                b.cmp(a).then_with(|| a_ngram.cmp(b_ngram))
524            });
525            ranked.truncate(self.k);
526        }
527
528        let kept_ngrams: DashMap<Bytes, usize, FxBuildHasher> =
529            DashMap::with_capacity_and_hasher(ranked.len(), FxBuildHasher::default());
530        for (ngram, count) in ranked {
531            kept_ngrams.insert(ngram, count);
532        }
533        self.ngrams = kept_ngrams;
534    }
535
536    /// Return a bitset marking every hash bucket this file has an n-gram in.
537    #[allow(clippy::cast_possible_truncation)]
538    fn find_ngram(&self, path: &Path) -> Result<Vec<u64>> {
539        let mut buckets = vec![0u64; Self::BITSET_WORDS];
540
541        for_each_window(path, self.n, |window| {
542            let Some(bucket) = self.select(window) else {
543                return Ok(());
544            };
545            buckets[bucket / u64::BITS as usize] |= 1 << (bucket % u64::BITS as usize);
546            Ok(())
547        })?;
548
549        Ok(buckets)
550    }
551
552    /// Save the n-grams as a plain text file
553    ///
554    /// # Errors
555    ///
556    /// An error occurs if the file cannot be opened or cannot be written.
557    pub fn save<P: AsRef<Path>>(&self, path: P, with_counts: bool) -> Result<()> {
558        let mut output = File::create(path)?;
559        writeln!(
560            output,
561            "# File type: {}\n# Original files: {}\n# Stride: {}",
562            self.ftype,
563            self.paths.len(),
564            self.s
565        )?;
566        if self.s > 1 {
567            writeln!(output, "# Stride: {}", self.s)?;
568        }
569        for entry in &self.ngrams {
570            if with_counts {
571                writeln!(output, "{},{}", hex::encode(entry.key()), entry.value())?;
572            } else {
573                writeln!(output, "{}", hex::encode(entry.key()))?;
574            }
575        }
576        output.flush()?;
577        Ok(())
578    }
579
580    /// Return the n-grams discovered
581    #[inline]
582    #[must_use]
583    pub fn ngrams(&self) -> &DashMap<Bytes, usize, FxBuildHasher> {
584        &self.ngrams
585    }
586
587    /// Return the expected or discovered file type
588    #[inline]
589    #[must_use]
590    pub fn ftype(&self) -> FileType {
591        self.ftype
592    }
593}
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598
599    /// Write `files` into a fresh directory and return an [`Ngrammer`] over them.
600    fn ngrammer(name: &str, files: &[Vec<u8>], n: u16, k: usize) -> Ngrammer {
601        ngrammer_strided(name, files, n, k, 1)
602    }
603
604    /// Like [`ngrammer`], with a stride other than 1.
605    fn ngrammer_strided(name: &str, files: &[Vec<u8>], n: u16, k: usize, s: u16) -> Ngrammer {
606        let dir = std::env::temp_dir().join(name);
607        let _ = std::fs::remove_dir_all(&dir);
608        std::fs::create_dir_all(&dir).unwrap();
609        let paths = files
610            .iter()
611            .enumerate()
612            .map(|(i, contents)| {
613                let path = dir.join(format!("{i}.bin"));
614                std::fs::write(&path, contents).unwrap();
615                path
616            })
617            .collect();
618
619        Ngrammer {
620            n,
621            k,
622            paths,
623            s,
624            keep_below: u64::MAX / u64::from(s),
625            ftype: FileType::ELF,
626            ngrams: DashMap::default(),
627        }
628    }
629
630    /// Deterministic filler bytes, distinct per `seed`.
631    fn noise(seed: u64, len: usize) -> Vec<u8> {
632        let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
633        (0..len)
634            .map(|_| {
635                state ^= state << 13;
636                state ^= state >> 7;
637                state ^= state << 17;
638                state.to_le_bytes()[4]
639            })
640            .collect()
641    }
642
643    #[test]
644    fn keeps_exactly_k_and_prefers_common() {
645        let shared = b"\x7fSHARED-NGRAM-IN-EVERY-FILE!".to_vec();
646        let files: Vec<Vec<u8>> = (0..4)
647            .map(|i| {
648                let mut contents = noise(i + 1, 256);
649                contents.extend_from_slice(&shared);
650                contents
651            })
652            .collect();
653
654        let mut ngrammer = ngrammer("mm_ngram_top_k", &files, 8, 10);
655        ngrammer.find();
656
657        assert_eq!(ngrammer.ngrams().len(), 10);
658        // Every window of the shared tail is in all four files, so those outrank the noise.
659        for entry in ngrammer.ngrams() {
660            assert_eq!(*entry.value(), 4, "{}", hex::encode(entry.key()));
661            assert!(shared.windows(8).any(|w| w == entry.key().as_slice()));
662        }
663    }
664
665    #[test]
666    fn candidates_never_exceed_counts() {
667        // More distinct n-grams than there are buckets, and a `k` that asks for all of them.
668        let distinct = Ngrammer::COUNTS + Ngrammer::COUNTS / 2;
669        let files: Vec<Vec<u8>> = (0..4u64)
670            .map(|i| noise(i + 100, distinct / 4 + 3))
671            .collect();
672
673        let mut ngrammer = ngrammer("mm_ngram_bounded", &files, 4, usize::MAX);
674        ngrammer.find();
675
676        assert!(!ngrammer.ngrams().is_empty());
677        assert!(ngrammer.ngrams().len() <= Ngrammer::COUNTS);
678    }
679
680    #[test]
681    #[allow(clippy::cast_possible_truncation)]
682    fn colliding_ngrams_are_both_kept() {
683        // Two different n-grams that land in the same bucket.
684        let mut seen: FxHashMap<usize, [u8; 4]> = FxHashMap::default();
685        let (first, second) = (0u32..)
686            .find_map(|i| {
687                let ngram = i.to_be_bytes();
688                let bucket = Ngrammer::select_hash(hash_bytes(&ngram), 1, u64::MAX)?;
689                seen.insert(bucket, ngram).map(|earlier| (earlier, ngram))
690            })
691            .unwrap();
692
693        let files = vec![first.to_vec(), second.to_vec(), first.to_vec()];
694        let mut ngrammer = ngrammer("mm_ngram_collisions", &files, 4, 2);
695        ngrammer.find();
696
697        assert_eq!(ngrammer.ngrams().len(), 2);
698        assert!(ngrammer.ngrams().contains_key(first.as_slice()));
699        assert!(ngrammer.ngrams().contains_key(second.as_slice()));
700    }
701
702    #[test]
703    fn same_corpus_same_ngrams() {
704        let files: Vec<Vec<u8>> = (0..8).map(|i| noise(i + 7, 8192)).collect();
705
706        let mut first = ngrammer("mm_ngram_repeat_a", &files, 3, 50);
707        first.find();
708        let mut second = ngrammer("mm_ngram_repeat_b", &files, 3, 50);
709        second.find();
710
711        let mut a: Vec<Bytes> = first.ngrams().iter().map(|e| e.key().clone()).collect();
712        let mut b: Vec<Bytes> = second.ngrams().iter().map(|e| e.key().clone()).collect();
713        a.sort();
714        b.sort();
715        assert_eq!(a.len(), 50);
716        assert_eq!(a, b);
717    }
718
719    #[test]
720    fn stride_keeps_only_sampled_ngrams() {
721        // With a stride, buckets off the stride used to leave their bit set, spinning forever.
722        let stride = 7u16;
723        let files: Vec<Vec<u8>> = (0..4).map(|i| noise(i + 40, 4096)).collect();
724
725        let mut ngrammer = ngrammer_strided("mm_ngram_stride", &files, 4, 100, stride);
726        ngrammer.find();
727
728        assert!(!ngrammer.ngrams().is_empty());
729        for entry in ngrammer.ngrams() {
730            assert!(
731                ngrammer.select(entry.key()).is_some(),
732                "{} was not sampled",
733                hex::encode(entry.key())
734            );
735        }
736    }
737
738    #[test]
739    #[allow(clippy::cast_precision_loss)]
740    fn stride_samples_evenly_and_fills_every_bucket() {
741        let stride = 7u16;
742        let keep_below = u64::MAX / u64::from(stride);
743        let total = 100_000u64;
744
745        let buckets: Vec<usize> = (0..total)
746            .filter_map(|i| Ngrammer::select_hash(hash_bytes(&i.to_le_bytes()), stride, keep_below))
747            .collect();
748
749        // About one hash in `stride` is sampled.
750        let expected = total as f64 / f64::from(stride);
751        let kept = buckets.len() as f64;
752        assert!(
753            (kept - expected).abs() < expected * 0.1,
754            "kept {kept}, expected {expected}"
755        );
756
757        // The sampled ones spread over the whole array, not only the strided buckets.
758        assert!(buckets.iter().all(|b| *b < Ngrammer::COUNTS));
759        let max = buckets.iter().copied().max().unwrap();
760        assert!(max > Ngrammer::COUNTS / 100 * 99, "largest bucket {max}");
761        for residue in 0..usize::from(stride) {
762            assert!(
763                buckets.iter().any(|b| b % usize::from(stride) == residue),
764                "no bucket = {residue} mod {stride}"
765            );
766        }
767    }
768
769    #[test]
770    #[allow(clippy::cast_possible_truncation)]
771    fn every_bucket_is_reachable_at_any_stride() {
772        // The cap on sampled hashes must not shrink the array: for every bucket there is a
773        // sampled hash that lands in it, however large the stride.
774        for stride in [1u16, 2, 7, 16, 1000, u16::MAX] {
775            let keep_below = u64::MAX / u64::from(stride);
776            for bucket in 0..Ngrammer::COUNTS {
777                // Smallest stretched value multiply-shift maps to `bucket`, then the smallest
778                // sampled hash that stretches to at least that.
779                let first = ((bucket as u128) << u64::BITS).div_ceil(Ngrammer::COUNTS as u128);
780                let hash = first.div_ceil(u128::from(stride)) as u64;
781                assert_eq!(
782                    Ngrammer::select_hash(hash, stride, keep_below),
783                    Some(bucket),
784                    "stride {stride}, bucket {bucket}"
785                );
786            }
787            // And the largest sampled hash lands in the last bucket.
788            assert_eq!(
789                Ngrammer::select_hash(keep_below, stride, keep_below),
790                Some(Ngrammer::COUNTS - 1),
791                "stride {stride}"
792            );
793        }
794    }
795
796    #[test]
797    fn stride_from_ngram_line() {
798        let line = "# Stride: 4";
799        let stride = stride_from_line(line).unwrap();
800        assert_eq!(stride, 4);
801    }
802}