返回 CodeWhale
check-dead-code-budget.py
根目录 / scripts / check-dead-code-budget.py
1 #!/usr/bin/env python3
2 """Ratchet on `#[allow(dead_code)]` so the wall can shrink but never regrow (#4785).
3
4 Why this exists rather than a one-time sweep:
5
6 issue filed 2026-07-?? 464 attributes / 143 files
7 audit 2026-07-26 426 / 111
8 audit 2026-07-28 481 / 155
9
10 The sweep was working and the count still went *up*, because two large landings
11 added state whose accessors only their own tests read. A sweep is a snapshot; a
12 budget is a direction. This gate makes the number a one-way door.
13
14 It deliberately does NOT judge whether any individual attribute is justified —
15 plenty are. It only refuses to let the total rise, which is the property the
16 issue actually needs and the only one that can be checked mechanically.
17
18 Note the blind spot this compensates for: CI's clippy runs without
19 `--all-targets`, so it never lints `cfg(test)` or integration-test code. A prior
20 strip-and-check measured 197 attributes alive *only* because a test references
21 them — exactly the ones a test-blind lint can never adjudicate.
22
23 Usage:
24 python3 scripts/check-dead-code-budget.py # enforce
25 python3 scripts/check-dead-code-budget.py --update # rewrite the budget file
26 """
27
28 from __future__ import annotations
29
30 import argparse
31 import json
32 import re
33 import sys
34 from pathlib import Path
35
36 REPO_ROOT = Path(__file__).resolve().parent.parent
37 CRATES_DIR = REPO_ROOT / "crates"
38 BUDGET_PATH = REPO_ROOT / "scripts" / "dead-code-budget.json"
39
40 # Matches `#[allow(dead_code)]`, `#![allow(dead_code)]`, and combined forms with
41 # `dead_code` in any position of the lint list, including lists that span lines,
42 # like `#[allow(async_fn_in_trait, dead_code)]`.
43 ALLOW_PATTERN = re.compile(r"\ballow\(\s*(?:[\w:]+\s*,\s*)*dead_code\b")
44 # `#[expect(dead_code)]` suppresses exactly the same lint. Counting only the
45 # `allow` spelling made the gate blind: rewriting an `allow` as an `expect`
46 # lowered the headline number by the full count while removing no dead code
47 # at all (#6241). `137fb70a9` did this 92 times and the budget recorded a
48 # 115-point "improvement" for a real reduction of 21.
49 EXPECT_PATTERN = re.compile(r"\bexpect\(\s*(?:[\w:]+\s*,\s*)*dead_code\b")
50
51
52 def strip_line_comments(text: str) -> str:
53 return "\n".join(
54 line for line in text.split("\n") if not line.lstrip().startswith("//")
55 )
56
57
58 def measure() -> tuple[int, int, dict[str, dict[str, int]]]:
59 """Return (allow total, expect total, per-crate {allow, expect} counts).
60
61 Both spellings suppress the same lint, so the gate ratchets on their sum.
62 They are still reported separately because `expect` is the better
63 attribute — it errors when the lint stops firing, so it cannot rot
64 silently — and a sweep converting `allow` into `expect` is real progress
65 even though it leaves the total unchanged.
66 """
67 per_crate: dict[str, dict[str, int]] = {}
68 allow_total = 0
69 expect_total = 0
70 for path in sorted(CRATES_DIR.rglob("*.rs")):
71 try:
72 text = path.read_text(encoding="utf-8")
73 except (OSError, UnicodeDecodeError):
74 continue
75 code = strip_line_comments(text)
76 allows = len(ALLOW_PATTERN.findall(code))
77 expects = len(EXPECT_PATTERN.findall(code))
78 if not allows and not expects:
79 continue
80 crate = path.relative_to(CRATES_DIR).parts[0]
81 entry = per_crate.setdefault(crate, {"allow": 0, "expect": 0})
82 entry["allow"] += allows
83 entry["expect"] += expects
84 allow_total += allows
85 expect_total += expects
86 return allow_total, expect_total, per_crate
87
88
89 def load_budget() -> dict:
90 if not BUDGET_PATH.exists():
91 sys.exit(f"missing budget file: {BUDGET_PATH.relative_to(REPO_ROOT)}")
92 return json.loads(BUDGET_PATH.read_text(encoding="utf-8"))
93
94
95 def write_budget(
96 allow_total: int, expect_total: int, per_crate: dict[str, dict[str, int]]
97 ) -> None:
98 payload = {
99 "_comment": (
100 "Ceiling for dead-code suppressions across crates/, counting both "
101 "`#[allow(dead_code)]` and `#[expect(dead_code)]`. `total` is the "
102 "sum and is the ratcheted figure. It may go down freely; raising "
103 "it needs a reviewer to say why in the PR. Regenerate with: "
104 "python3 scripts/check-dead-code-budget.py --update"
105 ),
106 "_issue": "https://github.com/codewhale-hq/CodeWhale/issues/4785",
107 "_expect_blind_spot": (
108 "Until #6241 this gate counted only the `allow` spelling, so "
109 "rewriting an allow as an expect lowered the number without "
110 "removing any dead code. The ceiling was re-based to the true "
111 "combined count when that was fixed; it is not a regression."
112 ),
113 "total": allow_total + expect_total,
114 "allow_total": allow_total,
115 "expect_total": expect_total,
116 "per_crate": dict(sorted(per_crate.items())),
117 }
118 BUDGET_PATH.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
119
120
121 def main() -> int:
122 parser = argparse.ArgumentParser(description=__doc__)
123 parser.add_argument(
124 "--update",
125 action="store_true",
126 help="rewrite the budget file from the working tree",
127 )
128 args = parser.parse_args()
129
130 allow_total, expect_total, per_crate = measure()
131 total = allow_total + expect_total
132
133 if args.update:
134 write_budget(allow_total, expect_total, per_crate)
135 rel = BUDGET_PATH.relative_to(REPO_ROOT)
136 print(
137 f"[dead-code-budget] wrote {rel}: total={total} "
138 f"(allow={allow_total}, expect={expect_total})"
139 )
140 return 0
141
142 budget = load_budget()
143 ceiling = int(budget["total"])
144
145 if total > ceiling:
146 print(
147 f"[dead-code-budget] FAIL: {total} dead-code suppressions "
148 f"(allow={allow_total}, expect={expect_total}), "
149 f"budget is {ceiling} (+{total - ceiling}).",
150 file=sys.stderr,
151 )
152 print("", file=sys.stderr)
153 print("Per crate now vs. budget:", file=sys.stderr)
154 recorded = budget.get("per_crate", {})
155 for crate in sorted(set(per_crate) | set(recorded)):
156 entry = per_crate.get(crate, {"allow": 0, "expect": 0})
157 now = entry["allow"] + entry["expect"]
158 was_entry = recorded.get(crate, 0)
159 # Tolerate the pre-#6241 shape, where each crate mapped to a bare
160 # `allow` count rather than an {allow, expect} pair.
161 if isinstance(was_entry, dict):
162 was = int(was_entry.get("allow", 0)) + int(was_entry.get("expect", 0))
163 else:
164 was = int(was_entry)
165 marker = " <-- grew" if now > was else ""
166 print(
167 f" {crate:<16} {now:>4} (allow {entry['allow']}, "
168 f"expect {entry['expect']}; budget {was}){marker}",
169 file=sys.stderr,
170 )
171 print("", file=sys.stderr)
172 print(
173 "Either delete the dead item, or narrow the attribute to the one item\n"
174 "that needs it instead of a whole module. If the growth is genuinely\n"
175 "justified, run `python3 scripts/check-dead-code-budget.py --update`\n"
176 "and say why in the PR description — the point of this gate is that\n"
177 "raising the number is a visible decision, not an accident.",
178 file=sys.stderr,
179 )
180 return 1
181
182 if total < ceiling:
183 print(
184 f"[dead-code-budget] {total} suppressions "
185 f"(allow={allow_total}, expect={expect_total}), budget {ceiling} "
186 f"({ceiling - total} under). Lower the budget to lock in the win:\n"
187 f" python3 scripts/check-dead-code-budget.py --update"
188 )
189 return 0
190
191 print(
192 f"[dead-code-budget] PASS: {total} suppressions "
193 f"(allow={allow_total}, expect={expect_total}), exactly at budget."
194 )
195 return 0
196
197
198 if __name__ == "__main__":
199 sys.exit(main())
200
200 lines PYTHON