mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(memory): read the relation key the memory_save schema advertises (#4647)
## Description Item 7 of #4362. `memory_save`'s plain `relationships[]` schema names the relationship key `relation` (`headroom/memory/tools.py:82-88`, also the compact schema at `:384-387`), but `LocalBackend.save_memory` read only `type` (`headroom/memory/backends/local.py:390` on `e4a60ed7`). Every relationship a model saved through the tool was therefore stored as the default `related_to`, and graph queries filtered by relation type found nothing. The optimized `extracted_relationships` path already converts its own key and is unchanged. `save_memory` now reads `type` first (the class docstring example and direct callers use it), then `relation`, then falls back to `related_to`. The schema is not changed, so clients that already send `relation` start working without a change on their side. Refs #4362 ## 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/local.py`: `rel_type = rel.get("type") or rel.get("relation") or "related_to"`, with a one-line comment naming the two key spellings. - `tests/test_memory/test_local_relationship_key.py` (new): pins that the advertised schema uses `relation`, and that `save_memory` stores `works_with` from `{"relation": ...}`, `manages` from `{"type": ...}`, and `related_to` when neither key is present. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) (run on `headroom/memory/backends/local.py` only, see below) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text # fail before (source ate4a60ed7, new test kept) FAILED tests/test_memory/test_local_relationship_key.py::test_relationship_type_is_read_from_relation_or_type[rel0-works_with] 1 failed, 3 passed # pass after 4 passed # tests/test_memory + tests/test_memory_system.py + tests/test_sqlite_graph_store.pye4a60ed7: 1 failed, 693 passed, 165 skipped (the failure is the new test) this branch: 694 passed, 165 skipped # ruff check / ruff format --check: All checks passed! / 2 files already formatted # mypy headroom/memory/backends/local.py: Success: no issues found in 1 source file ``` ## Real Behavior Proof - Environment: Ubuntu (WSL2) on Windows 11, Python 3.12.15, `headroom` Python source at `e4a60ed7` and at this branch, offline. - Exact command / steps: `MemorySystem(LocalBackend, user_id="alice").process_tool_call("memory_save", {"content": "Alice works with Bob on the billing service", "importance": 0.7, "entities": ["Alice", "Bob"], "relationships": [{"source": "Alice", "relation": "works_with", "target": "Bob"}]})`, with a real `SQLiteGraphStore` on a temporary file as the backend's graph; then `get_entity_by_name("alice", "Alice")` and `get_relationships(...)` on that store. - Observed result: on `e4a60ed7` the stored `relation_type` is `['related_to']`; on this branch it is `['works_with']`. Both runs return `success: True`. - Not tested: the vector/text side of `LocalBackend` was stubbed (no embedder offline), so the proof covers the graph write only. Not tested: the mem0 and Qdrant/Neo4j backends, and `mypy headroom` as a whole. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A - Stable/default behavior changed: Yes, narrowly: a relationship saved with the schema's `relation` key is stored with that relation type instead of `related_to`. Relationships stored before this change keep `related_to`. - Kill switch / disable path: None added; revert. - Unsafe override required: No - Qualification impact: None expected - Rollback path: revert this commit. ## 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 - [ ] 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) ## Screenshots (if applicable) N/A ## Additional Notes One logical change per PR, as CONTRIBUTING asks: this covers item 7 of #4362 only. Of the other items, 3 is fixed by #4365, 4 is #3308, and 8 is #4452. Produced with AI assistance (Claude Code) operated by me (HetCreep); the reproduction was run on my machine against a clone of the repository. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4647" 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 --> ### Maintainer qualification against current main Qualified source head `0e29e3faa7a505431de80893915ab1fd7ff5fb02` against upstream main `e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`. 58 focused relation, SQLite graph, and Gemini fixture tests passed. Independent public MemorySystem(LocalBackend).process_tool_call("memory_save", ...) ran through composed HierarchicalMemory/SQLite/HNSW/FTS and SQLiteGraphStore. Reopening the graph preserved works_with on this PR; actual main stored related_to for the identical schema-advertised relation input. Both tool calls reported success. Deterministic embeddings were used; no cloud or model-factory qualification is claimed. The maintainer cherry-picked only the shared Gemini test-fixture repair from #4644: real Starlette Request with two ASGI receive chunks, preserving the existing test assertions. This addresses the same four independently verified failures on main; contributor production logic is unchanged. Ruff, formatting, and whitespace checks passed. Exact-head hosted CI is being checked before formal approval. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
JerrettDavis
Claude Opus 5.5
parent
ee638f9532
commit
7592e68145
@@ -387,7 +387,9 @@ class LocalBackend:
|
||||
for rel in all_relationships:
|
||||
source_name = rel.get("source", "").lower()
|
||||
target_name = rel.get("target", "").lower()
|
||||
rel_type = rel.get("type", "related_to")
|
||||
# The memory_save tool schema names the key `relation`
|
||||
# (tools.py); direct callers and older docs use `type`.
|
||||
rel_type = rel.get("type") or rel.get("relation") or "related_to"
|
||||
|
||||
source_id = entity_id_map.get(source_name)
|
||||
target_id = entity_id_map.get(target_name)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""The local backend reads the relationship key the memory_save schema advertises.
|
||||
|
||||
`memory_save`'s plain `relationships[]` schema (headroom/memory/tools.py) names the
|
||||
relationship key `relation`. LocalBackend.save_memory read only `type`, so every
|
||||
relationship saved through the tool was stored as the default `related_to`.
|
||||
See https://github.com/headroomlabs-ai/headroom/issues/4362 (item 7).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from headroom.memory.backends.local import LocalBackend
|
||||
from headroom.memory.models import Memory
|
||||
from headroom.memory.tools import MEMORY_TOOLS
|
||||
|
||||
|
||||
def _backend() -> tuple[LocalBackend, AsyncMock]:
|
||||
backend = LocalBackend()
|
||||
backend._initialized = True
|
||||
|
||||
async def fake_add(**kwargs: object) -> Memory:
|
||||
return Memory(
|
||||
id="m1",
|
||||
content=str(kwargs["content"]),
|
||||
user_id=str(kwargs["user_id"]),
|
||||
entity_refs=list(kwargs["entity_refs"]), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
async def fake_add_entity(entity: object) -> object:
|
||||
return entity
|
||||
|
||||
add_relationship = AsyncMock()
|
||||
backend._hierarchical_memory = SimpleNamespace(add=AsyncMock(side_effect=fake_add))
|
||||
backend._graph = SimpleNamespace(
|
||||
get_entity_by_name=AsyncMock(side_effect=lambda user_id, name: None),
|
||||
add_entity=AsyncMock(side_effect=fake_add_entity),
|
||||
add_relationship=add_relationship,
|
||||
)
|
||||
return backend, add_relationship
|
||||
|
||||
|
||||
def test_schema_names_the_key_relation() -> None:
|
||||
"""Pins the premise: the advertised schema uses `relation`, not `type`."""
|
||||
save = next(t for t in MEMORY_TOOLS if t["function"]["name"] == "memory_save")
|
||||
item = save["function"]["parameters"]["properties"]["relationships"]["items"]
|
||||
assert "relation" in item["required"]
|
||||
assert "type" not in item["properties"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("rel", "expected"),
|
||||
[
|
||||
({"source": "Alice", "relation": "works_with", "target": "Bob"}, "works_with"),
|
||||
({"source": "Alice", "type": "manages", "target": "Bob"}, "manages"),
|
||||
({"source": "Alice", "target": "Bob"}, "related_to"),
|
||||
],
|
||||
)
|
||||
async def test_relationship_type_is_read_from_relation_or_type(
|
||||
rel: dict[str, str], expected: str
|
||||
) -> None:
|
||||
backend, add_relationship = _backend()
|
||||
|
||||
await backend.save_memory(
|
||||
content="Alice works with Bob",
|
||||
user_id="alice",
|
||||
entities=["Alice", "Bob"],
|
||||
relationships=[rel],
|
||||
)
|
||||
|
||||
add_relationship.assert_awaited_once()
|
||||
stored = add_relationship.await_args.args[0]
|
||||
assert stored.relation_type == expected
|
||||
Reference in New Issue
Block a user