# Session Metrics Monitoring (MVP)

Simple monitoring system for tracking voice agent cost, latency, and success rates using Supabase.

Part of Issue #151 - Production Deployment & Monitoring (Option 1: Built-in tools)

## Setup

### 1. Apply Database Migration

```bash
# Apply the session_metrics migration to Supabase
cd apps/slide-system/supabase
supabase db push
```

Or manually via Supabase Dashboard SQL Editor:
```sql
-- Copy and paste contents of:
-- apps/slide-system/supabase/migrations/20251022_add_session_metrics.sql
```

### 2. Verify Migration

Check that these objects exist in Supabase:
- Table: `session_metrics`
- Views: `v_session_metrics_recent`, `v_session_metrics_cost_stats`, `v_session_metrics_latency_stats`, `v_session_metrics_success_rate`

## Usage in Voice Agent

### Basic Integration

```python
from voice_agent_livekit.metrics import SessionMetrics
from voice_agent_livekit.supabase_client import create_supabase_client

# Initialize
supabase = create_supabase_client()
metrics = SessionMetrics(
    session_id="uuid-from-conversation-sessions",
    supabase_client=supabase.client
)

# Start tracking
await metrics.start()

# Record costs (incremental)
await metrics.update_cost(
    stt=0.005,   # $0.005 for this STT call
    llm=0.050,   # $0.050 for this LLM call
    tts=0.120    # $0.120 for this TTS call
)

# Record latencies
await metrics.record_latency(
    session_init=2150,      # 2150ms from button to greeting
    voice_response=1250,    # 1250ms from customer stop to agent start
    slide_control=350       # 350ms from command to visual update
)

# Track turns and commands
await metrics.increment_turns()
await metrics.increment_slide_commands()

# Mark complete
await metrics.complete(audio_minutes=3.5)

# Or mark failed
await metrics.fail(
    error_message="LiveKit connection timeout",
    error_code="LIVEKIT_TIMEOUT"
)
```

### Example: Full Session Lifecycle

```python
async def run_voice_session(session_id: str):
    supabase = create_supabase_client()
    metrics = SessionMetrics(session_id, supabase.client)

    try:
        # Start metrics tracking
        await metrics.start()

        # Track session init latency
        start = time.time()
        await connect_to_livekit()
        init_latency = int((time.time() - start) * 1000)
        await metrics.record_latency(session_init=init_latency)

        # ... run conversation ...

        # Track each turn
        await metrics.increment_turns()
        await metrics.update_cost(stt=0.005, llm=0.050, tts=0.120)

        # Track slide commands
        await metrics.increment_slide_commands()

        # Complete successfully
        await metrics.complete(audio_minutes=3.5)

    except Exception as e:
        await metrics.fail(str(e), error_code="UNEXPECTED_ERROR")
        raise
```

## Monitoring with Supabase Dashboard

### Quick View: Recent Sessions

```sql
-- View last 100 sessions with key metrics
SELECT * FROM v_session_metrics_recent;
```

### Cost Tracking

```sql
-- Daily cost summary
SELECT * FROM v_session_metrics_cost_stats
WHERE day >= CURRENT_DATE - INTERVAL '7 days'
ORDER BY day DESC;

-- Sessions exceeding cost target ($0.66)
SELECT
    session_id,
    livekit_room_name,
    cost_total,
    cost_total - 0.66 AS over_budget,
    created_at
FROM v_session_metrics_recent
WHERE cost_total > 0.66
ORDER BY cost_total DESC
LIMIT 20;

-- Cost breakdown by component
SELECT
    AVG(cost_stt) AS avg_stt,
    AVG(cost_llm) AS avg_llm,
    AVG(cost_tts) AS avg_tts,
    AVG(cost_livekit) AS avg_livekit,
    AVG(cost_total) AS avg_total
FROM session_metrics
WHERE status = 'completed'
    AND created_at >= CURRENT_DATE - INTERVAL '7 days';
```

### Latency Monitoring

```sql
-- Daily latency stats with p95
SELECT * FROM v_session_metrics_latency_stats
WHERE day >= CURRENT_DATE - INTERVAL '7 days'
ORDER BY day DESC;

-- Sessions exceeding latency targets
SELECT
    session_id,
    livekit_room_name,
    latency_session_init,
    latency_voice_response,
    latency_slide_control,
    created_at
FROM v_session_metrics_recent
WHERE latency_voice_response > 2000  -- Target: <2s
   OR latency_session_init > 3000     -- Target: <3s
   OR latency_slide_control > 500     -- Target: <500ms
ORDER BY created_at DESC
LIMIT 20;
```

### Success Rate Tracking

