Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3892aea30b |
No files matched your search
+13
-1
@@ -4794,7 +4794,8 @@ def dispatch_command(cmd: str) -> None:
|
||||
# graphify-out/ dir into a project that asked for external output.
|
||||
# `root` stays the scanned project so source_file/ids relativize
|
||||
# against it; conflating the two basenamed every node (#1941).
|
||||
ast_kwargs: dict = {"cache_root": out_root, "root": target}
|
||||
# One extract() per process here, so free its parse memo when done.
|
||||
ast_kwargs: dict = {"cache_root": out_root, "root": target, "release_parse_memo": True}
|
||||
if cli_max_workers is not None:
|
||||
ast_kwargs["max_workers"] = cli_max_workers
|
||||
# #2437/#2438 (the `graphify update` twin of watch's #2406 fix): an
|
||||
@@ -4940,10 +4941,13 @@ def dispatch_command(cmd: str) -> None:
|
||||
_ctx_edges.append(_ctx_edge)
|
||||
except Exception:
|
||||
_ctx_nodes, _ctx_edges = [], []
|
||||
# Only the context lists are needed; free the full parse.
|
||||
_ctx_graph = None
|
||||
if _ctx_nodes:
|
||||
ast_kwargs["resolution_context_nodes"] = _ctx_nodes
|
||||
if _ctx_edges:
|
||||
ast_kwargs["resolution_context_edges"] = _ctx_edges
|
||||
del _ctx_nodes, _ctx_edges
|
||||
print(f"[graphify extract] AST extraction on {len(code_files)} code files...")
|
||||
try:
|
||||
ast_result = _ast_extract(code_files, **ast_kwargs)
|
||||
@@ -4958,6 +4962,9 @@ def dispatch_command(cmd: str) -> None:
|
||||
sys.exit(1)
|
||||
ast_result = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
_extraction_incomplete = True # the whole AST pass was lost
|
||||
# Only extract() reads the resolution context; free it before the
|
||||
# semantic pass and graph build.
|
||||
del ast_kwargs
|
||||
stages.mark("AST extract")
|
||||
|
||||
# Semantic extraction on docs/papers/images. Check cache first.
|
||||
@@ -5574,6 +5581,11 @@ def dispatch_command(cmd: str) -> None:
|
||||
else:
|
||||
G = _build([merged], dedup=not no_dedup, dedup_llm_backend=dedup_backend, root=target)
|
||||
stages.mark("build")
|
||||
# G holds its own copy of every node and edge now. Drop the raw
|
||||
# extraction lists so cluster/analyze/export can reuse that memory.
|
||||
ast_result = sem_result = pg_result = cargo_result = fresh = {}
|
||||
cached_nodes = cached_edges = cached_hyperedges = []
|
||||
merged = {"input_tokens": merged["input_tokens"], "output_tokens": merged["output_tokens"]}
|
||||
if G.number_of_nodes() == 0:
|
||||
print(
|
||||
"[graphify extract] graph is empty — extraction produced no nodes. "
|
||||
|
||||
@@ -138,6 +138,7 @@ def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
|
||||
)
|
||||
for src, tgt, attrs in edge_rows:
|
||||
stable.add_edge(src, tgt, **attrs)
|
||||
del edge_rows # `stable` holds the edges now
|
||||
|
||||
native_result = _native_leiden(stable, resolution)
|
||||
if native_result is not None:
|
||||
|
||||
+15
-2
@@ -334,7 +334,10 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
else:
|
||||
try:
|
||||
existing_data = json.loads(raw)
|
||||
del raw
|
||||
existing_nodes = existing_data.get("nodes", [])
|
||||
# Only the node list is compared; let the links go now.
|
||||
del existing_data
|
||||
if not isinstance(existing_nodes, list):
|
||||
existing_nodes = []
|
||||
existing_n = len(existing_nodes)
|
||||
@@ -395,6 +398,8 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
file=_sys.stderr,
|
||||
)
|
||||
return False
|
||||
# The guard passed; free its copies of both graphs before export.
|
||||
del existing_nodes, new_node_list, existing_ids
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
_labels: dict[int, str] = {int(k): v for k, v in (community_labels or {}).items()}
|
||||
@@ -468,8 +473,14 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
rest = sorted(k for k in item if k not in leading)
|
||||
return {k: item[k] for k in (*leading, *rest)}
|
||||
|
||||
data["nodes"] = [_canonical(n, ("id", "label")) for n in data["nodes"]]
|
||||
data["links"] = [_canonical(link, ("source", "target", "relation")) for link in data["links"]]
|
||||
def _canonicalize_in_place(items: list, lead: tuple[str, ...]) -> None:
|
||||
# Replace each dict in place so the old one is freed at once, instead
|
||||
# of holding two full copies of the node/link lists.
|
||||
for i, item in enumerate(items):
|
||||
items[i] = _canonical(item, lead)
|
||||
|
||||
_canonicalize_in_place(data["nodes"], ("id", "label"))
|
||||
_canonicalize_in_place(data["links"], ("source", "target", "relation"))
|
||||
data["nodes"].sort(key=_json_sort_key)
|
||||
data["links"].sort(key=_json_sort_key)
|
||||
if "hyperedges" not in getattr(G, "graph", {}):
|
||||
@@ -490,6 +501,8 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
_prev = json.loads(existing_path.read_text(encoding="utf-8"))
|
||||
if isinstance(_prev, dict):
|
||||
_prev_hyperedges = _prev.get("hyperedges")
|
||||
# Only the hyperedges are read; do not hold the whole parse.
|
||||
del _prev
|
||||
except Exception:
|
||||
_prev_hyperedges = None
|
||||
if _prev_hyperedges:
|
||||
|
||||
@@ -146,6 +146,7 @@ from graphify.extractors.resolution import ( # noqa: E402,F401
|
||||
_package_entry_candidates,
|
||||
_parse_js_tree,
|
||||
_parse_python_tree,
|
||||
_parse_python_tree_cached,
|
||||
_pascal_class_stem_cache,
|
||||
_pascal_project_root,
|
||||
_pascal_resolve_class,
|
||||
@@ -10359,6 +10360,7 @@ def extract(
|
||||
max_workers: int | None = None,
|
||||
resolution_context_nodes: list[dict] | None = None,
|
||||
resolution_context_edges: list[dict] | None = None,
|
||||
release_parse_memo: bool = False,
|
||||
) -> dict:
|
||||
"""Extract AST nodes and edges from a list of code files.
|
||||
|
||||
@@ -10398,6 +10400,9 @@ def extract(
|
||||
Read-only, same contract as
|
||||
resolution_context_nodes: they widen the resolvers' view but only
|
||||
fresh results are appended to the returned nodes/edges.
|
||||
release_parse_memo: clear the Python parse memo once both resolution
|
||||
passes are done. One-shot callers (`graphify extract`) set it to
|
||||
cut peak RAM; long-lived callers keep the memo for the next run.
|
||||
"""
|
||||
paths = [Path(p) for p in paths]
|
||||
if resolution_context_nodes:
|
||||
@@ -11401,6 +11406,9 @@ def extract(
|
||||
except Exception as exc:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("Cross-file import resolution failed, skipping: %s", exc)
|
||||
if release_parse_memo:
|
||||
# Both Python resolution passes are done; the memo pins every tree.
|
||||
_parse_python_tree_cached.cache_clear()
|
||||
# An incremental build re-extracts only the changed files, so the rewire also
|
||||
# needs the unchanged ones as candidates, or it resolves less than a full build.
|
||||
_fresh_ids = {n.get("id") for n in all_nodes}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""`graphify extract` frees its whole-graph intermediates without changing output.
|
||||
|
||||
The Python parse memo pinned every tree-sitter tree (and its node wrappers)
|
||||
after AST extraction, and to_json kept copies of the old and new graphs alive
|
||||
through the write. Releasing them early must not change a byte of graph.json.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
|
||||
import networkx as nx
|
||||
import pytest
|
||||
|
||||
import graphify.__main__ as mainmod
|
||||
import graphify.export as export_mod
|
||||
from graphify.export import to_json
|
||||
|
||||
# to_json output for _graph() below, as written before the memory changes.
|
||||
EXPECTED_GRAPH_JSON = (
|
||||
'{"directed":false,"multigraph":false,"graph":{"hyperedges":[{"id":"h1","nodes":["a","b","c"],'
|
||||
'"relation":"group"}],"schema_version":1},"nodes":[{"id":"a","label":"A","community":0,'
|
||||
'"file_type":"code","norm_label":"a","source_file":"a.py"},{"id":"b","label":"B","community":0,'
|
||||
'"file_type":"code","norm_label":"b","source_file":"b.py"},{"id":"c","label":"C","community":1,'
|
||||
'"file_type":"document","norm_label":"c","source_file":"c.md"}],"links":[{"source":"b",'
|
||||
'"target":"a","relation":"calls","confidence":"EXTRACTED","confidence_score":1.0},'
|
||||
'{"source":"b","target":"c","relation":"references","confidence":"INFERRED",'
|
||||
'"confidence_score":0.55}],"hyperedges":[{"id":"h1","nodes":["a","b","c"],"relation":"group"}],'
|
||||
'"built_at_commit":"abc"}'
|
||||
)
|
||||
|
||||
|
||||
def _graph(*, hyperedges: bool = True) -> nx.Graph:
|
||||
G = nx.Graph()
|
||||
# `id` stored inline on one node: canonicalization must still put it first.
|
||||
G.add_node("b", label="B", file_type="code", source_file="b.py", id="b")
|
||||
G.add_node("a", label="A", file_type="code", source_file="a.py")
|
||||
G.add_node("c", label="C", file_type="document", source_file="c.md")
|
||||
G.add_edge("a", "b", relation="calls", confidence="EXTRACTED", _src="b", _tgt="a")
|
||||
G.add_edge("b", "c", relation="references", confidence="INFERRED")
|
||||
if hyperedges:
|
||||
G.graph["hyperedges"] = [{"id": "h1", "nodes": ["a", "b", "c"], "relation": "group"}]
|
||||
return G
|
||||
|
||||
|
||||
def test_to_json_bytes_unchanged_on_forced_and_guarded_writes(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(export_mod, "_graphify_version", lambda: None)
|
||||
communities = {0: ["a", "b"], 1: ["c"]}
|
||||
forced = tmp_path / "forced.json"
|
||||
assert to_json(_graph(), communities, str(forced), force=True, built_at_commit="abc")
|
||||
assert forced.read_text(encoding="utf-8") == EXPECTED_GRAPH_JSON
|
||||
|
||||
# The guarded write parses the existing file and frees it before exporting.
|
||||
guarded = tmp_path / "guarded.json"
|
||||
shutil.copy(forced, guarded)
|
||||
assert to_json(_graph(), communities, str(guarded), force=False, built_at_commit="abc")
|
||||
assert guarded.read_bytes() == forced.read_bytes()
|
||||
|
||||
|
||||
def test_to_json_hyperedge_wipe_warning_still_reads_previous_graph(tmp_path, capsys):
|
||||
out = tmp_path / "graph.json"
|
||||
to_json(_graph(), {0: ["a", "b", "c"]}, str(out), force=True, built_at_commit="abc")
|
||||
assert to_json(_graph(hyperedges=False), {0: ["a", "b", "c"]}, str(out),
|
||||
force=True, built_at_commit="abc")
|
||||
assert "already holds 1 hyperedge(s)" in capsys.readouterr().err
|
||||
assert json.loads(out.read_text(encoding="utf-8"))["hyperedges"] == []
|
||||
|
||||
|
||||
def test_extract_cli_releases_python_parse_memo(tmp_path, monkeypatch):
|
||||
pytest.importorskip("tree_sitter_python")
|
||||
from graphify.extractors.resolution import _parse_python_tree_cached
|
||||
|
||||
corpus = tmp_path / "corpus"
|
||||
corpus.mkdir()
|
||||
(corpus / "a.py").write_text("def helper():\n return 1\n", encoding="utf-8")
|
||||
(corpus / "b.py").write_text(
|
||||
"from a import helper\n\ndef run():\n return helper()\n", encoding="utf-8"
|
||||
)
|
||||
out_dir = tmp_path / "out"
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(
|
||||
mainmod.sys, "argv",
|
||||
["graphify", "extract", str(corpus), "--code-only", "--out", str(out_dir)],
|
||||
)
|
||||
_parse_python_tree_cached.cache_clear()
|
||||
try:
|
||||
mainmod.main()
|
||||
except SystemExit as exc:
|
||||
assert exc.code in (None, 0), f"unexpected exit code {exc.code}"
|
||||
|
||||
assert (out_dir / "graphify-out" / "graph.json").exists()
|
||||
# Both resolution passes parse a.py and b.py through the memo; it must be
|
||||
# empty once the command is done with it (it held 2 trees before).
|
||||
assert _parse_python_tree_cached.cache_info().currsize == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("release", [False, True])
|
||||
def test_extract_parse_memo_release_is_opt_in(tmp_path, release):
|
||||
pytest.importorskip("tree_sitter_python")
|
||||
from graphify.extract import extract
|
||||
from graphify.extractors.resolution import _parse_python_tree_cached
|
||||
|
||||
(tmp_path / "a.py").write_text("def helper():\n return 1\n", encoding="utf-8")
|
||||
(tmp_path / "b.py").write_text("from a import helper\n", encoding="utf-8")
|
||||
_parse_python_tree_cached.cache_clear()
|
||||
extract([tmp_path / "a.py", tmp_path / "b.py"], cache_root=tmp_path / "out",
|
||||
root=tmp_path, release_parse_memo=release)
|
||||
# Long-lived callers (watch, MCP) keep the memo warm for their next run.
|
||||
assert _parse_python_tree_cached.cache_info().currsize == (0 if release else 2)
|
||||
Reference in new issue
Block a user