Repository navigation
Expand file tree
/
Copy pathstructural_delta.py
More file actions
1149 lines (989 loc) · 39.2 KB
/
Copy pathstructural_delta.py
File metadata and controls
1149 lines (989 loc) · 39.2 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
"""Structural delta after a write (issue #1525).
An edit lands in the graph through the scoped re-ingest (issue #1524); this
module reads the touched files' subgraph before and after that re-ingest and
reports what the edit did to the structure: symbols added, removed and
renamed, callers left pointing at nothing, signature changes with an arity
verdict per call site, new duplicates of existing functions, new import
cycles, and the tests that reach the changed symbols. It is the in-memory
twin of `services/graph_diff.py`, which diffs exported indexes offline.
Everything is fixed Cypher scoped to one project plus client-side set
arithmetic over the fetched rows, so the report is deterministic and cheap:
the graph reads are linear in the touched files' edges, plus one linear
project scan for the duplicate index; tests reaching a changed symbol are
found by walking its callers one hop at a time.
"""
from __future__ import annotations
import re
import time
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import NamedTuple, TypedDict
from . import constants as cs
from . import cypher_queries as cq
from .crash_correlation import ArityError, diagnose_arity
from .dead_code import (
_is_test_symbol,
_node_props,
_NodeId,
_rust_test_fn_spans,
_rust_test_modules_from_nodes,
)
from .duplicates import _jaccard
from .graph_query import QueryFn, _prefix
from .types_defs import PropertyDict, ReingestReport, ResultRow
_METHOD_LABELS = frozenset({cs.NodeLabel.METHOD.value})
class Definition(NamedTuple):
label: str
qualified_name: str
name: str
path: str
start_line: int
end_line: int
positional_params: tuple[str, ...] | None
fingerprint: str
fingerprint_nodes: int
branches: frozenset[str]
class CallSite(NamedTuple):
caller: str
caller_path: str
rel: str
callee: str
callee_path: str
line: int | None
col: int | None
arg_count: int | None
kwarg_names: tuple[str, ...]
class Snapshot(NamedTuple):
"""The touched files' subgraph plus the project's module import graph.
`definitions` are the symbols defined in the touched files; `callees`
the definitions elsewhere that the touched files' sites resolve to.
"""
paths: frozenset[str]
definitions: dict[str, Definition]
callees: dict[str, Definition]
sites: tuple[CallSite, ...]
imports: dict[str, frozenset[str]]
module_paths: dict[str, str]
class RenameFinding(TypedDict):
old: str
new: str
path: str
class DanglingCaller(TypedDict):
caller: str
path: str
line: int | None
col: int | None
target: str
renamed_to: str | None
class ArityAtSite(TypedDict):
caller: str
path: str
line: int | None
col: int | None
arg_count: int | None
kwarg_names: list[str]
declared_count: int
verdict: str
class SignatureChange(TypedDict):
qualified_name: str
path: str
before: list[str] | None
after: list[str] | None
sites: list[ArityAtSite]
class DuplicateOriginal(TypedDict):
qualified_name: str
path: str
start_line: int
class NewDuplicate(TypedDict):
qualified_name: str
path: str
start_line: int
kind: str
similarity: float
original: DuplicateOriginal
class TestReach(TypedDict):
qualified_name: str
path: str | None
depth: int
through: str
class SiteCounts(TypedDict):
"""CALLS sites into the touched files' definitions, before and after."""
before: int
after: int
class SymbolDelta(TypedDict):
added: list[str]
removed: list[str]
renamed: list[RenameFinding]
changed: list[str]
class StaleImporter(TypedDict):
"""A module still importing from where a moved symbol used to live."""
importer: str
path: str
line: int
class StructuralDelta(TypedDict):
paths: list[str]
reparsed: list[str]
affected: list[str]
removed_files: list[str]
symbols: SymbolDelta
dangling_callers: list[DanglingCaller]
signature_changes: list[SignatureChange]
arity_findings: list[ArityAtSite]
new_duplicates: list[NewDuplicate]
new_import_cycles: list[list[str]]
# Importers that still name a module a moved symbol has left. Empty for
# every operation that moves nothing, so a non-move never carries one.
stale_importers: list[StaleImporter]
tests_reaching: list[TestReach]
call_sites: SiteCounts
reingest_ms: float
delta_ms: float
# --- snapshot -----------------------------------------------------------------
def _text(value: object) -> str:
return str(value) if isinstance(value, str) else ""
def _int(value: object, default: int = 0) -> int:
return value if isinstance(value, int) and not isinstance(value, bool) else default
def _opt_int(value: object) -> int | None:
return value if isinstance(value, int) and not isinstance(value, bool) else None
def _strings(value: object) -> tuple[str, ...]:
if isinstance(value, list):
return tuple(str(item) for item in value)
return ()
def normalise_paths(paths: Iterable[Path | str], repo_root: Path | None) -> list[str]:
"""Repo-relative POSIX paths, the form the graph stores in `path`."""
out: set[str] = set()
for raw in paths:
path = Path(raw)
if repo_root is not None and path.is_absolute():
try:
path = path.resolve().relative_to(repo_root.resolve())
except ValueError:
continue
out.add(path.as_posix())
return sorted(out)
def _definition(row: ResultRow) -> Definition:
params = row.get(cs.KEY_POSITIONAL_PARAMS)
return Definition(
label=_text(row.get(cs.KEY_LABEL)),
qualified_name=_text(row.get(cs.KEY_QUALIFIED_NAME)),
name=_text(row.get(cs.KEY_NAME)),
path=_text(row.get(cs.KEY_PATH)),
start_line=_int(row.get(cs.KEY_START_LINE)),
end_line=_int(row.get(cs.KEY_END_LINE)),
positional_params=_strings(params) if isinstance(params, list) else None,
fingerprint=_text(row.get(cs.KEY_AST_FINGERPRINT)),
fingerprint_nodes=_int(row.get(cs.KEY_AST_FINGERPRINT_NODES)),
branches=frozenset(_strings(row.get(cs.KEY_AST_BRANCH_FINGERPRINTS))),
)
def _site(row: ResultRow) -> CallSite:
return CallSite(
caller=_text(row.get(cs.KEY_FROM_QN)),
caller_path=_text(row.get(cs.KEY_FROM_PATH)),
rel=_text(row.get(cs.KEY_REL_TYPE)),
callee=_text(row.get(cs.KEY_TO_QN)),
callee_path=_text(row.get(cs.KEY_TO_PATH)),
line=_opt_int(row.get(cs.KEY_LINE)),
col=_opt_int(row.get(cs.KEY_COL)),
arg_count=_opt_int(row.get(cs.KEY_ARG_COUNT)),
kwarg_names=_strings(row.get(cs.KEY_KWARG_NAMES)),
)
def snapshot(fetch_all: QueryFn, project_name: str, paths: Iterable[str]) -> Snapshot:
"""Read the subgraph of `paths` (repo-relative) and the module imports."""
path_list = sorted(set(paths))
params: PropertyDict = {
cs.KEY_PROJECT_PREFIX: _prefix(project_name),
cs.CYPHER_PARAM_PATHS: list(path_list),
}
definitions: dict[str, Definition] = {}
for row in fetch_all(cq.CYPHER_DELTA_DEFINITIONS, params):
definition = _definition(row)
if definition.qualified_name:
definitions[definition.qualified_name] = definition
sites = tuple(
site
for site in (_site(row) for row in fetch_all(cq.CYPHER_DELTA_SITES, params))
if site.caller and site.callee
)
missing = sorted({s.callee for s in sites} - set(definitions))
callees: dict[str, Definition] = {}
if missing:
for row in fetch_all(
cq.CYPHER_DELTA_DEFINITIONS_BY_QN,
{cs.KEY_QNS: missing, cs.KEY_PROJECT_PREFIX: _prefix(project_name)},
):
definition = _definition(row)
if definition.qualified_name:
callees[definition.qualified_name] = definition
imports: dict[str, set[str]] = {}
module_paths: dict[str, str] = {}
for row in fetch_all(cq.CYPHER_DELTA_MODULE_IMPORTS, params):
source = _text(row.get(cs.KEY_FROM_QN))
target = _text(row.get(cs.KEY_TO_QN))
if not source or not target:
continue
imports.setdefault(source, set()).add(target)
imports.setdefault(target, set())
module_paths[source] = _text(row.get(cs.KEY_FROM_PATH))
return Snapshot(
paths=frozenset(path_list),
definitions=definitions,
callees=callees,
sites=sites,
imports={qn: frozenset(targets) for qn, targets in imports.items()},
module_paths=module_paths,
)
# --- symbols ------------------------------------------------------------------
def _pair_by_shape(
removed: list[str], by_shape: dict[tuple[str, str], list[str]], before: Snapshot
) -> tuple[list[RenameFinding], list[str]]:
"""Pass 1: same fingerprint, same file, new name -- a plain rename."""
renames: list[RenameFinding] = []
unpaired: list[str] = []
for qn in removed:
definition = before.definitions[qn]
candidates = by_shape.get((definition.path, definition.fingerprint))
if definition.fingerprint and candidates:
renames.append(
RenameFinding(old=qn, new=candidates.pop(0), path=definition.path)
)
else:
unpaired.append(qn)
return renames, unpaired
def _pair_by_move(
unpaired: list[str],
by_shape: dict[tuple[str, str], list[str]],
before: Snapshot,
after: Snapshot,
) -> tuple[list[RenameFinding], list[str]]:
"""Pass 2: same name and body, different file -- a move (issue #1534)."""
by_name_shape: dict[tuple[str, str], list[str]] = {}
for candidates in by_shape.values():
for qn in candidates:
definition = after.definitions[qn]
by_name_shape.setdefault(
(definition.name, definition.fingerprint), []
).append(qn)
renames: list[RenameFinding] = []
still_unpaired: list[str] = []
for qn in unpaired:
definition = before.definitions[qn]
candidates = by_name_shape.get((definition.name, definition.fingerprint))
if definition.fingerprint and candidates:
new = candidates.pop(0)
by_shape[(after.definitions[new].path, definition.fingerprint)].remove(new)
renames.append(RenameFinding(old=qn, new=new, path=definition.path))
else:
still_unpaired.append(qn)
return renames, still_unpaired
def _carried_container(
qn: str,
renames: list[RenameFinding],
paired_new: set[str],
added: list[str],
before: Snapshot,
after: Snapshot,
) -> str | None:
"""The added container a removed one moved to, when its members agree.
A class carries no fingerprint of its own, so a renamed class reads as
removed plus added; its methods do carry one and were paired already.
"""
definition = before.definitions[qn]
if definition.fingerprint:
return None
prefix = qn + cs.SEPARATOR_DOT
targets = {
r["new"][: len(r["new"]) - (len(r["old"]) - len(qn))]
for r in renames
if r["old"].startswith(prefix)
}
if len(targets) != 1:
return None
(target,) = targets
candidate = after.definitions.get(target)
if (
candidate is None
or candidate.fingerprint
or candidate.label != definition.label
or target in paired_new
or target not in added
):
return None
return target
def _pair_lone_containers(
still_unpaired: list[str],
renames: list[RenameFinding],
paired_new: set[str],
added: list[str],
before: Snapshot,
after: Snapshot,
declared: frozenset[tuple[str, str]],
) -> list[RenameFinding]:
"""Pass 4: an EMPTY container, paired only when the caller DECLARED it.
An empty container has no fingerprint and no descendants, and the only
thing that changed is its name -- so nothing in the two snapshots can
tell a rename from a replacement. They are the same edit. Neither
content similarity (git's heuristic) nor tree-sitter's changed ranges
separates them, because the difference is intent, not syntax.
So this pass does not infer. An operation that RENAMED something knows
which pairs it applied and passes them in `declared`; anything else is
reported as a removal plus an addition, which is the truth about what
the snapshots show. Guessing here produced renames that never happened,
and the contract treats an unexpected rename as a failure, so an
invented one rolls back a correct edit (Greptile, PR #1547).
"""
lone_removed = [
qn
for qn in still_unpaired
if not before.definitions[qn].fingerprint
and not any(r["old"] == qn for r in renames)
]
lone_added = [
qn
for qn in added
if qn not in paired_new and not after.definitions[qn].fingerprint
]
found: list[RenameFinding] = []
for qn in lone_removed:
definition = before.definitions[qn]
matches = [
other
for other in lone_added
if (qn, other) in declared
and after.definitions[other].path == definition.path
and after.definitions[other].label == definition.label
]
if len(matches) != 1:
continue
target = matches[0]
peers = [other for other in lone_removed if (other, target) in declared]
if len(peers) == 1:
found.append(RenameFinding(old=qn, new=target, path=definition.path))
paired_new.add(target)
lone_added.remove(target)
return found
def _renames(
removed: list[str],
added: list[str],
before: Snapshot,
after: Snapshot,
declared: frozenset[tuple[str, str]] = frozenset(),
) -> list[RenameFinding]:
# A rename keeps the body: the same whole-skeleton fingerprint under a
# new name in the same file. Paired one-to-one in sorted order so a
# duplicated body cannot be reported as two renames of one symbol.
#
# Four passes, each narrower than the last and each extracted to its own
# function (S3776): plain rename, move, container carried by its members,
# then the lone empty container.
by_shape: dict[tuple[str, str], list[str]] = {}
for qn in added:
definition = after.definitions[qn]
if definition.fingerprint:
by_shape.setdefault((definition.path, definition.fingerprint), []).append(
qn
)
renames, unpaired = _pair_by_shape(removed, by_shape, before)
moved, still_unpaired = _pair_by_move(unpaired, by_shape, before, after)
renames.extend(moved)
paired_new = {r["new"] for r in renames}
for qn in still_unpaired:
target = _carried_container(qn, renames, paired_new, added, before, after)
if target is not None:
renames.append(
RenameFinding(old=qn, new=target, path=before.definitions[qn].path)
)
paired_new.add(target)
renames.extend(
_pair_lone_containers(
still_unpaired, renames, paired_new, added, before, after, declared
)
)
return renames
def _changed(before: Snapshot, after: Snapshot) -> list[str]:
changed: list[str] = []
for qn in sorted(set(before.definitions) & set(after.definitions)):
old, new = before.definitions[qn], after.definitions[qn]
if (old.fingerprint, old.positional_params) != (
new.fingerprint,
new.positional_params,
):
changed.append(qn)
return changed
def _symbols(
before: Snapshot,
after: Snapshot,
declared: frozenset[tuple[str, str]] = frozenset(),
) -> SymbolDelta:
added = sorted(set(after.definitions) - set(before.definitions))
removed = sorted(set(before.definitions) - set(after.definitions))
renamed = _renames(removed, added, before, after, declared)
renamed_old = {r["old"] for r in renamed}
renamed_new = {r["new"] for r in renamed}
return SymbolDelta(
added=[qn for qn in added if qn not in renamed_new],
removed=[qn for qn in removed if qn not in renamed_old],
renamed=renamed,
changed=_changed(before, after),
)
# --- dangling callers ---------------------------------------------------------
def _dangling(
before: Snapshot, after: Snapshot, symbols: SymbolDelta
) -> list[DanglingCaller]:
gone = set(symbols["removed"]) | {r["old"] for r in symbols["renamed"]}
renamed_to = {r["old"]: r["new"] for r in symbols["renamed"]}
after_pairs = {(site.caller, site.callee) for site in after.sites}
out: list[DanglingCaller] = []
seen: set[tuple[str, str, int | None, int | None]] = set()
for site in before.sites:
if site.callee not in gone:
continue
new_name = renamed_to.get(site.callee)
# A caller re-parsed in this pass that now binds to the renamed
# symbol was updated; every other caller still names what is gone.
if site.caller_path in after.paths and (
(new_name is not None and (site.caller, new_name) in after_pairs)
or site.caller not in after.definitions
):
continue
key = (site.caller, site.callee, site.line, site.col)
if key in seen:
continue
seen.add(key)
out.append(
DanglingCaller(
caller=site.caller,
path=site.caller_path,
line=site.line,
col=site.col,
target=site.callee,
renamed_to=new_name,
)
)
return sorted(
out, key=lambda d: (d["path"], d["line"] or 0, d["col"] or 0, d["caller"])
)
# --- signature changes --------------------------------------------------------
# `*name` only: a bare `*` (keyword-only marker) accepts no extra positionals
# and `**name` accepts keywords, not positionals.
_VARIADIC = re.compile(r"(?<!\*)\*(?!\*)\s*[A-Za-z_]")
def _is_variadic(definition: Definition, repo_root: Path | None) -> bool:
"""Whether the Python definition's header declares `*args`.
`positional_params` ends at the star (CPython counts nothing after it),
so the stored list alone cannot tell `f(a)` from `f(a, *rest)`; the
header is read back so a variadic callee is never reported as
receiving too many arguments.
"""
if repo_root is None or not definition.path or definition.start_line < 1:
return False
try:
lines = (
(repo_root / definition.path)
.read_text(encoding=cs.ENCODING_UTF8)
.splitlines()
)
except (OSError, UnicodeDecodeError):
return False
header: list[str] = []
for line in lines[definition.start_line - 1 : definition.end_line or None]:
header.append(line)
if ")" in line:
break
text = "\n".join(header)
open_at = text.find("(")
close_at = text.find(")", open_at + 1)
if open_at < 0 or close_at < 0:
return False
return _VARIADIC.search(text[open_at:close_at]) is not None
def _arity_verdict(
site: CallSite, definition: Definition, repo_root: Path | None
) -> tuple[int, str]:
declared = definition.positional_params
if declared is None:
return -1, cs.DELTA_ARITY_UNKNOWN
if site.arg_count is None:
return len(declared), cs.DELTA_ARITY_UNKNOWN
is_method = definition.label in _METHOD_LABELS
# `arg_count` counts keyword arguments too (issue #1522); only the
# positionals plus the keywords naming a declared positional parameter
# fill the declared list. A keyword naming nothing declared is neutral:
# it may be a keyword-only parameter or `**kwargs`, which the stored
# positional list cannot see, and a wrong name is not an arity fault.
positional = site.arg_count - len(site.kwarg_names)
matched = sum(1 for name in site.kwarg_names if name in declared)
passed = positional + matched + (1 if is_method else 0)
# `diagnose_arity` owns the receiver arithmetic (`self` counts for
# CPython but is not caller-supplied); here the "message" is the site.
verdict = diagnose_arity(
ArityError(callee=definition.name, expected=passed, actual=passed),
declared,
is_method,
)
declared_count = verdict.declared_count - (1 if is_method else 0)
if verdict.confirmed:
return declared_count, cs.DELTA_ARITY_OK
if positional + (1 if is_method else 0) > verdict.declared_count:
if _is_variadic(definition, repo_root):
return declared_count, cs.DELTA_ARITY_OK
return declared_count, cs.DELTA_ARITY_TOO_MANY
if passed > verdict.declared_count:
return declared_count, cs.DELTA_ARITY_OK
return declared_count, cs.DELTA_ARITY_POSSIBLY_MISSING
def _site_finding(
site: CallSite, definition: Definition, repo_root: Path | None
) -> ArityAtSite:
declared_count, verdict = _arity_verdict(site, definition, repo_root)
return ArityAtSite(
caller=site.caller,
path=site.caller_path,
line=site.line,
col=site.col,
arg_count=site.arg_count,
kwarg_names=list(site.kwarg_names),
declared_count=declared_count,
verdict=verdict,
)
def _site_order(finding: ArityAtSite) -> tuple[str, int, int]:
return (finding["path"], finding["line"] or 0, finding["col"] or 0)
def _arity_findings(after: Snapshot, repo_root: Path | None) -> list[ArityAtSite]:
"""Call sites in the re-parsed files that pass more than the callee takes.
The definitive verdict only: a site passing fewer positional arguments
may be relying on defaults the graph does not record.
"""
out: list[ArityAtSite] = []
for site in after.sites:
callee = after.definitions.get(site.callee) or after.callees.get(site.callee)
if (
callee is None
or site.caller_path not in after.paths
or site.rel != cs.RelationshipType.CALLS.value
):
continue
finding = _site_finding(site, callee, repo_root)
if finding["verdict"] == cs.DELTA_ARITY_TOO_MANY:
out.append(finding)
return sorted(out, key=_site_order)
def _signature_changes(
before: Snapshot, after: Snapshot, symbols: SymbolDelta, repo_root: Path | None
) -> list[SignatureChange]:
out: list[SignatureChange] = []
for qn in symbols["changed"]:
old, new = before.definitions[qn], after.definitions[qn]
if old.positional_params == new.positional_params:
continue
sites = [
_site_finding(site, new, repo_root)
for site in after.sites
if site.callee == qn and site.rel == cs.RelationshipType.CALLS.value
]
out.append(
SignatureChange(
qualified_name=qn,
path=new.path,
before=list(old.positional_params) if old.positional_params else None,
after=list(new.positional_params) if new.positional_params else None,
sites=sorted(sites, key=_site_order),
)
)
return out
# --- new duplicates -----------------------------------------------------------
class _Shape(NamedTuple):
qualified_name: str
path: str
start_line: int
fingerprint: str
nodes: int
branches: frozenset[str]
def _shape(row: ResultRow) -> _Shape:
return _Shape(
qualified_name=_text(row.get(cs.KEY_QUALIFIED_NAME)),
path=_text(row.get(cs.KEY_PATH)),
start_line=_int(row.get(cs.KEY_START_LINE)),
fingerprint=_text(row.get(cs.KEY_AST_FINGERPRINT)),
nodes=_int(row.get(cs.KEY_AST_FINGERPRINT_NODES)),
branches=frozenset(_strings(row.get(cs.KEY_AST_BRANCH_FINGERPRINTS))),
)
def _match_duplicate_shapes(
candidate: _Shape, other: _Shape, threshold: float
) -> tuple[str, float] | None:
if other.qualified_name == candidate.qualified_name:
return None
if other.fingerprint == candidate.fingerprint:
return cs.KIND_EXACT, 1.0
if not candidate.branches or not other.branches:
return None
similarity = _jaccard(candidate.branches, other.branches)
if similarity >= threshold:
return cs.KIND_SIMILAR, similarity
return None
def _best_duplicate_match(
candidate: _Shape,
shapes: list[_Shape],
fresh_set: set[str],
threshold: float,
) -> tuple[float, _Shape, str] | None:
"""The most similar prior shape `candidate` duplicates, if any."""
best: tuple[float, _Shape, str] | None = None
for other in shapes:
found = _match_duplicate_shapes(candidate, other, threshold)
# An existing symbol is the original; a fresh one is at best a
# peer, reported once from the lexically earlier side.
if found is None or (
other.qualified_name in fresh_set
and other.qualified_name < candidate.qualified_name
):
continue
kind, similarity = found
if best is None or similarity > best[0]:
best = (similarity, other, kind)
return best
def _new_duplicate(
candidate: _Shape, other: _Shape, kind: str, similarity: float
) -> NewDuplicate:
return NewDuplicate(
qualified_name=candidate.qualified_name,
path=candidate.path,
start_line=candidate.start_line,
kind=kind,
similarity=round(similarity, 3),
original=DuplicateOriginal(
qualified_name=other.qualified_name,
path=other.path,
start_line=other.start_line,
),
)
def _new_duplicates(
fetch_all: QueryFn,
project_name: str,
fresh: Iterable[str],
threshold: float = cs.DUPLICATES_DEFAULT_THRESHOLD,
min_nodes: int = cs.DUPLICATES_DEFAULT_MIN_NODES,
) -> list[NewDuplicate]:
fresh_set = set(fresh)
if not fresh_set:
return []
rows = fetch_all(
cq.CYPHER_DUPLICATE_FINGERPRINTS, {cs.KEY_PROJECT_PREFIX: _prefix(project_name)}
)
shapes = [
s for s in (_shape(r) for r in rows) if s.fingerprint and s.nodes >= min_nodes
]
out: list[NewDuplicate] = []
for candidate in shapes:
if candidate.qualified_name not in fresh_set:
continue
best = _best_duplicate_match(candidate, shapes, fresh_set, threshold)
if best is not None:
similarity, other, kind = best
out.append(_new_duplicate(candidate, other, kind, similarity))
return sorted(out, key=lambda d: (d["path"], d["start_line"], d["qualified_name"]))
# --- import cycles ------------------------------------------------------------
class _TarjanState:
"""The bookkeeping Tarjan's algorithm carries between its two phases."""
def __init__(self) -> None:
self.index: dict[str, int] = {}
self.low: dict[str, int] = {}
self.on_stack: set[str] = set()
self.stack: list[str] = []
self.counter = 0
def enter(self, node: str) -> None:
"""Number `node` and push it onto the current path."""
self.index[node] = self.low[node] = self.counter
self.counter += 1
self.stack.append(node)
self.on_stack.add(node)
def pop_component(self, root: str) -> frozenset[str]:
"""Unwind the path down to `root`, which closes one SCC."""
component: set[str] = set()
while True:
member = self.stack.pop()
self.on_stack.discard(member)
component.add(member)
if member == root:
return frozenset(component)
def _tarjan_descend(
state: _TarjanState,
graph: dict[str, frozenset[str]],
work: list[tuple[str, Iterable[str]]],
node: str,
child: str,
) -> None:
"""Follow one edge: recurse into an unseen child, else relax the low-link."""
if child not in state.index:
state.enter(child)
work.append((child, iter(sorted(graph.get(child, ())))))
elif child in state.on_stack:
state.low[node] = min(state.low[node], state.index[child])
def strongly_connected(graph: dict[str, frozenset[str]]) -> list[frozenset[str]]:
"""Tarjan's SCCs, iteratively (a module graph can be thousands deep)."""
state = _TarjanState()
out: list[frozenset[str]] = []
for root in sorted(graph):
if root in state.index:
continue
work: list[tuple[str, Iterable[str]]] = [
(root, iter(sorted(graph.get(root, ()))))
]
state.enter(root)
while work:
node, children = work[-1]
child = next(children, None)
if child is not None:
_tarjan_descend(state, graph, work, node, child)
continue
work.pop()
if work:
parent = work[-1][0]
state.low[parent] = min(state.low[parent], state.low[node])
if state.low[node] == state.index[node]:
out.append(state.pop_component(node))
return out
def _cycles(graph: dict[str, frozenset[str]]) -> set[frozenset[str]]:
return {
component
for component in strongly_connected(graph)
if len(component) > 1
or any(member in graph.get(member, ()) for member in component)
}
def import_cycles(graph: dict[str, frozenset[str]]) -> set[frozenset[str]]:
"""The cyclic strongly connected components of a module import graph."""
return _cycles(graph)
def _new_import_cycles(before: Snapshot, after: Snapshot) -> list[list[str]]:
touched = {qn for qn, path in after.module_paths.items() if path in after.paths}
touched |= {qn for qn, path in before.module_paths.items() if path in before.paths}
fresh = _cycles(after.imports) - _cycles(before.imports)
return sorted(sorted(component) for component in fresh if component & touched)
# --- tests reaching -----------------------------------------------------------
class _Reach(NamedTuple):
depth: dict[str, int]
through: dict[str, str]
nodes: dict[_NodeId, PropertyDict]
def _walk_callers(fetch_all: QueryFn, prefix: str, targets: set[str]) -> _Reach:
"""Multi-source backward BFS, one indexed query per hop.
The cost is proportional to what is reached rather than to the project:
a project-wide reverse call graph costs more to build than most deltas
take in total.
"""
depth = dict.fromkeys(targets, 0)
through = {qn: qn for qn in targets}
nodes: dict[_NodeId, PropertyDict] = {}
frontier = sorted(targets)
for hop in range(1, cs.DELTA_REACH_MAX_DEPTH + 1):
if not frontier:
break
rows = fetch_all(
cq.CYPHER_DELTA_CALLERS_OF,
{cs.KEY_PROJECT_PREFIX: prefix, cs.KEY_QNS: frontier},
)
next_frontier: list[str] = []
for row in sorted(
rows,
key=lambda r: (
_text(r.get(cs.KEY_QUALIFIED_NAME)),
_text(r.get(cs.KEY_TO_QN)),
),
):
qn = _text(row.get(cs.KEY_QUALIFIED_NAME))
if not qn or qn in depth:
continue
depth[qn] = hop
through[qn] = _text(row.get(cs.KEY_TO_QN))
nodes[(_text(row.get(cs.KEY_LABEL)), qn)] = _node_props(row)
next_frontier.append(qn)
frontier = next_frontier
return _Reach(depth, through, nodes)
def _rust_inputs(
fetch_all: QueryFn, prefix: str, reached: dict[_NodeId, PropertyDict]
) -> tuple[set[str], dict[str, list[tuple[int, int]]]]:
rust_paths = sorted(
{
str(props.get(cs.KEY_PATH))
for props in reached.values()
if str(props.get(cs.KEY_PATH, "")).endswith(cs.EXT_RS)
}
)
if not rust_paths:
return set(), {}
modules: dict[_NodeId, PropertyDict] = {}
for row in fetch_all(cq.CYPHER_DELTA_RUST_MODULES, {cs.KEY_PROJECT_PREFIX: prefix}):
qn = _text(row.get(cs.KEY_QUALIFIED_NAME))
if qn:
modules[(_text(row.get(cs.KEY_LABEL)), qn)] = _node_props(row)
functions: dict[_NodeId, PropertyDict] = {}
for row in fetch_all(
cq.CYPHER_DELTA_RUST_TEST_FNS,
{cs.KEY_PROJECT_PREFIX: prefix, cs.CYPHER_PARAM_PATHS: rust_paths},
):
qn = _text(row.get(cs.KEY_QUALIFIED_NAME))
if qn:
functions[(_text(row.get(cs.KEY_LABEL)), qn)] = _node_props(row)
return _rust_test_modules_from_nodes(modules), _rust_test_fn_spans(functions)
def _tests_reaching(
fetch_all: QueryFn, project_name: str, targets: Iterable[str]
) -> list[TestReach]:
prefix = _prefix(project_name)
reach = _walk_callers(fetch_all, prefix, set(targets))
rust_modules, rust_spans = _rust_inputs(fetch_all, prefix, reach.nodes)
out: list[TestReach] = []
for (_label, raw_qn), props in reach.nodes.items():
qn = str(raw_qn)
path = str(props.get(cs.KEY_PATH) or "")
if _is_test_symbol(
props, qn, path, cs.TEST_PATH_PATTERNS, rust_modules, rust_spans
):
out.append(
TestReach(
qualified_name=qn,
path=path or None,
depth=reach.depth[qn],
through=reach.through[qn],
)
)
return sorted(out, key=lambda r: (r["depth"], r["qualified_name"]))
# --- the delta ----------------------------------------------------------------
def _inbound_calls(snap: Snapshot) -> int:
return sum(
1
for site in snap.sites
if site.rel == cs.RelationshipType.CALLS.value
and site.callee in snap.definitions
)
def structural_delta(
fetch_all: QueryFn,
project_name: str,