Public repository: timo / mitch

Reader

A migration stitcher (therefore mitch) for PostgreSQL, SQLite, MariaDB, and others

feat: add ordering constraints via `after`

public

feat: add ordering constraints via `after`

Order migrations without pulling their targets onto a deployment.
Constraints are stored as edges of kind `ordering`, so a late target
is detected even when the declaring project isn't loaded. Default
warns and proceeds; --restore-order reverts and re-applies in one
transaction (--allow-autocommit for non-transactional ones).

Refs #2
Changesetc8f11ab639692f4e441c5ff666e365b5f67f251f
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents606f4271c456
Children
Pushlog
by timo via ssh

modified src/mitch/cli/deploy.py +118 −14

@@ -1,3 +1,4 @@
1
+from contextlib import nullcontext
12
 from enum import Enum
23
 from pathlib import Path
34
 from typing import Annotated, Callable, Iterable
@@ -6,13 +7,13 @@
67
 import typer
78
 from rich.prompt import Confirm
89
 
9
-from ..errors import CannotAddLinkedMigrationError
10
+from ..errors import BlockedRevertError, CannotAddLinkedMigrationError
1011
 from ..helpers import connection_for
11
-from ..migration import Migration
12
+from ..migration import Migration, MigrationKey
1213
 from ..project import Project
1314
 from ..runner import DeploymentStatus, Runner
1415
 from ..watcher import EventType
15
-from .revert import refuse_revert_if_blocked
16
+from .revert import ensure_rebuild_is_safe, refuse_revert_if_blocked
1617
 
1718
 
1819
 class IfModifiedOption(str, Enum):
@@ -23,6 +24,22 @@
2324
 
2425
 
2526
 app = typer.Typer()
27
+
28
+RestoreOrderOption = Annotated[
29
+    bool,
30
+    typer.Option(
31
+        "--restore-order",
32
+        help="When a migration arrives after migrations ordered after it, revert and re-apply those instead of warning.",
33
+    ),
34
+]
35
+
36
+AllowAutocommitOption = Annotated[
37
+    bool,
38
+    typer.Option(
39
+        "--allow-autocommit",
40
+        help="Allow reverting and re-applying around a change in autocommit mode when non-transactional migrations take part.",
41
+    ),
42
+]
2643
 
2744
 LateDependenciesOption = Annotated[
2845
     bool,
@@ -129,11 +146,58 @@
129146
     )
130147
 
131148
 
149
+def _late_arrivals(runner: Runner, to_apply: list[Migration]) -> dict[Migration, set[MigrationKey]]:
150
+    """Pending migrations that applied migrations are ordered after, with those migrations' keys."""
151
+    late = {}
152
+    for migration in to_apply:
153
+        if runner.deployment_status(migration) == "pending":
154
+            ordered_after = runner.applied_dependants(migration, kind="ordering")
155
+            if ordered_after:
156
+                late[migration] = ordered_after
157
+    return late
158
+
159
+
160
+def _key_name(project: Project, key: MigrationKey) -> str:
161
+    loaded = {m.key: m for m in project.all_migrations}
162
+    return project.display_name(loaded[key]) if key in loaded else f"{key[0]}:{key[1]}"
163
+
164
+
165
+def _restore_order(
166
+    project: Project,
167
+    runner: Runner,
168
+    to_apply: list[Migration],
169
+    late: dict[Migration, set[MigrationKey]],
170
+    allow_autocommit: bool,
171
+) -> tuple[set[Migration], set[Migration]]:
172
+    """Revert the migrations ordered after late arrivals.
173
+
174
+    Returns the reverted migrations and those among them that were applied for their own sake.
175
+    """
176
+    loaded = {m.key: m for m in project.all_migrations}
177
+    keys = set().union(*late.values())
178
+    if unknown := {key for key in keys if key not in loaded}:
179
+        raise BlockedRevertError(unknown)
180
+    to_revert = [m for m in project.with_dependants(loaded[key] for key in keys) if runner.is_recorded(m)]
181
+    refuse_revert_if_blocked(project, runner, to_revert)
182
+    ensure_rebuild_is_safe(project, to_revert, to_apply, allow_autocommit)
183
+    requested = {m for m in to_revert if not runner.is_pulled_in(m)}
184
+    _revert_with_feedback(
185
+        runner,
186
+        to_revert,
187
+        lambda migration, status: (
188
+            f"[blue]Reverting:[/blue] Migration '{project.display_name(migration)}' ({status}) to restore the order."
189
+        ),
190
+    )
191
+    return set(to_revert), requested
192
+
193
+
132194
 def _apply_planned_migrations(
133195
     project: Project,
134196
     runner: Runner,
135197
     covered_migrations: set[Migration],
136198
     redeploy: set[Migration],
199
+    restore_order: bool = False,
200
+    allow_autocommit: bool = False,
137201
 ) -> None:
138202
     to_revert = list(project.with_dependants(redeploy))
139203
     refuse_revert_if_blocked(project, runner, to_revert)
@@ -153,14 +217,32 @@
153217
         if runner.deployment_status(migration) == "pending"
154218
     }
155219
     to_apply = list(project.with_dependencies(pending | redeploy))
156
-    _deploy_with_feedback(
157
-        project,
158
-        runner,
159
-        to_apply,
160
-        lambda migration, status: (
161
-            f"[green]Deploying:[/green] Migration '{project.display_name(migration)}' ({status})"
162
-        ),
163
-    )
220
+
221
+    def deploy(migrations: list[Migration]) -> None:
222
+        _deploy_with_feedback(
223
+            project,
224
+            runner,
225
+            migrations,
226
+            lambda migration, status: (
227
+                f"[green]Deploying:[/green] Migration '{project.display_name(migration)}' ({status})"
228
+            ),
229
+        )
230
+
231
+    late = _late_arrivals(runner, to_apply)
232
+    if late and restore_order:
233
+        transactional = not allow_autocommit
234
+        with runner.atomic() if transactional else nullcontext():
235
+            reverted, requested = _restore_order(project, runner, to_apply, late, allow_autocommit)
236
+            requested_before |= requested
237
+            deploy(list(project.with_dependencies(set(to_apply) | reverted)))
238
+    else:
239
+        for migration, keys in late.items():
240
+            rich.print(
241
+                f"[yellow]Warning:[/yellow] Applying '{project.display_name(migration)}' after "
242
+                f"{', '.join(repr(_key_name(project, key)) for key in sorted(keys))}, which are ordered after it. "
243
+                f"The order deviates from the graph; use --restore-order to revert and re-apply them."
244
+            )
245
+        deploy(to_apply)
164246
     runner.mark_requested(m for m in requested_before if runner.is_recorded(m))
165247
 
166248
 
@@ -223,6 +305,8 @@
223305
     watch: bool,
224306
     allow_new_migrations: bool,
225307
     late_dependencies: bool = False,
308
+    restore_order: bool = False,
309
+    allow_autocommit: bool = False,
226310
 ) -> None:
227311
     project = Project.from_path(root)
228312
     requested = project.resolve_all(migration_ids)
@@ -236,7 +320,9 @@
236320
         runner = Runner(connection)
237321
         runner.sync_edges(project.all_migrations)
238322
         redeploy = _collect_redeploy_migrations(project, runner, covered_migrations, if_modified, late_dependencies)
239
-        _apply_planned_migrations(project, runner, covered_migrations, redeploy)
323
+        _apply_planned_migrations(
324
+            project, runner, covered_migrations, redeploy, restore_order=restore_order, allow_autocommit=allow_autocommit
325
+        )
240326
         runner.mark_requested(m for m in requested if runner.is_recorded(m))
241327
 
242328
         if not watch:
@@ -278,9 +364,21 @@
278364
         typer.Option("--watch", help="Watch the project and re-run deployments on changes."),
279365
     ] = False,
280366
     late_dependencies: LateDependenciesOption = False,
367
+    restore_order: RestoreOrderOption = False,
368
+    allow_autocommit: AllowAutocommitOption = False,
281369
 ) -> None:
282370
     """Apply the specified migrations in the project."""
283
-    run_deploy(migration_ids, root, database_url, if_modified, watch, allow_new_migrations=False, late_dependencies=late_dependencies)
371
+    run_deploy(
372
+        migration_ids,
373
+        root,
374
+        database_url,
375
+        if_modified,
376
+        watch,
377
+        allow_new_migrations=False,
378
+        late_dependencies=late_dependencies,
379
+        restore_order=restore_order,
380
+        allow_autocommit=allow_autocommit,
381
+    )
284382
 
285383
 
286384
 def run_up(
@@ -289,6 +387,8 @@
289387
     if_modified: IfModifiedOption | None = None,
290388
     watch: bool = False,
291389
     late_dependencies: bool = False,
390
+    restore_order: bool = False,
391
+    allow_autocommit: bool = False,
292392
 ) -> None:
293393
     project = Project.from_path(root)
294394
     run_deploy(
@@ -299,6 +399,8 @@
299399
         watch,
300400
         allow_new_migrations=True,
301401
         late_dependencies=late_dependencies,
402
+        restore_order=restore_order,
403
+        allow_autocommit=allow_autocommit,
302404
     )
303405
 
304406
 
@@ -322,6 +424,8 @@
322424
         typer.Option("--watch", help="Watch the project and re-run deployments on changes."),
323425
     ] = False,
324426
     late_dependencies: LateDependenciesOption = False,
427
+    restore_order: RestoreOrderOption = False,
428
+    allow_autocommit: AllowAutocommitOption = False,
325429
 ) -> None:
326430
     """Apply all pending migrations in the project, plus the linked migrations they require."""
327
-    run_up(root, database_url, if_modified, watch, late_dependencies)
431
+    run_up(root, database_url, if_modified, watch, late_dependencies, restore_order, allow_autocommit)

modified src/mitch/cli/revert.py +16 −1

@@ -4,7 +4,7 @@
44
 import rich
55
 import typer
66
 
7
-from ..errors import BlockedRevertError
7
+from ..errors import BlockedRevertError, UnsafeRebuildError
88
 from ..helpers import connection_for
99
 from ..migration import Migration
1010
 from ..project import Project
@@ -46,6 +46,21 @@
4646
         raise BlockedRevertError(blockers)
4747
 
4848
 
49
+def ensure_rebuild_is_safe(
50
+    project: Project, to_revert: list[Migration], to_apply: list[Migration], allow_autocommit: bool
51
+) -> None:
52
+    """A rebuild is all or nothing: everything reverted needs a down script, and everything must run in
53
+    one transaction unless autocommit is explicitly allowed (ADR runner/rebuild-dependants-through-the-migration-graph)."""
54
+    without_down = [project.display_name(m) for m in to_revert if m.down_script is None]
55
+    if without_down:
56
+        raise UnsafeRebuildError("no down script", without_down)
57
+    non_transactional = [project.display_name(m) for m in {*to_revert, *to_apply} if not m.transactional]
58
+    if non_transactional and not allow_autocommit:
59
+        raise UnsafeRebuildError(
60
+            "non-transactional migrations cannot be rolled back (allow with --allow-autocommit)", non_transactional
61
+        )
62
+
63
+
4964
 def revert_orphans(project: Project, runner: Runner) -> None:
5065
     """Revert linked migrations that were pulled in and are no longer needed by any applied migration."""
5166
     while orphans := [

modified src/mitch/errors.py +8 −0

@@ -102,3 +102,11 @@
102102
             f"Cannot revert: applied migrations of projects that are not loaded depend on it: {listed}. "
103103
             f"Revert them from their own projects first."
104104
         )
105
+
106
+
107
+class UnsafeRebuildError(MitchError):
108
+    """Raised when migrations would have to be reverted and re-applied, but that cannot be done safely."""
109
+
110
+    def __init__(self, reason: str, migrations: Iterable[str]):
111
+        listed = ", ".join(sorted(migrations))
112
+        super().__init__(f"Cannot revert and re-apply around this change: {reason}: {listed}.")

modified src/mitch/migration.py +3 −0

@@ -25,10 +25,13 @@
2525
 
2626
     # References as written in the config: own migration IDs or qualified IDs (`alias:migration`).
2727
     dependencies: set[str] = field(default_factory=set, repr=False)
28
+    # Ordering constraints: run after these when they are applied or in the same run, without requiring them.
29
+    after: set[str] = field(default_factory=set, repr=False)
2830
     project: "Project | None" = field(default=None, repr=False)
2931
 
3032
     # Filled in when the project graph is built.
3133
     resolved_dependencies: set["Migration"] = field(default_factory=set, repr=False)
34
+    resolved_after: set["Migration"] = field(default_factory=set, repr=False)
3235
 
3336
     @property
3437
     def project_id(self) -> str | None:

modified src/mitch/project.py +39 −17

@@ -140,6 +140,7 @@
140140
                         idempotent=config.get("idempotent", False),
141141
                         created_at=self._created_at_from_config(config.get("created_at"), config_file),
142142
                         dependencies={*config.get("dependencies", [])},
143
+                        after={*config.get("after", [])},
143144
                         project=self,
144145
                     )
145146
                 )
@@ -215,35 +216,54 @@
215216
         self._canonical = canonical
216217
 
