refactor(memory): deprecate the orphaned Mem0SystemAdapter (#4114)

## Description

`Mem0SystemAdapter` (`headroom/memory/backends/mem0_system_adapter.py`)
adapts `Mem0Backend` to the `MemorySystem` backend protocol. In that
design Mem0 runs its own LLM extraction: 3-4 LLM calls per save.
`DirectMem0Adapter` replaced it. Nothing in Headroom constructs it, and
no test covers it.

It is listed in `headroom.memory.backends.__all__` and lazily exported
from that package, so it is public API. This PR deprecates it instead of
deleting it: constructing it now emits a `DeprecationWarning`. It stays
in the subpackage `__all__` and in the lazy export, and importing
`headroom.memory.backends` stays quiet.

**What to use instead:**
- Local mode (Qdrant + Neo4j): `DirectMem0Adapter`, from
`headroom.memory.backends.direct_mem0` or the `headroom.memory.backends`
lazy export. It satisfies the same `MemoryBackend` protocol.
`save_memory` skips Mem0's LLM extraction only when the caller passes
non-empty pre-extracted `facts`, `extracted_entities` or
`extracted_relationships`. Passing only `content` with
`entities`/`relationships` still runs Mem0's extraction.
- Cloud mode (`Mem0Config(mode="cloud")`): there is no replacement in
Headroom, because `DirectMem0Adapter` has no cloud or API-key path. Use
the `mem0` client directly.

Evidence: `grep -rn Mem0SystemAdapter` across `headroom crates plugins
sdk docs wiki scripts benchmarks examples e2e .github tests` and the
consumer repos finds only the module itself and its lazy export in
`backends/__init__.py`.

Refs #4136

## Type of Change

- [ ] 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
- [x] Code refactoring (no functional changes)

## Changes Made

- `headroom/memory/backends/mem0_system_adapter.py`:
- `Mem0SystemAdapter.__init__` emits a `DeprecationWarning` with the
guidance above, shown in the proof below.
  - The module and class docstrings get `.. deprecated::`.
- `headroom/memory/backends/__init__.py`: the package docstring marks it
deprecated. `__all__` and the lazy export are unchanged, so the name
stays importable during the deprecation period.
- `tests/test_memory/test_mem0_system_adapter_deprecation.py` (new):
- asserts the warning fires. `Mem0Backend` is stubbed so the test does
not need the optional mem0 install;
- pins the migration guidance with spies on the Mem0 client and the
direct Qdrant/Neo4j writers. Non-empty `facts`, `extracted_entities` or
`extracted_relationships` skip Mem0's `add()`. `entities` alone,
`relationships` alone, or empty pre-extracted lists call it. The adapter
code is unchanged, so this test locks in current behaviour and passes
before and after.

## 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 -q -p no:cacheprovider tests/test_memory/test_mem0_system_adapter_deprecation.py tests/test_proxy_healthchecks.py tests/test_memory/test_direct_mem0.py tests/test_memory/test_qdrant_env.py
============================= 74 passed in 15.04s ==============================
$ python -W error::DeprecationWarning -c "import headroom.memory.backends; from headroom.memory.backends import mem0_system_adapter"
import ok, quiet
$ mypy headroom/memory/backends/mem0_system_adapter.py headroom/memory/backends/__init__.py --ignore-missing-imports
Success: no issues found in 2 source files
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13 (mem0 not installed), repo .venv,
branch checkout at 2aff9be2 (base a9815bbb), temp HOME /
HEADROOM_WORKSPACE_DIR / CODEX_HOME, offline.
- Exact command / steps:
- Ran the shared smoke harness, which starts a real proxy from this
checkout against a local fake upstream and sends one Anthropic and one
OpenAI request with a compressible tool result.
- Ran `python -W always`, which constructs the adapter with a local
`Mem0Config`. Construction is lazy, so it needs no services.
  - Ran the deprecation, health-check, DirectMem0 and Qdrant env tests.
- Observed result:
  - Both proxy requests return HTTP 200 with savings.
- Construction emits the new warning with the local and cloud guidance,
and the adapter is still built.
  - The tests pass.
- Not tested: Using the adapter against a live Mem0 install, local or
cloud. Behaviour after the warning is unchanged.

```text
$ bash smoke.sh <worktree>
branch: cleanup/memory-cache-deprecate-mem0-system-adapter @ dab5f560
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines:
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you 
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.

$ HOME=$TMP/home HEADROOM_WORKSPACE_DIR=$TMP/ws CODEX_HOME=$TMP/codex python -W always -c "<Mem0SystemAdapter(Mem0Config(mode='local'))>"
<string>:4: DeprecationWarning: Mem0SystemAdapter is deprecated and will be removed in a future release; for local mode use DirectMem0Adapter (headroom.memory.backends.direct_mem0), which skips Mem0's LLM extraction only when given pre-extracted facts, extracted_entities or extracted_relationships; cloud mode has no Headroom replacement, so use the mem0 client directly.
constructed: Mem0SystemAdapter
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; deprecation notice only.
- Stable/default behavior changed: No. The adapter works as before and
additionally warns when constructed.
- Kill switch / disable path: Standard `warnings` filters.
- Unsafe override required: No.
- Qualification impact: None.
- 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

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

- The audit first proposed deleting the module and its subpackage
`__all__` entry. Under the deprecate-first rule for public API, it is
deprecated here instead.
- Removal from `headroom.memory.backends.__all__` and from the lazy
export is deferred to the removal release.
- No user docs mention it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tejas Chopra
2026-10-10 09:04:25 -07:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 235043d39b
commit 7387b8cc11
3 changed files with 86 additions and 1 deletions
+2 -1
View File
@@ -3,7 +3,8 @@
This module provides backend adapters for the memory system:
- LocalBackend: Fully local using SQLite + HNSW + InMemoryGraph (default)
- Mem0Backend: Graph + vector memory via Mem0 (Neo4j + Qdrant)
- Mem0SystemAdapter: Adapter to use Mem0Backend with MemorySystem tools
- Mem0SystemAdapter: Adapter to use Mem0Backend with MemorySystem tools (deprecated;
use DirectMem0Adapter for local mode; cloud mode has no replacement)
- DirectMem0Adapter: Optimized adapter that bypasses Mem0's LLM extraction
LocalBackend is always available. Mem0-based backends require optional
@@ -2,12 +2,23 @@
This adapter bridges the Mem0Backend interface to the MemoryBackend protocol
required by MemorySystem, enabling Mem0 to be used with the memory tools system.
.. deprecated::
Nothing in Headroom uses this adapter. For local mode (Qdrant + Neo4j), use
``DirectMem0Adapter`` (``headroom.memory.backends.direct_mem0``), which also
satisfies the MemoryBackend protocol. ``save_memory`` skips Mem0's LLM
extraction only when the caller passes non-empty pre-extracted ``facts``,
``extracted_entities`` or ``extracted_relationships``. Passing only ``content``
with ``entities``/``relationships`` still runs Mem0's extraction. Cloud mode
(``Mem0Config(mode="cloud")``) has no replacement in Headroom; use the ``mem0``
client directly.
"""
from __future__ import annotations
import asyncio
import uuid
import warnings
from datetime import datetime, timezone
from typing import Any
@@ -24,6 +35,10 @@ def _utcnow() -> datetime:
class Mem0SystemAdapter:
"""Adapter that makes Mem0Backend conform to MemorySystem's MemoryBackend protocol.
.. deprecated::
Use ``DirectMem0Adapter`` for local mode. Cloud mode has no replacement in
Headroom; use the ``mem0`` client directly.
This adapter wraps Mem0Backend and provides the interface expected by
MemorySystem, enabling LLM-driven memory tools (memory_save, memory_search,
memory_update, memory_delete) to work with Mem0's graph and vector capabilities.
@@ -53,6 +68,15 @@ class Mem0SystemAdapter:
Args:
config: Configuration for Mem0. If None, uses default local config.
"""
warnings.warn(
"Mem0SystemAdapter is deprecated and will be removed in a future release; "
"for local mode use DirectMem0Adapter (headroom.memory.backends.direct_mem0), "
"which skips Mem0's LLM extraction only when given pre-extracted facts, "
"extracted_entities or extracted_relationships; "
"cloud mode has no Headroom replacement, so use the mem0 client directly.",
DeprecationWarning,
stacklevel=2,
)
self._backend = Mem0Backend(config)
self._config = config or Mem0Config()
@@ -0,0 +1,60 @@
"""Mem0SystemAdapter is deprecated in favour of DirectMem0Adapter."""
from __future__ import annotations
import pytest
from headroom.memory.backends import mem0_system_adapter
def test_mem0_system_adapter_warns_deprecated(monkeypatch: pytest.MonkeyPatch) -> None:
# Mem0Backend's constructor needs no live services, but stub it so the test
# does not depend on the optional mem0 install.
monkeypatch.setattr(mem0_system_adapter, "Mem0Backend", lambda config: object())
with pytest.warns(DeprecationWarning, match="Mem0SystemAdapter is deprecated"):
mem0_system_adapter.Mem0SystemAdapter()
_ENTITY = [{"entity": "Netflix", "entity_type": "organization"}]
_RELATION = [{"source": "user", "relationship": "works_at", "destination": "Netflix"}]
@pytest.mark.asyncio
@pytest.mark.parametrize(
("kwargs", "runs_mem0_extraction"),
[
({"facts": ["Works at Netflix"]}, False),
({"extracted_entities": _ENTITY}, False),
({"extracted_relationships": _RELATION}, False),
# The legacy names do not select the optimized path.
({"entities": ["Netflix"]}, True),
({"relationships": _RELATION}, True),
# Empty pre-extracted inputs do not count either.
({"facts": [], "extracted_entities": [], "extracted_relationships": []}, True),
],
)
async def test_direct_adapter_skips_mem0_extraction_only_for_pre_extracted_args(
kwargs: dict, runs_mem0_extraction: bool
) -> None:
"""The deprecation names facts/extracted_entities/extracted_relationships as the
way to skip Mem0's LLM extraction; entities/relationships alone still run it."""
from unittest.mock import AsyncMock, MagicMock
from headroom.memory.backends.direct_mem0 import DirectMem0Adapter, Mem0Config
adapter = DirectMem0Adapter(Mem0Config(enable_graph=True))
adapter._ensure_initialized = AsyncMock() # type: ignore[method-assign]
mem0_client = MagicMock()
mem0_client.add.return_value = {"results": [{"id": "m1", "memory": "Works at Netflix"}]}
adapter._mem0_client = mem0_client
write_facts = AsyncMock(return_value=["f1"])
write_graph = AsyncMock()
adapter._write_facts_to_qdrant = write_facts # type: ignore[method-assign]
adapter._write_graph_to_neo4j = write_graph # type: ignore[method-assign]
await adapter.save_memory(
content="I work at Netflix", user_id="u1", importance=0.5, background=False, **kwargs
)
assert mem0_client.add.called is runs_mem0_extraction
assert write_facts.called is not runs_mem0_extraction