-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathladybug_queries.py
More file actions
1989 lines (1835 loc) · 88.2 KB
/
Copy pathladybug_queries.py
File metadata and controls
1989 lines (1835 loc) · 88.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
"""Read-only Cypher helpers over the Ladybug AST graph built by `build_ast_graph.py`.
Each function opens a Ladybug connection on demand and returns plain JSON-ish dicts
so the MCP server can serialize them without further mapping.
The Ladybug database is opened read-only and cached per-process. This module is
intentionally dependency-light: nothing here imports LanceDB or sentence-transformers.
Cypher pitfalls (see also ``AGENTS.md``): avoid ``label(e) IN $list`` in ``WHERE`` for
relationship-type filters; use OR of ``label(e) = $param`` with bound parameters.
Typed unions ``-[e:A|B]-`` require every ``RETURN`` column on ``e`` to exist on all
listed rel types, or the binder may fail.
"""
from __future__ import annotations
import json
import logging
import os
import re
import threading
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Literal
import ladybug
from ast_java import ONTOLOGY_VERSION as _ONTOLOGY_VERSION
log = logging.getLogger(__name__)
def _parse_ladybug_json(raw: str | None) -> dict[str, Any]:
"""Parse JSON from LadybugDB which returns unquoted keys like {key: value}."""
if not raw:
return {}
# LadybugDB returns JSON without quotes around keys: {packages: 1, files: 2}
# Convert to standard JSON: {"packages": 1, "files": 2}
# This regex matches word characters followed by ':' at the start of a key
quoted = re.sub(r'(\w+):', r'"\1":', raw)
try:
return json.loads(quoted)
except Exception:
try:
# Fallback: try parsing as-is (for standard JSON)
return json.loads(raw)
except Exception:
log.warning("Failed to parse counts_json: %s", raw[:100])
return {}
# Composed describe / neighbors dot-keys (not stored graph edge labels).
_MEMBER_EDGE_COMPOSED_REL_MAP: tuple[tuple[str, str], ...] = (
("DECLARES.DECLARES_CLIENT", "DECLARES_CLIENT"),
("DECLARES.DECLARES_PRODUCER", "DECLARES_PRODUCER"),
("DECLARES.EXPOSES", "EXPOSES"),
)
_MEMBER_EDGE_COMPOSED_REL_BY_KEY: dict[str, str] = dict(_MEMBER_EDGE_COMPOSED_REL_MAP)
_OVERRIDE_AXIS_COMPOSED_REL_MAP: tuple[tuple[str, str | None], ...] = (
("OVERRIDDEN_BY", None),
("OVERRIDDEN_BY.DECLARES_CLIENT", "DECLARES_CLIENT"),
("OVERRIDDEN_BY.DECLARES_PRODUCER", "DECLARES_PRODUCER"),
("OVERRIDDEN_BY.EXPOSES", "EXPOSES"),
)
_OVERRIDE_AXIS_COMPOSED_REL_BY_KEY: dict[str, str | None] = dict(_OVERRIDE_AXIS_COMPOSED_REL_MAP)
OVERRIDE_AXIS_COMPOSED_EDGE_TYPES: frozenset[str] = frozenset(_OVERRIDE_AXIS_COMPOSED_REL_BY_KEY)
def _coerce_id_list(raw: Any) -> list[str]:
"""Normalize Ladybug ``collect(DISTINCT ...)`` list results to string ids."""
if raw is None:
return []
if isinstance(raw, list):
return [str(x) for x in raw if x is not None and str(x) != ""]
s = str(raw)
return [s] if s else []
__all__ = [
"LadybugGraph",
"resolve_ladybug_path",
"SymbolHit",
"EdgeHit",
"CallEdge",
"ViaEdge",
"StageSymbol",
"RouteCaller",
"find_symbols_in_file_range",
]
def resolve_ladybug_path(explicit: str | None = None) -> str:
"""Resolve the Ladybug DB path the same way the builder does."""
if explicit:
return str(Path(explicit).expanduser())
idx = os.environ.get("JAVA_CODEBASE_RAG_INDEX_DIR", "").strip()
if idx and not idx.startswith(("s3://", "gs://", "az://")):
return str(Path(os.path.expanduser(idx.rstrip("/"))) / "code_graph.lbug")
return str((Path.cwd() / ".java-codebase-rag" / "code_graph.lbug").resolve())
@dataclass
class SymbolHit:
id: str
kind: str
name: str
fqn: str
package: str
module: str
microservice: str
filename: str
start_line: int
end_line: int
start_byte: int
end_byte: int
modifiers: list[str]
annotations: list[str]
capabilities: list[str]
role: str
signature: str
parent_id: str
resolved: bool
@dataclass
class EdgeHit:
type: str # EXTENDS | IMPLEMENTS | INJECTS
src: SymbolHit
dst: SymbolHit
mechanism: str = ""
annotation: str = ""
field_or_param: str = ""
resolved: bool = True
@dataclass
class CallEdge:
src: SymbolHit
dst: SymbolHit
confidence: float
strategy: str
source: str
call_site_line: int
call_site_byte: int
arg_count: int
resolved: bool
@dataclass
class ViaEdge:
"""Labelled edge from a previous-stage node to a stage symbol.
Populated by `trace_flow` so callers can see *why* two types ended up
in the same chain (e.g. `INJECTS` vs `IMPLEMENTS` vs `CALLS`) and at what hop
from the frontier they were reached.
"""
edge_type: str # INJECTS | EXTENDS | IMPLEMENTS | CALLS | HTTP_CALLS | ASYNC_CALLS
from_fqn: str
hop: int # 1 = direct neighbour of previous-stage frontier
caller_node_id: str = "" # Client id when edge_type is HTTP_CALLS (SCHEMA v2)
@dataclass
class StageSymbol:
"""A trace_flow stage entry: the symbol plus the edges that pulled it in.
Stage 0 (seeds) has `via=[]`. Later stages list every first-time path
from the previous frontier to `symbol`.
"""
symbol: SymbolHit
via: list[ViaEdge]
@dataclass
class RouteCaller:
caller_node_id: str
caller_node_kind: Literal["client", "producer"]
caller_microservice: str
declaring_symbol_id: str
confidence: float
match: str
target_service: str = ""
raw_uri: str = ""
topic: str = ""
broker: str = ""
def _symbol_return_for(alias: str) -> str:
"""Ladybug RETURN projection for Symbol properties, using the given node alias.
Centralised so queries that bind Symbol under a non-`s` alias (e.g. `n` in
graph-expansion / flow-tracing) don't emit `s.*` references that Ladybug
rejects with `Variable s is not in scope`.
"""
return (
f"{alias}.id AS id, {alias}.kind AS kind, {alias}.name AS name, {alias}.fqn AS fqn, "
f"{alias}.package AS package, {alias}.module AS module, "
f"{alias}.microservice AS microservice, {alias}.filename AS filename, "
f"{alias}.start_line AS start_line, {alias}.end_line AS end_line, "
f"{alias}.start_byte AS start_byte, {alias}.end_byte AS end_byte, "
f"{alias}.modifiers AS modifiers, {alias}.annotations AS annotations, "
f"{alias}.capabilities AS capabilities, "
f"{alias}.role AS role, {alias}.signature AS signature, "
f"{alias}.parent_id AS parent_id, {alias}.resolved AS resolved"
)
_SYMBOL_RETURN = _symbol_return_for("s")
def _scope_filters(
alias: str,
*,
module: str | None,
microservice: str | None,
params: dict[str, Any],
) -> list[str]:
"""Build module/microservice scoping predicates against a node alias.
Mutates `params` to bind `$module` / `$microservice` only when the
corresponding filter is set, so unused names don't leak into the
Ladybug plan.
"""
out: list[str] = []
if module:
params["module"] = module
out.append(f"{alias}.module = $module")
if microservice:
params["microservice"] = microservice
out.append(f"{alias}.microservice = $microservice")
return out
_EXTERNAL_PREFIXES = (
"java.",
"javax.",
"jakarta.",
"org.springframework.",
"lombok.",
)
_EDGE_TYPES: tuple[str, ...] = (
"EXTENDS",
"IMPLEMENTS",
"INJECTS",
"OVERRIDES",
"DECLARES",
"CALLS",
"EXPOSES",
"DECLARES_CLIENT",
"DECLARES_PRODUCER",
"HTTP_CALLS",
"ASYNC_CALLS",
)
def _type_part_fqn(sym_fqn: str) -> str:
return sym_fqn.split("#", 1)[0]
def _is_external_fqn(fqn: str) -> bool:
base = _type_part_fqn(fqn)
return any(base.startswith(p) for p in _EXTERNAL_PREFIXES)
def _row_to_symbol(row: dict[str, Any]) -> SymbolHit:
return SymbolHit(
id=row.get("id", "") or "",
kind=row.get("kind", "") or "",
name=row.get("name", "") or "",
fqn=row.get("fqn", "") or "",
package=row.get("package", "") or "",
module=row.get("module", "") or "",
microservice=row.get("microservice", "") or "",
filename=row.get("filename", "") or "",
start_line=int(row.get("start_line") or 0),
end_line=int(row.get("end_line") or 0),
start_byte=int(row.get("start_byte") or 0),
end_byte=int(row.get("end_byte") or 0),
modifiers=list(row.get("modifiers") or []),
annotations=list(row.get("annotations") or []),
capabilities=list(row.get("capabilities") or []),
role=row.get("role", "") or "",
signature=row.get("signature", "") or "",
parent_id=row.get("parent_id", "") or "",
resolved=bool(row.get("resolved", True)),
)
_SYM_COLS = (
"id", "kind", "name", "fqn", "package", "module", "microservice",
"filename", "start_line", "end_line", "start_byte", "end_byte",
"modifiers", "annotations", "capabilities", "role", "signature", "parent_id", "resolved",
)
def find_symbols_in_file_range(
graph: "LadybugGraph",
*,
filename: str,
start_line: int,
end_line: int,
) -> list[SymbolHit]:
"""Return `Symbol` rows overlapping `[start_line, end_line]` in `filename` (1-based, inclusive)."""
if start_line < 1 or end_line < start_line:
return []
q = (
f"MATCH (s:Symbol) WHERE s.filename = $fn "
f"AND s.start_line <= $hmax AND s.end_line >= $hmin "
f"RETURN {_SYMBOL_RETURN} ORDER BY s.start_line, s.end_line"
)
params = {"fn": filename, "hmax": int(end_line), "hmin": int(start_line)}
return [_row_to_symbol(r) for r in graph._rows(q, params)]
def _prefixed_symbol_row(prefix: str, row: dict[str, Any]) -> dict[str, Any]:
p = f"{prefix}_"
return {k[len(p) :]: v for k, v in row.items() if k.startswith(p)}
def _row_to_call_edge(row: dict[str, Any]) -> CallEdge:
return CallEdge(
src=_row_to_symbol(_prefixed_symbol_row("caller", row)),
dst=_row_to_symbol(_prefixed_symbol_row("callee", row)),
confidence=float(row.get("confidence") or 0.0),
strategy=str(row.get("strategy") or ""),
source=str(row.get("source") or "static"),
call_site_line=int(row.get("call_site_line") or 0),
call_site_byte=int(row.get("call_site_byte") or 0),
arg_count=int(row.get("arg_count") or 0),
resolved=bool(row.get("resolved", True)),
)
def _call_graph_needle_phantom_arity_alt(needle: str) -> str | None:
"""Map ``Type#method(123)`` → ``Type#method(?)`` for phantom callee FQNs (D1)."""
if "#" not in needle:
return None
i = needle.rfind("(")
if i <= 0 or not needle.endswith(")"):
return None
inner = needle[i + 1 : -1]
if not inner.isdigit():
return None
return needle[:i] + "(?)"
class LadybugGraph:
"""Thin wrapper around a read-only Ladybug connection.
Safe to share across threads: we hold a single `Connection`, guarded by a lock.
"""
_lock = threading.Lock()
_instance: "LadybugGraph | None" = None
_instance_path: str | None = None
def __init__(self, db_path: str) -> None:
self.db_path = db_path
self._db = ladybug.Database(db_path, read_only=True)
self._conn = ladybug.Connection(self._db)
self._conn_lock = threading.Lock()
@classmethod
def get(cls, db_path: str | None = None) -> "LadybugGraph":
resolved = resolve_ladybug_path(db_path)
with cls._lock:
if cls._instance is None or cls._instance_path != resolved:
instance = cls(resolved)
meta = instance.meta()
graph_version = int(meta.get("ontology_version") or 0)
if "error" not in meta and graph_version < _ONTOLOGY_VERSION:
raise RuntimeError(
f"Graph ontology version {graph_version} is older than the "
f"required version {_ONTOLOGY_VERSION}. "
"Rebuild the graph: `python build_ast_graph.py --source-root <repo>`, "
"or run `java-codebase-rag reprocess --source-root <repo>` for a full "
"Lance+Ladybug re-index."
)
cls._instance = instance
cls._instance_path = resolved
return cls._instance
@classmethod
def exists(cls, db_path: str | None = None) -> bool:
resolved = resolve_ladybug_path(db_path)
p = Path(resolved)
if not p.exists():
return False
# Ladybug represents DB as a directory; allow file form too (single-file DBs).
return True
# ---- low-level ----
def _rows(self, query: str, params: dict[str, Any] | None = None) -> list[dict[str, Any]]:
with self._conn_lock:
r = self._conn.execute(query, params or {})
columns = r.get_column_names()
out: list[dict[str, Any]] = []
while r.has_next():
vals = r.get_next()
out.append(dict(zip(columns, vals)))
return out
# ---- meta ----
def meta(self) -> dict[str, Any]:
_META_PR_F1 = (
"MATCH (m:GraphMeta) RETURN m.key AS key, m.ontology_version AS ontology_version, "
"m.built_at AS built_at, m.source_root AS source_root, "
"m.counts_json AS counts_json, m.parse_errors AS parse_errors, "
"m.routes_total AS routes_total, m.exposes_total AS exposes_total, "
"m.routes_by_framework AS routes_by_framework, "
"m.routes_resolved_pct AS routes_resolved_pct, "
"m.routes_from_brownfield_pct AS routes_from_brownfield_pct, "
"m.routes_by_layer AS routes_by_layer, "
"m.http_calls_total AS http_calls_total, m.async_calls_total AS async_calls_total, "
"m.http_calls_by_strategy AS http_calls_by_strategy, m.async_calls_by_strategy AS async_calls_by_strategy, "
"m.http_calls_resolved_pct AS http_calls_resolved_pct, m.async_calls_resolved_pct AS async_calls_resolved_pct, "
"m.http_clients_from_brownfield_pct AS http_clients_from_brownfield_pct, "
"m.async_producers_from_brownfield_pct AS async_producers_from_brownfield_pct, "
"m.http_calls_match_breakdown AS http_calls_match_breakdown, "
"m.async_calls_match_breakdown AS async_calls_match_breakdown, "
"m.cross_service_calls_total AS cross_service_calls_total, "
"m.pass3_skipped_cross_service AS pass3_skipped_cross_service, "
"m.pass4_exposes_suppressed_feign AS pass4_exposes_suppressed_feign, "
"m.cross_service_resolution AS cross_service_resolution"
)
_META_PR_E3 = (
"MATCH (m:GraphMeta) RETURN m.key AS key, m.ontology_version AS ontology_version, "
"m.built_at AS built_at, m.source_root AS source_root, "
"m.counts_json AS counts_json, m.parse_errors AS parse_errors, "
"m.routes_total AS routes_total, m.exposes_total AS exposes_total, "
"m.routes_by_framework AS routes_by_framework, "
"m.routes_resolved_pct AS routes_resolved_pct, "
"m.routes_from_brownfield_pct AS routes_from_brownfield_pct, "
"m.routes_by_layer AS routes_by_layer, "
"m.http_calls_total AS http_calls_total, m.async_calls_total AS async_calls_total, "
"m.http_calls_by_strategy AS http_calls_by_strategy, m.async_calls_by_strategy AS async_calls_by_strategy, "
"m.http_calls_resolved_pct AS http_calls_resolved_pct, m.async_calls_resolved_pct AS async_calls_resolved_pct, "
"m.http_clients_from_brownfield_pct AS http_clients_from_brownfield_pct, "
"m.async_producers_from_brownfield_pct AS async_producers_from_brownfield_pct, "
"m.http_calls_match_breakdown AS http_calls_match_breakdown, "
"m.async_calls_match_breakdown AS async_calls_match_breakdown, "
"m.cross_service_calls_total AS cross_service_calls_total, "
"m.pass3_skipped_cross_service AS pass3_skipped_cross_service, "
"m.cross_service_resolution AS cross_service_resolution"
)
_META_PRE_E3 = (
"MATCH (m:GraphMeta) RETURN m.key AS key, m.ontology_version AS ontology_version, "
"m.built_at AS built_at, m.source_root AS source_root, "
"m.counts_json AS counts_json, m.parse_errors AS parse_errors, "
"m.routes_total AS routes_total, m.exposes_total AS exposes_total, "
"m.routes_by_framework AS routes_by_framework, "
"m.routes_resolved_pct AS routes_resolved_pct, "
"m.routes_from_brownfield_pct AS routes_from_brownfield_pct, "
"m.routes_by_layer AS routes_by_layer, "
"m.http_calls_total AS http_calls_total, m.async_calls_total AS async_calls_total, "
"m.http_calls_by_strategy AS http_calls_by_strategy, m.async_calls_by_strategy AS async_calls_by_strategy, "
"m.http_calls_resolved_pct AS http_calls_resolved_pct, m.async_calls_resolved_pct AS async_calls_resolved_pct, "
"m.http_clients_from_brownfield_pct AS http_clients_from_brownfield_pct, "
"m.async_producers_from_brownfield_pct AS async_producers_from_brownfield_pct, "
"m.http_calls_match_breakdown AS http_calls_match_breakdown, "
"m.async_calls_match_breakdown AS async_calls_match_breakdown, "
"m.cross_service_calls_total AS cross_service_calls_total"
)
_META_PR_A2 = (
"MATCH (m:GraphMeta) RETURN m.key AS key, m.ontology_version AS ontology_version, "
"m.built_at AS built_at, m.source_root AS source_root, "
"m.counts_json AS counts_json, m.parse_errors AS parse_errors, "
"m.routes_total AS routes_total, m.exposes_total AS exposes_total, "
"m.routes_by_framework AS routes_by_framework, "
"m.routes_resolved_pct AS routes_resolved_pct"
)
_META_LEGACY = (
"MATCH (m:GraphMeta) RETURN m.key AS key, m.ontology_version AS ontology_version, "
"m.built_at AS built_at, m.source_root AS source_root, "
"m.counts_json AS counts_json, m.parse_errors AS parse_errors"
)
rows: list[dict[str, Any]]
meta_mode = "pr_f1"
try:
rows = self._rows(_META_PR_F1)
except Exception:
meta_mode = "pr_e3"
try:
rows = self._rows(_META_PR_E3)
except Exception:
meta_mode = "pre_e3"
try:
rows = self._rows(_META_PRE_E3)
except Exception:
meta_mode = "pr_a2"
try:
rows = self._rows(_META_PR_A2)
except Exception:
meta_mode = "legacy"
try:
rows = self._rows(_META_LEGACY)
except Exception as e:
return {"error": f"{e}"}
if not rows:
return {"error": "no GraphMeta node"}
row = rows[0]
counts: dict[str, Any] = _parse_ladybug_json(row.get("counts_json"))
# Ensure counts has expected keys even if empty
if not counts:
counts = {
"packages": 0, "files": 0, "types": 0, "members": 0, "phantoms": 0,
"extends": 0, "implements": 0, "injects": 0, "declares": 0, "overrides": 0,
"calls": 0, "routes": 0, "exposes": 0, "clients": 0, "declares_client": 0,
"producers": 0, "declares_producer": 0, "http_calls": 0, "async_calls": 0,
}
routes_total = exposes_total = 0
routes_resolved_pct = 0.0
routes_by_framework: dict[str, Any] = {}
routes_from_brownfield_pct = 0.0
routes_by_layer: dict[str, Any] = {}
http_calls_total = 0
async_calls_total = 0
http_calls_by_strategy: dict[str, Any] = {}
async_calls_by_strategy: dict[str, Any] = {}
http_calls_resolved_pct = 0.0
async_calls_resolved_pct = 0.0
http_clients_from_brownfield_pct = 0.0
async_producers_from_brownfield_pct = 0.0
http_calls_match_breakdown: dict[str, Any] = {}
async_calls_match_breakdown: dict[str, Any] = {}
cross_service_calls_total = 0
pass3_skipped_cross_service = 0
pass4_exposes_suppressed_feign: int | None = None
cross_service_resolution: str | None = None
if meta_mode != "legacy":
rfw_raw = row.get("routes_by_framework") or "{}"
routes_by_framework = _parse_ladybug_json(rfw_raw) if isinstance(rfw_raw, str) else (rfw_raw or {})
if not isinstance(routes_by_framework, dict):
routes_by_framework = {}
routes_total = int(row.get("routes_total") or 0)
exposes_total = int(row.get("exposes_total") or 0)
routes_resolved_pct = float(row.get("routes_resolved_pct") or 0.0)
if meta_mode in ("pr_f1", "pr_e3", "pre_e3"):
routes_from_brownfield_pct = float(row.get("routes_from_brownfield_pct") or 0.0)
rbl_raw = row.get("routes_by_layer") or "{}"
routes_by_layer = _parse_ladybug_json(rbl_raw) if isinstance(rbl_raw, str) else (rbl_raw or {})
if not isinstance(routes_by_layer, dict):
routes_by_layer = {}
http_calls_total = int(row.get("http_calls_total") or 0)
async_calls_total = int(row.get("async_calls_total") or 0)
hbs_raw = row.get("http_calls_by_strategy") or "{}"
abs_raw = row.get("async_calls_by_strategy") or "{}"
http_calls_by_strategy = _parse_ladybug_json(hbs_raw) if isinstance(hbs_raw, str) else (hbs_raw or {})
if not isinstance(http_calls_by_strategy, dict):
http_calls_by_strategy = {}
async_calls_by_strategy = _parse_ladybug_json(abs_raw) if isinstance(abs_raw, str) else (abs_raw or {})
if not isinstance(async_calls_by_strategy, dict):
async_calls_by_strategy = {}
http_calls_resolved_pct = float(row.get("http_calls_resolved_pct") or 0.0)
async_calls_resolved_pct = float(row.get("async_calls_resolved_pct") or 0.0)
http_clients_from_brownfield_pct = float(row.get("http_clients_from_brownfield_pct") or 0.0)
async_producers_from_brownfield_pct = float(row.get("async_producers_from_brownfield_pct") or 0.0)
hmb_raw = row.get("http_calls_match_breakdown") or "{}"
amb_raw = row.get("async_calls_match_breakdown") or "{}"
http_calls_match_breakdown = _parse_ladybug_json(hmb_raw) if isinstance(hmb_raw, str) else (hmb_raw or {})
if not isinstance(http_calls_match_breakdown, dict):
http_calls_match_breakdown = {}
async_calls_match_breakdown = _parse_ladybug_json(amb_raw) if isinstance(amb_raw, str) else (amb_raw or {})
if not isinstance(async_calls_match_breakdown, dict):
async_calls_match_breakdown = {}
cross_service_calls_total = int(row.get("cross_service_calls_total") or 0)
pass3_skipped_cross_service = int(row.get("pass3_skipped_cross_service") or 0)
if meta_mode == "pr_f1":
pass4_exposes_suppressed_feign = int(row.get("pass4_exposes_suppressed_feign") or 0)
raw_csr = row.get("cross_service_resolution")
cross_service_resolution = (
str(raw_csr) if raw_csr not in (None, "") else None
)
elif meta_mode == "pr_e3":
raw_csr = row.get("cross_service_resolution")
cross_service_resolution = (
str(raw_csr) if raw_csr not in (None, "") else None
)
edge_counts = {edge: 0 for edge in _EDGE_TYPES}
failed_edges: list[str] = []
for edge_type in _EDGE_TYPES:
try:
edge_rows = self._rows(
f"MATCH ()-[e:{edge_type}]->() RETURN count(e) AS n"
)
edge_counts[edge_type] = int(edge_rows[0].get("n") or 0) if edge_rows else 0
except Exception as exc:
failed_edges.append(edge_type)
log.warning("edge count query failed for %s: %s", edge_type, exc)
if len(failed_edges) == len(_EDGE_TYPES):
log.warning("edge count queries failed for all edge types; returning zeroed edge_counts")
return {
"ontology_version": int(row.get("ontology_version") or 0),
"built_at": int(row.get("built_at") or 0),
"source_root": row.get("source_root") or "",
"parse_errors": int(row.get("parse_errors") or 0),
"counts": counts,
"routes_total": routes_total,
"exposes_total": exposes_total,
"routes_by_framework": routes_by_framework,
"routes_resolved_pct": routes_resolved_pct,
"routes_from_brownfield_pct": routes_from_brownfield_pct,
"routes_by_layer": routes_by_layer,
"http_calls_total": http_calls_total,
"async_calls_total": async_calls_total,
"http_calls_by_strategy": http_calls_by_strategy,
"async_calls_by_strategy": async_calls_by_strategy,
"http_calls_resolved_pct": http_calls_resolved_pct,
"async_calls_resolved_pct": async_calls_resolved_pct,
"http_clients_from_brownfield_pct": http_clients_from_brownfield_pct,
"async_producers_from_brownfield_pct": async_producers_from_brownfield_pct,
"http_calls_match_breakdown": http_calls_match_breakdown,
"async_calls_match_breakdown": async_calls_match_breakdown,
"cross_service_calls_total": cross_service_calls_total,
"pass3_skipped_cross_service": pass3_skipped_cross_service,
"pass4_exposes_suppressed_feign": pass4_exposes_suppressed_feign,
"cross_service_resolution": cross_service_resolution,
"edge_counts": edge_counts,
"db_path": self.db_path,
}
def edge_counts_for(self, node_id: str) -> dict[str, dict[str, int]]:
rows = self._rows(
"MATCH (n {id: $id})-[e]->() "
"RETURN label(e) AS edge_type, 'out' AS direction, count(e) AS n "
"UNION ALL "
"MATCH (n {id: $id})<-[e]-() "
"RETURN label(e) AS edge_type, 'in' AS direction, count(e) AS n",
{"id": node_id},
)
out: dict[str, dict[str, int]] = {}
for row in rows:
edge_type = str(row.get("edge_type") or "")
direction = str(row.get("direction") or "")
if edge_type == "" or direction not in ("in", "out"):
continue
out.setdefault(edge_type, {"in": 0, "out": 0})
out[edge_type][direction] = int(row.get("n") or 0)
return {
edge_type: dirs
for edge_type, dirs in out.items()
if int(dirs.get("in", 0)) > 0 or int(dirs.get("out", 0)) > 0
}
def member_edge_rollup_for(self, type_id: str) -> dict[str, dict[str, int]]:
"""2-hop DECLARES member edge counts for a type Symbol (describe-time only).
Keys use dot notation and are not stored graph edge labels.
"""
params = {"id": type_id}
rollup: dict[str, dict[str, int]] = {}
for key, rel in _MEMBER_EDGE_COMPOSED_REL_MAP:
rows = self._rows(
f"MATCH (t:Symbol {{id: $id}})-[:DECLARES]->(m:Symbol)-[e:{rel}]->() "
"RETURN count(e) AS n",
params,
)
n = sum(int(r.get("n") or 0) for r in rows) if rows else 0
if n > 0:
rollup[key] = {"in": 0, "out": n}
return rollup
def member_edge_traversal_for(self, type_id: str, composed_key: str) -> list[dict[str, Any]]:
"""2-hop DECLARES member traversal for a type Symbol (neighbors dot-key path)."""
rel = _MEMBER_EDGE_COMPOSED_REL_BY_KEY.get(composed_key)
if rel is None:
return []
# Untyped [e] + label(e) filter: typed unions fail the binder when RETURN references
# columns that exist on only some rel types (same pattern as flat neighbors_v2).
return self._rows(
"MATCH (t:Symbol {id: $id})-[:DECLARES]->(m:Symbol)-[e]->(term) "
"WHERE label(e) = $rel "
"RETURN m.id AS via_id, label(e) AS stored_edge_type, "
"term.id AS other_id, e.confidence AS confidence, e.strategy AS strategy, "
"e.match AS match, e.mechanism AS mechanism, e.annotation AS annotation, "
"e.field_or_param AS field_or_param, e.source AS source, "
"e.call_site_line AS call_site_line, e.call_site_byte AS call_site_byte, "
"e.arg_count AS arg_count, e.resolved AS resolved",
{"id": type_id, "rel": rel},
)
def override_axis_traversal_for(self, method_id: str, composed_key: str) -> list[dict[str, Any]]:
"""Override-axis composed traversal for a method Symbol (neighbors dot-key path).
Uses stored ``[:OVERRIDES]`` for the dispatch hop (aligned with ``override_axis_rollup_for``
overrider ids). Base key returns overrider method ids only; composed keys return terminal
rows with full edge attr projection plus ``via_id`` (overrider method id).
"""
rel = _OVERRIDE_AXIS_COMPOSED_REL_BY_KEY.get(composed_key)
if rel is None and composed_key != "OVERRIDDEN_BY":
return []
if rel is None:
return self._rows(
"MATCH (decl:Symbol {id: $id})<-[:OVERRIDES]-(mover:Symbol) "
"RETURN mover.id AS other_id",
{"id": method_id},
)
return self._rows(
"MATCH (decl:Symbol {id: $id})<-[:OVERRIDES]-(mover:Symbol)-[e]->(term) "
"WHERE label(e) = $rel "
"RETURN mover.id AS via_id, label(e) AS stored_edge_type, "
"term.id AS other_id, e.confidence AS confidence, e.strategy AS strategy, "
"e.match AS match, e.mechanism AS mechanism, e.annotation AS annotation, "
"e.field_or_param AS field_or_param, e.source AS source, "
"e.call_site_line AS call_site_line, e.call_site_byte AS call_site_byte, "
"e.arg_count AS arg_count, e.resolved AS resolved",
{"id": method_id, "rel": rel},
)
def count_calls_for_symbol(self, origin_id: str, *, direction: Literal["in", "out"]) -> int:
"""Count CALLS edges incident on a Symbol (hints / diagnostics)."""
if direction == "out":
pattern = "MATCH (origin:Symbol {id: $id})-[e:CALLS]->() RETURN count(e) AS n"
else:
pattern = "MATCH (origin:Symbol {id: $id})<-[e:CALLS]-() RETURN count(e) AS n"
rows = self._rows(pattern, {"id": origin_id})
return int(rows[0].get("n") or 0) if rows else 0
def neighbor_calls_for_symbol(
self,
origin_id: str,
*,
direction: Literal["in", "out"],
offset: int = 0,
limit: int | None = None,
sql_pagination: bool = True,
min_confidence: float | None = None,
include_strategies: list[str] | None = None,
exclude_strategies: list[str] | None = None,
callee_declaring_role: str | None = None,
callee_declaring_roles: list[str] | None = None,
exclude_callee_declaring_roles: list[str] | None = None,
) -> list[dict[str, Any]]:
"""CALLS neighbors with source-order delivery and optional edge-attribute pushdown.
When ``sql_pagination`` is True and ``limit`` is set, ``SKIP``/``LIMIT`` apply after
``ORDER BY e.call_site_line, e.call_site_byte``. Otherwise the full ordered stream is
returned for caller-side ``NodeFilter`` / pagination.
"""
wh_parts = ["origin.id = $id"]
params: dict[str, Any] = {"id": origin_id}
if min_confidence is not None:
wh_parts.append("e.confidence >= $min_confidence")
params["min_confidence"] = min_confidence
if include_strategies:
wh_parts.append("e.strategy IN $include_strategies")
params["include_strategies"] = include_strategies
if exclude_strategies:
wh_parts.append("NOT (e.strategy IN $exclude_strategies)")
params["exclude_strategies"] = exclude_strategies
if callee_declaring_role is not None:
wh_parts.append("e.callee_declaring_role = $callee_declaring_role")
params["callee_declaring_role"] = callee_declaring_role
if callee_declaring_roles:
wh_parts.append("e.callee_declaring_role IN $callee_declaring_roles")
params["callee_declaring_roles"] = callee_declaring_roles
if exclude_callee_declaring_roles:
wh_parts.append("NOT (e.callee_declaring_role IN $exclude_callee_declaring_roles)")
params["exclude_callee_declaring_roles"] = exclude_callee_declaring_roles
where = " AND ".join(wh_parts)
if direction == "out":
match = "MATCH (origin:Symbol)-[e:CALLS]->(other:Symbol)"
else:
match = "MATCH (origin:Symbol)<-[e:CALLS]-(other:Symbol)"
q = (
f"{match} WHERE {where} "
"RETURN other.id AS other_id, 'CALLS' AS edge_type, "
"e.confidence AS confidence, e.strategy AS strategy, e.source AS source, "
"e.call_site_line AS call_site_line, e.call_site_byte AS call_site_byte, "
"e.arg_count AS arg_count, e.resolved AS resolved, "
"e.callee_declaring_role AS callee_declaring_role "
"ORDER BY e.call_site_line, e.call_site_byte"
)
if sql_pagination and limit is not None:
q += " SKIP $offset LIMIT $limit"
params["offset"] = offset
params["limit"] = limit
return self._rows(q, params)
def count_unresolved_for_caller(self, caller_id: str) -> int:
rows = self._rows(
"MATCH (:Symbol {id: $id})-[:UNRESOLVED_AT]->(u:UnresolvedCallSite) "
"RETURN count(u) AS n",
{"id": caller_id},
)
return int(rows[0].get("n") or 0) if rows else 0
def unresolved_sites_for_caller(
self,
caller_id: str,
*,
direction: Literal["in", "out"] = "out",
) -> list[dict[str, Any]]:
if direction != "out":
return []
return self._rows(
"MATCH (:Symbol {id: $id})-[:UNRESOLVED_AT]->(u:UnresolvedCallSite) "
"RETURN u.id AS id, u.caller_id AS caller_id, u.call_site_line AS call_site_line, "
"u.call_site_byte AS call_site_byte, u.arg_count AS arg_count, "
"u.callee_simple AS callee_simple, u.receiver_expr AS receiver_expr, "
"u.reason AS reason "
"ORDER BY u.call_site_line, u.call_site_byte",
{"id": caller_id},
)
def unresolved_sites_for_describe(
self,
method_id: str,
*,
inline_limit: int = 5,
) -> tuple[list[dict[str, Any]], int]:
total_rows = self._rows(
"MATCH (:Symbol {id: $id})-[:UNRESOLVED_AT]->(u:UnresolvedCallSite) "
"RETURN count(u) AS n",
{"id": method_id},
)
total = int(total_rows[0].get("n") or 0) if total_rows else 0
if total == 0:
return [], 0
rows = self._rows(
"MATCH (:Symbol {id: $id})-[:UNRESOLVED_AT]->(u:UnresolvedCallSite) "
"RETURN u.call_site_line AS line, u.reason AS reason, "
"u.callee_simple AS callee_simple, u.receiver_expr AS receiver_expr "
"ORDER BY u.call_site_line, u.call_site_byte "
f"LIMIT {int(inline_limit)}",
{"id": method_id},
)
return rows, total
def list_unresolved_call_sites(
self,
*,
method_id: str | None = None,
reason: str | None = None,
microservice: str | None = None,
callee_simple: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
wh_parts: list[str] = []
params: dict[str, Any] = {"lim": int(limit)}
if method_id:
wh_parts.append("caller.id = $method_id")
params["method_id"] = method_id
if reason:
wh_parts.append("u.reason = $reason")
params["reason"] = reason
if microservice:
wh_parts.append("caller.microservice = $microservice")
params["microservice"] = microservice
if callee_simple:
wh_parts.append("u.callee_simple = $callee_simple")
params["callee_simple"] = callee_simple
where = ("WHERE " + " AND ".join(wh_parts)) if wh_parts else ""
return self._rows(
"MATCH (caller:Symbol)-[:UNRESOLVED_AT]->(u:UnresolvedCallSite) "
f"{where} "
"RETURN u.id AS id, caller.id AS caller_id, caller.fqn AS caller_fqn, "
"caller.microservice AS microservice, u.call_site_line AS call_site_line, "
"u.call_site_byte AS call_site_byte, u.arg_count AS arg_count, "
"u.callee_simple AS callee_simple, u.receiver_expr AS receiver_expr, "
"u.reason AS reason "
"ORDER BY u.call_site_line, u.call_site_byte "
"LIMIT $lim",
params,
)
def stats_unresolved_call_sites(
self,
*,
by: Literal["reason", "microservice", "caller_role"],
) -> list[dict[str, Any]]:
if by == "reason":
return self._rows(
"MATCH (:Symbol)-[:UNRESOLVED_AT]->(u:UnresolvedCallSite) "
"RETURN u.reason AS bucket, count(*) AS n ORDER BY n DESC",
)
if by == "microservice":
return self._rows(
"MATCH (caller:Symbol)-[:UNRESOLVED_AT]->(:UnresolvedCallSite) "
"RETURN caller.microservice AS bucket, count(*) AS n ORDER BY n DESC",
)
return self._rows(
"MATCH (caller:Symbol)-[:UNRESOLVED_AT]->(:UnresolvedCallSite) "
"MATCH (parent:Symbol)-[:DECLARES]->(caller) "
"RETURN parent.role AS bucket, count(*) AS n ORDER BY n DESC",
)
def _edge_row_count_from_method_ids(self, method_ids: list[str], rel: str) -> int:
"""Count outgoing ``rel`` edges from method symbols (describe rollup helper)."""
total = 0
for mid in method_ids:
rows = self._rows(
f"MATCH (x:Symbol {{id: $mid}})-[e:{rel}]->() RETURN count(e) AS n",
{"mid": mid},
)
total += int(rows[0].get("n") or 0) if rows else 0
return total
def _override_impl_ids_from_stored(self, method_id: str) -> list[str]:
"""Overrider method ids for a declaration method (stored ``[:OVERRIDES]`` in-hop)."""
rows = self._rows(
"MATCH (decl:Symbol {id: $id})<-[:OVERRIDES]-(mover:Symbol) "
"RETURN collect(DISTINCT mover.id) AS ids",
{"id": method_id},
)
return list(dict.fromkeys(_coerce_id_list(rows[0].get("ids") if rows else None)))
def _override_decl_ids_from_stored(self, method_id: str) -> list[str]:
"""Declaration method ids overridden by a concrete method (stored ``[:OVERRIDES]`` out-hop)."""
rows = self._rows(
"MATCH (m:Symbol {id: $id})-[:OVERRIDES]->(decl:Symbol) "
"RETURN collect(DISTINCT decl.id) AS ids",
{"id": method_id},
)
return list(dict.fromkeys(_coerce_id_list(rows[0].get("ids") if rows else None)))
def override_axis_rollup_for(self, method_id: str) -> dict[str, dict[str, int]]:
"""Dispatch-axis composed keys for method Symbols (describe-time only).
Dispatch hop uses materialized ``[:OVERRIDES]`` (same as ``override_axis_traversal_for`` /
``neighbors`` dot-keys). Terminal composed counts sum outgoing edges from overrider
methods. Omits keys with zero counts. Returns ``{}`` for non-methods, constructors,
and static methods.
"""
params = {"id": method_id}
gate = self._rows(
"MATCH (m:Symbol {id: $id}) "
"WHERE m.kind = 'method' "
"AND NOT list_contains(COALESCE(m.modifiers, []), 'static') "
"RETURN 1 AS ok LIMIT 1",
params,
)
if not gate:
return {}
rollup: dict[str, dict[str, int]] = {}
impl_ids = self._override_impl_ids_from_stored(method_id)
if impl_ids:
rollup["OVERRIDDEN_BY"] = {"in": 0, "out": len(impl_ids)}
n_dc = self._edge_row_count_from_method_ids(impl_ids, "DECLARES_CLIENT")
if n_dc > 0:
rollup["OVERRIDDEN_BY.DECLARES_CLIENT"] = {"in": 0, "out": n_dc}
n_dp = self._edge_row_count_from_method_ids(impl_ids, "DECLARES_PRODUCER")
if n_dp > 0:
rollup["OVERRIDDEN_BY.DECLARES_PRODUCER"] = {"in": 0, "out": n_dp}
n_ex = self._edge_row_count_from_method_ids(impl_ids, "EXPOSES")
if n_ex > 0:
rollup["OVERRIDDEN_BY.EXPOSES"] = {"in": 0, "out": n_ex}
decl_ids = self._override_decl_ids_from_stored(method_id)
if decl_ids:
rollup["OVERRIDES"] = {"in": 0, "out": len(decl_ids)}
return rollup
def _scope_counts(self, column: str) -> dict[str, int]:
"""Generic helper: count resolved type symbols grouped by `column`.
Empty-string keys mean the builder could not infer a value
(no build-marker ancestor / no path segment under project_root).
"""
try:
rows = self._rows(
f"MATCH (s:Symbol) WHERE s.resolved "
f"AND s.kind IN ['class','interface','enum','record','annotation'] "
f"RETURN s.{column} AS bucket, count(*) AS n"
)
except Exception:
return {}
out: dict[str, int] = {}
for r in rows:
key = r.get("bucket") or ""
out[str(key)] = int(r.get("n") or 0)
return out
def module_counts(self) -> dict[str, int]:
"""Map of module name -> resolved type-symbol count."""
return self._scope_counts("module")
def microservice_counts(self) -> dict[str, int]:
"""Map of microservice name -> resolved type-symbol count."""
return self._scope_counts("microservice")
# ---- symbol-level lookups ----
def find_by_name_or_fqn(self, name_or_fqn: str, *, kinds: list[str] | None = None,
module: str | None = None,
microservice: str | None = None,
limit: int = 50) -> list[SymbolHit]:
filters = ["(s.name = $needle OR s.fqn = $needle)"]
params: dict[str, Any] = {"needle": name_or_fqn}
if kinds:
params["kinds"] = kinds
filters.append("s.kind IN $kinds")
filters.extend(_scope_filters("s", module=module, microservice=microservice, params=params))
where = " AND ".join(filters)