Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(memory): match compound and null SQLite metadata filters (#4373)

xiaoheiai4719-collabb50b3eb5ed0c
diff --git a/headroom/memory/adapters/sqlite.py b/headroom/memory/adapters/sqlite.py
index 635167dc3..3a849ebc5 100644
--- a/headroom/memory/adapters/sqlite.py
+++ b/headroom/memory/adapters/sqlite.py
@@ -67,6 +67,12 @@ class SQLiteMemoryStore:
Schema:
The memories table stores all Memory fields with appropriate indexes
for efficient querying by scope, category, importance, and time.
+
+ Metadata filters:
+ Numbers and booleans use native SQLite equality. String filters match only
+ JSON text values. None matches an explicit JSON null,
+ not a missing key. Arrays and objects compare as compact JSON text with
+ matching JSON types; array order and object member order are significant.
"""
def __init__(self, db_path: str | Path = "headroom_memory.db") -> None:
@@ -571,13 +577,22 @@ class SQLiteMemoryStore:
# equates ``5 = '5'`` — so an int/float/bool metadata filter matched
# nothing. ``bool`` is a subclass of ``int``, so it is covered here
# (a JSON ``true`` extracts to 1, and Python ``True`` binds to 1).
- # A non-scalar value (dict/list) is not a bindable SQLite type, so it
- # keeps the JSON-text comparison rather than raising.
- conditions.append(f"json_extract(metadata, '$.{key}') = ?")
- if isinstance(value, (str, int, float)):
+ if value is None:
+ # json_extract returns SQL NULL for both null and missing keys.
+ conditions.append(f"json_type(metadata, '$.{key}') = 'null'")
+ elif isinstance(value, (str, int, float)):
+ if isinstance(value, str):
+ # Extracted JSON arrays/objects are also SQL text.
+ conditions.append(f"json_type(metadata, '$.{key}') = 'text'")
+ conditions.append(f"json_extract(metadata, '$.{key}') = ?")
params.append(value)
else:
- params.append(json.dumps(value))
+ # Normalize whitespace like json_extract does for arrays/objects,
+ # and do not match a string containing the same JSON text.
+ encoded = json.dumps(value)
+ conditions.append(f"json_type(metadata, '$.{key}') = json_type(?)")
+ conditions.append(f"json_extract(metadata, '$.{key}') = json(?)")
+ params.extend([encoded, encoded])
return conditions, params
diff --git a/tests/test_memory/test_metadata_matching.py b/tests/test_memory/test_metadata_matching.py
new file mode 100644
index 000000000..06e14102b
--- /dev/null
+++ b/tests/test_memory/test_metadata_matching.py
@@ -0,0 +1,123 @@
+"""Execute JSON-valued metadata filters against the real SQLite memory store."""
+
+import json
+
+import pytest
+
+from headroom.memory.adapters.sqlite import SQLiteMemoryStore
+from headroom.memory.models import Memory
+from headroom.memory.ports import MemoryFilter
+
+
+ "value",
+ [
+ ["a", "b"],
+ {"priority": 5},
+ {"nested": ["a", "b"]},
+ ["café", {"note": "spaces within strings remain"}],
+ [],
+ {},
+ ["single"],
+ ],
+)
+async def test_compound_metadata_matches_without_matching_json_strings(tmp_path, value):
+ store = SQLiteMemoryStore(tmp_path / "memory.db")
+ await store.save(
+ Memory(id="match", user_id="alice", content="saved", metadata={"value": value})
+ )
+ await store.save(
+ Memory(
+ id="string",
+ user_id="alice",
+ content="not a compound value",
+ metadata={"value": json.dumps(value, separators=(",", ":"))},
+ )
+ )
+ await store.save(
+ Memory(id="other-user", user_id="bob", content="saved", metadata={"value": value})
+ )
+ query = MemoryFilter(user_id="alice", metadata_filters={"value": value})
+
+ assert [memory.id for memory in await store.query(query)] == ["match"]
+ assert await store.count(query) == 1
+
+
+async def test_null_metadata_matches_explicit_null_not_missing_or_text(tmp_path):
+ store = SQLiteMemoryStore(tmp_path / "memory.db")
+ for name, metadata in [("null", {"value": None}), ("missing", {}), ("text", {"value": "null"})]:
+ await store.save(Memory(id=name, user_id="alice", content="saved", metadata=metadata))
+ query = MemoryFilter(user_id="alice", metadata_filters={"value": None})
+
+ assert [memory.id for memory in await store.query(query)] == ["null"]
+ assert await store.count(query) == 1
+
+
+async def test_compound_metadata_preserves_array_and_object_member_order(tmp_path):
+ store = SQLiteMemoryStore(tmp_path / "memory.db")
+ await store.save(
+ Memory(
+ id="saved",
+ user_id="alice",
+ content="saved",
+ metadata={"array": [1, 2], "object": {"a": 1, "b": 2}},
+ )
+ )
+ for metadata in [{"array": [2, 1]}, {"object": {"b": 2, "a": 1}}]:
+ query = MemoryFilter(user_id="alice", metadata_filters=metadata)
+ assert await store.query(query) == []
+ assert await store.count(query) == 0
+
+
+ "value",
+ [
+ ["a", "b"],
+ {"priority": 5},
+ {"nested": ["a", "b"]},
+ ["café", {"note": "spaces within strings remain"}],
+ [],
+ {},
+ ["single"],
+ None,
+ ],
+)
+async def test_json_looking_string_filter_matches_only_text(tmp_path, value):
+ store = SQLiteMemoryStore(tmp_path / "memory.db")
+ text = json.dumps(value, separators=(",", ":"))
+ for name, saved in [("text", text), ("json", value)]:
+ await store.save(
+ Memory(id=name, user_id="alice", content="saved", metadata={"value": saved})
+ )
+ query = MemoryFilter(user_id="alice", metadata_filters={"value": text})
+
+ assert [memory.id for memory in await store.query(query)] == ["text"]
+ assert await store.count(query) == 1
+
+
[email protected]("value", [True, False, 1, 0, 1.0, 0.0])
+async def test_numeric_and_boolean_metadata_retains_native_sqlite_equality(tmp_path, value):
+ store = SQLiteMemoryStore(tmp_path / "memory.db")
+ for name, saved in [
+ ("true", True),
+ ("false", False),
+ ("one", 1),
+ ("zero", 0),
+ ("float-one", 1.0),
+ ("float-zero", 0.0),
+ ("text-one", "1"),
+ ("text-zero", "0"),
+ ]:
+ await store.save(
+ Memory(id=name, user_id="alice", content="saved", metadata={"value": saved})
+ )
+ query = MemoryFilter(user_id="alice", metadata_filters={"value": value})
+ expected = {"true", "one", "float-one"} if value else {"false", "zero", "float-zero"}
+
+ assert {memory.id for memory in await store.query(query)} == expected
+ assert await store.count(query) == 3