# Screenshare Bot Monitoring Guide

Comprehensive monitoring, alerting, and performance tracking guide for production operations.

## Table of Contents

- [Overview](#overview)
- [Railway Monitoring](#railway-monitoring)
- [Bot Health Metrics](#bot-health-metrics)
- [Application Metrics](#application-metrics)
- [Alert Configuration](#alert-configuration)
- [Log Analysis](#log-analysis)
- [Performance Tracking](#performance-tracking)
- [Dashboards](#dashboards)
- [Troubleshooting Metrics](#troubleshooting-metrics)

---

## Overview

### Monitoring Philosophy

The screenshare bot monitoring strategy follows a three-tier approach:

1. **Infrastructure Monitoring** (Railway platform)
   - Service health and uptime
   - Resource usage (memory, CPU)
   - Deployment status
   - Platform-level alerts

2. **Application Monitoring** (Bot processes)
   - Active bot count
   - Spawn success rate
   - Bot lifecycle events
   - Performance metrics per bot

3. **Performance Monitoring** (Real-time metrics)
   - Frame rate stability
   - Memory consumption trends
   - CPU utilization patterns
   - Command latency

### Monitoring Objectives

- **Detect issues before they impact users**
- **Provide actionable alerts with context**
- **Track performance trends over time**
- **Support capacity planning decisions**
- **Enable rapid incident response**

---

## Railway Monitoring

### Accessing Railway Dashboard

Railway provides a comprehensive web-based monitoring dashboard.

**Access the Dashboard:**

```bash
# Open Railway dashboard
railway open --service slide-system

# Or visit directly
# https://railway.app/project/YOUR_PROJECT_ID/service/slide-system
```

**Dashboard Navigation:**

```
Railway Dashboard Layout:
├─ Deployments Tab
│  ├─ Active deployment status
│  ├─ Deployment history
│  ├─ Build logs
│  └─ Rollback options
│
├─ Metrics Tab ⭐ Primary monitoring view
│  ├─ CPU usage graph
│  ├─ Memory usage graph
│  ├─ Network I/O graph
│  └─ Restart count
│
├─ Logs Tab
│  ├─ Real-time log stream
│  ├─ Log search/filter
│  └─ Log export
│
├─ Variables Tab
│  ├─ Environment variables
│  └─ Secret management
│
└─ Settings Tab
   ├─ Service configuration
   ├─ Health checks
   └─ Resource limits
```

---

### Key Railway Metrics

#### 1. CPU Usage

**What it measures:** Percentage of CPU resources consumed by the service

**How to monitor:**

```bash
# View real-time CPU in Railway CLI
railway logs --service slide-system | grep "CPU:"

# Expected values:
# - Idle (no bots): 5-15%
# - 1 bot streaming: 20-35%
# - 3 bots streaming: 60-105%
# - 5 bots streaming: 100-175%
```

**Railway Dashboard View:**
- Navigate to Metrics tab
- View "CPU Usage" graph
- Hover over points for exact values
- Toggle time range (1h, 6h, 24h, 7d)

**Alert Thresholds:**

| Status | Threshold | Action |
|--------|-----------|--------|
| Normal | <80% | None |
| Warning | 80-95% | Monitor closely |
| Critical | >95% sustained | Reduce bot count or scale up |

**Troubleshooting High CPU:**

```bash
# Check how many bots are active
curl https://YOUR_SERVICE.railway.app/api/tavus/bot/status | jq '.activeCount'

# If count > expected, kill excess bots
curl -X POST https://YOUR_SERVICE.railway.app/api/tavus/bot/kill-all

# Check for runaway processes
railway run --service slide-system "ps aux | grep python"
```

---

#### 2. Memory Usage

**What it measures:** RAM consumption by the service (includes all bot processes)

**How to monitor:**

```bash
# View memory usage from logs
railway logs --service slide-system | grep "Memory:" | tail -10

# Expected memory per bot: 250-350 MB
# Expected total:
# - 1 bot: 300-400 MB
# - 3 bots: 900-1200 MB
# - 5 bots: 1500-2000 MB
```

**Railway Dashboard View:**
- Navigate to Metrics tab
- View "Memory Usage" graph
- Look for gradual increases (potential leak)
- Compare against Railway memory limit

**Alert Thresholds:**

| Bot Count | Normal | Warning | Critical |
|-----------|--------|---------|----------|
| 1 bot | <400 MB | 400-500 MB | >500 MB |
| 3 bots | <1200 MB | 1200-1500 MB | >1500 MB |
| 5 bots | <2000 MB | 2000-2500 MB | >2500 MB |

**Memory Leak Detection:**

A memory leak is indicated by steadily increasing memory over time without corresponding increase in bot count.

```bash
# Sample memory every 5 minutes for 30 minutes
for i in {1..6}; do
  echo "$(date): $(railway logs --service slide-system | grep "Memory:" | tail -1)"
  sleep 300
done

# Healthy pattern (memory plateaus):
# 10:00 Memory: 1250.2MB
# 10:05 Memory: 1248.5MB
# 10:10 Memory: 1253.1MB
# 10:15 Memory: 1251.8MB

# Memory leak pattern (continuous increase):
# 10:00 Memory: 1250.2MB
# 10:05 Memory: 1350.5MB
# 10:10 Memory: 1450.8MB
# 10:15 Memory: 1555.2MB  ⚠️ LEAK DETECTED
```

**Resolution:**

```bash
# Kill all bots to reclaim memory
curl -X POST https://YOUR_SERVICE.railway.app/api/tavus/bot/kill-all

# Restart service if memory doesn't drop
railway restart --service slide-system

# If leak persists, investigate bot cleanup logic
railway logs --service slide-system | grep "cleanup\|terminate"
```

---

#### 3. Service Restarts

**What it measures:** Number of times the service has restarted (crashes, deploys, manual restarts)

**How to monitor:**

```bash
# Check restart count via Railway dashboard
# Metrics tab > "Restarts" counter

# Check for recent crashes in logs
railway logs --service slide-system | grep "Railway.*restart\|Exit"
```

**Railway Dashboard View:**
- Navigate to Metrics tab
- View "Restarts" counter in top-right
- Click for restart history

**Alert Thresholds:**

| Restarts | Period | Status | Action |
|----------|--------|--------|--------|
| 0-1 | 24 hours | Normal | None |
| 2-3 | 24 hours | Warning | Investigate logs |
| 4+ | 24 hours | Critical | Immediate investigation |

**Restart Causes:**

```bash
# Check why service restarted
railway logs --service slide-system | grep -B 5 -A 5 "restart"

# Common patterns:
# - "OOM" = Out of memory (exit code 137)
# - "SIGTERM" = Graceful shutdown
# - "SIGKILL" = Forced kill
# - "Error:" = Application error
# - "Deploy" = New deployment
```

---

#### 4. Network I/O

**What it measures:** Incoming/outgoing network bandwidth

**How to monitor:**

Railway Dashboard:
- Navigate to Metrics tab
- View "Network" graph
- Monitor for unusual spikes

**Expected Bandwidth:**

```
Per Bot (10 FPS, 1280x720 PNG):
- Outbound: ~2-4 Mbps
- Inbound: <100 Kbps (commands only)

Total (5 bots):
- Outbound: ~10-20 Mbps
- Inbound: <500 Kbps
```

**Alert Thresholds:**

| Status | Outbound | Inbound |
|--------|----------|---------|
| Normal | <25 Mbps | <1 Mbps |
| Warning | 25-40 Mbps | 1-5 Mbps |
| Critical | >40 Mbps | >5 Mbps |

---

### Setting Up Railway Alerts

Railway supports notifications for critical events via webhooks.

#### Configure Notifications

**Via Railway Dashboard:**

1. Go to Project Settings > Notifications
2. Add webhook URL (Slack, Discord, etc.)
3. Select events to monitor:
   - `deployment.failed`
   - `deployment.crashed`
   - `service.restart`

**Slack Webhook Example:**

```bash
# Add Slack webhook to Railway
# 1. Create Slack webhook: https://api.slack.com/messaging/webhooks
# 2. Add to Railway:
#    Settings > Notifications > Add Webhook
#    URL: https://hooks.slack.com/services/YOUR/WEBHOOK/URL
#    Events: deployment.failed, deployment.crashed, service.restart
```

**Railway CLI Monitoring Script:**

```bash
#!/bin/bash
# monitor_railway.sh - Continuous Railway monitoring

while true; do
  echo "=== $(date) ==="

  # Check service status
  STATUS=$(railway status --service slide-system 2>&1)
  echo "$STATUS"

  # Check for crashes
  CRASHES=$(railway logs --service slide-system --since 5m | grep -c "crash\|Exit code: [^0]")
  if [ "$CRASHES" -gt 0 ]; then
    echo "⚠️ WARNING: $CRASHES crash(es) detected in last 5 minutes"
    # Send alert (integrate with your alerting system)
  fi

  # Check memory usage
  MEMORY=$(railway logs --service slide-system | grep "Memory:" | tail -1 | awk '{print $NF}' | sed 's/MB//')
  if (( $(echo "$MEMORY > 2000" | bc -l) )); then
    echo "⚠️ WARNING: High memory usage: ${MEMORY}MB"
  fi

  echo ""
  sleep 300  # Check every 5 minutes
done
```

---

## Bot Health Metrics

### Active Bot Count

**What it measures:** Number of currently running bot processes

**How to monitor:**

```bash
# Via API endpoint
curl https://YOUR_SERVICE.railway.app/api/tavus/bot/status | jq '.activeCount'

# Via logs
railway logs --service slide-system | grep "Active bots:" | tail -1

# Expected values: 0-5 (based on MAX_CONCURRENT_BOTS)
```

**Alert Conditions:**

```yaml
# Alert if bot count exceeds limit
- condition: active_bot_count > MAX_CONCURRENT_BOTS
  severity: critical
  action: Page on-call (possible bot leak)

# Alert if expected bots not running
- condition: active_bot_count < expected_count
  severity: warning
  action: Notify #ops-alerts (possible spawn failures)
```

**Monitoring Script:**

```bash
#!/bin/bash
# check_bot_count.sh

MAX_BOTS=5
ACTUAL=$(curl -s https://YOUR_SERVICE.railway.app/api/tavus/bot/status | jq -r '.activeCount')

if [ "$ACTUAL" -gt "$MAX_BOTS" ]; then
  echo "CRITICAL: Bot count ($ACTUAL) exceeds limit ($MAX_BOTS)"
  exit 2
elif [ "$ACTUAL" -eq "$MAX_BOTS" ]; then
  echo "WARNING: Bot count at maximum ($MAX_BOTS)"
  exit 1
else
  echo "OK: Bot count is $ACTUAL (limit: $MAX_BOTS)"
  exit 0
fi
```

---

### Memory Per Bot

**What it measures:** RAM consumption for each individual bot process

**How to monitor:**

```bash
# View performance logs for all active bots
railway logs --service slide-system | grep "Performance -" | tail -10

# Example output:
# Bot conv-123 Performance - Memory: 285.2MB, CPU: 22.1%, FPS: 10.0, ...
# Bot conv-456 Performance - Memory: 292.8MB, CPU: 24.3%, FPS: 10.1, ...
```

**Target Metrics:**

| Metric | Target | Warning | Critical |
|--------|--------|---------|----------|
| Memory per bot | <350 MB | 350-450 MB | >500 MB |
| Baseline (idle) | 200-250 MB | - | - |
| Streaming | 280-350 MB | - | - |

**Tracking Over Time:**

```bash
# Extract memory for specific bot
BOT_ID="conv-123"
railway logs --service slide-system | \
  grep "Bot $BOT_ID.*Memory:" | \
  awk '{print $6}' | \
  sed 's/Memory://; s/MB,//' | \
  tail -20

# Calculate average memory
railway logs --service slide-system | \
  grep "Performance -.*Memory:" | \
  awk '{print $6}' | \
  sed 's/Memory://; s/MB,//' | \
  awk '{sum+=$1; count+=1} END {print "Avg Memory:", sum/count, "MB"}'
```

---

### CPU Per Bot

**What it measures:** CPU percentage for each bot process

**How to monitor:**

```bash
# View CPU usage from performance logs
railway logs --service slide-system | grep "CPU:" | tail -10

# Example:
# Bot conv-123 Performance - Memory: 285.2MB, CPU: 22.1%, FPS: 10.0
```

**Target Metrics:**

| State | Target CPU | Warning | Critical |
|-------|------------|---------|----------|
| Idle (loading) | 5-15% | - | - |
| Streaming | 15-30% | 30-40% | >40% |
| 3 bots total | 45-90% | 90-120% | >120% |
| 5 bots total | 75-150% | 150-200% | >200% |

**CPU Performance Analysis:**

```bash
# Check if CPU is bottlenecking frame rate
railway logs --service slide-system | \
  grep "Performance -" | \
  tail -10 | \
  awk '{print "CPU:", $8, "FPS:", $10}'

# Example output:
# CPU: 22.1%, FPS: 10.0  ✅ Healthy
# CPU: 38.5%, FPS: 9.2   ⚠️ CPU high, FPS dropping
# CPU: 45.2%, FPS: 8.1   🚨 CPU bottleneck detected
```

---

### Frame Rate Per Bot

**What it measures:** Actual frames per second being sent to Daily.co room

**How to monitor:**

```bash
# View FPS from performance logs
railway logs --service slide-system | grep "Actual FPS:" | tail -10

# Example:
# Frames: 1000, Actual FPS: 10.02, Target FPS: 10
```

**Target Metrics:**

| Status | FPS Range | Action |
|--------|-----------|--------|
| Excellent | 9.9-10.1 | None |
| Good | 9.5-9.9 or 10.1-10.5 | Monitor |
| Degraded | 9.0-9.5 | Investigate |
| Critical | <9.0 | Reduce load or debug |

**Frame Rate Stability Test:**

```bash
# Sample FPS over 5 minutes
for i in {1..10}; do
  FPS=$(railway logs --service slide-system | grep "Actual FPS:" | tail -1 | awk '{print $6}')
  echo "$(date +%H:%M:%S): FPS = $FPS"
  sleep 30
done

# Analyze variance
# Low variance (±0.1 FPS): Stable ✅
# High variance (±1.0 FPS): Unstable ⚠️
```

**Frame Rate Troubleshooting:**

```bash
# If FPS < 9.0, check these metrics:

# 1. CPU usage (should be <30% per bot)
railway logs --service slide-system | grep "CPU:" | tail -5

# 2. Frame capture time (should be <50ms)
railway logs --service slide-system | grep "Frame Capture:" | tail -5

# 3. Network latency to Daily.co
railway logs --service slide-system | grep "DailyTransport.*latency"

# 4. Number of concurrent bots (reduce if needed)
curl -s https://YOUR_SERVICE.railway.app/api/tavus/bot/status | jq '.activeCount'
```

---

## Application Metrics

### Bots Spawned Total

**What it tracks:** Cumulative count of all bots spawned since service started

**How to monitor:**

```bash
# Count spawn events in logs
railway logs --service slide-system | grep -c "Bot spawned for"

# If metrics endpoint implemented:
curl https://YOUR_SERVICE.railway.app/api/metrics | jq '.bots_spawned_total'
```

**Usage:** Capacity planning, understanding usage patterns

---

### Bots Terminated Total

**What it tracks:** Cumulative count of all bots that terminated normally

**How to monitor:**

```bash
# Count normal terminations (exit code 0)
railway logs --service slide-system | grep "Bot process exited.*code: 0" | wc -l

# If metrics endpoint implemented:
curl https://YOUR_SERVICE.railway.app/api/metrics | jq '.bots_terminated_total'
```

**Metric Relationship:**

```
Termination Success Rate = bots_terminated_total / bots_spawned_total
Target: >95%
```

---

### Bots Crashed Total

**What it tracks:** Cumulative count of all bots that crashed (non-zero exit code)

**How to monitor:**

```bash
# Count crashes (exit code != 0)
railway logs --service slide-system | grep "Bot process exited" | grep -v "code: 0" | wc -l

# If metrics endpoint implemented:
curl https://YOUR_SERVICE.railway.app/api/metrics | jq '.bots_crashed_total'
```

**Alert Threshold:**

```yaml
- condition: crash_rate > 5% over 1 hour
  severity: warning
  action: Investigate crash patterns

- condition: crash_rate > 10% over 1 hour
  severity: critical
  action: Page on-call, consider rollback
```

**Crash Analysis:**

```bash
# Analyze crash exit codes
railway logs --service slide-system | grep "Bot process exited" | grep -v "code: 0"

# Common exit codes:
# - 1: General error (check stack trace)
# - 2: Missing arguments
# - 137: OOM killed
# - 143: SIGTERM (normal shutdown during deploy)
```

---

### Average Session Duration

**What it tracks:** Mean lifetime of bot sessions

**How to monitor:**

```bash
# Extract session durations from logs
railway logs --service slide-system | grep "Session duration:" | awk '{print $NF}' | sed 's/s//'

# Calculate average
railway logs --service slide-system | \
  grep "Session duration:" | \
  awk '{sum+=$NF; count+=1} END {print "Avg Duration:", sum/count, "seconds"}'
```

**Expected Values:**

```
Average Session Duration:
- Development/testing: 30-300 seconds (0.5-5 minutes)
- Production: 300-1800 seconds (5-30 minutes)
- Long presentations: 1800-3600 seconds (30-60 minutes)
```

**Usage:** Understanding typical conversation lengths, capacity planning

---

### Command Latency

**What it tracks:** Time between receiving slide navigation command and executing it

**How to monitor:**

```bash
# View command latency in performance logs
railway logs --service slide-system | grep "Command Latency:" | tail -10

# Example:
# Performance - ... Command Latency: 45.2ms
```

**Target Metrics:**

| Status | Latency | User Experience |
|--------|---------|-----------------|
| Excellent | <100ms | Imperceptible |
| Good | 100-300ms | Barely noticeable |
| Acceptable | 300-500ms | Slight delay |
| Poor | 500-1000ms | Noticeable lag |
| Critical | >1000ms | Significant delay |

**Alert Threshold:**

```yaml
- condition: command_latency > 500ms average over 5 minutes
  severity: warning
  action: Investigate Supabase connection

- condition: command_latency > 1000ms
  severity: critical
  action: Check network, Supabase status
```

---

## Alert Configuration

### Alert Severity Levels

**Critical Alerts** (Page On-Call)

```yaml
alerts:
  # Service completely down
  - name: Service Down
    condition: no_log_entries_for > 5 minutes
    severity: critical
    action: Page on-call engineer
    escalation: After 10 minutes, page team lead

  # Bot spawn failures
  - name: Bot Spawn Failure Rate High
    condition: spawn_success_rate < 90% over 10 minutes
    severity: critical
    action: Page on-call engineer
    context: Check Railway logs for spawn errors

  # OOM kills
  - name: Out of Memory Kills
    condition: exit_code == 137
    severity: critical
    action: Page on-call engineer
    context: Bot OOM killed, check memory usage

  # All bots crashed
  - name: Zero Active Bots
    condition: active_bot_count == 0 AND expected_count > 0
    severity: critical
    action: Page on-call engineer
    context: All bots have crashed or terminated

  # Service restart loop
  - name: Restart Loop Detected
    condition: restart_count > 3 in 15 minutes
    severity: critical
    action: Page on-call engineer
    context: Service crashing repeatedly
```

**Warning Alerts** (Notify Channel)

```yaml
alerts:
  # High memory usage
  - name: High Memory Usage Per Bot
    condition: memory > 450MB per bot
    severity: warning
    action: Notify #ops-alerts
    context: Bot memory approaching limit

  # High CPU usage
  - name: High CPU Usage
    condition: cpu > 35% per bot sustained for 5 minutes
    severity: warning
    action: Notify #ops-alerts
    context: Bot CPU usage elevated

  # Low frame rate
  - name: Low Frame Rate
    condition: fps < 9.0 sustained for 2 minutes
    severity: warning
    action: Notify #ops-alerts
    context: Frame rate below target

  # Frequent bot restarts
  - name: Frequent Bot Restarts
    condition: bot_restarts > 2 per hour
    severity: warning
    action: Notify #ops-alerts
    context: Bots restarting more often than normal

  # High command latency
  - name: High Command Latency
    condition: command_latency > 500ms average over 5 minutes
    severity: warning
    action: Notify #ops-alerts
    context: Slide commands responding slowly

  # Memory leak suspected
  - name: Potential Memory Leak
    condition: memory_increase > 100MB over 30 minutes with constant bot count
    severity: warning
    action: Notify #ops-alerts, schedule bot restart
    context: Memory increasing without bot count increase
```

**Info Alerts** (Log Only)

```yaml
alerts:
  # Bot spawned
  - name: Bot Spawned
    condition: log contains "Bot spawned"
    severity: info
    action: Increment spawned_total metric

  # Bot terminated normally
  - name: Bot Terminated
    condition: log contains "Bot process exited (code: 0)"
    severity: info
    action: Increment terminated_total metric

  # Deck validation failed
  - name: Deck Validation Failed
    condition: log contains "Deck URL validation failed"
    severity: info
    action: Log to metrics dashboard
    context: Bot fell back to test deck

  # Max concurrent bots reached
  - name: Max Concurrent Bots Reached
    condition: active_bot_count == MAX_CONCURRENT_BOTS
    severity: info
    action: Log to metrics dashboard
    context: Operating at capacity
```

---

### Alert Channel Configuration

**Slack Integration:**

```bash
# Example Slack webhook payload
curl -X POST https://hooks.slack.com/services/YOUR/WEBHOOK/URL \
  -H 'Content-Type: application/json' \
  -d '{
    "text": "⚠️ ALERT: High Memory Usage",
    "attachments": [
      {
        "color": "warning",
        "fields": [
          {
            "title": "Bot ID",
            "value": "conv-123",
            "short": true
          },
          {
            "title": "Memory",
            "value": "485 MB",
            "short": true
          },
          {
            "title": "Threshold",
            "value": "450 MB",
            "short": true
          },
          {
            "title": "Action",
            "value": "Monitor or restart bot",
            "short": true
          }
        ]
      }
    ]
  }'
```

**Email Integration:**

```bash
# Example email alert (using sendmail or SMTP)
cat <<EOF | mail -s "CRITICAL: Bot Spawn Failure Rate High" oncall@yourcompany.com
Alert: Bot Spawn Failure Rate High
Time: $(date)
Service: slide-system
Environment: production

Details:
- Spawn Success Rate: 85% (threshold: 90%)
- Period: Last 10 minutes
- Active Bots: 2
- Failed Spawns: 3

Recommended Actions:
1. Check Railway logs: railway logs --service slide-system --tail
2. Check for spawn errors: railway logs | grep "Failed to spawn"
3. Verify environment variables are set
4. Check Daily.co API status: https://status.daily.co

Runbook: /apps/slide-system/bots/screenshare-bot/RUNBOOK.md
EOF
```

**PagerDuty Integration:**

```bash
# Example PagerDuty event
curl -X POST https://events.pagerduty.com/v2/enqueue \
  -H 'Content-Type: application/json' \
  -d '{
    "routing_key": "YOUR_INTEGRATION_KEY",
    "event_action": "trigger",
    "payload": {
      "summary": "Service Down: slide-system",
      "severity": "critical",
      "source": "Railway Monitoring",
      "custom_details": {
        "service": "slide-system",
        "environment": "production",
        "last_log_entry": "5 minutes ago",
        "expected_state": "RUNNING",
        "actual_state": "UNKNOWN"
      }
    }
  }'
```

---

## Log Analysis

### Structured Logging Format

The bot uses structured logging for easy parsing and analysis.

**Log Entry Format:**

```
[TIMESTAMP] LEVEL: Component - Message [key=value, ...]

Example:
[2025-10-12 14:30:45] INFO: BotManager - Bot spawned for conv-123 (PID: 12345)
[2025-10-12 14:30:50] INFO: Bot conv-123 - Performance - Memory: 285.2MB, CPU: 22.1%, FPS: 10.0
[2025-10-12 14:35:45] INFO: Bot conv-123 - Bot process exited for conv-123 (code: 0)
```

---

### Searching Logs in Railway

**Via Railway Dashboard:**

1. Navigate to Logs tab
2. Use search box with filters:
   - `ERROR` - All errors
   - `Bot spawned` - Bot creation events
   - `Performance -` - Performance metrics
   - `exit code` - Bot terminations

**Via Railway CLI:**

```bash
# Real-time log streaming
railway logs --service slide-system --tail

# Search for specific patterns
railway logs --service slide-system | grep "ERROR"

# Search with context (5 lines before/after)
railway logs --service slide-system | grep -B 5 -A 5 "Bot crashed"

# Filter by time range (last hour)
railway logs --service slide-system --since 1h

# Export logs to file
railway logs --service slide-system --since 24h > logs_$(date +%Y%m%d).txt
```

---

### Key Log Patterns

**Bot Lifecycle Events:**

```bash
# Bot spawned successfully
railway logs | grep "Bot spawned for"
# Output: Bot spawned for conv-123 (PID: 12345)

# Bot joined Daily room
railway logs | grep "Successfully joined Daily.co room"

# Bot started streaming
railway logs | grep "Frames:" | head -1
# Output: Frames: 10, Actual FPS: 10.01

# Bot terminated normally
railway logs | grep "Bot process exited.*code: 0"

# Bot crashed
railway logs | grep "Bot process exited" | grep -v "code: 0"
```

**Error Patterns:**

```bash
# Spawn failures
railway logs | grep "Failed to spawn bot"

# Daily.co connection failures
railway logs | grep "Failed to join room"

# Supabase connection errors
railway logs | grep "Supabase.*error"

# Playwright browser errors
railway logs | grep "Browser.*error"

# Memory errors
railway logs | grep "MemoryError\|OOM"

# Python exceptions
railway logs | grep "Traceback" -A 10
```

**Performance Patterns:**

```bash
# High memory usage
railway logs | grep "Memory:" | awk '{if ($6 > 450) print}'

# Low frame rate
railway logs | grep "Actual FPS:" | awk '{if ($6 < 9.0) print}'

# High CPU usage
railway logs | grep "CPU:" | awk '{if ($8 > 35) print}'

# Slow frame capture
railway logs | grep "Frame Capture:" | awk '{if ($11 > 50) print}'
```

---

### Log Aggregation Queries

**Daily Summary:**

```bash
#!/bin/bash
# daily_summary.sh - Generate daily log summary

echo "=== Daily Bot Summary for $(date +%Y-%m-%d) ==="
echo ""

LOGS=$(railway logs --service slide-system --since 24h)

SPAWNED=$(echo "$LOGS" | grep -c "Bot spawned")
TERMINATED=$(echo "$LOGS" | grep "Bot process exited.*code: 0" | wc -l)
CRASHED=$(echo "$LOGS" | grep "Bot process exited" | grep -cv "code: 0")
ERRORS=$(echo "$LOGS" | grep -c "ERROR")

echo "Bots Spawned: $SPAWNED"
echo "Bots Terminated (normal): $TERMINATED"
echo "Bots Crashed: $CRASHED"
echo "Error Count: $ERRORS"
echo ""

AVG_MEMORY=$(echo "$LOGS" | grep "Memory:" | awk '{sum+=$6; count++} END {printf "%.1f MB\n", sum/count}')
AVG_CPU=$(echo "$LOGS" | grep "CPU:" | awk '{sum+=$8; count++} END {printf "%.1f%%\n", sum/count}')
AVG_FPS=$(echo "$LOGS" | grep "Actual FPS:" | awk '{sum+=$6; count++} END {printf "%.2f\n", sum/count}')

echo "Average Memory: $AVG_MEMORY"
echo "Average CPU: $AVG_CPU"
echo "Average FPS: $AVG_FPS"
```

---

## Performance Tracking

### Baseline Metrics

Establish baseline performance from load testing (Task 118):

**Load Test Results (Reference):**

```yaml
baseline_metrics:
  single_bot:
    memory: 280-320 MB
    cpu: 20-28%
    fps: 9.9-10.1
    frame_capture_time: 25-35ms

  three_bots:
    total_memory: 900-1100 MB
    total_cpu: 60-90%
    fps_per_bot: 9.8-10.2
    frame_capture_time: 30-45ms

  five_bots:
    total_memory: 1500-1900 MB
    total_cpu: 100-150%
    fps_per_bot: 9.5-10.5
    frame_capture_time: 35-50ms
```

**Use baselines to detect performance degradation over time.**

---

### Performance Trend Analysis

**Weekly Performance Report:**

```bash
#!/bin/bash
# weekly_performance_report.sh

echo "=== Weekly Performance Report ==="
echo "Period: $(date -d '7 days ago' +%Y-%m-%d) to $(date +%Y-%m-%d)"
echo ""

# Collect logs for past week
LOGS=$(railway logs --service slide-system --since 7d)

# Calculate averages per day
for i in {0..6}; do
  DATE=$(date -d "$i days ago" +%Y-%m-%d)
  DAY_LOGS=$(echo "$LOGS" | grep "$DATE")

  AVG_MEM=$(echo "$DAY_LOGS" | grep "Memory:" | awk '{sum+=$6; c++} END {printf "%.1f", sum/c}')
  AVG_CPU=$(echo "$DAY_LOGS" | grep "CPU:" | awk '{sum+=$8; c++} END {printf "%.1f", sum/c}')
  AVG_FPS=$(echo "$DAY_LOGS" | grep "Actual FPS:" | awk '{sum+=$6; c++} END {printf "%.2f", sum/c}')

  echo "$DATE: Memory=${AVG_MEM}MB, CPU=${AVG_CPU}%, FPS=${AVG_FPS}"
done

echo ""
echo "Trend Analysis:"
# Compare first 3 days vs last 3 days
# Flag if average increased >10%
```

---

### Performance Degradation Detection

**Automated Detection Script:**

```bash
#!/bin/bash
# detect_degradation.sh - Alert if performance degrades from baseline

# Load baseline from load test results
BASELINE_MEMORY=320  # MB per bot
BASELINE_CPU=28      # % per bot
BASELINE_FPS=10.0

# Get current averages (last hour)
CURRENT_MEMORY=$(railway logs --service slide-system --since 1h | \
  grep "Memory:" | awk '{sum+=$6; c++} END {print sum/c}')

CURRENT_CPU=$(railway logs --service slide-system --since 1h | \
  grep "CPU:" | awk '{sum+=$8; c++} END {print sum/c}')

CURRENT_FPS=$(railway logs --service slide-system --since 1h | \
  grep "Actual FPS:" | awk '{sum+=$6; c++} END {print sum/c}')

# Calculate degradation percentages
MEMORY_DEGRADATION=$(echo "scale=2; ($CURRENT_MEMORY - $BASELINE_MEMORY) / $BASELINE_MEMORY * 100" | bc)
CPU_DEGRADATION=$(echo "scale=2; ($CURRENT_CPU - $BASELINE_CPU) / $BASELINE_CPU * 100" | bc)
FPS_DEGRADATION=$(echo "scale=2; ($BASELINE_FPS - $CURRENT_FPS) / $BASELINE_FPS * 100" | bc)

# Alert if any metric degraded >15%
if (( $(echo "$MEMORY_DEGRADATION > 15" | bc -l) )); then
  echo "ALERT: Memory usage increased by ${MEMORY_DEGRADATION}%"
fi

if (( $(echo "$CPU_DEGRADATION > 15" | bc -l) )); then
  echo "ALERT: CPU usage increased by ${CPU_DEGRADATION}%"
fi

if (( $(echo "$FPS_DEGRADATION > 5" | bc -l) )); then
  echo "ALERT: FPS decreased by ${FPS_DEGRADATION}%"
fi
```

---

### Capacity Planning

**Usage Trend Tracking:**

```bash
# Track bot spawns per day to predict capacity needs
railway logs --service slide-system --since 30d | \
  grep "Bot spawned" | \
  awk '{print $1}' | \
  uniq -c

# Example output:
#  12 2025-10-01  # 12 bots spawned
#  18 2025-10-02  # 18 bots spawned
#  15 2025-10-03
#  ...

# Calculate growth rate
# If spawn rate increasing >20% weekly, consider scaling resources
```

**Resource Capacity Calculator:**

```bash
#!/bin/bash
# capacity_calculator.sh

# Current limits
MAX_BOTS=5
MEMORY_PER_BOT=350  # MB
CPU_PER_BOT=25      # %

# Railway limits (adjust to your plan)
RAILWAY_MEMORY_LIMIT=8192  # MB (8GB)
RAILWAY_CPU_LIMIT=2000     # % (20 cores)

# Calculate maximum capacity
MAX_BY_MEMORY=$(echo "$RAILWAY_MEMORY_LIMIT / $MEMORY_PER_BOT" | bc)
MAX_BY_CPU=$(echo "$RAILWAY_CPU_LIMIT / $CPU_PER_BOT" | bc)

echo "Capacity Analysis:"
echo "Current Limit: $MAX_BOTS concurrent bots"
echo "Max by Memory: $MAX_BY_MEMORY bots"
echo "Max by CPU: $MAX_BY_CPU bots"
echo ""

if [ $MAX_BY_MEMORY -lt $MAX_BOTS ] || [ $MAX_BY_CPU -lt $MAX_BOTS ]; then
  echo "⚠️ WARNING: Current limit exceeds resource capacity!"
else
  echo "✅ Current limit is within resource capacity"
fi
```

---

## Dashboards

### Custom Monitoring Dashboard

Create a simple web dashboard to visualize metrics.

**Dashboard Script (HTML + JavaScript):**

```html
<!DOCTYPE html>
<html>
<head>
  <title>Screenshare Bot Monitoring</title>
  <meta http-equiv="refresh" content="30"> <!-- Auto-refresh every 30s -->
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .metric { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }
    .metric h3 { margin: 0 0 10px 0; }
    .status-good { background-color: #d4edda; }
    .status-warning { background-color: #fff3cd; }
    .status-critical { background-color: #f8d7da; }
  </style>
</head>
<body>
  <h1>Screenshare Bot Monitoring Dashboard</h1>

  <div id="metrics"></div>

  <script>
    async function fetchMetrics() {
      // Fetch from Railway API endpoint
      const response = await fetch('https://YOUR_SERVICE.railway.app/api/tavus/bot/status');
      const data = await response.json();

      // Render metrics
      const container = document.getElementById('metrics');
      container.innerHTML = `
        <div class="metric ${data.activeCount > 5 ? 'status-critical' : 'status-good'}">
          <h3>Active Bots</h3>
          <p style="font-size: 2em;">${data.activeCount} / 5</p>
        </div>

        ${data.bots.map(bot => `
          <div class="metric ${bot.memory > 450 ? 'status-warning' : 'status-good'}">
            <h3>Bot: ${bot.conversationId}</h3>
            <p>Memory: ${bot.memory} MB</p>
            <p>CPU: ${bot.cpu}%</p>
            <p>FPS: ${bot.fps}</p>
          </div>
        `).join('')}
      `;
    }

    // Fetch on load
    fetchMetrics();

    // Refresh every 30 seconds
    setInterval(fetchMetrics, 30000);
  </script>
</body>
</html>
```

---

### Grafana Integration (Optional)

If using Grafana for monitoring:

**Data Source Configuration:**

```yaml
# prometheus.yml - Expose metrics in Prometheus format
# Add to bot.py if implementing /metrics endpoint

GET /api/metrics

Response:
# HELP bots_active_count Number of currently active bots
# TYPE bots_active_count gauge
bots_active_count 3

# HELP bots_spawned_total Total bots spawned since service start
# TYPE bots_spawned_total counter
bots_spawned_total 127

# HELP bots_crashed_total Total bots that crashed
# TYPE bots_crashed_total counter
bots_crashed_total 2

# HELP bot_memory_bytes Memory usage per bot
# TYPE bot_memory_bytes gauge
bot_memory_bytes{conversation_id="conv-123"} 299827200

# HELP bot_cpu_percent CPU usage per bot
# TYPE bot_cpu_percent gauge
bot_cpu_percent{conversation_id="conv-123"} 22.5

# HELP bot_fps Frames per second per bot
# TYPE bot_fps gauge
bot_fps{conversation_id="conv-123"} 10.02
```

**Grafana Dashboard Panels:**

1. Active Bot Count (Gauge)
2. Memory Usage Per Bot (Graph)
3. CPU Usage (Stacked Graph)
4. Frame Rate (Graph)
5. Spawn Success Rate (Stat)
6. Crash Rate (Stat)
7. Recent Logs (Logs Panel)

---

## Troubleshooting Metrics

### Metrics Not Appearing in Logs

**Symptoms:** Performance logs not showing up

**Causes:**
- PerformanceMonitor not initialized
- Logging level too high (set to ERROR instead of INFO)
- Bot crashing before metrics logged

**Resolution:**

```bash
# Check logging level
railway vars --service slide-system | grep LOG_LEVEL

# Should be: LOG_LEVEL=INFO

# Set if missing
railway vars --service slide-system set LOG_LEVEL=INFO

# Restart service
railway restart --service slide-system
```

---

### Inconsistent Metric Values

**Symptoms:** Metrics fluctuate wildly or show impossible values

**Causes:**
- Multiple bots logging simultaneously (interleaved logs)
- Metrics calculated incorrectly
- Resource contention

**Resolution:**

```bash
# Verify metrics are per-bot (not aggregated incorrectly)
railway logs --service slide-system | grep "Performance -" | tail -20

# Each bot should have its own conversation_id
# Look for pattern: Bot conv-XXX Performance - ...

# If seeing aggregate metrics, check PerformanceMonitor implementation
```

---

### Alert Fatigue

**Symptoms:** Too many alerts, team ignoring notifications

**Causes:**
- Thresholds set too low
- Alerting on transient issues
- No alert grouping/deduplication

**Resolution:**

1. Review alert thresholds and increase if needed
2. Add time conditions (e.g., "sustained for 5 minutes")
3. Implement alert grouping (send one alert for multiple occurrences)
4. Add alert suppression during deployments
5. Regularly review and tune alerts based on false positive rate

---

## Quick Reference

### Essential Monitoring Commands

```bash
# Check service status
railway status --service slide-system

# View active bots
curl https://YOUR_SERVICE.railway.app/api/tavus/bot/status | jq

# Stream logs in real-time
railway logs --service slide-system --tail

# Check memory usage
railway logs --service slide-system | grep "Memory:" | tail -10

# Check CPU usage
railway logs --service slide-system | grep "CPU:" | tail -10

# Check frame rate
railway logs --service slide-system | grep "Actual FPS:" | tail -10

# Check for errors
railway logs --service slide-system | grep "ERROR" | tail -20

# Check for crashes
railway logs --service slide-system | grep "Bot process exited" | grep -v "code: 0"

# Daily summary
railway logs --service slide-system --since 24h | grep -c "Bot spawned"
```

---

### Monitoring Checklist

**Daily Monitoring (5 minutes):**

```
□ Check Railway dashboard for service health
□ Verify active bot count is expected
□ Review error logs (should be minimal)
□ Check memory usage (should be stable)
□ Confirm no recent crashes
```

**Weekly Review (30 minutes):**

```
□ Generate weekly performance report
□ Review trend analysis (memory, CPU, FPS)
□ Check for performance degradation vs baseline
□ Review alert history and tune thresholds
□ Update capacity planning projections
□ Review any incidents or unusual patterns
```

**Monthly Review (1 hour):**

```
□ Analyze monthly usage trends
□ Review capacity planning
□ Update baseline metrics if needed
□ Review and update alert configurations
□ Document any new monitoring patterns discovered
□ Plan monitoring improvements
```

---

### Support Resources

```
Railway Dashboard: https://railway.app/project/YOUR_PROJECT
Railway Status Page: https://railway.app/status
Daily.co Status: https://status.daily.co
Supabase Status: https://status.supabase.com

Documentation:
- Runbook: RUNBOOK.md
- Deployment Guide: DEPLOYMENT.md
- Monitoring Guide: MONITORING.md (this document)

Team Channels:
- #ops-alerts (critical issues)
- #engineering (general discussion)
- #on-call (incident response)

On-Call Rotation: [Your rotation schedule]
Escalation Path: [Your escalation policy]
```

---

**Document Version:** 1.0
**Last Updated:** 2025-10-12
**Maintained By:** DevOps Team
