agentmemory icon indicating copy to clipboard operation
agentmemory copied to clipboard

persistGraphDelta can zero the graph snapshot on a transient read failure (readSnapshot fail-open)

Open cbsincool opened this issue 2 months ago • 0 comments

Summary

persistGraphDelta treats a failed snapshot read as an empty store, then writes the resulting zeroed snapshot back. One transient state::get error silently replaces a 40k-node graph counter with a handful of nodes.

Where

src/functions/graph.ts:80-93 — readSnapshot swallows every error:

async function readSnapshot(kv: StateKV): Promise<GraphSnapshot | null> {
  try {
    const snap = await kv.get<GraphSnapshot>(KV.graphSnapshot, SNAPSHOT_KEY);
    if (snap && typeof snap === "object" && snap.version === 1) {
      return snap;
    }
    return null;
  } catch (err) {
    logger.warn("Graph snapshot read failed", { error: ... });
    return null;              // <-- read failure and "no snapshot yet" become the same value
  }
}

src/functions/graph.ts:557 — that null is immediately coalesced into an empty snapshot, and the function goes on to kv.set it:

const snap = (await readSnapshot(kv)) ?? emptySnapshot();

Impact

readSnapshot can only return null for two very different situations: (1) the key really is absent — a genuine first run, where emptySnapshot() is correct; and (2) the read failed — a store that is saturated or timing out. Case (2) is a read of an existing snapshot, and the caller then writes back a snapshot derived from emptySnapshot(), zeroing stats.totalNodes / stats.totalEdges / nodesByType.

The live graph is untouched — KV.graphNodes / KV.graphEdges still hold everything — so this is a snapshot corruption, not data loss. But the snapshot is what /graph/query (no-walk branch) and /graph/stats serve, and what the viewer badge renders, so every counter reads near-zero afterwards.

This is not hypothetical: a store saturated by the batch-loop hangs in #1127 / #1339 times out on state::get, which is exactly the case that reaches this code path. In our deployment the badge went from ~40k to double digits after a graph/build replay that logged 27 consecutive graph-build batch failed entries.

It also makes recovery harder than it needs to be: with a zeroed snapshot, the rebuild preflight in #825 sees a corpus that no longer matches, and graph/reset deletes the live graph the user still has.

Also in the same place

The snap.version === 1 check has the same conflation. A snapshot that is present under an unknown schema version also returns null, so a future schema bump would be read as "empty store" and overwritten on the next extraction.

Proposed fix

Give the writer a strict reader and keep the lenient one for readers (readers lose nothing by falling back — they only ever display):

  • retry a failed read once, and let a second failure propagate, so the delta aborts before any write;
  • return null only when the key is genuinely absent;
  • treat a present-but-unrecognised schema as an abort rather than a miss.
async function readSnapshotStrict(kv: StateKV): Promise<GraphSnapshot | null> {
  let snap: GraphSnapshot | null;
  try {
    snap = await kv.get<GraphSnapshot>(KV.graphSnapshot, SNAPSHOT_KEY);
  } catch (err) {
    logger.warn("Graph snapshot read failed, retrying once", { error: ... });
    snap = await kv.get<GraphSnapshot>(KV.graphSnapshot, SNAPSHOT_KEY); // 2nd failure propagates
  }
  if (snap && typeof snap === "object" && snap.version === 1) return snap;
  if (snap) {
    throw new Error(
      `Graph snapshot has unknown schema version: ${JSON.stringify(snap.version)}`,
    );
  }
  return null; // absent key: first run, emptySnapshot() is safe
}

and graph.ts:557 becomes const snap = (await readSnapshotStrict(kv)) ?? emptySnapshot();.

I have this running as a build-time patch in production against 0.9.29 and it holds; happy to send it as a PR with tests covering: missing key → null; transient failure → retried once, recovers; persistent failure → throws instead of returning null; present-but-unknown version → throws instead of returning null.

/cc #1127 #1339 (the store saturation that makes the transient case reachable) and #825 (the recovery dead-end a zeroed snapshot creates).

cbsincool avatar Sep 21 '26 07:09 cbsincool