summaryrefslogtreecommitdiffstats
path: root/tests/architecture.rs
blob: b32ea54179fe8f4630f145ca6d7cf53a3c83f031 (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
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
//! 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 {
    pub_crate_decl(line).is_some()
}

/// The name a `pub(crate)` declaration introduces. A narrowed item is still a
/// member of its module, which is what the allowlist is checked against.
fn pub_crate_decl(line: &str) -> Option<String> {
    if is_comment(line) {
        return None;
    }
    let rest = line.trim_start().strip_prefix("pub(crate) ")?;
    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_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,
    over_wide: 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();
        let allowlist = allowed_pub_items();
        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 {
                // An item the budget file argues for is a decision, not a hole,
                // so it leaves the dead columns entirely. `deadonly` then means
                // *dead and unargued* — the one number that can stay at zero.
                if allowlist.contains(&format!("{module}.{name}")) {
                    continue;
                }
                let module = modules.get_mut(module).unwrap();
                module.dead += 1;
                if used_by_tests {
                    module.test_only += 1;
                } else {
                    module.dead_only += 1;
                }
            }
        }

        // A `pub(crate)` item is over-wide when no file except the one that
        // declares it writes its name: it offers the crate a thing nothing
        // outside its own file reaches, and plain private is what it should be.
        // `tests/` is not consulted — a separate crate cannot name a `pub(crate)`
        // item, so a mention there says nothing. As with `dead`, a name declared
        // in several files is flagged only when no file outside all of them says
        // it, and the compiler, not this count, gives the verdict.
        let mut pc_declared: BTreeMap<String, BTreeSet<PathBuf>> = BTreeMap::new();
        for (path, text) in &texts {
            for line in text.lines() {
                if let Some(name) = pub_crate_decl(line) {
                    pc_declared.entry(name).or_default().insert(path.clone());
                }
            }
        }
        let over_allow = allowed_overwide_items();
        for (name, files) in &pc_declared {
            let read_outside = texts
                .iter()
                .any(|(path, text)| !files.contains(path) && mentions(text, name));
            if read_outside {
                continue;
            }
            for path in files {
                let module = module_of(path);
                // Argued, so not counted: the reason it stays `pub(crate)` is in
                // the budget file next to its name, exactly as on the `pub` side.
                if over_allow.contains(&format!("{module}.{name}")) {
                    continue;
                }
                modules.get_mut(&module).unwrap().over_wide += 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
    }
}

/// The `dead_code.allowlist` keys — `module.item` for every item that stays
/// `pub` by decision, with its reason next to it in the same file.
fn allowed_pub_items() -> BTreeSet<String> {
    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");
    value
        .get("dead_code")
        .and_then(|d| d.get("allowlist"))
        .and_then(|a| a.as_object())
        .map(|a| {
            a.keys()
                .map(|k| {
                    assert!(!k.trim().is_empty(), "an allowlist key cannot be blank");
                    k.clone()
                })
                .collect()
        })
        .unwrap_or_default()
}

/// The `over_visibility.allowlist` keys — `module.item` for every `pub(crate)`
/// item that stays `pub(crate)` by decision, with the compiler fact beside it.
fn allowed_overwide_items() -> BTreeSet<String> {
    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");
    value
        .get("over_visibility")
        .and_then(|d| d.get("allowlist"))
        .and_then(|a| a.as_object())
        .map(|a| {
            a.keys()
                .map(|k| {
                    assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank");
                    k.clone()
                })
                .collect()
        })
        .unwrap_or_default()
}

