agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

Bug: entity-graph query/traversal (graph-query query + startNodeId) heartbeat-crashes past ~25K nodes on FRESH corpora — needs the per-node edge index #816 references

Open allandelmare opened this issue 5 months ago • 3 comments

Generated with Claude Code from hands-on testing + code reading against a large corpus. Apologies for any AI-slop — push back on anything wrong.

Companion to #825 (write-side) and the now-closed #814/#816 (hot path). This tracks the read-side gap: the entity-graph query and traversal API (mem::graph-query with query or startNodeId) still enumerates the full graph and heartbeat-crashes past ~25K nodes — and unlike #825, this affects freshly-built corpora, not just legacy ones.

Why this is separate from #814/#816 and #825

  • #814/#816 (merged, ✅): the overview hot path (empty-body graph/query + graph/stats) now serves a bounded top-N snapshot and degrades gracefully. Verified clean on a ~75K-node corpus.
  • #825 (open): the write path (snapshot-rebuild, graph-reset) crashes on state::list — a repair/migration concern for legacy corpora.
  • This issue (read path): mem::graph-query with a query string or startNodeId still does the full kv.list<GraphNode>(KV.graphNodes) + kv.list<GraphEdge>(KV.graphEdges) pair (graph.ts ~L661-662), then filters/walks in memory. That's the same crashing primitive — but it's the actual graph-traversal feature, and it has no size guard, so it bites every user who crosses ~25K, including those who built the graph cleanly via incremental extraction post-#816.

Verified mechanism

graph-extract is enumeration-free (targeted kv.get/set on a name-index + degree counters), so a fresh corpus rebuilds to 75K+ on disk with the snapshot kept current — confirmed. But the full node/edge sets still live in KV.graphNodes/KV.graphEdges, so the moment you call:

POST /agentmemory/graph/query {"query": "stripe"}      # text search across the graph
POST /agentmemory/graph/query {"startNodeId": "<id>"}  # BFS traversal from a node

