summaryrefslogtreecommitdiffstats
path: root/tests/architecture.rs
blob: 882adeefa113ed624d823a10be0420c0ffce0304 (plain)
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
//! The layer map, in one place, checked on every test run.
//!
//! `tests/layers.rs` grew four greps for four mistakes. Four greps cannot say
//! what the architecture *is*, cannot tell you where a new module belongs, and
//! say nothing at all about the modules nobody has tripped over yet. This
//! declares the whole map instead: every module in `src/` gets a rank, and a
//! module may name only modules ranked strictly below it. One rule, every
//! module, and the direction of dependence is written down rather than
//! remembered.
//!
//! The same file holds the interface budgets. An interface is only as narrow as
//! the items a module hands out, so each module is budgeted on how many `pub`
//! items it declares and how many of them nothing outside the module ever
//! names. Budgets live in `architecture-budget.json` and may only shrink: a
//! number that grows fails the suite, and a number that has quietly got smaller
//! has to be written back at the lower value, which is what stops a widening
//! being mistaken for progress.
//!
//! `tools/arch-census.py` computes the same numbers for a human to read.
//! `the_census_tool_and_this_test_agree` is the seam between them.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

/// A module may name only modules ranked strictly below it. The order is the
/// dependency graph itself, so each rank is written with the reason it sits
/// there — a bare number invites someone to slot a module in wherever it is
/// convenient.
const RANKS: &[(&str, u8, &str)] = &[
    ("error", 0, "the crate's error type: nothing in the crate is beneath it"),
    ("hash", 1, "sha256 and canonical json: pure"),
    ("time", 1, "the clock seam: pure"),
    ("urlutil", 1, "url and name shapes: pure"),
    ("pkgver", 1, "vercmp and the dependency grammar: pure, and the oracle test proves it"),
    ("pkginfo", 1, ".PKGINFO and .BUILDINFO parsing: pure"),
    ("config", 2, "config.json: needs an error type and a hash, nothing else"),
    ("fetch", 2, "the HTTP seam: an adapter over the outside world"),
    ("git", 2, "the git seam: an adapter over the git binary"),
    ("db", 3, "persistence: owns the schema, so it may use config, hash, pkgver and time"),
    ("sandbox", 3, "where build code runs: config and the clock, no knowledge of what gets built"),
    ("recipe", 4, "PKGBUILD parsing: needs the row types it fills in"),
    ("review", 5, "candidates, diff, risk, approval: reads persisted state and recipes"),
    ("shims", 5, "the fake toolchain: emulates tools over pkgver, pkginfo and recipe — test-only"),
    ("watch", 6, "detection: turns a moved upstream into a candidate, so it needs review"),
    ("pipeline", 7, "the step machine: orchestrates watch, review and sandbox"),
    ("ops", 8, "retention, metrics, backup: reads across the modules it reports on"),
    ("usecase", 9, "the workflows both front ends run: orchestrates review, watch, pipeline and ops"),
    ("http", 10, "the UI: renders use-case results, so only the composition roots are above it"),
    ("main", 11, "the CLI: composition root"),
    ("lib", 11, "the crate root: declares the modules and re-exports the error type"),
    ("bin/sandbox-agent", 11, "the sandbox agent: composition root on the far side of the wire"),
    ("bin/gpg", 11, "a shim binary: composition root for one tool"),
    ("bin/makepkg", 11, "a shim binary: composition root for one tool"),
    ("bin/makechrootpkg", 11, "a shim binary: composition root for one tool"),
    ("bin/mkarchroot", 11, "a shim binary: composition root for one tool"),
    ("bin/pacman", 11, "a shim binary: composition root for one tool"),
    ("bin/repo-add", 11, "a shim binary: composition root for one tool"),
];

/// `pub use … ::*` a module is still allowed to keep, as `module -> count`.
/// This is the allowlist, and the ratchet is what empties it: a glob re-export
/// flattens a namespace so a reader cannot see a module's width from its
/// exports, which is the whole point of the budgets. `db` used to need two; it
/// now names every export, so the slot is closed rather than left at zero.
const GLOB_ALLOWLIST: &[(&str, usize)] = &[("http", 2)];