/// 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); 5] {
    [
        ("pub", row.pub_items),
        ("dead", row.dead),
        ("deadonly", row.dead_only),
        ("overwide", row.over_wide),
        ("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),
            ("overwide", mine.over_wide),
            ("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")
    );

    // A row is `ambiguous` when the only evidence that production uses the item
    // is a bare mention of a name the detector cannot resolve — `new`, `open`
    // and `record` are declared in many modules, and a line saying `Foo::new()`
    // in http says nothing about `db::open`. The tool genuinely does not know,
    // so a human has to say which item the mention meant and record the verdict.
    let mut unadjudicated = Vec::new();
    for row in rows {
        if row.get("ambiguous").and_then(|v| v.as_bool()).unwrap_or(false)
            && !row.get("adjudicated").and_then(|v| v.as_bool()).unwrap_or(false)
        {
            unadjudicated.push(format!(
                "{}:{} at {}",
                row.get("module").and_then(|v| v.as_str()).unwrap_or("?"),
                row.get("name").and_then(|v| v.as_str()).unwrap_or("?"),
                row.get("where").and_then(|v| v.as_str()).unwrap_or("?")
            ));
        }
    }
    assert!(
        unadjudicated.is_empty(),
        "{} items look production-used only because a bare mention of a colliding \n\
         name could have meant them, and no human has said which item the mention \n\
         referred to. Read the cited line and record the verdict in \n\
         tools/test-surface-ambiguous.json:\n{}",
        unadjudicated.len(),
        unadjudicated.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")
    );
}

/// The definitive check, and the slow one: compile a throwaway crate against
/// `aur-build` twice, once without `test-support` and once with it, and try to
/// name every dispositioned item from outside.
///
/// `tools/test-surface.py` infers the test surface by reading source, and
/// inference has been wrong before — a name matched inside a string literal
/// made `review::approve::withdraw` look production-used, and keying rows by
/// bare name merged `pipeline::dispatch::Pool::shutdown` into the gated
/// `db::Writer::shutdown` row. This test does not read source. It asks the
/// compiler what a release build actually lets an outside crate reach.
///
/// `#[ignore]`d because it builds the library twice from scratch, roughly
/// doubling the suite. Run it with `cargo test --test architecture -- --ignored`
/// or `AUR_PROBE_RELEASE_SURFACE=1 cargo test --test architecture`.
#[test]
#[ignore = "builds the library twice; run with --ignored or AUR_PROBE_RELEASE_SURFACE=1"]
fn the_release_build_exports_nothing_that_only_tests_reach() {
    let out = std::process::Command::new("python3")
        .arg("tools/release-surface-probe.py")
        .current_dir(root())
        .output()
        .expect("run tools/release-surface-probe.py");
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        out.status.success(),
        "a release build still exports something only the test tier needs:\n{text}{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        text.contains("nothing leaked"),
        "the probe did not report success:\n{text}"
    );
}

/// The `dead_code.allowlist` is a set of decisions, so it has to stay in step
/// with the code in both directions.
///
/// An entry that names nothing is the dangerous direction: it is an excuse that
/// outlived the item it excused, and the next item to appear under that name
/// inherits a permission nobody granted. The other direction — a blank reason —
/// is an entry nobody read, which is the same thing as no entry.
#[test]
fn the_dead_code_allowlist_names_real_items() {
    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 allow = value
        .get("dead_code")
        .and_then(|d| d.get("allowlist"))
        .and_then(|a| a.as_object())
        .expect("budget file has a dead_code.allowlist object");

    // Every name a module declares, `pub` or `pub(crate)`: a narrowed item keeps
    // its entry (the reason it is not named from outside still holds), an item
    // that no longer exists does not.
    let mut declared: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for path in src_files() {
        let module = module_of(&path);
        for line in std::fs::read_to_string(&path).expect("read source").lines() {
            let name = match pub_decl(line) {
                Some(name) => name,
                None => match pub_crate_decl(line) {
                    Some(name) => name,
                    None => continue,
                },
            };
            if !name.is_empty() {
                declared.entry(module.clone()).or_default().insert(name);
            }
        }
    }

    let mut stale = Vec::new();
    let mut blank = Vec::new();
    for (key, reason) in allow {
        let Some((module, name)) = key.split_once('.') else {
            stale.push(format!("{key}: a key is `module.item`"));
            continue;
        };
        if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) {
            blank.push(key.clone());
        }
        if !declared.get(module).is_some_and(|names| names.contains(name)) {
            stale.push(format!("{key} at {reason}"));
        }
    }
    stale.sort();
    blank.sort();
    assert!(
        stale.is_empty(),
        "these allowlist entries name something the module no longer declares.\n\
         A permission nobody can point at is how a dead item returns unnoticed:\n{}",
        stale.join("\n")
    );
    assert!(
        blank.is_empty(),
        "these allowlist entries have no reason (or one too short to be a reason):\n{}\n\
         an item is kept by an argument, not by a blank line.",
        blank.join("\n")
    );
}

