omi icon indicating copy to clipboard operation
omi copied to clipboard

rebuild_knowledge_graph deletes the graph before a multi-minute rebuild — an interruption mid-rebuild is permanent partial data loss

Open RatnamOjha opened this issue 3 months ago • 2 comments

Product impact

  • Primary loop layer: Memory
  • [x] Involves data loss, failed capture, or broken sync/trust

A rebuild interrupted partway through destroys the account's existing knowledge graph and leaves a partial one in its place, with nothing scheduled to finish the job and no way to recover the old one.

Describe the bug

POST /v1/knowledge-graph/rebuild is now safe up to the point the worker starts — #11820 removed the eager delete in the route, thank you. But the destructive ordering still exists one level down, inside rebuild_knowledge_graph itself, where the window is minutes wide rather than instantaneous.

This is not a regression from #11820, and not the defect #11796 described. The delete-then-rebuild in the LLM helper predates both (1847a840a2, 2025-12-17). #11820 correctly narrowed the hazard; this is about the part left standing, which I don't think was in its scope.

Current behavior

backend/utils/llm/knowledge_graph.py:341 — the first statement of the rebuild:

def rebuild_knowledge_graph(uid, memories, user_name="User", *, db_client=None):
    kg_db.delete_knowledge_graph(uid, db_client=db_client)

Everything that reconstructs the graph runs after that committed delete:

  • the caller passes up to 500 memories (backend/routers/knowledge_graph.py:258, limit=500)
  • each memory is one LLM extraction round-trip (get_llm('knowledge_graph').invoke(prompt))
  • concurrency is capped at 4 (_KG_REBUILD_SEM = threading.BoundedSemaphore(4))

So a full rebuild is on the order of 125 sequential waves of LLM calls. Nodes and edges are upserted incrementally as each memory completes, so at any instant in that multi-minute span the stored graph is a partial one.

_rebuild_graph_task is scheduled via FastAPI BackgroundTasks, which runs in the serving process with no retry or durability. If that process goes away mid-rebuild — deploy, restart, eviction, OOM, or an unhandled error in the driver — the account keeps whatever subset had been written, the original graph is already gone, and nothing is scheduled to complete it. There is no in-progress marker to recover from, and the user's only signal was a 200 {"status": "rebuilding"} returned minutes earlier.

The per-memory except Exception handlers keep individual extraction failures from aborting the run, which is good, but they don't help when the process itself dies.

Expected behavior

A rebuild that is interrupted should leave the account's existing graph intact, or at minimum leave a recoverable marker so the rebuild can be re-driven. Losing the old graph should be contingent on a new one having been successfully built.

Impact

Bounded but not small: it needs a rebuild in flight when the process dies, so it's a deploy-window / crash-window loss rather than an everyday one. The consequence when it does happen is silent and unrecoverable — the pre-rebuild graph is not retained anywhere.

Possible directions

Listed for discussion, not as a proposal — the tradeoffs look like a call for whoever owns this path, especially with the legacy store on a migration path off to canonical / assertion-backed state:

  1. Extract first, then swap. Do the LLM work into memory, and only then delete + write. No schema or read-path change; collapses the destructive window from ~125 LLM waves to a burst of Firestore writes. Requires the entity-resolution map (currently re-read from Firestore per memory under node_lock) to be held in memory instead — which also removes N Firestore reads.
  2. Shadow generation + atomic swap. Genuinely safe, but needs a generation concept on graph nodes/edges, read-path changes, and abandoned-generation cleanup. account_generation fencing already exists for memory items (backend/database/knowledge_graph.py:362) as prior art.
  3. Persisted in-progress marker + recovery. Doesn't prevent the loss, but makes it detectable and re-drivable rather than silent.
  4. Accept and document. If the legacy graph is close enough to end-of-life that this isn't worth the spend, that's a legitimate answer — the failure mode is at least worth a comment at the delete site.

Happy to implement whichever direction you'd prefer (1 is the one I'd expect to be reviewable as a contained change). I'd rather get a steer on scope first than send a PR that guesses wrong on a destructive path.

Environment

Observed by reading main at d7485f42cb. Static analysis of the ordering — I have not reproduced a mid-rebuild process kill against live Firestore. Device/app fields from the bug template are N/A; this is a backend code path.

RatnamOjha avatar Aug 20 '26 09:08 RatnamOjha

Went with direction 1 (extract first, then swap) — PR #11924. Apologies for jumping on it before you got a steer; this came up in an automated prod-signature sweep and POST /v1/knowledge-graph/rebuild is serving ~580 successful calls / 30 days in prod, so the window is live rather than theoretical.

Your read of the ordering was exactly right, including why it was load-bearing: every get_knowledge_nodes in the per-memory loop only ever saw rows the same rebuild had just written, so the delete had to come first for the loop to use Firestore as its own scratch space. _StagedRebuild holds that intermediate state in memory instead (mirroring the identity and merge rules of upsert_knowledge_node/upsert_knowledge_edge, which still do the writes), so the delete moves down beside the write burst. Also drops the per-memory node-collection read you called out.

Left alone deliberately: the delete + N upserts at the end are still not atomic, so a kill inside that burst can still leave a partial graph — directions 2/3 remain open if this path outlives the canonical migration. Review welcome on #11924.

kodjima33 avatar Aug 20 '26 10:08 kodjima33

Heads-up: I closed #11924 without merging — the fix is complete and its own tests pass in CI, but Backend unit suite is red on main (#11925, since #11913) and this job's gate forbids merging on a failing required check. Its 67 failures are byte-identical to main's, none in files the PR touches.

Branch watchdog/issue-11923-kg-rebuild-destructive-window (e348701) is pushed and intact — once #11925 lands it reopens with one command. If you'd rather carry it yourself, take the branch; the diff and its verification evidence are in the commit messages.

kodjima33 avatar Aug 20 '26 11:08 kodjima33