# Staging Isolation, Cutover, Rollback & Decommissioning Runbook

Follow this runbook to guarantee zero production impact during staging, a clean sub-minute cutover with instant rollback, and a safe owner-gated decommission.

---

## 1. Stage 2 Staging Isolation Checklist (`STAGING_SAFE_MODE`)

Before starting the staging container on `staging.<domain>`, verify every item below:

- [ ] **Separate Deployment Project & Network:** Staging runs in its own Docker Compose project / systemd unit and isolated internal network—zero shared bridge with production's database.
- [ ] **Cloned Database Only:** Staging connects to a *separate* database volume (`db_staging`) seeded from a read-only production dump. **Zero production DB credentials** exist in staging `.env`.
- [ ] **Cloned/Separate Object Storage:** Uploads/deletes write to a dedicated staging bucket or local staging volume so staging tests can never delete or overwrite live user files.
- [ ] **Outbound Email Trapped:** `SMTP_HOST` points to a local sink (e.g., Mailpit) or sandbox mode—staging can never email real users or customers.
- [ ] **Live Webhooks, Billing & Push Sandboxed:** Payment keys are test/sandbox mode only; outbound webhooks, social posting, and push notifications are disabled or routed to local mock receivers when `STAGING_SAFE_MODE=1`.
- [ ] **Background Crons Quarantined:** Scheduled jobs that burn paid API quotas or mutate external services are disabled by default and triggered manually in dry-run/staging mode only.
- [ ] **Search Engine & Public Access Blocked:** Staging serves `robots.txt` with `User-agent: *\nDisallow: /` and `X-Robots-Tag: noindex, nofollow`, gated behind Basic Auth, IP allowlist, or Zero Trust Access.

---

## 2. Stage 4A — Controlled Production Cutover Runbook

> **PREREQUISITE:** Explicit owner sign-off on `PARITY_REPORT.md` (100% Playwright visual, CSS, functional, API, SEO, and security parity on `staging.<domain>`).

### Pre-Stage (`T - 15 min`)
1. Confirm a low-traffic maintenance window (between scheduled cron runs).
2. Build and tag the exact release binary/image that passed staging verification (no unverified last-minute commits!).
3. Pre-start the production Rust container on an internal loopback/alternate port (e.g., `:3001`) with production `.env` (`STAGING_SAFE_MODE` unset) and verify `/healthz` against a rehearsal DB.
4. Confirm zero in-flight long-running background jobs.

### Atomic Cutover (`~30–90s` write pause, `0s` dropped HTTP connections if proxy supports retry)
1. **Quiesce Background Writers (`T = 0s`):** Stop cron scheduler / background workers so nothing writes during DB sync.
2. **Brief Write Freeze & Final DB Sync:**
   - **Postgres:** Set legacy DB to read-only (`ALTER DATABASE <db> SET default_transaction_read_only = on;`) so public reads stay `200 OK`, then stream `pg_dump -Fc -Z 0` → `pg_restore` into the target Postgres volume (or switch the Rust app onto the existing Postgres DB if schema is 100% compatible with zero destructive migrations).
   - **SQLite:** Pause writes briefly, run `sqlite3 prod.db ".backup '/path/to/rust-prod.db'"` (WAL-safe online backup), and verify `PRAGMA integrity_check;`.
3. **Automated Data Integrity Gate (Abort on ANY mismatch):**
   - Compare exact `COUNT(*)` across **every table**, sequence `last_value`s, and foreign key validity between legacy DB and target DB.
   - If even 1 row disagrees: **abort immediately**, re-enable writes on legacy DB, restart legacy crons, and investigate before retrying.
4. **Atomic Reverse-Proxy Flip:**
   - Update reverse proxy upstream (e.g., Caddy `reverse_proxy old:3000` → `reverse_proxy rust-app:3001`, or Nginx `proxy_pass`) and perform a graceful reload (`caddy reload` / `nginx -s reload`).
   - Re-enable background crons pointed at the new Rust service.
   - **Stop** the legacy application container (do **NOT** delete the container image, legacy DB volume, or legacy code yet!).
5. **Immediate Live Post-Cutover Smoke Test (`T + 60s`):**
   - Run the Playwright smoke suite against live `https://<domain>` (homepage, key dynamic pages, login/auth, CSS/font/asset zero-404 check, `/healthz`, `robots.txt`, `sitemap.xml`).
   - Watch live application logs, error rates, and `docker stats` for 15–30 minutes.

---

## 3. Instant Rollback Procedure (`< 5 Seconds` During Cutover)

If any critical regression appears immediately after cutover:
1. Start the stopped legacy app container (`docker compose start <legacy-app>`).
2. Re-enable writes on legacy DB if read-only was left on (`ALTER DATABASE <db> SET default_transaction_read_only = off;`).
3. Flip the reverse proxy back to `<legacy-app>` and gracefully reload (`caddy reload` / `nginx -s reload`).
4. Point crons back to `<legacy-app>` and verify `/healthz` + homepage.

*(If rolling back after live writes occurred during the soak period, export the delta rows from the Rust DB before switching back so no user data is lost.)*

---

## 4. Soak Period Checklist (Recommended: 3–7 Days)

Monitor daily before requesting owner approval to decommission:
- [ ] Zero 5xx spikes or unhandled panics in Rust logs.
- [ ] Zero user-reported CSS, layout, auth, email, or payment regressions.
- [ ] Every scheduled cron / webhook / email flow has executed cleanly at least once in production.
- [ ] Memory, CPU, and disk usage remain flat and leak-free (`docker stats` / host metrics).
- [ ] Backups are running cleanly against the new production database/volumes.

---

## 5. Stage 4B — Owner-Gated Decommissioning Runbook

> **HARD STOP:** Execute ONLY after the soak period is green AND the owner explicitly instructs: *"Decommission legacy now."*

1. **Final Archival Snapshot:**
   - Take an encrypted/off-site archive backup of the legacy database volume and legacy `.env` / config files.
   - Create an annotated git tag right before deleting legacy files:
     `git tag -a pre-decommission-legacy -m "Final snapshot before removing legacy framework"`
2. **Retire Legacy Production Services:**
   - Remove legacy app containers, unused BaaS/ORM/runtime containers, and orphaned volumes from `docker-compose.yml` (or systemd) and prune stopped legacy containers/images.
3. **Retire Staging Subdomain & Artifacts:**
   - Stop and remove `staging.<domain>` containers and staging DB/storage volumes (unless the owner explicitly wants to keep a permanent staging environment).
   - Remove temporary staging reverse-proxy blocks, Basic Auth credentials, and staging DNS records.
4. **Clean the Repository:**
   - Remove legacy framework directories, lockfiles, and dependencies (`next.config.*`, `package.json`/`node_modules` if no longer needed, `prisma/`, legacy Python/Node backend folders).
   - Update `README.md`, `Makefile`, CI workflows, and deployment docs to reflect the lean Rust + Vanilla Web architecture as the single source of truth.
5. **Final Verification:**
   - Run full automated test suite (`cargo test` + Playwright live smoke check).
   - Verify clean production HTTP `200`s, zero broken assets, and record final server RAM/CPU/disk savings.