/// The `over_visibility.allowlist` is a set of decisions too, and it is checked
/// the same two ways: an entry must name something that is still `pub(crate)` in
/// the module it names, and it must carry a reason worth reading.
///
/// The first direction matters more here than on the `pub` side. A `pub(crate)`
/// item that has since gone private still matches a `module.item` key written
/// against the module's declared names, so the check has to look at the
/// `pub(crate)` declarations specifically — otherwise the permission quietly
/// re-widens the item it was left behind by.
#[test]
fn the_over_visibility_allowlist_names_real_items() {
    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 allow = value
        .get("over_visibility")
        .and_then(|d| d.get("allowlist"))
        .and_then(|a| a.as_object())
        .expect("budget file has an over_visibility.allowlist object");

    let mut pub_crate_declared: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for path in src_files() {
        let module = module_of(&path);
        for line in std::fs::read_to_string(&path).expect("read source").lines() {
            if let Some(name) = pub_crate_decl(line) {
                pub_crate_declared.entry(module.clone()).or_default().insert(name);
            }
        }
    }

    let mut stale = Vec::new();
    let mut blank = Vec::new();
    for (key, reason) in allow {
        let Some((module, name)) = key.split_once('.') else {
            stale.push(format!("{key}: a key is `module.item`"));
            continue;
        };
        if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) {
            blank.push(key.clone());
        }
        if !pub_crate_declared
            .get(module)
            .is_some_and(|names| names.contains(name))
        {
            stale.push(format!("{key} at {reason}"));
        }
    }
    stale.sort();
    blank.sort();
    assert!(
        stale.is_empty(),
        "these over-wide permissions name something that is no longer a `pub(crate)`\n\
         item in that module — it went private, or it was never one:\n{}",
        stale.join("\n")
    );
    assert!(
        blank.is_empty(),
        "these over-wide permissions have no reason (or one too short to be one):\n{}\n\
         say what the compiler refuses to let go private, not that it felt safer.",
        blank.join("\n")
    );
}

