perf(load): do not hold graph.json rows and the graph at once

Loading kept every parsed row until networkx had copied it, and a separate
copy of each repeated string. Hand rows over as they are used and share
repeated strings. Drop the TypeError retry at these sites: networkx>=3.4 is
required, and a retry over consumed rows would return a partial graph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 34d86aafca)
This commit is contained in:
ajbmachon authored and safishamsi committed 2026-11-03 21:36:30 +00:00
1 parent 123da822a5
commit 787f5fd026
5 files changed
+120 -44

No files matched your search

+4 -5
View File
@@ -453,7 +453,8 @@ def load_graph(path: Path) -> nx.Graph:
from networkx.readwrite import json_graph
try:
raw = json.loads(path.read_text(encoding="utf-8"))
from graphify.paths import consumed, read_graph_json
raw = read_graph_json(path)
except (json.JSONDecodeError, OSError) as exc:
raise RuntimeError(
f"Cannot read graph file {path}: {exc}. "
@@ -468,7 +469,5 @@ def load_graph(path: Path) -> nx.Graph:
# (__main__.py) already normalizes this (#738; same class as #1198).
if "links" not in raw and "edges" in raw:
raw = dict(raw, links=raw["edges"])
try:
return json_graph.node_link_graph(raw, edges="links")
except TypeError:
return json_graph.node_link_graph(raw)
raw = dict(raw, nodes=consumed(raw["nodes"]), links=consumed(raw["links"]))
return json_graph.node_link_graph(raw, edges="links")
+18 -27
View File
@@ -1682,7 +1682,8 @@ def dispatch_command(cmd: str) -> None:
import json as _json
import networkx as _nx
_raw = _json.loads(gp.read_text(encoding="utf-8"))
from graphify.paths import consumed_graph_rows, read_graph_json
_raw = read_graph_json(gp)
if "links" not in _raw and "edges" in _raw:
_raw = dict(_raw, links=_raw["edges"])
# `query` deliberately keeps the graph undirected (unlike `path` /
@@ -1696,24 +1697,16 @@ def dispatch_command(cmd: str) -> None:
# Keep in-file markers when present (#2309): unconditionally
# overwriting them with source/target would clobber the true
# direction of a link persisted in flipped endpoint order.
_raw = dict(
_raw,
links=[
{
**link,
"_src": link.get("_src", link.get("source")),
"_tgt": link.get("_tgt", link.get("target")),
}
for link in _raw.get("links", [])
],
)
try:
G = json_graph.node_link_graph(_raw, edges="links")
except TypeError:
G = json_graph.node_link_graph(_raw)
try:
from graphify.build import graph_has_legacy_ids as _legacy
if _legacy(_raw.get("nodes", [])):
_legacy_ids = _legacy(_raw.get("nodes", []))
except Exception:
_legacy_ids = False
_rows = consumed_graph_rows(dict(_raw, links=_raw.get("links", [])))
del _raw
G = json_graph.node_link_graph(_rows, edges="links")
try:
if _legacy_ids:
print(
"[graphify] note: this graph uses the pre-#1504 node-ID scheme; "
"rebuild with `graphify extract --force` to get path-qualified IDs "
@@ -2048,7 +2041,8 @@ def dispatch_command(cmd: str) -> None:
print(f"error: graph file not found: {gp}", file=sys.stderr)
sys.exit(1)
_enforce_graph_size_cap_or_exit(gp)
_raw = json.loads(gp.read_text(encoding="utf-8"))
from graphify.paths import consumed, read_graph_json
_raw = read_graph_json(gp)
if "links" not in _raw and "edges" in _raw:
_raw = dict(_raw, links=_raw["edges"])
# Force directed so the renderer can recover stored caller→callee
@@ -2058,10 +2052,8 @@ def dispatch_command(cmd: str) -> None:
# printed relation could be one the traversed pair doesn't actually
# carry (#2074). Local to this read; serve's shared graph is untouched.
_raw = {**_raw, "directed": True, "multigraph": True}
try:
G = json_graph.node_link_graph(_raw, edges="links")
except TypeError:
G = json_graph.node_link_graph(_raw)
_raw = dict(_raw, nodes=consumed(_raw["nodes"]), links=consumed(_raw["links"]))
G = json_graph.node_link_graph(_raw, edges="links")
src_nid, src_scored, src_err = _resolve_path_endpoint(G, source_label)
tgt_nid, tgt_scored, tgt_err = _resolve_path_endpoint(G, target_label)
for _label, _nid, _err in (
@@ -2223,15 +2215,14 @@ def dispatch_command(cmd: str) -> None:
print(f"error: graph file not found: {gp}", file=sys.stderr)
sys.exit(1)
_enforce_graph_size_cap_or_exit(gp)
_raw = json.loads(gp.read_text(encoding="utf-8"))
from graphify.paths import consumed, read_graph_json
_raw = read_graph_json(gp)
if "links" not in _raw and "edges" in _raw:
_raw = dict(_raw, links=_raw["edges"])
# Force directed so the renderer can recover stored caller→callee direction.
_raw = {**_raw, "directed": True}
try:
G = json_graph.node_link_graph(_raw, edges="links")
except TypeError:
G = json_graph.node_link_graph(_raw)
_raw = dict(_raw, nodes=consumed(_raw["nodes"]), links=consumed(_raw["links"]))
G = json_graph.node_link_graph(_raw, edges="links")
nid, refusal = _resolve_single_node(G, label)
if nid is None:
print(refusal)
+34 -7
View File
@@ -571,6 +571,35 @@ def nfc(s: str) -> str:
return unicodedata.normalize("NFC", s)
def read_graph_json(path) -> dict:
"""A graph file's data with one copy of each string its rows repeat."""
shared: dict[str, str] = {}
def share(row: dict) -> dict:
for field, value in row.items():
if type(value) is str:
row[field] = shared.setdefault(value, value)
return row
return json.loads(Path(path).read_text(encoding="utf-8"), object_hook=share)
def consumed(rows: list):
"""Each row in order, let go as it is taken, so a graph built from them never holds both."""
rows.reverse()
while rows:
yield rows.pop()
def consumed_graph_rows(data: dict) -> dict:
"""``data`` for networkx to build a graph from once, stamped as ``restore_arc_direction`` stamps it."""
for link in data["links"]:
if isinstance(link, dict):
link["_src"] = link.get("_src", link.get("source"))
link["_tgt"] = link.get("_tgt", link.get("target"))
return dict(data, nodes=consumed(data["nodes"]), links=consumed(data["links"]))
def restore_arc_direction(data: dict) -> dict:
"""Stamp each link's stored direction as ``_src``/``_tgt`` before loading.
@@ -606,16 +635,14 @@ def load_node_link_graph(path_or_data):
"""
from networkx.readwrite import json_graph
data = path_or_data
if not isinstance(data, dict):
owned = not isinstance(data, dict)
if owned:
p = Path(data)
from graphify.security import check_graph_file_size_cap # lazy: security imports paths
check_graph_file_size_cap(p)
data = json.loads(p.read_text(encoding="utf-8"))
data = read_graph_json(p)
if isinstance(data, dict) and "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
if isinstance(data, dict):
data = restore_arc_direction(data)
try:
return json_graph.node_link_graph(data, edges="links")
except TypeError: # networkx too old for the edges kwarg; default is "links"
return json_graph.node_link_graph(data)
data = consumed_graph_rows(data) if owned and isinstance(data.get("links"), list) else restore_arc_direction(data)
return json_graph.node_link_graph(data, edges="links")
+5 -5
View File
@@ -13,6 +13,7 @@ import threading
from typing import NamedTuple
import networkx as nx
from networkx.readwrite import json_graph
from graphify.paths import consumed, read_graph_json
from graphify.security import sanitize_label, check_graph_file_size_cap, _CONTROL_CHAR_RE
from graphify.build import _CONFIDENCE_RANK, edge_datas, edge_evidence, has_parallel_links
from graphify.paths import default_graph_json as _default_graph_json
@@ -52,7 +53,7 @@ def _read_graph(graph_path: str) -> nx.Graph:
raise FileNotFoundError(f"Graph file not found: {resolved}")
check_graph_file_size_cap(resolved)
safe = resolved
data = json.loads(safe.read_text(encoding="utf-8"))
data = read_graph_json(safe)
if "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
# Stash the on-disk logical flag before the load-time override below:
@@ -78,10 +79,9 @@ def _read_graph(graph_path: str) -> nx.Graph:
)
except Exception:
pass
try:
G = json_graph.node_link_graph(data, edges="links")
except TypeError:
G = json_graph.node_link_graph(data)
G = json_graph.node_link_graph(
dict(data, nodes=consumed(data["nodes"]), links=consumed(data["links"])), edges="links",
)
G.graph["_logical_directed"] = _logical_directed
# node_link_graph drops top-level keys other than data["graph"], so the
# build commit export.to_json writes there is stashed by hand (#3354).
+59
View File
@@ -0,0 +1,59 @@
"""Loading graph.json must not hold the parsed rows and the graph at the same time."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from networkx.readwrite import json_graph
from graphify.paths import consumed, load_node_link_graph, restore_arc_direction
def _graph_file(tmp_path: Path, nodes: list, links: list) -> Path:
path = tmp_path / "graph.json"
path.write_text(json.dumps({"directed": False, "multigraph": True, "graph": {}, "nodes": nodes, "links": links}))
return path
def test_load_gives_the_same_graph_as_a_plain_load(tmp_path: Path) -> None:
path = _graph_file(
tmp_path,
[{"id": "b", "source_file": "x.py"}, {"id": "a", "source_file": "x.py"}],
[
{"source": "b", "target": "a", "relation": "calls", "key": 0},
{"source": "b", "target": "a", "relation": "imports", "key": 1},
{"source": "a", "target": "b", "relation": "uses", "_src": "b", "_tgt": "a", "key": 2},
],
)
plain = json_graph.node_link_graph(restore_arc_direction(json.loads(path.read_text())), edges="links")
loaded = load_node_link_graph(path)
assert list(loaded.nodes(data=True)) == list(plain.nodes(data=True))
assert list(loaded.edges(keys=True, data=True)) == list(plain.edges(keys=True, data=True))
def test_rows_share_their_repeated_strings(tmp_path: Path) -> None:
path = _graph_file(tmp_path, [{"id": "a", "source_file": "x.py"}, {"id": "b", "source_file": "x.py"}], [])
graph = load_node_link_graph(path)
assert graph.nodes["a"]["source_file"] is graph.nodes["b"]["source_file"]
def test_consumed_lets_go_of_each_row_in_order() -> None:
rows = [{"id": "a"}, {"id": "b"}]
stream = consumed(rows)
assert next(stream) == {"id": "a"}
assert rows == [{"id": "b"}]
assert next(stream) == {"id": "b"}
assert rows == []
def test_a_bad_row_fails_and_never_gives_a_partial_graph(tmp_path: Path) -> None:
path = _graph_file(tmp_path, [{"id": "a"}, {"id": {"unhashable": 1}}, {"id": "c"}], [])
with pytest.raises(TypeError):
load_node_link_graph(path)