legit-hamming 0.1.3

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
//! The `legit-hamming` program: `info`, `verify` of a sound and a damaged snapshot, `query`'s
//! exit statuses and its answer to a line too long, `stats`, command-line mistakes, and a README
//! and help that name nothing a reader of the published crate lacks.

use std::fs;
use std::io::Write;
use std::process::{Command, Output, Stdio};

use legit_hamming::Value;
use serde_json::{Value as Json, json};

use crate::service::{SetDir, records};
use crate::support::Rng;

fn run(arguments: &[&str], input: &str) -> Output {
    let mut child = Command::new(env!("CARGO_BIN_EXE_legit-hamming"))
        .args(arguments)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("the program runs");
    // A program that exits before reading all its input, as `query` does when an index can't be
    // searched, closes the pipe: that isn't a failure of the test...
    let written = child.stdin.take().expect("standard input").write_all(input.as_bytes());
    if let Err(error) = written {
        assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe, "the input is written");
    }
    child.wait_with_output().expect("the program ends")
}

fn lines(output: &Output) -> Vec<Json> {
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|line| serde_json::from_str(line).expect("each line is JSON"))
        .collect()
}

#[test]
fn info_reports_the_paths_formats_and_limits() {
    let output = run(&["info"], "");
    assert_eq!(output.status.code(), Some(0));
    let info: Json = serde_json::from_slice(&output.stdout).expect("JSON");
    assert_eq!(
        (&info["program"], &info["format"]),
        (&json!("legit-hamming"), &json!(1))
    );
    assert_eq!(
        info["snapshot"],
        json!({"format": "legit-hamming-snapshot", "version": 1})
    );
    assert!(info["cpu"]["path_64"].is_string() && info["cpu"]["path_256"].is_string());
    assert!(info["cpu"]["threads"].as_u64().is_some_and(|threads| threads >= 1));
    assert_eq!(info["limits"]["max_radius_64"], 16);
}

#[test]
fn verify_says_whether_a_snapshot_is_sound() {
    let mut rng = Rng::new(30);
    let set = SetDir::new();
    set.write("sound", &records::<[u64; 4]>(&mut rng, 2_000));
    let dir = set.path().join("sound");
    let output = run(&["verify", dir.to_str().expect("UTF-8")], "");
    assert_eq!(output.status.code(), Some(0));
    let report: Json = serde_json::from_slice(&output.stdout).expect("JSON");
    assert_eq!(report["sound"], true);
    assert_eq!(
        (&report["holds"]["records"], &report["holds"]["width"]),
        (&json!(2_000), &json!(256))
    );
    assert_eq!(report["holds"]["parts"], 3);

    let part = dir.join("part-00001.bin");
    let mut bytes = fs::read(&part).expect("a part");
    bytes[20] ^= 1;
    fs::write(&part, bytes).expect("damaged");
    let output = run(&["verify", dir.to_str().expect("UTF-8")], "");
    assert_eq!(output.status.code(), Some(1));
    let report: Json = serde_json::from_slice(&output.stdout).expect("JSON");
    assert_eq!(report["sound"], false);
    assert!(report["error"].as_str().is_some_and(|error| error.contains("SHA-256")));

    assert_eq!(run(&["verify"], "").status.code(), Some(2));
}

#[test]
fn query_answers_every_line_and_exits_by_what_it_answered() {
    let mut rng = Rng::new(31);
    let set = SetDir::new();
    let records = records::<u64>(&mut rng, 1_000);
    set.publish("s", &records);
    let flag = format!("m={}", set.path().display());
    let good =
        json!({"format": 1, "index": "m", "width": 64, "radius": 4, "values": [records.value(0).to_hex()]}).to_string();
    let output = run(&["query", "--index", &flag], &format!("{good}\n\n{good}\r\n"));
    assert_eq!(output.status.code(), Some(0));
    let answers = lines(&output);
    assert_eq!(answers.len(), 2, "a blank line is skipped");
    assert_eq!(answers[0]["snapshot"], "s");

    let long = format!("{{\"pad\": \"{}\"}}", "x".repeat(300));
    let output = run(
        &["query", "--index", &flag, "--max-options-bytes", "200"],
        &format!("{good}\n{long}\nnot json\n{good}\n"),
    );
    assert_eq!(output.status.code(), Some(1));
    let answers = lines(&output);
    let codes: Vec<&str> = answers
        .iter()
        .map(|answer| answer["error_type"].as_str().unwrap_or("success"))
        .collect();
    assert_eq!(codes, ["success", "invalid_options", "invalid_options", "success"]);

    // A set with no snapshot doesn't stop the others: each of its searches is `not_ready`...
    let empty = SetDir::new();
    let later = json!({"format": 1, "index": "later", "width": 64, "radius": 4, "values": [records.value(0).to_hex()]});
    let output = run(
        &[
            "query",
            "--index",
            &flag,
            "--index",
            &format!("later={}", empty.path().display()),
        ],
        &format!("{later}\n{good}\n"),
    );
    assert_eq!(output.status.code(), Some(1));
    assert!(String::from_utf8_lossy(&output.stderr).contains("no snapshot loaded"));
    let answers = lines(&output);
    assert_eq!(
        (&answers[0]["error_type"], &answers[0]["state"]),
        (&json!("not_ready"), &json!("empty"))
    );
    assert_eq!(answers[1]["snapshot"], "s");
}