const DECL_KEYWORDS: [&str; 7] = ["fn", "struct", "enum", "trait", "const", "static", "type"];

fn root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf()
}

fn src_root() -> PathBuf {
    root().join("src")
}

fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
    for entry in std::fs::read_dir(dir).expect("read_dir") {
        let path = entry.expect("entry").path();
        if path.is_dir() {
            rust_files(&path, out);
        } else if path.extension().is_some_and(|e| e == "rs") {
            out.push(path);
        }
    }
}

fn src_files() -> Vec<PathBuf> {
    let mut out = Vec::new();
    rust_files(&src_root(), &mut out);
    out.sort();
    assert!(out.len() > 40, "found only {} source files — the walk is wrong", out.len());
    out
}

fn test_files() -> Vec<PathBuf> {
    let mut out = Vec::new();
    rust_files(&root().join("tests"), &mut out);
    out.sort();
    out
}

/// The module a file belongs to: a directory is one module, a top-level file is
/// a module of its own, and a binary keeps its own name. A map that lumped
/// eleven unrelated top-level files into one box could not say anything about
/// any of them.
fn module_of(path: &Path) -> String {
    let rel = path.strip_prefix(src_root()).unwrap();
    let parts: Vec<String> = rel
        .components()
        .map(|c| c.as_os_str().to_string_lossy().into_owned())
        .collect();
    match parts.as_slice() {
        [only] => only.trim_end_matches(".rs").to_string(),
        [head, rest @ ..] if head == "bin" => {
            format!("bin/{}", rest.last().unwrap().trim_end_matches(".rs"))
        }
        [head, ..] => head.clone(),
        [] => unreachable!("a walked file always has a name"),
    }
}

fn is_comment(line: &str) -> bool {
    line.trim_start().starts_with("//")
}

fn word_tail(rest: &str) -> String {
    rest.chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect()
}

/// The name a `pub` declaration introduces, if this line declares one. `pub
/// use` is a re-export and is counted separately, never as a declaration.
fn pub_decl(line: &str) -> Option<String> {
    if is_comment(line) {
        return None;
    }
    let rest = line.trim_start().strip_prefix("pub ")?;
    let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} ")))?;
    let name = word_tail(&rest[keyword.len() + 1..]);
    (!name.is_empty()).then_some(name)
}

fn is_pub_crate_decl(line: &str) -> bool {
    if is_comment(line) {
        return false;
    }
    let Some(rest) = line.trim_start().strip_prefix("pub(crate) ") else {
        return false;
    };
    DECL_KEYWORDS.into_iter().any(|kw| rest.starts_with(&format!("{kw} ")))
}

fn is_glob_reexport(line: &str) -> bool {
    if is_comment(line) {
        return false;
    }
    let t = line.trim_start();
    let after = match t
        .strip_prefix("pub(crate) use ")
        .or_else(|| t.strip_prefix("pub use "))
    {
        Some(after) => after,
        None => return false,
    };
    after.contains("::*")
}

fn path_edges(line: &str, prefix: &str) -> Vec<String> {
    if is_comment(line) {
        return Vec::new();
    }
    let mut out = Vec::new();
    let bytes = line.as_bytes();
    let mut from = 0;
    while let Some(pos) = line[from..].find(prefix).map(|p| p + from) {
        from = pos + prefix.len();
        // A leading word character means this is `foo::crate::`, not a path root.
        if pos > 0 {
            let prev = bytes[pos - 1];
            if prev.is_ascii_alphanumeric() || prev == b'_' {
                continue;
            }
        }
        let name = word_tail(&line[from..]);
        if !name.is_empty() {
            out.push(name);
        }
    }
    out
}

