Skip to content

Commit d2d1f68

Browse files
safishamsiclaude
andcommitted
fix: surface silently-skipped dirs in enumeration + dedup Pascal edges
Two correctness fixes found while analysing the reported 'graphify update occasionally writes a partial graph.json' bug. Enumeration (P0): detect()'s os.walk had no onerror handler, so any os.scandir failure -- a transient PermissionError, or a directory created/deleted mid-walk by concurrent writes (e.g. benchmarking racing the scan) -- was silently swallowed and that entire subtree dropped out of the file list with no log, no error. Downstream that becomes a silently partial graph.json. The walk now records each skipped directory (surfaced as walk_errors in detect()'s result) and warns to stderr, while still enumerating the rest of the tree. This stays visible even when a --force/GRAPHIFY_FORCE rebuild bypasses the shrink guards. Relatedly, to_json's #479 anti-shrink guard was fail-OPEN: a non-empty but unreadable existing graph.json (corrupt or mid-write) proceeded with the overwrite. It now fails SAFE -- refuse and point at force=True -- while an empty/whitespace existing file (no nodes to lose) still proceeds. The size-cap check keeps running before any read, so an oversized existing file is not loaded into memory. Pascal edges (P1): a class method declared in the interface section and defined in the implementation section each emitted a "method" edge to the same node id, and the edge helpers (unlike the node helpers) did not dedup, so ~half of a Pascal/Delphi graph's method edges were doubled -- inflating degree/centrality and tripping the #1739 cross-file resolver's single-owner god-node guard. Both extractors now dedup edges on (source, target, relation). Adds regression tests for all three behaviours. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent d89efbf commit d2d1f68

7 files changed

