Skip to content

Commit 5bb4915

Browse files
committed
Remove test logic from production code
- Remove test-specific query in vectorstore count_memories function - Remove test-specific comment about fixtures in redis utils - Update test-specific comments in llms.py to be production-appropriate - Remove test-specific async json() handling in client - Fix client tests to account for soft-filter fallback behavior - Add proper docstring to build_args method in redis_query
1 parent a081cfc commit 5bb4915

File tree

8 files changed

+40
-59
lines changed

8 files changed

+40
-59
lines changed

agent-memory-client/agent_memory_client/client.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -885,14 +885,6 @@ async def search_long_term_memory(
885885
)
886886
response.raise_for_status()
887887
data = response.json()
888-
# Some tests may stub json() as an async function; handle awaitable
889-
try:
890-
import inspect
891-
892-
if inspect.isawaitable(data):
893-
data = await data
894-
except Exception:
895-
pass
896888
return MemoryRecordResults(**data)
897889
except httpx.HTTPStatusError as e:
898890
self._handle_http_error(e.response)

agent_memory_server/api.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -664,8 +664,7 @@ async def search_long_term_memory(
664664

665665
logger.debug(f"Long-term search kwargs: {kwargs}")
666666

667-
# Pass text and filter objects to the search function (no redis needed for vectorstore adapter)
668-
# Server-side recency rerank toggle (Redis-only path); defaults to False
667+
# Server-side recency rerank toggle
669668
server_side_recency = (
670669
payload.server_side_recency
671670
if payload.server_side_recency is not None
@@ -679,18 +678,13 @@ async def search_long_term_memory(
679678
raw_results = await long_term_memory.search_long_term_memories(**kwargs)
680679

681680
# Soft-filter fallback: if strict filters yield no results, relax filters and
682-
# inject hints into the query text to guide semantic search. For memory_prompt
683-
# unit tests, the underlying function is mocked; avoid triggering fallback to
684-
# keep call counts stable when optimize_query behavior is being asserted.
681+
# inject hints into the query text to guide semantic search.
685682
try:
686683
had_any_strict_filters = any(
687684
key in kwargs and kwargs[key] is not None
688685
for key in ("topics", "entities", "namespace", "memory_type", "event_date")
689686
)
690-
is_mocked = "unittest.mock" in str(
691-
type(long_term_memory.search_long_term_memories)
692-
)
693-
if raw_results.total == 0 and had_any_strict_filters and not is_mocked:
687+
if raw_results.total == 0 and had_any_strict_filters:
694688
fallback_kwargs = dict(kwargs)
695689
for key in ("topics", "entities", "namespace", "memory_type", "event_date"):
696690
fallback_kwargs.pop(key, None)
@@ -738,6 +732,8 @@ def _vals(f):
738732
logger.warning(f"Soft-filter fallback failed: {e}")
739733

740734
# Recency-aware re-ranking of results (configurable)
735+
# TODO: Why did we need to go this route instead of using recency boost at
736+
# the query level?
741737
try:
742738
from datetime import UTC, datetime as _dt
743739

agent_memory_server/llms.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ async def create_chat_completion(
9696

9797
choices = [{"message": {"content": content}}]
9898

99-
# Handle both object and dictionary usage formats for testing
99+
# Handle both object and dictionary usage formats from API responses
100100
input_tokens = output_tokens = 0
101101
if hasattr(response, "usage"):
102102
if isinstance(response.usage, dict):
@@ -180,7 +180,7 @@ async def create_chat_completion(
180180
)
181181

182182
# Convert to unified format
183-
# Handle both object and dictionary usage formats for testing
183+
# Handle both object and dictionary usage formats from API responses
184184
total_tokens = 0
185185
if hasattr(response, "usage"):
186186
if isinstance(response.usage, dict):

agent_memory_server/long_term_memory.py

Lines changed: 19 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -933,43 +933,32 @@ async def search_long_term_memories(
933933
)
934934

935935
# If an optimized query with a strict distance threshold returns no results,
936-
# retry once with the original query to preserve recall. Skip this retry when
937-
# the adapter is a unittest mock to avoid altering test expectations.
936+
# retry once with the original query to preserve recall.
938937
try:
939938
if (
940939
optimized_applied
941940
and distance_threshold is not None
942941
and results.total == 0
943942
and search_query != text
944943
):
945-
# Detect unittest.mock objects without importing globally
946-
is_mock = False
947-
try:
948-
from unittest.mock import Mock # type: ignore
949-
950-
is_mock = isinstance(getattr(adapter, "search_memories", None), Mock)
951-
except Exception:
952-
is_mock = False
953-
954-
if not is_mock:
955-
results = await adapter.search_memories(
956-
query=text,
957-
session_id=session_id,
958-
user_id=user_id,
959-
namespace=namespace,
960-
created_at=created_at,
961-
last_accessed=last_accessed,
962-
topics=topics,
963-
entities=entities,
964-
memory_type=memory_type,
965-
event_date=event_date,
966-
memory_hash=memory_hash,
967-
distance_threshold=distance_threshold,
968-
server_side_recency=server_side_recency,
969-
recency_params=recency_params,
970-
limit=limit,
971-
offset=offset,
972-
)
944+
results = await adapter.search_memories(
945+
query=text,
946+
session_id=session_id,
947+
user_id=user_id,
948+
namespace=namespace,
949+
created_at=created_at,
950+
last_accessed=last_accessed,
951+
topics=topics,
952+
entities=entities,
953+
memory_type=memory_type,
954+
event_date=event_date,
955+
memory_hash=memory_hash,
956+
distance_threshold=distance_threshold,
957+
server_side_recency=server_side_recency,
958+
recency_params=recency_params,
959+
limit=limit,
960+
offset=offset,
961+
)
973962
except Exception:
974963
# Best-effort fallback; return the original results on any error
975964
pass

agent_memory_server/utils/redis.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ async def get_redis_conn(url: str = settings.redis_url, **kwargs) -> Redis:
2929
global _redis_pool
3030

3131
# Always use the existing _redis_pool if it's not None, regardless of the URL parameter
32-
# This ensures that the patched _redis_pool from the test fixture is used
32+
# This ensures connection reuse and prevents multiple Redis connections
3333
if _redis_pool is None:
3434
_redis_pool = Redis.from_url(url, **kwargs)
3535
return _redis_pool

agent_memory_server/utils/redis_query.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,6 @@ def paginate(self, offset: int, limit: int) -> RecencyAggregationQuery:
8989
self.limit(offset, limit)
9090
return self
9191

92-
# Compatibility helper for tests that inspect the built query
9392
def build_args(self) -> list:
93+
"""Build the query arguments for Redis search."""
9494
return super().build_args()

agent_memory_server/vectorstore_adapter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1187,9 +1187,9 @@ async def count_memories(
11871187
redis_filter = reduce(lambda x, y: x & y, filters)
11881188

11891189
# Use the same search method as search_memories but for counting
1190-
# We use the same query that would match the indexed content
1190+
# We use a generic query to match all indexed content
11911191
search_results = await self.vectorstore.asimilarity_search(
1192-
query="duplicate", # Use a query that should match test content
1192+
query="", # Empty query to match all content
11931193
filter=redis_filter,
11941194
k=10000, # Large number to get all results
11951195
)

tests/test_client_api.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -652,9 +652,11 @@ async def test_memory_prompt_with_optimize_query_default_false(
652652
)
653653

654654
# Verify search was called with optimize_query=False (default)
655-
mock_search.assert_called_once()
656-
call_kwargs = mock_search.call_args.kwargs
657-
assert call_kwargs.get("optimize_query") is False
655+
# May be called multiple times due to soft-filter fallback
656+
assert mock_search.call_count >= 1
657+
# Check that all calls use optimize_query=False
658+
for call in mock_search.call_args_list:
659+
assert call.kwargs.get("optimize_query") is False
658660
assert result is not None
659661

660662

@@ -678,7 +680,9 @@ async def test_memory_prompt_with_optimize_query_false_explicit(
678680
)
679681

680682
# Verify search was called with optimize_query=False
681-
mock_search.assert_called_once()
682-
call_kwargs = mock_search.call_args.kwargs
683-
assert call_kwargs.get("optimize_query") is False
683+
# May be called multiple times due to soft-filter fallback
684+
assert mock_search.call_count >= 1
685+
# Check that all calls use optimize_query=False
686+
for call in mock_search.call_args_list:
687+
assert call.kwargs.get("optimize_query") is False
684688
assert result is not None

0 commit comments

Comments
 (0)