# Gradual Rollout Plan for Screenshare Bot

**Purpose**: Phased deployment strategy to safely roll out the screenshare bot to production.

**Strategy**: Start with 1 bot, monitor for 4 hours, then scale to 3 bots, then 5 bots over 48 hours.

**Risk Mitigation**: Early detection of issues with minimal impact, structured decision points, clear rollback criteria.

---

## Table of Contents

1. [Rollout Overview](#rollout-overview)
2. [Phase 1: Single Bot Validation](#phase-1-single-bot-validation-4-hours)
3. [Phase 2: Three Bot Validation](#phase-2-three-bot-validation-4-hours)
4. [Phase 3: Five Bot Production](#phase-3-five-bot-production-12-48-hours)
5. [Decision Criteria](#decision-criteria)
6. [Rollback Procedures](#rollback-procedures)
7. [Monitoring Requirements](#monitoring-requirements)

---

## Rollout Overview

### Rollout Timeline

```
Total Duration: 20-56 hours (minimum to maximum)

┌─────────────┬─────────────┬──────────────────────────────┐
│   Phase 1   │   Phase 2   │          Phase 3             │
│  (4 hours)  │  (4 hours)  │       (12-48 hours)          │
├─────────────┼─────────────┼──────────────────────────────┤
│   1 Bot     │   3 Bots    │         5 Bots               │
│  Validate   │  Validate   │  Production Validation       │
│  Basic      │  Concurrent │  Full Load & Stability       │
│  Func       │  Handling   │                              │
└─────────────┴─────────────┴──────────────────────────────┘
      ↓              ↓                    ↓
   Go/No-Go      Go/No-Go           Go-Live Decision
```

### Objectives by Phase

**Phase 1 (1 Bot)**:
- Verify basic functionality works in production
- Validate Railway configuration
- Confirm bot can spawn, join room, stream, and terminate
- Establish performance baseline

**Phase 2 (3 Bots)**:
- Test concurrent bot handling
- Verify resource management under moderate load
- Detect any concurrency issues
- Validate bot manager state tracking

**Phase 3 (5 Bots)**:
- Validate production-scale concurrent handling
- Monitor long-term stability (12-48 hours)
- Confirm no memory leaks or performance degradation
- Final production validation

---

## Phase 1: Single Bot Validation (4 Hours)

### Configuration

**Environment Variables**:
```bash
MAX_CONCURRENT_BOTS=1
LOG_LEVEL=INFO
DEBUG_MODE=false
BOT_TIMEOUT_MINUTES=30
FRAME_RATE=10
```

**Set in Railway**:
```bash
railway vars --service slide-system set MAX_CONCURRENT_BOTS=1
railway vars --service slide-system set LOG_LEVEL=INFO
```

### Timeline

| Time | Activity | Duration |
|------|----------|----------|
| T+0 | Deploy to Railway | 5-10 min |
| T+10 | Run smoke tests | 10 min |
| T+20 | Spawn test bot | 2 min |
| T+22 | Monitor bot performance | 4 hours |
| T+4h | Phase 1 evaluation | 15 min |
| T+4h15 | Go/No-Go decision | - |

### Deployment Steps

**T+0: Deploy with Phase 1 Config**

```bash
# Ensure MAX_CONCURRENT_BOTS=1
railway vars --service slide-system set MAX_CONCURRENT_BOTS=1

# Deploy
git push origin main  # If auto-deploy enabled
# OR
railway up --service slide-system

# Monitor deployment
railway logs --service slide-system --tail
```

**T+10: Run Smoke Tests**

See PRODUCTION-VALIDATION.md for detailed smoke test procedures.

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

# Test 1: API responds
curl -s "$API_URL/api/tavus/bot/status" | jq

# Test 2: Bot status endpoint works
# Expected: {"activeCount": 0, "bots": []}
```

**T+20: Spawn Test Bot**

```bash
# Create test Daily.co room (if needed)
cd /Users/lars/mycode/buzztrail/epic-pipecat-based-screenshare-bot/apps/slide-system/bots/screenshare-bot
python scripts/create_test_room.py

# Save room URL
export TEST_ROOM_URL="<room_url_from_script>"

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

# Expected response:
# {"success": true, "message": "Bot spawned for conversation phase1-validation-..."}
```

**T+22: Begin 4-Hour Monitoring**

Monitor every 30 minutes using this checklist:

**30-Minute Monitoring Checklist**:
```
□ Check bot is still running
□ Review performance logs
□ Check memory usage
□ Check CPU usage
□ Check frame rate
□ Check for errors in logs
□ Verify no crashes
```

**Monitoring Commands**:
```bash
# Check bot status
curl -s "$API_URL/api/tavus/bot/status" | jq

# Check performance logs
railway logs --service slide-system | grep "Performance -" | tail -5

# Expected output example:
# Bot phase1-validation-123 Performance - Memory: 285.2MB, CPU: 22.1%, FPS: 10.0, Frame Capture: 35.2ms

# Check for errors
railway logs --service slide-system --since 30m | grep -i "error" | wc -l
# Expected: 0 (or very low count)
```

**Monitoring Schedule**:
- **T+30min**: First check
- **T+1h**: Second check
- **T+1h30**: Third check
- **T+2h**: Fourth check
- **T+2h30**: Fifth check
- **T+3h**: Sixth check
- **T+3h30**: Seventh check
- **T+4h**: Final check + evaluation

### Metrics to Track

**Performance Metrics**:

| Metric | Target | Warning | Critical |
|--------|--------|---------|----------|
| Memory | <350 MB | 350-450 MB | >500 MB |
| CPU | <30% | 30-40% | >40% |
| FPS | 9.9-10.1 | 9.5-9.9 or 10.1-10.5 | <9.5 or >10.5 |
| Frame Capture Time | <50ms | 50-75ms | >75ms |
| Crashes | 0 | 0 | >0 |
| Errors (non-critical) | <5 | 5-10 | >10 |

**Recording Metrics**:
```bash
# Create metrics log file
echo "Phase 1 Metrics Log - $(date)" > phase1_metrics.log

# Record metrics every 30 minutes
while true; do
  echo "=== $(date) ===" >> phase1_metrics.log
  railway logs --service slide-system | grep "Performance -" | tail -1 >> phase1_metrics.log
  curl -s "$API_URL/api/tavus/bot/status" | jq '.activeCount' >> phase1_metrics.log
  sleep 1800  # 30 minutes
done
```

### Phase 1 Success Criteria

At T+4h, evaluate against these criteria:

**MUST PASS (Critical)**:
- [ ] Bot spawned successfully (PID logged)
- [ ] Bot joined Daily.co room successfully
- [ ] Bot ran for 4 hours without crashing (exit code 0 or still running)
- [ ] Frame rate stable between 9.5-10.5 FPS throughout
- [ ] Memory usage remained < 500MB throughout
- [ ] CPU usage remained < 40% throughout
- [ ] Zero crashes (exit code != 0)
- [ ] Bot responds to kill command gracefully

**SHOULD PASS (Important)**:
- [ ] Memory usage remained < 350MB (baseline)
- [ ] CPU usage remained < 30% (baseline)
- [ ] Frame rate 9.9-10.1 FPS (optimal)
- [ ] Frame capture time < 50ms
- [ ] Fewer than 5 non-critical errors in logs

**EVALUATION SCRIPT**:
```bash
#!/bin/bash
# evaluate_phase1.sh

echo "Phase 1 Evaluation - $(date)"
echo "======================================"

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

# Check 1: Bot still running or terminated normally
ACTIVE=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
CRASHES=$(echo "$LOGS" | grep "Bot process exited" | grep -cv "code: 0")

echo "Active Bots: $ACTIVE"
echo "Crashes: $CRASHES"

# Check 2: Memory metrics
AVG_MEMORY=$(echo "$LOGS" | grep "Memory:" | awk '{sum+=$6; count++} END {print sum/count}')
MAX_MEMORY=$(echo "$LOGS" | grep "Memory:" | awk '{if ($6 > max) max=$6} END {print max}')

echo "Average Memory: ${AVG_MEMORY} MB"
echo "Peak Memory: ${MAX_MEMORY} MB"

# Check 3: CPU metrics
AVG_CPU=$(echo "$LOGS" | grep "CPU:" | awk '{sum+=$8; count++} END {print sum/count}')
MAX_CPU=$(echo "$LOGS" | grep "CPU:" | awk '{if ($8 > max) max=$8} END {print max}')

echo "Average CPU: ${AVG_CPU}%"
echo "Peak CPU: ${MAX_CPU}%"

# Check 4: FPS stability
AVG_FPS=$(echo "$LOGS" | grep "Actual FPS:" | awk '{sum+=$6; count++} END {print sum/count}')
MIN_FPS=$(echo "$LOGS" | grep "Actual FPS:" | awk 'NR==1 {min=$6} {if ($6 < min) min=$6} END {print min}')

echo "Average FPS: $AVG_FPS"
echo "Minimum FPS: $MIN_FPS"

# Check 5: Errors
ERROR_COUNT=$(echo "$LOGS" | grep -ci "error")

echo "Error Count: $ERROR_COUNT"
echo ""

# Decision
if [ "$CRASHES" -eq 0 ] && \
   (( $(echo "$MAX_MEMORY < 500" | bc -l) )) && \
   (( $(echo "$MAX_CPU < 40" | bc -l) )) && \
   (( $(echo "$MIN_FPS > 9.5" | bc -l) )) && \
   [ "$ERROR_COUNT" -lt 10 ]; then
  echo "✅ Phase 1 SUCCESS - Proceed to Phase 2"
  exit 0
else
  echo "❌ Phase 1 FAILED - Rollback and investigate"
  exit 1
fi
```

### Go/No-Go Decision

**GO to Phase 2 if**:
- All critical success criteria PASS
- At least 80% of important criteria PASS
- No blocking issues identified
- Team consensus to proceed

**NO-GO (Rollback) if**:
- Any critical criterion FAILS
- Bot crashed during monitoring period
- Memory or CPU exceeded critical thresholds
- Frame rate dropped below 9.0 FPS
- Significant errors in logs

**NO-GO Actions**:
```bash
# 1. Kill the test bot
curl -X POST "$API_URL/api/tavus/bot/kill" \
  -H "Content-Type: application/json" \
  -d '{"conversation_id": "phase1-validation-..."}'

# 2. Rollback deployment
railway rollback --service slide-system <PREVIOUS_DEPLOYMENT_ID>

# 3. Document issues
# Create incident report with:
# - What went wrong
# - Metrics at time of failure
# - Logs showing the issue
# - Recommended fixes

# 4. Fix issues in development
# 5. Re-run Phase 1 after fixes
```

---

## Phase 2: Three Bot Validation (4 Hours)

**Prerequisites**:
- Phase 1 completed successfully
- All Phase 1 success criteria met
- Team available for monitoring

### Configuration

**Update Environment Variable**:
```bash
railway vars --service slide-system set MAX_CONCURRENT_BOTS=3
```

**Note**: Railway will auto-restart service with new config. No redeployment needed.

### Timeline

| Time | Activity | Duration |
|------|----------|----------|
| T+0 | Update MAX_CONCURRENT_BOTS to 3 | 2 min |
| T+2 | Service restarts with new config | 2 min |
| T+4 | Create 3 test rooms | 2 min |
| T+6 | Spawn 3 bots (staggered) | 3 min |
| T+9 | Monitor 3 bots | 4 hours |
| T+4h | Phase 2 evaluation | 15 min |
| T+4h15 | Go/No-Go decision | - |

### Deployment Steps

**T+0: Update Configuration**

```bash
# Set MAX_CONCURRENT_BOTS to 3
railway vars --service slide-system set MAX_CONCURRENT_BOTS=3

# Service will auto-restart (watch logs)
railway logs --service slide-system --tail
```

**T+4: Create Test Rooms**

```bash
cd /Users/lars/mycode/buzztrail/epic-pipecat-based-screenshare-bot/apps/slide-system/bots/screenshare-bot

# Create 3 rooms
python scripts/create_test_rooms.py --count 3

# Save room URLs
export ROOM_1="<url1>"
export ROOM_2="<url2>"
export ROOM_3="<url3>"
```

**T+6: Spawn 3 Bots (Staggered)**

Spawn bots with 30-second intervals to avoid race conditions:

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

# Bot 1
curl -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{
    \"conversation_id\": \"phase2-bot1-$(date +%s)\",
    \"room_url\": \"$ROOM_1\"
  }"

sleep 30

# Bot 2
curl -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{
    \"conversation_id\": \"phase2-bot2-$(date +%s)\",
    \"room_url\": \"$ROOM_2\"
  }"

sleep 30

# Bot 3
curl -X POST "$API_URL/api/tavus/bot/spawn" \
  -H "Content-Type: application/json" \
  -d "{
    \"conversation_id\": \"phase2-bot3-$(date +%s)\",
    \"room_url\": \"$ROOM_3\"
  }"

# Verify all 3 bots active
curl -s "$API_URL/api/tavus/bot/status" | jq
# Expected: {"activeCount": 3, "bots": [...]
```

**T+9: Begin 4-Hour Monitoring**

**30-Minute Monitoring Checklist** (expanded for 3 bots):
```
□ Check all 3 bots are still running
□ Review performance logs for each bot
□ Check total memory usage (expect ~900MB)
□ Check total CPU usage (expect ~60-90%)
□ Check frame rate for each bot
□ Check for errors in logs
□ Verify no crashes
□ Check for resource contention between bots
```

**Monitoring Commands**:
```bash
# Check all bots active
curl -s "$API_URL/api/tavus/bot/status" | jq '.activeCount'
# Expected: 3

# Check each bot's performance
railway logs --service slide-system | grep "Performance -" | tail -15

# Calculate total memory
railway logs --service slide-system | grep "Memory:" | tail -3 | \
  awk '{sum+=$6} END {print "Total Memory:", sum, "MB"}'

# Calculate total CPU
railway logs --service slide-system | grep "CPU:" | tail -3 | \
  awk '{sum+=$8} END {print "Total CPU:", sum, "%"}'

# Check for errors
railway logs --service slide-system --since 30m | grep -i "error" | wc -l
```

### Metrics to Track

**Per-Bot Metrics** (same as Phase 1):

| Metric | Target | Warning | Critical |
|--------|--------|---------|----------|
| Memory per bot | <350 MB | 350-450 MB | >500 MB |
| CPU per bot | <30% | 30-40% | >40% |
| FPS per bot | 9.9-10.1 | 9.5-9.9 or 10.1-10.5 | <9.5 or >10.5 |

**Total Metrics** (3 bots):

| Metric | Target | Warning | Critical |
|--------|--------|---------|----------|
| Total Memory | <1050 MB | 1050-1350 MB | >1500 MB |
| Total CPU | <90% | 90-120% | >120% |
| Active Bot Count | 3 | 2 | <2 |

### Phase 2 Success Criteria

At T+4h, evaluate against these criteria:

**MUST PASS (Critical)**:
- [ ] All 3 bots spawned successfully
- [ ] All 3 bots joined Daily.co rooms successfully
- [ ] All 3 bots ran for 4 hours without crashing
- [ ] Each bot maintains FPS between 9.5-10.5
- [ ] Total memory usage remained < 1500MB
- [ ] Total CPU usage remained < 120%
- [ ] Zero crashes across all bots
- [ ] Bot manager correctly tracks all 3 bots
- [ ] All bots respond to kill commands

**SHOULD PASS (Important)**:
- [ ] Total memory < 1050MB (baseline)
- [ ] Total CPU < 90% (baseline)
- [ ] Each bot FPS 9.9-10.1
- [ ] No performance degradation over time
- [ ] No resource contention detected

**EVALUATION SCRIPT**:
```bash
#!/bin/bash
# evaluate_phase2.sh

echo "Phase 2 Evaluation - $(date)"
echo "======================================"

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

# Check bot count
ACTIVE=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
echo "Active Bots: $ACTIVE (Expected: 3)"

# Check crashes
CRASHES=$(echo "$LOGS" | grep "Bot process exited" | grep -cv "code: 0")
echo "Crashes: $CRASHES (Expected: 0)"

# Check total memory
TOTAL_MEMORY=$(echo "$LOGS" | grep "Memory:" | tail -3 | awk '{sum+=$6} END {print sum}')
echo "Total Memory: ${TOTAL_MEMORY} MB (Target: <1050 MB)"

# Check total CPU
TOTAL_CPU=$(echo "$LOGS" | grep "CPU:" | tail -3 | awk '{sum+=$8} END {print sum}')
echo "Total CPU: ${TOTAL_CPU}% (Target: <90%)"

# Check FPS for all bots
echo "FPS per bot:"
echo "$LOGS" | grep "Actual FPS:" | tail -3

# Decision
if [ "$ACTIVE" -eq 3 ] && \
   [ "$CRASHES" -eq 0 ] && \
   (( $(echo "$TOTAL_MEMORY < 1500" | bc -l) )) && \
   (( $(echo "$TOTAL_CPU < 120" | bc -l) )); then
  echo ""
  echo "✅ Phase 2 SUCCESS - Proceed to Phase 3"
  exit 0
else
  echo ""
  echo "❌ Phase 2 FAILED - Rollback and investigate"
  exit 1
fi
```

### Go/No-Go Decision

**GO to Phase 3 if**:
- All critical success criteria PASS
- At least 80% of important criteria PASS
- No performance degradation observed
- No resource contention detected
- Team consensus to proceed

**NO-GO (Rollback) if**:
- Any critical criterion FAILS
- Any bot crashed
- Total memory exceeded 1500MB
- Total CPU exceeded 120%
- Performance degraded over time
- Resource contention detected

**NO-GO Actions**:
```bash
# 1. Kill all bots
curl -X POST "$API_URL/api/tavus/bot/kill-all"

# 2. Revert to Phase 1 config
railway vars --service slide-system set MAX_CONCURRENT_BOTS=1

# 3. Rollback if needed
railway rollback --service slide-system <PREVIOUS_DEPLOYMENT_ID>

# 4. Document issues and fix
```

---

## Phase 3: Five Bot Production (12-48 Hours)

**Prerequisites**:
- Phase 1 and Phase 2 completed successfully
- All success criteria met
- Stakeholders notified
- Monitoring alerts configured

### Configuration

**Update Environment Variable**:
```bash
railway vars --service slide-system set MAX_CONCURRENT_BOTS=5
```

### Timeline

| Time | Activity | Duration |
|------|----------|----------|
| T+0 | Update MAX_CONCURRENT_BOTS to 5 | 2 min |
| T+2 | Service restarts | 2 min |
| T+4 | Create 5 test rooms | 3 min |
| T+7 | Spawn 5 bots (staggered) | 5 min |
| T+12 | **Intensive monitoring** | 4 hours |
| T+4h | Initial validation | 15 min |
| T+4h15 | **Extended monitoring** | 8-44 hours |
| T+12h-48h | Final evaluation | 30 min |
| T+Final | Production sign-off | - |

### Deployment Steps

**T+0: Update Configuration**

```bash
# Set MAX_CONCURRENT_BOTS to 5
railway vars --service slide-system set MAX_CONCURRENT_BOTS=5

# Monitor restart
railway logs --service slide-system --tail
```

**T+4: Create Test Rooms**

```bash
cd /Users/lars/mycode/buzztrail/epic-pipecat-based-screenshare-bot/apps/slide-system/bots/screenshare-bot

# Create 5 rooms
python scripts/create_test_rooms.py --count 5

# Save room URLs
export ROOM_1="<url1>"
export ROOM_2="<url2>"
export ROOM_3="<url3>"
export ROOM_4="<url4>"
export ROOM_5="<url5>"
```

**T+7: Spawn 5 Bots**

```bash
# Spawn all 5 bots with 30-second intervals
for i in {1..5}; do
  ROOM_VAR="ROOM_$i"
  curl -X POST "$API_URL/api/tavus/bot/spawn" \
    -H "Content-Type: application/json" \
    -d "{
      \"conversation_id\": \"phase3-bot${i}-$(date +%s)\",
      \"room_url\": \"${!ROOM_VAR}\"
    }"

  echo "Bot $i spawned"
  sleep 30
done

# Verify all 5 bots
curl -s "$API_URL/api/tavus/bot/status" | jq
# Expected: {"activeCount": 5, ...}
```

**T+12: Intensive Monitoring (First 4 Hours)**

Monitor every 30 minutes with full checklist:

```bash
# Automated monitoring script
#!/bin/bash
# phase3_monitor.sh

while true; do
  echo "=== Phase 3 Check - $(date) ==="

  # Bot count
  ACTIVE=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
  echo "Active Bots: $ACTIVE / 5"

  # Performance metrics
  railway logs --service slide-system | grep "Performance -" | tail -5

  # Total resources
  TOTAL_MEM=$(railway logs --service slide-system | grep "Memory:" | tail -5 | \
    awk '{sum+=$6} END {print sum}')
  TOTAL_CPU=$(railway logs --service slide-system | grep "CPU:" | tail -5 | \
    awk '{sum+=$8} END {print sum}')

  echo "Total Memory: ${TOTAL_MEM} MB (Target: <2000 MB)"
  echo "Total CPU: ${TOTAL_CPU}% (Target: <150%)"

  # Errors
  ERRORS=$(railway logs --service slide-system --since 30m | grep -ci "error")
  echo "Errors (last 30min): $ERRORS"

  echo ""
  sleep 1800  # 30 minutes
done
```

**T+4h15: Extended Monitoring (8-44 Hours)**

After initial 4-hour validation:

**Monitoring Frequency**:
- Hours 4-12: Check every 1 hour
- Hours 12-24: Check every 2 hours
- Hours 24-48: Check every 4 hours

**Extended Monitoring Checklist**:
```
□ All 5 bots still running
□ No crashes over extended period
□ Memory usage stable (no leaks)
□ CPU usage stable
□ FPS remains stable
□ No performance degradation
□ No error rate increase
```

### Metrics to Track

**Per-Bot Metrics**:

| Metric | Target | Warning | Critical |
|--------|--------|---------|----------|
| Memory per bot | <350 MB | 350-450 MB | >500 MB |
| CPU per bot | <30% | 30-40% | >40% |
| FPS per bot | 9.9-10.1 | 9.5-9.9 or 10.1-10.5 | <9.5 |

**Total Metrics (5 bots)**:

| Metric | Target | Warning | Critical |
|--------|--------|---------|----------|
| Total Memory | <1750 MB | 1750-2250 MB | >2500 MB |
| Total CPU | <150% | 150-200% | >200% |
| Active Bot Count | 5 | 4 | <4 |

**Stability Metrics**:

| Metric | Target | Warning | Critical |
|--------|--------|---------|----------|
| Memory Increase Rate | <10 MB/hour | 10-20 MB/hour | >20 MB/hour |
| Crash Rate | 0 crashes | 1 crash/24h | >1 crash/24h |
| Error Rate | <1 error/hour | 1-5 errors/hour | >5 errors/hour |
| Spawn Success Rate | >99% | 95-99% | <95% |

### Phase 3 Success Criteria

**4-Hour Validation** (Minimum):

**MUST PASS**:
- [ ] All 5 bots spawned successfully
- [ ] All 5 bots ran for 4 hours without crashing
- [ ] Total memory < 2500MB
- [ ] Total CPU < 200%
- [ ] Each bot FPS between 9.5-10.5
- [ ] Zero crashes
- [ ] Bot manager tracks all 5 correctly

**12-Hour Validation** (Recommended):

**MUST PASS**:
- [ ] All 5 bots ran for 12 hours without crashing
- [ ] Memory usage stable (no continuous increase)
- [ ] CPU usage stable
- [ ] FPS stable across all bots
- [ ] Crash rate: 0
- [ ] Error rate < 1/hour average

**48-Hour Validation** (Production-Ready):

**MUST PASS**:
- [ ] All 5 bots ran for 48 hours OR multiple sessions totaling 48 hours
- [ ] Memory usage stable over 48 hours (no leaks)
- [ ] CPU usage stable over 48 hours
- [ ] FPS maintained 9.5-10.5 over 48 hours
- [ ] Crash rate: 0 over 48 hours
- [ ] Error rate < 1/hour average over 48 hours
- [ ] Spawn success rate > 99% over 48 hours
- [ ] No performance degradation observed

**SHOULD PASS**:
- [ ] Total memory < 1750MB average
- [ ] Total CPU < 150% average
- [ ] Each bot FPS 9.9-10.1 average
- [ ] No resource contention
- [ ] All manual tests passed (see PRODUCTION-VALIDATION.md)

### Final Evaluation

**48-Hour Evaluation Script**:
```bash
#!/bin/bash
# evaluate_phase3_final.sh

echo "Phase 3 Final Evaluation - $(date)"
echo "==========================================="

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

# 1. Check total runtime
START_TIME=$(echo "$LOGS" | grep "Bot spawned.*phase3" | head -1 | awk '{print $1, $2}')
END_TIME=$(date)
echo "Start Time: $START_TIME"
echo "End Time: $END_TIME"

# 2. Check stability
ACTIVE=$(curl -s "$API_URL/api/tavus/bot/status" | jq -r '.activeCount')
TOTAL_SPAWNED=$(echo "$LOGS" | grep -c "Bot spawned")
CRASHES=$(echo "$LOGS" | grep "Bot process exited" | grep -cv "code: 0")
CRASH_RATE=$(echo "scale=2; $CRASHES / 48" | bc)

echo ""
echo "Active Bots: $ACTIVE"
echo "Total Spawned: $TOTAL_SPAWNED"
echo "Total Crashes: $CRASHES"
echo "Crash Rate: ${CRASH_RATE} crashes/hour"

# 3. Check memory stability
MEMORY_START=$(echo "$LOGS" | grep "Memory:" | head -5 | awk '{sum+=$6; c++} END {print sum/c}')
MEMORY_END=$(echo "$LOGS" | grep "Memory:" | tail -5 | awk '{sum+=$6; c++} END {print sum/c}')
MEMORY_INCREASE=$(echo "$MEMORY_END - $MEMORY_START" | bc)

echo ""
echo "Memory (start): ${MEMORY_START} MB"
echo "Memory (end): ${MEMORY_END} MB"
echo "Memory Increase: ${MEMORY_INCREASE} MB over 48h"

# 4. Check FPS stability
AVG_FPS=$(echo "$LOGS" | grep "Actual FPS:" | awk '{sum+=$6; c++} END {print sum/c}')
MIN_FPS=$(echo "$LOGS" | grep "Actual FPS:" | awk 'NR==1 {min=$6} {if ($6 < min) min=$6} END {print min}')
MAX_FPS=$(echo "$LOGS" | grep "Actual FPS:" | awk 'NR==1 {max=$6} {if ($6 > max) max=$6} END {print max}')

echo ""
echo "Average FPS: $AVG_FPS"
echo "Min FPS: $MIN_FPS"
echo "Max FPS: $MAX_FPS"

# 5. Check error rate
ERROR_COUNT=$(echo "$LOGS" | grep -ci "error")
ERROR_RATE=$(echo "scale=2; $ERROR_COUNT / 48" | bc)

echo ""
echo "Total Errors: $ERROR_COUNT"
echo "Error Rate: ${ERROR_RATE} errors/hour"

# 6. Final decision
echo ""
echo "==========================================="

if [ "$CRASHES" -eq 0 ] && \
   (( $(echo "$MEMORY_INCREASE < 100" | bc -l) )) && \
   (( $(echo "$MIN_FPS > 9.5" | bc -l) )) && \
   (( $(echo "$ERROR_RATE < 1" | bc -l) )); then
  echo "✅ Phase 3 SUCCESS - PRODUCTION READY"
  echo ""
  echo "Next Steps:"
  echo "1. Complete DEPLOYMENT-SIGN-OFF.md"
  echo "2. Announce go-live to team"
  echo "3. Begin accepting production traffic"
  exit 0
else
  echo "❌ Phase 3 FAILED - Extend monitoring or rollback"
  echo ""
  echo "Issues:"
  [ "$CRASHES" -gt 0 ] && echo "  - Crashes detected: $CRASHES"
  (( $(echo "$MEMORY_INCREASE >= 100" | bc -l) )) && echo "  - Memory leak suspected: +${MEMORY_INCREASE}MB"
  (( $(echo "$MIN_FPS <= 9.5" | bc -l) )) && echo "  - FPS dropped below target: $MIN_FPS"
  (( $(echo "$ERROR_RATE >= 1" | bc -l) )) && echo "  - High error rate: ${ERROR_RATE}/hour"
  exit 1
fi
```

### Go-Live Decision

**GO LIVE if**:
- All 48-hour success criteria PASS
- Team consensus reached
- Production monitoring configured
- On-call rotation ready
- Stakeholders approved
- Documentation complete

**EXTEND MONITORING if**:
- Most criteria pass but one minor issue
- Need more confidence in stability
- Stakeholder requests additional validation

**ROLLBACK if**:
- Any critical criterion FAILS
- Memory leak detected
- Persistent crashes
- Performance degradation
- Team consensus to rollback

---

## Decision Criteria

### Summary Table

| Phase | Duration | Bot Count | Go Criteria | No-Go Criteria |
|-------|----------|-----------|-------------|----------------|
| **1** | 4 hours | 1 | No crashes, FPS 9.5-10.5, Memory <500MB, CPU <40% | Any crash, FPS <9.5, Memory >500MB |
| **2** | 4 hours | 3 | All phase 1 criteria × 3 bots, Total memory <1500MB, Total CPU <120% | Any crash, Total memory >1500MB, Total CPU >120% |
| **3** | 12-48 hours | 5 | All phase 2 criteria × 5 bots, Total memory <2500MB, No leaks, Crash rate: 0 | Any crash, Memory leak, Persistent errors |

### Decision Tree

```
                    [Phase 1 Complete]
                           │
                           ↓
                   All criteria pass?
                    /            \
                  YES             NO
                  /                \
                 ↓                  ↓
          [Go to Phase 2]     [Rollback & Fix]
                 │
                 ↓
          [Phase 2 Complete]
                 │
                 ↓
         All criteria pass?
          /            \
        YES             NO
        /                \
       ↓                  ↓
[Go to Phase 3]    [Rollback to Phase 1]
       │
       ↓
[Phase 3: 4-hour validation]
       │
       ↓
All criteria pass?
  /            \
YES             NO
 /               \
↓                 ↓
[Extend to 12h]  [Rollback]
 │
 ↓
[12-hour validation]
 │
 ↓
All criteria pass?
  /            \
YES             NO
 /               \
↓                 ↓
[Extend to 48h]  [Investigate/Rollback]
 │
 ↓
[48-hour validation]
 │
 ↓
All criteria pass?
  /            \
YES             NO
 /               \
↓                 ↓
[GO LIVE]    [Rollback/Fix]
```

---

## Rollback Procedures

### Immediate Rollback

For critical issues requiring immediate action:

```bash
# 1. Kill all bots
curl -X POST "$API_URL/api/tavus/bot/kill-all"

# 2. Revert to Phase 1 config (safe state)
railway vars --service slide-system set MAX_CONCURRENT_BOTS=1

# 3. Rollback deployment if needed
railway deployments --service slide-system | head -5
railway rollback --service slide-system <PREVIOUS_DEPLOYMENT_ID>

# 4. Verify rollback
railway status --service slide-system
railway logs --service slide-system --tail
```

**Time to rollback**: 2-3 minutes

### Controlled Rollback

For non-critical issues:

```bash
# 1. Stop new bot spawns (set to 0)
railway vars --service slide-system set MAX_CONCURRENT_BOTS=0

# 2. Let existing bots complete naturally

# 3. After all bots terminated, rollback deployment
railway rollback --service slide-system <PREVIOUS_DEPLOYMENT_ID>

# 4. Reset to Phase 1 for investigation
railway vars --service slide-system set MAX_CONCURRENT_BOTS=1
```

**Time to rollback**: 5-30 minutes (depending on bot sessions)

### Rollback to Specific Phase

```bash
# Rollback from Phase 3 to Phase 2
railway vars --service slide-system set MAX_CONCURRENT_BOTS=3

# Rollback from Phase 2 to Phase 1
railway vars --service slide-system set MAX_CONCURRENT_BOTS=1

# Rollback from Phase 1 to Phase 0 (no bots)
railway vars --service slide-system set MAX_CONCURRENT_BOTS=0
```

---

## Monitoring Requirements

### Tools Required

- [ ] Railway dashboard access
- [ ] Railway CLI installed and configured
- [ ] Terminal for running monitoring scripts
- [ ] Browser for Railway logs
- [ ] Slack/Discord for team communication
- [ ] Incident reporting tool ready

### Monitoring Checklist

**Continuous Monitoring**:
```
□ Railway dashboard open (Metrics tab)
□ Log stream active (railway logs --tail)
□ Bot status API accessible
□ Monitoring scripts running
□ Team communication channel active
```

**Periodic Checks**:
```
Every 30 minutes (Phases 1 & 2):
□ Check bot count
□ Review performance logs
□ Check resource usage
□ Check for errors
□ Record metrics

Every 1-4 hours (Phase 3):
□ All above checks
□ Check for memory leaks
□ Check for performance degradation
□ Review long-term trends
```

### Alert Configuration

**Critical Alerts** (immediate action):
- Any bot crash (exit code != 0)
- Memory > 500MB per bot
- CPU > 40% per bot sustained
- FPS < 9.0
- Service down

**Warning Alerts** (monitor closely):
- Memory 350-500MB
- CPU 30-40%
- FPS 9.0-9.5
- Error rate > 0.5/hour

---

## Post-Rollout Actions

After successful Phase 3 completion:

1. [ ] Complete DEPLOYMENT-SIGN-OFF.md
2. [ ] Update team on successful rollout
3. [ ] Configure production monitoring alerts
4. [ ] Document any issues encountered
5. [ ] Update runbooks if needed
6. [ ] Schedule post-rollout review meeting
7. [ ] Begin accepting production traffic
8. [ ] Continue monitoring for first week

---

**Document Version**: 1.0
**Last Updated**: 2025-10-12
**Owner**: Stream C - Production Validation & Rollout
**Related Documents**: PRE-DEPLOYMENT-CHECKLIST.md, RAILWAY-DEPLOYMENT-STEPS.md, PRODUCTION-VALIDATION.md, DEPLOYMENT-SIGN-OFF.md
