Spaces:
Sleeping
Sleeping
File size: 15,954 Bytes
b13e570 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
# =============================================================
# File: backend/tests/test_conversation_memory.py
# =============================================================
"""
Comprehensive tests for short-term conversation memory with expiration.
Tests:
1. Memory storage and retrieval
2. Memory injection into tool payloads
3. Session isolation (different session_ids don't share memory)
4. Memory expiration (TTL)
5. Memory bounded size (only last N items)
6. Session clearing (end_session flag)
7. Memory is NOT keyed by tenant_id (same session_id across tenants shares memory)
"""
import sys
from pathlib import Path
import pytest
import time
from unittest.mock import AsyncMock, MagicMock, patch
import asyncio
# Add backend directory to Python path
backend_dir = Path(__file__).parent.parent
sys.path.insert(0, str(backend_dir))
from mcp_server.common import memory
from mcp_server.common.utils import execute_tool, ToolHandler
from mcp_server.common.tenant import TenantContext
# =============================================================
# FIXTURES
# =============================================================
@pytest.fixture(autouse=True)
def clear_memory():
"""Clear memory before and after each test."""
# Clear all memory before test
memory._MEMORY.clear()
yield
# Clear all memory after test
memory._MEMORY.clear()
@pytest.fixture
def mock_tool_handler():
"""Create a mock tool handler that captures the payload."""
captured_payloads = []
async def handler(context: TenantContext, payload: dict) -> dict:
captured_payloads.append(payload)
return {"result": "success", "tool_output": "test_data"}
handler.captured = captured_payloads
return handler
# =============================================================
# UNIT TESTS: Memory Module
# =============================================================
def test_extract_session_id():
"""Test session ID extraction from payload."""
# Test various key formats
assert memory.extract_session_id({"session_id": "s1"}) == "s1"
assert memory.extract_session_id({"sessionId": "s2"}) == "s2"
assert memory.extract_session_id({"conversation_id": "s3"}) == "s3"
assert memory.extract_session_id({"conversationId": "s4"}) == "s4"
# Test first match wins
assert memory.extract_session_id({
"session_id": "s1",
"sessionId": "s2"
}) == "s1"
# Test missing session ID
assert memory.extract_session_id({"tenant_id": "t1"}) is None
assert memory.extract_session_id({}) is None
# Test empty string
assert memory.extract_session_id({"session_id": ""}) is None
assert memory.extract_session_id({"session_id": " "}) is None
def test_add_and_get_entry():
"""Test basic memory storage and retrieval."""
session_id = "test-session-1"
# Add entries
memory.add_entry(session_id, "tool1", {"output": "data1"}, max_items=10, ttl_seconds=900)
memory.add_entry(session_id, "tool2", {"output": "data2"}, max_items=10, ttl_seconds=900)
memory.add_entry(session_id, "tool3", {"output": "data3"}, max_items=10, ttl_seconds=900)
# Retrieve entries
entries = memory.get_recent(session_id, ttl_seconds=900)
assert len(entries) == 3
assert entries[0]["tool"] == "tool1"
assert entries[1]["tool"] == "tool2"
assert entries[2]["tool"] == "tool3"
assert entries[0]["output"] == {"output": "data1"}
assert "timestamp" in entries[0]
def test_memory_bounded_size():
"""Test that memory only keeps last N items."""
session_id = "test-session-2"
max_items = 3
# Add more items than max
for i in range(5):
memory.add_entry(session_id, f"tool{i}", {"data": i}, max_items=max_items, ttl_seconds=900)
entries = memory.get_recent(session_id, ttl_seconds=900)
# Should only have last 3 items
assert len(entries) == 3
assert entries[0]["tool"] == "tool2"
assert entries[1]["tool"] == "tool3"
assert entries[2]["tool"] == "tool4"
def test_memory_expiration():
"""Test that expired entries are automatically removed."""
session_id = "test-session-3"
short_ttl = 1 # 1 second TTL
# Add entry
memory.add_entry(session_id, "tool1", {"data": "old"}, max_items=10, ttl_seconds=short_ttl)
# Should be present immediately
entries = memory.get_recent(session_id, ttl_seconds=short_ttl)
assert len(entries) == 1
# Wait for expiration
time.sleep(1.1)
# Should be expired now
entries = memory.get_recent(session_id, ttl_seconds=short_ttl)
assert len(entries) == 0
def test_session_isolation():
"""Test that different session_ids don't share memory."""
session1 = "session-1"
session2 = "session-2"
memory.add_entry(session1, "tool1", {"data": "s1"}, max_items=10, ttl_seconds=900)
memory.add_entry(session2, "tool2", {"data": "s2"}, max_items=10, ttl_seconds=900)
entries1 = memory.get_recent(session1, ttl_seconds=900)
entries2 = memory.get_recent(session2, ttl_seconds=900)
assert len(entries1) == 1
assert len(entries2) == 1
assert entries1[0]["tool"] == "tool1"
assert entries2[0]["tool"] == "tool2"
def test_clear_session():
"""Test that clear_session removes all memory for a session."""
session_id = "test-session-4"
memory.add_entry(session_id, "tool1", {"data": "d1"}, max_items=10, ttl_seconds=900)
memory.add_entry(session_id, "tool2", {"data": "d2"}, max_items=10, ttl_seconds=900)
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 2
memory.clear_session(session_id)
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 0
def test_memory_not_keyed_by_tenant():
"""Test that memory is keyed by session_id, NOT tenant_id."""
session_id = "shared-session"
tenant1 = "tenant-a"
tenant2 = "tenant-b"
# Simulate: tenant1 calls tool, then tenant2 calls tool with same session_id
# They should see each other's tool outputs (because memory is session-based, not tenant-based)
# This is intentional for safety - memory is NOT per-tenant
# In a real scenario, you'd want to ensure session_ids are unique per tenant
# But the memory system itself doesn't enforce this
# Add entry from tenant1 perspective
memory.add_entry(session_id, "tool1", {"tenant": tenant1, "data": "from-tenant1"}, max_items=10, ttl_seconds=900)
# Add entry from tenant2 perspective (same session_id)
memory.add_entry(session_id, "tool2", {"tenant": tenant2, "data": "from-tenant2"}, max_items=10, ttl_seconds=900)
# Both should see both entries (because same session_id)
entries = memory.get_recent(session_id, ttl_seconds=900)
assert len(entries) == 2
assert entries[0]["output"]["tenant"] == tenant1
assert entries[1]["output"]["tenant"] == tenant2
def test_get_recent_with_limit():
"""Test that get_recent respects the limit parameter."""
session_id = "test-session-5"
# Add 5 entries
for i in range(5):
memory.add_entry(session_id, f"tool{i}", {"data": i}, max_items=10, ttl_seconds=900)
# Get all
all_entries = memory.get_recent(session_id, limit=None, ttl_seconds=900)
assert len(all_entries) == 5
# Get last 2
recent_2 = memory.get_recent(session_id, limit=2, ttl_seconds=900)
assert len(recent_2) == 2
assert recent_2[0]["tool"] == "tool3"
assert recent_2[1]["tool"] == "tool4"
# =============================================================
# INTEGRATION TESTS: execute_tool with Memory
# =============================================================
@pytest.mark.asyncio
async def test_execute_tool_stores_memory(mock_tool_handler):
"""Test that execute_tool stores tool output in memory."""
payload = {
"tenant_id": "test-tenant",
"session_id": "test-session-6",
"query": "test query"
}
result = await execute_tool("test.tool", payload, mock_tool_handler)
# Check that result is successful
assert result["status"] == "ok"
# Check that memory was stored
entries = memory.get_recent("test-session-6", ttl_seconds=900)
assert len(entries) == 1
assert entries[0]["tool"] == "test.tool"
assert entries[0]["output"] == {"result": "success", "tool_output": "test_data"}
@pytest.mark.asyncio
async def test_execute_tool_injects_memory(mock_tool_handler):
"""Test that execute_tool injects recent memory into payload."""
session_id = "test-session-7"
# First call - no memory yet
payload1 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "first query"
}
await execute_tool("tool1", payload1, mock_tool_handler)
# Second call - should have memory from first call
payload2 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "second query"
}
await execute_tool("tool2", payload2, mock_tool_handler)
# Check that second call received memory
assert len(mock_tool_handler.captured) == 2
second_payload = mock_tool_handler.captured[1]
assert "memory" in second_payload
assert len(second_payload["memory"]) == 1
assert second_payload["memory"][0]["tool"] == "tool1"
@pytest.mark.asyncio
async def test_execute_tool_clears_memory_on_end_session(mock_tool_handler):
"""Test that execute_tool clears memory when end_session is True."""
session_id = "test-session-8"
# First call - store memory
payload1 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "first query"
}
await execute_tool("tool1", payload1, mock_tool_handler)
# Verify memory exists
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 1
# Second call with end_session=True
payload2 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"end_session": True,
"query": "closing"
}
await execute_tool("tool2", payload2, mock_tool_handler)
# Memory should be cleared
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 0
# Third call - should have no memory
payload3 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "new query"
}
await execute_tool("tool3", payload3, mock_tool_handler)
# Check that third call received no memory
third_payload = mock_tool_handler.captured[2]
assert "memory" in third_payload
assert len(third_payload["memory"]) == 0
@pytest.mark.asyncio
async def test_execute_tool_no_memory_without_session_id(mock_tool_handler):
"""Test that execute_tool doesn't store/inject memory if no session_id."""
payload = {
"tenant_id": "test-tenant",
"query": "test query"
# No session_id
}
await execute_tool("test.tool", payload, mock_tool_handler)
# Should not have stored memory
# (We can't easily check this without session_id, but handler shouldn't have memory field)
first_payload = mock_tool_handler.captured[0]
assert "memory" not in first_payload
@pytest.mark.asyncio
async def test_execute_tool_multi_step_workflow(mock_tool_handler):
"""Test a multi-step workflow where each step sees previous tool outputs."""
session_id = "test-session-9"
# Step 1: RAG search
payload1 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "search for X"
}
await execute_tool("rag.search", payload1, mock_tool_handler)
# Step 2: Web search (should see RAG results in memory)
payload2 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "search web for Y"
}
await execute_tool("web.search", payload2, mock_tool_handler)
# Step 3: LLM synthesis (should see both RAG and Web results)
payload3 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "synthesize results"
}
await execute_tool("llm.synthesize", payload3, mock_tool_handler)
# Verify all steps captured memory
assert len(mock_tool_handler.captured) == 3
# First call has no memory
assert "memory" not in mock_tool_handler.captured[0] or len(mock_tool_handler.captured[0].get("memory", [])) == 0
# Second call has memory from first
assert len(mock_tool_handler.captured[1].get("memory", [])) == 1
assert mock_tool_handler.captured[1]["memory"][0]["tool"] == "rag.search"
# Third call has memory from both previous calls
assert len(mock_tool_handler.captured[2].get("memory", [])) == 2
assert mock_tool_handler.captured[2]["memory"][0]["tool"] == "rag.search"
assert mock_tool_handler.captured[2]["memory"][1]["tool"] == "web.search"
@pytest.mark.asyncio
async def test_execute_tool_end_session_variants(mock_tool_handler):
"""Test that both end_session and endSession flags work."""
session_id = "test-session-10"
# Store some memory
payload1 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"query": "first"
}
await execute_tool("tool1", payload1, mock_tool_handler)
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 1
# Test end_session (snake_case)
payload2 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"end_session": True,
"query": "end"
}
await execute_tool("tool2", payload2, mock_tool_handler)
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 0
# Store memory again
await execute_tool("tool3", payload1, mock_tool_handler)
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 1
# Test endSession (camelCase)
payload3 = {
"tenant_id": "test-tenant",
"session_id": session_id,
"endSession": True,
"query": "end"
}
await execute_tool("tool4", payload3, mock_tool_handler)
assert len(memory.get_recent(session_id, ttl_seconds=900)) == 0
# =============================================================
# EDGE CASES
# =============================================================
def test_empty_session_id():
"""Test that empty session_id doesn't cause errors."""
memory.add_entry("", "tool1", {"data": "test"}, max_items=10, ttl_seconds=900)
# Should not store anything
assert len(memory.get_recent("", ttl_seconds=900)) == 0
def test_none_session_id():
"""Test that None session_id doesn't cause errors."""
# This shouldn't happen in practice, but test for safety
entries = memory.get_recent(None, ttl_seconds=900) # type: ignore
assert entries == []
@pytest.mark.asyncio
async def test_concurrent_sessions(mock_tool_handler):
"""Test that concurrent sessions don't interfere with each other."""
session1 = "session-concurrent-1"
session2 = "session-concurrent-2"
# Execute tools in both sessions concurrently
tasks = [
execute_tool("tool1", {
"tenant_id": "tenant1",
"session_id": session1,
"query": "q1"
}, mock_tool_handler),
execute_tool("tool2", {
"tenant_id": "tenant2",
"session_id": session2,
"query": "q2"
}, mock_tool_handler),
]
await asyncio.gather(*tasks)
# Each session should have its own memory
entries1 = memory.get_recent(session1, ttl_seconds=900)
entries2 = memory.get_recent(session2, ttl_seconds=900)
assert len(entries1) == 1
assert len(entries2) == 1
assert entries1[0]["tool"] == "tool1"
assert entries2[0]["tool"] == "tool2"
if __name__ == "__main__":
pytest.main([__file__, "-v"])
|