/// `tests/common/mod.rs` is compiled into every test binary, so the suite keeps
/// a crate-level `allow(dead_code)` there — a helper used by one binary is dead
/// code in the other twenty, and the lint would fire everywhere and mean
/// nothing. That allowance is only honest if nothing is unused by *all* of them,
/// which is what this checks.
///
/// A name is used if anything under `tests/` writes it besides its own
/// declaration. A type whose name nobody writes is still used if a field or
/// method of it is: `Web::raw_request` hands back a `Raw` no test names, and
/// reading `.status` off it is a use of the type.
///
/// Private items are checked too. The blanket allowance in `tests/common`
/// excuses a private helper exactly as thoroughly as a public one, and a
/// private helper called by nothing is the harder case to notice, not the
/// easier one.
#[test]
fn the_test_helpers_are_used() {
    let common = root().join("tests/common/mod.rs");
    let text = std::fs::read_to_string(&common).expect("read tests/common/mod.rs");
    let mut others = String::new();
    for path in test_files() {
        others.push_str(&std::fs::read_to_string(&path).expect("read test"));
    }

    let lines: Vec<&str> = text.lines().collect();
    let mut unused = Vec::new();
    for (i, line) in lines.iter().enumerate() {
        // `pub` and private alike: the blanket `allow(dead_code)` at the top of
        // the file excuses both, so a private helper nobody calls is exactly as
        // dead as a public one, and just as invisible to the compiler here.
        let t = line.trim_start();
        let indent = line.len() - t.len();
        if indent > 4 {
            continue;
        }
        let rest = t.strip_prefix("pub ").unwrap_or(t);
        let Some(kind) = ["fn ", "struct ", "enum ", "const ", "static ", "type ", "trait "]
            .into_iter()
            .find(|k| rest.starts_with(k))
        else {
            continue;
        };
        let name = word_tail(&rest[kind.len()..]);
        if name.is_empty() {
            continue;
        }
        // Everything this declaration introduces, minus the declaration itself.
        let mut corpus = others
            .replace(&format!("pub {kind}{name}"), "")
            .replace(&format!("{kind}{name}"), "");
        if kind != "fn " {
            // Members of a struct or enum count as uses of the type.
            let mut depth = 0;
            for follow in lines[i..].iter() {
                depth += follow.matches('{').count() as i32 - follow.matches('}').count() as i32;
                if depth > 1 {
                    let member = follow
                        .trim_start()
                        .trim_start_matches("pub ")
                        .split([':', '('])
                        .next()
                        .unwrap_or("")
                        .split_whitespace()
                        .last()
                        .unwrap_or("");
                    if !member.is_empty() && member != name {
                        corpus.push('\n');
                        corpus.push_str(member);
                    }
                }
                if depth <= 0 && follow != line {
                    break;
                }
            }
        }
        if !mentions(&corpus, &name) {
            unused.push(format!("{name} ({})", &t[..t.len().min(60)]));
        }
    }
    unused.sort();
    assert!(
        unused.is_empty(),
        "these test helpers are named by no test:\n{}\n\
         delete them; `allow(dead_code)` in `tests/common` excuses per-binary \
         noise, not dead weight.",
        unused.join("\n")
    );
}

/// A fixture no test names is a corpus entry nobody maintains: it still costs
/// the copy every `env_with_fixture` performs on its way to failing, and it
/// drifts silently because nothing notices it drifting.
#[test]
fn every_fixture_is_referenced() {
    let corpus = root().join("testcorpus");
    let mut names = String::new();
    for path in test_files() {
        names.push_str(&std::fs::read_to_string(&path).expect("read test"));
    }
    let unreferenced: Vec<String> = std::fs::read_dir(&corpus)
        .expect("read testcorpus")
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
        .map(|e| e.file_name().to_string_lossy().to_string())
        .filter(|name| !mentions(&names, name))
        .collect();
    assert!(
        unreferenced.is_empty(),
        "these fixtures in testcorpus/ are named by no test: {unreferenced:?}\n\
         either drive one or delete the directory.",
    );
}

/// The two places the budget states how many unargued dead items a module may
/// have must say the same thing.
///
/// `modules.<m>.deadonly` is the ratchet `interfaces_stay_within_budget` reads;
/// `dead_code.deadonly.<m>` is the one `tools/arch-census.py --budget` reads.
/// They are written by the same invocation and disagree only if someone edited
/// one by hand, which is exactly the moment a ratchet stops meaning anything.
/// Both are zero, and zero is the point: an item that is dead, exported and
/// unargued is not a budget question, it is a failure.
#[test]
fn the_dead_code_budget_matches_the_code() {
    let path = root().join("tests/architecture-budget.json");
    let value: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json");
    let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules");
    let dead_code = value
        .get("dead_code")
        .and_then(|d| d.get("deadonly"))
        .and_then(|d| d.as_object())
        .expect("dead_code.deadonly");
    let census = Census::take();

    let mut mismatch = Vec::new();
    for (module, row) in modules {
        let interface = row.get("deadonly").and_then(|v| v.as_u64()).unwrap_or(u64::MAX);
        let dead = dead_code.get(module).and_then(|v| v.as_u64());
        let actual = census
            .modules
            .get(module)
            .map(|m| m.dead_only as u64)
            .unwrap_or(u64::MAX);
        if dead != Some(interface) || interface != actual {
            mismatch.push(format!(
                "{module}: dead_code.deadonly {:?}, modules.deadonly {interface}, actual {actual}",
                dead
            ));
        }
    }
    for module in dead_code.keys() {
        if !modules.contains_key(module) {
            mismatch.push(format!("{module}: in dead_code.deadonly, absent from modules"));
        }
    }
    mismatch.sort();
    assert!(
        mismatch.is_empty(),
        "the budget contradicts itself about how many unargued dead items a module has:\n{}",
        mismatch.join("\n")
    );
}

