返回 CodeWhale
check-swallowed-errors-budget.py
根目录 / scripts / check-swallowed-errors-budget.py
1 #!/usr/bin/env python3
2 """Ratchet for `let _ =` swallowing durability-critical results.
3
4 Dropping the result of `sync_all`, `write_atomic`, `save_session`,
5 `record_failure` or a `.spawn(` in production code turns an I/O failure into
6 silent data loss or a missing task. This check counts those statements per file
7 (test code excluded) and fails if any file exceeds its audited count in
8 `swallowed-errors-budget.json`. Handle the error, or log it and keep the
9 `let _ =` only with an audited reason by raising the budget.
10
11 Run `python3 scripts/check-swallowed-errors-budget.py --update` after removing
12 sites or after an intentional addition.
13 """
14
15 from __future__ import annotations
16
17 import importlib.util
18 import json
19 import re
20 import sys
21 from pathlib import Path
22
23 ROOT = Path(__file__).resolve().parents[1]
24 CRATES = ROOT / "crates"
25 BUDGET_PATH = Path(__file__).with_name("swallowed-errors-budget.json")
26
27 _spec = importlib.util.spec_from_file_location(
28 "_blocking_budget", Path(__file__).with_name("check-blocking-calls-budget.py")
29 )
30 _blocking = importlib.util.module_from_spec(_spec)
31 sys.modules[_spec.name] = _blocking
32 _spec.loader.exec_module(_blocking)
33
34 LET_RE = re.compile(r"\blet\s+_\s*(?::[^=;]+)?=\s*([^;]*);", re.DOTALL)
35 CFG_TEST_RE = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]")
36 TARGETS = {
37 "sync_all": re.compile(r"\bsync_all\b"),
38 "write_atomic": re.compile(r"\bwrite_atomic\w*"),
39 "save_session": re.compile(r"\bsave_session\w*"),
40 "record_failure": re.compile(r"\brecord_failure\w*"),
41 "spawn": re.compile(r"\.spawn\s*\("),
42 }
43
44
45 def blank_cfg_test_items(text: str) -> str:
46 out = list(text)
47 for match in CFG_TEST_RE.finditer(text):
48 brace = text.find("{", match.end())
49 semi = text.find(";", match.end())
50 if brace == -1 or (semi != -1 and semi < brace):
51 continue
52 depth = 0
53 end = len(text)
54 for i in range(brace, len(text)):
55 if text[i] == "{":
56 depth += 1
57 elif text[i] == "}":
58 depth -= 1
59 if depth == 0:
60 end = i + 1
61 break
62 for i in range(match.start(), end):
63 if out[i] != "\n":
64 out[i] = " "
65 return "".join(out)
66
67
68 def count_text(text: str) -> dict[str, int]:
69 cleaned = blank_cfg_test_items(_blocking.strip_comments_and_strings(text))
70 counts: dict[str, int] = {}
71 for stmt in LET_RE.finditer(cleaned):
72 for name, pattern in TARGETS.items():
73 if pattern.search(stmt.group(1)):
74 counts[name] = counts.get(name, 0) + 1
75 return counts
76
77
78 def collect_current() -> dict[str, dict[str, int]]:
79 current: dict[str, dict[str, int]] = {}
80 test_only = _blocking.cfg_test_module_files()
81 for path in sorted(CRATES.rglob("*.rs")):
82 if path.resolve() in test_only or "tests" in path.relative_to(CRATES).parts:
83 continue
84 try:
85 counts = count_text(path.read_text(encoding="utf-8", errors="ignore"))
86 except OSError:
87 continue
88 if counts:
89 current[str(path.relative_to(ROOT))] = counts
90 return current
91
92
93 def compare(current: dict, budget: dict) -> tuple[list[str], list[str]]:
94 failures: list[str] = []
95 savings: list[str] = []
96 for path, counts in sorted(current.items()):
97 allowed = budget.get(path, {})
98 for name, count in counts.items():
99 limit = allowed.get(name, 0)
100 if count > limit:
101 failures.append(f"{path}: {name} swallowed {count} > budget {limit}")
102 elif count < limit:
103 savings.append(f"{path}: {name} swallowed {count} < budget {limit} — tighten with --update")
104 for path, counts in sorted(budget.items()):
105 for name, limit in counts.items():
106 if name not in current.get(path, {}):
107 savings.append(f"{path}: {name} swallowed 0 < budget {limit} — tighten with --update")
108 return failures, savings
109
110
111 def main() -> int:
112 current = collect_current()
113 if "--update" in sys.argv:
114 BUDGET_PATH.write_text(json.dumps(current, indent=2, sort_keys=True) + "\n", encoding="utf-8")
115 total = sum(sum(v.values()) for v in current.values())
116 print(f"wrote {BUDGET_PATH.name}: {total} sites across {len(current)} files")
117 return 0
118 if not BUDGET_PATH.exists():
119 print(f"missing {BUDGET_PATH.name}; run with --update to create it", file=sys.stderr)
120 return 2
121 failures, savings = compare(current, json.loads(BUDGET_PATH.read_text(encoding="utf-8")))
122 for line in savings:
123 print(line)
124 if failures:
125 print("\nSwallowed-error budget exceeded — new `let _ =` drops a durability result:", file=sys.stderr)
126 for line in failures:
127 print(f" {line}", file=sys.stderr)
128 print(
129 "Propagate or log the error. If dropping it is audited and intended, run:\n"
130 " python3 scripts/check-swallowed-errors-budget.py --update",
131 file=sys.stderr,
132 )
133 return 1
134 total = sum(sum(v.values()) for v in current.values())
135 print(f"swallowed-errors budget ok: {total} audited sites across {len(current)} files")
136 return 0
137
138
139 if __name__ == "__main__":
140 raise SystemExit(main())
141
141 lines PYTHON