#[test]
fn stats_prints_each_set_with_its_neighbour_table() {
    let mut rng = Rng::new(32);
    let (index, subset) = (SetDir::new(), SetDir::new());
    index.publish("i", &records::<u64>(&mut rng, 3_000));
    subset.publish("b", &legit_hamming::Records::from_values([1u64, 3, 7]).expect("values"));
    let output = run(
        &[
            "stats",
            "--index",
            &format!("m={}", index.path().display()),
            "--subset",
            &format!("m.flagged={}", subset.path().display()),
            "--sample",
            "100",
            "--max-distance",
            "4",
            "--seed",
            "9",
        ],
        "",
    );
    assert_eq!(output.status.code(), Some(0));
    let stats = lines(&output);
    assert_eq!(stats.len(), 2);
    assert_eq!(
        (&stats[0]["index"], &stats[1]["subset"]),
        (&json!("m"), &json!("flagged"))
    );
    let neighbours = &stats[0]["neighbours"];
    assert_eq!((&neighbours["sample"], &neighbours["seed"]), (&json!(100), &json!(9)));
    assert_eq!(neighbours["counts"].as_array().map(Vec::len), Some(5));
    // Every sampled record has the repeated value's other copies at distance 0...
    assert!(neighbours["counts"][0].as_u64().is_some_and(|count| count > 0));
    assert_eq!(stats[1]["neighbours"]["sample"], 3);
}

#[test]
fn a_command_line_mistake_exits_2() {
    for arguments in [
        &["nothing"][..],
        &["query", "--bogus"],
        &["query", "--index", "Bad=/tmp"],
        &["query", "--table-memory", "lots"],
        &["query", "--query-time", "0"],
        &["query", "--max-result-bytes", "10", "--index", "m=/tmp"],
        &["stats"],
    ] {
        let output = run(arguments, "");
        assert_eq!(output.status.code(), Some(2), "{arguments:?}");
        assert!(String::from_utf8_lossy(&output.stderr).contains("legit-hamming"));
    }
    assert_eq!(run(&["--version"], "").status.code(), Some(0));
    assert_eq!(run(&["help"], "").status.code(), Some(0));
}

#[test]
fn the_readme_and_the_help_name_nothing_outside_the_published_crate() {
    let help = String::from_utf8(run(&["help"], "").stdout).expect("the help is UTF-8");
    assert!(help.contains("--state-dir"), "the help is printed");
    for (name, text) in [("README.md", include_str!("../README.md")), ("help", &help)] {
        // Directories of the repository the crate is developed in, which its package doesn't
        // hold: a name at the start of a path, not inside a longer one such as `my-tools/`...
        for directory in ["tools/", "docs/", "export/", "research/"] {
            let named = text.match_indices(directory).any(|(at, _)| {
                text[..at]
                    .chars()
                    .next_back()
                    .is_none_or(|before| !(before.is_ascii_alphanumeric() || "_-.".contains(before)))
            });
            assert!(!named, "the {name} names `{directory}`");
        }
        // ...and a document a reader doesn't have, however the line breaks it.
        let words = text.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase();
        let draft = ["contract", " draft"].concat();
        assert!(!words.contains(&draft), "the {name} cites a {draft}");
    }
}

#[test]
fn the_source_and_the_tests_use_neutral_example_names_and_no_unpublished_tool() {
    // Built from pieces, so this file doesn't name what it looks for.
    let needles = [
        ["ban", "ned"].concat(),
        ["known", "-bad"].concat(),
        ["hamming", "-bench"].concat(),
        ["hamming-serve", "-sm", "oke"].concat(),
        ["contract", " draft"].concat(),
    ];
    let word = ["med", "ia"].concat();
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let mut directories = vec![root.join("src"), root.join("tests")];
    let mut files = 0;
    while let Some(directory) = directories.pop() {
        for entry in std::fs::read_dir(&directory).expect("a readable directory") {
            let path = entry.expect("a directory entry").path();
            if path.is_dir() {
                directories.push(path);
                continue;
            }
            files += 1;
            let text = std::fs::read_to_string(&path).expect("a UTF-8 file").to_lowercase();
            for needle in &needles {
                assert!(
                    !text.contains(needle.as_str()),
                    "{} contains `{needle}`",
                    path.display()
                );
            }
            // The whole word only: `median` passes.
            let whole = text.match_indices(word.as_str()).any(|(at, _)| {
                let boundary = |c: Option<char>| c.is_none_or(|c| !(c.is_alphanumeric() || c == '_'));
                boundary(text[..at].chars().next_back()) && boundary(text[at + word.len()..].chars().next())
            });
            assert!(!whole, "{} contains the word `{word}`", path.display());
        }
    }
    assert!(files > 10, "the walk found the crate's files");
}

#[test]
fn help_after_any_command_prints_the_help_and_exits_0() {
    let help = run(&["help"], "").stdout;
    for arguments in [
        &["query", "--help"][..],
        &["query", "--lane", "fast", "-h"],
        &["stats", "--help"],
        &["stats", "--sample", "3", "-h"],
        &["verify", "--help"],
        &["verify", "-h"],
        &["info", "--help"],
        &["info", "-h"],
        &["serve", "--help"],
        &["serve", "--no-fast", "-h"],
    ] {
        let output = run(arguments, "");
        assert_eq!(output.status.code(), Some(0), "{arguments:?}");
        assert_eq!(output.stdout, help, "{arguments:?}");
        assert!(output.stderr.is_empty(), "{arguments:?}");
    }
}