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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(memory): compare SQLite timestamps as UTC instants (#4499)
Rudy Mizrahi Celekli6f958e94c2b3
diff --git a/headroom/memory/adapters/sqlite.py b/headroom/memory/adapters/sqlite.pyindex 3a849ebc5..32e12ad80 100644--- a/headroom/memory/adapters/sqlite.py+++ b/headroom/memory/adapters/sqlite.py@@ -49,6 +49,20 @@ def _validate_metadata_key(key: str) -> bool:return _SAFE_METADATA_KEY_PATTERN.match(key) is not None+def _utc_timestamp(value: str | None) -> str | None:+ """Comparable UTC text without rewriting stored offsets or rounding fractions.++ Naive timestamps follow Memory's UTC defaults. SQLite date functions round+ fractional seconds, so keep Python's full microsecond precision here.+ """+ if value is None:+ return None+ timestamp = datetime.fromisoformat(value)+ if timestamp.tzinfo is not None:+ timestamp = timestamp.astimezone(timezone.utc).replace(tzinfo=None)+ return timestamp.isoformat(timespec="microseconds")++class SQLiteMemoryStore:"""SQLite-based memory store implementing the MemoryStore protocol.@@ -95,6 +109,7 @@ class SQLiteMemoryStore:"""conn = connect_private_sqlite(self.db_path, what="memory store")conn.row_factory = sqlite3.Row+ conn.create_function("headroom_utc_timestamp", 1, _utc_timestamp, deterministic=True)try:with conn:yield conn@@ -507,21 +522,23 @@ class SQLiteMemoryStore:if scope_conditions:conditions.append(f"({' OR '.join(scope_conditions)})")+ # Normalize both sides: persisted rows may retain explicit UTC offsets.+ # This favors correct instant comparisons over the raw TEXT time index.# Temporal filteringif filter.created_after is not None:- conditions.append("created_at >= ?")- params.append(filter.created_after.isoformat())+ conditions.append("headroom_utc_timestamp(created_at) >= ?")+ params.append(_utc_timestamp(filter.created_after.isoformat()))if filter.created_before is not None:- conditions.append("created_at <= ?")- params.append(filter.created_before.isoformat())+ conditions.append("headroom_utc_timestamp(created_at) <= ?")+ params.append(_utc_timestamp(filter.created_before.isoformat()))# Point-in-time queryif filter.valid_at is not None:- valid_at_str = filter.valid_at.isoformat()- conditions.append("valid_from <= ?")+ valid_at_str = _utc_timestamp(filter.valid_at.isoformat())+ conditions.append("headroom_utc_timestamp(valid_from) <= ?")params.append(valid_at_str)- conditions.append("(valid_until IS NULL OR valid_until > ?)")+ conditions.append("(valid_until IS NULL OR headroom_utc_timestamp(valid_until) > ?)")params.append(valid_at_str)# Superseded filtering@@ -620,6 +637,9 @@ class SQLiteMemoryStore:):order_column = "created_at"+ if order_column in ("created_at", "last_accessed"):+ order_column = f"headroom_utc_timestamp({order_column})"+order_direction = "DESC" if filter.order_desc else "ASC"# Build full querydiff --git a/tests/test_memory/test_sqlite_temporal_filters.py b/tests/test_memory/test_sqlite_temporal_filters.pynew file mode 100644index 000000000..cc2a03e01--- /dev/null+++ b/tests/test_memory/test_sqlite_temporal_filters.py@@ -0,0 +1,94 @@+"""Temporal memory queries compare instants, including existing offset rows."""++from datetime import datetime, timedelta, timezone++import pytest++from headroom.memory.adapters.sqlite import SQLiteMemoryStore+from headroom.memory.models import Memory+from headroom.memory.ports import MemoryFilter++UTC = timezone.utc+ZONES = [UTC, timezone(timedelta(hours=5)), timezone(timedelta(hours=-4))]+++def _utc(value: datetime) -> datetime:+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)++[email protected]("zone", ZONES)+ "field,baseline",+ [+ ("created_after", datetime(2026, 1, 1, 11, tzinfo=UTC)),+ ("created_before", datetime(2026, 1, 1, 12, tzinfo=UTC)),+ ("valid_at", datetime(2026, 1, 1, 12, 30, tzinfo=UTC)),+ ("valid_at", datetime(2026, 1, 1, 13, tzinfo=UTC)),+ ("created_after", datetime(2026, 1, 1, 12, 0, 0, 1, tzinfo=UTC)),+ ],+)+async def test_temporal_query_and_count_match_datetime_oracle(tmp_path, field, baseline, zone):+ path = tmp_path / "memory.db"+ store = SQLiteMemoryStore(path)+ memories = [+ Memory(+ id="naive",+ user_id="fixture",+ created_at=datetime(2026, 1, 1, 12),+ valid_from=datetime(2026, 1, 1, 12),+ valid_until=datetime(2026, 1, 1, 13),+ ),+ Memory(+ id="aware",+ user_id="fixture",+ created_at=datetime(2026, 1, 1, 17, tzinfo=ZONES[1]),+ valid_from=datetime(2026, 1, 1, 8, tzinfo=ZONES[2]),+ valid_until=datetime(2026, 1, 1, 18, tzinfo=ZONES[1]),+ ),+ Memory(+ id="microsecond",+ user_id="fixture",+ created_at=datetime(2026, 1, 1, 12, 0, 0, 1),+ valid_from=datetime(2026, 1, 1, 12, 0, 0, 1),+ valid_until=datetime(2026, 1, 1, 13, 0, 0, 1),+ ),+ ]+ for memory in memories:+ await store.save(memory)+ # Stored bytes stay offset-bearing across a new adapter instance.+ store = SQLiteMemoryStore(path)+ retained = await store.get("aware")+ assert retained is not None+ assert retained.created_at.isoformat() == memories[1].created_at.isoformat()+ bound = baseline.astimezone(zone)++ def matches(memory):+ if field == "created_after":+ return _utc(memory.created_at) >= _utc(bound)+ if field == "created_before":+ return _utc(memory.created_at) <= _utc(bound)+ return _utc(memory.valid_from) <= _utc(bound) < _utc(memory.valid_until)++ expected = sorted(memory.id for memory in memories if matches(memory))+ query = MemoryFilter(user_id="fixture", include_superseded=True, **{field: bound})+ assert sorted(memory.id for memory in await store.query(query)) == expected+ assert await store.count(query) == len(expected)+++async def test_temporal_order_precedes_pagination_and_preserves_null_access(tmp_path):+ store = SQLiteMemoryStore(tmp_path / "memory.db")+ # Wall-clock text sorts these incorrectly; UTC chronological order is a,b,c.+ for identity, timestamp in [+ ("a", datetime(2026, 1, 1, 15, tzinfo=ZONES[1])),+ ("b", datetime(2026, 1, 1, 11)),+ ("c", datetime(2026, 1, 1, 8, tzinfo=ZONES[2])),+ ]:+ await store.save(Memory(id=identity, user_id="fixture", created_at=timestamp))+ result = await store.query(MemoryFilter(user_id="fixture", order_desc=False, limit=1, offset=1))+ assert [memory.id for memory in result] == ["b"]+ # Last-access timestamps are nullable; their established ordering stays valid.+ await store.record_access(["b"], datetime(2026, 1, 1, 11, tzinfo=UTC))+ accessed = await store.query(MemoryFilter(user_id="fixture", order_by="last_accessed", limit=1))+ assert [memory.id for memory in accessed] == ["b"]