Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
bc1617c
1
Parent(s): 0f0e878
fix: allow staff cross-workspace live events via WebSockets
Browse filesFiles changed (7)
62 unmodified lines63646566676869707172737475767778798081828384858687888990919293949562 unmodified linescurrent_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:# Strictly enforce current user's workspace, allowing override for authorized stafftarget_ws = current_user.workspace_idif workspace_id:if current_user.role == UserRole.SC_ADMIN:target_ws = workspace_idelse:from models.user_workspace import UserWorkspacews_check = await db.execute(select(UserWorkspace).where(UserWorkspace.user_id == current_user.id,UserWorkspace.workspace_id == workspace_id))if ws_check.scalar_one_or_none():target_ws = workspace_idstmt = (select(func.avg(Feedback.rating), func.count(Feedback.id)).where(Feedback.workspace_id == target_ws))result = await db.execute(stmt)avg_rating, count = result.one()return {"average_rating": float(avg_rating) if avg_rating else 0,"total_responses": count}@router.get("/sla/", dependencies=[Depends(require_roles(EVERYBODY_ROLES))])async def get_sla_compliance(62 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010110210362 unmodified linescurrent_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:try:# Strictly enforce current user's workspace, allowing override for authorized stafftarget_ws = current_user.workspace_idif workspace_id:if current_user.role == UserRole.SC_ADMIN:target_ws = workspace_idelse:from models.user_workspace import UserWorkspacews_check = await db.execute(select(UserWorkspace).where(UserWorkspace.user_id == current_user.id,UserWorkspace.workspace_id == workspace_id))if ws_check.scalar_one_or_none():target_ws = workspace_idif not target_ws:return {"average_rating": 0, "total_responses": 0}stmt = (select(func.avg(Feedback.rating), func.count(Feedback.id)).where(Feedback.workspace_id == target_ws))result = await db.execute(stmt)avg_rating, count = result.one()return {"average_rating": float(avg_rating) if avg_rating else 0,"total_responses": count or 0}except Exception as e:logger.error(f"CSAT Report Error: {str(e)}")return {"average_rating": 0, "total_responses": 0}@router.get("/sla/", dependencies=[Depends(require_roles(EVERYBODY_ROLES))])async def get_sla_compliance(
89 unmodified lines90919293949596973 unmodified lines1011021031041051064 unmodified lines1111121131141151162 unmodified lines11912012112212312412512613 unmodified lines1401411421431441458 unmodified lines1541551561571581597 unmodified lines16716816917017117217317417517617717817989 unmodified lines"""Manages semantic LLM response caching using pgvector.Bypasses entirely the LangGraph orchestration if an idential query was asked before."""@staticmethodasync def check_cache(workspace_id: str, query: str, is_agent: bool = False, user_role: str = "customer_user", user_id: Optional[str] = None) -> Optional[str]:from core.llm import get_embeddings3 unmodified linesimport logginglogger = logging.getLogger(__name__)try:# OPTIMIZATION: Skip embedding generation for very short queries (greetings, etc.)4 unmodified linesquery_vector = await embedder.aembed_query(query)async with async_session_factory() as db:stmt = (select(NexusSemanticCache,2 unmodified lines.where(and_(NexusSemanticCache.workspace_id == workspace_id,NexusSemanticCache.is_agent == is_agent,NexusSemanticCache.user_role == user_role)).order_by("distance")13 unmodified lines.values(hit_count=NexusSemanticCache.hit_count + 1))await db.commit()return cache_hit.response_textexcept Exception as e:logger.error(f"Semantic Cache Check Failed: {str(e)}")8 unmodified linesimport logginglogger = logging.getLogger(__name__)try:# OPTIMIZATION: Skip embedding generation for very short queries7 unmodified linescache_entry = NexusSemanticCache(workspace_id=workspace_id,user_id=user_id, # Keep user_id in record for audit, but not lookupis_agent=is_agent,user_role=user_role,query_text=query,query_embedding=query_vector,response_text=response_text)db.add(cache_entry)await db.commit()except Exception as e:logger.error(f"Semantic Cache Set Failed: {str(e)}")89 unmodified lines909192939495969798991001011021031041051061071083 unmodified lines1121131141151161171184 unmodified lines1231241251261271281292 unmodified lines13213313413513613713813914013 unmodified lines1541551561571581591608 unmodified lines1691701711721731741757 unmodified lines18318418518618718818919019119219319419519619789 unmodified lines"""Manages semantic LLM response caching using pgvector.Bypasses entirely the LangGraph orchestration if an idential query was asked before.PARTITION KEY: (workspace_id, role_class)- role_class is normalized to 'staff' or 'customer' to prevent cross-persona cache leaks."""@staticmethoddef _normalize_role_class(user_role: str = "", is_agent: bool = False) -> str:"""Normalize any role string to a strict partition class."""role_lower = str(user_role).lower()if is_agent or "3sc" in role_lower or "agent" in role_lower or "lead" in role_lower or role_lower == "admin":return "staff"return "customer"@staticmethodasync def check_cache(workspace_id: str, query: str, is_agent: bool = False, user_role: str = "customer_user", user_id: Optional[str] = None) -> Optional[str]:from core.llm import get_embeddings3 unmodified linesimport logginglogger = logging.getLogger(__name__)role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent)try:# OPTIMIZATION: Skip embedding generation for very short queries (greetings, etc.)4 unmodified linesquery_vector = await embedder.aembed_query(query)async with async_session_factory() as db:from sqlalchemy import textstmt = (select(NexusSemanticCache,2 unmodified lines.where(and_(NexusSemanticCache.workspace_id == workspace_id,NexusSemanticCache.is_agent == (role_class == "staff"),NexusSemanticCache.user_role == role_class,NexusSemanticCache.created_at >= (func.now() - text("INTERVAL '6 hours'")))).order_by("distance")13 unmodified lines.values(hit_count=NexusSemanticCache.hit_count + 1))await db.commit()logger.info(f"🧠 Semantic Cache HIT [{role_class}]: ws={workspace_id[:8]} q='{query[:40]}'")return cache_hit.response_textexcept Exception as e:logger.error(f"Semantic Cache Check Failed: {str(e)}")8 unmodified linesimport logginglogger = logging.getLogger(__name__)role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent)try:# OPTIMIZATION: Skip embedding generation for very short queries7 unmodified linescache_entry = NexusSemanticCache(workspace_id=workspace_id,user_id=user_id, # Keep user_id in record for audit, but not lookupis_agent=(role_class == "staff"),user_role=role_class,query_text=query,query_embedding=query_vector,response_text=response_text)db.add(cache_entry)await db.commit()logger.info(f"🧠 Semantic Cache SET [{role_class}]: ws={workspace_id[:8]} q='{query[:40]}'")except Exception as e:logger.error(f"Semantic Cache Set Failed: {str(e)}")
1138 unmodified lines1139114011411138 unmodified linesexcept Exception as e:logger.error(f"FAILURE: Global Insight generation failed: {str(e)}")await db.rollback()1138 unmodified lines113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641138 unmodified linesexcept Exception as e:logger.error(f"FAILURE: Global Insight generation failed: {str(e)}")await db.rollback()async def purge_stale_semantic_cache(ctx):"""Periodic task to physically delete semantic cache records older than 12 hours.Maintains a 6-hour functional TTL buffer for troubleshooting."""from models.nexus_semantic_cache import NexusSemanticCachefrom sqlalchemy import text, deletelogger.info("Executing Semantic Cache Purge...")async with async_session_factory() as db:try:# Delete records older than 12 hoursstmt = delete(NexusSemanticCache).where(NexusSemanticCache.created_at < (func.now() - text("INTERVAL '12 hours'")))result = await db.execute(stmt)count = result.rowcountawait db.commit()logger.info(f"SUCCESS: Purged {count} stale semantic cache entries.")except Exception as e:logger.error(f"FAILURE: Semantic Cache Purge failed: {e}")await db.rollback()
75 unmodified lines7677787980818283847 unmodified lines92939495969775 unmodified lines// Pre-load logic: We wait for auth AND for the first set of stats to arrive.// AI/Narrative loading is now "soft" to avoid navigation flickers.const isInitialLoading = (authLoading && !user) || (user && ((statsLoading && !stats)));if (isInitialLoading) {return (7 unmodified lines);}const renderContent = () => {// 403 Forbidden check for direct navigation or state manipulationconst forbidden = <div className="forbidden-view">403: Forbidden — Insufficient Permissions</div>;75 unmodified lines76777879808182838485868788899091929394959697987 unmodified lines10610710810911011111275 unmodified lines// Pre-load logic: We wait for auth AND for the first set of stats to arrive.// AI/Narrative loading is now "soft" to avoid navigation flickers.// SAFETY: 5-second hard timeout prevents infinite loading if a backend endpoint 500s.const [bootstrapComplete, setBootstrapComplete] = useState(false);useEffect(() => {const timer = setTimeout(() => setBootstrapComplete(true), 5000);return () => clearTimeout(timer);}, []);useEffect(() => {if (stats || (!statsLoading && user)) {setBootstrapComplete(true);}}, [stats, statsLoading, user]);const isInitialLoading = !bootstrapComplete && ((authLoading && !user) || (user && (statsLoading && !stats)));if (isInitialLoading) {return (7 unmodified lines);}const renderContent = () => {// 403 Forbidden check for direct navigation or state manipulationconst forbidden = <div className="forbidden-view">403: Forbidden — Insufficient Permissions</div>;
44 unmodified lines4546474849505152535455565758596044 unmodified linesfetchNotifications();const token = localStorage.getItem(getStorageKey('token'));if (token && user?.workspace_id) {const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`));ws.onmessage = (event) => {const data = JSON.parse(event.data);if (data.type === 'notification' || data.event === 'ticket_updated') {setHasUnread(true);fetchNotifications();}};return () => ws.close();}}, [user?.workspace_id]);useEffect(() => {44 unmodified lines454647484950515253545556575859606162636465666744 unmodified linesfetchNotifications();const token = localStorage.getItem(getStorageKey('token'));if (token && user?.workspace_id) {try {const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`));ws.onmessage = (event) => {const data = JSON.parse(event.data);if (data.type === 'notification' || data.event === 'ticket_updated') {setHasUnread(true);fetchNotifications();}};ws.onerror = () => console.warn('[WS] Connection error — notifications may be delayed');ws.onclose = () => console.info('[WS] Connection closed');return () => ws.close();} catch (e) {console.warn('[WS] Failed to initialize:', e);}}}, [user?.workspace_id]);useEffect(() => {
19 unmodified lines2021222324252638 unmodified lines6566676869707112 unmodified lines8485868788899019 unmodified linesgenerate_global_insight,crystallize_memory,nexus_pulse_check,send_triple_notification)from agents.workflow import run_ai_workflow38 unmodified linesgenerate_global_insight,crystallize_memory,nexus_pulse_check,send_triple_notification]# Concurrency / Performance12 unmodified linescron(monitor_sla_thresholds, minute={0, 20, 40}), # Every 10 minutes (Improved resolution)cron(record_system_heartbeat, hour={0, 12}, minute=0), # Twice a daycron(generate_global_insight, hour=3, minute=0), # Once a day at 3 AMcron(nexus_pulse_check, minute=set(range(0, 60, 15))) # Every 15 minutes]on_startup = startup19 unmodified lines202122232425262738 unmodified lines666768697071727312 unmodified lines868788899091929319 unmodified linesgenerate_global_insight,crystallize_memory,nexus_pulse_check,send_triple_notification,purge_stale_semantic_cache)from agents.workflow import run_ai_workflow38 unmodified linesgenerate_global_insight,crystallize_memory,nexus_pulse_check,send_triple_notification,purge_stale_semantic_cache]# Concurrency / Performance12 unmodified linescron(monitor_sla_thresholds, minute={0, 20, 40}), # Every 10 minutes (Improved resolution)cron(record_system_heartbeat, hour={0, 12}, minute=0), # Twice a daycron(generate_global_insight, hour=3, minute=0), # Once a day at 3 AMcron(nexus_pulse_check, minute=set(range(0, 60, 15))), # Every 15 minutescron(purge_stale_semantic_cache, hour={0, 6, 12, 18}, minute=0) # Every 6 hours]on_startup = startup
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import asyncioimport osimport sysfrom datetime import datetime, timedeltafrom uuid import uuid4from unittest.mock import MagicMock, AsyncMock
# Add project root to pathsys.path.append(os.getcwd())
from core.database import async_session_factoryfrom models.workspace import Workspacefrom models.user import User, UserRolefrom models.nexus_semantic_cache import NexusSemanticCachefrom core.cache import SemanticCacheManagerfrom core.tasks import purge_stale_semantic_cachefrom 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())api/v1/reports.py+33-25
core/cache.py+22-4
core/tasks.py+23
frontend/apps/internal/src/App.tsx+18-3
frontend/apps/internal/src/components/TopBar.tsx+16-9
nexus_worker.py+6-3
scratch/test_cache_lifecycle.pyAdded+141