217218
         self._dependants: dict[Migration, set[Migration]] = defaultdict(set)
219
+        self._ordered_after: dict[Migration, set[Migration]] = defaultdict(set)
218220
         for migration in canonical.values():
219221
             migration.resolved_dependencies.clear()
220
-            assert migration.project is not None
221
-            for reference in migration.dependencies:
222
-                try:
223
-                    target = migration.project._resolve_in_scope(reference, canonical)
224
-                except (UnknownAliasError, MissingMigrationError) as error:
225
-                    if self._loader.strict:
226
-                        raise
227
-                    self.warnings.append(str(error))
228
-                    continue
229
-                migration.resolved_dependencies.add(target)
230
-                self._dependants[target].add(migration)
222
+            migration.resolved_after.clear()
223
+            for dependency in self._resolve_references(migration, migration.dependencies, canonical):
224
+                migration.resolved_dependencies.add(dependency)
225
+                self._dependants[dependency].add(migration)
226
+            for predecessor in self._resolve_references(migration, migration.after, canonical):
227
+                migration.resolved_after.add(predecessor)
228
+                self._ordered_after[predecessor].add(migration)
231229
 
232230
         # Copies must also agree on what a migration depends on, or consumers would keep rewriting its edges.
233231
         for copy in copies:
234232
             assert copy.project is not None
235233
             original = canonical[copy.key]
236234
             try:
237
-                copy_dependencies = {copy.project._resolve_in_scope(r, canonical).key for r in copy.dependencies}
235
+                copy_references = (
236
+                    {copy.project._resolve_in_scope(r, canonical).key for r in copy.dependencies},
237
+                    {copy.project._resolve_in_scope(r, canonical).key for r in copy.after},
238
+                )
238239
             except (UnknownAliasError, MissingMigrationError):
239
-                copy_dependencies = None
240
-            if copy_dependencies != {d.key for d in original.resolved_dependencies}:
240
+                copy_references = None
241
+            original_references = (
242
+                {d.key for d in original.resolved_dependencies},
243
+                {a.key for a in original.resolved_after},
244
+            )
245
+            if copy_references != original_references:
241246
                 raise ConflictingCopiesError(copy.project_id or "", copy.id, original.up_script, copy.up_script)
242247
 
243248
         try:
244
-            TopologicalSorter({m: m.resolved_dependencies for m in canonical.values()}).prepare()
249
+            TopologicalSorter({m: m.resolved_dependencies | m.resolved_after for m in canonical.values()}).prepare()
245250
         except CycleError as error:
246251
             raise MigrationCycleError(self.display_name(m) for m in error.args[1]) from None
252
+
253
+    def _resolve_references(
254
+        self, migration: Migration, references: Iterable[str], canonical: dict[MigrationKey, Migration]
255
+    ) -> list[Migration]:
256
+        """Resolve references written in `migration`'s project; in lenient mode, skip and warn."""
257
+        assert migration.project is not None
258
+        resolved = []
259
+        for reference in references:
260
+            try:
261
+                resolved.append(migration.project._resolve_in_scope(reference, canonical))
262
+            except (UnknownAliasError, MissingMigrationError) as error:
263
+                if self._loader.strict:
264
+                    raise
265
+                self.warnings.append(str(error))
266
+        return resolved
247267
 
248268
     def _resolve_in_scope(self, reference: str, canonical: dict[MigrationKey, Migration]) -> Migration:
249269
         """Resolve a reference as written inside this project."""
@@ -393,12 +413,14 @@
393413
     def with_dependencies(self, migrations: Iterable[Migration]) -> Iterable[Migration]:
394414
         """The migrations plus everything they transitively depend on, dependencies first."""
395415
         nodes = self._closure(migrations, lambda m: m.resolved_dependencies)
396
-        yield from self._iter_sorted({m: m.resolved_dependencies & nodes for m in nodes})
416
+        yield from self._iter_sorted({m: (m.resolved_dependencies | m.resolved_after) & nodes for m in nodes})
397417
 
398418
     def with_dependants(self, migrations: Iterable[Migration]) -> Iterable[Migration]:
399419
         """The migrations plus everything that transitively depends on them, dependants first."""
400420
         nodes = self._closure(migrations, lambda m: self._dependants.get(m, set()))
401
-        yield from self._iter_sorted({m: self._dependants.get(m, set()) & nodes for m in nodes})
421
+        yield from self._iter_sorted(
422
+            {m: (self._dependants.get(m, set()) | self._ordered_after.get(m, set())) & nodes for m in nodes}
423
+        )
402424
 
