-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
1681 lines (1482 loc) · 54.9 KB
/
Copy pathrun.py
File metadata and controls
1681 lines (1482 loc) · 54.9 KB
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
#!/usr/bin/env python3
"""Run Culler's public benchmark suite.
The benchmark is intentionally dependency-free. Projects and expected findings
are checked in; the runner only validates, executes tools, parses outputs, and
scores deterministic results.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
CATEGORIES = {
"unused_import",
"unused_local",
"unreachable_statement",
"unused_function",
"unused_class",
"unused_private_method",
}
CULL_TYPE_TO_CATEGORY = {
("CULL001", "function"): "unused_function",
("CULL002", "class"): "unused_class",
("CULL003", "function"): "unused_function",
("CULL004", "class"): "unused_class",
("CULL005", None): "unused_import",
("CULL006", None): "unused_local",
("CULL007", None): "unreachable_statement",
("CULL008", "function"): "unused_private_method",
}
VULTURE_RE = re.compile(
r"^(?P<path>.*?):(?P<line>\d+): unused "
r"(?P<kind>function|class|method|import|variable|attribute|property) "
r"'(?P<name>[^']+)'"
)
VULTURE_UNREACHABLE_RE = re.compile(r"^(?P<path>.*?):(?P<line>\d+): unreachable code")
DEADCODE_RE = re.compile(
r"^(?P<path>.*?):(?P<line>\d+):(?P<column>\d+): "
r"(?P<code>DC\d+) (?P<kind>Function|Class|Method|Variable|Import|Name|Attribute|Property) "
r"`(?P<name>[^`]+)` is never used"
)
DEADCODE_UNREACHABLE_RE = re.compile(
r"^(?P<path>.*?):(?P<line>\d+):(?P<column>\d+): (?P<code>DC\d+) .*unreachable"
)
ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
NORMAL_EXIT_CODES = {
"culler": {0, 1},
"vulture": {0, 3},
"deadcode": {0},
}
@dataclass(frozen=True)
class ExpectedFinding:
id: str
category: str
path: str
name: str | None
line: int
column: int | None
end_line: int
rationale: str
qualified_name: str | None = None
end_column: int | None = None
culler_rule: str | None = None
tool_notes: str | None = None
@dataclass(frozen=True)
class ToolFinding:
tool: str
category: str
path: str
line: int
name: str | None
raw: str
rule_id: str | None = None
confidence: str | None = None
@dataclass
class CommandRun:
command: list[str]
exit_code: int
stdout: str
stderr: str
seconds: float
max_rss_bytes: int | None
timed_out: bool = False
@dataclass(frozen=True)
class ParsedToolOutput:
findings: list[ToolFinding]
parse_warnings: list[str]
review_findings: list[ToolFinding] | None = None
@dataclass
class Project:
id: str
path: Path
expected_path: Path
mode: str
source_roots: list[str]
shape: str
clean: bool = False
large: bool = False
@dataclass
class ProjectResult:
project: Project
expected: list[ExpectedFinding]
tool_results: dict[str, dict[str, Any]] = field(default_factory=dict)
culler_high_plus_review: dict[str, Any] | None = None
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--suite", default="suite.json")
parser.add_argument("--culler", default="target/release/culler")
parser.add_argument("--tools", default="culler,vulture,deadcode")
parser.add_argument("--runs", type=int, default=5)
parser.add_argument("--warmups", type=int, default=1)
parser.add_argument("--timeout", type=float, default=60.0)
parser.add_argument("--results", default="benchmark/results/latest.json")
parser.add_argument("--validate-only", action="store_true")
parser.add_argument("--project", action="append", dest="projects")
args = parser.parse_args()
benchmark_root = Path(__file__).resolve().parent
repo_root = benchmark_root.parent
suite = load_json(benchmark_root / args.suite)
validate_suite_schema(suite)
all_projects = load_projects(benchmark_root, suite)
expected_by_project = {
project.id: load_expected(project.expected_path) for project in all_projects
}
corpus = validate_corpus(all_projects, expected_by_project)
projects = all_projects
if args.projects:
selected = set(args.projects)
projects = [project for project in projects if project.id in selected]
missing = selected - {project.id for project in projects}
if missing:
raise SystemExit(f"unknown project selection: {', '.join(sorted(missing))}")
if args.validate_only:
print(
"benchmark corpus is valid: "
f"{corpus['project_count']} projects, "
f"{corpus['python_files']} Python files, "
f"{corpus['python_loc']} Python LOC, "
f"{corpus['expected_findings']} expected findings"
)
return 0
tools = parse_tools(args.tools)
validate_runtime_args(args, tools, repo_root)
result_path = resolve_result_path(repo_root, benchmark_root, args.results)
result = run_benchmark(
benchmark_root=benchmark_root,
repo_root=repo_root,
suite=suite,
projects=projects,
expected_by_project=expected_by_project,
corpus=corpus,
tools=tools,
culler=(repo_root / args.culler).resolve(),
raw_root=result_path.parent / "raw" / result_path.stem,
runs=args.runs,
warmups=args.warmups,
timeout=args.timeout,
)
result = normalize_paths(result, repo_root)
result_path.parent.mkdir(parents=True, exist_ok=True)
write_json(result_path, result)
write_markdown(result_path.with_suffix(".md"), result)
print(f"wrote {result_path}")
print(
"aggregate: "
+ ", ".join(
f"{tool} precision={metrics['precision']:.3f} "
f"recall={metrics['recall']:.3f} f1={metrics['f1']:.3f}"
for tool, metrics in result["aggregate"].items()
)
)
return 0
def parse_tools(value: str) -> list[str]:
tools = [tool.strip() for tool in value.split(",") if tool.strip()]
allowed = {"culler", "vulture", "deadcode"}
unknown = set(tools) - allowed
if unknown:
raise SystemExit(f"unknown benchmark tools: {', '.join(sorted(unknown))}")
if not tools:
raise SystemExit("at least one tool must be selected")
return tools
def validate_suite_schema(suite: dict[str, Any]) -> None:
if not isinstance(suite, dict):
raise SystemExit("benchmark suite must be a JSON object")
if suite.get("schema_version") != 1:
raise SystemExit("benchmark suite schema_version must be 1")
if not isinstance(suite.get("projects"), list):
raise SystemExit("benchmark suite projects must be a list")
def validate_runtime_args(args: argparse.Namespace, tools: list[str], repo_root: Path) -> None:
if args.runs <= 0:
raise SystemExit("--runs must be positive")
if args.warmups < 0:
raise SystemExit("--warmups must be non-negative")
if args.timeout <= 0:
raise SystemExit("--timeout must be positive")
if "culler" in tools and not (repo_root / args.culler).exists():
raise SystemExit(f"Culler binary not found: {repo_root / args.culler}")
if any(tool in tools for tool in ("vulture", "deadcode")) and shutil.which("uvx") is None:
raise SystemExit("uvx is required to run Vulture/deadcode baselines")
def resolve_result_path(repo_root: Path, benchmark_root: Path, value: str) -> Path:
path = Path(value)
if path.is_absolute():
return path
if path.parts and path.parts[0] == "benchmark":
return repo_root / path
return benchmark_root / path
def load_projects(benchmark_root: Path, suite: dict[str, Any]) -> list[Project]:
projects = []
for index, entry in enumerate(suite.get("projects", [])):
if not isinstance(entry, dict):
raise SystemExit(f"suite.projects[{index}] must be an object")
project_id = require_string(entry, "id", f"suite.projects[{index}]")
projects.append(
Project(
id=project_id,
path=benchmark_root / require_string(entry, "path", project_id),
expected_path=benchmark_root / require_string(entry, "expected", project_id),
mode=require_string(entry, "mode", project_id),
source_roots=require_string_list(
entry.get("source_roots", ["src"]),
"source_roots",
project_id,
),
shape=require_string(entry, "shape", project_id),
clean=optional_bool(entry.get("clean", False), "clean", project_id),
large=optional_bool(entry.get("large", False), "large", project_id),
)
)
return projects
def load_expected(path: Path) -> list[ExpectedFinding]:
data = load_json(path)
if not isinstance(data, dict):
raise SystemExit(f"{path}: expected file must be a JSON object")
items = data.get("expected")
if not isinstance(items, list):
raise SystemExit(f"{path}: expected must be a list")
expected = []
for index, item in enumerate(items):
context = f"{path}:{index}"
if not isinstance(item, dict):
raise SystemExit(f"{context}: expected item must be an object")
category = require_string(item, "category", context)
if category not in CATEGORIES:
raise SystemExit(f"{context}: invalid category {category!r}")
line = require_int(item, "line", context)
end_line = int(item.get("end_line", line))
if end_line < line:
raise SystemExit(f"{context}: end_line must be >= line")
column = optional_int(item.get("column"), "column", context)
expected.append(
ExpectedFinding(
id=require_string(item, "id", context),
category=category,
path=normalize_relative_path(require_string(item, "path", context)),
name=optional_string(item.get("name"), "name", context),
line=line,
column=column,
end_line=end_line,
rationale=require_string(item, "rationale", context),
qualified_name=optional_string(
item.get("qualified_name"), "qualified_name", context
),
end_column=optional_int(item.get("end_column"), "end_column", context),
culler_rule=optional_string(item.get("culler_rule"), "culler_rule", context),
tool_notes=optional_string(item.get("tool_notes"), "tool_notes", context),
)
)
return expected
def validate_corpus(
projects: list[Project],
expected_by_project: dict[str, list[ExpectedFinding]],
*,
enforce_size: bool = True,
) -> dict[str, Any]:
if enforce_size and len(projects) != 15:
raise SystemExit(f"benchmark must contain 15 projects, found {len(projects)}")
project_ids = [project.id for project in projects]
duplicate_projects = duplicates(project_ids)
if duplicate_projects:
raise SystemExit(f"duplicate project ids: {', '.join(duplicate_projects)}")
all_expected_ids: list[str] = []
expected_count = 0
category_counts = {category: 0 for category in sorted(CATEGORIES)}
python_files = 0
python_loc = 0
clean_projects = 0
large_projects = 0
answer_token_hits: list[str] = []
for project in projects:
if not project.path.exists():
raise SystemExit(f"{project.id}: project path does not exist: {project.path}")
if not project.expected_path.exists():
raise SystemExit(
f"{project.id}: expected file does not exist: {project.expected_path}"
)
validate_expected_metadata(project)
if project.mode not in {"auto", "application", "library"}:
raise SystemExit(f"{project.id}: invalid mode {project.mode!r}")
for source_root in project.source_roots:
if not (project.path / source_root).exists():
raise SystemExit(f"{project.id}: missing source root {source_root!r}")
files = sorted(project.path.rglob("*.py"))
if not files:
raise SystemExit(f"{project.id}: no Python files")
project_loc = 0
for file_path in files:
text = file_path.read_text(encoding="utf-8")
project_loc += count_loc(text)
if contains_answer_leak(text):
answer_token_hits.append(os.fspath(file_path))
python_files += len(files)
python_loc += project_loc
expected = expected_by_project[project.id]
if project.clean and expected:
raise SystemExit(f"{project.id}: clean project has expected findings")
if project.clean:
clean_projects += 1
if project.large:
large_projects += 1
expected_count += len(expected)
all_expected_ids.extend(finding.id for finding in expected)
for finding in expected:
category_counts[finding.category] += 1
target = project.path / finding.path
if not target.exists():
raise SystemExit(f"{project.id}: expected path missing: {finding.path}")
if not finding.rationale.strip():
raise SystemExit(f"{project.id}: empty rationale for {finding.id}")
duplicate_ids = duplicates(all_expected_ids)
if duplicate_ids:
raise SystemExit(f"duplicate expected ids: {', '.join(duplicate_ids[:10])}")
if answer_token_hits:
raise SystemExit(
"benchmark source files contain answer-leaking comments/tokens: "
+ ", ".join(answer_token_hits[:10])
)
if enforce_size and not (45_000 <= python_loc <= 80_000):
raise SystemExit(f"total Python LOC must be 45k-80k, found {python_loc}")
if enforce_size and not (250 <= python_files <= 500):
raise SystemExit(f"Python file count must be 250-500, found {python_files}")
if enforce_size and not (500 <= expected_count <= 900):
raise SystemExit(
f"expected finding count must be 500-900, found {expected_count}"
)
if enforce_size and clean_projects != 2:
raise SystemExit(f"benchmark must contain 2 clean projects, found {clean_projects}")
if enforce_size and large_projects < 2:
raise SystemExit(
f"benchmark must contain at least 2 large/noisy projects, found {large_projects}"
)
missing_categories = [category for category, count in category_counts.items() if count == 0]
if enforce_size and missing_categories:
raise SystemExit(f"missing expected categories: {', '.join(missing_categories)}")
return {
"project_count": len(projects),
"python_files": python_files,
"python_loc": python_loc,
"expected_findings": expected_count,
"clean_projects": clean_projects,
"large_projects": large_projects,
"category_counts": category_counts,
}
def validate_expected_metadata(project: Project) -> None:
data = load_json(project.expected_path)
if not isinstance(data, dict):
raise SystemExit(f"{project.id}: expected file must be a JSON object")
expected_project = require_string(data, "project", os.fspath(project.expected_path))
if expected_project != project.id:
raise SystemExit(
f"{project.id}: expected project metadata is {expected_project!r}"
)
benchmark_root = project.expected_path.parent.parent
try:
expected_root = normalize_relative_path(
os.fspath(project.path.relative_to(benchmark_root))
)
except ValueError:
raise SystemExit(
f"{project.id}: project path must be under benchmark root"
) from None
actual_root = normalize_relative_path(
require_string(data, "root", os.fspath(project.expected_path))
)
if actual_root != expected_root:
raise SystemExit(
f"{project.id}: expected root metadata is {actual_root!r}, "
f"expected {expected_root!r}"
)
def contains_answer_leak(text: str) -> bool:
for line in text.splitlines():
stripped = line.strip().lower()
if not stripped.startswith("#"):
continue
if any(token in stripped for token in ("dead", "unused", "expected", "benchmark")):
return True
return False
def run_benchmark(
*,
benchmark_root: Path,
repo_root: Path,
suite: dict[str, Any],
projects: list[Project],
expected_by_project: dict[str, list[ExpectedFinding]],
corpus: dict[str, Any],
tools: list[str],
culler: Path,
raw_root: Path,
runs: int,
warmups: int,
timeout: float,
) -> dict[str, Any]:
prepare_raw_root(raw_root)
tool_metadata = collect_tool_metadata(repo_root, culler, tools)
project_results = []
for project in projects:
expected = expected_by_project[project.id]
result = ProjectResult(project=project, expected=expected)
for tool in tools:
run_result = run_tool_project(
tool=tool,
project=project,
culler=culler,
runs=runs,
warmups=warmups,
timeout=timeout,
)
raw_paths = write_raw_outputs(
raw_root,
tool,
project.id,
run_result["measured_runs"],
)
parsed = parse_stable_tool_output(
tool=tool,
project=project,
runs=run_result["measured_runs"],
)
metrics = score_findings(expected, parsed.findings)
result.tool_results[tool] = {
"command": run_result["command"],
"version": tool_metadata[tool]["version"],
"runs": [serialize_run(run) for run in run_result["measured_runs"]],
"median_seconds": median([run.seconds for run in run_result["measured_runs"]]),
"max_rss_bytes": max_rss(run_result["measured_runs"]),
"raw_output": os.fspath(raw_paths[-1]),
"raw_outputs": [os.fspath(path) for path in raw_paths],
"finding_count": len(parsed.findings),
"parse_warnings": parsed.parse_warnings,
"metrics": metrics,
}
if tool == "culler":
review_findings = parsed.review_findings or []
result.culler_high_plus_review = {
"finding_count": len(review_findings),
"metrics": score_findings(expected, review_findings),
}
project_results.append(result)
result = {
"schema_version": 1,
"suite": suite.get("description", "Culler benchmark"),
"corpus": corpus,
"environment": environment(repo_root, runs, warmups, timeout),
"tools": tool_metadata,
"aggregate": aggregate(project_results, tools),
"by_category": aggregate_by_category(project_results, tools),
"timing": timing_summary(project_results, tools),
"projects": [serialize_project_result(result, tools) for result in project_results],
}
if "culler" in tools:
result["culler_high_plus_review"] = aggregate_culler_review(project_results)
return result
def prepare_raw_root(raw_root: Path) -> None:
if raw_root.exists():
shutil.rmtree(raw_root)
raw_root.mkdir(parents=True)
def run_tool_project(
*,
tool: str,
project: Project,
culler: Path,
runs: int,
warmups: int,
timeout: float,
) -> dict[str, Any]:
command = command_for_tool(tool, project, culler)
for _ in range(warmups):
validate_command_run(tool, project, run_command(command, timeout))
measured = []
for _ in range(runs):
run = run_command(command, timeout)
validate_command_run(tool, project, run)
measured.append(run)
return {"command": command, "measured_runs": measured}
def parse_stable_tool_output(
*,
tool: str,
project: Project,
runs: list[CommandRun],
) -> ParsedToolOutput:
parsed_runs = []
for run in runs:
findings = parse_tool_findings(
tool,
run.stdout,
project.path,
include_culler_review=False,
)
review_findings = None
if tool == "culler":
review_findings = parse_tool_findings(
tool,
run.stdout,
project.path,
include_culler_review=True,
)
parsed_runs.append(
ParsedToolOutput(
findings=findings,
parse_warnings=collect_parse_warnings(tool, run.stdout),
review_findings=review_findings,
)
)
baseline = parsed_runs[0]
baseline_key = canonical_parsed_output(baseline)
for index, parsed in enumerate(parsed_runs[1:], start=2):
if canonical_parsed_output(parsed) != baseline_key:
raise SystemExit(
f"{tool} output changed across measured runs on {project.id}; "
f"run 1 and run {index} produced different parsed findings"
)
return baseline
def canonical_parsed_output(parsed: ParsedToolOutput) -> tuple[
list[tuple[str, str, int, str, str, str]],
tuple[str, ...],
list[tuple[str, str, int, str, str, str]],
]:
return (
canonical_findings(parsed.findings),
tuple(sorted(parsed.parse_warnings)),
canonical_findings(parsed.review_findings or []),
)
def canonical_findings(
findings: list[ToolFinding],
) -> list[tuple[str, str, int, str, str, str]]:
return sorted(
(
finding.category,
finding.path,
finding.line,
finding.name or "",
finding.rule_id or "",
finding.confidence or "",
)
for finding in findings
)
def command_for_tool(tool: str, project: Project, culler: Path) -> list[str]:
source_roots = [os.fspath(project.path / source) for source in project.source_roots]
if tool == "culler":
command = [
os.fspath(culler),
"check",
os.fspath(project.path),
"--format",
"json",
"--mode",
project.mode,
]
for source in project.source_roots:
command.extend(["--src", source])
return command
if tool == "vulture":
return ["uvx", "vulture==2.16", *source_roots]
if tool == "deadcode":
return ["uvx", "--python", "3.11", "deadcode==2.4.1", *source_roots]
raise ValueError(tool)
def validate_command_run(tool: str, project: Project, run: CommandRun) -> None:
if run.timed_out:
raise SystemExit(f"{tool} timed out on {project.id}")
accepted = NORMAL_EXIT_CODES.get(tool)
if accepted is None:
raise ValueError(tool)
if run.exit_code not in accepted:
raise SystemExit(
f"{tool} failed on {project.id} with exit code {run.exit_code}: "
f"{stderr_summary(run.stderr)}"
)
if run.stderr.strip():
raise SystemExit(f"{tool} wrote stderr on {project.id}: {stderr_summary(run.stderr)}")
def stderr_summary(stderr: str) -> str:
text = " ".join(line.strip() for line in stderr.splitlines() if line.strip())
if not text:
return "no stderr"
if len(text) > 300:
return f"{text[:297]}..."
return text
def run_command(command: list[str], timeout: float) -> CommandRun:
timed_command = time_command(command)
start = time.perf_counter()
try:
completed = subprocess.run(
timed_command,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
timeout=timeout,
)
seconds = time.perf_counter() - start
stderr, max_rss = split_time_stderr(completed.stderr)
return CommandRun(
command=command,
exit_code=completed.returncode,
stdout=completed.stdout,
stderr=stderr,
seconds=seconds,
max_rss_bytes=max_rss,
)
except subprocess.TimeoutExpired as error:
return CommandRun(
command=command,
exit_code=124,
stdout=error.stdout or "",
stderr=error.stderr or "",
seconds=time.perf_counter() - start,
max_rss_bytes=None,
timed_out=True,
)
def time_command(command: list[str]) -> list[str]:
if sys.platform == "darwin" and Path("/usr/bin/time").exists():
return ["/usr/bin/time", "-l", *command]
return command
def split_time_stderr(stderr: str) -> tuple[str, int | None]:
max_rss = None
tool_lines = []
for line in stderr.splitlines():
stripped = line.strip()
if stripped.endswith("maximum resident set size"):
try:
max_rss = int(stripped.split()[0])
except (IndexError, ValueError):
max_rss = None
continue
if stripped.startswith("Command being timed:"):
continue
if re.match(r"^\d+\.\d+ real\s+\d+\.\d+ user\s+\d+\.\d+ sys$", stripped):
continue
if any(
stripped.endswith(suffix)
for suffix in (
"average shared memory size",
"average unshared data size",
"average unshared stack size",
"page reclaims",
"page faults",
"swaps",
"block input operations",
"block output operations",
"messages sent",
"messages received",
"signals received",
"voluntary context switches",
"involuntary context switches",
"instructions retired",
"cycles elapsed",
"peak memory footprint",
)
):
continue
tool_lines.append(line)
return "\n".join(tool_lines), max_rss
def parse_tool_findings(
tool: str,
stdout: str,
project_root: Path,
*,
include_culler_review: bool,
) -> list[ToolFinding]:
if tool == "culler":
return parse_culler(stdout, include_review=include_culler_review)
if tool == "vulture":
return parse_vulture(stdout, project_root)
if tool == "deadcode":
return parse_deadcode(stdout, project_root)
raise ValueError(tool)
def parse_culler(stdout: str, *, include_review: bool = False) -> list[ToolFinding]:
if not stdout.strip():
return []
try:
data = json.loads(stdout)
except json.JSONDecodeError as error:
raise SystemExit(f"Culler JSON could not be parsed: {error}") from None
findings = []
for item in data.get("findings", []):
confidence = item.get("confidence")
if confidence != "high" and not (include_review and confidence == "review"):
continue
subject = item.get("subject", {})
rule_id = item.get("rule_id")
category = culler_category(rule_id, subject)
if category is None:
continue
path, line, name = subject_location(subject, category)
findings.append(
ToolFinding(
tool="culler",
category=category,
path=path,
line=line,
name=name,
raw=item.get("finding_id", ""),
rule_id=rule_id,
confidence=confidence,
)
)
return findings
def culler_category(rule_id: str | None, subject: dict[str, Any]) -> str | None:
subject_kind = None
if subject.get("subject_type") == "definition":
subject_kind = subject.get("kind")
return CULL_TYPE_TO_CATEGORY.get((rule_id, subject_kind)) or CULL_TYPE_TO_CATEGORY.get(
(rule_id, None)
)
def subject_location(subject: dict[str, Any], category: str) -> tuple[str, int, str | None]:
subject_type = subject.get("subject_type")
if subject_type == "import_binding":
return (
normalize_relative_path(subject["file"]),
int(subject["line"]),
subject.get("bound_name"),
)
if subject_type == "binding":
return (
normalize_relative_path(subject["file"]),
int(subject["line"]),
subject.get("name"),
)
if subject_type == "statement_range":
return (
normalize_relative_path(subject["file"]),
int(subject["start_line"]),
None,
)
return (
normalize_relative_path(subject["file"]),
int(subject["line"]),
subject.get("name"),
)
def parse_vulture(stdout: str, project_root: Path) -> list[ToolFinding]:
findings = []
for line in stdout.splitlines():
stripped = line.strip()
match = VULTURE_RE.match(stripped)
if match:
category = vulture_category(match.group("kind"), match.group("name"))
if category is None:
continue
findings.append(
ToolFinding(
tool="vulture",
category=category,
path=relative_path(match.group("path"), project_root),
line=int(match.group("line")),
name=match.group("name"),
raw=stripped,
)
)
continue
match = VULTURE_UNREACHABLE_RE.match(stripped)
if match:
findings.append(
ToolFinding(
tool="vulture",
category="unreachable_statement",
path=relative_path(match.group("path"), project_root),
line=int(match.group("line")),
name=None,
raw=stripped,
)
)
return findings
def parse_deadcode(stdout: str, project_root: Path) -> list[ToolFinding]:
findings = []
for raw_line in stdout.splitlines():
stripped = ANSI_RE.sub("", raw_line.strip())
match = DEADCODE_RE.match(stripped)
if match:
category = deadcode_category(match.group("kind"), match.group("name"))
if category is None:
continue
findings.append(
ToolFinding(
tool="deadcode",
category=category,
path=relative_path(match.group("path"), project_root),
line=int(match.group("line")),
name=match.group("name"),
raw=stripped,
rule_id=match.group("code"),
)
)
continue
match = DEADCODE_UNREACHABLE_RE.match(stripped)
if match:
findings.append(
ToolFinding(
tool="deadcode",
category="unreachable_statement",
path=relative_path(match.group("path"), project_root),
line=int(match.group("line")),
name=None,
raw=stripped,
rule_id=match.group("code"),
)
)
return findings
def collect_parse_warnings(tool: str, stdout: str) -> list[str]:
if tool == "culler":
return []
if tool == "vulture":
return unparsed_vulture_lines(stdout)
if tool == "deadcode":
return unparsed_deadcode_lines(stdout)
return [f"unknown tool parser: {tool}"]
def unparsed_vulture_lines(stdout: str) -> list[str]:
warnings = []
for line in stdout.splitlines():
stripped = line.strip()
if not stripped:
continue
match = VULTURE_RE.match(stripped)
if match:
category = vulture_category(match.group("kind"), match.group("name"))
if category is None:
warnings.append(f"unsupported Vulture category: {stripped}")
continue
if VULTURE_UNREACHABLE_RE.match(stripped):
continue
warnings.append(stripped)
return warnings
def unparsed_deadcode_lines(stdout: str) -> list[str]:
warnings = []
for raw_line in stdout.splitlines():
stripped = ANSI_RE.sub("", raw_line.strip())
if not stripped:
continue
if stripped.startswith("Well done!"):
continue
match = DEADCODE_RE.match(stripped)
if match:
category = deadcode_category(match.group("kind"), match.group("name"))
if category is None:
warnings.append(f"unsupported deadcode category: {stripped}")
continue
if DEADCODE_UNREACHABLE_RE.match(stripped):
continue
warnings.append(stripped)
return warnings
def vulture_category(kind: str, name: str) -> str | None:
if kind == "import":
return "unused_import"
if kind == "variable":
return "unused_local"
if kind == "function":
return "unused_function"
if kind == "class":
return "unused_class"
if kind == "method":
return "unused_private_method" if is_private_method_name(name) else "unused_function"
return None
def deadcode_category(kind: str, name: str) -> str | None:
if kind == "Import":
return "unused_import"
if kind in {"Variable", "Name"}:
return "unused_local"
if kind == "Function":
return "unused_function"
if kind == "Class":
return "unused_class"
if kind == "Method":
return "unused_private_method" if is_private_method_name(name) else "unused_function"
return None
def is_private_method_name(name: str) -> bool:
return name.startswith("_") and not (name.startswith("__") and name.endswith("__"))
def score_findings(
expected: list[ExpectedFinding],
findings: list[ToolFinding],
) -> dict[str, Any]:
matched_expected: set[str] = set()
true_positive: list[dict[str, Any]] = []
false_positive: list[dict[str, Any]] = []