""" AI Observability Utils — centralized logic for recording AI workflow steps. """ from uuid import UUID from datetime import datetime from sqlalchemy import select, update, cast, func from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.asyncio import AsyncSession from models.ai_workflow import AIWorkflow from core.logging import get_logger logger = get_logger(__name__) async def record_workflow_step( db: AsyncSession, entity_id: UUID, workspace_id: UUID, workflow_type: str, step_name: str, input_data: any = None, output_data: any = None, status: str = "success", duration_ms: float = 0.0, current_stage: str = None ): """ Records a step in an AI workflow lifecycle. Finds the existing workflow for this entity_id (ticket_id, article_id, search_id) or creates a new one. """ try: # 1. Fetch existing workflow stmt = select(AIWorkflow).where( AIWorkflow.entity_id == entity_id, AIWorkflow.workflow_type == workflow_type ) res = await db.execute(stmt) workflow = res.scalar_one_or_none() step_entry = { "timestamp": datetime.utcnow().isoformat(), "step_name": step_name, "status": status, "input": input_data, "output": output_data, "duration_ms": round(duration_ms, 2) } if not workflow: # 2. Create new record workflow = AIWorkflow( workspace_id=workspace_id, entity_id=entity_id, workflow_type=workflow_type, current_stage=current_stage or step_name, steps=[step_entry], total_duration_ms=duration_ms ) db.add(workflow) else: # 3. USE ATOMIC UPDATE to prevent lost steps in concurrent background tasks stmt = ( update(AIWorkflow) .where(AIWorkflow.id == workflow.id) .values( steps=func.coalesce(AIWorkflow.steps, cast([], JSONB)).concat(cast([step_entry], JSONB)), total_duration_ms=AIWorkflow.total_duration_ms + duration_ms, current_stage=current_stage or AIWorkflow.current_stage ) ) await db.execute(stmt) # We flush so the ID is available, caller commits the full transaction await db.flush() return workflow except Exception as e: logger.error(f"Failed to record AI workflow step for {entity_id}: {e}") return None def setup_telemetry(app) -> None: """ Initializes OpenTelemetry SDK for distributed tracing of the FastAPI application. Connects the FastAPIInstrumentor and configures the OTLP/Console exporters. """ from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor from opentelemetry.sdk.resources import SERVICE_NAME, Resource from core.config import get_settings settings = get_settings() # Define the Resource (Service Name) resource = Resource(attributes={ SERVICE_NAME: settings.APP_NAME }) # Set global TracerProvider with the Resource provider = TracerProvider(resource=resource) # PERFORMANCE OPTIMIZATION: Only export spans to Console in DEBUG mode or on Windows. # Printing full JSON spans to stdout in production (HuggingFace/Railway) causes # log rate-limiting (e.g. 500 logs/sec) and performance degradation. import platform if settings.DEBUG or platform.system() == "Windows": processor = BatchSpanProcessor(ConsoleSpanExporter()) provider.add_span_processor(processor) logger.info("OpenTelemetry Console Span Exporting ENABLED (DEBUG/Local mode)") else: # In production, we would typically use an OTLP exporter here. # For now, we suppress console export to stay within cloud log quotas. logger.info("OpenTelemetry Console Span Exporting DISABLED (Production mode)") trace.set_tracer_provider(provider) # Auto-instrument FastAPI routes FastAPIInstrumentor.instrument_app(app) logger.info(f"OpenTelemetry Trace Provider configured for service: {settings.APP_NAME}") async def check_infra_health(db: AsyncSession, arq_pool: any) -> dict: """ Perform a traced health check across core dependencies. Returns a status dict and raises no exceptions. Optimized with a 30s local memory cache to prevent Redis/DB saturation. """ from opentelemetry import trace import time from core.cache import get_l1_cache, set_l1_cache # 0. Check Local Cache (30s TTL) cache_key = "nexus:internal:infra_health" cached = get_l1_cache(cache_key) if cached: return cached tracer = trace.get_tracer(__name__) results = { "database": "DOWN", "database_latency": 0.0, "redis": "DOWN", "redis_latency": 0.0, "pending_jobs": 0, "status": "unhealthy" } # 1. Database Sub-span with tracer.start_as_current_span("health_check.database") as span: start_time = time.perf_counter() try: from sqlalchemy import text await db.execute(text("SELECT 1")) latency = (time.perf_counter() - start_time) * 1000 results["database"] = "UP" results["database_latency"] = round(latency, 2) span.set_attribute("health.status", "UP") span.set_attribute("health.latency_ms", latency) except Exception as e: results["database"] = f"DOWN: {str(e)}" span.record_exception(e) span.set_status(trace.Status(trace.StatusCode.ERROR)) # 2. Redis/Arq Sub-span with tracer.start_as_current_span("health_check.redis") as span: start_time = time.perf_counter() try: await arq_pool.ping() latency = (time.perf_counter() - start_time) * 1000 results["redis"] = "UP" results["redis_latency"] = round(latency, 2) # Gauge active jobs for process queue visibility (SAFE SCAN replacement for KEYS) pending_count = 0 worker_count = 0 # Use SCAN to avoid blocking Redis event loop # Catch all jobs regardless of queue async for _ in arq_pool.scan_iter("arq:job:*"): pending_count += 1 # Catch all health checks across regular and heavy workers async for _ in arq_pool.scan_iter("arq:health-check*"): worker_count += 1 results["pending_jobs"] = pending_count results["workers_online"] = worker_count span.set_attribute("health.status", "UP") span.set_attribute("health.latency_ms", latency) span.set_attribute("health.pending_jobs", pending_count) span.set_attribute("health.workers_active", worker_count) except Exception as e: results["redis"] = f"DOWN: {str(e)}" span.record_exception(e) span.set_status(trace.Status(trace.StatusCode.ERROR)) if results["database"] == "UP" and results["redis"] == "UP" and results.get("workers_online", 0) > 0: results["status"] = "healthy" elif results["database"] == "UP" and results["redis"] == "UP": results["status"] = "degraded" else: results["status"] = "unhealthy" # Final step: Cache results for 30s set_l1_cache(cache_key, results, ttl=30) return results