Lines changed: 172 additions & 6 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ Full release notes with details on each version: [GitHub Releases](https://githu
44

55
## 0.9.11 (2026-07-08)
66

7+
- Fix: file enumeration no longer silently drops a directory subtree. `detect()`'s `os.walk` had no `onerror` handler, so an `os.scandir` failure (a permission error, or a directory created/deleted mid-walk by concurrent writes) was swallowed and that whole subtree vanished from the scan with no log, yielding a silently partial `graph.json`. The walk now records every skipped directory (surfaced in the result's `walk_errors`) and warns to stderr, while still enumerating the rest. Relatedly, `to_json`'s anti-shrink guard (#479) now fails safe: a non-empty but unreadable existing `graph.json` refuses the overwrite (pass `force=True` to override) instead of silently clobbering a good graph; an empty file still proceeds.
8+
- Fix: Pascal/Delphi extractors no longer emit duplicate `method`/`contains`/`inherits` edges. A class method declared in the interface section and defined in the implementation section each emitted an edge to the same node, so ~half of a Pascal graph's method edges were doubled (skewing degree/centrality and tripping the new cross-file resolver's god-node guard). Both extractors now dedup edges on (source, target, relation), mirroring the existing node dedup.
79
- Fix: Pascal/Delphi call resolution is scoped to the caller's class + inherits chain, and calls to methods inherited across file boundaries now resolve (#1739, thanks @richtext). Both extractors previously resolved every call via a single file-wide `{name: node_id}` dict, so two unrelated classes with a same-named method (property accessors, generated COM/TLB wrappers) collapsed onto whichever was inserted last, producing wrong cross-class `calls` edges. Resolution now walks own-class then ancestor chain then file-level free functions, emitting no edge when ambiguous (same god-node guard as the Ruby resolver). A new corpus-wide resolver (`graphify/pascal_resolution.py`) resolves calls from a descendant to a base-class method declared in a different file (the common generated-base/manual-descendant split). Also stops emitting a duplicate cross-file base-class stub carrying the wrong `source_file`.
810
- Fix: query ranking no longer lets a lone generic term that exact-matches a short leaf label hijack seed selection in multi-term queries (#1602/#1724, thanks @fkhawajagh). `_score_nodes` scales the per-term exact/prefix tiers by squared term coverage; single-term and full-coverage queries are unchanged.
911
- Fix: Kotlin enum entries are extracted as nodes with `case_of` edges to their enum (#1700, thanks @ivanzhilovich). Closes the Kotlin half of #1700 (the Java half shipped in 0.9.10 via #1719); `enum class ChatType { NORMAL, GROUP, SYSTEM }` now yields NORMAL/GROUP/SYSTEM nodes and "where is ChatType.X used" works for Kotlin.

graphify/detect.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1107,9 +1107,29 @@ def _wc(path: Path) -> int:
11071107
seen: set[Path] = set()
11081108
all_files: list[Path] = []
11091109

1110+
# os.walk swallows os.scandir errors by default (no onerror -> the failing
1111+
# directory subtree is silently skipped). That turns a transient
1112+
# PermissionError, or a directory created/deleted mid-walk (e.g. concurrent
1113+
# writes racing the scan), into a partial file list and, downstream, a
1114+
# silently partial graph.json. Record and surface every skipped directory
1115+
# so an incomplete enumeration is visible rather than silent.
1116+
walk_errors: list[str] = []
1117+
1118+
def _on_walk_error(err: OSError) -> None:
1119+
import sys as _sys
1120+
target = getattr(err, "filename", None) or "<unknown>"
1121+
walk_errors.append(f"{target}: {err}")
1122+
print(
1123+
f"[graphify] WARNING: could not scan {target} ({err}); "
1124+
f"its files are missing from this run's enumeration.",
1125+
file=_sys.stderr,
1126+
)
1127+
11101128
for scan_root in scan_paths:
11111129
in_memory_tree = memory_dir.exists() and str(scan_root).startswith(str(memory_dir))
1112-
for dirpath, dirnames, filenames in os.walk(scan_root, followlinks=follow_symlinks):
1130+
for dirpath, dirnames, filenames in os.walk(
1131+
scan_root, followlinks=follow_symlinks, onerror=_on_walk_error
1132+
):
11131133
dp = Path(dirpath)
11141134
if follow_symlinks and os.path.islink(dirpath):
11151135
real = os.path.realpath(dirpath)
@@ -1245,6 +1265,7 @@ def _wc(path: Path) -> int:
12451265
"warning": warning,
12461266
"skipped_sensitive": skipped_sensitive,
12471267
"unclassified": sorted(unclassified),
1268+
"walk_errors": walk_errors,
12481269
"graphifyignore_patterns": len(ignore_patterns),
12491270
"scan_root": str(root.resolve()),
12501271
}

graphify/export.py

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -184,11 +184,44 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
184184
# Safety check: refuse to silently shrink an existing graph (#479)
185185
existing_path = Path(output_path)
186186
if not force and existing_path.exists():
187+
from graphify.security import check_graph_file_size_cap
187188
try:
188-
from graphify.security import check_graph_file_size_cap
189189
check_graph_file_size_cap(existing_path)
190-
existing_data = json.loads(existing_path.read_text(encoding="utf-8"))
191-
existing_n = len(existing_data.get("nodes", []))
190+
except Exception:
191+
# Existing graph.json trips the size cap; reading it to compare would
192+
# be the very DoS the cap guards against. Can't verify — let the new
193+
# graph replace the oversized file.
194+
oversized = True
195+
else:
196+
oversized = False
197+
if not oversized:
198+
try:
199+
raw = existing_path.read_text(encoding="utf-8")
200+
except Exception:
201+
raw = ""
202+
if not raw.strip():
203+
# Empty/whitespace existing file (e.g. a freshly touched path):
204+
# no nodes to lose, so any new graph is a growth — proceed.
205+
existing_n = 0
206+
else:
207+
try:
208+
existing_data = json.loads(raw)
209+
existing_n = len(existing_data.get("nodes", []))
210+
except Exception as exc:
211+
# Non-empty but unparseable existing graph (corrupt or a
212+
# mid-write): we cannot verify the new graph is not a silent
213+
# shrink. Fail SAFE — refuse rather than overwrite. A
214+
# fail-OPEN here (the prior behavior) is the silent data-loss
215+
# path #479 exists to prevent: a transiently unreadable
216+
# graph.json would let a partial rebuild clobber a good one.
217+
import sys as _sys
218+
print(
219+
f"[graphify] WARNING: existing {existing_path} could not be "
220+
f"read to verify the new graph is not smaller ({exc}). "
221+
f"Refusing to overwrite; pass force=True to override.",
222+
file=_sys.stderr,
223+
)
224+
return False
192225
new_n = G.number_of_nodes()
193226
if new_n < existing_n:
194227
import sys as _sys
@@ -203,8 +236,6 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
203236
file=_sys.stderr,
204237
)
205238
return False
206-
except Exception:
207-
pass # unreadable existing file — proceed with write
208239

