# Production Deployment Runbook - slide-system

**Service**: slide-system (Pipecat Screenshare Bot)
**Platform**: Railway
**Production URL**: https://slide-system-production-5813.up.railway.app
**Last Updated**: 2025-10-12

---

## Table of Contents

1. [Pre-Deployment Checklist](#pre-deployment-checklist)
2. [Deployment Procedure](#deployment-procedure)
3. [Post-Deployment Validation](#post-deployment-validation)
4. [Monitoring & Alerts](#monitoring--alerts)
5. [Rollback Procedure](#rollback-procedure)
6. [Troubleshooting](#troubleshooting)
7. [Environment Variables](#environment-variables)
8. [API Endpoints](#api-endpoints)

---

## Pre-Deployment Checklist

Before deploying to production, verify:

### Code Quality
- [ ] All tests passing locally
- [ ] No linting errors (`pnpm nx lint slide-system`)
- [ ] No TypeScript errors (`pnpm nx typecheck slide-system`)
- [ ] All Motia steps have `emits` property defined

### Database
- [ ] Supabase migrations applied to production database
- [ ] Database connection tested (`supabase db push`)
- [ ] Active bots table exists and indexed

### Dependencies
- [ ] All npm dependencies installed (`pnpm install`)
- [ ] Python dependencies listed in `bots/screenshare-bot/requirements.txt`
- [ ] Docker image builds successfully

### Configuration
- [ ] Environment variables documented
- [ ] Secrets configured in Railway
- [ ] API keys validated

### Documentation
- [ ] Architecture docs updated
- [ ] API changes documented
- [ ] Runbook updated (this file)

---

## Deployment Procedure

### Automatic Deployment (Recommended)

Railway automatically deploys when code is pushed to `main` branch:

```bash
# 1. Ensure you're on main branch
git checkout main
git pull origin main

# 2. Commit your changes
git add .
git commit -m "feat: your feature description"

# 3. Push to trigger deployment
git push origin main

# 4. Monitor deployment
railway logs --follow
```

**Deployment Time**: ~6-7 minutes (Docker build + deploy)

### Manual Deployment (Emergency)

If automatic deployment fails:

```bash
# 1. Link Railway service
railway service

# 2. Trigger manual deployment
railway up

# 3. Monitor logs
railway logs --tail 100
```

### Gradual Rollout Strategy

For major changes, use gradual rollout:

**Phase 1: Single Bot Test (Week 1)**
- Deploy to production
- Spawn 1 test bot with premade deck
- Monitor for 24 hours
- Verify metrics: uptime, memory, CPU
- Check logs for errors

**Phase 2: Limited Production (Week 2)**
- Enable for 2-3 customer sessions
- Monitor bot lifecycle metrics
- Validate slide control latency <500ms
- Collect user feedback

**Phase 3: Full Rollout (Week 3+)**
- Scale to 5 concurrent bots
- Enable for all customer sessions
- Monitor resource usage
- Auto-scaling if needed

---

## Post-Deployment Validation

### 1. Health Check

Verify service is healthy:
```bash
curl https://slide-system-production-5813.up.railway.app/api/health
```

**Expected Response**:
```json
{
  "status": "healthy",
  "timestamp": "2025-10-12T12:00:00.000Z",
  "service": "slide-system",
  "version": "1.0.0",
  "checks": {
    "database": {
      "status": "up",
      "error": null
    },
    "api": {
      "status": "up",
      "response_time_ms": 50
    }
  },
  "uptime_seconds": 1234
}
```

**Success Criteria**: HTTP 200, status="healthy", database="up"

### 2. API Endpoints Verification

Test all critical endpoints:
```bash
# Bot status (should return empty array initially)
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/status
# Expected: {"active_count":0,"bots":[]}

# Bot spawn endpoint exists
curl -X OPTIONS https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn
# Expected: HTTP 204
# Slidev generation endpoint
curl -X OPTIONS https://slide-system-production-5813.up.railway.app/api/slidev/generate
# Expected: HTTP 204
```

### 3. Bot Spawn Test (Optional)

**⚠️ WARNING**: Only run this test in staging or with a test session.

```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn \
  -H "Content-Type: application/json" \
  -d '{
    "room_url": "https://buzztrail.daily.co/test-room",
    "deck_url": "https://example.com/test-deck",
    "session_id": "test-uuid-here"
  }'
```

**Expected Response**:
```json
{
  "bot_id": "uuid",
  "status": "spawning",
  "pid": 12345,
  "estimated_join_time": "5s",
  "message": "Bot spawned successfully for session test-uuid-here",
  "log_file": "/path/to/logs/bot-uuid.log"
}
```

### 4. Database Validation

Check Supabase for bot metadata:

```bash
# Via Supabase CLI
supabase db dump --data-only --table active_bots

# Or query directly
psql $SUPABASE_URL -c "SELECT * FROM active_bots LIMIT 5;"
```

### 5. Deployment Metrics

Monitor Railway dashboard:
- **Build time**: Should be <5 minutes
- **Deploy time**: Should be <3 minutes
- **Memory usage**: Should be <1GB at idle
- **CPU usage**: Should be <10% at idle

---

## Monitoring & Alerts

### Key Metrics to Monitor

| Metric | Threshold | Action |
|--------|-----------|--------|
| Health check failing | >3 consecutive failures | Alert on-call, investigate |
| Memory usage | >80% of limit | Scale up or optimize |
| CPU usage | >70% sustained | Investigate bot count |
| Bot spawn failures | >10% fail rate | Check logs, verify env vars |
| API response time | >500ms p95 | Check database, optimize |
| Database connection errors | Any | Check Supabase status |

### Setting Up Alerts

**Railway Built-in Monitoring**:
- Railway dashboard: https://railway.app/project/slide-system
- CPU/Memory graphs available
- Crash alerts automatic

**External Monitoring (Recommended)**:

1. **Uptime Monitoring**:
   - Service: UptimeRobot or Pingdom
   - Check: `GET https://slide-system-production-5813.up.railway.app/api/health`
   - Interval: 5 minutes
   - Alert: Email + Slack on failure

2. **Log Monitoring**:
   - View logs: `railway logs --tail 1000`
   - Search for errors: `railway logs | grep ERROR`
   - Alert on: "[ERROR]", "failed", "crash", "SIGKILL"

3. **Database Monitoring**:
   - Supabase dashboard: https://supabase.com/dashboard
   - Monitor: Connection pool, query performance
   - Alert on: Connection timeouts, slow queries

### Log Aggregation

**Viewing Logs**:
```bash
# Real-time logs
railway logs --follow

# Last 100 lines
railway logs --tail 100

# Search logs
railway logs | grep "bot_id"

# Filter by timestamp
railway logs --since 1h
```

**Key Log Messages**:
- `[ScreenshareBotSpawn] ✅ Bot {id} spawned successfully` - Success
- `[ScreenshareBotSpawn] Failed to spawn bot` - Error (investigate)
- `[ScreenshareBotStatus] Bot {id} process died` - Unexpected termination
- `[ERROR]` - Motia validation errors

---

## Rollback Procedure

If deployment causes critical issues:

### 1. Immediate Rollback via Railway

```bash
# View recent deployments
railway deployments

# Rollback to previous deployment
railway rollback <deployment-id>
# Verify rollback
curl https://slide-system-production-5813.up.railway.app/api/health
```

### 2. Git-based Rollback

```bash
# Find last known good commit
git log --oneline -10

# Revert to that commit
git revert <bad-commit-sha>

# Or reset (if safe)
git reset --hard <good-commit-sha>
git push origin main --force

# Railway will auto-deploy previous version
```

### 3. Kill Active Bots (if needed)

If bots are misbehaving after deployment:

```bash
# Get all active bots
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/status

# Kill each bot
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/kill/{bot_id}
```

### 4. Database Rollback (if needed)

If Supabase migration caused issues:

```bash
# View migration history
supabase migration list

# Rollback last migration
supabase db reset

# Reapply up to safe migration
supabase db push
```

---

## Troubleshooting

### Issue: Health Check Failing

**Symptoms**: `GET /api/health` returns 503 or timeout

**Diagnosis**:
```bash
# Check service status
railway status

# Check recent logs
railway logs --tail 50

# Check database
supabase db status
```

**Common Causes**:
1. **Supabase connection issue**: Check `SUPABASE_URL` and `SUPABASE_SERVICE_KEY`
2. **Motia crashed**: Check logs for errors, restart service
3. **Railway outage**: Check Railway status page

**Resolution**:
1. Verify environment variables: `railway variables`
2. Restart service: Railway auto-restarts on crash
3. Check Supabase dashboard for database health

---

### Issue: Bot Spawn Failing

**Symptoms**: `POST /api/bots/screenshare/spawn` returns 500 error

**Diagnosis**:
```bash
# Check spawn logs
railway logs | grep "ScreenshareBotSpawn"

# Check Python bot logs
railway logs | grep "bot.py"

# Check Playwright errors
railway logs | grep "playwright"
```

**Common Causes**:
1. **Missing DAILY_PIPECAT_API_KEY**: Bot can't join room
2. **Playwright browsers not installed**: Check Docker image
3. **Python venv missing**: Check Docker build logs
4. **Deck URL inaccessible**: Test URL directly

**Resolution**:
1. Verify all env vars: `railway variables`
2. Check Docker image includes Playwright: See `Dockerfile`
3. Test bot locally: `python bots/screenshare-bot/bot.py <args>`
4. Check bot log files in Railway logs

---

### Issue: Status Endpoint Returns 404

**Symptoms**: `GET /api/bots/screenshare/status` returns 404

**Diagnosis**:
```bash
# Check if step is registered
railway logs | grep "ScreenshareBotStatus"

# Check for Motia validation errors
railway logs | grep "[ERROR]"
```

**Common Cause**: Missing `emits` property in step config

**Resolution**:
1. Check `steps/bot-status.step.ts` has `emits: []`
2. Regenerate `types.d.ts`: Delete file, restart Motia
3. Commit and redeploy

---

### Issue: High Memory Usage

**Symptoms**: Railway dashboard shows >80% memory usage

**Diagnosis**:
```bash
# Check active bots count
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/status

# Check memory per bot
railway logs | grep "RSS"
```

**Common Causes**:
1. **Too many concurrent bots**: Each bot ~200-300MB
2. **Memory leak in bot**: Check bot uptime
3. **Playwright memory not released**: Orphaned browsers

**Resolution**:
1. Kill inactive bots: `POST /api/bots/screenshare/kill/{bot_id}`
2. Restart Railway service to clear memory
3. Scale Railway plan if needed
4. Optimize bot code: Review `bot.py` for leaks

---

### Issue: Slow API Response Times

**Symptoms**: API endpoints take >500ms to respond

**Diagnosis**:
```bash
# Check database query times
# (View in Supabase dashboard)

# Check Railway CPU usage
railway status
```

**Common Causes**:
1. **Slow database queries**: Missing indexes
2. **High CPU load**: Too many bots
3. **Network latency**: Supabase region mismatch

**Resolution**:
1. Add database indexes: See `supabase/migrations/`
2. Optimize queries: Use `select()` with specific columns
3. Scale Railway plan: Increase CPU allocation

---

## Environment Variables

### Required Variables

| Variable | Description | Example | Source |
|----------|-------------|---------|--------|
| `DAILY_PIPECAT_API_KEY` | Pipecat/Daily.co integration key | `dk_...` | Daily.co dashboard |
| `DAILY_API_KEY` | Daily.co room creation key | `abc123...` | Daily.co dashboard |
| `SUPABASE_URL` | Supabase project URL | `https://xxx.supabase.co` | Supabase dashboard |
| `SUPABASE_SERVICE_KEY` | Supabase admin key | `eyJhbGc...` | Supabase dashboard |

### Setting Variables

**Via Railway CLI**:
```bash
railway variables set DAILY_PIPECAT_API_KEY=xxx
railway variables set SUPABASE_URL=https://...
railway variables set SUPABASE_SERVICE_KEY=yyy
```

**Via Railway Dashboard**:
1. Open Railway project
2. Navigate to "Variables" tab
3. Add/update variables
4. Save (triggers automatic redeploy)

### Verifying Variables

```bash
# List all variables (values masked)
railway variables

# Test specific variable in deployment
railway logs | grep "SUPABASE_URL"
```

---

## API Endpoints

### Production Endpoints

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/health` | Service health check |
| POST | `/api/bots/screenshare/spawn` | Spawn new bot |
| GET | `/api/bots/screenshare/status` | Get all bots status |
| GET | `/api/bots/screenshare/status/:bot_id` | Get specific bot status |
| POST | `/api/bots/screenshare/kill/:bot_id` | Kill specific bot |
| POST | `/api/slidev/generate` | Generate Slidev deck |
| POST | `/api/slidev/control` | Send slide navigation command |

### Testing Production Endpoints

See [Post-Deployment Validation](#post-deployment-validation) for curl commands.

---

## Emergency Contacts

**On-Call Engineer**: Check team calendar
**Railway Support**: https://railway.app/help
**Supabase Support**: https://supabase.com/support
**Daily.co Support**: support@daily.co

---

## Version History

| Date | Version | Changes | Author |
|------|---------|---------|--------|
| 2025-10-12 | 1.0.0 | Initial production deployment runbook | Claude |

---

## Automated Demo System Deployment

### Pre-Deployment Checklist

- [ ] Tavus replica configured with FAST MODE
- [ ] Tool forwarder bot code deployed
- [ ] Demo UI updated with spawning logic
- [ ] Environment variables set: TAVUS_REPLICA_ID, TAVUS_API_KEY
- [ ] Supabase schema updated (conversation_sessions columns)

### Deployment Steps

1. Deploy tool forwarder bot to Railway
2. Test spawn endpoint: `POST /api/bots/tool-forwarder/spawn`
3. Verify Tavus replica function calling in sandbox
4. Deploy updated demo UI
5. Run 3 internal test demos
6. Monitor Railway logs for errors
7. Validate success rate >90%

### Post-Deployment Validation

- Run 5 test demos and measure metrics
- Verify cost per demo ~$1.50
- Check all failure modes have recovery
- Update team with testing results

---

## Additional Resources

- **Architecture Guide**: [MOTIA_SUPABASE_ARCHITECTURE.md](./MOTIA_SUPABASE_ARCHITECTURE.md)
- **Development Guide**: [README.md](./README.md)
- **PRD**: [pipecat-based-screenshare-bot.md](../../.claude/prds/pipecat-based-screenshare-bot.md)
- **Railway Dashboard**: https://railway.app/project/slide-system
- **Supabase Dashboard**: https://supabase.com/dashboard/project/dwdytxxqcvlrmyemonxz
- **Motia Docs**: https://www.motia.dev/docs
