Skip to content

fix: graph search silently dropping all results#937

Open
abhinav-m22 wants to merge 4 commits into
rohitg00:mainfrom
abhinav-m22:fix/graph-retrieval-session-resolution
Open

fix: graph search silently dropping all results#937
abhinav-m22 wants to merge 4 commits into
rohitg00:mainfrom
abhinav-m22:fix/graph-retrieval-session-resolution

Conversation

@abhinav-m22

@abhinav-m22 abhinav-m22 commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Graph search was finding the right observations and then throwing them all away.

GraphNode never stored a sessionId, so graph-retrieval.ts hardcoded sessionId: "" on every result. enrichResults then looked them up via KV.observations(""), got nothing, and silently dropped them — so graphScore was always null and graphContext never showed up. The whole graph retrieval path was effectively dead for observations.

  • Stores sessionId on GraphNode, stamped at extract time (both graph-extract and temporal-graph-extract)
  • Retrieval now uses that session, but verifies it against KV first. A node can accumulate observations across several sessions while only storing the most recent one, so trusting the hint blindly would re-break the same thing for the older obs. On a miss it falls back to scanning sessions for the real owner.
  • Legacy nodes written before this change have no sessionId — they resolve via the same scan, so nothing needs a migration.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Graph nodes can now carry an optional session identifier, improving provenance tracking for extracted and retrieved graph content.
    • Session identifiers are resolved more accurately during graph search and expansion, with fallback scanning when hints are missing or stale.
  • Tests

    • Added a dedicated test suite and cases validating session ID propagation and resolution across search, traversal, expansion, legacy nodes, and failure scenarios.
    • Added coverage ensuring graph extraction stamps all created nodes with the correct session identifier.

@vercel

vercel Bot commented Jun 15, 2026

Copy link
Copy Markdown

@abhinav-m22 is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: aafbf4d3-b9ec-47c2-ab47-6c8c31856d05

📥 Commits

Reviewing files that changed from the base of the PR and between bf998d0 and c6d3942.

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

📝 Walkthrough

Walkthrough

Adds an optional sessionId field to GraphNode, then propagates it through graph.ts and temporal-graph.ts extraction pipelines via a new sessionByObsId parameter. GraphRetrieval now seeds sessionId hints from node data and runs a resolveSessionIds helper that KV-verifies and corrects each hint (with session-scan fallback) on the top-K results before returning.

Changes

sessionId propagation and resolution across graph extraction and retrieval

Layer / File(s) Summary
GraphNode sessionId type contract
src/types.ts
Adds optional sessionId?: string to the GraphNode interface with documentation for its role and backward-compatibility behavior.
Session propagation in graph extraction
src/functions/graph.ts, test/graph.test.ts
mergeNode refreshes sessionId from the incoming node; parseGraphXml accepts a sessionByObsId map and stamps sessionId on constructed nodes; mem::graph-extract builds the map and passes it to the parser. Test asserts every extracted node carries the source sessionId.
Session propagation in temporal graph extraction
src/functions/temporal-graph.ts
parseTemporalGraphXml gains a sessionByObsId parameter that drives sessionId annotation on emitted nodes; mem::temporal-graph-extract builds the map and passes it into the parser; KV merge refreshes sessionId when the new extract resolved one.
Session hint population and KV-backed resolver in GraphRetrieval
src/functions/graph-retrieval.ts, test/graph-retrieval.test.ts
searchByEntities and expandFromChunks now seed sessionId hints from node data. New resolveSessionIds private helper verifies each hint via KV, scans known sessions on misses, and mutates the result before returning. Tests cover start-node, edge-traversal, expandFromChunks, legacy backfill, stale-hint correction, no-session fallback, and KV listing failure handling.

Sequence Diagram(s)

sequenceDiagram
  participant Extraction as graph-extract / temporal-graph-extract
  participant Parse as parseGraphXml / parseTemporalGraphXml
  participant Retrieval as GraphRetrieval.searchByEntities
  participant Resolver as resolveSessionIds
  participant KV

  Extraction->>Extraction: build sessionByObsId from input observations
  Extraction->>Parse: pass sessionByObsId map
  Parse->>Parse: resolve sessionId for each entity node
  Parse-->>Extraction: GraphNode[] with sessionId

  Extraction->>KV: merge extracted nodes with sessionId

  Retrieval->>Retrieval: build results, seed sessionId from node data
  Retrieval->>Resolver: top-K results with sessionId hints
  Resolver->>KV: verify hint in hinted session (fast path)
  alt hint valid
    KV-->>Resolver: observation found
  else hint invalid or empty
    Resolver->>KV: list known sessions (lazy, once)
    loop scan sessions
      Resolver->>KV: probe each session for observation
      alt found
        KV-->>Resolver: owning session located
      end
    end
  end
  Resolver->>Resolver: mutate result.sessionId with resolved value
  Resolver-->>Retrieval: results with authoritative sessionIds
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • rohitg00/agentmemory#816: Both PRs modify src/functions/graph.ts graph extraction path (including mem::graph-extract and merge behavior), so the sessionId propagation in this PR overlaps with snapshot/index-based extraction rewrites in that PR.