/// Whole-word mention, the same test the census tool applies.
fn mentions(hay: &str, needle: &str) -> bool {
    let word = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
    let h = hay.as_bytes();
    if needle.is_empty() {
        return false;
    }
    let mut from = 0;
    while let Some(pos) = hay[from..].find(needle).map(|p| p + from) {
        let before_ok = pos == 0 || !word(h[pos - 1]);
        let after = pos + needle.len();
        let after_ok = after >= h.len() || !word(h[after]);
        if before_ok && after_ok {
            return true;
        }
        from = pos + 1;
    }
    false
}

#[derive(Default, Debug)]
struct Module {
    pub_items: usize,
    dead: usize,
    test_only: usize,
    dead_only: usize,
    pub_crate: usize,
    globs: usize,
    lines: usize,
}

#[derive(Debug)]
struct Census {
    modules: BTreeMap<String, Module>,
    edges: BTreeMap<String, BTreeSet<String>>,
}

impl Census {
    fn take() -> Census {
        let files = src_files();
        let texts: Vec<(PathBuf, String)> = files
            .iter()
            .map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source")))
            .collect();
        let test_texts: Vec<String> = test_files()
            .iter()
            .map(|f| std::fs::read_to_string(f).expect("read test"))
            .collect();

        let mut modules: BTreeMap<String, Module> = BTreeMap::new();
        for (path, text) in &texts {
            let module = modules.entry(module_of(path)).or_default();
            module.lines += text.lines().count();
            for line in text.lines() {
                if is_pub_crate_decl(line) {
                    module.pub_crate += 1;
                }
                if is_glob_reexport(line) {
                    module.globs += 1;
                }
            }
        }

        // name -> the modules that declare it. A name declared in two modules
        // is only dead when neither is read from outside either of them.
        let mut declared: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        for (path, text) in &texts {
            let module = module_of(path);
            for line in text.lines() {
                if let Some(name) = pub_decl(line) {
                    declared.entry(name).or_default().insert(module.clone());
                }
            }
        }

        for (name, declaring) in &declared {
            for module in declaring {
                modules.get_mut(module).unwrap().pub_items += 1;
            }
            let read_outside = texts
                .iter()
                .any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name));
            if read_outside {
                continue;
            }
            let used_by_tests = test_texts.iter().any(|t| mentions(t, name));
            for module in declaring {
                let module = modules.get_mut(module).unwrap();
                module.dead += 1;
                if used_by_tests {
                    module.test_only += 1;
                } else {
                    module.dead_only += 1;
                }
            }
        }

        let mut edges: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        for (path, text) in &texts {
            let source = module_of(path);
            let known: BTreeSet<String> = modules.keys().cloned().collect();
            for line in text.lines() {
                let named = if source.starts_with("bin/") || source == "main" {
                    path_edges(line, "aur_build::")
                } else {
                    path_edges(line, "crate::")
                };
                for target in named {
                    if target != source && known.contains(&target) {
                        edges.entry(source.clone()).or_default().insert(target);
                    }
                }
            }
        }

        Census { modules, edges }
    }

    /// The budget file, as `module -> key -> allowed`.
    fn budget() -> BTreeMap<String, BTreeMap<String, usize>> {
        let path = root().join("tests/architecture-budget.json");
        let text = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            panic!(
                "read {}: {}",
                path.display(),
                e
            )
        });
        let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
        let mut out = BTreeMap::new();
        let modules = value
            .get("modules")
            .and_then(|m| m.as_object())
            .expect("budget file has a modules object");
        for (module, row) in modules {
            let mut keys = BTreeMap::new();
            if let Some(row) = row.as_object() {
                for (key, val) in row {
                    if let Some(n) = val.as_u64() {
                        keys.insert(key.clone(), n as usize);
                    }
                }
            }
            out.insert(module.clone(), keys);
        }
        out
    }
}

/// A top-level section of the budget file, as `key -> allowed`.
fn budget_section(section: &str) -> BTreeMap<String, usize> {
    let path = root().join("tests/architecture-budget.json");
    let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e));
    let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
    let mut out = BTreeMap::new();
    let obj = value
        .get(section)
        .unwrap_or_else(|| panic!("budget file has no `{section}` section"))
        .as_object()
        .unwrap_or_else(|| panic!("budget `{section}` section is an object"));
    for (key, val) in obj {
        if let Some(n) = val.as_u64() {
            out.insert(key.clone(), n as usize);
        }
    }
    out
}

fn rank_of(module: &str) -> Option<u8> {
    RANKS
        .iter()
        .find(|(name, _, _)| *name == module)
        .map(|(_, rank, _)| *rank)
}

#[test]
fn every_module_is_on_the_map() {
    let census = Census::take();
    let unmapped: Vec<&String> = census
        .modules
        .keys()
        .filter(|m| rank_of(m).is_none())
        .collect();
    assert!(
        unmapped.is_empty(),
        "these modules have no rank, so nothing says what they may depend on: {unmapped:#?}\n\
         add each to RANKS with the reason a module below it cannot serve as its home"
    );
}

#[test]
fn the_map_names_no_module_twice() {
    let mut seen = BTreeSet::new();
    let dupes: Vec<&str> = RANKS
        .iter()
        .filter(|(name, _, _)| !seen.insert(*name))
        .map(|(name, _, _)| *name)
        .collect();
    assert!(dupes.is_empty(), "RANKS lists {dupes:?} twice; the second entry is dead weight");
    for (_, _, reason) in RANKS {
        assert!(reason.len() > 12, "a rank needs a reason, not a shrug: {reason:?}");
    }
}

#[test]
fn dependence_only_points_downward() {
    let mut violations = Vec::new();
    for path in src_files() {
        let text = std::fs::read_to_string(&path).expect("read source");
        let source = module_of(&path);
        let Some(from) = rank_of(&source) else { continue };
        for line in text.lines() {
            let named = if source.starts_with("bin/") || source == "main" {
                path_edges(line, "aur_build::")
            } else {
                path_edges(line, "crate::")
            };
            for target in named {
                if target == source {
                    // `crate::review::risk` from inside review is a path, not a
                    // dependence on another module.
                    continue;
                }
                let Some(to) = rank_of(&target) else { continue };
                if to >= from {
                    violations.push(format!(
                        "{}: {source} (rank {from}) names {target} (rank {to})",
                        path.strip_prefix(root()).unwrap().display()
                    ));
                }
            }
        }
    }
    violations.sort();
    violations.dedup();
    assert!(
        violations.is_empty(),
        "a module may only name modules ranked strictly below it:\n{}",
        violations.join("\n")
    );
}

#[test]
fn the_map_admits_no_cycle() {
    // Strictly downward edges make a cycle impossible by construction, which is
    // the whole trick — so this asserts the property the map is trusted for,
    // over the edges that actually exist, rather than trusting the ranks.
    let census = Census::take();
    let mut offenders = Vec::new();
    for (source, targets) in &census.edges {
        for target in targets {
            let (Some(from), Some(to)) = (rank_of(source), rank_of(target)) else {
                continue;
            };
            if to >= from {
                offenders.push(format!("{source} -> {target}"));
            }
        }
    }
    assert!(
        offenders.is_empty(),
        "these edges close a cycle, so neither module can be understood alone:\n{}",
        offenders.join("\n")
    );
}

#[test]
fn glob_reexports_stay_on_the_allowlist() {
    let census = Census::take();
    let mut offenders = Vec::new();
    for (module, row) in &census.modules {
        let allowed = GLOB_ALLOWLIST
            .iter()
            .find(|(m, _)| m == module)
            .map(|(_, n)| *n)
            .unwrap_or(0);
        if row.globs > allowed {
            offenders.push(format!("{module}: {} glob re-exports, {allowed} allowed", row.globs));
        }
    }
    assert!(
        offenders.is_empty(),
        "a glob re-export hides how wide a module is; name the items you export:\n{}",
        offenders.join("\n")
    );
}