…it enumerates those scopes → multi-MB JSON.parse → worker heartbeat starved → Invocation stopped at ~0.35s + worker reconnect. (Same death we documented three other ways in #825; it's the identical kv.list pair on the same scope, so mechanism-certain.) The withTimeout(..., LIVE_ENUMERATION_BUDGET_MS) race intended to fall back to the snapshot can't fire — the heartbeat deadline (~0.35s) is far shorter than the 6s budget, and a synchronous parse blocks the timer too.

The code already names the fix in its own timeout-fallback warning:

"Query / startNodeId paths degrade on >25K-node corpora until a per-node edge index lands. Result reflects top-degree snapshot, not the requested walk."

There's no open issue tracking that index — this is it.

Impact

For any corpus past ~25K nodes, the entity graph is buildable and viewable as a top-N overview, but not queryable or traversable. The graph-traversal recall capability (search the graph, expand from a node) — arguably the differentiating feature of having a graph at all — has no production path at scale. This is independent of #825: even after a clean reset + full incremental rebuild, the graph would re-cross 25K and these paths would crash again.

(Note: day-to-day smart-search/recall is unaffected — search.ts enumerates the memories and sessions scopes, which are small, and doesn't consult KV.graphNodes in the hot path. So this is specifically about the explicit graph query/traversal surface, not core recall.)

Suggested direction (per-node adjacency index)

The degree counter (KV.graphNodeDegree) and name index (KV.graphNameIndex) already prove the pattern: maintain small per-key indexes incrementally during graph-extract, never enumerate on read.

  • Traversal (startNodeId BFS): add KV.graphNodeEdges (nodeId → adjacency list of edge ids/neighbor ids), written incrementally alongside the degree counter on each extract. BFS then reads only the adjacency of visited nodes via targeted kv.get — O(result size), not O(total nodes). No kv.list.
  • Text query (query string): reuse/extend the existing KV.graphNameIndex (already maintained for dedup) into a token→nodeId index so text search resolves via targeted lookups instead of scanning every node's properties.
  • Both eliminate the kv.list from the read path entirely, matching the enumeration-free design the hot path and extract already follow.

(The deeper alternative is the closed #309 — moving graph state to an indexed store. A per-node adjacency index is the in-KV middle path that doesn't require unpinning iii v0.11.2.)

Related

  • #825 — write-side (rebuild/reset) crash, same state::list root cause
  • #814 / #816 — hot-path snapshot fix (merged); introduced the "until a per-node edge index lands" caveat this issue tracks
  • #309 (closed) — the indexed-store architectural epic that would have covered both read and write
  • #345 — concept-edge recall graph (a different graph: concepts[] co-occurrence for ranking, not the entity graph) — flagging because its KV.conceptEdges BFS could hit the same scaling wall if it lands without targeted-index access

Standing offer

We have the >50K repro (680 sessions / ~75K nodes / 344 MB), a backup, and a one-command rebuild-and-test loop. Push any branch with a per-node edge index and we'll report query/startNodeId latency + worker-reconnect deltas against the real corpus.

Environment

  • agentmemory b494f23 (merged #816 head), node dist/cli.mjs
  • macOS Darwin 25.2.0 arm64, Node 26 (Homebrew), iii-engine pinned v0.11.2
  • LLM/embeddings: OpenRouter (gemini-2.5-flash-lite + openai/text-embedding-3-small)

allandelmare avatar Jun 04 '26 20:06 allandelmare

Re-test on released v0.9.28 and on PR #893, against the same >50K corpus, via Claude Code. Push back on anything that reads wrong.

Two datapoints: the shipped release still reproduces this, and I took up my own standing offer and built PR #893 ("Serve graph reads from side-indexes instead of full enumeration") against the real corpus. Fresh backup first; data intact throughout both runs (131/133 memories, 691 sessions, snapshot unchanged).

1. Released v0.9.28 — still reproduces

POST /graph/query {}                                    -> 200  0.039s  reconnect +0   (hot path — healthy)
POST /graph/query {"query":"stripe"}                    -> 500  0.691s  reconnect +1   {"error":"Invocation stopped"}
POST /graph/query {"startNodeId":"gn_mq726k2m_7b50..."} -> 500  0.569s  reconnect +1   {"error":"Invocation stopped"}

graph.ts is byte-identical between v0.9.27 and v0.9.28, so this is expected — logging it so the issue has a released-build datapoint. The kv.list<GraphNode> + kv.list<GraphEdge> pair at graph.ts:714-715 and the "until a per-node edge index lands" caveat at :734 are both still present on main (0.9.29) as of today.

Server log confirms the race is still unwinnable:

[agentmemory] warn Graph query enumeration timed out, using snapshot
  {"error":"graph-query enumeration: exceeded 6000ms budget"}

— emitted after the worker already died and reconnected. So the intended snapshot fallback never serves; the caller gets a 500, not a degrade. (Same as reported in June; re-confirming it holds on the release.)

2. PR #893 — correct architecture, but it cannot seed a legacy corpus

I built e2608e3 from source and pointed it at the same corpus. The index design looks right and its own parity suite is green (10/10, test/graph-index-parity.test.ts) — but on this corpus the read paths still crash identically:

boot                                                    -> 2 worker registrations (released v0.9.28 boots with 1)
POST /graph/query {}                                    -> 200  0.035s  reconnect +0
POST /graph/query {"query":"stripe"}                    -> 500  0.587s  reconnect +1
POST /graph/query {"startNodeId":"gn_mq726k2m_7b50..."} -> 500  0.374s  reconnect +1
POST /graph/snapshot-rebuild                            -> 500  0.449s  reconnect +1

The extra boot registration is the tell. The new backfill in src/index.ts gates like this:

const totalNodes = graphSnap?.stats?.totalNodes ?? 0;
if (graphSnap && totalNodes > 0 && totalNodes <= GRAPH_INDEX_NODE_CEILING) {
  const [graphNodes, graphEdges] = await Promise.all([
    kv.list<GraphNode>(KV.graphNodes),
    kv.list<GraphEdge>(KV.graphEdges),
  ]);
  await backfillGraphIndexes(...);
}

On this corpus stats.totalNodes is 108 (a healthy post-reset incremental snapshot), so the gate passes — and then kv.list enumerates the ~75K pre-reset orphan rows still sitting in those scopes, starving the heartbeat. The worker dies mid-backfill at boot.

Notably, neither the Backfilled graph read indexes success line nor the Failed to backfill graph indexes warn appears in the log — the worker dies inside the await, so the try/catch never resolves either way. It fails silently.

Consequence: graphIndexesReady is never set → retrieval falls back to full enumeration (as the code comment says it will, "so skipping here is safe (just slower)") → query and startNodeId crash exactly as before. On a legacy corpus this PR is a no-op for the bug it targets, at the cost of one extra worker reconnect per boot.

This is the same failure shape as #825's rebuild guard: gating on the snapshot's self-reported node count while the enumeration cost is set by the on-disk row count. After a graph-reset those two numbers are unrelated by construction (see #1189, filed independently today: reset leaves the raw rows on disk). CodeRabbit flagged this exact risk in review on the PR — "If stale graph records have accumulated, this can exceed the intended ceiling" — and this corpus is the concrete instance.

Detailed notes are on the PR itself.

What would make #893 land for corpora like this

Suggestions, not demands — the index design is the right call and I'd like to see it merged:

  • Seed incrementally rather than in one shot. Walk in bounded batches, persisting progress, so no single call has to survive the whole corpus; set the readiness marker only when the walk completes. Needs a cursor/pagination primitive on state::list, which is the same missing piece #825 runs into.
  • Don't trust stats.totalNodes as a proxy for enumeration cost. If a cheap on-disk count isn't available, treat "snapshot has resetAt" as "orphans may exist → size unknown → skip backfill" rather than "small → safe".
  • Make the silent failure loud. Even if the backfill can't be made safe, a boot-time refusal with a log line beats a swallowed worker crash — right now there's no way to tell from the logs that indexing didn't happen.

Standing offer

Unchanged and still good: >50K repro (691 sessions / ~75K pre-reset rows / 335 MB), backups, one-command build-and-test loop. Push any revision of #893 — or any branch touching the adjacency index — and I'll report query/startNodeId latency plus worker-reconnect deltas against the real corpus, usually within the hour.

Environment

  • agentmemory v0.9.28 (released, npm global) and PR #893 @ e2608e3 built from source (node dist/cli.mjs)
  • macOS Darwin 25.6.0 arm64, Node 26 (Homebrew), iii-engine pinned v0.11.2
  • LLM/embeddings: OpenRouter (gemini-2.5-flash-lite + openai/text-embedding-3-small)
  • Corpus: 691 sessions, 131/133 memories, snapshot 108 nodes / 73 edges, 335 MB on disk
  • Data verified intact after every crash in both runs

allandelmare avatar Aug 14 '26 13:08 allandelmare

Investigated with Claude Code — hands-on measurement on a live install plus reading the 0.9.29 bundle. Numbers are from my own machine; push back on anything that looks wrong.

Independent reproduction on 0.9.29, macOS (Apple Silicon), file-based kv state store, single user. Posting measurements because this issue predicted the behaviour exactly and I arrived at it from the symptom end without having read it first — which I think makes the numbers useful corroboration.

Corpus

48,107 nodes / 107,060 edges   (graph/stats)
  nodes: concept 41,299 (86%), file 6,416, decision 83, error 81, …
  edges: related_to 106,675 (99.6%), uses 125, depends_on 60, modifies 57, fixes 47, causes 46, …
on disk: mem:graph:nodes.bin 133 MB, mem:graph:edges.bin 225 MB

Roughly 2× the ~25K ceiling this issue names.

Symptom split is exactly along "touches the graph"

Every graph-touching read returned {"error":"Invocation stopped"}; everything else was perfectly healthy:

Dead Alive
/agentmemory/search /agentmemory/lessons/search
/agentmemory/smart-search /agentmemory/frontier
/agentmemory/semantic /agentmemory/insights/search
/agentmemory/graph/query /agentmemory/graph/stats (fromSnapshot: true)

Measurements

One call = one worker death. Snapshotting grep -c "Reconnecting in" ~/.agentmemory/daemon.log before and after a single curl gives delta = 1, repeatably. The [iii] Reconnecting in Nms (attempt 1)... / Worker registered with ID: pairs in the log are the failed searches. (This is the same blast radius described in #1124.)

The cost is the graph load. Sampling ps -o rss= on both processes during one graph/query:

iii engine:            3,203,568 KB -> 3,612,592 KB   (+409 MB)
agentmemory worker:      600,928 KB ->   601,456 KB   (flat)

+409 MB ≈ nodes.bin 133 MB + edges.bin 225 MB. A bare /agentmemory/search costs +259 MB on its own. The blowup is entirely engine-side.

It is the load, not the traversal. graph/query {"maxDepth": 1} fails identically to an unbounded one — consistent with this issue's point that the full enumeration happens before any traversal, so the 6s LIVE_ENUMERATION_BUDGET_MS fallback to the snapshot is unreachable: the worker dies first.

The memory is never released. This is what makes it degrade rather than just fail. A freshly restarted engine booted at 2.21 GB and climbed to 3.16 GB within minutes purely from my probe calls, each leaking its ~250–400 MB. The long-lived process had reached 3.2 GB baseline over ~3 days.

Restart is not a workaround. Full stack restart gave a fresh 2.21 GB engine on which all four paths still failed, while lessons/search still worked. Worth stating explicitly since "restart it" is the natural first thing to try.

What actually restored service

Stopping the engine and moving the six mem:graph:*.bin files aside (nodes, edges, snapshot, edge-key, name-index, node-degree), then restarting:

memory_recall             results: []            -> real hits
search / smart-search     Invocation stopped     -> real content
graph/query               Invocation stopped     -> clean empty result
iii RSS                   3.20 GB                -> 413 MB
reconnects per call       1                      -> 0

Note /agentmemory/graph/reset does not achieve this — it only writes an empty snapshot and leaves nodes/edges intact (that's #1239).

The part I think is under-stated

The user-visible failure mode is silent. memory_recall returns {"results": []} — an empty array, not an error. Nothing in the MCP surface says "the graph leg crashed the worker". A session that hits this reasonably concludes nothing is stored and stops trusting its own memory. On this machine that misreading cost a full day of re-deriving things that were already recorded.

If a guard lands, even a degraded-but-honest response (warning: live enumeration skipped, corpus too large) would be a large improvement over an empty result set, independent of the per-node edge index this issue asks for.

aberenyi avatar Sep 11 '26 17:09 aberenyi

@allandelmare v0.9.30 caps node and edge provenance at 32 ids and compacts existing rows, which shrinks what a traversal loads per node. Traversal still reads the graph scopes, so please retest graph-query with startNodeId on 0.9.30 before we decide. https://github.com/rohitg00/agentmemory/releases/tag/v0.9.30

rohitg00 avatar Oct 08 '26 06:10 rohitg00