Poem

🐇 A sessionId was lost in the graph's wide sea,
Each node now wears its session tag with glee.
We verify the hint, then scan if wrong,
No memory leaks where they don't belong.
The rabbit stamps each node and hops along! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: graph search silently dropping all results' accurately reflects the main issue being addressed—the critical bug where graph search results were being discarded.
Linked Issues check ✅ Passed All coding requirements from #925 are met: sessionId field added to GraphNode, propagated through graph-extract and temporal-graph-extract, retrieval logic updated with verification and fallback scanning, and backward compatibility ensured.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the identified issues: GraphNode type extension, extraction logic propagation, retrieval logic enhancement, and supporting tests—no unrelated modifications detected.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@abhinav-m22 abhinav-m22 marked this pull request as ready for review June 15, 2026 12:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/functions/temporal-graph.ts (1)

172-304: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add audit recording for mem::temporal-graph-extract state mutations.

This function writes/updates graph nodes and edges but does not emit an audit entry, so state changes are not traceable in the audit stream.

Proposed fix
 import { logger } from "../logger.js";
+import { recordAudit } from "./audit.js";
@@
         logger.info("Temporal graph extraction complete", {
           nodes: nodes.length,
           edges: edges.length,
         });
+        await recordAudit(
+          kv,
+          "observe",
+          "mem::temporal-graph-extract",
+          obsIds,
+          {
+            nodesExtracted: nodes.length,
+            edgesExtracted: edges.length,
+          },
+        );
         return {
           success: true,
           nodesAdded: nodes.length,
           edgesAdded: edges.length,
         };

As per coding guidelines: src/**/*.ts state-changing operations should use recordAudit().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/functions/temporal-graph.ts` around lines 172 - 304, The
mem::temporal-graph-extract function performs multiple state mutations by
calling kv.set() for graph nodes, graph edges, and graph edge history, but does
not record any audit entries for these operations. Add recordAudit() calls after
each kv.set() operation to ensure all state changes are traceable in the audit
stream: one audit entry when nodes are created or updated (when setting
KV.graphNodes), one when edges are created or updated (when setting
KV.graphEdges), and one when edge history is recorded (when setting
KV.graphEdgeHistory). Include appropriate context in each audit entry such as
the action performed and the IDs affected.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/functions/graph-retrieval.ts`:
- Around line 93-95: The fallback resolution code in the sessions initialization
block does not handle potential exceptions from the kv.list call. Wrap the await
this.kv.list<Session>(KV.sessions) statement in a try-catch block to gracefully
handle list failures. In the catch block, set sessions to an empty collection as
a safe fallback instead of allowing the error to propagate. This allows
searchByEntities and expandFromChunks to continue with degraded functionality by
falling back to an unresolved sessionId ("") rather than aborting the entire
retrieval process.

---

Outside diff comments:
In `@src/functions/temporal-graph.ts`:
- Around line 172-304: The mem::temporal-graph-extract function performs
multiple state mutations by calling kv.set() for graph nodes, graph edges, and
graph edge history, but does not record any audit entries for these operations.
Add recordAudit() calls after each kv.set() operation to ensure all state
changes are traceable in the audit stream: one audit entry when nodes are
created or updated (when setting KV.graphNodes), one when edges are created or
updated (when setting KV.graphEdges), and one when edge history is recorded
(when setting KV.graphEdgeHistory). Include appropriate context in each audit
entry such as the action performed and the IDs affected.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 591030c8-8155-42c0-a913-84c88171a332

📥 Commits

Reviewing files that changed from the base of the PR and between f6f9e3c and bf998d0.

📒 Files selected for processing (6)
  • src/functions/graph-retrieval.ts
  • src/functions/graph.ts
  • src/functions/temporal-graph.ts
  • src/types.ts
  • test/graph-retrieval.test.ts
  • test/graph.test.ts

Comment thread src/functions/graph-retrieval.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

graph search silently drops all results due to hardcoded sessionId: ""

1 participant