403425
     def __iter__(self) -> Generator[Migration, None, None]:
404426
         yield from self.with_dependencies(self.migrations)

modified src/mitch/runner.py +32 −14

@@ -11,11 +11,13 @@
1111
 from .sql import script_hashes, split_statements
1212
 
1313
 DeploymentStatus: TypeAlias = Literal["pending", "applied", "modified"]
14
+EdgeKind: TypeAlias = Literal["dependency", "ordering"]
1415
 
1516
 
1617
 class Runner:
1718
     def __init__(self, connection: Connection) -> None:
18
-        self._pending_work = []
19
+        self._pending_work: list[str] = []
20
+        self._atomic = False
1921
         self.connection = connection
2022
         self._project_local_ids: dict[str, int] = {}
2123
         sa.event.listen(self.connection, "commit", self._on_commit)
@@ -182,7 +184,21 @@
182184
             self.connection.commit()
183185
 
184186
     @contextmanager
187
+    def atomic(self):
188
+        """Run everything inside in one transaction, including reverts and applies that open their own."""
189
+        self._commit_transaction_if_open_but_empty()
190
+        with self.connection.begin():
191
+            self._atomic = True
192
+            try:
193
+                yield self
194
+            finally:
195
+                self._atomic = False
196
+
197
+    @contextmanager
185198
     def transaction(self):
199
+        if self._atomic:
200
+            yield self
201
+            return
186202
         self._commit_transaction_if_open_but_empty()
187203
         with self.connection.begin() as transaction:
188204
             try:
@@ -255,21 +271,20 @@
255271
     # ------------------------------------------------------------------ dependency edges
256272
 
257273
     def _write_edges(self, migration: Migration) -> None:
274
+        """Replace the recorded dependencies and ordering constraints of `migration` with its source."""
258275
         local_key = self._local_key(migration)
259
-        self.connection.execute(
260
-            self.edge_table.delete().where(
261
-                sa.and_(self._key_filter(self.edge_table, local_key), self.edge_table.c.kind == 'dependency')
262
-            )
263
-        )
264
-        for dependency in migration.resolved_dependencies:
265
-            dependency_local_id, dependency_id = self._local_key(dependency)
276
+        self.connection.execute(self.edge_table.delete().where(self._key_filter(self.edge_table, local_key)))
277
+        edges = [(d, 'dependency') for d in migration.resolved_dependencies]
278
+        edges += [(a, 'ordering') for a in migration.resolved_after]
279
+        for other, kind in edges:
280
+            other_local_id, other_id = self._local_key(other)
266281
             self.connection.execute(
267282
                 self.edge_table.insert().values(
268283
                     project_id=local_key[0],
269284
                     migration_id=local_key[1],
270
-                    dependency_project_id=dependency_local_id,
271
-                    dependency_migration_id=dependency_id,
272
-                    kind='dependency',
285
+                    dependency_project_id=other_local_id,
286
+                    dependency_migration_id=other_id,
287
+                    kind=kind,
273288
                 )
274289
             )
275290
 
@@ -280,8 +295,11 @@
280295
                 if self.is_recorded(migration):
281296
                     self._write_edges(migration)
282297
 
283
-    def applied_dependants(self, migration: Migration) -> set[MigrationKey]:
284
-        """(project ID, migration ID) of applied migrations recorded as depending on `migration`."""
298
+    def applied_dependants(self, migration: Migration, kind: EdgeKind = 'dependency') -> set[MigrationKey]:
299
+        """(project ID, migration ID) of applied migrations recorded as depending on `migration`.
300
+
301
+        With kind 'ordering': applied migrations recorded as ordered after `migration`.
302
+        """
285303
         project_local_id, migration_id = self._local_key(migration)
286304
         dependant_project = self.project_table.alias('dependant_project')
287305
         rows = self.connection.execute(
@@ -301,7 +319,7 @@
301319
                 sa.and_(
302320
                     self.edge_table.c.dependency_project_id == project_local_id,
303321
                     self.edge_table.c.dependency_migration_id == migration_id,
304
-                    self.edge_table.c.kind == 'dependency',
322
+                    self.edge_table.c.kind == kind,
305323
                 )
306324
             )
307325
         )

modified src/mitch/transition.py +1 −0

@@ -20,6 +20,7 @@
2020
         _normalized(migration.up_script),
2121
         _normalized(migration.down_script),
2222
         tuple(sorted(migration.dependencies)),
