# Rebuild on apply and on revert

## Goal

A migration can request a rebuild of dependent objects separately for its up script and its down script, and mitch performs it on every path that applies or reverts migrations. A second question rides along: whether a fresh deployment takes the shortest path or the same path an existing deployment takes.

## Why

### The direction matters, not the migration

Whether a rebuild is needed depends on the script that runs. Example on PostgreSQL: the up script extends a view with `CREATE OR REPLACE VIEW`, adding a column at the end, which works while other objects depend on the view. The down script has to remove that column again, which `CREATE OR REPLACE VIEW` cannot do; it needs `DROP VIEW`, which fails while a materialized view, a policy or another view depends on it. Here the revert needs the rebuild, the apply does not.

Reworks produce exactly this pattern. `mitch rework` prefills the new version's down script with the previous up script. If the new version only adds a column, the down script recreates the view without it and fails on PostgreSQL as soon as something depends on the view. Every path that reverts is affected: `drop`, `down`, redeploys of modified migrations, `checkout` back across a rework, and `stash` of a rework in progress.

### Not every path rebuilds today

`rebuild_dependants_of` only acts when a migration is applied by `up`, `add` or `checkout --and-up`. Re-applying in `checkout` without `--and-up`, in `stash`, and in `up --watch` does not rebuild, and no revert rebuilds.

### Shortest path or upgrade path

For the rework example from ADR `runner/rebuild-reapplies-dependants-after-the-new-version`, an existing deployment records

```
orders, order-summary, summary-report,
summary-report (revert), order-summary@2, summary-report
```

and a fresh deployment currently records the same, so that both share one history. On a fresh deployment it is fair to ask why `summary-report` is applied only to be reverted right away. The shortest path would be:

```
orders, order-summary, order-summary@2, summary-report
```

The end state of the rebuilt objects is the same, because their up scripts run last against the same new version in both paths; differences stay at catalog level, such as OIDs. The proposal from the design discussion: the shortest path by default, and a flag (working title `--upgrade-path`) for the path an existing deployment takes, so that CI can test what production will run.

Points raised so far:

