mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(memory): return stored id from a background DirectMem0 save (#4759)
## Description `DirectMem0Adapter.save_memory(background=True)` returned an id from a second `_generate_id` call. That helper salts with the current time, so the returned id never matched the Qdrant point the background task wrote, and a later `memory_update` / `memory_delete` with it found nothing. The direct-write ids are now generated once, passed to the background task, and returned. On the Mem0 extraction path (no pre-extracted data), Mem0 assigns ids itself, so no id is known up front. The save is marked `_id_pending`, and `memory_save` reports `memory_id: None` instead of an invented id. The real id is available from `get_task_status(task_id)`. Refs #4362 (item 6 only). ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `headroom/memory/backends/direct_mem0.py`: generate fact ids before scheduling the background task, then store and return those same ids. `_write_facts_to_qdrant` accepts optional `memory_ids`. Mem0-path background saves are marked `_id_pending`. Fixed the `_generate_id` docstring, which said the ids were "deterministic". - `headroom/memory/system.py`: `memory_save` returns `memory_id: None` when the id is pending. - Background saves snapshot `facts` before generating ids and schedule that same snapshot, so a caller mutating its list after queueing can't make the task fail. The returned `_all_memory_ids` is a copy for the same reason. - `tests/test_memory/test_direct_mem0_background_ids.py`: 4 regression tests, using a fake Qdrant client and a fake Mem0 client. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ pytest tests/test_memory/test_direct_mem0_background_ids.py -v test_background_save_returns_stored_fact_id PASSED test_mutating_lists_after_queueing_does_not_break_the_save PASSED test_background_mem0_extraction_does_not_invent_an_id PASSED test_memory_save_tool_withholds_a_pending_id PASSED 4 passed in 0.36s ``` ## Real Behavior Proof - Environment: macOS; Qdrant v1.15.5 server in Docker (`localhost:6333`); `mem0ai` 2.2.1 and `qdrant-client` 1.20.0 (real `Memory.get/update/delete`); embeddings from Ollama 0.40.6 `nomic-embed-text` through its OpenAI-compatible API (`OPENAI_BASE_URL=http://localhost:11434/v1`). `DirectMem0Adapter` ran unmodified, with `enable_graph=False`. - Exact command / steps: a script on a fresh 768-dim collection: `save_memory(facts=[...], background=True)` → append to the caller's `facts` list → `flush_pending()` → `get_memory` / `update_memory` / `get_memory` / `delete_memory` / `get_memory`, all using the **returned** id. Run once on this branch and once on `main` (`a385ea8e`) as a control. - Observed result: Returned IDs resolve to the stored points; before/after results are below. | | this branch | `main` | |---|---|---| | task status | completed | completed | | returned id is a stored Qdrant point | **True** | False | | `get_memory(returned id)` | `'Prefers Python over JavaScript'` | `None` | | `update_memory` → `get_memory` | `'Prefers Rust over Python'` | `Memory with id 0ad08f… not found` | | `delete_memory(returned id)` | `True`, 0 points left | `False`, 2 points left | | fact appended after queueing | not stored (snapshot) | stored under an id never returned to the caller | - Not tested: the Mem0 LLM-extraction background path (`_id_pending`; it needs an OpenAI LLM and none was available); Neo4j graph writes; hosted Qdrant; OpenAI's own embedding API. ## Runtime Rollout Safety - Rollout-managed feature(s): None - Minimum rollout channel: NA - Stable/default behavior changed: Only background saves on `DirectMem0Adapter` (opt-in via `background=true` or `async_writes=True`). The proxy doesn't use background saves. Synchronous saves are unchanged. - Kill switch / disable path: Don't use background saves. - Unsafe override required: NA - Qualification impact: None - Rollback path: Revert this PR ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4759" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JD Davis
parent
177fab3782
commit
6665940656
@@ -335,7 +335,7 @@ class DirectMem0Adapter:
|
||||
return list(response.data[0].embedding)
|
||||
|
||||
def _generate_id(self, content: str, user_id: str) -> str:
|
||||
"""Generate a deterministic ID for a memory."""
|
||||
"""Generate a unique (time-salted) ID for a memory."""
|
||||
hash_input = f"{user_id}:{content}:{_utcnow().isoformat()}"
|
||||
return hashlib.sha256(hash_input.encode()).hexdigest()[:32]
|
||||
|
||||
@@ -345,6 +345,7 @@ class DirectMem0Adapter:
|
||||
user_id: str,
|
||||
importance: float,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
memory_ids: list[str] | None = None,
|
||||
) -> list[str]:
|
||||
"""Write pre-extracted facts directly to Qdrant.
|
||||
|
||||
@@ -358,19 +359,21 @@ class DirectMem0Adapter:
|
||||
user_id: User identifier.
|
||||
importance: Importance score.
|
||||
metadata: Optional additional metadata.
|
||||
memory_ids: Optional IDs to store the facts under, one per fact.
|
||||
|
||||
Returns:
|
||||
List of memory IDs for the stored facts.
|
||||
"""
|
||||
from qdrant_client.models import PointStruct
|
||||
|
||||
if memory_ids is None:
|
||||
memory_ids = [self._generate_id(fact, user_id) for fact in facts]
|
||||
elif len(memory_ids) != len(facts):
|
||||
raise ValueError(f"Got {len(memory_ids)} memory IDs for {len(facts)} facts")
|
||||
|
||||
points = []
|
||||
memory_ids = []
|
||||
|
||||
for fact in facts:
|
||||
memory_id = self._generate_id(fact, user_id)
|
||||
memory_ids.append(memory_id)
|
||||
|
||||
for fact, memory_id in zip(facts, memory_ids):
|
||||
# Generate embedding
|
||||
embedding = await asyncio.to_thread(self._embed, fact)
|
||||
|
||||
@@ -656,6 +659,14 @@ class DirectMem0Adapter:
|
||||
task_id = self._generate_task_id()
|
||||
now = _utcnow()
|
||||
|
||||
# Snapshot facts so a caller mutating its list can't desync the IDs.
|
||||
facts = list(facts) if facts is not None else None
|
||||
|
||||
# Pick the IDs now so the returned ID is the one actually stored.
|
||||
fact_ids: list[str] | None = None
|
||||
if facts or extracted_entities or extracted_relationships:
|
||||
fact_ids = [self._generate_id(fact, user_id) for fact in (facts or [content])]
|
||||
|
||||
# Create the background task
|
||||
task = asyncio.create_task(
|
||||
self._save_memory_internal(
|
||||
@@ -669,12 +680,20 @@ class DirectMem0Adapter:
|
||||
facts=facts,
|
||||
extracted_entities=extracted_entities,
|
||||
extracted_relationships=extracted_relationships,
|
||||
fact_ids=fact_ids,
|
||||
)
|
||||
)
|
||||
self._background_tasks[task_id] = task
|
||||
|
||||
# Return immediately with task info
|
||||
primary_id = self._generate_id(facts[0] if facts else content, user_id)
|
||||
pending_metadata: dict[str, Any]
|
||||
if fact_ids is not None:
|
||||
primary_id = fact_ids[0]
|
||||
pending_metadata = {"_all_memory_ids": list(fact_ids)}
|
||||
else:
|
||||
# Mem0 assigns the ID later; see get_task_status(task_id).
|
||||
primary_id = task_id
|
||||
pending_metadata = {"_id_pending": True}
|
||||
return Memory(
|
||||
id=primary_id,
|
||||
content=facts[0] if facts else content,
|
||||
@@ -684,6 +703,7 @@ class DirectMem0Adapter:
|
||||
entity_refs=entities or [],
|
||||
metadata={
|
||||
**(metadata or {}),
|
||||
**pending_metadata,
|
||||
"_async": True,
|
||||
"_task_id": task_id,
|
||||
"_status": "processing",
|
||||
@@ -718,6 +738,7 @@ class DirectMem0Adapter:
|
||||
facts: list[str] | None = None,
|
||||
extracted_entities: list[dict[str, str]] | None = None,
|
||||
extracted_relationships: list[dict[str, str]] | None = None,
|
||||
fact_ids: list[str] | None = None,
|
||||
) -> Memory:
|
||||
"""Internal save implementation (can run in background)."""
|
||||
now = _utcnow()
|
||||
@@ -730,31 +751,18 @@ class DirectMem0Adapter:
|
||||
memory_ids = []
|
||||
|
||||
# Write facts to Qdrant (vector store)
|
||||
if facts:
|
||||
fact_ids = await self._write_facts_to_qdrant(
|
||||
facts=facts,
|
||||
user_id=user_id,
|
||||
importance=importance,
|
||||
metadata={
|
||||
"session_id": session_id,
|
||||
"entity_refs": entities or [],
|
||||
**(metadata or {}),
|
||||
},
|
||||
)
|
||||
memory_ids.extend(fact_ids)
|
||||
else:
|
||||
# If no facts, write content as single fact
|
||||
fact_ids = await self._write_facts_to_qdrant(
|
||||
facts=[content],
|
||||
user_id=user_id,
|
||||
importance=importance,
|
||||
metadata={
|
||||
"session_id": session_id,
|
||||
"entity_refs": entities or [],
|
||||
**(metadata or {}),
|
||||
},
|
||||
)
|
||||
memory_ids.extend(fact_ids)
|
||||
stored_ids = await self._write_facts_to_qdrant(
|
||||
facts=facts or [content],
|
||||
user_id=user_id,
|
||||
importance=importance,
|
||||
metadata={
|
||||
"session_id": session_id,
|
||||
"entity_refs": entities or [],
|
||||
**(metadata or {}),
|
||||
},
|
||||
memory_ids=fact_ids,
|
||||
)
|
||||
memory_ids.extend(stored_ids)
|
||||
|
||||
# Write entities and relationships to Neo4j (graph store)
|
||||
if (extracted_entities or extracted_relationships) and self._config.enable_graph:
|
||||
|
||||
@@ -437,6 +437,9 @@ class MemorySystem:
|
||||
result["task_id"] = memory.metadata.get("_task_id")
|
||||
result["status"] = memory.metadata.get("_status", "processing")
|
||||
result["message"] = f"Memory save queued (task: {result['task_id']})"
|
||||
if memory.metadata.get("_id_pending"):
|
||||
# The real ID isn't known until the background task runs.
|
||||
result["memory_id"] = None
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Background DirectMem0Adapter saves return the stored id (#4362 item 6)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import types
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from headroom.memory.backends.direct_mem0 import DirectMem0Adapter, Mem0Config
|
||||
from headroom.memory.system import MemorySystem
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PointStruct:
|
||||
id: str
|
||||
vector: list[float]
|
||||
payload: dict[str, Any]
|
||||
|
||||
|
||||
class _RecordingQdrant:
|
||||
def __init__(self) -> None:
|
||||
self.points: list[_PointStruct] = []
|
||||
|
||||
def upsert(self, collection_name: str, points: list[_PointStruct]) -> None:
|
||||
self.points.extend(points)
|
||||
|
||||
|
||||
class _RecordingMem0:
|
||||
def __init__(self) -> None:
|
||||
self.calls = 0
|
||||
|
||||
def add(self, content: str, user_id: str, metadata: dict[str, Any]) -> dict[str, Any]:
|
||||
self.calls += 1
|
||||
return {"results": [{"id": "mem0-assigned-id", "memory": content}]}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def adapter(monkeypatch: pytest.MonkeyPatch) -> DirectMem0Adapter:
|
||||
models = types.ModuleType("qdrant_client.models")
|
||||
models.PointStruct = _PointStruct # type: ignore[attr-defined]
|
||||
package = types.ModuleType("qdrant_client")
|
||||
package.models = models # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "qdrant_client", package)
|
||||
monkeypatch.setitem(sys.modules, "qdrant_client.models", models)
|
||||
|
||||
instance = DirectMem0Adapter(Mem0Config(enable_graph=False))
|
||||
instance._initialized = True
|
||||
instance._qdrant_client = _RecordingQdrant()
|
||||
instance._mem0_client = _RecordingMem0()
|
||||
monkeypatch.setattr(instance, "_embed", lambda text: [0.0, 1.0])
|
||||
return instance
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_background_save_returns_stored_fact_id(adapter: DirectMem0Adapter) -> None:
|
||||
returned = await adapter.save_memory(
|
||||
content="ignored when facts are given",
|
||||
user_id="alice",
|
||||
importance=0.7,
|
||||
facts=["Prefers Python", "Works at Acme"],
|
||||
background=True,
|
||||
)
|
||||
await adapter.flush_pending()
|
||||
|
||||
stored_ids = [point.id for point in adapter._qdrant_client.points]
|
||||
assert stored_ids, "background task wrote nothing"
|
||||
assert returned.id == stored_ids[0]
|
||||
assert returned.metadata["_all_memory_ids"] == stored_ids
|
||||
|
||||
status = adapter.get_task_status(returned.metadata["_task_id"])
|
||||
assert status["status"] == "completed"
|
||||
assert status["result"].id == returned.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mutating_lists_after_queueing_does_not_break_the_save(
|
||||
adapter: DirectMem0Adapter,
|
||||
) -> None:
|
||||
facts = ["A"]
|
||||
returned = await adapter.save_memory(
|
||||
content="x", user_id="alice", importance=0.5, facts=facts, background=True
|
||||
)
|
||||
facts.append("B")
|
||||
returned.metadata["_all_memory_ids"].append("bogus")
|
||||
await adapter.flush_pending()
|
||||
|
||||
status = adapter.get_task_status(returned.metadata["_task_id"])
|
||||
assert status["status"] == "completed", status
|
||||
assert [p.payload["memory"] for p in adapter._qdrant_client.points] == ["A"]
|
||||
assert [p.id for p in adapter._qdrant_client.points] == [returned.id]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_background_mem0_extraction_does_not_invent_an_id(
|
||||
adapter: DirectMem0Adapter,
|
||||
) -> None:
|
||||
"""Without pre-extraction, Mem0 assigns ids itself; none can be known up front."""
|
||||
returned = await adapter.save_memory(
|
||||
content="Likes tea",
|
||||
user_id="alice",
|
||||
importance=0.5,
|
||||
background=True,
|
||||
)
|
||||
|
||||
assert returned.metadata["_id_pending"] is True
|
||||
assert returned.id == returned.metadata["_task_id"]
|
||||
|
||||
await adapter.flush_pending()
|
||||
status = adapter.get_task_status(returned.metadata["_task_id"])
|
||||
assert status["result"].id == "mem0-assigned-id"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_memory_save_tool_withholds_a_pending_id(adapter: DirectMem0Adapter) -> None:
|
||||
system = MemorySystem(adapter, user_id="alice")
|
||||
|
||||
result = await system.process_tool_call(
|
||||
"memory_save", {"content": "Likes tea", "importance": 0.6, "background": True}
|
||||
)
|
||||
await adapter.flush_pending()
|
||||
|
||||
assert result["async"] is True
|
||||
assert result["memory_id"] is None
|
||||
assert result["task_id"]
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Background IDs against embedded Qdrant with deterministic synthetic embeddings."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from headroom.memory.backends.direct_mem0 import DirectMem0Adapter, Mem0Config
|
||||
from tests.test_memory.test_direct_mem0 import _inmemory_mem0, _vec3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_queued_id_supports_persistent_qdrant_read_update_delete(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
qdrant = pytest.importorskip("qdrant_client")
|
||||
from qdrant_client.models import Distance, PointIdsList, VectorParams
|
||||
|
||||
storage = tmp_path / "qdrant"
|
||||
config = Mem0Config(enable_graph=False)
|
||||
client = qdrant.QdrantClient(path=str(storage))
|
||||
client.create_collection(
|
||||
collection_name=config.collection_name,
|
||||
vectors_config=VectorParams(size=2, distance=Distance.COSINE),
|
||||
)
|
||||
adapter = DirectMem0Adapter(config)
|
||||
adapter._initialized = True
|
||||
adapter._qdrant_client = client
|
||||
monkeypatch.setattr(adapter, "_embed", lambda text: [0.0, 1.0])
|
||||
try:
|
||||
facts = ["Prefers Python"]
|
||||
returned = await adapter.save_memory(
|
||||
content="fallback",
|
||||
user_id="alice",
|
||||
importance=0.7,
|
||||
facts=facts,
|
||||
background=True,
|
||||
)
|
||||
facts.append("Later caller edit")
|
||||
await adapter.flush_pending()
|
||||
status = adapter.get_task_status(returned.metadata["_task_id"])
|
||||
assert status["status"] == "completed"
|
||||
assert status["result"].id == returned.id
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
# Reopening exercises disk persistence, using the ID returned before the write.
|
||||
client = qdrant.QdrantClient(path=str(storage))
|
||||
try:
|
||||
points = client.retrieve(collection_name=config.collection_name, ids=[returned.id])
|
||||
assert len(points) == 1
|
||||
assert points[0].payload["data"] == "Prefers Python"
|
||||
assert points[0].payload["user_id"] == "alice"
|
||||
assert client.count(collection_name=config.collection_name).count == 1
|
||||
|
||||
client.set_payload(
|
||||
collection_name=config.collection_name,
|
||||
points=[returned.id],
|
||||
payload={"data": "Prefers Rust", "memory": "Prefers Rust"},
|
||||
wait=True,
|
||||
)
|
||||
updated = client.retrieve(collection_name=config.collection_name, ids=[returned.id])
|
||||
assert updated[0].payload["data"] == "Prefers Rust"
|
||||
|
||||
client.delete(
|
||||
collection_name=config.collection_name,
|
||||
points_selector=PointIdsList(points=[returned.id]),
|
||||
wait=True,
|
||||
)
|
||||
assert client.retrieve(collection_name=config.collection_name, ids=[returned.id]) == []
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_background_id_supports_real_mem0_read_update_delete(tmp_path) -> None:
|
||||
"""Use real Mem0/Qdrant APIs with the existing deterministic embedder."""
|
||||
mem0_memory, qdrant = _inmemory_mem0(tmp_path)
|
||||
adapter = DirectMem0Adapter(Mem0Config(enable_graph=False))
|
||||
adapter._initialized = True
|
||||
adapter._qdrant_client = qdrant
|
||||
adapter._mem0_client = mem0_memory
|
||||
adapter._embed = _vec3
|
||||
try:
|
||||
facts = ["Prefers Python"]
|
||||
returned = await adapter.save_memory(
|
||||
content="fallback",
|
||||
user_id="alice",
|
||||
importance=0.7,
|
||||
facts=facts,
|
||||
background=True,
|
||||
)
|
||||
facts.append("Later caller edit")
|
||||
await adapter.flush_pending()
|
||||
status = adapter.get_task_status(returned.metadata["_task_id"])
|
||||
assert status["status"] == "completed"
|
||||
assert status["result"].id == returned.id
|
||||
|
||||
stored = await adapter.get_memory(returned.id)
|
||||
assert stored is not None
|
||||
assert stored.content == "Prefers Python"
|
||||
assert stored.user_id == "alice"
|
||||
await adapter.update_memory(returned.id, "Prefers Rust", user_id="alice")
|
||||
updated = await adapter.get_memory(returned.id)
|
||||
assert updated is not None
|
||||
assert updated.content == "Prefers Rust"
|
||||
assert await adapter.delete_memory(returned.id, user_id="alice")
|
||||
assert await adapter.get_memory(returned.id) is None
|
||||
mem0_memory.llm.generate_response.assert_not_called()
|
||||
finally:
|
||||
await adapter.close()
|
||||
Reference in New Issue
Block a user