/// The four comparisons the ratchet makes, as `(key, actual)` pairs.
fn budgeted(row: &Module) -> [(&'static str, usize); 4] {
    [
        ("pub", row.pub_items),
        ("dead", row.dead),
        ("deadonly", row.dead_only),
        ("glob", row.globs),
    ]
}

#[test]
fn interfaces_stay_within_budget() {
    // A `pub` item with no reader outside its module is not an interface, it is
    // a hole: a thing a caller may depend on and a thing a later refactor cannot
    // change without a grep across the crate. Zero holes is the destination, not
    // the starting point, so the rule is the ratchet — `deadonly` is how many
    // holes a module still has, and the only direction it may move is down.
    let census = Census::take();
    let budget = Census::budget();
    let mut over = Vec::new();
    for (module, row) in &census.modules {
        let Some(allowed) = budget.get(module) else {
            over.push(format!("{module}: absent from the budget file"));
            continue;
        };
        for (key, actual) in budgeted(row) {
            if let Some(max) = allowed.get(key) {
                if actual > *max {
                    over.push(format!("{module}.{key}: {actual} > {max}"));
                }
            }
        }
    }
    over.sort();
    assert!(
        over.is_empty(),
        "these numbers grew. An interface may shrink freely; widening one is a\n\
         decision to make in the open — lower the number in the budget file and\n\
         say why in the commit message:\n{}",
        over.join("\n")
    );
}

#[test]
fn a_shrunk_interface_is_written_back() {
    // The ratchet cuts both ways. A stale, generous budget is how a later
    // widening slips through unnoticed, so the file has to say what is true.
    let census = Census::take();
    let budget = Census::budget();
    let mut stale = Vec::new();
    for (module, row) in &census.modules {
        let Some(allowed) = budget.get(module) else { continue };
        for (key, actual) in budgeted(row) {
            if let Some(max) = allowed.get(key) {
                if *max > actual {
                    stale.push(format!("{module}.{key}: budget {max}, actual {actual}"));
                }
            }
        }
    }
    stale.sort();
    assert!(
        stale.is_empty(),
        "these budgets are looser than the code, hiding ground already won:\n{}",
        stale.join("\n")
    );
}

#[test]
fn the_census_tool_and_this_test_agree() {
    // Two implementations of one definition will drift, and a drift means the
    // ratchet is measuring the wrong thing. Gated the way the vercmp oracle is:
    // without python3 the note prints and the suite moves on.
    let available = std::process::Command::new("python3")
        .arg("--version")
        .output()
        .is_ok();
    if !available {
        println!("python3 is not on PATH — skipping the census cross-check");
        return;
    }
    let out = std::process::Command::new("python3")
        .arg("tools/arch-census.py")
        .arg("--json")
        .current_dir(root())
        .output()
        .expect("run tools/arch-census.py");
    assert!(out.status.success(), "census tool failed: {}", String::from_utf8_lossy(&out.stderr));
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("census json");
    let census = Census::take();

    let mut disagreements = Vec::new();
    let mods = report.get("modules").and_then(|m| m.as_object()).expect("modules");
    for (module, row) in mods {
        let Some(mine) = census.modules.get(module) else {
            disagreements.push(format!("{module}: the census tool sees a module this test does not"));
            continue;
        };
        for (key, theirs) in [
            ("pub", mine.pub_items),
            ("dead", mine.dead),
            ("test", mine.test_only),
            ("deadonly", mine.dead_only),
            ("priv", mine.pub_crate),
            ("glob", mine.globs),
        ] {
            let got = row.get(key).and_then(|v| v.as_u64()).unwrap_or(u64::MAX) as usize;
            if got != theirs {
                disagreements.push(format!("{module}.{key}: tool {got}, test {theirs}"));
            }
        }
    }
    disagreements.sort();
    assert!(
        disagreements.is_empty(),
        "tools/arch-census.py and this test disagree about what a module exports;\n\
         one of them is wrong, and the budget cannot be trusted until they match:\n{}",
        disagreements.join("\n")
    );
}

/// Every `pub` item that exists only because a test names it has a recorded
/// disposition, and the counts may only shrink.
///
/// `tools/test-surface.py` asks two questions the census cannot: whether a test
/// actually *calls* the item or merely mentions it inside a string, and whether
/// production code inside the declaring module calls it. The answers yield four
/// dispositions — `gate`, `move-test`, `narrow`, `residue` — and this test holds
/// the crate to them in three ways:
///
/// - every row must carry a hand-written reason from
///   `tools/test-surface-reasons.json`, so no item is disposed of by a heuristic
///   nobody read;
/// - the per-disposition counts, and `gate_pending` — items decided to be gated
///   but not yet gated — may only shrink against the budget.
///
/// `residue` is the honest column: items production needs inside their own module
/// *and* a fixture-bound integration test needs from outside. Rust has no
/// test-conditional visibility, so those cannot be narrowed without breaking one
/// side or the other; ratcheting the count is what keeps the column from growing
/// while it is worked down by changing tests rather than visibilities.
#[test]
fn the_test_surface_is_disposed_of() {
    if !std::process::Command::new("python3")
        .arg("--version")
        .output()
        .is_ok()
    {
        println!("python3 is not on PATH — skipping the test-surface check");
        return;
    }
    let out = std::process::Command::new("python3")
        .arg("tools/test-surface.py")
        .arg("--json")
        .current_dir(root())
        .output()
        .expect("run tools/test-surface.py");
    assert!(
        out.status.success(),
        "tools/test-surface.py failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("test-surface json");
    let rows = report.get("rows").and_then(|r| r.as_array()).expect("rows");

    let mut unreasoned = Vec::new();
    let mut unconfirmed = Vec::new();
    for row in rows {
        let name = row.get("name").and_then(|v| v.as_str()).unwrap_or("?");
        let module = row.get("module").and_then(|v| v.as_str()).unwrap_or("?");
        let disp = row.get("disp").and_then(|v| v.as_str()).unwrap_or("?");
        if !row.get("hand_written").and_then(|v| v.as_bool()).unwrap_or(false) {
            unreasoned.push(format!("{module}.{name} ({disp})"));
        }
        // Every piece of in-module evidence for this item is a call in method
        // position on some receiver. A name match cannot tell `self.store_dir()`
        // from `listener.local_addr()` — the latter is std's, on a different
        // type, and it once made a function with no callers look production-used.
        // So these rows are named for a human and stay failing until confirmed.
        if row.get("dotted_only").and_then(|v| v.as_bool()).unwrap_or(false)
            && disp != "already-gated"
            && !row.get("confirmed").and_then(|v| v.as_bool()).unwrap_or(false)
        {
            unconfirmed.push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?")));
        }
    }
    assert!(
        unreasoned.is_empty(),
        "{} test-only items have no hand-written disposition reason in \
         tools/test-surface-reasons.json:\n{}\n\
         a disposition nobody argued for is not a decision.",
        unreasoned.len(),
        unreasoned.join("\n")
    );
    assert!(
        unconfirmed.is_empty(),
        "{} items are counted as production-used only because something calls \
         `.name()` somewhere in their module, and no human has confirmed that the \
         receiver is the right type. Read each cited line and add it to \
         tools/test-surface-confirmed.json, or gate the item:\n{}",
        unconfirmed.len(),
        unconfirmed.join("\n")
    );

    let budget = budget_section("test_surface");
    let surface = &budget;
    let counts = report.get("counts").and_then(|c| c.as_object()).expect("counts");
    let mut looser = Vec::new();
    let mut tighter = Vec::new();
    for (key, ceiling) in surface {
        let actual = counts.get(key).and_then(|v| v.as_u64()).unwrap_or(0) as usize;
        if actual > *ceiling {
            looser.push(format!("{key}: budget {ceiling}, actual {actual}"));
        } else if actual < *ceiling {
            tighter.push(format!("{key}: budget {ceiling}, actual {actual}"));
        }
    }
    assert!(
        looser.is_empty(),
        "the test surface grew past its budget — a new `pub` item that only tests \
         name needs a disposition and a lower ceiling elsewhere:\n{}",
        looser.join("\n")
    );
    assert!(
        tighter.is_empty(),
        "these test-surface budgets are looser than the code, hiding ground already \
         won (rewrite with `python3 tools/test-surface.py --write` and re-record):\n{}",
        tighter.join("\n")
    );
}