# Environment Refresh

How to reset QA, dev, or UAT environments from production data.

## When to Refresh

- Before running a QA/UAT accounting run against fresh production data
- When the environment has drifted too far from prod (stale contracts, missing accounts)
- After a botched QA run that left data in an inconsistent state

## Pre-Refresh Checklist

1. **Broadcast in `#accounting-tech`** — give people at least 5-10 minutes to respond
2. **Verify no conflicts** — active tests, demos, or development work will be destroyed
3. **Do NOT skip the broadcast.** This has caused data loss for other team members.

## Steps

### RDS Refresh (MySQL)

1. Go to [`rds-refresh-pipeline`](https://pipeline.theorchard.io/job/rds-refresh-pipeline/)
2. Click **Build with Parameters**
3. Set:
   - **Service Name** = `royalty-accounting` (or `art-relations` if refreshing that cluster)
   - **Source Environment** = `prod`
   - **Target Environment** = `QA`, `dev`, or `UAT`
   - **Snowflake Refresh** = enabled
4. Click **Build**
5. Wait for completion

### Verify the Refresh

After the refresh, confirm the target environment has current data:

```sql
-- Should return zero for the most recent period (data was in prod but hasn't been re-ingested in QA)
SELECT COUNT(*)
FROM ROYALTY_ACCOUNTING.QA.VW_ABACUS_FACT_SALES_DISTRO_V3
WHERE statement_period_id = <latest_period_id>;

-- Staging should also be empty for the latest period
SELECT COUNT(*)
FROM ROYALTY_ACCOUNTING.QA.STMT_DB_SALES_DISTRO_STAGING
WHERE BATCH_ID = '<latest_batch_id>';
```

### Post-Refresh

After refreshing, if you're running an accounting run in the refreshed environment:

1. Check that no E2E run controllers are present (they may have come from CI)
2. Re-ingest sales data for the target period (see [Run Guide Step 1](run-guide.md#step-1-ingest-a-sales-file))
3. Open a new accounting period (only one per contract type)

## Notes

- The refresh copies the **entire** database from prod. This includes all contracts, accounts, ledger history, etc.
- Snowflake refresh copies the Snowflake replica as well, so both MySQL and Snowflake should be consistent.
- The `art-relations` cluster is separate from `royalty-accounting` — refresh both if needed for a legacy run.
