
# Safe schema changes

To change how a column is stored, ship three times: **expand** (add the new column and keep both in sync), **migrate** (make it required and move the code to it), then **contract** (drop the old one, declared in its header). Each must reach `"outcome": "live"`, exit 0, before the next.

## Ask your agent

```text
Move prices from dollars in "amount" to integer cents in "amount_cents" without downtime, using Agent Cloud's
expand, migrate and contract steps. Ship each step separately and tell me when one needs my approval.
```

You'll approve three releases: the first and last on the console (the agent gives you a link), the middle one in chat.

## Steps

The example moves `requests.amount numeric(12,2)` to `requests.amount_cents bigint`. Start with a running mirror (`agc up --detach`). Timestamps are examples; use the stems `agc migration new` prints in `after` and `until`.

### 1. Expand ship

```bash
agc migration new amount_cents
```

```sql
-- 20261001120000_amount_cents
-- Runs in one transaction. First line "-- agentcloud: no-transaction" opts out.

ALTER TABLE requests ADD COLUMN amount_cents bigint;
UPDATE requests SET amount_cents = round(amount * 100) WHERE amount_cents IS NULL;

CREATE FUNCTION requests_amount_sync() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    IF NEW.amount_cents IS NULL THEN NEW.amount_cents := round(NEW.amount * 100); END IF;
    IF NEW.amount IS NULL THEN NEW.amount := NEW.amount_cents / 100.0; END IF;
  ELSIF NEW.amount IS DISTINCT FROM OLD.amount THEN
    NEW.amount_cents := round(NEW.amount * 100);
  ELSIF NEW.amount_cents IS DISTINCT FROM OLD.amount_cents THEN
    NEW.amount := NEW.amount_cents / 100.0;
  END IF;
  RETURN NEW;
END $$;

CREATE TRIGGER requests_amount_sync BEFORE INSERT OR UPDATE ON requests
  FOR EACH ROW EXECUTE FUNCTION requests_amount_sync();
```

The backfill runs before the trigger exists, and `ADD COLUMN` holds the table's lock until the file commits, so no write slips between them. Add an invariant for the new column, active only once this migration is applied:

```toml
[[check.invariant]]
name  = "cents agree with dollars"
sql   = "SELECT id FROM requests WHERE amount_cents IS DISTINCT FROM round(amount * 100)"
after = "20261001120000_amount_cents"
until = "20261008090000_drop_amount"
```

The code can keep writing `amount`; the trigger fills `amount_cents`.

```bash
agc migrate
agc check
agc ship
```

### 2. Migrate ship

```bash
agc migration new amount_cents_required
```

```sql
-- 20261005090000_amount_cents_required
UPDATE requests SET amount_cents = round(amount * 100) WHERE amount_cents IS NULL;
ALTER TABLE requests ALTER COLUMN amount_cents SET NOT NULL;
```

In the same ship, switch every read and write to `amount_cents`. The trigger fills `amount` for rows the new code writes, so the release that is still live during the switch keeps working.

```bash
agc migrate
agc check
agc ship
```

### 3. Contract ship

Use the stem your step-1 `until` names, or update the `until`:

```bash
agc migration new drop_amount
```

```sql
-- 20261008090000_drop_amount
-- agentcloud: drops requests.amount
DROP TRIGGER requests_amount_sync ON requests;
DROP FUNCTION requests_amount_sync();
ALTER TABLE requests DROP COLUMN amount;
```

```bash
agc migrate
agc check
agc ship
```

Checks with that `until` report `skipped: retired by 20261008090000_drop_amount` once it applies. Write replacements on the new column if needed.

## How it works