- A rebuild is not necessarily cheap on a fresh deployment: a materialized view can read from external sources, for example through a foreign data wrapper.
- Replaying a recorded order (see [Freeze](freeze.md)) always takes the recorded path.
- On a fresh deployment, the shortest path conflicts with the ordering constraints a rework writes; see [Ordering constraints in the shortest path](#ordering-constraints-in-the-shortest-path).
- The audit table could record why an entry happened, for example "rebuild for `order-summary@2`", so that `log` explains the revert-and-re-apply steps instead of showing them unexplained.

### Ordering constraints in the shortest path

The intent for a rebuild in the shortest path, in two lines:

- A dependant that is already applied is rebuilt.
- A dependant that is part of the run is sorted after the new version.

#### Terms

*Part of the run* means the migrations the current command will apply: for `mitch up`, the project's own migrations plus the linked ones they require; for `mitch add A B C`, the named migrations plus everything they depend on transitively. In both cases only those not yet applied. Migrations already applied are *applied*, not part of the run.

For an ordering constraint `after = ["X"]` on B:

| Situation | Constraint active? | Effect |
|---|---|---|
| X is applied | yes | met; X is already before B |
| X is part of the run | yes | mitch sorts B after X |
| X is neither | no | X is not rolled out, B runs anyway |

With `mitch add`: `add B` leaves X out and the constraint inactive; `add B X` applies X, then B; `add A B`, where A depends on X, brings X into the run as a dependency, so B again runs after X. Only the second row matters for sorting. The first matters when the order is reversed, that is when B is applied and X arrives later (late arrival, with a warning or `--restore-order`).

An active constraint is *enforced* in a run when mitch has to sort the migration behind X. When it is not enforced, mitch sorts as if the line were not there.

#### Why the rework's constraints get in the way

A rework writes the dependants of the previous version into `after`. If those constraints are enforced, a fresh deployment applies the dependants before the new version, and the rebuild then has to revert and re-apply them: that is the upgrade path, not the shortest one. The shortest path needs the opposite order. Enforcing the constraints is therefore the cause of the long path, not a way around it.

Proposed rule, which needs no new syntax: in the shortest path, mitch does not enforce those `after` constraints of a migration whose target depends on one of the migrations in the same migration's `rebuild_dependants_of`. All other ordering constraints stay enforced. With the upgrade-path flag, all are enforced, as today.

#### Example

Five migrations:

- `orders` creates a table.
- `order-summary` creates the view `order_summary` and depends on `orders`.
- `summary-report` creates the view `summary_report` and depends on `order-summary`, so it is a dependant.
- `add-status-shipped` adds an enum value and depends only on `orders`, not on `order-summary`.
- `order-summary@2` comes from `mitch rework`, with the rebuild enabled and `add-status-shipped` added to `after` by hand:

```toml
id = "order-summary@2"
dependencies = ["order-summary"]
after = ["summary-report", "add-status-shipped"]
rebuild_dependants_of = ["order-summary"]
```

The rule sorts the ordering constraints by asking, for each target, whether it depends on `order-summary`:

| Target of `after` | Depends on `order-summary`? | In the shortest path |
|---|---|---|
| `summary-report` | yes | not enforced: rebuilt if applied, otherwise sorted after `order-summary@2` |
| `add-status-shipped` | no | enforced |

Three runs of `mitch up`:

1. Existing deployment, everything but `order-summary@2` applied:
   ```
   summary-report (revert), order-summary@2, summary-report
   ```
   `summary-report` was there, so the rebuild handles it. `add-status-shipped` was there, so its constraint is already met.
2. Fresh deployment, shortest path:
   ```
   orders, order-summary, add-status-shipped, order-summary@2, summary-report
   ```
   `add-status-shipped` comes before `order-summary@2` because its constraint is enforced. `summary-report` comes after, because its constraint is not; it is created against the new view right away, without a revert.
3. Fresh deployment with the upgrade-path flag:
   ```
   orders, order-summary, summary-report, add-status-shipped,
   summary-report (revert), order-summary@2, summary-report
   ```
   Both constraints are enforced, as today. This is the path of the existing deployment, which is what CI should test.

Open case: someone writes `summary-report` into `after` by hand because `order-summary@2` really must run after it, and enables the rebuild. Mitch cannot tell that constraint from the one `rework` wrote; while the rebuild is enabled, the rule would not enforce it in the shortest path.

#### Effect on sorting

The algorithm stays a topological sort with creation time as the tie-break within each step; only the set of edges changes before sorting. That is already the case today, where active ordering constraints between migrations of the run are added to the dependencies. For a migration M with `rebuild_dependants_of`, the shortest path changes the edge set twice:

1. M's ordering constraints on dependants of the rebuilt migrations are left out.
2. For each of those dependants that is part of the run, the reverse edge is added: the dependant runs after M.

Step 2 is needed. With the constraint merely left out, `summary-report` and `order-summary@2` become ready at the same time once `order-summary` is done, and the tie-break decides; `summary-report` is older and would come first, which is the long path again, by accident instead of on purpose.

To keep in mind:

- **Cycles at run time.** The reversed edge can form a cycle that the check at load time does not see, for example when M has a real dependency on a dependant it also asks to rebuild. That configuration contradicts itself. The sorter notices the cycle at once, but mitch has to report it as an error message, not a traceback.
- **The edge set depends on the mode.** The shortest path and the upgrade path sort the same graph with differently directed edges. One test per mode with the example above would cover it.
- **Cost.** Mitch needs the dependants of the rebuilt migrations, a closure it already computes for the rebuild itself.

## Already settled

- Rebuilds go through mitch's migration graph instead of catalog walks: ADR `runner/rebuild-dependants-through-the-migration-graph`.
- Today a rebuild re-applies dependants after the new version, and fresh and existing deployments share one history: ADR `runner/rebuild-reapplies-dependants-after-the-new-version`. This topic reopens that decision.
- A reworked version depends on its previous version, which every deployment runs first: ADR `cli/rework/rework-keeps-the-previous-version-in-every-history`.
- Up and down scripts are also told apart in [Destructive scripts](destructive-scripts.md); both topics may share a configuration shape.
