perf(extract): free whole-graph intermediates early to cut peak RAM

graphify extract kept several full copies of the graph alive after they
were consumed. Release each one as soon as it is used, without changing
call order or output (graph.json is byte-identical):

- extract(): new opt-in release_parse_memo clears the Python parse memo
  once both resolution passes finish; the CLI sets it, watch/MCP/library
  callers keep the warm memo as before.
- extract CLI: drop the parsed previous graph.json once the resolution
  context is built, the context after AST extraction, and the raw
  AST/semantic/merged lists once G is built.
- to_json: canonicalize node/link dicts in place, and free the shrink
  guard copies and the previous-graph parse before writing.
- cluster._partition: drop the sorted edge rows once stable is built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015ykSAxiohPs7ei9m9DasUD
(cherry picked from commit 3892aea30b)
This commit is contained in:
tpateeq authored and safishamsi committed 2026-11-09 16:44:06 +00:00
1 parent 2643077a22
commit eb9468a906
5 files changed
+146 -3

No files matched your search

+13 -1
View File
@@ -4918,7 +4918,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
@@ -5064,10 +5065,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)
@@ -5082,6 +5086,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.
@@ -5715,6 +5722,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. "
+1
View File
@@ -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
View File
@@ -337,7 +337,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)
@@ -398,6 +401,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()}
@@ -471,8 +476,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", {}):
@@ -493,6 +504,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:
+8
View File
@@ -147,6 +147,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,
@@ -10640,6 +10641,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.
@@ -10679,6 +10681,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:
@@ -11682,6 +11687,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}
+109
View File
@@ -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)