# Production Validation Procedures for Screenshare Bot

**Purpose**: End-to-end validation tests to verify the screenshare bot functions correctly in production.

**When to Use**: After every deployment, before accepting production traffic, during gradual rollout phases.

---

## Table of Contents

1. [Overview](#overview)
2. [Test Environment Setup](#test-environment-setup)
3. [End-to-End Test Suite](#end-to-end-test-suite)
4. [Validation Criteria](#validation-criteria)
5. [Test Execution Workflow](#test-execution-workflow)
6. [Troubleshooting Test Failures](#troubleshooting-test-failures)

---

## Overview

### Validation Approach

This document provides comprehensive end-to-end tests to validate the screenshare bot in production:

1. **Functional Tests**: Verify core functionality works
2. **Performance Tests**: Verify bot meets performance targets
3. **Reliability Tests**: Verify bot handles edge cases gracefully
4. **Integration Tests**: Verify bot integrates with all dependencies

### Test Categories

| Category | Tests | Duration | Criticality |
|----------|-------|----------|-------------|
| **Smoke Tests** | 5 tests | 5-10 min | Critical - Run after every deployment |
| **Functional Tests** | 7 tests | 15-20 min | Critical - Run before accepting traffic |
| **Performance Tests** | 4 tests | 10-15 min | Important - Run during rollout |
| **Reliability Tests** | 5 tests | 20-30 min | Important - Run in Phase 3 |
| **Integration Tests** | 3 tests | 10-15 min | Important - Run before go-live |

**Total Comprehensive Test Time**: 60-90 minutes

---

## Test Environment Setup

### Prerequisites

Before running tests, ensure:

1. **Railway Deployment Complete**
   - Service status: RUNNING
   - Build successful
   - No errors in deployment logs

2. **Environment Variables Set**
   - All 5 required variables configured
   - Variables verified in Railway dashboard

3. **Test Tools Available**
   - curl (for API calls)
   - jq (for JSON parsing)
   - Python 3.9+ (for test scripts)
   - Railway CLI (for log access)

### Setup Steps

```bash
# 1. Set API URL environment variable
export API_URL="https://slide-system-production-5813.up.railway.app"

# Verify API is accessible
curl -s "$API_URL/api/tavus/bot/status"
# Expected: {"activeCount": 0, "bots": []}

# 2. Navigate to bot directory
cd /Users/lars/mycode/buzztrail/epic-pipecat-based-screenshare-bot/apps/slide-system/bots/screenshare-bot

# 3. Create test output directory
mkdir -p test-results
cd test-results

# 4. Create test log file
echo "Production Validation - $(date)" > validation_log.txt
```

---

## End-to-End Test Suite

### Smoke Tests (Critical - 5-10 min)

Run immediately after deployment to verify basic functionality.

---

#### Test 1: API Health Check

**Objective**: Verify API is responsive

**Test Steps**:
```bash
echo "Test 1: API Health Check" | tee -a validation_log.txt

# Call bot status endpoint
RESPONSE=$(curl -s -w "\n%{http_code}" "$API_URL/api/tavus/bot/status")
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | head -1)

echo "HTTP Code: $HTTP_CODE" | tee -a validation_log.txt
echo "Response: $BODY" | tee -a validation_log.txt
```

**Expected Results**:
- HTTP Status Code: `200`
- Response contains: `{"activeCount": 0, "bots": []}`

**Pass Criteria**:
- ✅ HTTP 200 received
- ✅ JSON response parseable
- ✅ activeCount is 0 (no bots running yet)

**Failure Actions**:
```bash
# If test fails
if [ "$HTTP_CODE" != "200" ]; then
  echo "❌ FAIL: API not responding correctly" | tee -a validation_log.txt
  echo "Check Railway logs: railway logs --service slide-system --tail"
  exit 1
fi
```

---

#### Test 2: Bot Spawn Test

**Objective**: Verify bot can be spawned successfully

**Test Steps**:
```bash
echo "Test 2: Bot Spawn Test" | tee -a validation_log.txt

# Create test Daily.co room
python ../scripts/create_test_room.py > room_info.txt
TEST_ROOM=$(cat room_info.txt | grep "Room URL:" | awk '{print $3}')

echo "Test Room: $TEST_ROOM" | tee -a validation_log.txt

# Spawn bot
SPAWN_RESPONSE=$(curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{
    \"conversation_id\": \"smoke-test-spawn-$(date +%s)\",
    \"room_url\": \"$TEST_ROOM\"
  }")

echo "Spawn Response: $SPAWN_RESPONSE" | tee -a validation_log.txt

# Wait for spawn to complete
sleep 5

# Check bot status
BOT_STATUS=$(curl -s "$API_URL/api/tavus/bot/status")
ACTIVE_COUNT=$(echo "$BOT_STATUS" | jq -r '.activeCount')

echo "Active Bots: $ACTIVE_COUNT" | tee -a validation_log.txt
```

**Expected Results**:
- Spawn response: `{"success": true, "message": "Bot spawned for conversation smoke-test-spawn-..."}`
- Active bot count: `1`
- Railway logs show: "Bot spawned for smoke-test-spawn-... (PID: xxxxx)"

**Pass Criteria**:
- ✅ Spawn API returns success
- ✅ Active bot count increased to 1
- ✅ Bot PID logged in Railway

**Failure Actions**:
```bash
if [ "$ACTIVE_COUNT" != "1" ]; then
  echo "❌ FAIL: Bot did not spawn" | tee -a validation_log.txt
  echo "Check logs: railway logs --service slide-system | grep spawn"
  exit 1
fi
```

---

#### Test 3: Daily.co Room Join Test

**Objective**: Verify bot joins Daily.co room successfully

**Test Steps**:
```bash
echo "Test 3: Daily.co Room Join Test" | tee -a validation_log.txt

# Wait for bot to join room (may take up to 10 seconds)
sleep 10

# Check Railway logs for join confirmation
railway logs --service slide-system --since 1m | grep "Successfully joined Daily.co room" > join_log.txt

if [ -s join_log.txt ]; then
  echo "✅ Bot joined Daily.co room successfully" | tee -a validation_log.txt
  cat join_log.txt | tee -a validation_log.txt
else
  echo "⏳ Waiting for join (retry)..." | tee -a validation_log.txt
  sleep 10
  railway logs --service slide-system --since 2m | grep "Successfully joined Daily.co room" > join_log.txt
fi
```

**Expected Results**:
- Log contains: "Successfully joined Daily.co room: [room_url]"
- No "Failed to join" errors in logs

**Pass Criteria**:
- ✅ Join success message in logs within 20 seconds
- ✅ No join failure errors

**Failure Actions**:
```bash
if [ ! -s join_log.txt ]; then
  echo "❌ FAIL: Bot did not join Daily.co room" | tee -a validation_log.txt
  echo "Check logs: railway logs --service slide-system | grep 'Daily.co'"
  exit 1
fi
```

---

#### Test 4: Screenshot Streaming Test

**Objective**: Verify bot is streaming screenshots at target frame rate

**Test Steps**:
```bash
echo "Test 4: Screenshot Streaming Test" | tee -a validation_log.txt

# Wait for streaming to start
sleep 15

# Check logs for frame streaming
railway logs --service slide-system --since 1m | grep "Frames:" > streaming_log.txt

if [ -s streaming_log.txt ]; then
  echo "✅ Bot is streaming frames" | tee -a validation_log.txt

  # Extract FPS
  LATEST_FPS=$(cat streaming_log.txt | tail -1 | grep -oP 'Actual FPS: \K[0-9.]+')
  echo "Latest FPS: $LATEST_FPS" | tee -a validation_log.txt

  # Check FPS is in range 9.5-10.5
  if (( $(echo "$LATEST_FPS >= 9.5 && $LATEST_FPS <= 10.5" | bc -l) )); then
    echo "✅ FPS within target range (9.5-10.5)" | tee -a validation_log.txt
  else
    echo "⚠️ WARNING: FPS out of range: $LATEST_FPS" | tee -a validation_log.txt
  fi
fi
```

**Expected Results**:
- Logs show: "Frames: [count], Actual FPS: 10.0, Target FPS: 10"
- FPS between 9.5 and 10.5

**Pass Criteria**:
- ✅ Frame streaming logs present
- ✅ FPS between 9.5 and 10.5
- ✅ Frame count increasing

**Failure Actions**:
```bash
if [ ! -s streaming_log.txt ]; then
  echo "❌ FAIL: Bot not streaming frames" | tee -a validation_log.txt
  echo "Check logs: railway logs --service slide-system | grep 'Frame'"
  exit 1
fi
```

---

#### Test 5: Bot Termination Test

**Objective**: Verify bot can be terminated gracefully

**Test Steps**:
```bash
echo "Test 5: Bot Termination Test" | tee -a validation_log.txt

# Get conversation ID of test bot
CONV_ID=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.bots[0].conversationId')
echo "Terminating bot: $CONV_ID" | tee -a validation_log.txt

# Kill bot
KILL_RESPONSE=$(curl -s -X POST "$API_URL/api/tavus/bot/kill" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}")

echo "Kill Response: $KILL_RESPONSE" | tee -a validation_log.txt

# Wait for termination
sleep 5

# Check bot count is back to 0
FINAL_COUNT=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
echo "Final Active Count: $FINAL_COUNT" | tee -a validation_log.txt

# Check logs for graceful exit
railway logs --service slide-system --since 1m | grep "Bot process exited.*code: 0" > exit_log.txt
```

**Expected Results**:
- Kill response: `{"success": true, "message": "Bot killed"}`
- Active count back to `0`
- Logs show: "Bot process exited for [conversation_id] (code: 0)"

**Pass Criteria**:
- ✅ Kill API returns success
- ✅ Active count returns to 0
- ✅ Bot exited with code 0 (graceful)

**Failure Actions**:
```bash
if [ "$FINAL_COUNT" != "0" ]; then
  echo "❌ FAIL: Bot did not terminate properly" | tee -a validation_log.txt
  echo "Check logs: railway logs --service slide-system | grep 'exit'"
  exit 1
fi
```

---

### Smoke Test Summary

```bash
echo "" | tee -a validation_log.txt
echo "=== Smoke Test Summary ===" | tee -a validation_log.txt
echo "Test 1 - API Health: ✅ PASS" | tee -a validation_log.txt
echo "Test 2 - Bot Spawn: ✅ PASS" | tee -a validation_log.txt
echo "Test 3 - Room Join: ✅ PASS" | tee -a validation_log.txt
echo "Test 4 - Streaming: ✅ PASS" | tee -a validation_log.txt
echo "Test 5 - Termination: ✅ PASS" | tee -a validation_log.txt
echo "" | tee -a validation_log.txt
echo "✅ ALL SMOKE TESTS PASSED - Proceed to functional tests" | tee -a validation_log.txt
```

**If any smoke test fails, STOP and fix the issue before proceeding.**

---

### Functional Tests (Critical - 15-20 min)

---

#### Test 6: Slide Navigation - Next Slide

**Objective**: Verify bot responds to "next slide" command

**Prerequisites**: Supabase realtime channel configured

**Test Steps**:
```bash
echo "Test 6: Slide Navigation - Next Slide" | tee -a validation_log.txt

# Spawn a new bot for navigation testing
CONV_ID="func-test-nav-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{
    \"conversation_id\": \"$CONV_ID\",
    \"room_url\": \"$TEST_ROOM\"
  }"

# Wait for bot to start streaming
sleep 20

# Send "next slide" command via Supabase
# (Assuming we have a script to send Supabase realtime messages)
python ../scripts/send_slide_command.py --conversation_id "$CONV_ID" --command "next"

# Wait for command processing
sleep 3

# Check logs for slide navigation
railway logs --service slide-system --since 1m | grep -i "slide.*next\|navigat.*next" > nav_log.txt

# Cleanup: Kill bot
curl -s -X POST "$API_URL/api/tavus/bot/kill" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Expected Results**:
- Logs show slide navigation command received
- Bot navigates to next slide
- No errors in command processing

**Pass Criteria**:
- ✅ Command received and processed
- ✅ Slide navigation successful
- ✅ No command errors

---

#### Test 7: Slide Navigation - Previous Slide

**Objective**: Verify bot responds to "previous slide" command

**Test Steps**: (Similar to Test 6, but with "previous" command)

```bash
echo "Test 7: Slide Navigation - Previous Slide" | tee -a validation_log.txt

# Spawn bot
CONV_ID="func-test-prev-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

sleep 20

# Send "previous slide" command
python ../scripts/send_slide_command.py --conversation_id "$CONV_ID" --command "previous"
sleep 3

# Check logs
railway logs --service slide-system --since 1m | grep -i "slide.*prev\|navigat.*prev" > nav_prev_log.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Pass Criteria**: Same as Test 6

---

#### Test 8: Slide Navigation - Go To Specific Slide

**Objective**: Verify bot responds to "go to slide N" command

**Test Steps**:
```bash
echo "Test 8: Slide Navigation - Go To Slide" | tee -a validation_log.txt

# Spawn bot
CONV_ID="func-test-goto-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

sleep 20

# Send "go to slide 5" command
python ../scripts/send_slide_command.py --conversation_id "$CONV_ID" --command "goto" --slide_number 5
sleep 3

# Check logs
railway logs --service slide-system --since 1m | grep -i "slide.*5\|goto.*5" > nav_goto_log.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Pass Criteria**: Bot navigates to slide 5 successfully

---

#### Test 9: Concurrent Session Test

**Objective**: Verify multiple bots can run concurrently without interference

**Test Steps**:
```bash
echo "Test 9: Concurrent Session Test" | tee -a validation_log.txt

# Spawn 2 bots concurrently
CONV_ID_1="concurrent-test-1-$(date +%s)"
CONV_ID_2="concurrent-test-2-$(date +%s)"

ROOM_1=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')
ROOM_2=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

# Spawn bot 1
curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID_1\", \"room_url\": \"$ROOM_1\"}"

sleep 2

# Spawn bot 2
curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID_2\", \"room_url\": \"$ROOM_2\"}"

# Wait for both to start streaming
sleep 20

# Check both bots are active
ACTIVE_COUNT=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
echo "Active Bots: $ACTIVE_COUNT (Expected: 2)" | tee -a validation_log.txt

# Check both are streaming
railway logs --service slide-system --since 1m | grep "Frames:" | tail -2 > concurrent_streaming.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID_1\"}"
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID_2\"}"
```

**Expected Results**:
- Both bots spawn successfully
- Active count shows 2
- Both bots streaming independently
- No interference between bots

**Pass Criteria**:
- ✅ Both bots active simultaneously
- ✅ Both streaming at target FPS
- ✅ No resource contention errors

---

#### Test 10: Bot Timeout Test

**Objective**: Verify bot auto-terminates after timeout period

**Test Steps**:
```bash
echo "Test 10: Bot Timeout Test" | tee -a validation_log.txt

# Note: This test requires BOT_TIMEOUT_MINUTES to be set low for testing
# For production validation, verify the timeout is set correctly but don't wait the full duration

# Check timeout configuration
TIMEOUT=$(railway vars --service slide-system | grep BOT_TIMEOUT_MINUTES | awk -F= '{print $2}')
echo "Configured Timeout: $TIMEOUT minutes" | tee -a validation_log.txt

# For validation, just verify timeout is configured
if [ -n "$TIMEOUT" ]; then
  echo "✅ Timeout configured: $TIMEOUT minutes" | tee -a validation_log.txt
else
  echo "⚠️ WARNING: BOT_TIMEOUT_MINUTES not set (using default: 30)" | tee -a validation_log.txt
fi

# Optional: If timeout is set to a short duration for testing (e.g., 1-2 minutes), test it
# Otherwise, mark as SKIPPED for production validation
```

**Pass Criteria**:
- ✅ Timeout configuration present
- ✅ (Optional) Bot terminates after timeout if tested

---

#### Test 11: Deck URL Validation and Fallback

**Objective**: Verify bot handles invalid deck URLs gracefully

**Test Steps**:
```bash
echo "Test 11: Deck URL Validation and Fallback" | tee -a validation_log.txt

# Spawn bot with invalid deck URL
CONV_ID="fallback-test-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

# Note: This assumes bot manager can accept deck_url parameter
# Spawn with invalid deck URL (should fall back to test deck)
curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{
    \"conversation_id\": \"$CONV_ID\",
    \"room_url\": \"$TEST_ROOM\",
    \"deck_url\": \"https://invalid-deck-url.example.com/nonexistent\"
  }"

sleep 10

# Check logs for fallback message
railway logs --service slide-system --since 1m | grep -i "fallback\|validation failed" > fallback_log.txt

if [ -s fallback_log.txt ]; then
  echo "✅ Deck validation and fallback working" | tee -a validation_log.txt
  cat fallback_log.txt | tee -a validation_log.txt
fi

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Expected Results**:
- Logs show: "Deck URL validation failed"
- Logs show: "Using fallback deck URL"
- Bot continues with test deck

**Pass Criteria**:
- ✅ Invalid deck detected
- ✅ Fallback to test deck successful
- ✅ Bot continues to function

---

#### Test 12: Real Tavus Conversation Integration

**Objective**: Verify bot works in real Tavus conversation scenario

**Prerequisites**: Tavus account with active conversation

**Test Steps**:
```bash
echo "Test 12: Real Tavus Conversation Integration" | tee -a validation_log.txt

# This test requires a real Tavus conversation
# For validation, verify integration points:

# 1. Check Tavus API connectivity
echo "Checking Tavus integration..." | tee -a validation_log.txt

# 2. Verify bot can be spawned via Tavus webhook/API
# (This would be triggered by Tavus, not directly testable here)

# 3. For validation, confirm integration is configured:
railway vars --service slide-system | grep TAVUS > tavus_config.txt

if [ -s tavus_config.txt ]; then
  echo "✅ Tavus integration configured" | tee -a validation_log.txt
else
  echo "ℹ️ Tavus integration not configured (may not be required)" | tee -a validation_log.txt
fi
```

**Pass Criteria**:
- ✅ Tavus integration configured (if required)
- ✅ Bot can be spawned via Tavus triggers
- ✅ Bot integrates with Tavus conversation flow

**Note**: This test may be SKIPPED if Tavus integration is not yet implemented.

---

### Performance Tests (Important - 10-15 min)

---

#### Test 13: Memory Usage Validation

**Objective**: Verify bot memory usage remains within acceptable limits

**Test Steps**:
```bash
echo "Test 13: Memory Usage Validation" | tee -a validation_log.txt

# Spawn bot for memory testing
CONV_ID="perf-test-memory-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

# Monitor memory for 5 minutes
for i in {1..10}; do
  sleep 30
  MEMORY=$(railway logs --service slide-system | grep "$CONV_ID.*Memory:" | tail -1 | grep -oP 'Memory: \K[0-9.]+')
  echo "Iteration $i - Memory: ${MEMORY} MB" | tee -a validation_log.txt
done

# Calculate average and max memory
AVG_MEMORY=$(railway logs --service slide-system | grep "$CONV_ID.*Memory:" | \
  awk '{sum+=$6; c++} END {print sum/c}')
MAX_MEMORY=$(railway logs --service slide-system | grep "$CONV_ID.*Memory:" | \
  awk '{if ($6 > max) max=$6} END {print max}')

echo "Average Memory: ${AVG_MEMORY} MB" | tee -a validation_log.txt
echo "Peak Memory: ${MAX_MEMORY} MB" | tee -a validation_log.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Expected Results**:
- Average memory: < 350 MB
- Peak memory: < 500 MB
- Memory stable (no continuous increase)

**Pass Criteria**:
- ✅ Average memory < 350 MB
- ✅ Peak memory < 500 MB
- ✅ No memory leak detected

---

#### Test 14: CPU Usage Validation

**Objective**: Verify bot CPU usage remains within acceptable limits

**Test Steps**:
```bash
echo "Test 14: CPU Usage Validation" | tee -a validation_log.txt

# Spawn bot for CPU testing
CONV_ID="perf-test-cpu-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

# Monitor CPU for 5 minutes
sleep 20  # Wait for bot to stabilize

for i in {1..10}; do
  sleep 30
  CPU=$(railway logs --service slide-system | grep "$CONV_ID.*CPU:" | tail -1 | grep -oP 'CPU: \K[0-9.]+')
  echo "Iteration $i - CPU: ${CPU}%" | tee -a validation_log.txt
done

# Calculate average and max CPU
AVG_CPU=$(railway logs --service slide-system | grep "$CONV_ID.*CPU:" | \
  awk '{sum+=$8; c++} END {print sum/c}')
MAX_CPU=$(railway logs --service slide-system | grep "$CONV_ID.*CPU:" | \
  awk '{if ($8 > max) max=$8} END {print max}')

echo "Average CPU: ${AVG_CPU}%" | tee -a validation_log.txt
echo "Peak CPU: ${MAX_CPU}%" | tee -a validation_log.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Expected Results**:
- Average CPU: < 25%
- Peak CPU: < 40%

**Pass Criteria**:
- ✅ Average CPU < 25%
- ✅ Peak CPU < 40%
- ✅ CPU stable during streaming

---

#### Test 15: Frame Rate Stability Test

**Objective**: Verify bot maintains consistent frame rate over time

**Test Steps**:
```bash
echo "Test 15: Frame Rate Stability Test" | tee -a validation_log.txt

# Spawn bot for FPS testing
CONV_ID="perf-test-fps-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

# Monitor FPS for 5 minutes
sleep 20

for i in {1..10}; do
  sleep 30
  FPS=$(railway logs --service slide-system | grep "$CONV_ID.*Actual FPS:" | tail -1 | grep -oP 'Actual FPS: \K[0-9.]+')
  echo "Iteration $i - FPS: $FPS" | tee -a validation_log.txt
done

# Calculate FPS statistics
AVG_FPS=$(railway logs --service slide-system | grep "$CONV_ID.*Actual FPS:" | \
  awk '{sum+=$6; c++} END {print sum/c}')
MIN_FPS=$(railway logs --service slide-system | grep "$CONV_ID.*Actual FPS:" | \
  awk 'NR==1 {min=$6} {if ($6 < min) min=$6} END {print min}')
MAX_FPS=$(railway logs --service slide-system | grep "$CONV_ID.*Actual FPS:" | \
  awk 'NR==1 {max=$6} {if ($6 > max) max=$6} END {print max}')

echo "Average FPS: $AVG_FPS" | tee -a validation_log.txt
echo "Min FPS: $MIN_FPS" | tee -a validation_log.txt
echo "Max FPS: $MAX_FPS" | tee -a validation_log.txt

# Calculate variance
VARIANCE=$(echo "$MAX_FPS - $MIN_FPS" | bc)
echo "FPS Variance: $VARIANCE" | tee -a validation_log.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Expected Results**:
- Average FPS: 9.9-10.1
- Min FPS: > 9.5
- Max FPS: < 10.5
- Variance: < 1.0

**Pass Criteria**:
- ✅ Average FPS 9.9-10.1
- ✅ Min FPS > 9.5
- ✅ FPS variance < 1.0

---

#### Test 16: Command Latency Test

**Objective**: Verify slide navigation commands respond quickly

**Test Steps**:
```bash
echo "Test 16: Command Latency Test" | tee -a validation_log.txt

# Spawn bot for latency testing
CONV_ID="perf-test-latency-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

sleep 20

# Send multiple commands and measure latency
for i in {1..5}; do
  START=$(date +%s%N)
  python ../scripts/send_slide_command.py --conversation_id "$CONV_ID" --command "next"

  # Wait for command to be processed (check logs)
  while ! railway logs --service slide-system --since 5s | grep -q "Command.*next"; do
    sleep 0.1
  done

  END=$(date +%s%N)
  LATENCY=$(echo "scale=2; ($END - $START) / 1000000" | bc)
  echo "Command $i Latency: ${LATENCY} ms" | tee -a validation_log.txt
done

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Expected Results**:
- Command latency: < 500ms

**Pass Criteria**:
- ✅ All commands < 500ms latency
- ✅ Average latency < 300ms

---

### Reliability Tests (Important - 20-30 min)

---

#### Test 17: Bot Crash Recovery Test

**Objective**: Verify system handles bot crashes gracefully

**Test Steps**:
```bash
echo "Test 17: Bot Crash Recovery Test" | tee -a validation_log.txt

# Spawn bot
CONV_ID="reliability-test-crash-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

sleep 10

# Force kill bot process (simulate crash)
# Get PID from logs
PID=$(railway logs --service slide-system | grep "Bot spawned.*$CONV_ID.*PID:" | tail -1 | grep -oP 'PID: \K[0-9]+')
echo "Bot PID: $PID" | tee -a validation_log.txt

# Kill process via Railway shell
railway run --service slide-system "kill -9 $PID"

sleep 5

# Check logs for crash detection
railway logs --service slide-system --since 1m | grep "Bot process exited.*$CONV_ID" > crash_log.txt

if [ -s crash_log.txt ]; then
  echo "✅ Bot crash detected by manager" | tee -a validation_log.txt
  cat crash_log.txt | tee -a validation_log.txt
fi

# Verify bot manager cleaned up
ACTIVE_COUNT=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
echo "Active count after crash: $ACTIVE_COUNT (Expected: 0)" | tee -a validation_log.txt
```

**Expected Results**:
- Bot crash logged
- Bot manager detects exit
- Bot removed from active list
- System remains stable

**Pass Criteria**:
- ✅ Crash detected and logged
- ✅ Bot cleaned up from manager
- ✅ System stable after crash

---

#### Test 18: Network Interruption Recovery

**Objective**: Verify bot handles Daily.co network interruptions

**Test Steps**:
```bash
echo "Test 18: Network Interruption Recovery" | tee -a validation_log.txt

# This test is difficult to automate - verify retry logic exists

# Check logs for retry attempts during previous tests
railway logs --service slide-system --since 1h | grep -i "retry\|attempt" > retry_log.txt

if [ -s retry_log.txt ]; then
  echo "✅ Retry logic present in bot" | tee -a validation_log.txt
  RETRY_COUNT=$(cat retry_log.txt | wc -l)
  echo "Retry attempts observed: $RETRY_COUNT" | tee -a validation_log.txt
else
  echo "ℹ️ No network interruptions observed (expected in stable environment)" | tee -a validation_log.txt
fi
```

**Pass Criteria**:
- ✅ Retry logic implemented (3 attempts as per RUNBOOK.md)
- ✅ Bot recovers from transient network issues

---

#### Test 19: Resource Exhaustion Handling

**Objective**: Verify bot handles resource limits gracefully

**Test Steps**:
```bash
echo "Test 19: Resource Exhaustion Handling" | tee -a validation_log.txt

# Check MAX_CONCURRENT_BOTS enforcement
MAX_BOTS=$(railway vars --service slide-system | grep MAX_CONCURRENT_BOTS | awk -F= '{print $2}')
echo "Max Concurrent Bots: $MAX_BOTS" | tee -a validation_log.txt

# Attempt to spawn bots up to limit
SPAWNED=0
for i in $(seq 1 $((MAX_BOTS + 1))); do
  ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')
  RESPONSE=$(curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
    -H "Content-Type: application/json" \
    -d "{\"conversation_id\": \"limit-test-$i\", \"room_url\": \"$ROOM\"}")

  if echo "$RESPONSE" | grep -q "success.*true"; then
    SPAWNED=$((SPAWNED + 1))
  else
    echo "Bot $i rejected (expected at limit)" | tee -a validation_log.txt
  fi

  sleep 2
done

echo "Bots spawned: $SPAWNED (Max: $MAX_BOTS)" | tee -a validation_log.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill-all"
```

**Expected Results**:
- Bots spawn up to MAX_CONCURRENT_BOTS limit
- Additional spawn requests rejected
- Rejection handled gracefully

**Pass Criteria**:
- ✅ Limit enforced correctly
- ✅ Rejection responses clear and informative

---

#### Test 20: Long-Running Session Test

**Objective**: Verify bot runs stably for extended period

**Test Steps**:
```bash
echo "Test 20: Long-Running Session Test" | tee -a validation_log.txt

# Spawn bot for long-running test
CONV_ID="long-run-test-$(date +%s)"
TEST_ROOM=$(python ../scripts/create_test_room.py | grep "Room URL:" | awk '{print $3}')

curl -s -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\", \"room_url\": \"$TEST_ROOM\"}"

echo "Bot spawned for 30-minute run" | tee -a validation_log.txt
echo "Start time: $(date)" | tee -a validation_log.txt

# Monitor for 30 minutes (or shorter for validation)
# For production validation, run for at least 15 minutes
DURATION=900  # 15 minutes in seconds

START_TIME=$(date +%s)
while [ $(($(date +%s) - START_TIME)) -lt $DURATION ]; do
  # Check bot status every 5 minutes
  sleep 300

  ACTIVE=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
  MEMORY=$(railway logs --service slide-system | grep "$CONV_ID.*Memory:" | tail -1 | grep -oP 'Memory: \K[0-9.]+')
  FPS=$(railway logs --service slide-system | grep "$CONV_ID.*Actual FPS:" | tail -1 | grep -oP 'Actual FPS: \K[0-9.]+')

  echo "Status check - Active: $ACTIVE, Memory: ${MEMORY}MB, FPS: $FPS" | tee -a validation_log.txt
done

echo "End time: $(date)" | tee -a validation_log.txt

# Check for stability
CRASHES=$(railway logs --service slide-system --since ${DURATION}s | grep "$CONV_ID.*exited" | grep -cv "code: 0")
echo "Crashes during run: $CRASHES" | tee -a validation_log.txt

# Cleanup
curl -s -X POST "$API_URL/api/tavus/bot/kill" -H "Content-Type: application/json" \
  -d "{\"conversation_id\": \"$CONV_ID\"}"
```

**Expected Results**:
- Bot runs for full duration without crash
- Memory stable throughout
- FPS stable throughout

**Pass Criteria**:
- ✅ Zero crashes during run
- ✅ Memory remains stable
- ✅ FPS remains in target range

---

#### Test 21: Supabase Connection Resilience

**Objective**: Verify bot handles Supabase connection issues

**Test Steps**:
```bash
echo "Test 21: Supabase Connection Resilience" | tee -a validation_log.txt

# This test verifies bot behavior when Supabase is unavailable
# For validation, check error handling exists

# Spawn bot with potentially unreachable Supabase (using invalid key temporarily)
# NOTE: This would require temporarily setting invalid SUPABASE_KEY
# For validation purposes, verify retry logic in logs

railway logs --service slide-system --since 1h | grep -i "supabase.*error\|supabase.*retry" > supabase_error_log.txt

if [ -s supabase_error_log.txt ]; then
  echo "✅ Supabase error handling observed" | tee -a validation_log.txt
  cat supabase_error_log.txt | tee -a validation_log.txt
else
  echo "ℹ️ No Supabase errors observed (expected in stable environment)" | tee -a validation_log.txt
fi
```

**Pass Criteria**:
- ✅ Supabase errors handled gracefully
- ✅ Bot continues to function (streaming) even if commands unavailable

---

## Validation Criteria

### Overall Validation Criteria

**Critical (Must Pass)**:
- All Smoke Tests (Tests 1-5): 100% pass rate
- Core Functional Tests (Tests 6-9): 100% pass rate
- Performance within limits (Tests 13-16): 100% pass rate

**Important (Should Pass)**:
- Reliability Tests (Tests 17-21): ≥80% pass rate
- Integration Tests: ≥80% pass rate

**Acceptance Criteria**:
- ✅ All critical tests pass
- ✅ At least 80% of important tests pass
- ✅ No blocking issues identified
- ✅ Performance meets or exceeds targets

---

## Test Execution Workflow

### Pre-Validation

1. Complete PRE-DEPLOYMENT-CHECKLIST.md
2. Ensure Railway deployment successful
3. Prepare test environment (scripts, tools)

### Validation Sequence

```
1. Smoke Tests (5-10 min)
   ├─ PASS → Continue to Functional Tests
   └─ FAIL → STOP, fix issues, redeploy

2. Functional Tests (15-20 min)
   ├─ PASS → Continue to Performance Tests
   └─ FAIL → Investigate, fix if possible, or STOP

3. Performance Tests (10-15 min)
   ├─ PASS → Continue to Reliability Tests
   └─ FAIL → Investigate performance issues

4. Reliability Tests (20-30 min)
   ├─ PASS → All tests complete
   └─ FAIL → Document issues, assess severity

5. Final Decision
   ├─ All Critical PASS, ≥80% Important PASS → APPROVE for rollout
   └─ Otherwise → INVESTIGATE & FIX
```

### Post-Validation

1. Document all test results
2. Update DEPLOYMENT-SIGN-OFF.md
3. Proceed to gradual rollout if validated
4. Continue monitoring in production

---

## Troubleshooting Test Failures

### Smoke Test Failures

**Test 1 (API Health) Fails**:
- Check Railway service status
- Check deployment logs for errors
- Verify service is running on correct port
- Check network connectivity

**Test 2 (Bot Spawn) Fails**:
- Check environment variables set
- Check Dockerfile includes bot dependencies
- Check Python path exists
- Review spawn error logs

**Test 3 (Room Join) Fails**:
- Verify Daily API key is valid
- Check Daily.co service status
- Check room URL is valid
- Review join error logs

**Test 4 (Streaming) Fails**:
- Check Playwright installed correctly
- Verify Chromium browser available
- Check deck URL is accessible
- Review streaming error logs

**Test 5 (Termination) Fails**:
- Check kill API endpoint
- Verify bot manager state
- Check for zombie processes
- Review termination logs

### Functional Test Failures

**Navigation Tests Fail**:
- Verify Supabase connection
- Check realtime channel subscription
- Verify command format
- Check bot receives commands

**Concurrent Test Fails**:
- Check MAX_CONCURRENT_BOTS setting
- Review resource usage
- Check for race conditions
- Verify bot manager handles concurrency

### Performance Test Failures

**Memory/CPU Exceeds Limits**:
- Review bot implementation for leaks
- Check for resource-intensive operations
- Consider optimizing code
- Check Railway resource allocation

**FPS Below Target**:
- Check frame capture performance
- Review CPU availability
- Check network latency to Daily.co
- Optimize screenshot capture if needed

---

## Quick Reference

### Test Status Tracking

```
□ Test 1: API Health Check
□ Test 2: Bot Spawn Test
□ Test 3: Daily.co Room Join Test
□ Test 4: Screenshot Streaming Test
□ Test 5: Bot Termination Test
□ Test 6: Slide Navigation - Next
□ Test 7: Slide Navigation - Previous
□ Test 8: Slide Navigation - Go To
□ Test 9: Concurrent Session Test
□ Test 10: Bot Timeout Test
□ Test 11: Deck URL Validation
□ Test 12: Tavus Integration
□ Test 13: Memory Usage Validation
□ Test 14: CPU Usage Validation
□ Test 15: Frame Rate Stability
□ Test 16: Command Latency
□ Test 17: Crash Recovery
□ Test 18: Network Recovery
□ Test 19: Resource Exhaustion
□ Test 20: Long-Running Session
□ Test 21: Supabase Resilience
```

### Common Test Commands

```bash
# Set API URL
export API_URL="https://slide-system-production-5813.up.railway.app"

# Check bot status
curl -s "$API_URL/api/tavus/bot/status" | jq

# Spawn bot
curl -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "test", "room_url": "ROOM_URL"}'

# Kill bot
curl -X POST "$API_URL/api/tavus/bot/kill" \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "test"}'

# Check logs
railway logs --service slide-system --tail
railway logs --service slide-system --since 5m | grep "ERROR"
```

---

**Document Version**: 1.0
**Last Updated**: 2025-10-12
**Owner**: Stream C - Production Validation & Rollout
**Related Documents**: PRE-DEPLOYMENT-CHECKLIST.md, GRADUAL-ROLLOUT-PLAN.md, PRODUCTION-MONITORING-CHECKLIST.md