#[test]
fn the_over_visibility_budget_matches_the_code() {
    // The same self-consistency the dead-code budget is held to: the accepted
    // count, the number in the `modules` section, and the number the census
    // actually measures have to be one number, or the ratchet is checking a
    // figure nothing reads.
    let path = root().join("tests/architecture-budget.json");
    let value: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json");
    let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules");
    let over = value
        .get("over_visibility")
        .and_then(|d| d.get("overwide"))
        .and_then(|d| d.as_object())
        .expect("over_visibility.overwide");
    let census = Census::take();

    let mut mismatch = Vec::new();
    for (module, row) in modules {
        let stated = row.get("overwide").and_then(|v| v.as_u64()).unwrap_or(u64::MAX);
        let accepted = over.get(module).and_then(|v| v.as_u64());
        let actual = census
            .modules
            .get(module)
            .map(|m| m.over_wide as u64)
            .unwrap_or(u64::MAX);
        if accepted != Some(stated) || stated != actual {
            mismatch.push(format!(
                "{module}: over_visibility.overwide {:?}, modules.overwide {stated}, actual {actual}",
                accepted
            ));
        }
    }
    for module in over.keys() {
        if !modules.contains_key(module) {
            mismatch.push(format!("{module}: in over_visibility.overwide, absent from modules"));
        }
    }
    mismatch.sort();
    assert!(
        mismatch.is_empty(),
        "the budget contradicts itself about how many over-wide `pub(crate)` items a\n\
         module has:\n{}",
        mismatch.join("\n")
    );
}

/// Two tools write one file, so neither may erase what the other owns.
///
/// `tools/arch-census.py` writes the module numbers and the accepted dead-code
/// counts; `tools/test-surface.py` writes the test-surface counts; a human owns
/// the allowlist. A rewrite that drops a section does not fail anything until
/// the ratchet quietly stops checking that axis, so this runs both writers
/// against a copy and fails if either section disappears.
#[test]
fn the_budget_writers_preserve_each_other() {
    let source = std::fs::read_to_string(root().join("tests/architecture-budget.json")).expect("read budget");
    let before: serde_json::Value = serde_json::from_str(&source).expect("budget is json");
    let tmp = std::env::temp_dir().join(format!("aur-budget-preserve-{}.json", std::process::id()));
    std::fs::write(&tmp, &source).expect("write temp budget");

    for tool in ["tools/arch-census.py", "tools/test-surface.py"] {
        let out = std::process::Command::new("python3")
            .arg(tool)
            .arg("--write-budget")
            .arg(&tmp)
            .current_dir(root())
            .output()
            .unwrap_or_else(|e| panic!("run {tool}: {e}"));
        assert!(out.status.success(), "{tool} failed: {}", String::from_utf8_lossy(&out.stderr));
        let after: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget"))
                .expect("written budget is json");
        for section in ["test_surface", "dead_code", "over_visibility"] {
            assert!(
                after.get(section).is_some(),
                "{tool} erased the `{section}` section it does not own"
            );
        }
        assert_eq!(
            after["dead_code"]["allowlist"], before["dead_code"]["allowlist"],
            "{tool} rewrote the hand-written allowlist"
        );
    }
    std::fs::remove_file(&tmp).ok();
}