fix: preserve graph relations and tagged templates
(cherry picked from commit 016d9d6ad1)
This commit is contained in:
1 parent
50e812321f
commit
1954192a8c
9 files changed
+104
-35
No files matched your search
+1
-1
@@ -60,7 +60,7 @@ After a cache hit, extraction consumes that scope to rewrite node IDs and edge
|
||||
endpoints relative to the current scan root, including when the cache was copied
|
||||
from another checkout. Module-source topology is still resolved against the
|
||||
current permitted corpus. The scope marker is internal and is not exported in
|
||||
the graph. AST cache schema 30 retires entries without this marker; the semantic
|
||||
the graph. AST cache schema 33 retires entries without this marker; the semantic
|
||||
cache is unchanged. Existing graphs with stale absolute Terraform IDs need a full
|
||||
code rebuild: `graphify extract . --code-only --force`.
|
||||
|
||||
|
||||
+17
-13
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
|
||||
from graphify.build import edge_data
|
||||
from graphify.build import edge_datas
|
||||
|
||||
# Builtin/mock names that can appear as annotation-derived nodes in pre-existing
|
||||
# graphs. Excluded from god-node ranking so they don't displace real abstractions
|
||||
@@ -410,18 +410,22 @@ def _cross_community_surprises(
|
||||
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
|
||||
result = []
|
||||
for (u, v), score in top_edges:
|
||||
data = edge_data(G, u, v)
|
||||
result.append({
|
||||
"source": G.nodes[u].get("label", u),
|
||||
"target": G.nodes[v].get("label", v),
|
||||
"source_files": [
|
||||
G.nodes[u].get("source_file", ""),
|
||||
G.nodes[v].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": data.get("relation", ""),
|
||||
"note": f"Bridges graph structure (betweenness={score:.3f})",
|
||||
})
|
||||
for data in edge_datas(G, u, v):
|
||||
result.append({
|
||||
"source": G.nodes[u].get("label", u),
|
||||
"target": G.nodes[v].get("label", v),
|
||||
"source_files": [
|
||||
G.nodes[u].get("source_file", ""),
|
||||
G.nodes[v].get("source_file", ""),
|
||||
],
|
||||
"confidence": data.get("confidence", "EXTRACTED"),
|
||||
"relation": data.get("relation", ""),
|
||||
"note": f"Bridges graph structure (betweenness={score:.3f})",
|
||||
})
|
||||
if len(result) >= top_n:
|
||||
break
|
||||
if len(result) >= top_n:
|
||||
break
|
||||
return result
|
||||
|
||||
# Build node → community map
|
||||
|
||||
+17
-10
@@ -2243,22 +2243,22 @@ def dispatch_command(cmd: str) -> None:
|
||||
except Exception:
|
||||
pass
|
||||
print(f" Degree: {G.degree(nid)}")
|
||||
from graphify.build import edge_data
|
||||
from graphify.build import edge_datas
|
||||
connections: list[tuple[str, str, dict]] = [] # (direction, neighbor_id, edge_data)
|
||||
# Classify by the edge's TRUE direction, not the loaded arc order:
|
||||
# a link persisted in flipped endpoint order carries its truth in the
|
||||
# per-edge _src marker (#2309). Markerless edges fall back to the arc
|
||||
# tail (today's behavior).
|
||||
for nb in G.successors(nid):
|
||||
_ed = edge_data(G, nid, nb)
|
||||
connections.append(
|
||||
("out" if _ed.get("_src", nid) == nid else "in", nb, _ed)
|
||||
)
|
||||
for _ed in edge_datas(G, nid, nb):
|
||||
connections.append(
|
||||
("out" if _ed.get("_src", nid) == nid else "in", nb, _ed)
|
||||
)
|
||||
for nb in G.predecessors(nid):
|
||||
_ed = edge_data(G, nb, nid)
|
||||
connections.append(
|
||||
("in" if _ed.get("_src", nb) == nb else "out", nb, _ed)
|
||||
)
|
||||
for _ed in edge_datas(G, nb, nid):
|
||||
connections.append(
|
||||
("in" if _ed.get("_src", nb) == nb else "out", nb, _ed)
|
||||
)
|
||||
if connections:
|
||||
print(f"\nConnections ({len(connections)}):")
|
||||
connections.sort(key=lambda c: G.degree(c[1]), reverse=True)
|
||||
@@ -4889,7 +4889,11 @@ def dispatch_command(cmd: str) -> None:
|
||||
# clustered path (whose DiGraph collapses both) and stays deterministic
|
||||
# across modes (#1317; node dedup also collapses shared Swift module
|
||||
# anchors emitted per importing file, #1327).
|
||||
from graphify.build import dedupe_edges as _dedupe_edges, dedupe_nodes as _dedupe_nodes
|
||||
from graphify.build import (
|
||||
dedupe_edges as _dedupe_edges,
|
||||
dedupe_nodes as _dedupe_nodes,
|
||||
has_parallel_links as _has_parallel_links,
|
||||
)
|
||||
from graphify.export import (
|
||||
backup_if_protected as _backup,
|
||||
existing_graph_node_count as _existing_graph_node_count,
|
||||
@@ -4975,6 +4979,9 @@ def dispatch_command(cmd: str) -> None:
|
||||
_cleared_semantic = _shrink[2]
|
||||
merged["nodes"] = _dedupe_nodes(merged["nodes"])
|
||||
merged["edges"] = _dedupe_edges(merged["edges"])
|
||||
merged["multigraph"] = _has_parallel_links(
|
||||
merged["edges"], directed=bool(merged.get("directed", False))
|
||||
)
|
||||
# Disambiguate colliding-basename file-node labels (#2032). This raw
|
||||
# --no-cluster path bypasses build_from_json (where the clustered path
|
||||
# gets this), so apply it directly on the merged node list.
|
||||
|
||||
+2
-3
@@ -2228,9 +2228,8 @@ def extract_js(path: Path) -> dict:
|
||||
source = _read_source_bytes(path)
|
||||
working = _normalize_ts_export_type_star(source) or source
|
||||
normalized = _normalize_ts_import_types(working, tsx=suffix == ".tsx")
|
||||
source_override = normalized if normalized is not None else (
|
||||
working if working is not source else None
|
||||
)
|
||||
working = normalized if normalized is not None else working
|
||||
source_override = working if working is not source else None
|
||||
except OSError:
|
||||
pass
|
||||
result = _extract_generic(path, config, source_override=source_override)
|
||||
|
||||
+6
-2
@@ -2579,18 +2579,21 @@ def _rebuild_code(
|
||||
disambiguate_file_labels_in_nodes as _disamb_labels,
|
||||
finalize_raw_graph_endpoints as _finalize_raw_graph_endpoints,
|
||||
qualify_csharp_method_labels_in_nodes as _qualify_cs_methods,
|
||||
has_parallel_links as _has_parallel_links,
|
||||
)
|
||||
raw_nodes = _dedupe_nodes(result.get("nodes", []))
|
||||
_disamb_labels(raw_nodes)
|
||||
_qualify_cs_methods(raw_nodes, result.get("edges", []))
|
||||
from graphify.extract import RUN_ONLY_EXTRACTION_KEYS as _RUN_ONLY_KEYS
|
||||
_directed = bool((existing_graph_data or {}).get("directed", False))
|
||||
raw_links = _dedupe_edges(result.get("edges", []))
|
||||
candidate_graph_data = {
|
||||
**{
|
||||
k: v for k, v in result.items()
|
||||
if k not in ("edges", "nodes") and k not in _RUN_ONLY_KEYS
|
||||
},
|
||||
"nodes": raw_nodes,
|
||||
"links": _dedupe_edges(result.get("edges", [])),
|
||||
"links": raw_links,
|
||||
# A first build's fresh extraction may carry no hyperedges key,
|
||||
# while a reconciled rebuild always does; write it either way so
|
||||
# the two builds of one tree give the same file.
|
||||
@@ -2598,7 +2601,8 @@ def _rebuild_code(
|
||||
# Inherit the existing graph's directed flag (#2342) so
|
||||
# `graphify update --no-cluster` can't silently drop it -
|
||||
# `result` (the raw merged extraction) never carries one.
|
||||
"directed": bool((existing_graph_data or {}).get("directed", False)),
|
||||
"directed": _directed,
|
||||
"multigraph": _has_parallel_links(raw_links, directed=_directed),
|
||||
}
|
||||
# This path writes the raw merged extraction, not a build_from_json
|
||||
# graph, so mint the same external stubs the builder does — otherwise
|
||||
|
||||
+8
-6
@@ -6,7 +6,7 @@ from pathlib import Path
|
||||
import re
|
||||
import networkx as nx
|
||||
|
||||
from graphify.build import edge_data
|
||||
from graphify.build import edge_datas
|
||||
from graphify.paths import stem_filename_budget, write_text_atomic_if_changed
|
||||
|
||||
# Room _unique_slug needs for the collision suffix ("_2" … "_9999") it appends
|
||||
@@ -218,12 +218,14 @@ def _god_node_article(G: nx.Graph, nid: str, labels: dict[int, str], node_commun
|
||||
by_relation: dict[str, list[str]] = {}
|
||||
for neighbor in sorted(G.neighbors(nid), key=lambda n: G.degree(n), reverse=True):
|
||||
nd = G.nodes[neighbor]
|
||||
ed = edge_data(G, nid, neighbor)
|
||||
rel = ed.get("relation", "related")
|
||||
neighbor_label = nd.get("label", neighbor)
|
||||
conf = ed.get("confidence", "")
|
||||
conf_str = f" `{conf}`" if conf else ""
|
||||
by_relation.setdefault(rel, []).append(f"{_md_link(neighbor_label, resolver)}{conf_str}")
|
||||
for ed in edge_datas(G, nid, neighbor):
|
||||
rel = ed.get("relation", "related")
|
||||
conf = ed.get("confidence", "")
|
||||
conf_str = f" `{conf}`" if conf else ""
|
||||
by_relation.setdefault(rel, []).append(
|
||||
f"{_md_link(neighbor_label, resolver)}{conf_str}"
|
||||
)
|
||||
|
||||
lines += ["## Connections by Relation", ""]
|
||||
for rel, targets in sorted(by_relation.items()):
|
||||
|
||||
@@ -620,6 +620,20 @@ def test_update_no_cluster_writes_raw_graph(tmp_path):
|
||||
assert all("community" not in node for node in data["nodes"])
|
||||
|
||||
|
||||
def test_extract_no_cluster_marks_parallel_links_as_multigraph(tmp_path):
|
||||
src = tmp_path / "sample.ts"
|
||||
src.write_text(
|
||||
"function owner() { function child() { return 1 } return child() }\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
r = _run(["extract", ".", "--code-only", "--no-cluster"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
|
||||
data = json.loads((tmp_path / "graphify-out" / "graph.json").read_text())
|
||||
assert data.get("multigraph") is True
|
||||
|
||||
|
||||
# Regression test for #934 - cluster-only crashes when graphify-out/ doesn't exist
|
||||
|
||||
def test_cluster_only_creates_output_dir_when_missing(tmp_path):
|
||||
|
||||
@@ -57,6 +57,29 @@ def test_caller_shows_callee_as_outbound(monkeypatch, tmp_path, capsys):
|
||||
assert "<-- " not in out
|
||||
|
||||
|
||||
def test_explain_lists_parallel_relations(monkeypatch, tmp_path, capsys):
|
||||
graph_data = {
|
||||
"directed": False,
|
||||
"multigraph": True,
|
||||
"graph": {},
|
||||
"nodes": [
|
||||
{"id": "owner", "label": "Owner()", "source_file": "app.ts"},
|
||||
{"id": "child", "label": "child()", "source_file": "app.ts"},
|
||||
],
|
||||
"links": [
|
||||
{"source": "owner", "target": "child", "relation": "contains", "confidence": "EXTRACTED"},
|
||||
{"source": "owner", "target": "child", "relation": "calls", "confidence": "EXTRACTED"},
|
||||
],
|
||||
}
|
||||
p = tmp_path / "graph.json"
|
||||
p.write_text(json.dumps(graph_data))
|
||||
|
||||
out = _run(monkeypatch, p, "Owner", capsys)
|
||||
|
||||
assert "--> child() [contains]" in out
|
||||
assert "--> child() [calls]" in out
|
||||
|
||||
|
||||
def test_explain_source_file_path_prefers_file_level_node(monkeypatch, tmp_path, capsys):
|
||||
source_file = "app/api/example/route.ts"
|
||||
graph_data = {
|
||||
|
||||
@@ -88,6 +88,22 @@ def test_ts_generics_as_and_jsx_logical_and_are_silent(tmp_path, capsys):
|
||||
_assert_silent(capsys.readouterr().err)
|
||||
|
||||
|
||||
def test_ts_generic_tagged_template_preserves_symbols(tmp_path, capsys):
|
||||
# TypeScript accepts generic tagged templates such as the typed postgres
|
||||
# query form used by this corpus, but tree-sitter-typescript 0.23 parses
|
||||
# the angle brackets as a recovery error and drops the file's symbols.
|
||||
r = _extract(tmp_path, {
|
||||
"queries.ts": (
|
||||
"declare function sql<T>(strings: TemplateStringsArray): T;\n"
|
||||
"export function loadRows() {\n"
|
||||
" return sql<{ id: string }[]>`select id from rows`;\n"
|
||||
"}\n"
|
||||
),
|
||||
})
|
||||
assert "loadRows()" in _labels(r)
|
||||
_assert_silent(capsys.readouterr().err)
|
||||
|
||||
|
||||
def test_ts_genuinely_broken_file_still_warns(tmp_path, capsys):
|
||||
# `function f( {` dissolves the whole parse — nothing beyond the file
|
||||
# node extracts. The warning must fire and name the file + first line.
|
||||
|
||||
Reference in new issue
Block a user