```sql
-- Daily success rate
SELECT * FROM v_session_metrics_success_rate
WHERE day >= CURRENT_DATE - INTERVAL '7 days'
ORDER BY day DESC;

-- Recent failures
SELECT
    session_id,
    error_code,
    error_message,
    created_at
FROM session_metrics
WHERE status = 'failed'
ORDER BY created_at DESC
LIMIT 20;

-- Error frequency by code
SELECT
    error_code,
    COUNT(*) AS error_count,
    COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS error_pct
FROM session_metrics
WHERE status = 'failed'
    AND created_at >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY error_code
ORDER BY error_count DESC;
```

### Real-time Monitoring

```sql
-- Currently active sessions
SELECT
    sm.session_id,
    cs.livekit_room_name,
    sm.total_turns,
    sm.total_slide_commands,
    EXTRACT(EPOCH FROM (NOW() - sm.created_at)) / 60 AS duration_minutes,
    sm.created_at
FROM session_metrics sm
JOIN conversation_sessions cs ON sm.session_id = cs.id
WHERE sm.status = 'in_progress'
ORDER BY sm.created_at DESC;

-- Session count by status
SELECT
    status,
    COUNT(*) AS count
FROM session_metrics
WHERE created_at >= CURRENT_DATE
GROUP BY status;
```

## Setting Up Alerts (Supabase Webhooks)

Create webhooks in Supabase Dashboard to trigger alerts when thresholds are exceeded:

### 1. High Cost Alert

```sql
-- Create webhook trigger when cost exceeds $0.66
CREATE OR REPLACE FUNCTION notify_high_cost()
RETURNS TRIGGER AS $$
BEGIN
    IF NEW.cost_total > 0.66 THEN
        PERFORM pg_notify(
            'high_cost_alert',
            json_build_object(
                'session_id', NEW.session_id,
                'cost_total', NEW.cost_total,
                'created_at', NEW.created_at
            )::text
        );
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER high_cost_trigger
    AFTER UPDATE ON session_metrics
    FOR EACH ROW
    WHEN (NEW.cost_total > 0.66)
    EXECUTE FUNCTION notify_high_cost();
```

### 2. High Latency Alert

```sql
-- Alert when voice response latency exceeds 2 seconds
CREATE OR REPLACE FUNCTION notify_high_latency()
RETURNS TRIGGER AS $$
BEGIN
    IF NEW.latency_voice_response > 2000 THEN
        PERFORM pg_notify(
            'high_latency_alert',
            json_build_object(
                'session_id', NEW.session_id,
                'latency_ms', NEW.latency_voice_response,
                'created_at', NEW.created_at
            )::text
        );
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER high_latency_trigger
    AFTER UPDATE ON session_metrics
    FOR EACH ROW
    WHEN (NEW.latency_voice_response > 2000)
    EXECUTE FUNCTION notify_high_latency();
```

## Migration to Grafana Cloud (Future)

When ready to upgrade to Grafana Cloud (Option 2), the session_metrics table already includes:
- All necessary metrics fields
- JSONB metadata column for extensibility
- Timestamptz for accurate time-series data
- Indexes for efficient querying

You can export this data to Grafana Cloud using:
1. Supabase REST API → Prometheus exporter
2. Scheduled queries → Grafana Loki
3. pg_exporter for direct PostgreSQL metrics

The views (`v_session_metrics_*`) can be converted directly to Grafana dashboards.

## Troubleshooting

### Metrics Not Recording

1. Check Supabase connection:
   ```bash
   echo $SUPABASE_URL
   echo $SUPABASE_SERVICE_KEY
   ```

2. Verify migration applied:
   ```sql
   SELECT EXISTS (
       SELECT FROM pg_tables
       WHERE schemaname = 'public'
       AND tablename = 'session_metrics'
   );
   ```

3. Check Railway logs for errors:
   ```bash
   railway logs --service voice-agent-livekit --environment production
   ```

### High Memory Usage

If tracking many sessions, the in-memory counters might accumulate. Consider:
- Periodic resets of `_latencies` list
- Move to SQL aggregations instead of Python accumulators
- Implement batch updates instead of per-turn updates

## Best Practices

1. **Always start metrics** at the beginning of the session
2. **Update costs incrementally** as each API call completes
3. **Record latencies immediately** after measuring
4. **Always mark sessions as completed/failed/abandoned** to avoid "in_progress" leak
5. **Use error codes** for categorization (easier to query and alert)

## Next Steps

When you're ready to upgrade to Grafana Cloud (Option 2):
1. Sign up at grafana.com (free tier: 10k series, 50GB logs, 14-day retention)
2. Set up Prometheus exporter from Supabase
3. Create Grafana dashboards using the SQL queries above as templates
4. Set up Loki for Railway log aggregation
5. Configure alerts in Grafana instead of Supabase webhooks
