import asyncio import os import sys from datetime import datetime, timedelta from unittest.mock import MagicMock, AsyncMock # Add project root to path sys.path.append(os.getcwd()) from core.database import async_session_factory from models.workspace import Workspace from models.user import User from models.nexus_semantic_cache import NexusSemanticCache from core.cache import SemanticCacheManager from core.tasks import purge_stale_semantic_cache from sqlalchemy import select, delete async def test_cache_lifecycle(): print("\n--- NEXUS: SEMANTIC CACHE LIFECYCLE TEST (MOCKED) ---") # 0. MOCK EMBEDDINGS to avoid Ollama connection issues mock_vector = [0.1] * 768 from core import llm original_get_embeddings = llm.get_embeddings mock_embedder = MagicMock() mock_embedder.aembed_query = AsyncMock(return_value=mock_vector) llm.get_embeddings = MagicMock(return_value=mock_embedder) try: async with async_session_factory() as db: # 1. Setup Mock User/WS ws_res = await db.execute(select(Workspace).limit(1)) ws = ws_res.scalar_one_or_none() if not ws: ws = Workspace(name="Test WS", slug="test-ws") db.add(ws) await db.commit() await db.refresh(ws) user_res = await db.execute(select(User).limit(1)) user = user_res.scalar_one_or_none() if not user: user = User(email="test@example.com", full_name="Test User", workspace_id=ws.id) db.add(user) await db.commit() await db.refresh(user) test_query = "how do i reset my nexus password for testing?" await db.execute(delete(NexusSemanticCache).where(NexusSemanticCache.query_text == test_query)) await db.commit() # 2. SEED STALE CACHE (7 hours ago) stale_entry = NexusSemanticCache( workspace_id=ws.id, user_id=user.id, user_role="customer_user", is_agent=False, query_text=test_query, query_embedding=mock_vector, response_text="STALE ANSWER", created_at=datetime.utcnow() - timedelta(hours=7) ) db.add(stale_entry) await db.commit() print("SUCCESS: Seeded STALE cache entry (7h old).") # 3. VERIFY STALE HIT FAILS (Freshness Check) hit = await SemanticCacheManager.check_cache( workspace_id=str(ws.id), query=test_query, is_agent=False, user_role="customer_user" ) if hit is None: print("SUCCESS: Stale cache ignored (Returned None as expected).") else: print(f"FAILURE: Stale cache was returned: {hit}") # 4. SEED FRESH CACHE (1 hour ago) await db.execute(delete(NexusSemanticCache).where(NexusSemanticCache.query_text == test_query)) await db.commit() fresh_entry = NexusSemanticCache( workspace_id=ws.id, user_id=user.id, user_role="customer_user", is_agent=False, query_text=test_query, query_embedding=mock_vector, response_text="FRESH ANSWER", created_at=datetime.utcnow() - timedelta(hours=1) ) db.add(fresh_entry) await db.commit() print("SUCCESS: Seeded FRESH cache entry (1h old).") # 5. VERIFY FRESH HIT WORKS (Mocked distance should be 0) hit = await SemanticCacheManager.check_cache( workspace_id=str(ws.id), query=test_query, is_agent=False, user_role="customer_user" ) if hit == "FRESH ANSWER": print(f"SUCCESS: Fresh cache HIT: {hit}") else: print(f"FAILURE: Fresh cache not found or found wrong entry: {hit}") # 6. TEST PURGE TASK (13-hour old record) purge_query = "purge test question" purge_entry = NexusSemanticCache( workspace_id=ws.id, user_id=user.id, user_role="customer_user", is_agent=False, query_text=purge_query, query_embedding=mock_vector, response_text="EXPIRED", created_at=datetime.utcnow() - timedelta(hours=13) ) db.add(purge_entry) await db.commit() await purge_stale_semantic_cache(ctx=None) res = await db.execute(select(NexusSemanticCache).where(NexusSemanticCache.query_text == purge_query)) if res.scalar_one_or_none() is None: print("SUCCESS: 13h old record physically purged.") else: print("FAILURE: 13h old record still exists.") finally: # Restore llm.get_embeddings = original_get_embeddings if __name__ == "__main__": asyncio.run(test_cache_lifecycle())