""" System and utility background tasks. """ import time import asyncio from typing import Any, Dict, Optional from uuid import UUID from datetime import datetime, timedelta, timezone from sqlalchemy import select, func, text, cast, String from sqlalchemy.dialects.postgresql import insert as pg_insert from core.database import async_session_factory from core.logging import get_logger from core.config import get_settings, get_redis_settings from core.cache import get_worker_redis_client from models.worker_job import WorkerJob, JobStatus from models.meta_infra_health import MetaInfraHealth, ServiceStatus from models.ticket import Ticket, TicketStatus from models.escalation_rule import EscalationRule from models.audit_log import AuditLog logger = get_logger(__name__) settings = get_settings() _redis_pool = None _redis_pool_lock = asyncio.Lock() async def get_task_pool(): """Singleton ARQ pool with a double-checked async lock to prevent race conditions.""" global _redis_pool if _redis_pool is not None: return _redis_pool async with _redis_pool_lock: # Re-check after acquiring lock — another coroutine may have initialized it if _redis_pool is None: from arq import create_pool _redis_pool = await create_pool(get_redis_settings()) return _redis_pool async def check_cron_lock(ctx, task_name: str, window_seconds: int = 60) -> bool: """ Prevent cross-replica cron duplication using the shared Postgres database. """ from agents.utils import get_deterministic_uuid job_id_raw = ctx.get('job_id') if not job_id_raw: return True job_id = get_deterministic_uuid(job_id_raw) async with async_session_factory() as db: try: limit = datetime.now(timezone.utc) - timedelta(seconds=window_seconds) stmt = select(WorkerJob).where( WorkerJob.id == job_id, WorkerJob.status == JobStatus.SUCCESS ) res = await db.execute(stmt) if res.scalar_one_or_none(): logger.info(f"⏭️ Skipping {task_name}: Already successfully completed.") return False stmt = select(WorkerJob).where( WorkerJob.id == job_id, WorkerJob.status == JobStatus.RUNNING, WorkerJob.started_at > limit ) res = await db.execute(stmt) if res.scalar_one_or_none(): logger.info(f"⏭️ Skipping {task_name}: Already running on another replica.") return False return True except Exception as e: logger.warning(f"Cron lock check failed for {task_name}: {e}") return True async def check_job_latch(ctx, entity_id: Any, task_type: str) -> bool: """ Implements Latest-Only Job Deduplication. """ try: redis = get_worker_redis_client() job_kwargs = ctx.get('job_kwargs', {}) enqueue_time = job_kwargs.get('enqueue_time_ms') if not enqueue_time: return True latch_key = f"job_latch:{task_type}:{str(entity_id)}" latest_time_str = await redis.get(latch_key) if latest_time_str: latest_time = int(latest_time_str) if enqueue_time < latest_time: logger.info(f"⏭️ Skipping stale job {ctx.get('job_id')} for {task_type}:{entity_id}") return False return True except Exception as e: logger.warning(f"Job latch check failed: {e}") return True async def enqueue_task(task_or_pool: Any, *args, **kwargs): """ Enqueues an ARQ job and updates the deduplication latch in Redis. """ task_name = "unknown" try: # Always use the internal singleton pool — callers that pass a pool as # the first argument (legacy pattern) still work, but a FastAPI Depends # object passed by mistake no longer causes a crash. pool_obj = await get_task_pool() if isinstance(task_or_pool, str): task_name = task_or_pool final_args = args else: if not args: raise ValueError("enqueue_task(pool, ...) requires a task_name string.") task_name = args[0] final_args = args[1:] target_pool = pool_obj entity_id = final_args[0] if final_args else "none" HEAVY_TASKS = [ "generate_ticket_embedding", "run_ai_workflow", "auto_summarize_ticket", "index_kb_article", "vectorize_nexus_interaction", "generate_global_insight", "crystallize_memory", "generate_workspace_insights", "harvest_expertise_task", "process_kb_import_task", "generate_nightly_personnel_analytics", "generate_workspace_story_task", "summarize_thread_title", "refresh_active_workspace_insights" ] queue_name = "arq:heavy" if task_name in HEAVY_TASKS else "arq:regular" now_ms = int(time.time() * 1000) latch_key = f"job_latch:{task_name}:{str(entity_id)}" redis = get_worker_redis_client() # Throttling Logic: Prevent re-enqueuing heavy tasks within a short window. # Certain tasks are excluded because they rely on rapid subsequent triggers # (e.g. chat streams, back-to-back KB edits, rapid ticket updates). THROTTLE_EXCLUDED = {"index_kb_article", "run_ai_workflow"} if task_name in HEAVY_TASKS and task_name not in THROTTLE_EXCLUDED: throttle_key = f"job_throttle:{task_name}:{str(entity_id)}" if await redis.get(throttle_key): logger.info(f"⏭️ Skipping {task_name} for {entity_id} (Throttled/Duplicate)") return await redis.set(throttle_key, now_ms, ex=120) # 2 min throttle for heavy tasks await redis.set(latch_key, now_ms, ex=86400) task_kwargs = kwargs.copy() task_kwargs['enqueue_time_ms'] = now_ms task_kwargs['metadata_json'] = { "entity_id": str(entity_id), "task_group": queue_name.split(':')[-1], "enqueued_at": datetime.now(timezone.utc).isoformat(), "latch_key_override": task_name } # Capture workspace_id for filtering — keep it in task_kwargs so the task receives it if "workspace_id" in task_kwargs: task_kwargs['metadata_json']["workspace_id"] = str(task_kwargs["workspace_id"]) # SMARTER AUTO-DETECTION: Extract workspace_id from positional args for known task patterns if "workspace_id" not in task_kwargs['metadata_json']: # Pattern A: workspace_id is the first argument (e.g. insights, stories, pulse) if task_name in ["generate_workspace_insights", "refresh_active_workspace_insights", "generate_workspace_story_task", "nexus_pulse_check", "monitor_sla_thresholds"]: task_kwargs['metadata_json']["workspace_id"] = str(entity_id) # Pattern B: workspace_id is the second argument (e.g. send_triple_notification, notify_mentions, record_workflow_step) elif task_name in ["send_triple_notification", "notify_mentions", "record_workflow_step_task", "recover_nexus_history"] and len(final_args) >= 2: task_kwargs['metadata_json']["workspace_id"] = str(final_args[1]) # Pattern C: Fallback to entity_id if it looks like a UUID and we have no other lead elif entity_id != "none" and task_name not in ["send_triple_notification"]: # notification entity_id is user_id, don't use as workspace_id task_kwargs['metadata_json']["workspace_id"] = str(entity_id) # PRE-RECORD: Create the job entry in DB immediately so it's visible while queued from agents.utils import get_deterministic_uuid, sanitize_for_db from core.database import async_session_factory from models.worker_job import WorkerJob, JobStatus # Generate a stable job_id if not provided. # Pop _job_id (ARQ-internal key) if a caller passed it directly — using it # as raw_job_id avoids a duplicate-kwarg crash when enqueue_job is called. raw_job_id = task_kwargs.pop("_job_id", None) or task_kwargs.get("job_id") or f"job:{task_name}:{now_ms}" job_uuid = get_deterministic_uuid(raw_job_id) try: now = datetime.now(timezone.utc) values = dict( id=job_uuid, task_name=task_name, status=JobStatus.QUEUED, args=sanitize_for_db(final_args), kwargs=sanitize_for_db(task_kwargs), metadata_json=sanitize_for_db(task_kwargs['metadata_json']), queued_at=now, created_at=now, updated_at=now, ) stmt = pg_insert(WorkerJob).values(**values).on_conflict_do_update( index_elements=['id'], set_=dict(status=JobStatus.QUEUED, queued_at=now, updated_at=now) ) async with async_session_factory() as db: await db.execute(stmt) await db.commit() except Exception as db_err: logger.warning(f"Failed to pre-record job {task_name}: {db_err}") await target_pool.enqueue_job(task_name, *final_args, _job_id=raw_job_id, _queue_name=queue_name, **task_kwargs) log_entity = task_kwargs.get("workspace_id", entity_id) logger.info(f"📤 Enqueued {task_name} to {queue_name} for {log_entity} | ID: {job_uuid}") return job_uuid except Exception as e: logger.error(f"Failed to enqueue task {task_name}: {e}") return None async def record_workflow_step_task( ctx: Any, entity_id: str, workspace_id: str, workflow_type: str, step_name: str, input_data: Optional[Dict] = None, output_data: Optional[Dict] = None, current_stage: Optional[str] = None, duration_ms: Optional[float] = None, **kwargs ): """Background task to record a workflow lifecycle step.""" try: async with async_session_factory() as db: from core.observability import record_workflow_step await record_workflow_step( db, entity_id=UUID(entity_id), workspace_id=UUID(workspace_id), workflow_type=workflow_type, step_name=step_name, input_data=input_data, output_data=output_data, current_stage=current_stage or "", duration_ms=duration_ms or 0.0 ) await db.commit() except Exception as e: logger.warning(f"Failed to record workflow step in background: {e}") async def monitor_sla_thresholds(ctx, *args, **kwargs): """ Periodic task to check for SLA breaches and apply escalation rules. """ if not await check_cron_lock(ctx, "monitor_sla_thresholds", window_seconds=120): return from core.cache import get_redis_client, invalidate_cache logger.info("Starting SLA monitoring check...") async with async_session_factory() as db: now = datetime.now(timezone.utc) stmt = ( select(Ticket, EscalationRule) .join(EscalationRule, (EscalationRule.workspace_id == Ticket.workspace_id) & (EscalationRule.priority_level == cast(Ticket.priority, String))) .where( Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED]), Ticket.deleted_at.is_(None), EscalationRule.is_active ) .limit(500) ) result = await db.execute(stmt) breached_candidates = result.all() from agents.utils import get_available_agents from models.user import UserRole # Cache for staff per workspace to avoid N+1 queries staff_cache = {} notification_tasks = [] redis = get_redis_client() # Batch-fetch all SLA notification latches in one MGET instead of per-ticket GETs. latch_keys = [] for ticket, _ in breached_candidates: tid = str(ticket.id) latch_keys += [ f"notified_sla_breached:{tid}", f"notified_sla_critical:{tid}", f"notified_sla_warning:{tid}", ] latch_values = await redis.mget(*latch_keys) if latch_keys else [] latch_map: dict = dict(zip(latch_keys, latch_values)) for ticket, rule in breached_candidates: try: threshold_time = ticket.created_at.replace(tzinfo=timezone.utc) age_minutes = (now - threshold_time).total_seconds() / 60 raw_risk_score = (age_minutes / rule.threshold_minutes) * 100 # RECIPIENTS: Always include assignee, plus role-based escalation recipients = [] if ticket.assigned_to: recipients.append(ticket.assigned_to) # Fetch all staff to identify Leads and Admins (Cached per workspace) if ticket.workspace_id not in staff_cache: staff_cache[ticket.workspace_id] = await get_available_agents(db, ticket.workspace_id) all_staff = staff_cache[ticket.workspace_id] leads = [s.id for s in all_staff if s.role in [UserRole.SC_LEAD, UserRole.SC_ADMIN]] # TIER 1: BREACHED (>100%) if raw_risk_score >= 100: latch = f"notified_sla_breached:{str(ticket.id)}" if not latch_map.get(latch): # Notify Everyone (Assignee + Leads + Admins) target_ids = list(set(recipients + leads)) for uid in target_ids: notification_tasks.append(enqueue_task( "send_triple_notification", uid, ticket.workspace_id, "🚨 SLA BREACHED: Immediate Intervention Required", f"Ticket '{ticket.title}' (P:{ticket.priority}) has exceeded its SLA. Urgent action needed.", link=f"/dashboard?ticket={ticket.id}" )) await redis.set(latch, "1", ex=86400) if not ticket.is_escalated: ticket.is_escalated = now db.add(ticket) await invalidate_cache(f"ticket:detail:{ticket.id}") db.add(AuditLog( workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id, action="SLA_ESCALATION", user_id=None, new_value={"rule": rule.name, "risk": "BREACHED"} )) # TIER 2: CRITICAL (>85%) elif raw_risk_score >= 85: latch = f"notified_sla_critical:{str(ticket.id)}" if not latch_map.get(latch): # Notify Assignee + Leads target_ids = list(set(recipients + leads)) for uid in target_ids: notification_tasks.append(enqueue_task( "send_triple_notification", uid, ticket.workspace_id, "🚨 CRITICAL RISK: SLA Breach Imminent (85%)", f"Ticket '{ticket.title}' is at 85% of its SLA. Resolution required immediately.", link=f"/dashboard?ticket={ticket.id}" )) await redis.set(latch, "1", ex=86400) db.add(AuditLog( workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id, action="SLA_CRITICAL_WARNING", user_id=None, new_value={"rule": rule.name, "risk": "85%"} )) # TIER 3: WARNING (>60%) elif raw_risk_score >= 60: latch = f"notified_sla_warning:{str(ticket.id)}" if not latch_map.get(latch): # Notify Assignee ONLY for uid in recipients: notification_tasks.append(enqueue_task( "send_triple_notification", uid, ticket.workspace_id, "⚠️ SLA WARNING: 60% Capacity Reached", f"Ticket '{ticket.title}' has utilized 60% of its SLA window. Please prioritize.", link=f"/dashboard?ticket={ticket.id}" )) await redis.set(latch, "1", ex=86400) db.add(AuditLog( workspace_id=ticket.workspace_id, entity_type="ticket", entity_id=ticket.id, action="SLA_WARNING", user_id=None, new_value={"rule": rule.name, "risk": "60%"} )) except Exception as e: logger.error(f"SLA Monitor error for ticket {ticket.id}: {e}") # Commit changes every 20 tickets to keep transaction duration low if len(notification_tasks) >= 20: await db.commit() # Run enqueue_task calls in parallel (they are fast as they only push to Redis) await asyncio.gather(*notification_tasks, return_exceptions=True) notification_tasks = [] await db.commit() if notification_tasks: await asyncio.gather(*notification_tasks, return_exceptions=True) async def record_system_heartbeat(ctx, *args, **kwargs): """ Periodic task to record infrastructure health snapshots. """ if not await check_cron_lock(ctx, "record_system_heartbeat", window_seconds=120): return from arq import create_pool import httpx logger.info("Recording system heartbeat...") async with async_session_factory() as db: # DB check db_start = time.perf_counter() db_status = ServiceStatus.DOWN db_latency = 0 try: await db.execute(text("SELECT 1")) db_status = ServiceStatus.UP db_latency = (time.perf_counter() - db_start) * 1000 except Exception: pass db.add(MetaInfraHealth(service_name="DATABASE", status=db_status, latency_ms=db_latency, environment="production")) # Redis check redis_start = time.perf_counter() redis_status = ServiceStatus.DOWN redis_latency = 0 try: await create_pool(get_redis_settings()) redis_status = ServiceStatus.UP redis_latency = (time.perf_counter() - redis_start) * 1000 except Exception: pass db.add(MetaInfraHealth(service_name="REDIS", status=redis_status, latency_ms=redis_latency, environment="production")) # Ollama check ollama_start = time.perf_counter() ollama_status = ServiceStatus.DOWN ollama_latency = 0 try: async with httpx.AsyncClient(timeout=5.0) as client: resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags") if resp.status_code == 200: ollama_status = ServiceStatus.UP ollama_latency = (time.perf_counter() - ollama_start) * 1000 except Exception: pass db.add(MetaInfraHealth(service_name="OLLAMA", status=ollama_status, latency_ms=ollama_latency, environment="production")) await db.commit() async def nexus_pulse_check(ctx, *args, **kwargs): """ Proactive AI "Pulse" Nudge. """ if not await check_cron_lock(ctx, "nexus_pulse_check", window_seconds=300): return logger.info("Executing Proactive AI Pulse Check...") from core.websockets import manager async with async_session_factory() as db: fifteen_mins_ago = datetime.now(timezone.utc) - timedelta(minutes=15) stmt = select(Ticket.workspace_id).where(Ticket.updated_at >= fifteen_mins_ago).distinct() workspaces = (await db.execute(stmt)).scalars().all() for w_id in workspaces: try: sla_breach_count = (await db.execute( select(func.count(Ticket.id)).where( Ticket.workspace_id == w_id, Ticket.priority == "P0", Ticket.status != "CLOSED", Ticket.updated_at >= fifteen_mins_ago ) )).scalar() or 0 if sla_breach_count >= 3: alert = {"type": "NEXUS_PULSE_ALERT", "level": "critical", "title": "Anomaly Detected", "message": f"{sla_breach_count} urgent tickets updated."} await asyncio.gather( manager.broadcast_to_role(w_id, "3sc_admin", alert), manager.broadcast_to_role(w_id, "3sc_lead", alert), return_exceptions=True ) except Exception: pass async def purge_stale_semantic_cache(ctx, *args, **kwargs): """ Periodic task to physically delete semantic cache records older than 12 hours. """ if not await check_cron_lock(ctx, "purge_stale_semantic_cache", window_seconds=600): return from models.nexus_semantic_cache import NexusSemanticCache from sqlalchemy import delete logger.info("Executing Semantic Cache Purge...") async with async_session_factory() as db: try: stmt = delete(NexusSemanticCache).where( NexusSemanticCache.created_at < (func.now() - text("INTERVAL '12 hours'")) ) await db.execute(stmt) await db.commit() except Exception: await db.rollback() async def recover_nexus_history(ctx, thread_id: UUID, workspace_id: UUID, user_role: str, **kwargs): """ Background worker task to load and mask conversational history for a Nexus thread. """ from models.nexus_interaction import NexusInteraction from agents.security import mask_for_role from models.user import User as UserTable logger.info(f"💾 Recovering nexus history for thread {thread_id}...") async with async_session_factory() as db: stmt = ( select(NexusInteraction, UserTable.full_name) .join(UserTable, NexusInteraction.user_id == UserTable.id) .where( NexusInteraction.thread_id == thread_id, NexusInteraction.workspace_id == workspace_id ) .order_by(NexusInteraction.created_at.asc()) ) result = await db.execute(stmt) rows = result.all() if not rows: return [] interaction_dicts = [dict( id=i.id, input_query=i.input_query, ai_answer=i.ai_answer, sender_name=full_name, created_at=i.created_at.isoformat() ) for i, full_name in rows] masked = mask_for_role(interaction_dicts, user_role) history = [] for i in masked: history.append({"role": "user", "content": i["input_query"], "senderName": i.get("sender_name", "User"), "timestamp": i["created_at"]}) history.append({"role": "assistant", "content": i["ai_answer"], "senderName": "Nexus", "timestamp": i["created_at"]}) return history