Repository navigation
Expand file tree
/
Copy pathtest_dead_code_eval.py
More file actions
717 lines (647 loc) · 25.8 KB
/
Copy pathtest_dead_code_eval.py
File metadata and controls
717 lines (647 loc) · 25.8 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
from pathlib import Path
from codebase_rag import constants as cs
from evals.dead_code import (
DeadCodeConfig,
cgr_dead_code,
dead_code_from_graph,
default_dead_code_config,
score_dead_code,
)
_MODULE = cs.NodeLabel.MODULE.value
_FUNCTION = cs.NodeLabel.FUNCTION.value
_CLASS = cs.NodeLabel.CLASS.value
_CALLS = cs.RelationshipType.CALLS.value
_DEFINES = cs.RelationshipType.DEFINES.value
_DEFINES_METHOD = cs.RelationshipType.DEFINES_METHOD.value
_INHERITS = cs.RelationshipType.INHERITS.value
_PREFIX = "proj."
_CONFIG = DeadCodeConfig(
include_tests=False,
include_classes=False,
root_decorators=frozenset(),
entry_points=(),
test_patterns=cs.TEST_PATH_PATTERNS,
)
def _fn(uid: str, path: str = "m.py", decorators: list[str] | None = None) -> tuple:
return (
(_FUNCTION, uid),
{
cs.KEY_QUALIFIED_NAME: uid,
cs.KEY_PATH: path,
cs.KEY_DECORATORS: decorators or [],
cs.KEY_IS_EXPORTED: False,
},
)
def _method(uid: str, path: str) -> tuple:
return (
(cs.NodeLabel.METHOD.value, uid),
{
cs.KEY_QUALIFIED_NAME: uid,
cs.KEY_PATH: path,
cs.KEY_DECORATORS: [],
cs.KEY_IS_EXPORTED: False,
},
)
def test_dead_code_flags_uncalled_function() -> None:
# (H) Module calls main(); main() calls helper(); orphan() is never called.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.main"),
_fn("proj.m.helper"),
_fn("proj.m.orphan"),
]
)
rels = [
(_MODULE, "proj.m", _CALLS, _FUNCTION, "proj.m.main"),
(_FUNCTION, "proj.m.main", _CALLS, _FUNCTION, "proj.m.helper"),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == {"proj.m.orphan"}
def test_go_init_and_main_are_roots() -> None:
# (H) Go `func init()` is auto-run by the runtime at package load and `func
# (H) main()` is the program entry; neither is ever called explicitly, so both
# (H) are reachability roots (like Python dunders). A same-file helper with no
# (H) caller is still dead -- the exemption is name-scoped to init/main.
nodes = dict(
[
(
(_MODULE, "proj.mode"),
{cs.KEY_QUALIFIED_NAME: "proj.mode", cs.KEY_PATH: "mode.go"},
),
_fn("proj.mode.init", path="mode.go"),
_fn("proj.main.main", path="main.go"),
_fn("proj.util.helper", path="util.go"),
_method("proj.mode.Type.init", path="mode.go"),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, _CONFIG)
assert "proj.mode.init" not in dead
assert "proj.main.main" not in dead
assert "proj.util.helper" in dead
# (H) A receiver method named init/main is NOT the package init/entry, so the
# (H) exemption is Function-scoped and this stays dead.
assert "proj.mode.Type.init" in dead
def test_rust_trait_methods_and_main_are_roots() -> None:
# (H) Rust trait-impl methods (Display::fmt, PartialEq::eq, Iterator::next) are
# (H) dispatched by the language (format!, ==, for), never called explicitly, and
# (H) `fn main()` is the program entry -- all reachability roots (like Python
# (H) dunders), gated by the .rs extension. A custom method (push_int) is not a
# (H) trait name, so it stays dead.
nodes = dict(
[
(
(_MODULE, "proj.frame"),
{cs.KEY_QUALIFIED_NAME: "proj.frame", cs.KEY_PATH: "frame.rs"},
),
_method("proj.frame.Frame.fmt", "frame.rs"),
_method("proj.frame.Frame.eq", "frame.rs"),
_method("proj.iter.It.next", "iter.rs"),
_method("proj.frame.Frame.push_int", "frame.rs"),
_fn("proj.main.main", path="main.rs"),
_method("proj.frame.Frame.main", "frame.rs"),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, _CONFIG)
assert "proj.frame.Frame.fmt" not in dead
assert "proj.frame.Frame.eq" not in dead
assert "proj.iter.It.next" not in dead
assert "proj.main.main" not in dead
assert "proj.frame.Frame.push_int" in dead
# (H) A method named main is not the binary entry, so it stays dead (main is
# (H) Function-scoped; trait-method rooting is the reverse, Method-scoped).
assert "proj.frame.Frame.main" in dead
def test_root_level_tests_dir_is_excluded() -> None:
# (H) A top-level `tests/` dir (Rust integration tests `tests/client.rs`, a JS
# (H) `tests/` folder) is test infrastructure. The `/tests/` pattern needs a
# (H) leading slash, so a root tests/ dir was missed and every test fn leaked as
# (H) a candidate. Path matching must normalize a leading slash so root tests/ is
# (H) recognized; a `contests/` dir must NOT be mistaken for a tests dir.
nodes = dict(
[
(
(_MODULE, "proj.tests.client"),
{
cs.KEY_QUALIFIED_NAME: "proj.tests.client",
cs.KEY_PATH: "tests/client.rs",
},
),
_fn("proj.tests.client.smoke", path="tests/client.rs"),
_fn("proj.contests.entry", path="contests/entry.rs"),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, _CONFIG)
assert "proj.tests.client.smoke" not in dead
# (H) `contests/` is not a tests dir, so a genuinely-uncalled symbol there is
# (H) still reported (no false leading-slash match).
assert "proj.contests.entry" in dead
def test_dead_code_excludes_generated_paths() -> None:
# (H) A generated file (openapi-ts client/core, routeTree.gen.ts) has no
# (H) in-repo caller, so every symbol in it reports as dead -- pure noise the
# (H) user cannot act on. An exclude glob suppresses those from the report while
# (H) a real orphan elsewhere is still flagged. Crucially, the excluded file
# (H) stays a live participant: `used_by_gen` is called only from the generated
# (H) module and must NOT be flagged dead (excluding before reachability would
# (H) drop that edge and wrongly report it).
nodes = dict(
[
(
(_MODULE, "proj.gen"),
{cs.KEY_QUALIFIED_NAME: "proj.gen", cs.KEY_PATH: "client/core/req.ts"},
),
_fn("proj.gen.helper", path="client/core/req.ts"),
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.ts"},
),
_fn("proj.m.orphan", path="m.ts"),
_fn("proj.m.used_by_gen", path="m.ts"),
]
)
rels = [
(_MODULE, "proj.gen", _CALLS, _FUNCTION, "proj.gen.helper"),
(_FUNCTION, "proj.gen.helper", _CALLS, _FUNCTION, "proj.m.used_by_gen"),
]
cfg = _CONFIG._replace(exclude_patterns=("*client/core*",))
dead = dead_code_from_graph(nodes, rels, _PREFIX, cfg)
assert dead == {"proj.m.orphan"}
def test_dead_code_flags_orphan_chain() -> None:
# (H) orphan() calls buried(), but orphan() itself is never reached, so both
# (H) are dead (a callee kept alive only by dead code is dead too).
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.main"),
_fn("proj.m.orphan"),
_fn("proj.m.buried"),
]
)
rels = [
(_MODULE, "proj.m", _CALLS, _FUNCTION, "proj.m.main"),
(_FUNCTION, "proj.m.orphan", _CALLS, _FUNCTION, "proj.m.buried"),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == {"proj.m.orphan", "proj.m.buried"}
def test_decorated_function_is_a_root() -> None:
# (H) A function with a recognised entry-point decorator (e.g. @app.route) is
# (H) live even if nothing calls it.
config = _CONFIG._replace(root_decorators=frozenset({"route"}))
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.handler", decorators=["@app.route('/x')"]),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, config)
assert dead == set()
def test_pydantic_validator_is_a_root() -> None:
# (H) Pydantic invokes @field_validator/@model_validator methods by registration
# (H) through library code that is not in the first-party graph, so reachability
# (H) cannot trace the call; the default decorator set must seed them as roots.
config = default_dead_code_config(include_tests=False, include_classes=False)
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn(
"proj.m.C._check",
decorators=["@pydantic.field_validator('x')"],
),
_fn("proj.m.C._verify", decorators=["@model_validator(mode='after')"]),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, config)
assert dead == set()
def test_test_file_symbols_are_not_candidates_when_tests_excluded() -> None:
# (H) A helper defined INSIDE a test file is test infrastructure, not
# (H) production dead code. With tests excluded its only callers (test
# (H) functions) can never root it, so reporting it is unconditional noise
# (H) (the MockHTTPRouter/mock-helper cluster); production code reached only
# (H) from tests must still be reported.
nodes = dict(
[
(
(_MODULE, "proj.tests.test_m"),
{
cs.KEY_QUALIFIED_NAME: "proj.tests.test_m",
cs.KEY_PATH: "tests/test_m.py",
},
),
_fn("proj.tests.test_m._helper", path="tests/test_m.py"),
_fn("proj.m.only_tested"),
]
)
rels = [
(_MODULE, "proj.tests.test_m", _CALLS, _FUNCTION, "proj.m.only_tested"),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == {"proj.m.only_tested"}
def test_pydantic_computed_field_is_a_root() -> None:
# (H) Pydantic calls @computed_field methods during serialization through
# (H) library code outside the first-party graph, so no CALLS edge reaches
# (H) them; the default decorator set must seed them as roots too.
config = default_dead_code_config(include_tests=False, include_classes=False)
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.C.full_name", decorators=["@computed_field", "@property"]),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, config)
assert dead == set()
def test_non_test_module_does_not_keep_code_alive_when_tests_excluded() -> None:
# (H) With tests excluded, a call from a test module must not root project code.
nodes = dict(
[
(
(_MODULE, "proj.tests.test_m"),
{
cs.KEY_QUALIFIED_NAME: "proj.tests.test_m",
cs.KEY_PATH: "tests/test_m.py",
},
),
_fn("proj.m.only_tested"),
]
)
rels = [(_MODULE, "proj.tests.test_m", _CALLS, _FUNCTION, "proj.m.only_tested")]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == {"proj.m.only_tested"}
def _make_repo(root: Path) -> None:
root.mkdir(parents=True)
(root / "__init__.py").write_text("", encoding="utf-8")
(root / "m.py").write_text(
"def helper():\n return 1\n\n\n"
"def main():\n return helper()\n\n\n"
"def orphan():\n return 2\n\n\n"
"def _orphan():\n return 3\n\n\n"
"main()\n",
encoding="utf-8",
)
def test_cgr_dead_code_matches_known_dead_set(tmp_path: Path) -> None:
src = tmp_path / "proj"
_make_repo(src)
dead = cgr_dead_code(src, "proj", default_dead_code_config(False, False))
# (H) A private, uncalled function is genuinely dead. A public one is part of
# (H) the module's API surface (a potential external entry point), so it is a
# (H) reachability root and must not be flagged.
assert "proj.m._orphan" in dead
assert "proj.m.orphan" not in dead
assert "proj.m.main" not in dead
assert "proj.m.helper" not in dead
def _method(uid: str, path: str = "m.py") -> tuple:
return (
(cs.NodeLabel.METHOD.value, uid),
{
cs.KEY_QUALIFIED_NAME: uid,
cs.KEY_NAME: uid.rsplit(cs.SEPARATOR_DOT, 1)[-1],
cs.KEY_PATH: path,
cs.KEY_DECORATORS: [],
cs.KEY_IS_EXPORTED: False,
},
)
def test_dunder_root_is_limited_to_methods() -> None:
# (H) Implicit dunder dispatch applies to special METHODS on objects, not to a
# (H) module-level function that merely has a dunder-shaped name, so an uncalled
# (H) function named __unused__ must stay a dead-code candidate.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
(
(_FUNCTION, "proj.m.__unused__"),
{
cs.KEY_QUALIFIED_NAME: "proj.m.__unused__",
cs.KEY_NAME: "__unused__",
cs.KEY_PATH: "m.py",
cs.KEY_DECORATORS: [],
cs.KEY_IS_EXPORTED: False,
},
),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, _CONFIG)
assert "proj.m.__unused__" in dead
def test_dunder_method_is_a_root() -> None:
# (H) __aenter__/__aexit__ are invoked by the `async with` protocol, never by an
# (H) explicit call, so cgr cannot see an inbound edge. They are runtime protocol
# (H) hooks and must be treated as reachable roots, while a plain private method
# (H) with no caller stays dead.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_method("proj.m.Inner.__aenter__"),
_method("proj.m.Inner.__aexit__"),
_method("proj.m.Inner._helper"),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, _CONFIG)
assert "proj.m.Inner.__aenter__" not in dead
assert "proj.m.Inner.__aexit__" not in dead
assert "proj.m.Inner._helper" in dead
def _make_async_cm_repo(root: Path) -> None:
root.mkdir(parents=True)
(root / "__init__.py").write_text("", encoding="utf-8")
(root / "m.py").write_text(
"class Counter:\n"
" def __call__(self):\n"
" class Inner:\n"
" async def __aenter__(self):\n"
" return None\n"
" async def __aexit__(self, *a):\n"
" return None\n"
" return Inner()\n\n\n"
"async def use():\n"
" c = Counter()\n"
" async with c():\n"
" pass\n\n\n"
"use()\n",
encoding="utf-8",
)
def test_cgr_dead_code_does_not_flag_context_manager_dunders(tmp_path: Path) -> None:
# (H) __aenter__/__aexit__ on the Inner class returned by Counter.__call__ are
# (H) driven by `async with` and can never show an inbound call edge; they must
# (H) not be reported dead (full parse -> graph -> reachability path).
src = tmp_path / "proj"
_make_async_cm_repo(src)
dead = cgr_dead_code(src, "proj", default_dead_code_config(False, False))
assert not any(qn.endswith("__aenter__") for qn in dead)
assert not any(qn.endswith("__aexit__") for qn in dead)
def test_dunder_root_is_scoped_to_python() -> None:
# (H) Dunder methods are a Python runtime protocol. A function named __unused__ in
# (H) another language (a .ts file) is not implicitly invoked, so it must stay a
# (H) dead-code candidate; only Python (.py) dunders are rooted.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.ts"},
),
(
(_FUNCTION, "proj.m.__unused__"),
{
cs.KEY_QUALIFIED_NAME: "proj.m.__unused__",
cs.KEY_NAME: "__unused__",
cs.KEY_PATH: "m.ts",
cs.KEY_DECORATORS: [],
cs.KEY_IS_EXPORTED: False,
},
),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, _CONFIG)
assert "proj.m.__unused__" in dead
def test_abstract_method_is_a_root() -> None:
# (H) An @abstractmethod is a contract invoked polymorphically through concrete
# (H) overrides, never by a direct call the graph can trace, so the abstract stub
# (H) must not be reported dead (SqsBatchJob._raw_batch_operation shape).
config = default_dead_code_config(include_tests=False, include_classes=False)
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.Base._raw", decorators=["@abstractmethod"]),
_fn("proj.m.Base._also", decorators=["@abc.abstractmethod"]),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, config)
assert dead == set()
def test_registration_decorated_nested_function_is_a_root() -> None:
# (H) A decorated function nested inside another function (prompt_toolkit
# (H) @bindings.add, MCP @server.list_tools) is handed to a framework when the
# (H) enclosing function runs, so it is live regardless of the decorator-name
# (H) whitelist; an undecorated uncalled sibling closure stays dead.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.outer"),
_fn("proj.m.outer._submit", decorators=["@bindings.add('c-j')"]),
_fn("proj.m.outer._unused"),
]
)
rels = [
(_MODULE, "proj.m", _CALLS, _FUNCTION, "proj.m.outer"),
(_FUNCTION, "proj.m.outer", _DEFINES, _FUNCTION, "proj.m.outer._submit"),
(_FUNCTION, "proj.m.outer", _DEFINES, _FUNCTION, "proj.m.outer._unused"),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == {"proj.m.outer._unused"}
def test_closure_of_dead_function_is_not_a_root() -> None:
# (H) The registration exemption is tied to a LIVE owner: when the enclosing
# (H) function is itself unreachable its decorated closure never registers, so
# (H) the closure and the helper only it calls are dead too, not hidden.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.main"),
_fn("proj.m.dead_outer"),
_fn("proj.m.dead_outer._ghost", decorators=["@bindings.add('c-x')"]),
_fn("proj.m.victim"),
]
)
rels = [
(_MODULE, "proj.m", _CALLS, _FUNCTION, "proj.m.main"),
(
_FUNCTION,
"proj.m.dead_outer",
_DEFINES,
_FUNCTION,
"proj.m.dead_outer._ghost",
),
(_FUNCTION, "proj.m.dead_outer._ghost", _CALLS, _FUNCTION, "proj.m.victim"),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == {
"proj.m.dead_outer",
"proj.m.dead_outer._ghost",
"proj.m.victim",
}
def test_closure_callee_of_live_function_stays_live() -> None:
# (H) The registered closure of a LIVE owner runs, so a helper reachable only
# (H) through the closure's calls is live as well.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m.outer"),
_fn("proj.m.outer._submit", decorators=["@bindings.add('c-j')"]),
_fn("proj.m._only_from_closure"),
]
)
rels = [
(_MODULE, "proj.m", _CALLS, _FUNCTION, "proj.m.outer"),
(_FUNCTION, "proj.m.outer", _DEFINES, _FUNCTION, "proj.m.outer._submit"),
(
_FUNCTION,
"proj.m.outer._submit",
_CALLS,
_FUNCTION,
"proj.m._only_from_closure",
),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == set()
def test_typer_callback_decorator_is_a_root() -> None:
# (H) typer invokes @app.callback() functions by registration, so the default
# (H) decorator whitelist must seed them as roots (codebase_rag.cli shape).
config = default_dead_code_config(include_tests=False, include_classes=False)
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m._global_options", decorators=["@app.callback()"]),
]
)
dead = dead_code_from_graph(nodes, [], _PREFIX, config)
assert dead == set()
def _class(uid: str, path: str = "m.py") -> tuple:
return (
(_CLASS, uid),
{cs.KEY_QUALIFIED_NAME: uid, cs.KEY_PATH: path},
)
def test_protocol_stub_method_is_a_root() -> None:
# (H) A method of a typing.Protocol subclass is an interface stub; callers are
# (H) traced to the implementations, never to the stub itself, so the stub must
# (H) not be reported dead while a plain class's uncalled private method is.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_class("proj.m.Loadable"),
_class("proj.m.Plain"),
_method("proj.m.Loadable._ensure_loaded"),
_method("proj.m.Plain._helper"),
]
)
rels = [
(_CLASS, "proj.m.Loadable", _INHERITS, _CLASS, "typing.Protocol"),
(
_CLASS,
"proj.m.Loadable",
_DEFINES_METHOD,
cs.NodeLabel.METHOD.value,
"proj.m.Loadable._ensure_loaded",
),
(
_CLASS,
"proj.m.Plain",
_DEFINES_METHOD,
cs.NodeLabel.METHOD.value,
"proj.m.Plain._helper",
),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert dead == {"proj.m.Plain._helper"}
def _make_registration_repo(root: Path) -> None:
root.mkdir(parents=True)
(root / "__init__.py").write_text("", encoding="utf-8")
(root / "m.py").write_text(
"from typing import Protocol\n\n\n"
"class Loadable(Protocol):\n"
" def _ensure_loaded(self) -> None: ...\n\n\n"
"def get_input(bindings):\n"
" @bindings.add('c-j')\n"
" def _submit(event):\n"
" return event\n"
" return bindings\n\n\n"
"get_input(None)\n",
encoding="utf-8",
)
def test_cgr_dead_code_keeps_registration_closures_and_protocol_stubs(
tmp_path: Path,
) -> None:
# (H) Full parse -> graph -> reachability: the @bindings.add closure and the
# (H) Protocol stub must not be flagged (the 2026-07-03 false-positive shapes).
src = tmp_path / "proj"
_make_registration_repo(src)
dead = cgr_dead_code(src, "proj", default_dead_code_config(False, False))
assert "proj.m.get_input._submit" not in dead
assert "proj.m.Loadable._ensure_loaded" not in dead
def test_score_dead_code_prf() -> None:
result = score_dead_code({"a", "b"}, {"a", "c"})
row = result.rows[0]
assert (row["tp"], row["fp"], row["fn"]) == (1, 1, 1)
def test_referenced_function_is_reachable() -> None:
# (H) A function reachable only through a REFERENCES edge (passed as a callback
# (H) into first-party plumbing that stores it) is live; a sibling with no
# (H) inbound edge stays dead.
nodes = dict(
[
(
(_MODULE, "proj.m"),
{cs.KEY_QUALIFIED_NAME: "proj.m", cs.KEY_PATH: "m.py"},
),
_fn("proj.m._main"),
_fn("proj.m._main.create_context"),
_fn("proj.m._orphan"),
]
)
rels = [
(_MODULE, "proj.m", _CALLS, _FUNCTION, "proj.m._main"),
(
_FUNCTION,
"proj.m._main",
cs.RelationshipType.REFERENCES.value,
_FUNCTION,
"proj.m._main.create_context",
),
]
dead = dead_code_from_graph(nodes, rels, _PREFIX, _CONFIG)
assert "proj.m._main.create_context" not in dead
assert "proj.m._orphan" in dead
def _make_callback_repo(root: Path) -> None:
root.mkdir(parents=True)
(root / "__init__.py").write_text("", encoding="utf-8")
(root / "brrrlib.py").write_text(
"def with_brrr_from_cfg(cfg, handlers, create_context=None):\n"
" cfg.ctx_factory = create_context\n"
" return cfg\n",
encoding="utf-8",
)
(root / "worker.py").write_text(
"from proj.brrrlib import with_brrr_from_cfg\n\n\n"
"def main(cfg, handlers, extra):\n"
" def create_context(active_worker, meta):\n"
" return (active_worker, extra)\n"
" return with_brrr_from_cfg(cfg, handlers, create_context=create_context)\n",
encoding="utf-8",
)
def test_cgr_dead_code_keeps_stored_callback_alive(tmp_path: Path) -> None:
# (H) Full pipeline: a nested callback passed by keyword into first-party
# (H) plumbing that stores it must not be reported dead (create_context shape).
src = tmp_path / "proj"
_make_callback_repo(src)
dead = cgr_dead_code(src, "proj", default_dead_code_config(False, False))
assert not any(qn.endswith("create_context") for qn in dead)