Skip to content

recent_activity hydrate_context has N+1 entity lookup pattern #710

Closed

Description

@phernandez

Problem

recent_activity is called frequently (112 times in the last 12h) and its shape_response phase has the same N+1 entity lookup pattern as search hydration (issue #707).

Inside shape_response, memory.hydrate_context.lookup_entities fetches entities one-by-one, paying Neon network latency per lookup. This averages 0.3s but spikes to 1.8s for larger result sets.

Evidence (last 12h, 112 calls)

Phase Avg P50 P95 Calls
build_context 0.45s 0.43s 0.62s 112
shape_response 0.30s 0.31s 0.39s 112

Worst case traces drilling into shape_response:

Trace 1 (shape_response: 1.84s):

shape_response                        1.837s
└── memory.hydrate_context            1.834s
    ├── lookup_entities               1.817s  ← N+1 queries
    └── shape_results                 0.013s

Trace 2 (shape_response: 0.46s):

shape_response                        0.462s
└── memory.hydrate_context            0.460s
    ├── lookup_entities               0.430s  ← N+1 queries
    └── shape_results                 0.026s

Trace 3 (shape_response: 0.43s):

shape_response                        0.430s
└── memory.hydrate_context            0.429s
    ├── lookup_entities               0.415s  ← N+1 queries
    └── shape_results                 0.011s

In all cases, lookup_entities dominates the phase.

Proposed Fix

Same approach as #707: collect all entity IDs/permalinks needed for hydration upfront, then batch-fetch in a single find_by_ids query instead of one query per entity.

Impact

recent_activity is one of the most-called endpoints (112 calls/12h). Batching the entity lookup would save ~0.3s avg per call and eliminate the 1.8s worst-case spikes.

Related: #707 (same N+1 pattern in search hydration)

Activity

  1. claude commented on Apr 1, 2026

    @claude
    Contributor

    Claude finished @phernandez's task in 7m 17s —— View job • claude/issue-710-20260401-2152 • Create PR ➔


    Triage & Implementation

    Triage:

    • Type: Enhancement / Performance Bug
    • Priority: Medium-High (frequent endpoint, 0.3s avg latency, 1.8s worst-case spikes)
    • Component: MCP / API v2 utils
    • Complexity: Medium

    Analysis: to_graph_context (used by recent_activity) already has the batch find_by_ids fix in place on main. The remaining N+1 issue is in to_search_results (used by search — related #707), which also had a pre-existing ordering bug where from_entity and to_entity both incorrectly pointed to entities[0] due to unordered IN-query results.

    • Analyze issue and classify
    • Read relevant source files
    • Verified to_graph_context (recent_activity) already uses batch find_by_ids — no change needed there
    • Fixed to_search_results N+1: collect all unique IDs (entity_id, from_id, to_id) upfront, batch-fetch in one query, use lookup dict — also fixes the pre-existing from_entity/to_entity ordering bug
    • Updated test_utils_telemetry.py: mock returns entities with .id, asserts from_entity/to_entity are now correctly resolved
    • Committed and pushed

    Changes:

    • src/basic_memory/api/v2/utils.py — replaced N+1 loop with single batch find_by_ids call
    • tests/api/v2/test_utils_telemetry.py — updated mock and added assertions for correct from_entity/to_entity resolution

    |

  2. added a commit that references this issue on Apr 1, 2026
    9de30dd
  3. added this to the teams-golive milestone on Apr 2, 2026
  4. phernandez commented on Apr 3, 2026

    @phernandez
    MemberAuthor

    Checked this on current main: the recent_activity / to_graph_context() hydration path is already batching entity lookups with a single find_by_ids(...) call, so there was no additional runtime fix needed here.

    I opened PR #716 to add regression coverage for that path so we keep the behavior locked in:

    • mixed entity/observation/relation hydration stays at one batched lookup
    • empty context results skip entity hydration entirely

    PR: #716

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestvalidatedTested and verified working

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions