# Railway Deployment Guide v4: The Pure Python Strategy (March 2026)

## 🚨 Critical Context: Why this exists
We previously used a standard Docker/Nixpacks deployment strategy. However, Railway's build environment (specifically the `nixpacks` builder) recently had issues resolving system-level dependencies (`libpq-dev`, `libpq.so.5`) required by the C-based `psycopg2` database driver.

To guarantee stability and platform independence, we have switched to a **Pure Python** strategy.

## 🏗️ The Stack Changes
1.  **Database Driver:** Switched from `psycopg2` (C extension) to `pg8000` + `scramp` (Pure Python).
    *   *Why:* No system libraries required. Runs anywhere Python runs.
2.  **Config:** `SQLALCHEMY_DATABASE_URI` in `config.py` automatically rewrites `postgres://` to `postgresql+pg8000://`.
3.  **Migrations:** We **CANNOT** use `flask db upgrade` reliably in the build phase because it might default to `psycopg2` if not carefully configured, or fail due to the missing system libs. We use **Custom Python Migration Scripts** instead.

## 🚀 Deployment Procedure

### 1. Prepare the Code
Ensure your `requirements.txt` contains:
```txt
pg8000
scramp
# psycopg2-binary  <-- REMOVED
```

### 2. Configure `start.sh`
The `start.sh` file is our entry point. It handles the migration logic *before* starting the web server.

**Check `start.sh`:**
```bash
#!/bin/bash
set -e

# ... (logging)

# 1. Try standard upgrade (might fail, allow continue)
flask db upgrade || echo "⚠️ Flask DB Upgrade failed, continuing with Auto-Migrate..."

# 2. RUN SPECIFIC PYTHON MIGRATIONS
# Uncomment the specific script needed for this deploy.
# Example: We just added Trust Circles, so we run that.
python procedures/migrate_trust_circles.py

# (Optional) Run the catch-all auto-migrate if needed, but usually specific scripts are safer.
# python procedures/auto_migrate.py

echo "Starting gunicorn..."
exec gunicorn run:app ...
```

### 3. Deploy to Railway
1.  **Commit & Push:** `git push origin main`
2.  **Watch Build:** Railway will detect the Python app.
    *   It will install `pg8000` and `scramp` (fast, no compiling).
3.  **Watch Deploy Logs:**
    *   Look for the `Starting Application` banner.
    *   Look for the migration output: `🦞 Migrating Trust Circles Schema...`
    *   Verify success: `✅ Added 'is_trust_circle'`, `🦞 Migration Complete!`
4.  **Verify App:** Check the dashboard URL.

## 🔄 Rollback / Troubleshooting

### If the App Crashes on Startup
1.  **Check Logs:** Is it a database connection error?
    *   *Error:* `ModuleNotFoundError: psycopg2` -> You might have old code importing it directly. Use `pg8000`.
    *   *Error:* `ImportError: libpq.so.5` -> You are accidentally using `psycopg2`. Check `requirements.txt`.
2.  **Revert `start.sh`:** If a migration script is crashing the boot loop, comment it out in `start.sh` and redeploy. The app code might still work if the schema change wasn't critical for boot.

### Database Schema Drift
Since we aren't strictly using Alembic (`flask db migrate`), our `migrations/` folder might drift from the actual DB state.
*   **Fix:** Periodically, when the dev environment is stable, run `flask db migrate` locally to generate a version file, but **do not rely on it** for the production apply step. Use the `procedures/` scripts for reliable production updates.

---
*Maintained by PowerLobster Engineering*
