Skip to content

serve: any change to graph.json stalls every MCP request for the full reload (~19 s on a 92k-node graph) — reload runs under one server-wide lock #5177

Closed

Description

@janmaticka

Pre-flight checks

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

  1. Serve a large graph over stdio: python -m graphify.serve graph.json.
  2. Call graph_stats twice (warm).
  3. Bump the mtime of graph.json (same content — what any rebuild does).
  4. Send three graph_stats calls 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

  1. github-actions commented on Nov 12, 2026

    @github-actions

    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.

  2. safishamsi commented on Nov 12, 2026

    @safishamsi
    Member

    Fixed by #5181 (abeb4b8), released in graphify 0.9.108. Thanks @janmaticka for the report and @ayushcodes10 for the fix.

  3. janmaticka commented on Nov 16, 2026

    @janmaticka
    Author

    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:

    transport graph warm 3 concurrent graph_stats right after touch graph.json
    stdio (behind mcp-proxy) 92.6k nodes 0.6–0.8 s 18.98 / 19.25 / 19.24 s
    --transport http 26.1k nodes 0.32 s 3.98 / 3.98 / 3.99 s

    Cause: call_tool is 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 call load() from several threads directly, which the server itself never does. read_resource has 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:

        async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
            ...
            try:
                # build (if needed) off the event loop; concurrent callers get the stale entry meanwhile
                await anyio.to_thread.run_sync(_load_ctx, _resolve_graph_path(project_path))
                _select_graph(project_path)  # now a cache hit, or the stale entry while a build is in flight
                return [types.TextContent(type="text", text=handler(arguments))]

    3 concurrent requests right after touch graph.json (26.1k-node graph, --transport http):

    • 0.9.111: 3.98 / 3.98 / 3.99 s
    • patched: 0.56 / 0.58 / 4.05 s (only the request that triggered the rebuild waits; the other two are served the current graph)

    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_graph holds. A narrow window remains if graph.json changes again between the two calls (then _select_graph builds 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_stats from 3 threads before and right after os.utime(graph.json).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions