Spaces:
Paused
Paused
File size: 5,278 Bytes
bc1617c 4405ca9 bc1617c | 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 | 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())
|