diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index a5ad98e..6226bf8 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -133,8 +133,22 @@ def _canonicalize_kg_path(path: str) -> str: return os.path.normcase(os.path.realpath(path)) -def _get_kg() -> KnowledgeGraph: - path = _canonicalize_kg_path(_resolve_kg_path()) +def _get_kg(canonical_path=None) -> KnowledgeGraph: + """Return the cached ``KnowledgeGraph`` for the resolved palace. + + When ``canonical_path`` is ``None`` (default), the path is resolved + from module state and canonicalized. Callers like :func:`_call_kg` + that have already captured a canonical key before entering a retry + loop should pass it through here so the dict insertion uses the same + key the caller will later use for eviction. Recomputing the key + inside this function would let ``MEMPALACE_PALACE_PATH`` rotation, + a symlink remap, or a mount remap between the captured value and + this call drift the insert and evict keys apart, stranding a closed + handle under one key while the lookup probes another. + """ + path = ( + canonical_path if canonical_path is not None else _canonicalize_kg_path(_resolve_kg_path()) + ) kg = _kg_by_path.get(path) if kg is not None: return kg @@ -164,17 +178,19 @@ def _call_kg(op): sustained race we won't win in this loop, and a hung loop is worse than a clear failure surface. - The eviction path is captured once before the retry loop rather than - re-canonicalized inside the ``except`` branch. Doing it there would - let ``realpath`` raise ``OSError`` on a transient FS hiccup (Windows - junction loss, mount remap) and mask the original - ``sqlite3.ProgrammingError``; it would also let canonicalization - drift between insert and evict, leaving the closed handle in the - cache under a key the lookup no longer matches. + The canonical path is captured once at the top and threaded through + every ``_get_kg`` call plus the eviction lookup. Doing canonicalize + only here means an ``OSError`` from ``realpath`` (transient Windows + junction loss, broken mount) surfaces cleanly before any handler + runs instead of masking a ``sqlite3.ProgrammingError`` mid-retry. + Passing the captured key through to ``_get_kg`` also locks the + insert key to the evict key even if FS or env state mutates between + attempts, preventing a closed handle from leaking under a stale + key the lookup no longer matches. """ path = _canonicalize_kg_path(_resolve_kg_path()) for attempt in range(2): - kg = _get_kg() + kg = _get_kg(path) try: return op(kg) except sqlite3.ProgrammingError: diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 277855f..f116942 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -77,7 +77,9 @@ def _patch_mcp_server(monkeypatch, config, kg): from mempalace import mcp_server monkeypatch.setattr(mcp_server, "_config", config) - monkeypatch.setattr(mcp_server, "_get_kg", lambda: kg) + # Accept varargs because production ``_get_kg`` now takes an optional + # canonical_path; ``_call_kg`` passes the captured key through. + monkeypatch.setattr(mcp_server, "_get_kg", lambda *a, **kw: kg) def _get_collection(palace_path, create=False): @@ -1928,6 +1930,91 @@ class TestKGLazyCache: mcp_server._call_kg(lambda kg: kg.query_entity("Alice")) assert calls["count"] == 2, "expected exactly one retry beyond the initial attempt" + def test_call_kg_passes_captured_path_through_resolve_drift(self, monkeypatch): + """``_call_kg`` must thread its captured canonical path through + ``_get_kg`` so insertion and eviction agree on the cache key even + when FS or env state would otherwise drift between attempts. The + end-to-end invariant: after the retry, the closed handle that was + cached under the captured path is gone (evicted) and the cache no + longer holds it under the stale key. + """ + import sqlite3 as _sqlite3 + from mempalace import mcp_server + + class _ClosedKG: + def query_entity(self, entity, **kwargs): + raise _sqlite3.ProgrammingError("Cannot operate on a closed database") + + class _FreshKG: + def query_entity(self, entity, **kwargs): + return [{"entity": entity}] + + # _resolve_kg_path returns shifting values (env rotation between + # attempts). _canonicalize_kg_path is identity so paths flow + # through verbatim. + resolved_seq = iter(["/path/v1", "/path/v2", "/path/v3"]) + monkeypatch.setattr(mcp_server, "_resolve_kg_path", lambda: next(resolved_seq)) + monkeypatch.setattr(mcp_server, "_canonicalize_kg_path", lambda p: p) + + closed = _ClosedKG() + cache = {"/path/v1": closed} + monkeypatch.setattr(mcp_server, "_kg_by_path", cache) + + get_kg_args: list = [] + + def spy_get_kg(canonical_path=None): + get_kg_args.append(canonical_path) + return cache.get(canonical_path) if canonical_path in cache else _FreshKG() + + monkeypatch.setattr(mcp_server, "_get_kg", spy_get_kg) + + result = mcp_server._call_kg(lambda kg: kg.query_entity("Alice")) + + assert result == [{"entity": "Alice"}] + # Both _get_kg calls received the captured path "/path/v1" rather + # than the drifted "/path/v2". Without pass-through, the second + # call would have used "/path/v2" and the closed handle at + # "/path/v1" would never have been evicted. + assert get_kg_args == ["/path/v1", "/path/v1"], ( + f"expected both _get_kg calls to receive captured '/path/v1', " + f"got {get_kg_args} -- captured-path pass-through broken" + ) + # Eviction landed under the captured key: the closed handle is + # gone from the cache. With drift the closed handle would still + # be at "/path/v1" because eviction would have probed "/path/v2". + assert "/path/v1" not in cache, ( + f"closed handle leaked under captured key after retry; " + f"cache state: {[(k, type(v).__name__) for k, v in cache.items()]}" + ) + + def test_call_kg_oserror_at_top_propagates_unmasked(self, monkeypatch): + """``OSError`` from ``_canonicalize_kg_path`` at the top of + ``_call_kg`` (e.g. transient Windows realpath hiccup on a stale + junction) must propagate unchanged. The fix-rationale invariant: + capturing the canonical path before the retry loop means an FS + error surfaces cleanly to the dispatcher's exception envelope + instead of getting raised inside the ``except`` branch where it + would mask a ``sqlite3.ProgrammingError``. + """ + from mempalace import mcp_server + + monkeypatch.setattr(mcp_server, "_resolve_kg_path", lambda: "/fake/path") + monkeypatch.setattr( + mcp_server, + "_canonicalize_kg_path", + lambda p: (_ for _ in ()).throw(OSError("simulated realpath failure")), + ) + + op_calls = {"n": 0} + + def op(kg): + op_calls["n"] += 1 + return None + + with pytest.raises(OSError, match="simulated realpath failure"): + mcp_server._call_kg(op) + assert op_calls["n"] == 0, "op must not run if canonicalize fails at top" + def test_canonicalize_kg_path_collapses_symlink_alias(self, tmp_path): """A symlink layer over the palace directory must collapse to one cache key — otherwise two tenants pointing at /srv/A and