Skip to content

Commit 456b038

Browse files
committed
fixup! fix(ingest): tie each code graph to its root and prune graphs of deleted roots (#711, slice 1)
Check unit, run 42051227576 (ADR-1122 mutation gate). Keep handler() byte-identical to main, so the gate does not charge this slice with the 182 pre-existing survivors of the whole handler. The marker is now written in _call_analyze (the graph Cortex asks upstream to build, which also answers the Codex P2 finding about the reused-graph path). _prune_precedent_graphs keeps its call site and prunes orphans beside output_dir. default_cache_dir is gone (no caller). Tests pin the marker, prune and log behaviour. Local ci_mutation_diff.py: 3 file(s), 0 failed, 0 untested. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018kyZYt8uiGG3xcmvaug2eG
1 parent 1922fb6 commit 456b038

6 files changed

Lines changed: 217 additions & 30 deletions

File tree

‎mcp_server/handlers/ingest_codebase.py‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -104,24 +104,23 @@ def _get_store() -> MemoryStore:
104104
def _default_output_dir(project_path: str) -> str:
105105
"""Default graph location under ~/.cache/cortex/code-graphs/."""
106106

107-
return str(graph_cache.default_cache_dir() / project_key(project_path))
107+
return str(
108+
Path.home() / ".cache" / "cortex" / "code-graphs" / project_key(project_path)
109+
)
108110

109111

110-
def _record_and_prune_graphs(project_path: str, output_dir: str) -> None:
111-
"""Tie ``output_dir`` to its project root, then prune orphaned graphs.
112+
def _prune_precedent_graphs(output_dir: str) -> list[str]:
113+
"""Remove the orphaned graphs beside ``output_dir`` once a graph is built.
112114
113-
Replaces the former name-prefix prune, which deleted any sibling sharing
114-
the project name's first segment (``cortex-viz-*`` for ``cortex``) and
115-
never removed a deleted worktree's graph (issue #711).
115+
A graph is orphaned when its ``cortex-root.json`` names a project root that
116+
no longer exists. The former rule matched siblings by name prefix: it
117+
deleted unrelated projects (``cortex-viz-*`` for ``cortex``) and never a
118+
deleted worktree's graph. Returns the removed directory names.
116119
117120
source: issue #711"""
118121

119-
if Path(output_dir).expanduser().is_dir():
120-
try:
121-
graph_cache.write_root_marker(output_dir, project_path)
122-
except OSError as exc:
123-
logger.warning("could not write root marker in %s: %s", output_dir, exc)
124-
graph_cache.prune_orphan_graphs(graph_cache.default_cache_dir())
122+
parent = Path(output_dir).expanduser().parent
123+
return list(graph_cache.prune_orphan_graphs(parent).removed)
125124

126125

127126
def _parse_int_or_none(raw: Any) -> int | None:
@@ -488,7 +487,8 @@ async def handler(
488487
"error": f"{type(exc).__name__}: {exc}",
489488
}
490489

491-
_record_and_prune_graphs(project_path, output_dir)
490+
# source: ADR-0399
491+
_prune_precedent_graphs(output_dir)
492492

493493
diagnostics: list[Any] = []
494494
do_symbols = top_symbols is None or top_symbols > 0

‎mcp_server/handlers/ingest_codebase_graph.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
memoise_graph_path,
1818
normalise_mcp_payload,
1919
)
20+
from mcp_server.infrastructure import code_graph_cache
2021
from mcp_server.infrastructure.memory_store import MemoryStore
2122

2223
logger = logging.getLogger(__name__)
@@ -41,7 +42,8 @@ def silent_clean_stale_graph_slot(output_dir: str) -> None:
4142

4243

