-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_ast_graph.py
More file actions
4218 lines (3749 loc) · 166 KB
/
Copy pathbuild_ast_graph.py
File metadata and controls
4218 lines (3749 loc) · 166 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
"""Four-pass AST-derived Knowledge Base builder (LadybugDB).
Walks a Java source tree with `tree_sitter_java`, writes a deterministic graph of:
Symbol nodes: package, file, class, interface, enum, record, annotation, method, constructor
Route nodes: declaration-site routes (Spring MVC/WebFlux, Feign, Kafka, …)
Rel tables: EXTENDS, IMPLEMENTS, INJECTS, DECLARES, OVERRIDES, CALLS, EXPOSES
Pass 1 builds every node and in-memory resolution indexes.
Pass 2 resolves each extends/implements/injection target using Java's lookup order
(same file → explicit import → same package → wildcard import → java.lang → phantom).
Pass 3 resolves static call sites into confidence-scored CALLS edges and DECLARES.
Pass 4 emits Route rows plus Symbol→Route EXPOSES edges from literal annotation metadata.
Usage:
build_ast_graph.py --source-root <repo> [--ladybug-path <path>] [--verbose]
Default LadybugDB database path resolution order:
--ladybug-path CLI arg (path passed to ladybug.Database(...))
JAVA_CODEBASE_RAG_INDEX_DIR/code_graph.lbug (if set and local)
./.java-codebase-rag/code_graph.lbug under cwd
The LadybugDB DB is dropped and rebuilt on every run (Phase 1 is a full rebuild).
"""
from __future__ import annotations
import argparse
import contextlib
import hashlib
import json
import logging
import os
import re
import sys
import threading
import time
from collections import defaultdict
from dataclasses import asdict, dataclass, field, replace
from pathlib import Path
import ladybug
import pyarrow as pa
from ast_java import (
ONTOLOGY_VERSION,
CallSite,
JavaFileAst,
MethodDecl,
OutgoingCallDecl,
TypeDecl,
injection_annotation_names,
lombok_required_args_annotations,
parse_java,
)
from graph_enrich import (
_load_config_cross_service_resolution,
collect_annotation_meta_chain,
load_brownfield_overrides,
microservice_for_path,
module_for_path,
phantom_id,
resolve_async_producer_for_method,
resolve_http_client_for_method,
resolve_role_and_capabilities,
resolve_routes_for_method,
symbol_id,
)
from path_filtering import LayeredIgnore, iter_java_source_files
from java_ontology import VALID_CLIENT_KINDS, VALID_HTTP_CALL_MATCHES, VALID_PRODUCER_KINDS
log = logging.getLogger(__name__)
_VERBOSE_STDERR_LOCK = threading.Lock()
_PASS1_START = "[graph] pass 1 · parsing Java files"
_PASS2_START = "[graph] pass 2 · emitting EXTENDS / IMPLEMENTS / DECLARES rows"
_PASS3_START = "[graph] pass 3 · call resolution (outgoing calls per site)"
_PASS4_START = "[graph] pass 4 · route and EXPOSES extraction"
_PASS5_START = "[graph] pass 5 · imperative HTTP_CALLS / ASYNC_CALLS edges"
_PASS6_START = "[graph] pass 6 · cross-service call-edge matching"
_WRITE_START = "[graph] writing · LadybugDB graph to disk"
def _verbose_stderr_line(content: str) -> None:
with _VERBOSE_STDERR_LOCK:
print(content, file=sys.stderr, flush=True)
def _emit_graph_progress(parts: dict[str, object], *, verbose: bool) -> None:
"""Emit one ``JCIRAG_PROGRESS kind=graph …`` line to stderr (gated by verbose).
The parent process (``pipeline.run_build_ast_graph`` /
``run_incremental_graph``) passes ``--verbose`` in default AND verbose modes
(only suppressed for ``--quiet``), so this structured progress surfaces in
default mode (where the parent renders it) and verbose mode (raw relay). In
``--quiet`` the builder is never invoked with ``--verbose`` so nothing is
emitted. Field order is fixed so the parser and tests can pin substrings.
"""
if not verbose:
return
fields = ["kind=graph"]
for key in ("pass", "done", "total", "status", "elapsed_s"):
if key in parts:
fields.append(f"{key}={parts[key]}")
line = "JCIRAG_PROGRESS " + " ".join(fields)
_verbose_stderr_line(line)
# Pass-1 per-file tick cadence: bound stderr volume on huge trees without making
# the bar feel stale. A final tick on pass completion carries status=done.
_PASS1_TICK_EVERY = 25
@contextlib.contextmanager
def _graph_pass_progress(pass_label: str, *, verbose: bool):
"""Emit ``pass=N/6 status=running`` on entry and ``status=done elapsed_s=…``
on exit for passes 2–6 (each advances the rendered bar by 1/6).
Usage: ``with _graph_pass_progress("2/6", verbose=verbose): …``
"""
if not verbose:
yield
return
_emit_graph_progress({"pass": pass_label, "status": "running"}, verbose=verbose)
t0 = time.time()
try:
yield
finally:
elapsed = time.time() - t0
_emit_graph_progress(
{"pass": pass_label, "status": "done", "elapsed_s": f"{elapsed:.2f}"},
verbose=verbose,
)
class _VerbosePassHeartbeats:
"""Emit ``[tag] running … Ns elapsed`` every 5s on stderr while in scope (verbose only)."""
def __init__(self, tag: str, *, verbose: bool) -> None:
self._tag = tag
self._verbose = verbose
self._thr: threading.Thread | None = None
self._stop: threading.Event | None = None
def __enter__(self) -> None:
if not self._verbose:
return None
self._stop = threading.Event()
stop = self._stop
tag = self._tag
def worker() -> None:
t0 = time.monotonic()
while not stop.wait(timeout=5.0):
elapsed = int(time.monotonic() - t0)
_verbose_stderr_line(f"{tag} · {elapsed}s elapsed")
self._thr = threading.Thread(target=worker, name=f"hb-{tag}", daemon=True)
self._thr.start()
return None
def __exit__(self, exc_type, exc, tb) -> bool:
if self._thr is not None and self._stop is not None:
self._stop.set()
self._thr.join(timeout=2.0)
return False
_JAVA_LANG_SIMPLE = frozenset({
"Object", "String", "Integer", "Long", "Short", "Byte", "Boolean", "Double",
"Float", "Character", "Number", "Void", "Class", "Enum", "Record",
"Throwable", "Exception", "RuntimeException", "Error", "Thread", "Runnable",
"Iterable", "Comparable", "CharSequence", "StringBuilder", "StringBuffer",
"Math", "System", "AutoCloseable", "Cloneable",
})
# ---------- dataclasses ----------
@dataclass
class TypeIndexEntry:
"""Pass-1 record for a type declaration + any methods/constructors inside it."""
decl: TypeDecl
file_path: str
module: str
microservice: str
package: str
outer_fqn: str | None
node_id: str
# True when this entry was loaded from the existing graph by
# `_load_existing_types` (an unchanged-file stub used only for cross-file
# resolution). Its `decl` is a placeholder (no annotations/methods), so its
# recomputed role/capabilities must never be written back over the real
# stored values. See `_write_nodes_impl`.
loaded_from_db: bool = False
@dataclass
class MemberEntry:
kind: str # method | constructor
decl: MethodDecl
parent_id: str
parent_fqn: str
file_path: str
module: str
microservice: str
node_id: str
# True when loaded from the existing graph by `_load_existing_members`
# (an unchanged-file stub used only for cross-file call resolution). Its
# DECLARES edge already persists in the graph, so it must not be re-emitted
# by `_populate_declares_rows` (REL tables have no PK → would duplicate).
loaded_from_db: bool = False
@dataclass
class EdgeRow:
src_id: str
dst_id: str
dst_name: str
dst_fqn: str
resolved: bool
@dataclass
class InjectsRow(EdgeRow):
mechanism: str = ""
annotation: str = ""
field_or_param: str = ""
@dataclass
class CallsRow:
src_id: str
dst_id: str
call_site_line: int = 0
call_site_byte: int = 0
arg_count: int = 0
confidence: float = 0.0
strategy: str = "phantom"
source: str = "static"
resolved: bool = True
callee_declaring_role: str = "OTHER"
@dataclass
class UnresolvedCallSiteRow:
id: str
caller_id: str
call_site_line: int
call_site_byte: int
arg_count: int
callee_simple: str
receiver_expr: str
reason: str
@dataclass
class DeclaresRow:
src_id: str
dst_id: str
@dataclass
class CallResolutionStats:
total: int = 0
by_strategy: dict[str, int] = field(default_factory=lambda: defaultdict(int))
phantom_chained: int = 0
phantom_other: int = 0
callee_unresolved: int = 0
skipped_cross_service: int = 0
@dataclass
class RouteRow:
id: str
kind: str
framework: str
method: str
path: str
path_template: str
path_regex: str
topic: str
broker: str
feign_name: str
feign_url: str
microservice: str
module: str
filename: str
start_line: int
end_line: int
resolved: bool
# B2a brownfield composition (PR-A3); not persisted on LadybugDB `Route` nodes.
source_layer: str = "builtin"
@dataclass
class ExposesRow:
symbol_id: str
route_id: str
confidence: float
strategy: str
@dataclass
class RouteExtractionStats:
routes_skipped_unresolved: int = 0
by_framework: dict[str, int] = field(default_factory=lambda: defaultdict(int))
by_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
routes_resolved_pct: float = 100.0
# Percentage of emitted `Route` rows whose `source_layer` is not `builtin`.
# Brownfield layers: `layer_b_ann`, `layer_a_meta`, `layer_c_source`, `layer_b_fqn`.
routes_from_brownfield_pct: float = 0.0
routes_by_layer: dict[str, int] = field(default_factory=dict)
exposes_suppressed_feign: int = 0
@dataclass
class HttpCallRow:
client_id: str
route_id: str
confidence: float
strategy: str
method_call: str
raw_uri: str
match: str
@dataclass
class AsyncCallRow:
producer_id: str
route_id: str
confidence: float
strategy: str
direction: str
raw_topic: str
match: str
@dataclass
class ClientRow:
id: str
client_kind: str
target_service: str
path: str
path_template: str
path_regex: str
method: str
member_fqn: str
member_id: str
microservice: str
module: str
filename: str
start_line: int
end_line: int
resolved: bool
source_layer: str
@dataclass
class DeclaresClientRow:
symbol_id: str
client_id: str
confidence: float
strategy: str
@dataclass
class ProducerRow:
id: str
producer_kind: str
topic: str
broker: str
direction: str
member_fqn: str
member_id: str
microservice: str
module: str
filename: str
start_line: int
end_line: int
resolved: bool
source_layer: str
@dataclass
class DeclaresProducerRow:
symbol_id: str
producer_id: str
confidence: float
strategy: str
@dataclass
class ClientExtractionStats:
clients_total: int = 0
declares_client_total: int = 0
clients_by_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
@dataclass
class ProducerExtractionStats:
producers_total: int = 0
declares_producer_total: int = 0
producers_by_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
@dataclass
class CallEdgeStats:
http_calls_total: int = 0
async_calls_total: int = 0
http_calls_by_client_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
async_calls_by_client_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
http_calls_by_strategy: dict[str, int] = field(default_factory=lambda: defaultdict(int))
async_calls_by_strategy: dict[str, int] = field(default_factory=lambda: defaultdict(int))
http_calls_skipped_unresolved: int = 0
async_calls_skipped_unresolved: int = 0
http_clients_from_brownfield_pct: float = 0.0
async_producers_from_brownfield_pct: float = 0.0
http_calls_match_breakdown: dict[str, int] = field(default_factory=lambda: defaultdict(int))
async_calls_match_breakdown: dict[str, int] = field(default_factory=lambda: defaultdict(int))
cross_service_calls_total: int = 0
@dataclass
class GraphTables:
types: dict[str, TypeIndexEntry] = field(default_factory=dict) # fqn -> entry
by_simple_name: dict[str, list[TypeIndexEntry]] = field(default_factory=dict)
by_package: dict[str, list[TypeIndexEntry]] = field(default_factory=dict)
files: dict[str, str] = field(default_factory=dict) # path -> node id
packages: dict[str, str] = field(default_factory=dict) # pkg -> node id
members: list[MemberEntry] = field(default_factory=list)
phantoms: dict[str, dict] = field(default_factory=dict) # id -> row
extends_rows: list[EdgeRow] = field(default_factory=list)
implements_rows: list[EdgeRow] = field(default_factory=list)
injects_rows: list[InjectsRow] = field(default_factory=list)
calls_rows: list[CallsRow] = field(default_factory=list)
unresolved_call_site_rows: list[UnresolvedCallSiteRow] = field(default_factory=list)
declares_rows: list[DeclaresRow] = field(default_factory=list)
routes_rows: list[RouteRow] = field(default_factory=list)
exposes_rows: list[ExposesRow] = field(default_factory=list)
http_call_rows: list[HttpCallRow] = field(default_factory=list)
async_call_rows: list[AsyncCallRow] = field(default_factory=list)
client_rows: list[ClientRow] = field(default_factory=list)
declares_client_rows: list[DeclaresClientRow] = field(default_factory=list)
producer_rows: list[ProducerRow] = field(default_factory=list)
declares_producer_rows: list[DeclaresProducerRow] = field(default_factory=list)
overrides_rows: list[DeclaresRow] = field(default_factory=list)
route_stats: RouteExtractionStats = field(default_factory=RouteExtractionStats)
call_edge_stats: CallEdgeStats = field(default_factory=CallEdgeStats)
client_stats: ClientExtractionStats = field(default_factory=ClientExtractionStats)
producer_stats: ProducerExtractionStats = field(default_factory=ProducerExtractionStats)
methods_by_type: dict[str, list[MemberEntry]] = field(default_factory=dict)
parse_errors: int = 0
skipped_files: int = 0
pass3_skipped_cross_service: int = 0
pass3_unresolved_phantom_receiver: int = 0
pass3_unresolved_chained: int = 0
cross_service_resolution: str = "auto"
# Populated in _write_nodes (same overrides + meta_chain as Symbol.role).
type_role_by_node_id: dict[str, str] = field(default_factory=dict)
@dataclass
class IncrementalResult:
"""Result of an incremental graph rebuild."""
mode: str # "incremental" | "full_fallback"
files_changed: int
files_added: int
files_removed: int
dependents_reprocessed: int
elapsed_sec: float
class FileHashTracker:
"""Track content hashes for incremental graph rebuild."""
def __init__(self, index_dir: Path):
self._path = index_dir / ".graph_hashes.json"
self._hashes: dict[str, str] = {} # rel_path -> sha256_hex
def load(self) -> None:
"""Load hashes from disk. No-op if file missing (first run)."""
if not self._path.exists():
return
try:
with open(self._path, "r", encoding="utf-8") as f:
self._hashes = json.load(f)
except (json.JSONDecodeError, OSError):
# Corrupt or unreadable hash file; start fresh.
self._hashes = {}
def save(self) -> None:
"""Persist hashes to disk atomically (write .tmp, rename)."""
tmp_path = self._path.with_suffix(".json.tmp")
try:
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(self._hashes, f, sort_keys=True)
os.replace(tmp_path, self._path)
except OSError as e:
# Fail gracefully; next run will treat as missing and rebuild.
log.warning("Failed to save hash file %s: %s; next run will rebuild from scratch", self._path, e)
def detect_changes(self, source_root: Path, ignore: LayeredIgnore) -> tuple[set[str], set[str], set[str]]:
"""Return (added, changed, removed) sets of relative POSIX paths."""
current_files: set[str] = set()
# Resolve source_root to handle symlinks
source_root_resolved = source_root.resolve()
for abs_path in iter_java_source_files(source_root, ignore=ignore):
# Resolve the absolute path and compute relative path
abs_path_resolved = abs_path.resolve()
try:
rel_path = abs_path_resolved.relative_to(source_root_resolved).as_posix()
except ValueError:
# Fallback to using the path as-is if it's not under source_root
rel_path = abs_path.as_posix()
current_files.add(rel_path)
added: set[str] = set()
changed: set[str] = set()
removed: set[str] = set()
# Detect added and changed files.
for rel_path in current_files:
abs_path = source_root / rel_path
try:
file_hash = _hash_file(abs_path)
except FileNotFoundError:
continue
stored_hash = self._hashes.get(rel_path)
if stored_hash is None:
added.add(rel_path)
elif stored_hash != file_hash:
changed.add(rel_path)
# Detect removed files.
for rel_path in self._hashes:
if rel_path not in current_files:
removed.add(rel_path)
return added, changed, removed
def update(self, rel_paths: set[str], source_root: Path) -> None:
"""Compute and store hashes for the given paths."""
for rel_path in rel_paths:
abs_path = source_root / rel_path
if abs_path.exists():
self._hashes[rel_path] = _hash_file(abs_path)
def _hash_file(abs_path: Path) -> str:
"""Compute SHA-256 hash of a file's raw bytes."""
hasher = hashlib.sha256()
with open(abs_path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
hasher.update(chunk)
return hasher.hexdigest()
# ---------- incremental rebuild helpers ----------
def _load_existing_types(conn: ladybug.Connection, tables: GraphTables, exclude_files: set[str] | None = None) -> None:
"""Load type entries from existing LadybugDB graph into tables for cross-file resolution.
When exclude_files is provided, only load types from files NOT in the set.
"""
if exclude_files is not None and not exclude_files:
return
where = f"WHERE s.kind IN {list(_TYPE_KINDS)}"
params: dict = {}
if exclude_files:
where += "\n AND NOT (s.filename IN $exclude_files)"
params["exclude_files"] = list(exclude_files)
query = f"""
MATCH (s:Symbol)
{where}
RETURN s.kind, s.fqn, s.name, s.filename, s.module, s.microservice, s.id
"""
result = conn.execute(query, params)
while result.has_next():
row = result.get_next()
kind, fqn, name, filename = row[0], row[1], row[2], row[3]
module = row[4] if len(row) > 4 else ""
microservice = row[5] if len(row) > 5 else ""
node_id = row[6] if len(row) > 6 else ""
decl = TypeDecl(name, kind, fqn)
package = fqn[: -(len(name) + 1)] if fqn.endswith("." + name) else ""
entry = TypeIndexEntry(
decl=decl,
file_path=filename,
module=module,
microservice=microservice,
package=package,
outer_fqn=None,
node_id=node_id,
loaded_from_db=True,
)
tables.types[fqn] = entry
tables.by_simple_name.setdefault(name, []).append(entry)
tables.by_package.setdefault(package, []).append(entry)
def _load_existing_members(conn: ladybug.Connection, tables: GraphTables, exclude_files: set[str] | None = None) -> None:
"""Load member entries from existing LadybugDB graph into tables.members.
When exclude_files is provided, only load members from files NOT in the set.
"""
if exclude_files is not None and not exclude_files:
return
where = "WHERE s.kind IN ['method', 'constructor']"
params: dict = {}
if exclude_files:
where += "\n AND NOT (s.filename IN $exclude_files)"
params["exclude_files"] = list(exclude_files)
query = f"""
MATCH (s:Symbol)
{where}
RETURN s.kind, s.name, s.filename, s.signature, s.parent_id, s.fqn, s.id
"""
result = conn.execute(query, params)
while result.has_next():
row = result.get_next()
kind, name, filename = row[0], row[1], row[2]
signature = row[3] if len(row) > 3 else ""
parent_id = row[4] if len(row) > 4 else ""
fqn = row[5] if len(row) > 5 else ""
node_id = row[6] if len(row) > 6 else ""
parent_fqn = fqn.split("#")[0] if "#" in fqn else ""
decl = MethodDecl(name, "", kind == "constructor")
decl.signature = signature
tables.members.append(MemberEntry(
kind=kind,
decl=decl,
parent_id=parent_id,
parent_fqn=parent_fqn,
file_path=filename,
module="",
microservice="",
node_id=node_id,
loaded_from_db=True,
))
# Every Symbol->Symbol REL TABLE type in the graph schema. A Symbol node can
# only have an INCOMING edge of one of these types, so `_find_dependents` MUST
# walk all of them: that completeness is what makes the changed-node DETACH
# DELETE in `_delete_file_scope` Phase 3 safe (every real caller of a changed
# node is pulled into scope, so Phase 1 removes the edge before the node delete).
# If you add a new Symbol->Symbol edge type to the schema, add it here too —
# otherwise changed-node deletion would silently drop its surviving edges.
_SYMBOL_TO_SYMBOL_EDGE_TYPES = (
"EXTENDS", "IMPLEMENTS", "INJECTS", "CALLS", "DECLARES", "OVERRIDES",
)
def _find_dependents(conn: ladybug.Connection, changed_node_ids: set[str]) -> set[str]:
"""Find files whose nodes have edges pointing into changed nodes. Returns set of filenames."""
dependent_files: set[str] = set()
params = {"changed_ids": list(changed_node_ids)}
for edge_type in _SYMBOL_TO_SYMBOL_EDGE_TYPES:
query = f"""
MATCH (src:Symbol)-[e:{edge_type}]->(dst:Symbol)
WHERE dst.id IN $changed_ids
RETURN DISTINCT src.filename
"""
result = conn.execute(query, params)
while result.has_next():
row = result.get_next()
filename = row[0]
if filename: # Skip phantom nodes (filename = "")
dependent_files.add(filename)
return dependent_files
def _find_annotation_dependents(conn: ladybug.Connection, changed_node_ids: set[str]) -> set[str]:
"""Find files that USE an annotation whose DEFINITION is among the changed nodes.
Annotation usage is a node property (``annotations`` STRING[]), not a
Symbol->Symbol edge, so `_find_dependents` — which walks edges — never pulls
annotation users into scope. When an annotation definition changes (e.g.
``@interface Foo`` gains a meta-annotation that shifts the Layer-A chain in
`resolve_role_and_capabilities`), every type carrying ``@Foo`` may need its
``role``/``capabilities`` recomputed or it goes stale until the next full
rebuild. Return those users' files so the orchestrator treats them as
dependents (re-parsed, role re-SET); the expansion cap bounds the scope.
Scope is direct usage only: a user of an annotation that transitively
composes the changed one (e.g. ``@A`` where ``@A`` is meta-annotated with the
changed ``@B``) is NOT pulled in — that reverse-chain walk is left to a
future hardening pass. The direct case covers the dominant real-world shape
(a stereotype annotation applied directly to many types).
"""
if not changed_node_ids:
return set()
# Changed annotation definitions → the simple names users reference them by.
# Runs before `_delete_file_scope`, so the def nodes still exist.
name_result = conn.execute(
"MATCH (s:Symbol) WHERE s.id IN $ids AND s.kind = 'annotation' RETURN s.name",
{"ids": list(changed_node_ids)},
)
names: list[str] = []
while name_result.has_next():
nm = name_result.get_next()[0]
if nm:
names.append(nm)
if not names:
return set()
dependent_files: set[str] = set()
for nm in names:
user_result = conn.execute(
"MATCH (s:Symbol) "
"WHERE list_contains(s.annotations, $nm) AND s.filename <> '' "
"RETURN DISTINCT s.filename",
{"nm": nm},
)
while user_result.has_next():
fn = user_result.get_next()[0]
if fn:
dependent_files.add(fn)
return dependent_files
def _delete_file_scope(
conn: ladybug.Connection,
changed_files: set[str],
dependent_files: set[str],
) -> None:
"""Delete nodes and edges for a scope split into changed vs dependent files.
``changed_files`` are files whose content actually changed (added/modified/
removed): their Symbol nodes are deleted (and re-created by ``_scoped_write``).
``dependent_files`` are files pulled in only to re-resolve their OUTGOING
edges against the changed nodes; their node definitions did not change, so
their nodes are deliberately PRESERVED (they re-MERGE in place on the same
deterministic ``symbol_id``). Skipping phantom nodes (filename="").
Why dependents are preserved (issue #305): the orchestrator computes
dependents from the *changed* nodes only, so a dependent file's node can
have an incoming CALLS edge from an out-of-scope caller. The ``source_file``
on every Symbol->Symbol edge is the CALLER's file (pinned by
``test_source_file_value_matches_symbol_filename``), so Phase 1 below only
deletes edges ORIGINATING in scope; incoming edges from out-of-scope callers
survive. If we then tried to DELETE the dependent node, LadybugDB rejects it
("Node ... has connected edges in table CALLS in the bwd direction, ...
Please delete the edges first or try DETACH DELETE") and the rebuild falls
back to a full rebuild. A naive fix (DETACH DELETE on dependents, or an
extra incoming-edge pass) would silence the crash but permanently drop those
out-of-scope edges, corrupting the graph. Preserving dependent nodes keeps
both the nodes and their incoming edges intact.
Phase 1 deletes ALL edge types across the whole scope (changed + dependent)
first to avoid LadybugDB "has connected edges" errors when edges from one
file point to nodes in another file within the same scope. Route/Client/
Producer nodes use DETACH DELETE as a safety net for any edges missed in
Phase 1.
"""
scope_files = changed_files | dependent_files
scope_list = list(scope_files)
changed_list = list(changed_files)
# Phase 1: Delete ALL edges ORIGINATING from any scope file (changed +
# dependent). Because `source_file` is the caller's file, this deletes edges
# whose source is in scope (including dependents' outgoing edges to changed
# nodes) while intentionally leaving incoming edges from out-of-scope callers
# intact — those must survive so the dependent nodes below can be preserved.
# This list is a superset of `_SYMBOL_TO_SYMBOL_EDGE_TYPES` (it also covers
# Symbol->Route/Client/Producer/UCS and Client/Producer->Route edges); keep
# both lists in sync with the schema.
edge_tables = [
"EXTENDS", "IMPLEMENTS", "INJECTS", "CALLS", "DECLARES", "OVERRIDES",
"UNRESOLVED_AT", "EXPOSES", "DECLARES_CLIENT", "DECLARES_PRODUCER",
"HTTP_CALLS", "ASYNC_CALLS",
]
for edge_type in edge_tables:
query = f"""
MATCH (src)-[e:{edge_type}]->(dst)
WHERE e.source_file IN $filenames
DELETE e
"""
conn.execute(query, {"filenames": scope_list})
# Phase 2: Collect all Symbol node IDs for UnresolvedCallSite cleanup.
symbol_ids: list[str] = []
symbol_ids_query = """
MATCH (s:Symbol)
WHERE s.filename IN $filenames
RETURN s.id
"""
result = conn.execute(symbol_ids_query, {"filenames": scope_list})
while result.has_next():
row = result.get_next()
symbol_ids.append(row[0])
# Delete UnresolvedCallSite nodes whose caller_id is in the collected set.
# These are children of scope symbols (including preserved dependents);
# deleting them is safe because every scope file — dependents included — is
# reprocessed and re-emits its UnresolvedCallSite nodes in `_scoped_write`.
if symbol_ids:
unresolved_query = """
MATCH (u:UnresolvedCallSite)
WHERE u.caller_id IN $symbol_ids
DELETE u
"""
conn.execute(unresolved_query, {"symbol_ids": symbol_ids})
# Phase 3: Delete Symbol nodes ONLY for changed files (not dependents).
# Dependent-file nodes are deliberately PRESERVED so their incoming edges
# from out-of-scope callers survive; the dependents are re-MERGEd in place
# by `_scoped_write` on the same deterministic node id. A changed node's
# real incoming edges all come from dependent files (callers pulled into
# scope by `_find_dependents`, which walks every type in
# `_SYMBOL_TO_SYMBOL_EDGE_TYPES`), so Phase 1 already removed them and the
# dependents re-emit them when reprocessed. DETACH DELETE is only a safety
# net for the rare surviving edge whose source was NOT pulled into scope
# (e.g. a phantom caller with filename="", which `_find_dependents` skips);
# such an edge is stale once the node is recreated, so dropping it is fine.
delete_symbols_query = """
MATCH (s:Symbol)
WHERE s.filename IN $filenames
DETACH DELETE s
"""
conn.execute(delete_symbols_query, {"filenames": changed_list})
# Phase 4: Delete Route, Client, Producer nodes.
# Use DETACH DELETE as a safety net in case any edges were missed in Phase 1.
for label in ["Route", "Client", "Producer"]:
conn.execute(
f"MATCH (n:{label}) WHERE n.filename IN $filenames DETACH DELETE n",
{"filenames": scope_list},
)
def _scoped_write(conn: ladybug.Connection, tables: GraphTables, *, project_root: Path, meta_chain: dict[str, frozenset[str]] | None) -> None:
"""Write nodes and edges to existing LadybugDB database without drop/create schema.
Like write_ladybug() but without _drop_all()/_create_schema(). The caller is
responsible for calling _populate_declares_rows() and _populate_overrides_rows()
before invoking this function.
Uses MERGE instead of CREATE to handle cases where nodes already exist.
"""
t0 = time.time()
_write_nodes_merge(
conn,
tables,
project_root=project_root,
meta_chain=meta_chain,
)
elapsed = time.time() - t0
if elapsed > 0.1: # Only log if significant
_verbose_stderr_line(f"[graph] scoped write · nodes written in {elapsed:.2f}s")
t1 = time.time()
_fbyid = _build_file_by_node_id(tables)
_write_edges(conn, tables, _fbyid)
elapsed = time.time() - t1
if elapsed > 0.1:
_verbose_stderr_line(f"[graph] scoped write · edges written in {elapsed:.2f}s")
t2 = time.time()
_write_routes_and_exposes(conn, tables, _fbyid)
elapsed = time.time() - t2
if elapsed > 0.1:
_verbose_stderr_line(f"[graph] scoped write · routes/exposes written in {elapsed:.2f}s")
def _write_nodes_merge(
conn: ladybug.Connection,
tables: GraphTables,
*,
project_root: Path,
meta_chain: dict[str, frozenset[str]] | None,
) -> None:
"""Write nodes to existing LadybugDB database using bulk COPY FROM."""
_write_nodes_impl(conn, tables, project_root=project_root, meta_chain=meta_chain)
# ---------- file walk (see `path_filtering.iter_java_source_files`) ----------
# ---------- pass 1 ----------
def _register_type(
tables: GraphTables,
decl: TypeDecl,
*,
file_path: str,
module: str,
microservice: str,
outer_fqn: str | None,
) -> TypeIndexEntry:
package = decl.fqn.rsplit(".", 1)[0] if "." in decl.fqn and outer_fqn is None else (
outer_fqn.rsplit(".", 1)[0] if outer_fqn and "." in outer_fqn else ""
)
# top-level: package = fqn - name; nested: inherit from outer
if outer_fqn is None:
package = decl.fqn[: -(len(decl.name) + 1)] if decl.fqn.endswith("." + decl.name) else ""
else:
# walk outward to find a top-level fqn; package is everything before its simple name
top = outer_fqn
while top in tables.types and tables.types[top].outer_fqn:
top = tables.types[top].outer_fqn # type: ignore[assignment]
package = top[: top.rfind(".")] if "." in top else ""
node_id = symbol_id(decl.kind, decl.fqn, file_path, decl.start_byte)
entry = TypeIndexEntry(
decl=decl,
file_path=file_path,
module=module,
microservice=microservice,
package=package,
outer_fqn=outer_fqn,
node_id=node_id,
)
tables.types[decl.fqn] = entry
tables.by_simple_name.setdefault(decl.name, []).append(entry)
tables.by_package.setdefault(package, []).append(entry)
for m in decl.methods:
kind = "constructor" if m.is_constructor else "method"
mid = symbol_id(kind, f"{decl.fqn}#{m.signature}", file_path, m.start_byte)
tables.members.append(MemberEntry(
kind=kind, decl=m, parent_id=node_id, parent_fqn=decl.fqn,
file_path=file_path, module=module, microservice=microservice,
node_id=mid,
))
for nested in decl.nested:
_register_type(
tables, nested, file_path=file_path,
module=module, microservice=microservice, outer_fqn=decl.fqn,
)
return entry
def pass1_parse(
root: Path,
tables: GraphTables,
*,
verbose: bool,
scope_files: set[str] | None = None,
removed_files: set[str] | None = None,
) -> dict[str, JavaFileAst]:
"""Walk files, parse them, populate node indexes. Returns path -> AST.
Args:
root: Source root directory.
tables: GraphTables to populate.
verbose: Whether to emit progress output.
scope_files: Optional set of relative POSIX paths to parse. If None, parse all files.
removed_files: Optional set of relative POSIX paths that no longer exist
on disk (incremental deletions). These are members of ``scope_files``
(they were deleted, so they participate in scoped deletion) but are
never visited by the parse walk, so they must be excluded from the
pass-1 total to keep ``done`` from undercounting then two-way-clamping.
"""
asts: dict[str, JavaFileAst] = {}
ignore = LayeredIgnore(root)
t0 = time.time()
n_files = 0
if verbose:
_verbose_stderr_line(_PASS1_START)
# Count-first: one filtered walk (no parsing) to set the EXACT total before
# the parse loop ticks. Single-layer ignore → the count is exact, so the
# rendered bar is determinate. For a scoped (incremental) parse the total is
# the number of files that will actually be visited: scope minus any removed
# files (which are members of scope for deletion but gone from disk, so the
# parse walk never ticks them); for a full rebuild it is the non-ignored
# .java count.
if verbose:
if scope_files is not None:
removed = removed_files if removed_files is not None else set()
pass1_total = len(scope_files - removed)
else:
pass1_total = sum(1 for _ in iter_java_source_files(root, ignore=ignore))
_emit_graph_progress(
{"pass": "1/6", "done": 0, "total": pass1_total, "status": "running"},
verbose=verbose,
)
slow_sec = 0.0
raw_slow = os.environ.get("JAVA_CODEBASE_RAG_TEST_GRAPH_SLOW_SEC", "").strip()
if raw_slow:
try:
slow_sec = float(raw_slow)
except ValueError:
slow_sec = 0.0