209240
node_community = _node_community_map(communities)
210241
_labels: dict[int, str] = {int(k): v for k, v in (community_labels or {}).items()}

graphify/extractors/pascal.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ def _extract_pascal_regex(path: Path) -> dict:
243243
edges: list[dict] = []
244244
seen_ids: set[str] = set()
245245
seen_call_pairs: set[tuple[str, str]] = set()
246+
seen_edges: set[tuple[str, str, str]] = set()
246247

247248
def _add_node(nid: str, label: str, line: int) -> None:
248249
if nid not in seen_ids:
@@ -256,6 +257,14 @@ def _add_node(nid: str, label: str, line: int) -> None:
256257
})
257258

258259
def _add_edge(src: str, tgt: str, relation: str, line: int, context: str | None = None) -> None:
260+
# A class method declared in the interface section and defined in the
261+
# implementation section both emit a `method` edge to the same node, so
262+
# dedup on (src, tgt, relation) to keep the graph from carrying doubled
263+
# method/contains/inherits edges (mirrors _add_node's seen_ids guard).
264+
key = (src, tgt, relation)
265+
if key in seen_edges:
266+
return
267+
seen_edges.add(key)
259268
edge: dict = {
260269
"source": src,
261270
"target": tgt,
@@ -459,6 +468,7 @@ def extract_pascal(path: Path) -> dict:
459468
nodes: list[dict] = []
460469
edges: list[dict] = []
461470
seen_ids: set[str] = set()
471+
seen_edges: set[tuple[str, str, str]] = set()
462472
proc_bodies: list[tuple[str, Any, str, str]] = []
463473
# (proc_nid, body_node, container, name_lower)
464474

@@ -478,6 +488,14 @@ def add_edge(
478488
confidence: str = "EXTRACTED", weight: float = 1.0,
479489
context: str | None = None,
480490
) -> None:
491+
# A class method declared in the interface section and defined in the
492+
# implementation section both emit a `method` edge to the same node, so
493+
# dedup on (src, tgt, relation) to keep the graph from carrying doubled
494+
# method/contains/inherits edges (mirrors add_node's seen_ids guard).
495+
key = (src, tgt, relation)
496+
if key in seen_edges:
497+
return
498+
seen_edges.add(key)
481499
edge: dict[str, Any] = {
482500
"source": src, "target": tgt, "relation": relation,
483501
"confidence": confidence, "source_file": str_path,

tests/test_detect.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1597,3 +1597,38 @@ def test_detect_unclassified_empty_when_all_supported(tmp_path):
15971597
(tmp_path / "README.md").write_text("# hi\n")
15981598
res = detect(tmp_path)
15991599
assert res.get("unclassified", []) == []
1600+
1601+
1602+
def test_detect_reports_walk_errors_key():
1603+
"""detect() always surfaces a walk_errors list so callers can tell whether
1604+
enumeration was complete."""
1605+
import tempfile
1606+
d = Path(tempfile.mkdtemp())
1607+
(d / "a.py").write_text("def f(): pass\n")
1608+
res = detect(d)
1609+
assert "walk_errors" in res
1610+
assert res["walk_errors"] == []
1611+
1612+
1613+
def test_detect_surfaces_unreadable_dir_instead_of_silent_skip(tmp_path, capsys):
1614+
"""os.walk silently skips a subtree whose scandir raises (permissions, or a
1615+
dir deleted mid-walk); that under-enumeration used to be invisible and could
1616+
yield a silently partial graph. detect() now records it in walk_errors and
1617+
warns, while still enumerating the rest of the tree."""
1618+
import os
1619+
if os.geteuid() == 0:
1620+
import pytest
1621+
pytest.skip("running as root: chmod 000 does not block scandir")
1622+
(tmp_path / "a.py").write_text("def f(): pass\n")
1623+
locked = tmp_path / "locked"
1624+
locked.mkdir()
1625+
(locked / "b.py").write_text("def g(): pass\n")
1626+
os.chmod(locked, 0o000)
1627+
try:
1628+
res = detect(tmp_path)
1629+
finally:
1630+
os.chmod(locked, 0o755) # restore for cleanup
1631+
code = res["files"]["code"]
1632+
assert any(f.endswith("a.py") for f in code) # rest of tree still enumerated
1633+
assert len(res["walk_errors"]) >= 1
1634+
assert "could not scan" in capsys.readouterr().err

tests/test_export.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -603,3 +603,39 @@ def test_backup_env_disable(tmp_path, monkeypatch):
603603
(tmp_path / "graph.json").write_text('{"nodes":[],"links":[]}')
604604
(tmp_path / ".graphify_semantic_marker").write_text("{}")
605605
assert backup_if_protected(tmp_path) is None
606+
607+
608+
def _mkG(n):
609+
import networkx as nx
610+
G = nx.Graph()
611+
for i in range(n):
612+
G.add_node(f"n{i}", label=f"n{i}", community=0)
613+
return G
614+
615+
616+
def test_to_json_refuses_shrink(tmp_path):
617+
"""#479: refuse to silently overwrite an existing graph with fewer nodes."""
618+
p = tmp_path / "graph.json"
619+
json.dump({"nodes": [{"id": f"n{i}"} for i in range(5)]}, p.open("w"))
620+
assert to_json(_mkG(2), {}, str(p), force=False) is False
621+
assert to_json(_mkG(2), {}, str(p), force=True) is True # force overrides
622+
623+
624+
def test_to_json_fails_safe_on_corrupt_existing(tmp_path):
625+
"""A non-empty but unparseable existing graph.json (corrupt or mid-write)
626+
must NOT be silently overwritten — we can't verify the new graph isn't a
627+
partial shrink, so fail safe (refuse) unless force is given."""
628+
p = tmp_path / "graph.json"
629+
p.write_text("{ this has content but is not valid json")
630+
assert to_json(_mkG(10), {}, str(p), force=False) is False
631+
assert to_json(_mkG(10), {}, str(p), force=True) is True
632+
633+
634+
def test_to_json_proceeds_on_empty_existing(tmp_path):
635+
"""An empty/whitespace existing file has no nodes to lose, so it is not a
636+
shrink risk — the write proceeds."""
637+
p = tmp_path / "graph.json"
638+
p.write_text("")
639+
assert to_json(_mkG(3), {}, str(p), force=False) is True
640+
data = json.loads(p.read_text())
641+
assert len(data["nodes"]) == 3

tests/test_pascal.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,3 +320,26 @@ def test_dfm_dispatch_registered():
320320
def test_dfm_detect_extension_registered():
321321
from graphify.detect import CODE_EXTENSIONS
322322
assert ".dfm" in CODE_EXTENSIONS
323+
324+
325+
def _dup_edges(r):
326+
from collections import Counter
327+
triples = Counter((e["source"], e["target"], e["relation"]) for e in r["edges"])
328+
return {k: v for k, v in triples.items() if v > 1}
329+
330+
331+
def test_pascal_no_duplicate_method_edges_tree_sitter():
332+
"""A class method appears in both the interface declaration and the
333+
implementation; each used to emit a `method` edge to the same node, so the
334+
graph carried doubled method/contains/inherits edges (skewing degree and
335+
breaking the cross-file inherited-call resolver's god-node guard). Edges are
336+
now deduped on (source, target, relation)."""
337+
from graphify.extract import extract_pascal
338+
r = extract_pascal(FIXTURES / "sample.pas")
339+
assert _dup_edges(r) == {}, f"duplicate edges: {_dup_edges(r)}"
340+
341+
342+
def test_pascal_no_duplicate_method_edges_regex():
343+
from graphify.extract import _extract_pascal_regex
344+
r = _extract_pascal_regex(FIXTURES / "sample.pas")
345+
assert _dup_edges(r) == {}, f"duplicate edges: {_dup_edges(r)}"

0 commit comments

Comments
 (0)