Repository navigation
Description
Pre-flight checks
- I searched existing issues and PRs (closest: fix(serve): revalidate graph identity before caching contexts #3656 / fix(serve): include the learning sidecar in the graph-context cache key #3044 on the context-cache key; nothing about reload blocking)
What happened?
graphify.serve hot-reloads graph.json when its (mtime_ns, size) changes, but the reload runs inside the request that notices the change, under _GraphContextCache._lock. There is a single cache instance per server (serve.py: _ctx_cache = _GraphContextCache(...)), so that one lock covers the pinned default graph and every project_path graph. While the new file is parsed and its trigram index is built, every request on the server waits — including requests for other graphs and requests that could have been answered from the graph already in memory.
On our 91,973-node / 242 MB graph the reload takes ~19 s (_load_graph 6.1 s + _get_trigram_index 11.6 s). A nightly rebuild rewrites graph.json several times (extract, cluster-only, label), and each rewrite causes such a stall on the next request. Our MCP health check (20 s timeout) reported the server as down when it landed in one.
Expected: requests keep being answered from the current graph while the new one is loaded, and the new context is swapped in once it is ready.
Steps to reproduce
- Serve a large graph over stdio:
python -m graphify.serve graph.json. - Call
graph_statstwice (warm). - Bump the mtime of
graph.json(same content — what any rebuild does). - Send three
graph_statscalls 0.2 s apart.
Stdlib-only driver used for the numbers below:
reload_bench.py
import json, os, subprocess, sys, threading, time
PY, GRAPH = sys.argv[1], sys.argv[2]
proc = subprocess.Popen([PY, "-m", "graphify.serve", GRAPH], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, bufsize=1, encoding="utf-8")
pending, lock = {}, threading.Lock()
def reader():
for line in iter(proc.stdout.readline, ""):
try:
msg = json.loads(line)
except Exception:
continue
with lock:
ev = pending.get(msg.get("id"))
if ev:
ev[1] = time.time(); ev[0].set()
threading.Thread(target=reader, daemon=True).start()
def send(msg):
with lock:
proc.stdin.write(json.dumps(msg) + "\n"); proc.stdin.flush()
def call(i, method, params):
ev = [threading.Event(), None]
with lock:
pending[i] = ev
t0 = time.time(); send({"jsonrpc": "2.0", "id": i, "method": method, "params": params}); ev[0].wait(300)
return ev[1] - t0
call(1, "initialize", {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "bench", "version": "1"}})
send({"jsonrpc": "2.0", "method": "notifications/initialized"})
q = {"name": "graph_stats", "arguments": {}}
print(f"warm call 1: {call(2, 'tools/call', q):.2f}s")
print(f"warm call 2: {call(3, 'tools/call', q):.2f}s")
os.utime(GRAPH, None)
res = {}
ths = [threading.Thread(target=lambda k=k: res.__setitem__(k, call(10 + k, "tools/call", q))) for k in range(3)]
for t in ths:
t.start(); time.sleep(0.2)
for t in ths:
t.join()
for k in sorted(res):
print(f"after graph.json write, concurrent call {k + 1}: {res[k]:.2f}s")
print(f"next call: {call(20, 'tools/call', q):.2f}s")
proc.terminate()Error output or graph output
warm call 1 (graph_stats): 0.28s
warm call 2 (graph_stats): 0.26s
after graph.json write, concurrent call 1: 19.09s
after graph.json write, concurrent call 2: 19.16s
after graph.json write, concurrent call 3: 18.96s
next call (reloaded): 0.27s
All three calls return together after the single reload; none is served from the graph that was already loaded.
Cause
serve.py, _GraphContextCache.load(): the stat, the key comparison and _load_entry() (→ _load_graph() + _get_trigram_index()) all run while self._lock is held, and the old entry is only replaced after the new one is built. Nobody can read the old entry in the meantime, because every request is queued on the same lock.
Suggested fix
- Build the new entry outside the lock and swap it in under the lock. While a reload for a path is in flight, return the current entry for that path (stale-while-revalidate).
- Single-flight per path, so concurrent requests do not start several reloads, and a reload of one graph never blocks requests for another.
- Optional: notice the new mtime in the background and pre-warm, so the first request after a rebuild does not pay the cost either.
to_json already writes through write_json_atomic (temp file + os.replace), so serving the previous graph until the new one is parsed carries no torn-read risk.
Graphify version
0.9.107 (same behaviour on 0.9.100)
Operating System
Linux x86_64 (openSUSE Leap 16), 4 vCPU
Python Version
3.13.13
Installation Method
uv tool install "graphifyy[openai,mcp]==0.9.107", served behind mcp-proxy (stdio → streamable HTTP)
Additional Environment Details
No provider calls involved. Reproduced on a copy of the graph in a scratch directory, separate from the production server.
Activity
github-actions commentedon Nov 12, 2026
Thanks for opening this issue, @janmaticka. A maintainer will take a look soon.
If you would like to discuss it in real time, come say hi on our Discord server. For longer-form questions and ideas there is also GitHub Discussions.
To help us triage, please make sure the report includes what you expected, what actually happened, and the steps (and a small sample) to reproduce it.
safishamsi commentedon Nov 12, 2026
Fixed by #5181 (abeb4b8), released in graphify 0.9.108. Thanks @janmaticka for the report and @ayushcodes10 for the fix.
janmaticka commentedon Nov 16, 2026
Thanks for the quick fix! I re-measured on 0.9.111 and, unfortunately, in the running MCP server every concurrent request still waits for the full reload:
graph_statsright aftertouch graph.json--transport httpCause:
call_toolis a coroutine that calls_select_graph()→_ctx_cache.load()synchronously, so_load_entry()(parse + trigram index) runs on the event-loop thread. Nothing else is dispatched until it returns, so the stale-entry and single-flight branches in_GraphContextCache.load()(which look correct) never get a chance to run: there is only ever one calling thread. I assume the tests callload()from several threads directly, which the server itself never does.read_resourcehas the same pattern (_select_graph(None)).Minimal fix, verified A/B on two copies of the same graph, same harness, unpatched and patched servers running side by side:
3 concurrent requests right after
touch graph.json(26.1k-node graph,--transport http):Warm latency is unchanged within noise (0.32 vs 0.39 s), and 40 s later both servers answer in 0.22–0.23 s from the new graph.
_select_graph()and the handler still run in one synchronous stretch, so the no-await invariant noted above_select_graphholds. A narrow window remains if graph.json changes again between the two calls (then_select_graphbuilds synchronously once more); returning the context from the worker thread and binding it synchronously would close that as well.Could this be reopened? I'm happy to share the measuring script: about 60 lines of stdlib Python that run
initialize+tools/call graph_statsfrom 3 threads before and right afteros.utime(graph.json).