Spaces:
Paused
Paused
Download core/observability.py from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 6.8 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/core/observability.py
- Command line
-
hf download hf://spaces/3SCError404/nexus/core/observability.py
-
curl -L -o observability.py https://huggingface.co/spaces/3SCError404/nexus/resolve/main/core/observability.py
6.8 kB
| """ | |
| AI Observability Utils — centralized logic for recording AI workflow steps. | |
| """ | |
| from uuid import UUID | |
| from datetime import datetime | |
| from sqlalchemy import select, update | |
| 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 | |
| # This is critical for parallel jobs like Triage and Indexing | |
| stmt = ( | |
| update(AIWorkflow) | |
| .where(AIWorkflow.id == workflow.id) | |
| .values( | |
| steps=AIWorkflow.steps.concat([step_entry]), # Atomic JSONB append | |
| 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 (captures them in status). | |
| """ | |
| from opentelemetry import trace | |
| import time | |
| 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 | |
| job_keys = await arq_pool.keys("arq:job:*") | |
| results["pending_jobs"] = len(job_keys) | |
| span.set_attribute("health.status", "UP") | |
| span.set_attribute("health.latency_ms", latency) | |
| span.set_attribute("health.pending_jobs", len(job_keys)) | |
| 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": | |
| results["status"] = "healthy" | |
| return results | |