4344
async def _call_analyze(project_path: str, output_dir: str, language: str) -> Any:
44-
return await call_upstream(
45+
"""Ask upstream to build the graph, then tie ``output_dir`` to its root (#711)."""
46+
payload = await call_upstream(
4547
_UPSTREAM_SERVER,
4648
"analyze_codebase",
4749
{
@@ -50,6 +52,8 @@ async def _call_analyze(project_path: str, output_dir: str, language: str) -> An
5052
"language": language,
5153
},
5254
)
55+
code_graph_cache.record_root(output_dir, project_path)
56+
return payload
5357

5458

5559
async def ensure_graph(

‎mcp_server/infrastructure/code_graph_cache.py‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,14 @@ class PruneReport:
4040
failed: tuple[str, ...]
4141

4242

43-
def default_cache_dir() -> Path:
44-
"""The cache directory ``ingest_codebase`` writes graphs into by default."""
45-
return Path.home() / ".cache" / "cortex" / "code-graphs"
43+
def record_root(graph_dir: str | Path, project_root: str | Path) -> None:
44+
"""Write the marker when ``graph_dir`` exists; a failed write is logged."""
45+
if not Path(graph_dir).expanduser().is_dir():
46+
return
47+
try:
48+
write_root_marker(graph_dir, project_root)
49+
except OSError as exc:
50+
logger.warning("could not write root marker in %s: %s", graph_dir, exc)
4651

4752

4853
def write_root_marker(graph_dir: str | Path, project_root: str | Path) -> None:
@@ -54,19 +59,21 @@ def write_root_marker(graph_dir: str | Path, project_root: str | Path) -> None:
5459
target = Path(graph_dir).expanduser()
5560
root = str(Path(project_root).expanduser().resolve())
5661
marker = target / ROOT_MARKER
57-
gated_files.write_json(marker, {"project_root": root}, indent=2)
62+
gated_files.write_json(marker, {"project_root": root})
5863
if read_root_marker(target) != root:
59-
marker.unlink(missing_ok=True)
64+
marker.unlink()
6065
logger.warning("root marker for %s was altered by redaction; removed", target)
6166

6267

6368
def read_root_marker(graph_dir: Path) -> str | None:
6469
"""The recorded project root, or None when the marker is absent or unreadable."""
6570
try:
66-
data = json.loads((graph_dir / ROOT_MARKER).read_text(encoding="utf-8"))
71+
data = json.loads((graph_dir / ROOT_MARKER).read_bytes())
6772
except (OSError, ValueError):
6873
return None
69-
root = data.get("project_root") if isinstance(data, dict) else None
74+
if not isinstance(data, dict):
75+
return None
76+
root = data.get("project_root")
7077
return root if isinstance(root, str) and root else None
7178

7279

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""ingest_codebase ties the graph it builds to its root and prunes orphans (#711)."""
2+
3+
from __future__ import annotations
4+
5+
from pathlib import Path
6+
7+
import pytest
8+
9+
from mcp_server.handlers import ingest_codebase as icb
10+
from mcp_server.handlers import ingest_codebase_graph as graphmod
11+
from mcp_server.infrastructure import code_graph_cache as graph_cache
12+
13+
14+
def test_prune_removes_orphans_beside_the_output_dir(tmp_path: Path) -> None:
15+
cache_dir = tmp_path / "cache"
16+
project = tmp_path / "proj"
17+
project.mkdir()
18+
graph_cache.write_root_marker(cache_dir / "proj-1", project)
19+
gone = tmp_path / "gone"
20+
gone.mkdir()
21+
graph_cache.write_root_marker(cache_dir / "gone-2", gone)
22+
gone.rmdir()
23+
24+
removed = icb._prune_precedent_graphs(str(cache_dir / "proj-1"))
25+
26+
assert removed == ["gone-2"]
27+
assert (cache_dir / "proj-1").is_dir()
28+
29+
30+
def test_prune_expands_a_tilde_output_dir(tmp_path: Path, monkeypatch) -> None:
31+
monkeypatch.setenv("HOME", str(tmp_path))
32+
gone = tmp_path / "gone"
33+
gone.mkdir()
34+
graph_cache.write_root_marker(tmp_path / "cache" / "gone-2", gone)
35+
gone.rmdir()
36+
37+
assert icb._prune_precedent_graphs("~/cache/proj-1") == ["gone-2"]
38+
39+
40+
@pytest.mark.asyncio
41+
async def test_analyze_call_records_the_root_of_the_graph_it_builds(
42+
tmp_path: Path, monkeypatch
43+
) -> None:
44+
project = tmp_path / "proj"
45+
project.mkdir()
46+
output_dir = tmp_path / "cache" / "proj-1"
47+
calls: list[tuple] = []
48+
49+
async def _fake_upstream(server, tool, args):
50+
calls.append((server, tool, args))
51+
output_dir.mkdir(parents=True)
52+
return {"status": "ok"}
53+
54+
monkeypatch.setattr(graphmod, "call_upstream", _fake_upstream)
55+
payload = await graphmod._call_analyze(str(project), str(output_dir), "python")
56+
57+
assert payload == {"status": "ok"}
58+
assert calls == [
59+
(
60+
"codebase",
61+
"analyze_codebase",
62+
{
63+
"path": str(project.resolve()),
64+
"output_dir": str(output_dir.resolve()),
65+
"language": "python",
66+
},
67+
)
68+
]
69+
assert graph_cache.read_root_marker(output_dir) == str(project.resolve())

‎tests_py/infrastructure/test_code_graph_cache.py‎

Lines changed: 114 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,6 @@ def _graph(cache_dir: Path, name: str, root: Path | None) -> Path:
1818
return graph_dir
1919

2020

21-
def test_default_cache_dir_is_under_the_user_cache(tmp_path: Path, monkeypatch) -> None:
22-
monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
23-
assert cache.default_cache_dir() == tmp_path / ".cache" / "cortex" / "code-graphs"
24-
25-
2621
def test_marker_records_the_resolved_root(tmp_path: Path) -> None:
2722
root = tmp_path / "proj"
2823
root.mkdir()
@@ -105,7 +100,9 @@ def test_missing_cache_dir_is_empty_report(tmp_path: Path) -> None:
105100
assert report == cache.PruneReport((), (), ())
106101

107102

108-
def test_marker_altered_by_redaction_is_removed(tmp_path: Path, monkeypatch) -> None:
103+
def test_marker_altered_by_redaction_is_removed(
104+
tmp_path: Path, monkeypatch, caplog
105+
) -> None:
109106
"""A redacted root would name a missing path and get the graph pruned."""
110107
root = tmp_path / "proj"
111108
root.mkdir()
@@ -117,9 +114,119 @@ def _redacting_write(path, data, **kwargs):
117114
return real_write(path, {"project_root": "REDACTED"}, **kwargs)
118115

119116
monkeypatch.setattr(cache.gated_files, "write_json", _redacting_write)
120-
cache.write_root_marker(graph_dir, root)
117+
with caplog.at_level(logging.WARNING, logger=cache.__name__):
118+
cache.write_root_marker(graph_dir, root)
119+
120+
assert caplog.messages == [
121+
f"root marker for {graph_dir} was altered by redaction; removed"
122+
]
121123

122124
assert not (graph_dir / cache.ROOT_MARKER).exists()
123125
assert cache.prune_orphan_graphs(graph_dir.parent).unattributed == (
124126
"proj-6666aaaa",
125127
)
128+
129+
130+
def test_tilde_paths_expand_to_home(tmp_path: Path, monkeypatch) -> None:
131+
monkeypatch.setenv("HOME", str(tmp_path))
132+
(tmp_path / "proj").mkdir()
133+
cache.write_root_marker("~/cache/proj-7777aaaa", "~/proj")
134+
graph_dir = tmp_path / "cache" / "proj-7777aaaa"
135+
assert cache.read_root_marker(graph_dir) == str((tmp_path / "proj").resolve())
136+
(tmp_path / "proj").rmdir()
137+
assert cache.prune_orphan_graphs("~/cache").removed == ("proj-7777aaaa",)
138+
139+
140+
def test_prune_logs_removed_and_unattributed(tmp_path: Path, caplog) -> None:
141+
gone = tmp_path / "gone"
142+
gone.mkdir()
143+
cache_dir = tmp_path / "cache"
144+
_graph(cache_dir, "gone-8888aaaa", gone)
145+
_graph(cache_dir, "legacy-8888bbbb", None)
146+
gone.rmdir()
147+
148+
with caplog.at_level(logging.INFO, logger=cache.__name__):
149+
cache.prune_orphan_graphs(cache_dir)
150+
151+
assert caplog.messages == [
152+
"pruned 1 orphan code graph(s): ['gone-8888aaaa']",
153+
f"1 code graph(s) under {cache_dir} carry no cortex-root.json and cannot "
154+
"be tied to a project root; kept, remove by hand if unused: "
155+
"['legacy-8888bbbb']",
156+
]
157+
158+
159+
def test_failed_removal_is_reported(tmp_path: Path, monkeypatch, caplog) -> None:
160+
gone = tmp_path / "gone"
161+
gone.mkdir()
162+
cache_dir = tmp_path / "cache"
163+
graph_dir = _graph(cache_dir, "gone-9999aaaa", gone)
164+
gone.rmdir()
165+
166+
def _refuse(path):
167+
raise OSError("busy")
168+
169+
monkeypatch.setattr(cache.shutil, "rmtree", _refuse)
170+
with caplog.at_level(logging.WARNING, logger=cache.__name__):
171+
report = cache.prune_orphan_graphs(cache_dir)
172+
173+
assert report == cache.PruneReport((), (), ("gone-9999aaaa",))
174+
assert caplog.messages == [f"could not prune orphan graph {graph_dir}: busy"]
175+
176+
177+
def test_plain_file_in_cache_is_skipped(tmp_path: Path) -> None:
178+
gone = tmp_path / "gone"
179+
gone.mkdir()
180+
cache_dir = tmp_path / "cache"
181+
_graph(cache_dir, "b-gone", gone)
182+
(cache_dir / "a-stray.txt").write_text("x", encoding="utf-8")
183+
gone.rmdir()
184+
assert cache.prune_orphan_graphs(cache_dir) == cache.PruneReport(
185+
("b-gone",), (), ()
186+
)
187+
188+
189+
def test_marker_without_a_root_string_is_unattributed(tmp_path: Path) -> None:
190+
cache_dir = tmp_path / "cache"
191+
for name, payload in (
192+
("list-1", "[]"),
193+
("empty-2", '{"project_root": ""}'),
194+
("number-3", '{"project_root": 3}'),
195+
("missing-4", '{"other": "/x"}'),
196+
):
197+
graph_dir = _graph(cache_dir, name, None)
198+
(graph_dir / cache.ROOT_MARKER).write_text(payload, encoding="utf-8")
199+
report = cache.prune_orphan_graphs(cache_dir)
200+
assert report.unattributed == ("empty-2", "list-1", "missing-4", "number-3")
201+
202+
203+
def test_record_root_writes_the_marker_when_the_dir_exists(tmp_path: Path) -> None:
204+
(tmp_path / "out").mkdir()
205+
cache.record_root(tmp_path / "out", tmp_path)
206+
assert cache.read_root_marker(tmp_path / "out") == str(tmp_path.resolve())
207+
208+
209+
def test_record_root_expands_a_tilde_dir(tmp_path: Path, monkeypatch) -> None:
210+
monkeypatch.setenv("HOME", str(tmp_path))
211+
(tmp_path / "out").mkdir()
212+
cache.record_root("~/out", tmp_path)
213+
assert cache.read_root_marker(tmp_path / "out") == str(tmp_path.resolve())
214+
215+
216+
def test_record_root_creates_nothing_for_an_absent_dir(tmp_path: Path) -> None:
217+
cache.record_root(tmp_path / "never-built", tmp_path)
218+
assert not (tmp_path / "never-built").exists()
219+
220+
221+
def test_record_root_logs_a_failed_write(tmp_path: Path, monkeypatch, caplog) -> None:
222+
(tmp_path / "out").mkdir()
223+
224+
def _refuse(graph_dir, project_root):
225+
raise OSError("read-only")
226+
227+
monkeypatch.setattr(cache, "write_root_marker", _refuse)
228+
with caplog.at_level(logging.WARNING, logger=cache.__name__):
229+
cache.record_root(tmp_path / "out", tmp_path)
230+
assert caplog.messages == [
231+
f"could not write root marker in {tmp_path / 'out'}: read-only"
232+
]

‎tests_py/test_ingest_progress.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ async def _fake_enrich(*args: Any, **kwargs: Any):
283283
monkeypatch.setattr(icb, "_pull_processes", _fake_pull_processes)
284284
monkeypatch.setattr(icb, "_enrich_process_symbols", _fake_enrich)
285285
monkeypatch.setattr(icb_pages, "write_process_pages", lambda _procs: [])
286-
monkeypatch.setattr(icb, "_record_and_prune_graphs", lambda *_: None)
286+
monkeypatch.setattr(icb, "_prune_precedent_graphs", lambda _: [])
287287

288288
reporter = FakeReporter()
289289
result = await icb.handler(
@@ -340,7 +340,7 @@ async def _fake_enrich(*args: Any, **kwargs: Any):
340340
monkeypatch.setattr(icb, "_pull_processes", _fake_pull_processes)
341341
monkeypatch.setattr(icb, "_enrich_process_symbols", _fake_enrich)
342342
monkeypatch.setattr(icb_pages, "write_process_pages", lambda _procs: [])
343-
monkeypatch.setattr(icb, "_record_and_prune_graphs", lambda *_: None)
343+
monkeypatch.setattr(icb, "_prune_precedent_graphs", lambda _: [])
344344

345345
np = NullProgress()
346346
result = await icb.handler(

0 commit comments

Comments
 (0)