Spaces:
Paused
Paused
File size: 24,128 Bytes
4777084 d8744fd 4777084 c52610e 4777084 12dfdef 4777084 12dfdef 4777084 12dfdef 4777084 d8744fd 4777084 d8744fd 4777084 878b20d 4777084 878b20d 4777084 878b20d 4777084 356a201 4777084 aa34d3f ef24f33 baf85c2 4777084 4c16050 6cc0dee 33a5449 aa34d3f 6cc0dee 4c16050 4777084 d8744fd 4777084 1c7bba3 774e02c 47835df 774e02c eced686 4777084 1c7bba3 c52610e 1c7bba3 4777084 1c7bba3 d8744fd c52610e 1c7bba3 c52610e 1c7bba3 e343b22 774e02c 1c7bba3 4777084 1c7bba3 4777084 d8744fd 4777084 d8744fd 4777084 1fdd745 4777084 186d110 4777084 d559c49 4777084 ecca730 4777084 1fdd745 4777084 1fdd745 4777084 186d110 1fdd745 186d110 1fdd745 d559c49 1fdd745 4777084 1fdd745 4777084 1fdd745 d559c49 1fdd745 186d110 1fdd745 4777084 1fdd745 d559c49 1fdd745 186d110 1fdd745 4777084 1fdd745 4777084 1fdd745 4777084 1fdd745 4777084 186d110 1fdd745 4777084 186d110 1fdd745 4777084 d8744fd 4777084 d8744fd 4777084 d8744fd 4777084 d8744fd 4777084 d8744fd 4777084 d8744fd 4777084 d8744fd 4777084 | 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 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | """
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
|