**Why three ships.** Production is migrated first and traffic moves to the new code afterwards, so until the switch the previous release runs on the new schema. Expand keeps that previous code working (the trigger fills the column it doesn't know about). Contract runs only after no live code reads the old column.

**Why a trigger and not dual writes.** The trigger also covers writes from the still-live release. With dual writes, rows the old code writes stay `NULL`, your invariants must tolerate `NULL`, and step 2 must backfill again.

**What every migration must keep.** Before the migrations run, Agent Cloud sets every eligible table's primary keys aside from a separate session: on your mirror in `agc migrate`, and on a fresh branch of production in the rehearsal. A table with rows but no primary key fails only if its row count drops. Afterwards it checks:

| Change | Without a declaration | With one |
|---|---|---|
| A row that existed is gone (looked up by its old key, compared as text, so an `int` to `text` key change still matches) | Fails | Still fails: `drops` names tables and columns, not rows |
| A table with data no longer exists (a view left under its name doesn't count) | Fails | `drops <table>`: noted |
| A column with data no longer exists | Fails | `drops <table>.<column>`: noted |
| The old primary key columns were removed | Fails | `rekeys <table>`: noted if the row count didn't drop (or `drops <table>` declares the loss); row counts are compared instead of keys |
| Rows it can't compare by key: a table with no primary key, one over 5,000,000 rows, or one the session can't read | Reported as `rows not proven preserved`, with its fix; never a failure | Same |

The result is the check `no existing row was deleted`, reported by `agc migrate`, shown again by `agc check`, and run in every rehearsal with migrations. Rows not proven preserved in a rehearsal make the release a person's decision in the console. Give such a table a primary key in a migration (both commands warn `Table <name> has no primary key`); every release after that one compares its rows. `unchanged` and `equal:` invariants are proven at the same time ([Testing against production data](/docs/data/migrations.md#testing-against-production-data)).

**Who approves.** A person decides every ship with a pending migration, seeing each declaration in words ("deletes bookings.amount", "gives orders a new primary key"). In this example, steps 1 (`CREATE TRIGGER … EXECUTE FUNCTION` counts as custom SQL) and 3 (it drops data) are console-only. Step 2 can be approved in the agent's session.

**Large tables.** A file is one transaction, so a backfill inside it locks the rows it touches until the file commits. For a large table, backfill in a separate file whose first line is `-- agentcloud: no-transaction`, with an explicit `COMMIT;` after each batch:

```sql
-- agentcloud: no-transaction
UPDATE requests SET amount_cents = round(amount * 100) WHERE id BETWEEN 1 AND 100000 AND amount_cents IS NULL;
COMMIT;
-- …and so on, one UPDATE and COMMIT per batch
```

Without the `COMMIT;` lines, Postgres runs the file as one implicit transaction anyway. A failure halfway leaves earlier batches applied and the file unrecorded, and nothing undoes them, so make each batch safe to run twice.

## Migration header directives

`no-transaction` runs a file outside a transaction (for `CREATE INDEX CONCURRENTLY`). `drops` and `rekeys` declare data you mean to remove or re-key. Without them, `no existing row was deleted` fails on your mirror (`agc migrate`, exit 11) and in the rehearsal.

| Directive | Where | Allows | Still refused |
|---|---|---|---|
| `-- agentcloud: no-transaction` | First non-blank content; any line before it, a comment included, disables it | Running without `BEGIN`/`COMMIT`; a failure isn't rolled back | |
| `-- agentcloud: drops <name>, …` (`drops orders`, `drops bookings.child_name`) | Any comment line before the first SQL | Dropping that table or column (`schema.table` outside `public`) while it holds data: noted, not failed | Deleting rows from a table that remains |
| `-- agentcloud: rekeys <table>, …` | Same | A new primary key replacing the old key columns | Fewer rows, unless `drops <table>` is also declared |

Matching is case-insensitive and names are lowercased. The header ends at the first line that isn't blank and doesn't start with `--`. Several files' declarations add up across one `agc migrate` or one ship.

## Errors

Every code, its exit and fix: [Error code catalog](/docs/reference/error-code-catalog.md). An undeclared drop on the mirror:

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "migrate",
  "error": {
    "code": "migrate.not_preserved",
    "message": "The migrations applied, but no existing row was deleted: undeclared: dropped requests.amount (a migration that means it says `-- agentcloud: drops <table>[.<column>]` or `rekeys <table>`).",
    "fix": "Fix the migration (it changed or lost data it should keep), then `agc db reset` and `agc migrate` again.",
    "retryable": false,
    "docs": "agc help checks"
  },
  "next": [{ "cmd": "agc db reset", "why": "start over from a fresh masked branch of production" }]
}
```

## Limits

| What | Value |
|---|---|
| Proof session timeout | 120 s per statement; `unchanged` digests 60 s |

## Agent notes

- Each ship must reach `"outcome": "live"` with exit 0 before you start the next.
- Migrations always run before the traffic switch, so split a change the live release can't run (a one-ship `ADD COLUMN … NOT NULL`) into expand, migrate and contract yourself.
- Don't use migrations to delete rows from a table you keep.
- `after` and `until` don't apply to `unchanged` and `equal:` invariants: they're measured around every ship's migrations. One that reads a column the ship drops fails with "it couldn't run after the migrations", so rewrite it to the new column in the migrate ship.
- Adding `until` to a [held check](/docs/checks/invariants.md#held-checks-and-fixes) is a change, decided by a person on the console.
- If a person says "ship it" for the whole change, ship steps 1 and 2, each to `live`, then submit step 3 and relay its approval.
- `agc migration new <slug>` writes two comment lines at the top; put `no-transaction` above them, as line 1. Below them it's ignored, and `CREATE INDEX CONCURRENTLY` fails inside the transaction.
- `DROP`, `TRUNCATE` or `DELETE` goes to a person in the console whatever the header says. Use `drops` only in the contract step.

## Related

- [Migrations](/docs/data/migrations.md)
- [Invariants](/docs/checks/invariants.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "data/safe-schema-changes: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
