# Local vs Railway Bot Analysis

**Date**: 2025-10-18
**Status**: Investigation in progress - bot works locally, Railway bot stops after imports

## Executive Summary

✅ **LOCAL TEST**: Bot successfully connects to LiveKit and streams frames
❌ **RAILWAY**: Bot spawns but stops after initial imports (before asyncio)

## Test Results

### Local Test Success (10-second test)

**Command**: `.venv/bin/python test_livekit_connection.py test-room-local 10`

**Results**:
- ✅ Bot connected to LiveKit room successfully
- ✅ Video track published to room
- ✅ 7 frames streamed in ~1.91 seconds
- ✅ Screenshot capture: 100% success rate, 188ms avg
- ✅ Frame processing: 82ms avg
- ✅ No crashes or connection errors

**Performance Metrics**:
```
Frames streamed: 7
Duration: 1.91 seconds of actual streaming (10.6 seconds total test time)
Average FPS: 0.66 (actual streaming ~3.66 FPS)
Screenshot capture success rate: 100%
Average capture time: 188.51ms
Average processing time: 82.19ms
```

**Log File**: `test_logs/livekit-test-20251018_195534.log`

### Railway Test Failure (Bot 40e62540)

**Session**: `voice-demo-39c589b9`
**Deck**: `https://buzztrail.github.io/buzztrail-presentations/decks/9bes-lz8r-skp5/`

**What Works**:
- ✅ Bot spawns successfully (PID: 309)
- ✅ Python 3.13.5 starts
- ✅ Imports: os, logging, time, BytesIO, typing, pathlib, PIL.Image, dotenv

**Where It Stops**:
- ❌ Last log line: `[Bot 40e62540 STDOUT] ✅ dotenv imported`
- ❌ Bot marked as "spawned successfully" but no further output
- ❌ Should next print "Importing asyncio..." (bot.py:57) but never appears
- ❌ No error messages, no stack trace

## Code Analysis

### Local Test Import Sequence (bot.py:12-140)

```python
# Lines 12-59: All succeed locally
print("BOT.PY STARTING - Python process initiated")
import sys, os, logging, time
from io import BytesIO
from typing import Optional, Dict, Any
from pathlib import Path
from PIL import Image
from dotenv import load_dotenv

# Lines 57-59: This is where Railway bot stops
print("Importing asyncio...")
import asyncio
print("✅ asyncio imported successfully")

# Lines 65-126: Never reached on Railway
from shared_types import ...
from livekit import rtc
from screenshot_capture import ScreenshotCapture
from frame_processor import FrameProcessor
from slide_control_listener import SlideControlListener
from slide_navigator import SlideNavigator
from lifecycle_manager import BotLifecycleManager
```

### Railway vs Local Environment

| Feature | Railway | Local | Status |
|---------|---------|-------|--------|
| Python Version | 3.13.5 | 3.14.0 | ⚠️ Different |
| Package Manager | uv | uv | ✅ Same |
| Environment Variables | Set by Railway | `.env.local` | ⚠️ Different source |
| LiveKit URL | wss://buzztrail-fifa4bj6.livekit.cloud | wss://buzztrail-fifa4bj6.livekit.cloud | ✅ Same |
| Working Directory | `/app/bots/screenshare-bot/` | `./` | ⚠️ Different |
| Venv Path | `/app/.venv/bin/python` | `./.venv/bin/python` | ⚠️ Different |

## Key Observation: Railway Bot Stops at `asyncio` Import

**Critical Finding**: The Railway bot log shows successful imports through `dotenv` (bot.py:52-53), but never reaches the `asyncio` import (bot.py:57-59).

**Possible Causes**:
1. **Event Loop Conflict**: Python 3.13 has different asyncio event loop initialization behavior
2. **Import Hanging**: `import asyncio` might be blocking/hanging without error
3. **Silent Process Kill**: Railway might be killing the process silently
4. **Output Buffering**: Logs after asyncio import might be buffered and not flushed
5. **Memory/Resource Limit**: Railway container OOM or CPU limit reached

## Next Steps for Debugging

### 1. Test asyncio Import in Isolation on Railway

Create a minimal test script:
```python
#!/usr/bin/env python3
print("Before asyncio import")
import asyncio
print("After asyncio import")
asyncio.run(asyncio.sleep(0.1))
print("After asyncio.run")
```

### 2. Add Explicit sys.stdout.flush()

Modify bot.py to flush after each print:
```python
print("Importing asyncio...")
sys.stdout.flush()
import asyncio
sys.stdout.flush()
print("✅ asyncio imported successfully")
sys.stdout.flush()
```

### 3. Check Railway Resource Limits

```bash
railway run bash -c "cat /proc/meminfo | head -5"
railway run bash -c "cat /proc/cpuinfo | grep processor | wc -l"
```

### 4. Test with Python 3.14 on Railway

Match local Python version to eliminate version differences.

### 5. Add Timeout Monitoring

Wrap imports in timeout decorator to detect if hanging:
```python
import signal
def timeout_handler(signum, frame):
    raise TimeoutError("Import took too long")

signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(5)  # 5 second timeout
import asyncio
signal.alarm(0)  # Cancel alarm
```

## Environment Variables Comparison

### Local (.env.local)
```bash
TRANSPORT_TYPE=livekit
LIVEKIT_URL=wss://buzztrail-fifa4bj6.livekit.cloud
LIVEKIT_API_KEY=APIXLYPswBShpTX
LIVEKIT_API_SECRET=fcF4dAtroNeZFUJwVVL1zAP1nUMhl1ItFjorTzVRpq6
LIVEKIT_ROOM_NAME=test-room-local
SUPABASE_URL=https://dwdytxxqcvlrmyemonxz.supabase.co
SUPABASE_SERVICE_KEY=eyJhbGc...
PYTHONUNBUFFERED=1
```

### Railway
Need to verify all variables are set correctly on Railway service.

## Test Files Created

1. `generate_livekit_token.py` - Token generator (working)
2. `test_livekit_connection.py` - Full LiveKit test (working locally)
3. `.env.local` - Local credentials (working)
4. `QUICK-START-LIVEKIT-TEST.md` - Setup instructions
5. `test_logs/livekit-test-20251018_195534.log` - Successful local test log

## Conclusion

The bot works perfectly locally with LiveKit, proving:
- ✅ Bot code is fundamentally correct
- ✅ LiveKit integration works
- ✅ Screenshot capture and frame processing are functional
- ✅ Token generation and room joining work

The issue is **Railway-specific** and appears to be related to the `asyncio` import failing silently around bot.py:57-59.

Next investigation should focus on why the Railway bot stops at this exact point without any error message.
