agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

fix(graph): top-degree snapshot cache for /graph/query + /graph/stats (#814)

Open rohitg00 opened this issue 6 months ago • 4 comments

Summary

Fixes #814 (@allandelmare). Two-phase fix. Phase 1 (initial commits) added snapshot cache + wall-clock budget. Phase 2 (this revision, after Allan's test against his 75K-node corpus exposed that the budget can't fire on a blocked event loop) eliminates kv.list from the hot path entirely.

Allan's diagnosis

Confirmed end-to-end. At 75K nodes the kv.list<GraphNode> + kv.list<GraphEdge> pair returns a ~37MB single WS frame. JSON.parse of that blocks the Node event loop for hundreds of ms. iii's heartbeat starves, worker is declared dead at ~0.5s. The Promise.race wall-clock timer never gets to fire because nothing on the loop runs. Caller sees raw Invocation stopped, never the graceful envelope.

mem::graph-snapshot-rebuild itself was running the same enumeration, so the very call meant to populate the cache died at ~2.6s on his corpus. Catch-22.

What changed in Phase 2

Incremental indexes maintained by mem::graph-extract

Three new KV scopes — all kv.get / kv.set only, no enumeration ever:

  • KV.graphNameIndex — ${type}|${name} → nodeId. Replaces the O(n) existingNodes.find(...) scan inside extract.
  • KV.graphEdgeKey — ${src}|${tgt}|${type} → edgeId. Same for edges.
  • KV.graphNodeDegree — nodeId → incident-edge count. Read / incremented on edge writes to maintain snapshot top-N ranking without scanning edges.

mem::graph-extract is now O(extract_size), not O(total_nodes). The bottleneck Allan was hitting on every observation capture is gone.

Snapshot updated inline on every extract

Read snapshot once, mutate stats / degree / topNodes / topEdges inline, write back. No dirty flag bouncing, no scheduled rebuild needed. Corpora built on a post-#814v2 build always have a current snapshot without any explicit rebuild call.

Hot path reads snapshot exclusively

  • mem::graph-query empty-body / nodeType-only branch: snapshot only. No kv.list fallback (that was the broken path).
  • mem::graph-stats: snapshot only. Empty envelope + warning on miss, never a 500.
  • mem::graph-query startNodeId / query branches: still need broader access; keep behind the wall-clock budget with snapshot fallback. Documented as degrading on >25K-node corpora until a per-node edge index lands.

Legacy corpus rebuild + reset

  • mem::graph-snapshot-rebuild now refuses to run when the recorded node count would block the worker (REBUILD_SAFE_NODE_CEILING = 25000). Returns { success: false, tooLarge: true, totalNodes, ceiling, error } instead of dying. Also backfills the new name-index / edge-key / degree scopes so post-rebuild extracts hit the O(1) path.
  • New mem::graph-reset + POST /agentmemory/graph/reset — wipes all graph KV scopes, writes an empty snapshot. Observations / recall / history are NOT touched. Operators above the safe ceiling reset and let future extracts rebuild incrementally.

Endpoint count + docs

  • 127 → 128 (added /graph/reset). Bumped README.md, AGENTS.md, src/index.ts boot log.

What this fixes for Allan

Even before backfilling, Allan's observation capture has been doing the broken kv.list on every extract since v0.9.21. That ALSO blocks the worker for hundreds of ms each time, and is the most likely cause of the worker-reconnect churn he observed. Phase 2 fixes that immediately — every new extract is O(1).

For his 75K accumulated graph: POST /agentmemory/graph/reset is the path. Recall + sessions + observations stay intact; the graph rebuilds from new observations as they come in. The 75K accumulated nodes were largely redundant anyway (heavy dedup pressure from re-extracting the same source files / functions across sessions).

Test plan

  • [x] npx vitest run — 1406/1406 pass (12 new tests for incremental index + snapshot inline update + reset + name-index dedup)
  • [x] npm run build clean
  • [x] npx tsc --noEmit — no new errors
  • [ ] Manual against @allandelmare's corpus: POST /agentmemory/graph/reset → trigger a few new observations → POST /agentmemory/graph/query {} and GET /agentmemory/graph/stats both return < 100ms

Out of scope

  • Per-node edge index for fast BFS on huge corpora — startNodeId / query paths still rely on kv.list and degrade above ~25K. Defer to a follow-up.
  • SQLite-backed graph store (#309 epic) — separate effort. Snapshot interface stays stable so the migration won't disrupt callers.

cc @allandelmare — would appreciate one more run against your corpus once this lands. Reset is the fast path; alternatively mem::graph-snapshot-rebuild will refuse above 25K with a clear tooLarge error envelope.

Summary by CodeRabbit

  • New Features

    • Cached graph snapshots for faster queries and stats
    • POST /agentmemory/graph/snapshot-rebuild to rebuild/persist snapshots
    • POST /agentmemory/graph/reset to clear graph state and write an empty snapshot
  • Improvements

    • Extraction avoids full scans using targeted indexes and updates snapshots incrementally (keeps top-degree tracking)
    • Queries/stats race live enumeration against a time budget and fall back to snapshots with warnings and metadata
  • Tests

    • Added snapshot-focused tests for persistence, reuse, fallbacks, and reset behavior
  • Documentation

    • Updated endpoint count in docs and startup message (126 → 128)

rohitg00 avatar Jun 03 '26 18:06 rohitg00

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
agentmemory Ready Ready Preview, Comment Jun 4, 2026 3:19pm

Request Review

vercel[bot] avatar Jun 03 '26 18:06 vercel[bot]

Review Change Stack

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 162b848f-8a14-4078-a604-5158dce2fc2f

📥 Commits

Reviewing files that changed from the base of the PR and between 795537bdefb11fd569e521636fa441d7895236b6 and b494f231ad94341e87a7d4ecf3f9d01aa426322d.

📒 Files selected for processing (1)
  • test/graph.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/graph.test.ts

📝 Walkthrough

Walkthrough

Adds a persisted top-degree GraphSnapshot and helpers; extract updates the snapshot incrementally; query and stats use snapshot-first or timeout-fallback behavior; adds mem::graph-snapshot-rebuild and mem::graph-reset handlers, API endpoints, tests, and docs/boot-log endpoint count updates.

Changes

Graph Snapshot Caching

Layer / File(s) Summary
Type contracts and storage schema
src/types.ts, src/state/schema.ts
Adds GraphSnapshot interface (versioned top-degree subgraph, per-type stats, timestamp, dirty flag) and extends GraphQueryResult with fromSnapshot and warning; adds KV keys graphSnapshot, graphNameIndex, graphEdgeKey, graphNodeDegree.
Snapshot infrastructure and helper functions
src/functions/graph.ts
Implements timeout-bounded async helper and snapshot lifecycle utilities: emptySnapshot, read/build from live arrays, paginate from snapshot, and removes old full-ranking path.
Incremental degree and top-N maintenance
src/functions/graph.ts
Implements applyDegreeDelta, topNodes/topEdges promote/evict logic, and merge helpers for node/edge updates used during extraction.
Graph extract using indexes and inline snapshot updates
src/functions/graph.ts
mem::graph-extract uses targeted name/edge indexes instead of full KV scans, merges existing records, updates snapshot stats/top-degree incrementally, and persists snapshot only when new nodes/edges are added; audit metadata extended with added counts.
Graph query: snapshot fast-path and timeout fallback
src/functions/graph.ts
Adds an empty-body/nodeType-only fast path that serves paginated results from the cached snapshot; for other queries, races live KV enumeration against a wall-clock budget and falls back to snapshot-based pagination or returns an empty response with a warning on timeout.
Graph stats snapshot-first behavior
src/functions/graph.ts
mem::graph-stats returns snapshot stats when present (annotated with fromSnapshot and a dirty warning if set); when no snapshot exists returns zeroed stats with a warning.
Snapshot rebuild and reset handlers
src/functions/graph.ts
Adds mem::graph-snapshot-rebuild to enumerate nodes/edges within budget, backfill indexes, rebuild and persist snapshot, and return timing/stats; adds mem::graph-reset to clear graph KV scopes and write an empty snapshot.
HTTP endpoints for rebuild/reset
src/triggers/api.ts
Registers authenticated POST /agentmemory/graph/snapshot-rebuild and /agentmemory/graph/reset that call the corresponding mem::graph-* handlers and return results or graphDisabledResponse() on error.
Snapshot cache test suite
test/graph.test.ts
New Vitest "snapshot cache (#814)" suite plus updated pagination tests covering rebuild persistence, query/stat fast-paths and timeout fallback, nodeType filtering, dirty/invalidation behaviour, inline extract updates and name-index dedup, reset clearing index scopes, and tooLarge/budget guards.
Docs and boot log endpoint count updates
AGENTS.md, README.md, src/index.ts
Increment documented REST endpoint count and boot log from 126 to 128.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HTTP_API as "api::graph-snapshot-rebuild"
  participant MemFn as "mem::graph-snapshot-rebuild"
  participant KV
  Client->>HTTP_API: POST /agentmemory/graph/snapshot-rebuild
  HTTP_API->>MemFn: invoke mem::graph-snapshot-rebuild()
  MemFn->>KV: enumerate nodes/edges (budgeted)
  KV-->>MemFn: node/edge batches
  MemFn->>KV: write graphNameIndex/graphEdgeKey/node-degree
  MemFn->>KV: persist KV.graphSnapshot
  MemFn-->>HTTP_API: {stats, tookMs}
  HTTP_API-->>Client: 200 {result}

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I cached the graph in the KV burrow deep,
Top nodes counted while the watchers sleep.
When live scans stall and time slips away,
I hand you a snapshot to brighten your day. ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Code changes implement snapshot caching, indexed KV lookups, and wall-clock budgets for /graph/query and /graph/stats; however, tester reports platform-level invocation stops persist despite graceful envelope implementation. Address the fundamental blocker: synchronous kv.list blocks Node event loop, preventing Promise.race timers and heartbeats from firing. Implement chunked pagination with event-loop yields (await/setImmediate between batches) or move rebuild off the hot request path.
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing a top-degree snapshot cache to fix /graph/query and /graph/stats timeouts.
Out of Scope Changes check ✅ Passed All changes directly support the PR objective: KV indexes, snapshot lifecycle, budget-bounded queries, rebuild/reset handlers, and test coverage for snapshot functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • [ ] Create stacked PR
  • [ ] Commit on current branch
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch fix/814-graph-degree-cache

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jun 03 '26 18:06 coderabbitai[bot]

The following was generated with the help of Claude Code based on a hands-on test against my corpus. Apologies for any AI-slop — please push back on anything that reads wrong.

Tested PR #816 (commit 75d77db) against the same 680-session / 75K-node / 344 MB ~/data/ corpus from #814. Backup taken first; data fully intact afterwards (131/133 memories, 684 sessions still readable, recall + observation capture all working).

Headline

The new code is bundled, it boots, and the 6s graceful budget path does fire (visible in logs as [agentmemory] warn Graph query enumeration timed out, using snapshot {"error":"graph-query enumeration: exceeded 6000ms budget"}). But callers still receive {"error":"Invocation stopped"} rather than the {warning, fromSnapshot} envelope, and the snapshot-rebuild endpoint can't escape the very enumeration-timeout problem it was designed to solve. Recall / memories / observation capture are unaffected.

Concrete repro

# Fresh boot of the PR build against existing 75K-node corpus
$ cd ~ && node /tmp/agentmemory-pr816/dist/cli.mjs &
# Ready in 1s; circuit breaker closed; 684 sessions, 131 memories readable.

$ time curl -s -X POST http://localhost:3111/agentmemory/graph/snapshot-rebuild
{"error":"Invocation stopped","error_id":"a5a8b329a1b0"}
real  0m2.66s

$ time curl -s -X POST http://localhost:3111/agentmemory/graph/snapshot-rebuild
{"error":"Invocation stopped","error_id":"a5a983a601d0"}
real  0m1.45s

$ time curl -s -X POST http://localhost:3111/agentmemory/graph/query -d '{}'
{"error":"Invocation stopped","error_id":"..."}
real  0m5.24s

$ time curl -s -X POST http://localhost:3111/agentmemory/graph/query -d '{"limit": 10}'
{"error":"Invocation stopped","error_id":"..."}
real  0m1.14s

$ time curl -s http://localhost:3111/agentmemory/graph/stats
{"error":"Invocation stopped"}    # or "Function not found" during reconnect window — see below

Server log during the same window confirms the new code paths execute:

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

What I think is happening

Bug 1 — iii invocation timeout < the new 6s budget. Snapshot-rebuild errors out in ~2.6s and /graph/query {"limit":10} errors in ~1.1s, both well under the 6s budget. iii is killing the invocation before the SDK's Promise.race reaches the timeout branch, so the graceful {warning, fromSnapshot} envelope never reaches the HTTP client. Either the budget needs to be < iii's per-function deadline, or the rebuild needs to run as a streamed/chunked operation that doesn't sit inside a single iii invocation.

Bug 2 — snapshot-rebuild itself can't escape the timeout it was built to solve. The endpoint is the first thing an operator runs to populate the cache, but it still needs to enumerate the full 75K-node corpus inside one iii call. At our scale that enumeration is exactly what was breaking /graph/query in the first place. The snapshot makes subsequent queries fast (architecturally sound) but only if you can pay the rebuild cost once — and on our corpus you can't. Suggestions:

  • Stream the rebuild in batches (paginated kv.list with cursor, accumulate, write at end) so each batch fits inside iii's window
  • Or: register snapshot-rebuild with a relaxed timeout (8–10x the default) since it's known-expensive
  • Or: rebuild incrementally during mem::graph-extract writes (incurs the per-write cost but amortizes — could be gated to "rebuild every N extracts when dirty")

Bug 3 — worker reconnect churn under sustained graph load. When I had the daemon running for a while, the log showed continuous [iii] Reconnecting in NNNms interleaved with the timeout warnings, and a fresh worker UUID would register every few seconds. During the ~1s gap between worker death and the next registerApiTriggers run, HTTP calls returned {"error":"Function api::graph-stats not found"} (the EXISTING endpoint, not just the new one — api::graph-stats was registered in main; this isn't a missing-registration bug, it's a registration-not-yet-rerun bug). Once the new worker finished registering, api::graph-stats came back. Suggests the graph timeouts are either crashing the worker or being treated as fatal by iii.

I don't know who's calling graph-stats internally — only the viewer in src/viewer/index.html does apiGet('graph/stats'), but I didn't have a viewer open. Could be MCP client probes (12 stale npm exec @agentmemory/mcp processes from prior Claude Code sessions still hanging around) or a background poller I missed. The setInterval calls I found in src/index.ts are for autoForget / lessonDecay / insightDecay / consolidation — none mention graph-stats. Worth checking.

What still works

  • /agentmemory/health — full metrics, 1292/1293 compress successes, 730/731 summarize successes, 94+ avg quality score
  • /agentmemory/memories?count=true — 131/133, instant
  • /agentmemory/sessions?limit=100000 — 684 sessions, < 1s
  • Observation capture from active Claude Code session — confirmed in log: [agentmemory] info Observation captured … hook=post_tool_use, compress=llm followed by Observation compressed
  • Boot is clean, no crash loops

Summary

The architecture in this PR is correct (snapshot cache + graceful timeout envelope), but the implementation has a coordination problem between the SDK's Promise.race and iii's per-invocation timeout, plus snapshot-rebuild needs to escape the enumeration-timeout itself before it can be useful at large scale.

Happy to test any follow-up patch against this corpus — fastest feedback loop you'll get for the > 50K-node case.

allandelmare avatar Jun 03 '26 18:06 allandelmare

Follow-up to my test report above, generated with Claude Code. Two things: (1) correcting an error in my first comment, and (2) a controlled experiment that I think pins the root cause. Please push back on anything that reads wrong.

Correction to my previous comment

I wrote "I didn't have a viewer open" and speculated about a mystery internal caller hammering graph/stats. That was wrong — I did have the viewer open. The viewer dashboard auto-refresh (setInterval in src/viewer/index.html, calling apiGet('graph/stats')) polls graph/stats every ~2s. So the "constant internal graph-stats calls" and the continuous worker-reconnect churn I described in Bug 3 were self-induced by my open viewer tab, not a background poller in the daemon. Apologies for the misdirection.

But re-testing with the viewer closed surfaced the actual mechanism, which is more useful:

Controlled experiment: graph calls crash the worker, cheap calls don't

Fresh boot, no viewer, worker confirmed healthy (memories?count=true returns instantly before each batch):

# 3x graph/query {} back-to-back:
  call 1: 0.578s   -> {"error":"Invocation stopped"}
  call 2: 0.0007s  -> {"error":"Function api::graph-query not found"}
  call 3: 0.0005s  -> {"error":"Function api::graph-query not found"}
  => Worker "registered" count delta: +1   (a reconnect happened)

# 3x memories?count=true back-to-back (control):
  call 1: 0.009s
  call 2: 0.004s
  call 3: 0.004s
  => Worker "registered" count delta: 0     (no reconnect)

Graph calls deterministically trigger a worker reconnect; cheap calls never do. Call 1 fires the enumeration and dies at ~0.5s; calls 2 & 3 land in the ~1s reconnect gap and get instant Function not found. At idle with no viewer, the worker still re-registered 4–5 times over ~90s purely from [OTel] WebSocket error -> Disconnected from engine, will reconnect cycles, but graph calls reliably force an extra one.

Root cause hypothesis

mem::graph-snapshot-rebuild, mem::graph-query (empty-body path), and mem::graph-stats all die at ~0.5–0.7s with zero enumeration log output, even with the worker confirmed up immediately prior. That's far below the new 6s budget, and the function body never logs progress. I think:

  1. The kv.list<GraphNode> + kv.list<GraphEdge> enumeration runs synchronously without yielding to the Node event loop.
  2. A blocked event loop can't fire the Promise.race 6s timer — so the graceful { warning, fromSnapshot } envelope this PR adds can never be returned; the caller always gets the raw iii Invocation stopped instead.
  3. The same blocked loop misses the iii websocket heartbeat, so iii declares the worker dead at ~0.5s and reconnects it — which is the reconnect we see correlated with every graph call.

In short: a Promise.race against a wall-clock timer can't interrupt a synchronously-blocked event loop. The timer and the heartbeat are both starved by the very enumeration they're meant to bound.

Implication for the fix

The snapshot-cache architecture is sound — precompute top-degree, serve the fast path, never enumerate on hot calls. But the rebuild itself (and any live-enumeration fallback) has to yield to the event loop, or it takes the worker down before it can finish or time out gracefully. Options:

  • Chunk the enumeration: paginated kv.list with a cursor, await/setImmediate between batches, accumulate, write the snapshot at the end. Each batch fits inside the heartbeat window and lets the budget timer fire.
  • Or move the snapshot rebuild off the request worker entirely (background job / separate worker) so a long enumeration never blocks the HTTP/heartbeat loop.
  • Either way, the live-enumeration fallback in graph-query/graph-stats should be removed or also chunked — as written it's the thing crashing the worker, so falling back to it defeats the cache's purpose on exactly the large corpora that need it.

Caveat

I'm running the PR build via node dist/cli.mjs directly (not the packaged launcher). The baseline [OTel] WebSocket error reconnect cycle at idle might be partly environmental to that launch method — worth confirming. But the graph-call-triggers-reconnect delta and the ~0.5s death with no enumeration log are robust and reproduce on every call regardless of launch method, since they're about the enumeration blocking the loop, not about how the process was started.

Data fully intact throughout (131/133 memories, 684 sessions, recall + observation capture all working). Standing by to test a chunked-enumeration patch against this corpus.

allandelmare avatar Jun 03 '26 19:06 allandelmare

Re-test of the latest push (b494f23) against the 75K-node corpus, via Claude Code. Good news + one precise remaining gap. Push back on anything that reads wrong.

Pulled b494f23 (incremental indexes + snapshot-only hot path + reset endpoint + the worker-death test), rebuilt, ran against the same 680-session / ~75K-node ~/data/. Backup held; no data loss — 131/133 memories, 685 sessions intact throughout (one transient sessions: 0 mid-test was just a reconnect-gap read while the worker was churning, not loss).

The core regression is FIXED ✅

The snapshot-only hot path works exactly as intended. Controlled experiment (no viewer, worker confirmed healthy first):

# 5x (graph/query {} + graph/stats) = 10 hot-path calls:
graph/query {}  -> 200 in 0.002s  {"nodes":[],"totalNodes":0,"warning":"No graph snapshot available..."}
graph/stats     -> 200 in 0.002s  {"fromSnapshot":false,"warning":"No graph snapshot available..."}
=> Worker "registered" delta: 0   (was +1 PER CALL before)

No more Invocation stopped, no worker death, no reconnect churn. An open viewer polling graph/stats every 2s would now be harmless. This is the fix — thank you.

Remaining gap: rebuild AND reset both still crash on a >25K legacy corpus

Both write-side paths still die the same way the hot path used to:

POST /graph/snapshot-rebuild -> 500 {"error":"Invocation stopped"} in 0.357s  ; worker delta +1
POST /graph/reset            -> 500 {"error":"Invocation stopped"} in 0.337s  ; worker delta +1

snapshot-rebuild: the REBUILD_SAFE_NODE_CEILING = 25000 guard reads snapshot.totalNodes — but a pre-#814 legacy corpus has no snapshot yet, so totalNodes is unknown/0, the guard doesn't fire, and it proceeds to the full kv.list<GraphNode> + kv.list<GraphEdge> pair → blocks the loop → worker dies. The guard can't know the corpus is 75K until it does the very enumeration that crashes it.

graph/reset: this is the more important one. It's the documented escape hatch in the warning envelope you added ("Run POST /agentmemory/graph/reset to wipe and let future extracts repopulate"), but the wipe itself enumerates the keys to delete them, so it hits the same kv.list block and crashes. So on a >25K legacy corpus there is currently no working path to either rebuild or clear the graph — only the graceful empty-graph warning state.

Why the 6s budget doesn't save them

Interesting detail from the log: the budget timer does eventually fire —

[agentmemory] error Graph snapshot rebuild failed {"error":"graph-snapshot-rebuild enumeration: exceeded 6000ms budget"}

— but it fires at ~6s, after the caller already got Invocation stopped at ~0.35s and the worker already reconnected. iii's heartbeat deadline (~0.35s observed) is far shorter than the 6s budget, and a synchronously-blocking kv.list starves the heartbeat before the Promise.race timer can resolve. So the budget bounds the function's wall-clock but can't prevent the worker death — it's defending against the wrong deadline.

Suggested direction

Both snapshot-rebuild and graph-reset need to stop loading the whole keyspace into one synchronous enumeration:

  • Cursor-paginated kv.list with await/setImmediate between batches, so the loop breathes and the heartbeat survives. Then the 6s budget (or any budget < heartbeat interval) can actually fire mid-walk.
  • For reset specifically, a streaming delete-by-key-prefix that never materializes all values in memory would be ideal — you don't need to read node bodies to wipe them.
  • Either fix makes the >25K escape hatch real; without it, large legacy corpora are stuck at empty-graph-forever.

Bottom line

Normal operation is now solid on a large corpus — that was the crash that made me stop using it, and it's gone. The remaining gap only bites operators with a big pre-#814 graph who want to reclaim it. Happy to test a yielding-enumeration patch against this exact corpus — it's the fastest >50K repro you'll get.

allandelmare avatar Jun 04 '26 15:06 allandelmare

Two structural observations from digging into the root cause, via Claude Code — in case they're useful for where the fix goes next. Plus a standing offer. Push back on anything wrong.

After the b494f23 re-test, I traced why rebuild + reset still crash and it bottoms out at one shared primitive, which I think reframes the fix slightly.

state::list is the single shared root cause

StateKV only wraps five engine primitives: get / set / update / delete / list. There's no clear-scope, no cursor/pagination on list, and no key-only keys variant. So every operation that must touch all existing keys is forced through state::list, which returns the entire scope and lands a multi-MB payload that JSON.parse chews synchronously — starving the worker heartbeat (the ~0.35s death we keep seeing, well under the 6s budget).

That's why all three of these are really the same bug:

  • rebuild — needs every node to compute top-degree → state::list
  • reset — needs every key to delete it (no clear-scope) → state::list
  • bootstrapping an incremental key-index for a legacy corpus — can't be done without one state::list to seed it

So for a pre-#814 corpus there's a chicken-and-egg: the incremental snapshot/index design (which is the right architecture) can't be seeded without the one call that crashes. The hot-path fix is solid because it never seeds — it just serves whatever snapshot exists. The write side can't avoid the seed.

The clean fix seems to live in the engine, not here — a paginated/streaming state::list (or a clear-scope / key-only keys) would let rebuild and reset walk in yielding batches so the heartbeat survives. I realize that's upstream of this repo and tangled with the v0.11.2 pin, so I'm flagging it as context, not asking for it here.

Same latent bug in migrate.ts

While tracing state::list callers: src/functions/migrate.ts does kv.list<Memory>(KV.memories). On a large-memory corpus that would heartbeat-crash a migration the same way. We only have 131 memories so it's fine for us, but an operator with tens of thousands of memories running a migration would hit it. Might be worth the same yielding/guard treatment whenever the enumeration primitive gets fixed.

Standing offer

We've got the >50K repro you can't easily synthesize (680 sessions / ~75K graph nodes / 344 MB on disk), a backup, and a one-command rebuild-and-test loop pointed at it. Push any branch and I'll report rebuild/reset/hot-path behavior + worker-reconnect deltas against the real corpus, usually within the hour. The hot-path fix already verified clean here — happy to be the scale check on whatever lands for the write side.

allandelmare avatar Jun 04 '26 15:06 allandelmare