grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
// Project:   grippo
// File:      src/shared_tests/corpus.rs
// Purpose:   The real-world corpus: manifest, licence checks and one record loop
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! `tests/corpus/manifest.toml` names every source of real data the tests
//! read. Committed sources sit under `tests/corpus/<id>/`. Local ones sit in
//! the cache `scripts/corpus_fetch.py` fills, and are read only when present.

#![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};

/// Licences a committed source may carry. The last is a source whose page
/// names no licence but says it may be freely redistributed.
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",
];

/// Most bytes one committed source, and all of them, may hold, a gzipped
/// file counted at its packed size.
const SOURCE_CAP: u64 = 512 * 1024;
const TOTAL_CAP: u64 = 5 * 1024 * 1024;

/// The cost check: an input of at least `SCALE_MIN_COPIES` copies of a record
/// and `SCALE_BYTES` long, and one `SCALE_FACTOR` times longer, each timed
/// `SCALE_REPS` times, may differ in cost by at most `SCALE_BOUND`. Linear
/// work differs by `SCALE_FACTOR` (32), work that rereads the input from each
/// position by its square (1024). The short input holds several copies
/// because one copy of a record and two of it can take different paths in a
/// reader. Below `SCALE_FLOOR` a run is too quick for the clock to tell apart.
/// A seed over `SCALE_SEED_CAP` bytes isn't grown, because 32 times its copies
/// would run for minutes. A long run over `SCALE_SLOW_RUN` is timed
/// `SCALE_SLOW_REPS` times, since a stall is small beside it.
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;
/// The work check's limit: linear work differs by `SCALE_FACTOR`, a reread of
/// the input from each position by its square.
const SCALE_WORK_BOUND: usize = 40;

/// How copies of a seed join into one input: before the first, between each,
/// and after the last.
#[derive(Debug, Clone, Copy)]
pub struct Join<'a> {
    pub open: &'a [u8],
    pub sep: &'a [u8],
    pub close: &'a [u8],
}

impl Join<'static> {
    /// Copies end to end.
    pub const NONE: Self = Self::between(b"");
    /// Copies on one line.
    pub const SPACE: Self = Self::between(b" ");
    /// Copies on their own lines.
    pub const LINES: Self = Self::between(b"\n");
    /// Copies as the elements of a JSON array.
    pub const ARRAY: Self = Self {
        open: b"[",
        sep: b",",
        close: b"]",
    };

    /// Copies with `sep` between them.
    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
    }
}

/// A hit count may fall this far below its floor before a test fails.
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,
    /// The licence text under `LICENSES/`, for a committed source.
    pub licence_file: Option<String>,
    /// The attribution notices NOTICE must carry, for an Apache-2.0 source
    /// whose own NOTICE file has some for what we take.
    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 {
    /// Where the file sits under its source's directory: the upstream path
    /// with a `.gz` dropped, `.lines` added for an extract, and `.gz` for a
    /// file kept gzipped.
    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}")
    }
}

/// One record of one file.
#[derive(Debug, Clone, Copy)]
pub struct Record<'a> {
    pub source: &'a str,
    pub file: &'a str,
    /// Line number from 1, or 0 for a whole file.
    pub line: usize,
    pub bytes: &'a [u8],
    pub unit: Unit,
}

impl Record<'_> {
    /// `source/file:line`, for a failure message.
    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")
}

/// The local tier's cache: `GRIPPO_CORPUS`, else `~/.cache/grippo-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()
});

/// The file's bytes, or `None` for a local source the cache doesn't hold.
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)
}

/// Every file tagged `tag` that is here: committed ones always, local ones
/// when the cache holds them. Prints one line naming what the cache lacks.
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
}

/// The bytes of the file `path` of source `id`.
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}"))
}

/// Each line of `bytes` with its number from 1, the line end and a CR before
/// it dropped. An empty line is skipped.
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())
}

/// Run `f` on every record tagged `tag`: each line of a line file, or the
/// whole of a file one. Returns how many records ran.
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
}

/// [`for_each_record`] over several tags, each record once.
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
}

/// What one test saw: per file and check, the records and the hits, and
/// every panic, mismatch and cost overrun.
#[derive(Debug, Default)]
pub struct Tally {
    seen: BTreeMap<(String, String), (usize, usize)>,
    problems: Vec<String>,
    /// The longest record of at most `SCALE_SEED_CAP` bytes a call has run,
    /// the seed of the cost check.
    longest: Vec<u8>,
    /// Where the cost check's short input starts, or 0 for `SCALE_BYTES`.
    scale_bytes: usize,
    /// Known bugs: a problem holding the text is counted under its note,
    /// not failed. Each has an `#[ignore]` test that fails until it's fixed.
    known: Vec<(&'static str, &'static str, usize)>,
}

impl Tally {
    /// Count `record` under `check`, a hit when `hit`.
    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);
    }

    /// Count a problem holding `text` under `bug` in place of failing on it.
    pub fn known_bug(&mut self, text: &'static str, bug: &'static str) {
        self.known.push((text, bug, 0));
    }

    /// Record a broken invariant.
    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)])
        ));
    }

    /// Run `f` on `record`, recording a panic. `None` when it panicked. Time
    /// isn't held here, because an elapsed budget on one call fails when the
    /// host stalls the process. [`Self::scales`] holds cost instead.
    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)
    }

    /// Start the cost check's short input at `bytes` instead of `SCALE_BYTES`,
    /// for a reader whose cost per byte is higher below that length.
    pub fn scale_from(&mut self, bytes: usize) {
        self.scale_bytes = bytes;
    }

    /// The longest record [`Self::caught`] has run, of at most `SCALE_SEED_CAP` bytes.
    pub fn longest(&self) -> &[u8] {
        &self.longest
    }

    /// [`Self::scales`] on [`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);
    }

    /// Records a problem when `run` costs more than [`SCALE_BOUND`] times as
    /// much on an input [`SCALE_FACTOR`] times longer, built from copies of
    /// `seed`. A run that reread the input from each position would cost
    /// [`SCALE_FACTOR`] squared. Short and long runs alternate and each keeps
    /// its fastest of [`SCALE_REPS`], so a stall on a shared host slows
    /// neither. An input `run` stops reading early costs the same at either
    /// length and passes.
    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()
            ));
        }
    }

    /// [`Self::scales`] counted in work units instead of time. `run` returns
    /// what it concluded and the units it spent, and the long input must reach
    /// the same conclusion on less than [`SCALE_WORK_BOUND`] times the units.
    /// A unit count is exact, so a stalled host can't fail it.
    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()
            ));
        }
    }

    /// Record a problem with no single record, counted under a known bug
    /// whose text it holds.
    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
            }
        }
    }

    /// Fails on any problem, or on a committed file whose hits fell below its
    /// floor in `tests/corpus/hits.toml`. A missing floor fails too, printing
    /// the rows to add.
    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()
});

/// Each line trimmed, so an excerpt matches NOTICE however it is indented.
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));
        // Data we generate ourselves ships under the repo's own LICENSE.
        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");
    }
}