Skip to content

bug: avoid full table scan on every delete/update in _remove_memory_from_entity_store #4988

@patricksurry

Description

@patricksurry

Component

Core / Python SDK

Description

Summary

_remove_memory_from_entity_store (mem0/memory/main.py L456) calls self.entity_store.list(filters=..., top_k=10000) on every memory delete or update. This fetches all entity rows including embedding vectors, then scans in Python for matching memory_id in linked_memory_ids.

This is (a) very slow and (b) incomplete when the store is >10K vectors.

Suggested fix: Use a targeted jsonb containment query on pgvector, which is about 40x faster on our instance (35K entities). The rest of the cleanup logic (delete if empty, update if remaining) stays the same.

  SELECT id, payload FROM {entity_table}
  WHERE payload->'linked_memory_ids' @> '["<memory_id>"]'::jsonb
    AND payload->>'agent_id' = %s

For other vector store backends, an equivalent targeted lookup could replace the full scan.

Environment

  • mem0 version: 2.0.0
  • Python version: 3.12.11
  • OS: macOS (Darwin 25.4.0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions