Spaces:
Paused
Paused
File size: 7,933 Bytes
5eb4857 f530d09 5eb4857 1049d57 5eb4857 b7980f7 e9a2d53 b7980f7 e9a2d53 b7980f7 99262de b7980f7 e9a2d53 f3a0c24 eb621b0 f3a0c24 eb621b0 f3a0c24 eb621b0 f3a0c24 1c89e32 f3a0c24 1c89e32 f3a0c24 1c89e32 f3a0c24 1c89e32 f3a0c24 1c89e32 f3a0c24 1c89e32 f3a0c24 1c89e32 eb621b0 1c89e32 eb621b0 8c5af7e eb621b0 8c5af7e eb621b0 058e076 f3a0c24 1c89e32 eb621b0 f3a0c24 058e076 f3a0c24 058e076 988a883 eb621b0 f3a0c24 eb621b0 f3a0c24 | 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 | """
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
|