Spaces:
Paused

File size: 5,714 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
e9a2d53
 
b7980f7
e9a2d53
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
e9a2d53
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
"""
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)
    
    # Use Console Exporting for local development
    # In production, this would be an OTLP exporter to Jaeger/Datadog/NewRelic
    processor = BatchSpanProcessor(ConsoleSpanExporter())
    provider.add_span_processor(processor)
    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",
        "redis": "DOWN",
        "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 select
            await db.execute(select(1))
            results["database"] = "UP"
            span.set_attribute("health.status", "UP")
            span.set_attribute("health.latency_ms", (time.perf_counter() - start_time) * 1000)
        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()
            results["redis"] = "UP"
            span.set_attribute("health.status", "UP")
            span.set_attribute("health.latency_ms", (time.perf_counter() - start_time) * 1000)
        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