Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions graphify/sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ def format_section(section: Section, label: str) -> str:
return "\n".join([header, *(f"Note: {n}" for n in notes), "", section.text])


_SECTION_VIEW_GRAPH_KEYS = frozenset({"_logical_directed"})


def resolve_section_query(G, query: str) -> "tuple[str | None, str]":
"""Resolve a heading label, node id or ``path::Heading`` to one section node.

Expand All @@ -186,6 +189,14 @@ def resolve_section_query(G, query: str) -> "tuple[str | None, str]":
if nid is not None and is_section_node(G.nodes[nid]):
return nid, ""
sections = G.subgraph([n for n, d in G.nodes(data=True) if is_section_node(d)])
# A subgraph view shares G.graph, so it would reuse the full graph's search
# caches (ids of nodes not in the view) or store its own over the full
# graph's. Keep public graph metadata and the logical direction flag, but
# discard other private state so future caches cannot leak into this view.
sections.graph = {
Comment on lines +193 to +196

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2  Non-string graph metadata keys can crash section lookup

A section lookup that needs the retry can raise AttributeError when the graph has a non-string metadata key.

Check that graph metadata keys are strings before calling startswith in resolve_section_query in graphify/sections.py.

Evidence · checked against the code

Expected: The resolver returns its normal section match or not-found result.
Actually: The retry’s metadata filter calls startswith on the non-string key and raises AttributeError.

  • Independent source review: The CLI caller loads a graph before calling the resolver, and the MCP caller uses its graph; these paths do not establish that all callers supply JSON-loaded graphs. The inspected tests cover retry behavior and cache isolation but do not test non-string graph metadata keys.
  • The inspected CLI and MCP call sites use graphs loaded from JSON, whose metadata keys are strings; the issue applies to callers that supply a NetworkX graph with a non-string metadata key.
  • Also reported as: Section lookup can raise an exception when the graph's metadata has a non-text key
Prompt to fix with AI
In graphify/sections.py, resolve_section_query (lines 193-196):
Problem: Non-string graph metadata keys can crash section lookup
Expected: The resolver returns its normal section match or not-found result.
Actually: The retry’s metadata filter calls `startswith` on the non-string key and raises `AttributeError`.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

k: v for k, v in G.graph.items()
if not k.startswith("_") or k in _SECTION_VIEW_GRAPH_KEYS
}
sec_nid, _ = _resolve_single_node(sections, query)
if sec_nid is not None:
return sec_nid, ""
Expand Down
79 changes: 79 additions & 0 deletions tests/test_section_subgraph_index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""get_section retry on the section view must not share the full graph's caches (#5385)."""
import networkx as nx
import pytest

from graphify.serve import _get_trigram_index, _resolve_single_node
from graphify.sections import resolve_section_query


def _graph():
G = nx.Graph()
G.add_node("readme_intro", label="Intro", node_kind="heading",
source_file="README.md", source_location="L1")
G.add_node("deploy_sh", label="deploy.sh", file_type="code", source_file="deploy.sh")
G.add_node("deploy_sh_rationale", label="deploy.sh rationale",
file_type="rationale", source_file="deploy.sh")
for i in range(50):
G.add_node(f"filler_{i}", label=f"filler {i}", file_type="code", source_file=f"f{i}.py")
return G


@pytest.mark.parametrize("warm", [False, True])
def test_non_section_query_does_not_raise(warm):
G = _graph()
if warm:
_get_trigram_index(G)
cold = resolve_section_query(_graph(), "deploy")
assert resolve_section_query(G, "deploy") == cold


def test_retry_does_not_replace_full_graph_index():
G = _graph()
resolve_section_query(G, "deploy")
assert len(_get_trigram_index(G)["ids"]) == G.number_of_nodes()
assert _resolve_single_node(G, "filler 7")[0] == "filler_7"


def test_heading_still_resolves_with_warm_index():
G = _graph()
_get_trigram_index(G)
assert resolve_section_query(G, "Intro") == ("readme_intro", "")


def _retry_view(monkeypatch, G):
from graphify import serve

calls = []
original = serve._resolve_single_node

def spy(graph, query):
calls.append((graph, query))
return original(graph, query)

monkeypatch.setattr(serve, "_resolve_single_node", spy)
resolve_section_query(G, "deploy")
assert len(calls) == 2
return calls[1][0]


def test_retry_uses_isolated_section_view(monkeypatch):
G = _graph()
G.graph["_logical_directed"] = False
_get_trigram_index(G)
full_index = G.graph["_trigram_index"]

view = _retry_view(monkeypatch, G)

assert set(view.nodes) == {"readme_intro"}
assert view.graph is not G.graph
assert view.graph["_logical_directed"] is False
assert view.graph.get("_trigram_index") is not full_index


def test_retry_drops_unknown_future_cache(monkeypatch):
G = _graph()
G.graph["_some_new_cache"] = {"full_graph_only": True}

view = _retry_view(monkeypatch, G)

assert "_some_new_cache" not in view.graph
Loading