23
+        tuple(sorted(migration.after)),
2324
         migration.transactional,
2425
         migration.idempotent,
2526
     )

modified tests/test_rework.py +81 −0

@@ -92,3 +92,84 @@
9292
     assert result.exit_code == 0, result.output
9393
     assert audit(tmp_path)[history_before:] == [("answer@2", "reverted")]
9494
     assert applied_ids(tmp_path) == {"answer", "reader"}
95
+
96
+
97
+# ---------------------------------------------------------------- ordering constraints
98
+
99
+
100
+def table(name: str) -> tuple[str, str]:
101
+    return f"CREATE TABLE {name} (id int);", f"DROP TABLE {name};"
102
+
103
+
104
+def test_ordering_constraint_runs_a_migration_after_another_in_the_same_run(tmp_path):
105
+    root = new_project(tmp_path / "app")
106
+    # Without the constraint, "early" would sort first by creation time.
107
+    write_migration(root, "late", *table("late"), 'created_at = 2026-02-01\n')
108
+    write_migration(root, "early", *table("early"), 'created_at = 2026-01-01\nafter = ["late"]\n')
109
+
110
+    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))
111
+
112
+    assert result.exit_code == 0, result.output
113
+    assert [m for m, _ in audit(tmp_path)] == ["late", "early"]
114
+
115
+
116
+def test_ordering_constraint_does_not_pull_in_its_target(tmp_path):
117
+    root = new_project(tmp_path / "app")
118
+    write_migration(root, "optional", *table("optional"))
119
+    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
120
+
121
+    result = mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))
122
+
123
+    assert result.exit_code == 0, result.output
124
+    assert applied_ids(tmp_path) == {"main"}
125
+
126
+
127
+def test_cycle_of_dependency_and_ordering_constraint_is_an_error(tmp_path):
128
+    root = new_project(tmp_path / "app")
129
+    write_migration(root, "a", *table("a"), 'after = ["b"]\n')
130
+    write_migration(root, "b", *table("b"), 'dependencies = ["a"]\n')
131
+
132
+    result = mitch("up", "-p", str(root), "-d", db_url(tmp_path))
133
+
134
+    assert result.exit_code == 1
135
+    assert "cycle" in result.output
136
+
137
+
138
+def test_late_target_of_ordering_constraint_is_applied_with_a_warning(tmp_path):
139
+    root = new_project(tmp_path / "app")
140
+    write_migration(root, "optional", *table("optional"))
141
+    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
142
+    mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))
143
+
144
+    result = mitch("add", "optional", "-p", str(root), "-d", db_url(tmp_path))
145
+
146
+    assert result.exit_code == 0, result.output
147
+    assert "Warning" in result.output and "main" in result.output
148
+    assert audit(tmp_path) == [("main", "applied"), ("optional", "applied")]
149
+
150
+
151
+def test_restore_order_reverts_and_reapplies_around_a_late_target(tmp_path):
152
+    root = new_project(tmp_path / "app")
153
+    write_migration(root, "optional", *table("optional"))
154
+    write_migration(root, "main", *table("main"), 'after = ["optional"]\n')
155
+    mitch("add", "main", "-p", str(root), "-d", db_url(tmp_path))
156
+
157
+    result = mitch("add", "optional", "--restore-order", "-p", str(root), "-d", db_url(tmp_path))
158
+
159
+    assert result.exit_code == 0, result.output
160
+    assert audit(tmp_path)[1:] == [("main", "reverted"), ("optional", "applied"), ("main", "applied")]
161
+
162
+
163
+def test_late_target_is_detected_through_the_recorded_constraint_of_a_project_not_loaded(tmp_path):
164
+    users = new_project(tmp_path / "users", "org.example.users")
165
+    write_migration(users, "create-users", *table("users"))
166
+    reports = new_project(tmp_path / "reports", "org.example.reports")
167
+    (reports / "mitch.toml").write_text('[project]\nid = "org.example.reports"\n\n[projects]\nu = "../users"\n', encoding="utf-8")
168
+    write_migration(reports, "report", *table("report"), 'after = ["u:create-users"]\n')
169
+    mitch("up", "-p", str(reports), "-d", db_url(tmp_path))
170
+    assert applied_ids(tmp_path) == {"report"}
171
+
172
+    result = mitch("up", "-p", str(users), "-d", db_url(tmp_path))
173
+
174
+    assert result.exit_code == 0, result.output
175
+    assert "Warning" in result.output and "org.example.reports:report" in result.output