#![allow(dead_code, reason = "each area's test uses its own part of this")]
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::time::{Duration, Instant};
const COMMITTABLE: [&str; 8] = [
"MIT",
"BSD-2-Clause",
"BSD-3-Clause",
"Apache-2.0",
"CC0-1.0",
"CC-BY-3.0",
"CC-BY-4.0",
"LicenseRef-freely-redistributed",
];
const SOURCE_CAP: u64 = 512 * 1024;
const TOTAL_CAP: u64 = 5 * 1024 * 1024;
const SCALE_MIN_COPIES: usize = 4;
const SCALE_BYTES: usize = 1_000;
const SCALE_FACTOR: usize = 32;
const SCALE_BOUND: u32 = 256;
const SCALE_REPS: usize = 5;
const SCALE_SLOW_REPS: usize = 2;
const SCALE_SLOW_RUN: Duration = Duration::from_millis(250);
const SCALE_FLOOR: Duration = Duration::from_micros(1);
const SCALE_SEED_CAP: usize = 4 * 1024;
const SCALE_WORK_BOUND: usize = 40;
#[derive(Debug, Clone, Copy)]
pub struct Join<'a> {
pub open: &'a [u8],
pub sep: &'a [u8],
pub close: &'a [u8],
}
impl Join<'static> {
pub const NONE: Self = Self::between(b"");
pub const SPACE: Self = Self::between(b" ");
pub const LINES: Self = Self::between(b"\n");
pub const ARRAY: Self = Self {
open: b"[",
sep: b",",
close: b"]",
};
pub const fn between(sep: &'static [u8]) -> Self {
Self {
open: b"",
sep,
close: b"",
}
}
}
impl Join<'_> {
fn repeat(&self, seed: &[u8], copies: usize) -> Vec<u8> {
let mut out = self.open.to_vec();
for i in 0..copies {
if i > 0 {
out.extend_from_slice(self.sep);
}
out.extend_from_slice(seed);
}
out.extend_from_slice(self.close);
out
}
}
const HIT_SLACK: f64 = 0.05;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Committed,
Local,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unit {
Line,
File,
}
#[derive(Debug)]
pub struct Source {
pub id: String,
pub licence: String,
pub licence_file: Option<String>,
pub notice: Option<String>,
pub mode: Mode,
pub files: Vec<File>,
}
#[derive(Debug)]
pub struct File {
pub path: String,
pub tags: Vec<String>,
pub unit: Unit,
pub keep: String,
pub gzip: bool,
}
impl File {
pub fn stored(&self) -> String {
let base = self.path.strip_suffix(".gz").unwrap_or(&self.path);
let lines = if self.keep.starts_with("extract") {
".lines"
} else {
""
};
let gz = if self.gzip { ".gz" } else { "" };
format!("{base}{lines}{gz}")
}
}
#[derive(Debug, Clone, Copy)]
pub struct Record<'a> {
pub source: &'a str,
pub file: &'a str,
pub line: usize,
pub bytes: &'a [u8],
pub unit: Unit,
}
impl Record<'_> {
pub fn at(&self) -> String {
format!("{}/{}:{}", self.source, self.file, self.line)
}
}
pub fn root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus")
}
pub fn cache() -> Option<PathBuf> {
let dir = std::env::var_os("GRIPPO_CORPUS")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| Path::new(&h).join(".cache/grippo-corpus")))?;
dir.is_dir().then_some(dir)
}
fn text<'t>(table: &'t toml::Table, key: &str, at: &str) -> &'t str {
table
.get(key)
.and_then(toml::Value::as_str)
.unwrap_or_else(|| panic!("manifest: {at} has no string {key}"))
}
fn read_file(f: &toml::Value, id: &str) -> File {
let f = f.as_table().expect("manifest: a file is a table");
let path = text(f, "path", id).to_owned();
let unit = match text(f, "unit", &path) {
"line" => Unit::Line,
"file" => Unit::File,
other => panic!("manifest: {path} has unit {other}"),
};
let tags: Vec<String> = f
.get("tags")
.and_then(toml::Value::as_array)
.unwrap_or_else(|| panic!("manifest: {path} has no tags"))
.iter()
.map(|t| t.as_str().expect("a tag is a string").to_owned())
.collect();
assert_eq!(text(f, "sha256", &path).len(), 64, "{path}");
File {
keep: text(f, "keep", &path).to_owned(),
gzip: f.get("gzip").and_then(toml::Value::as_bool) == Some(true),
path,
tags,
unit,
}
}
fn read_source(s: &toml::Value) -> Source {
let s = s.as_table().expect("manifest: a source is a table");
let id = text(s, "id", "a source").to_owned();
let mode = match text(s, "mode", &id) {
"committed" => Mode::Committed,
"local" => Mode::Local,
other => panic!("manifest: {id} has mode {other}"),
};
let files: Vec<File> = s
.get("file")
.and_then(toml::Value::as_array)
.unwrap_or_else(|| panic!("manifest: {id} has no [[source.file]]"))
.iter()
.map(|f| read_file(f, &id))
.collect();
Source {
licence: text(s, "licence", &id).to_owned(),
licence_file: s
.get("licence_file")
.and_then(toml::Value::as_str)
.map(str::to_owned),
notice: match s.get("needs_notice").and_then(toml::Value::as_bool) {
Some(true) => Some(text(s, "notice", &id).to_owned()),
Some(false) => None,
None => panic!("manifest: {id} has no needs_notice"),
},
id,
mode,
files,
}
}
pub static MANIFEST: LazyLock<Vec<Source>> = LazyLock::new(|| {
let path = root().join("manifest.toml");
let body = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
let manifest: toml::Table = body.parse().unwrap_or_else(|e| panic!("{path:?}: {e}"));
manifest
.get("source")
.and_then(toml::Value::as_array)
.expect("manifest: no [[source]]")
.iter()
.map(read_source)
.collect()
});
fn load(source: &Source, file: &File) -> Option<Vec<u8>> {
let dir = match source.mode {
Mode::Committed => root(),
Mode::Local => cache()?,
};
let path = dir.join(&source.id).join(file.stored());
if source.mode == Mode::Local && !path.is_file() {
return None;
}
let raw = std::fs::read(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
if !file.gzip {
return Some(raw);
}
let mut out = Vec::new();
flate2::read::GzDecoder::new(raw.as_slice())
.read_to_end(&mut out)
.unwrap_or_else(|e| panic!("{path:?}: {e}"));
Some(out)
}
pub fn files(tag: &str) -> Vec<(&'static Source, &'static File, Vec<u8>)> {
let mut out = Vec::new();
let mut missing = 0;
for source in MANIFEST.iter() {
for file in source
.files
.iter()
.filter(|f| f.tags.iter().any(|t| t == tag))
{
match load(source, file) {
Some(bytes) => out.push((source, file, bytes)),
None => missing += 1,
}
}
}
if missing > 0 {
println!("corpus {tag}: {missing} local files skipped, run scripts/corpus_fetch.py");
}
out
}
pub fn file_bytes(id: &str, path: &str) -> Vec<u8> {
MANIFEST
.iter()
.filter(|s| s.id == id)
.flat_map(|s| s.files.iter().map(move |f| (s, f)))
.find(|(_, f)| f.path == path)
.and_then(|(s, f)| load(s, f))
.unwrap_or_else(|| panic!("no {id}/{path}"))
}
pub fn lines(bytes: &[u8]) -> impl Iterator<Item = (usize, &[u8])> {
bytes
.split(|&b| b == b'\n')
.enumerate()
.map(|(i, l)| (i + 1, l.strip_suffix(b"\r").unwrap_or(l)))
.filter(|(_, l)| !l.is_empty())
}
pub fn for_each_record(tag: &str, mut f: impl FnMut(&Record<'_>)) -> usize {
let mut n = 0;
for (source, file, bytes) in files(tag) {
let mut one = |line: usize, record: &[u8]| {
f(&Record {
source: &source.id,
file: &file.path,
line,
bytes: record,
unit: file.unit,
});
n += 1;
};
match file.unit {
Unit::File => one(0, &bytes),
Unit::Line => lines(&bytes).for_each(|(i, l)| one(i, l)),
}
}
n
}
pub fn for_each_record_of(tags: &[&str], mut f: impl FnMut(&Record<'_>)) -> usize {
let mut seen = BTreeSet::new();
let mut n = 0;
for tag in tags {
for_each_record(tag, |r| {
if seen.insert((r.source.to_owned(), r.file.to_owned(), r.line)) {
f(r);
n += 1;
}
});
}
n
}
#[derive(Debug, Default)]
pub struct Tally {
seen: BTreeMap<(String, String), (usize, usize)>,
problems: Vec<String>,
longest: Vec<u8>,
scale_bytes: usize,
known: Vec<(&'static str, &'static str, usize)>,
}
impl Tally {
pub fn count(&mut self, check: &str, record: &Record<'_>, hit: bool) {
let key = (
format!("{}/{}", record.source, record.file),
check.to_owned(),
);
let e = self.seen.entry(key).or_default();
e.0 += 1;
e.1 += usize::from(hit);
}
pub fn known_bug(&mut self, text: &'static str, bug: &'static str) {
self.known.push((text, bug, 0));
}
pub fn problem(&mut self, what: &str, record: &Record<'_>, detail: &str) {
if let Some(k) = self.known.iter_mut().find(|k| detail.contains(k.0)) {
k.2 += 1;
return;
}
self.problems.push(format!(
"{what} on {}: {detail}: {:?}",
record.at(),
String::from_utf8_lossy(&record.bytes[..record.bytes.len().min(300)])
));
}
pub fn caught<T>(
&mut self,
what: &str,
record: &Record<'_>,
f: impl FnOnce() -> T,
) -> Option<T> {
let len = record.bytes.len();
if len > self.longest.len() && len <= SCALE_SEED_CAP {
self.longest = record.bytes.to_vec();
}
let out = catch_unwind(AssertUnwindSafe(f));
self.unwound(what, record, out)
}
pub fn scale_from(&mut self, bytes: usize) {
self.scale_bytes = bytes;
}
pub fn longest(&self) -> &[u8] {
&self.longest
}
pub fn scales_longest(&mut self, what: &str, join: Join<'_>, run: impl FnMut(&[u8])) {
let seed = self.longest.clone();
self.scales(what, &seed, join, run);
}
pub fn scales(&mut self, what: &str, seed: &[u8], join: Join<'_>, mut run: impl FnMut(&[u8])) {
if seed.is_empty() || seed.len() > SCALE_SEED_CAP {
return;
}
let copies = SCALE_BYTES
.max(self.scale_bytes)
.div_ceil(seed.len())
.max(SCALE_MIN_COPIES);
let (short, long) = (
join.repeat(seed, copies),
join.repeat(seed, copies * SCALE_FACTOR),
);
let mut time = |input: &[u8]| {
let start = Instant::now();
let out = catch_unwind(AssertUnwindSafe(|| run(input)));
(start.elapsed(), out.is_ok())
};
let (_, ok_short) = time(&short);
let (warm_long, ok_long) = time(&long);
if !(ok_short && ok_long) {
self.flag(format!(
"{what}: panicked on {copies} copies of a real record"
));
return;
}
let reps = if warm_long > SCALE_SLOW_RUN {
SCALE_SLOW_REPS
} else {
SCALE_REPS
};
let (mut fast, mut slow) = (Duration::MAX, Duration::MAX);
for _ in 0..reps {
fast = fast.min(time(&short).0);
slow = slow.min(time(&long).0);
}
if slow >= fast.max(SCALE_FLOOR) * SCALE_BOUND {
self.flag(format!(
"{what}: {SCALE_FACTOR}x the input ({} bytes) took {slow:?} against {fast:?}",
long.len()
));
}
}
pub fn scales_work<O: PartialEq + std::fmt::Debug>(
&mut self,
what: &str,
seed: &[u8],
join: Join<'_>,
mut run: impl FnMut(&[u8]) -> (O, usize),
) {
if seed.is_empty() || seed.len() > SCALE_SEED_CAP {
return;
}
let copies = SCALE_BYTES
.max(self.scale_bytes)
.div_ceil(seed.len())
.max(SCALE_MIN_COPIES);
let (short, long) = (
join.repeat(seed, copies),
join.repeat(seed, copies * SCALE_FACTOR),
);
let (Ok((outcome, few)), Ok((long_outcome, many))) = (
catch_unwind(AssertUnwindSafe(|| run(&short))),
catch_unwind(AssertUnwindSafe(|| run(&long))),
) else {
self.flag(format!(
"{what}: panicked on {copies} copies of a real record"
));
return;
};
if outcome != long_outcome {
self.flag(format!(
"{what}: {SCALE_FACTOR}x the input changed the outcome from {outcome:?} to {long_outcome:?}"
));
} else if many >= few.max(1) * SCALE_WORK_BOUND {
self.flag(format!(
"{what}: {SCALE_FACTOR}x the input ({} bytes) spent {many} units against {few}",
long.len()
));
}
}
fn flag(&mut self, detail: String) {
if let Some(k) = self.known.iter_mut().find(|k| detail.contains(k.0)) {
k.2 += 1;
} else {
self.problems.push(detail);
}
}
fn unwound<T>(
&mut self,
what: &str,
record: &Record<'_>,
out: std::thread::Result<T>,
) -> Option<T> {
match out {
Ok(v) => Some(v),
Err(p) => {
let msg = p
.downcast_ref::<String>()
.cloned()
.or_else(|| p.downcast_ref::<&str>().map(|s| (*s).to_owned()))
.unwrap_or_default();
self.problem(what, record, &format!("panicked: {msg}"));
None
}
}
}
pub fn finish(self, what: &str) {
for (_, bug, n) in &self.known {
println!("{what}: {n} records hit the known bug: {bug}");
}
let committed: BTreeSet<String> = MANIFEST
.iter()
.filter(|s| s.mode == Mode::Committed)
.flat_map(|s| s.files.iter().map(move |f| format!("{}/{}", s.id, f.path)))
.collect();
let mut low = Vec::new();
let mut absent = Vec::new();
for ((file, check), (records, hits)) in &self.seen {
if !committed.contains(file) {
println!("{what} local {file} {check}: {hits} of {records}");
continue;
}
let key = format!("{file} {check}");
match FLOORS.get(&key) {
None => absent.push(format!("{key:?} = {hits}")),
Some(&floor) => {
#[allow(clippy::cast_precision_loss, reason = "counts far below 2^52")]
let (hits_f, least) = (*hits as f64, floor as f64 * (1.0 - HIT_SLACK));
if hits_f < least {
low.push(format!("{key}: {hits} of {records}, floor {floor}"));
}
}
}
}
let shown: Vec<&String> = self.problems.iter().take(20).collect();
if !absent.is_empty() {
println!(
"{what}: no floor in tests/corpus/hits.toml for:\n{}",
absent.join("\n")
);
}
assert!(
self.problems.is_empty(),
"{what}: {} problems: {shown:#?}",
self.problems.len()
);
assert!(low.is_empty(), "{what}: hit rate fell: {low:#?}");
assert!(
absent.is_empty(),
"{what}: no floor in tests/corpus/hits.toml for:\n{}",
absent.join("\n")
);
}
}
static FLOORS: LazyLock<BTreeMap<String, usize>> = LazyLock::new(|| {
let path = root().join("hits.toml");
let body = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{path:?}: {e}"));
let table: toml::Table = body.parse().unwrap_or_else(|e| panic!("{path:?}: {e}"));
table
.iter()
.map(|(k, v)| {
let n = v
.as_integer()
.unwrap_or_else(|| panic!("hits.toml: {k} is not a count"));
(
k.clone(),
usize::try_from(n).expect("a count is not negative"),
)
})
.collect()
});
fn trimmed(text: &str) -> String {
text.lines().map(str::trim).collect::<Vec<_>>().join("\n")
}
#[test]
fn committed_sources_carry_a_licence_we_may_ship() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let notice = trimmed(&std::fs::read_to_string(root.join("NOTICE")).expect("NOTICE"));
let mut ids = BTreeSet::new();
for s in MANIFEST.iter() {
assert!(ids.insert(s.id.as_str()), "{} twice", s.id);
if let Some(excerpt) = &s.notice {
assert_eq!(
s.licence, "Apache-2.0",
"{}: only Apache-2.0 needs NOTICE",
s.id
);
assert!(
notice.contains(trimmed(excerpt.trim()).as_str()),
"NOTICE lacks {}'s attribution notices: {excerpt}",
s.id
);
}
if s.mode != Mode::Committed {
continue;
}
assert!(
COMMITTABLE.contains(&s.licence.as_str()),
"{} is committed under {}, which only a local source may carry",
s.id,
s.licence
);
let file = s
.licence_file
.as_deref()
.unwrap_or_else(|| panic!("{} names no licence_file", s.id));
assert!(
(file.starts_with("LICENSES/") || file == "LICENSE") && root.join(file).is_file(),
"{}: no licence text at {file}",
s.id
);
}
}
#[test]
fn committed_data_stays_under_its_caps_and_matches_the_manifest() {
let mut total = 0;
let mut named = BTreeSet::new();
for s in MANIFEST.iter().filter(|s| s.mode == Mode::Committed) {
let mut size = 0;
for f in &s.files {
let path = root().join(&s.id).join(f.stored());
size += std::fs::metadata(&path)
.unwrap_or_else(|e| panic!("{path:?}: {e}"))
.len();
named.insert(path);
}
assert!(size <= SOURCE_CAP, "{} holds {size} bytes", s.id);
total += size;
}
assert!(total <= TOTAL_CAP, "the corpus holds {total} bytes");
let mut stray = Vec::new();
let mut walk = vec![root()];
while let Some(dir) = walk.pop() {
for entry in std::fs::read_dir(&dir).expect("corpus dir") {
let path = entry.expect("corpus entry").path();
if path.is_dir() {
walk.push(path);
} else if path.parent() != Some(root().as_path()) && !named.contains(&path) {
stray.push(path);
}
}
}
assert!(
stray.is_empty(),
"files the manifest doesn't name: {stray:#?}"
);
}
#[test]
fn every_record_loop_reads_a_committed_source() {
let mut tags: BTreeSet<&str> = BTreeSet::new();
for s in MANIFEST.iter().filter(|s| s.mode == Mode::Committed) {
for f in &s.files {
tags.extend(f.tags.iter().map(String::as_str));
}
}
for tag in tags {
assert!(for_each_record(tag, |_| {}) > 0, "{tag} has no records");
}
}