@neralabs/rerail-pack-alembic 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,449 @@
1
- # Temporary Holding Version
1
+ # Rerail rule pack: Alembic
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `alembic-practice-*` rules are Rerail's own; none is a port of a linter rule. They catch the Alembic migrations
4
+ that fail at deploy or cannot be trusted later: concurrent index builds left in the migration's transaction, revisions
5
+ that fork the history, data migrations that import the application's models, and downgrades that do nothing while the
6
+ upgrade changes the schema. Each rule is advice that the PostgreSQL, Alembic or SQLAlchemy documentation gives, or that
7
+ Squawk, strong_migrations, django-migration-linter and well-known migration post-mortems give, from at least two
8
+ independent sources ([NOTES-alembic.md](NOTES-alembic.md)). The pack's rules for locks on live tables and lost data
9
+ (index builds, constraint checks, NOT NULL columns, type changes, dropped and renamed columns, lock_timeout) are
10
+ candidates until they pass the release bar ([candidates/README.md](candidates/README.md)).
11
+
12
+ **What it adds over a SQL linter.** Squawk reads the SQL that `alembic upgrade head --sql` renders, and projects such
13
+ as `alembic-squawk` and PandaDoc's `migration-lint` package that pipeline. This pack adds three things that pipeline
14
+ lacks:
15
+
16
+ - it runs in the edit window, on the Python the agent just wrote, with no offline render and no database;
17
+ - it reads revisions that cannot render offline (inspector calls, data migrations, `op.get_bind()`), common in dify,
18
+ superset and open-webui;
19
+ - it has the cross-file rules no SQL linter can have: `model-import-in-migration`, `multiple-heads`, `empty-downgrade`,
20
+ and the env.py side of `concurrent-index-outside-autocommit`.
21
+
22
+ Ruff, mypy, Bandit and pylint check none of these shapes.
23
+
24
+ **Code and actionable.** Whether a migration's advice applies can depend on how a project deploys, which the rules
25
+ cannot see: advice for a database that serves traffic fixes nothing when a project stops the application to migrate
26
+ (jupyterhub's upgrade guide says "Shut down JupyterHub" before `upgrade-db`; mealie runs
27
+ `command.upgrade(alembic_cfg, "head")` in `mealie/db/init_db.py` before its one process serves). So the corpus figures
28
+ below give two precisions: **code** (the file holds the shape the message describes) and **actionable** (a reviewer of
29
+ that repository would ask for the change: not on a database that migrates with the app stopped, not a no-op).
30
+
31
+ Each rule reads the repository's Python files through the pack's library [`rules/lib/alembic.rerail`](rules/lib/alembic.rerail),
32
+ which resolves what it reads rather than matching spellings: `op.*` and `batch_op.*` operations through `from alembic
33
+ import op`; the table each acts on (a literal, `op.f(...)` or a module constant); the tables the same `upgrade()`
34
+ creates or empties; project helpers that forward a table to an operation (one call deep, across modules); flags by
35
+ value (`postgresql_concurrently=CONCURRENT` with `CONCURRENT = True`, imported too); types by the SQLAlchemy class they
36
+ resolve to (aliases, TypeDecorators, subclasses, functions that return a type); dialect tests by their structure
37
+ (comparisons with a database name, `isinstance` on SQLAlchemy dialect classes, `not`/`and`/`or`, test functions of the
38
+ run); `autocommit_block()` regions; SQLAlchemy and sqlmodel model classes with their columns; revision ids; env.py and
39
+ the module it imports its engine from.
40
+
41
+ Each rule is proven three ways: by its cases in `upstream/alembic-practice/authored/<id>/` (pack test data in S3, pulled
42
+ by `npm run fixtures:pull -- --pack alembic`, not in git), where a line ending in `# caught` must be reported and no
43
+ other line may be (`rerail rules test <file>.rerail`, which reads the case directory as one repository); by a run on the
44
+ 8 open-source repositories of the corpus that use Alembic ([the corpus](#the-corpus)), whose matches were read and judged
45
+ (every match, or a spread sample covering every repository); and by an independent review
46
+ ([REVIEW-alembic.md](REVIEW-alembic.md)), whose findings were applied (its "Applied" section). Each rule was then
47
+ benchmarked on #1120's engine over further repositories (lemur, pyaleph, letta, flaskbb, HaloWebUI, notify-server,
48
+ remnawave-admin, themecp-backend-v2, siema_tech_fastapi); each rule's details give the figures. A rule ships, on, only
49
+ when more than 90% of its judged matches on repositories it was not tuned or fixed on are actionable, with at least 5
50
+ such matches in at least 2 repositories; under that floor it ships only if no false match of it is known anywhere. The
51
+ others are candidates ([candidates/README.md](candidates/README.md)).
52
+
53
+ Figures are after the review's fixes (runs `alembic-fix-*`), on the 8 Alembic repositories; "read" is every match or
54
+ the spread sample the rule's details name. The last column adds the benchmark's judged matches.
55
+
56
+ | Rule | Mode | Catches | Matches (repos) | Code precision (read) | Actionable (read) | Actionable, with the benchmark |
57
+ |---|---|---|---|---|---|---|
58
+ | `alembic-practice-concurrent-index-outside-autocommit` | Steer | a concurrent index build or drop run inside the migration's transaction | 0 (0) | no matches; 224 wrapped concurrent calls left alone | n/a | n/a (no matches) |
59
+ | `alembic-practice-multiple-heads` | Steer | revisions that leave one migration directory with two heads: `alembic upgrade head` refuses to run | 0 (0) | no matches at release commits | n/a | n/a (no matches) |
60
+ | `alembic-practice-model-import-in-migration` | Steer | a migration that imports an application ORM model instead of declaring the table it needs | 13 (4) | 100% (13 of 13) | 100% | 100% (15 of 15) |
61
+ | `alembic-practice-empty-downgrade` | Log | a downgrade() that does nothing while upgrade() changes the schema, in a tree whose other revisions implement downgrade | 3 (2) | 100% (3 of 3) | 100% | 100% (3 of 3; no new matches) |
62
+
63
+ Each rule details its gaps and the shapes it leaves alone below. Rules in Log mode record matches without steering
64
+ the agent; the details give the reason.
65
+
66
+ ## Starting values
67
+
68
+ All 4 rules start on: 3 steer (`concurrent-index-outside-autocommit`, `multiple-heads`, `model-import-in-migration`)
69
+ and 1 logs (`empty-downgrade`). None has 5 judged matches on the benchmark, so each ships because no false match of it
70
+ is known, in the corpus or the benchmark: `model-import-in-migration` is 2 of 2 on the benchmark (pyaleph) and 15 of 15
71
+ with the corpus; `empty-downgrade` 3 of 3 on the corpus, with no benchmark match.
72
+
73
+ `concurrent-index-outside-autocommit` and `multiple-heads` have no matches on real code, in the corpus or the
74
+ benchmark, by design: at a release commit every repository already gets these right, and the bug exists only between
75
+ writing a migration and finishing the change, which is when Rerail checks an edit. They keep their starting state;
76
+ each was proven by an edit-window test on a copy of a corpus repository (see its details). On the five corpus
77
+ repositories the benchmark re-ran (the template, jupyterhub, mealie, open-webui, dispatch), #1120's engine reports
78
+ exactly the corpus findings for every rule.
79
+
80
+ ## The corpus
81
+
82
+ The 8 open-source repositories with Alembic migrations among the 20 of the Python team corpus, shallow clones at pinned
83
+ commits. Each rule ran over every one of them (with `corpus-run`, or with the engine directly on the repository's
84
+ migration directory where a rule reads one revision at a time; each rule's details say which).
85
+
86
+ | Repository | Commit | Alembic revision files |
87
+ |---|---|--:|
88
+ | fastapi/full-stack-fastapi-template | `77e550a7` | 5 |
89
+ | jupyterhub/jupyterhub | `3ca37442` | 20 |
90
+ | mealie-recipes/mealie | `8dbb9280` | 66 |
91
+ | open-webui/open-webui | `0666e59d` | 72 |
92
+ | Netflix/dispatch | `dd2837e8` | 158 |
93
+ | polarsource/polar | `872272fb` | 203 |
94
+ | langgenius/dify | `724ac151` | 246 |
95
+ | apache/superset | `fdf61721` | 325 |
96
+
97
+ ## Rule details
98
+
99
+ ### `alembic-practice-concurrent-index-outside-autocommit`
100
+
101
+ Rerail's own rule, not a port. PostgreSQL refuses `CREATE INDEX CONCURRENTLY` and `DROP INDEX CONCURRENTLY` inside a
102
+ transaction block, and Alembic runs each revision in a transaction on PostgreSQL, so a concurrent index operation left
103
+ in it fails the deploy's migration with "CREATE INDEX CONCURRENTLY cannot run inside a transaction block". In an
104
+ Alembic revision's `upgrade()` or `downgrade()`, or in a module-level function of the same file that a step calls from
105
+ outside an autocommit block, it reports:
106
+
107
+ - `op.create_index(..., postgresql_concurrently=True)` and `op.drop_index(..., postgresql_concurrently=True)`, and the
108
+ same on the handle of `with op.batch_alter_table("t") as batch_op:`;
109
+ - such a call after an autocommit block in the same function (the revision's transaction is open again there), and
110
+ one in PostgreSQL's own branch of a dialect test.
111
+
112
+ The message names the fix, `with op.get_context().autocommit_block():` around the call, and its cost: the block first
113
+ commits what the revision ran before it, so the concurrent work goes last. This rule also guards the advice of the
114
+ candidate `alembic-practice-index-not-concurrent` ([candidates/README.md](candidates/README.md)): an agent told to
115
+ build an index concurrently often adds only the keyword.
116
+
117
+ `postgresql_concurrently` is read by value: the literal `True`, or a module constant of the same file or one imported
118
+ from another module (`postgresql_concurrently=CONCURRENT`).
119
+
120
+ It leaves alone: calls inside `with <ctx>.autocommit_block():` at any depth (an `if` or a `batch_alter_table` in it,
121
+ a helper called from it, a MigrationContext held in a local); `postgresql_concurrently` False, absent, or an
122
+ expression the rule cannot evaluate; code in a branch that runs only on another database (read by the test's
123
+ structure, lib/alembic's `al_non_pg`); revisions under `tests/`; files without module-level `revision` and
124
+ `down_revision`; an `op` that is not `alembic.op`.
125
+
126
+ **Across files.** An env.py that runs its revisions with no transaction around them makes CONCURRENTLY work as
127
+ written: `context.configure(..., transactional_ddl=False)` (by value), or an engine or connection with
128
+ `isolation_level="AUTOCOMMIT"` set in env.py or in the module env.py imports it from (`from app.db import engine`).
129
+ The rule reports nothing in the revisions under that env.py's directory, nor in revisions under no env.py's directory
130
+ of the run when such an env.py exists. Other Alembic trees of the same repository, with their own env.py, are still
131
+ read (Netflix/dispatch's core and tenant schemas). `transaction_per_migration=True` still opens a transaction per
132
+ revision: still reported.
133
+
134
+ **Gaps:** raw SQL (`op.execute("CREATE INDEX CONCURRENTLY ...")`) is not read (Squawk reads SQL); the old
135
+ `op.execute("COMMIT")` workaround is not recognised (none in the corpus); helpers in another module, or two calls
136
+ deep, are not followed; an env.py outside the run, or `transactional_ddl` passed through a `**kwargs` dict
137
+ (superset's env.py, for SQLite and MySQL only), is not seen.
138
+
139
+ **Corpus** (BRIEF commits; polar and superset on the review's trimmed copies):
140
+
141
+ | Repository | Commit | Concurrent index calls | Inside an autocommit block | Matches |
142
+ |---|---|--:|--:|--:|
143
+ | fastapi/full-stack-fastapi-template | 77e550a | 0 | – | 0 |
144
+ | jupyterhub/jupyterhub | 3ca3744 | 0 | – | 0 |
145
+ | mealie-recipes/mealie | 8dbb928 | 0 | – | 0 |
146
+ | open-webui/open-webui | 0666e59 | 0 | – | 0 |
147
+ | Netflix/dispatch | dd2837e | 0 | – | 0 |
148
+ | polarsource/polar | 872272f | 213 | 211, and 2 in helpers called only from inside one | 0 |
149
+ | langgenius/dify | 724ac15 | 11 | 11 | 0 |
150
+ | apache/superset | fdf6172 | 0 | – | 0 |
151
+
152
+ No match before or after the review's fixes, so no precision to measure: every repository that uses concurrent index
153
+ operations wraps them, which is the practice the rule enforces. polar's
154
+ `server/migrations/versions/2026-11-12-1405_add_manual_benefit_grant_timestamps.py` is the shape that needs the
155
+ helper reading: its `_create_index` and `_drop_index` call `op.create_index(..., postgresql_concurrently=True)`
156
+ outside any `with`, and `upgrade()` and `downgrade()` call them only inside `autocommit_block()`. The review's
157
+ edit-window test on a copy of the template (a new revision with both calls in `upgrade()` and `downgrade()`) reports
158
+ both lines, and the wrapped version is silent.
159
+
160
+ **On #1120's engine (benchmark).** No matches on the benchmark repositories, and no new ones on the corpus repositories
161
+ it re-ran.
162
+
163
+ **Sources:** PostgreSQL, [CREATE INDEX](https://www.postgresql.org/docs/current/sql-createindex.html) ("a regular
164
+ CREATE INDEX command can be performed within a transaction block, but CREATE INDEX CONCURRENTLY cannot") and
165
+ [DROP INDEX](https://www.postgresql.org/docs/current/sql-dropindex.html); SQLAlchemy's PostgreSQL dialect,
166
+ ["Indexes with CONCURRENTLY"](https://docs.sqlalchemy.org/en/21/dialects/postgresql.html); Alembic,
167
+ [`MigrationContext.autocommit_block`](https://alembic.sqlalchemy.org/en/latest/api/runtime.html); Squawk
168
+ [ban-concurrent-index-creation-in-transaction](https://squawkhq.com/docs/ban-concurrent-index-creation-in-transaction)
169
+ (SQL files only). No Ruff or Bandit rule reads Alembic operations; this rule adds what Squawk cannot see in Python:
170
+ the autocommit block around the call (or around the helper call), the batch handle, and the env.py that decides
171
+ whether revisions run in a transaction at all.
172
+
173
+ ### `alembic-practice-multiple-heads`
174
+
175
+ Rerail's own rule, not a port. It reads every Alembic revision file of the repository (module-level `revision = ...` and
176
+ `down_revision = ...`, annotated or not, outside test code) as one graph. A revision's parents are the ids its
177
+ `down_revision` names: a string, a name bound to one in the same file (`down_revision = PARENT`), or each element of a
178
+ tuple or list; a tuple or list of one is a single parent, not a merge. An id resolves first among the revisions of the
179
+ same directory and only then elsewhere, so two version directories that reuse ids (`"0001"`, `"0002"`) stay apart. A
180
+ head is a revision no other revision names in its `down_revision` (`depends_on` orders an upgrade but joins nothing:
181
+ Alembic's `RevisionMap` counts heads by `down_revision` alone). Two heads that share an ancestor, or that sit in one
182
+ version directory (a second base, `down_revision = None`, next to the existing line), make `alembic upgrade head`
183
+ refuse to run: "Multiple head revisions are present for given argument 'head'" (checked with Alembic 1.20.1 by the
184
+ review). The rule reports at each head's `down_revision = ...`, once per other head:
185
+
186
+ - two revisions written on the same parent, with no merge revision joining them: the usual result of two branches
187
+ each adding a migration on the head they saw (both heads are reported, also when one line has grown further);
188
+ - a fork whose one side only carries `depends_on`;
189
+ - a second base in the same version directory, the shape an agent creates by writing `down_revision = None`;
190
+ - a merge revision that is one head while a revision written on a pre-merge revision is the other;
191
+ - two branches that each ran `alembic merge heads` on the same heads (two merge heads).
192
+
193
+ The message names the other head and the revision that starts each line: if it has not run on any shared database,
194
+ point its `down_revision` at the other head; otherwise add a merge revision with `alembic merge heads`. For two merge
195
+ heads it says to merge again or delete the merge that has not run. It says when to leave it: an intentional parallel
196
+ branch, which should carry `branch_labels`.
197
+
198
+ It leaves alone:
199
+
200
+ - forks joined by a merge revision (`down_revision = ("b2", "b3")`, also as a list or through constants);
201
+ - heads of trees in separate directories that share no ancestor (Netflix/dispatch's `core` and `tenant` trees, two
202
+ services that reuse sequential ids);
203
+ - a head whose own line (between the fork, or its own base, and the head) sets `branch_labels`: an intentional branch,
204
+ migrated with `alembic upgrade heads` or `branch@head`. Labels on the shared base or trunk do not silence a fork;
205
+ - a line holding a revision whose parent is unknown (an imported name, a call, or an id no revision of the run has: a
206
+ squashed history, a library's version location), which would otherwise look like a second base;
207
+ - revisions in test trees.
208
+
209
+ **Gaps:** a history spread over several directories (`version_locations`, recursive version directories) whose lines
210
+ share no ancestor is read as separate trees, because which directories a script location reads is in `alembic.ini`;
211
+ a parent imported from another module is unknown and its line is left alone.
212
+
213
+ **Sources:** Alembic, "Working with Branches" (https://alembic.sqlalchemy.org/en/latest/branches.html): the multiple
214
+ heads error, `alembic merge heads`, `branch_labels`; Alembic's `RevisionMap` (`alembic/script/revision.py`), whose
215
+ `heads` drop only revisions named in a `down_revision` (not in `depends_on`); pytest-alembic's
216
+ `test_single_head_revision`, for merge conflicts that "lazily break during deployment"
217
+ (https://pytest-alembic.readthedocs.io/en/latest/quickstart.html).
218
+
219
+ **Overlap:** pytest-alembic (an opt-in test) and Alembic's own error at deploy; no linter (Ruff, Bandit, Squawk) reads
220
+ the revision graph. This rule's value is catching it while the revision is written, before the deploy fails.
221
+
222
+ **Corpus** (8 Alembic repositories at the `MANIFEST.tsv` commits). "Engine" is the rule's own count before and after
223
+ the review's fixes (runs `alembic-fix-multiple-heads-*`, polar, dify and superset on the review's trimmed copies);
224
+ "heads" and "merges" come from an independent Python `ast` survey of every revision file:
225
+
226
+ | Repository | Commit | Revisions | Trees | Heads | Merge revisions | Engine matches |
227
+ |---|---|--:|--:|--:|--:|--:|
228
+ | fastapi/full-stack-fastapi-template | 77e550a | 5 | 1 | 1 | 0 | 0 |
229
+ | jupyterhub/jupyterhub | 3ca3744 | 19 | 1 | 1 | 0 | 0 |
230
+ | mealie-recipes/mealie | 8dbb928 | 66 | 1 | 1 | 0 | 0 |
231
+ | open-webui/open-webui | 0666e59 | 72 | 1 | 1 | 0 | 0 |
232
+ | Netflix/dispatch | dd2837e | 162 | 2 (`core`, `tenant`) | 2 | 3 | 0 |
233
+ | polarsource/polar | 872272f | 205 | 1 | 1 | 0 | 0 |
234
+ | langgenius/dify | 724ac15 | 253 | 1 | 1 | 4 | 0 |
235
+ | apache/superset | fdf6172 | 411 | 1 | 1 | 48 | 0 |
236
+
237
+ 0 matches at the pinned commits, as expected: a release has one head per tree. A diagnostic copy of the rule confirmed
238
+ the engine resolves the graphs (polar 205, dify 253, superset 411 revisions, one head each; dispatch 162 revisions, one
239
+ head in `core` and one in `tenant`). The 55 merge
240
+ revisions are real past forks the rule sees as joined. Edit-window checks: a new revision added to a copy of polar's
241
+ migrations with `down_revision` on the head's parent (`f3238e76d766`) is reported together with the current head
242
+ `3c1e7a9d52f4`, and adding `alembic merge heads`' revision silences both; deleting superset's merge revision
243
+ `3740c7bcb2c6` from a copy reports the two heads it joined (`875472b9c016`, itself a merge, and `d623a0cb6bb0`).
244
+ After the rework, a text count of each version directory finds one base and one head in every tree, so the second-base
245
+ and unknown-parent readings change nothing at release commits. The review's counterexamples: two bases and a
246
+ `depends_on`-only fork are now reported (both lines each); `("r1",)` gets the rebase message; the review's
247
+ `down_revision = PARENT` with `PARENT` bound after its use (a NameError at import, which Alembic cannot load either)
248
+ is left alone, while a constant bound before its use is resolved. The review's edit-window copies: the fork is
249
+ reported on both lines, the revision written on the head is silent.
250
+
251
+ **On #1120's engine (benchmark).** No matches on the benchmark repositories, and no new ones on the corpus repositories
252
+ it re-ran.
253
+
254
+ ### `alembic-practice-model-import-in-migration`
255
+
256
+ Rerail's own rule, not a port. It reads a migration against the application's models. In an Alembic revision outside
257
+ test code (module level, `upgrade()`, `downgrade()` or a helper), it reports
258
+
259
+ - each name of `from app.models.group import Group` (or `from app.models import Group`, a re-export followed to the
260
+ class) that is a mapped ORM class of the application, one finding per imported name;
261
+ - a model read through its module, `from jupyterhub import orm` then `db.query(orm.APIToken)`: the first use of each
262
+ model in the file, outside type annotations.
263
+
264
+ A mapped class is a class of the repository that declares `__tablename__`, is a sqlmodel `table=True` class,
265
+ subclasses either (`al_model_q`), or subclasses a declarative base (`class Base(DeclarativeBase)`, a module-level
266
+ `Base = declarative_base()`, or Flask-SQLAlchemy's `db.Model` for a module-level `db = SQLAlchemy(...)`, each resolved
267
+ through imports) without `__abstract__ = True`: Netflix/dispatch names every table with a `declared_attr` on its base,
268
+ so its models declare no `__tablename__`. A class of another library that merely has a `Model` attribute is no base.
269
+ An import whose module sits in a namespace package (a directory without `__init__.py`, as dispatch's
270
+ `dispatch/feedback/`) is matched to the class by file path. The message says why (the model follows today's schema,
271
+ not this revision's) and names the replacement: declare the table in the migration with `sa.table()` and
272
+ `sa.column()`; it says that enums, types and constants may stay. A model the migration uses only for its table name
273
+ (`User.__tablename__`, `User.__table__.name`) gets its own message: nothing queries its columns, but the import still
274
+ loads the application when the migration runs, so write the table name as a string.
275
+
276
+ It leaves alone:
277
+
278
+ - column types and TypeDecorators (`GUID`, `StringUUID`, `LongText`, `JSONDict`, `NaiveDateTime`), enums and constants
279
+ (`ObjectType`, `TagType`, `AppTriggerStatus`, `ADDITIVE_METRIC_TYPES_LOWER`), pydantic schemas, sqlmodel classes
280
+ without `table=True`, plain helper classes;
281
+ - the declarative base and mixins (`SqlAlchemyBase`, `Base`, `TimestampMixin`). Evidence: the one migration in the
282
+ corpus that imports an application base (mealie `c7427796f7b6`) calls its static `SqlAlchemyBase.normalize()`, and
283
+ `Base.metadata` carries no column a query names. Querying the base itself is not something code does;
284
+ - a model class declared inside the migration file (mealie's later revisions declare their own `SqlAlchemyBase` and
285
+ `RecipeModel`, `IngredientFoodModel`, ... locally; superset declares `declarative_base()` models in its migrations),
286
+ and a model of a module under a `migrations/` or `alembic/` directory (superset's `migrations/shared/` keeps frozen
287
+ copies for the migrations);
288
+ - `if TYPE_CHECKING:` imports and annotations (jupyterhub's `def access_scopes(oauth_client: orm.OAuthClient, ...)`);
289
+ - `env.py` (it imports `Base.metadata` on purpose), revisions in test trees, and test files.
290
+
291
+ **Gaps:** a model module bound to a local name another way (`importlib.import_module(...)`); a base assigned from
292
+ `declarative_base()` in the same module as its models (the base reference does not resolve there); models from an
293
+ installed package; a class whose base chain crosses a namespace package (the path fallback covers only the imported
294
+ name itself).
295
+
296
+ **Sources:** zzzeek on sqlalchemy/alembic#679 ("your ORM models may have changed so would no longer work in this
297
+ migration once it's older", https://github.com/sqlalchemy/alembic/issues/679); the Alembic cookbook's data migrations,
298
+ which declare tables with `sa.table()`/`sa.column()` (https://alembic.sqlalchemy.org/en/latest/cookbook.html);
299
+ django-migration-linter's RUNPYTHON_MODEL_IMPORT error
300
+ (https://github.com/3YOURMIND/django-migration-linter/blob/main/docs/incompatibilities.md). jupyterhub's own
301
+ `651f5419b74d_api_token_scopes.py` shows the failure: it has to `defer(orm.Spawner.display_name)` because "the new
302
+ display_name column isn't added until a subsequent db upgrade script runs".
303
+
304
+ **Overlap:** django-migration-linter checks Django migrations only; Ruff and Bandit check nothing here. This rule's value
305
+ is the cross-file resolution: it follows the import (re-exports and namespace packages included) to a class and decides
306
+ from the class's definition whether it is mapped, so it tells `Group` from `GUID` in the same models package.
307
+
308
+ **Corpus** (8 Alembic repositories at the `MANIFEST.tsv` commits; every match read). Before the review's fixes, six
309
+ were run whole through `corpus-run` and polar and dify with the engine on the files the rule needs; after them, all 8
310
+ through `corpus-run` (polar, dify and superset on the review's trimmed copies; runs `alembic-fix-mine-*`), with the
311
+ same 13 matches, all with the query message (none uses a model only for its table name).
312
+
313
+ | Repository | Commit | Matches | Real | Files |
314
+ |---|---|--:|--:|---|
315
+ | fastapi/full-stack-fastapi-template | 77e550a | 0 | 0 | |
316
+ | jupyterhub/jupyterhub | 3ca3744 | 4 | 4 | `651f5419b74d_api_token_scopes.py` (`orm.APIToken`, `orm.Role`, `orm.OAuthClient`, `orm.Spawner`, queried and monkeypatched with `relationship()`) |
317
+ | mealie-recipes/mealie | 8dbb928 | 7 | 7 | `04ac51cbe9a4_added_group_slug.py` (`Group`), `0341b154f79a_added_normalized_unit_and_food_names.py` (`IngredientFoodModel`, `IngredientUnitModel`), `dded3119c1fe_added_unique_constraints.py` (`MultiPurposeLabel`, `IngredientFoodModel`, `IngredientUnitModel`, `RecipeIngredientModel`) |
318
+ | open-webui/open-webui | 0666e59 | 0 | 0 | |
319
+ | Netflix/dispatch | dd2837e | 1 | 1 | `tenant/versions/2024-10-16_3c49f62d7914.py` (`Feedback`, `session.query(Feedback).all()`) |
320
+ | polarsource/polar | 872272f | 0 | 0 | |
321
+ | langgenius/dify | 724ac15 | 0 | 0 | |
322
+ | apache/superset | fdf6172 | 1 | 1 | `2021-08-09_17-32_07071313dd52_change_fetch_values_predicate_to_text.py` (`SqlaTable`, `session.query(SqlaTable).filter(...)`) |
323
+
324
+ Every match is a migration that queries or writes through the imported model (`session.query(Model)`,
325
+ `select(Model)`, `load_only(Model.col)`), or reads its `__tablename__` next to such a query. An independent `grep` of
326
+ the corpus's migration imports finds the same set and no other import of a mapped class; dispatch's plugin
327
+ configuration imports (pydantic models) and superset's `ObjectType`/`TagType`/`ReportState` enums stay silent, as do
328
+ mealie's ten `GUID` imports, dify's `StringUUID`/`LongText` imports and jupyterhub's `JSONDict` imports. The first
329
+ version missed dispatch's `Feedback`: `dispatch/feedback/` has no `__init__.py`, so the class's qualified name lacks the
330
+ `dispatch.feedback` prefix the import names; the file-path fallback fixed it (a case covers it).
331
+
332
+ Precision on the corpus: code and actionable 13 of 13 (100%). The 13 sit in 6 revisions, because projects that learned this
333
+ moved to local models (mealie's revisions from 2024 on declare their own `SqlAlchemyBase` and model classes, which stay
334
+ silent). Edit-window check: a new revision added to a copy of polar that imports `Organization` (through the
335
+ `polar.models` re-export) and `polar.models.user.User` is reported on both lines and `polar.config.settings` is not; in
336
+ a copy of dify, `from models.model import App` and `models.Account` (through `import models`) are reported, and
337
+ `StringUUID` and `AppTriggerStatus` are not.
338
+
339
+ **On #1120's engine (benchmark).** 2 matches (pyaleph `0016:17`, `0032:18`), both real and actionable; with the
340
+ corpus, 15 of 15.
341
+
342
+ ### `alembic-practice-empty-downgrade`
343
+
344
+ Rerail's own rule, not a port. It reports, at `def downgrade():`, an Alembic revision whose `upgrade()` changes the
345
+ schema while its `downgrade()` does nothing (`pass`, `...`, a bare `return`, or those, with at most Alembic's
346
+ autogenerate markers `# ### commands auto generated by Alembic - please adjust! ###`), in a migration tree that
347
+ implements its downgrades.
348
+ `alembic downgrade` runs the empty function, reports success and moves the version table back while the schema keeps
349
+ the change: the database no longer matches the revision it records, the next `alembic upgrade` can fail on what is
350
+ already there (a column that exists, a constraint already dropped), and the rollback path the team relies on is broken.
351
+
352
+ A schema change is any Alembic operation (`op.m(...)`, or `b.m(...)` on a `with op.batch_alter_table(...) as b:`
353
+ handle, also inside a module-level helper `upgrade()` calls) other than `execute`, `bulk_insert`, `f`, `get_bind`,
354
+ `get_context`, `batch_alter_table`, `inline_literal`, `invoke`, `run_async` and `implementation_for`.
355
+
356
+ The convention is read across files. A migration tree is the revision files of one directory (Netflix/dispatch's
357
+ `core/versions` and `tenant/versions` are two trees). Its counted revisions have one parent, a schema change in
358
+ `upgrade()`, and are not excused (below). The rule reports only when at least 4 in 5 of a tree's counted revisions have
359
+ a `downgrade()` that does something. So a tree needs 5 counted revisions before one empty downgrade can be reported,
360
+ and a tree where 3 of 4 downgrades are implemented (75%) stays silent. Why 80%: every tree of the 8 Alembic repositories
361
+ is at 98% or more once the excused revisions are set aside (superset 169 of 171, dispatch's `tenant` 136 of 137), so
362
+ the threshold only matters for small or young trees where empty downgrades are the habit. The message gives the tree's
363
+ count ("136 of the 137 revisions ... implement theirs").
364
+
365
+ The message says to reverse `upgrade()` there, or raise when the change cannot be undone, so a rollback stops instead
366
+ of leaving the schema behind; and to leave it in a project that never runs downgrades. No primary source prefers
367
+ `raise` over `pass`; the message offers both.
368
+
369
+ It leaves alone (and does not count):
370
+
371
+ - merge revisions (`down_revision` a tuple or list);
372
+ - revisions whose `upgrade()` is empty or data-only (`op.execute`, `op.bulk_insert`, ORM sessions);
373
+ - a `downgrade()` that does anything, including one that raises or calls a helper;
374
+ - an empty `downgrade()` when `upgrade()` reads the live schema first (`sa.inspect`, `Inspector.from_engine`,
375
+ `get_table_names`, `get_columns`, `has_table`, `get_pk_constraint`, superset's `table_has_column` and
376
+ `get_table_column`, ...): an idempotent repair, which a second upgrade after the empty downgrade reruns without error
377
+ (polar's `restore_event_sequences`, open-webui's `add_missing_primary_keys_to_legacy_`);
378
+ - an empty `downgrade()` with its author's own comment below the `def` line, or a docstring: a recorded decision, such
379
+ as dify's "The corrected down revision already defines nullable columns". In these the advice to raise would break a
380
+ downgrade that is correct as it is. A comment that starts `TODO`, `FIXME` or `XXX` records no decision and excuses
381
+ nothing;
382
+ - revisions in test code.
383
+
384
+ **Gaps:** schema changes made outside Alembic's `op` (raw DDL in `op.execute`, a project's own `add_columns` wrapper,
385
+ sqlalchemy-searchable's `sync_trigger`) are not schema changes here, so such a revision is neither reported nor counted.
386
+ A `downgrade()` made of other no-op statements (`print(...)`, a log call) counts as implemented. Any other explaining
387
+ comment silences the rule, whatever it says. In a tree of fewer than 10 counted revisions, two empty downgrades put it
388
+ under 80% and silence the rule for the whole tree (by design: the habit is then the tree's own). The tree is a
389
+ directory, not the revision graph, so one tree spread over several `version_locations` is judged per directory.
390
+
391
+ **Sources:** Alembic cookbook, which expects migrations to reach the finished schema "and back again"
392
+ (https://alembic.sqlalchemy.org/en/latest/cookbook.html); pytest-alembic's `test_up_down_consistency`, which checks only
393
+ that every downgrade runs, so an empty one passes (https://pytest-alembic.readthedocs.io/en/latest/quickstart.html);
394
+ django-migration-linter's `RUNPYTHON_REVERSIBLE` and `RUNSQL_REVERSIBLE`, which warn on Django migrations without reverse
395
+ code.
396
+
397
+ **Overlap:** none for Alembic. Ruff, Bandit and Squawk do not read Alembic's steps; pytest-alembic's round trip passes
398
+ an empty downgrade. The rule's value over a per-file check is the tree's convention: it stays silent in projects whose
399
+ downgrades are mostly empty.
400
+
401
+ **Corpus** (8 Alembic repositories at the `MANIFEST.tsv` commits). "Candidates" are revisions with one parent, an
402
+ Alembic schema change in `upgrade()` and a downgrade of only `pass`/`...`/comments/docstring, from an independent Python
403
+ `ast` survey (Python 3.15). "Excused" are the candidates the reflection and explanation exemptions set aside.
404
+
405
+ | Repository | Commit | Tree(s): implemented / counted | Candidates | Excused | Matches | Real |
406
+ |---|---|---|--:|--:|--:|--:|
407
+ | fastapi/full-stack-fastapi-template | 77e550a | 5 / 5 | 0 | 0 | 0 | - |
408
+ | jupyterhub/jupyterhub | 3ca3744 | 18 / 18 | 0 | 0 | 0 | - |
409
+ | mealie-recipes/mealie | 8dbb928 | 59 / 59 | 0 | 0 | 0 | - |
410
+ | open-webui/open-webui | 0666e59 | 68 / 68 | 2 | 2 | 0 | - |
411
+ | Netflix/dispatch | dd2837e | `core` 7 / 7, `tenant` 136 / 137 | 2 | 1 | 1 | 1 |
412
+ | polarsource/polar | 872272f | 186 / 186 | 1 | 1 | 0 | - |
413
+ | langgenius/dify | 724ac15 | 235 / 235 | 3 | 3 | 0 | - |
414
+ | apache/superset | fdf6172 | 169 / 171 | 8 | 6 | 2 | 2 |
415
+
416
+ 3 matches, all real (precision 3 of 3; a small sample):
417
+
418
+ - `Netflix__dispatch/src/dispatch/database/revisions/tenant/versions/2023-11-29a_bdaeabba3e53.py`: `upgrade()` drops
419
+ the index `signal_instance_search_vector_idx` and the column `signal_instance.search_vector`; `downgrade()` is only
420
+ autogenerate markers and `pass`. After a downgrade the next upgrade fails dropping an index that no longer exists.
421
+ - `apache__superset/superset/migrations/versions/2020-12-23_11-34_c878781977c6_alert_reports_shared_uniqueness.py`:
422
+ `upgrade()` drops `uq_report_schedule_name` and creates `uq_report_schedule_name_type`; `downgrade()` is `pass`, so a
423
+ downgrade leaves the new constraint and the re-upgrade fails dropping the old one.
424
+ - `apache__superset/superset/migrations/versions/2016-03-13_21-30_18e88e1cc004_making_audit_nullable.py`: `upgrade()`
425
+ drops four columns of `columns` and relaxes NOT NULL on a dozen more; `downgrade()` is `pass`.
426
+
427
+ The 13 excused candidates were read: each is an inspector-guarded repair (open-webui 2, polar 1, dify 1, dispatch
428
+ `928b725d64f6`, superset 6) or explains its empty downgrade (dify 2), and none would fail a re-upgrade. Reporting them
429
+ would have made precision 3 of 16. An estimate given before the rule existed counted 82 empty downgrades with schema
430
+ operations (superset 52, dispatch 13); the survey above finds 16. Of dispatch's 18 empty downgrades, 3 are merges, 2
431
+ follow an empty `upgrade()`, 7 follow data-only upgrades (ORM sessions, `op.execute`), 4 follow sqlalchemy-searchable's
432
+ `sync_trigger` (a schema change outside `op`: a gap, and idempotent on re-upgrade) and 2 are candidates. Of superset's
433
+ 104 empty downgrades, 47 are merges, 4 follow an empty `upgrade()`, 45 change no schema through `op` (43 run ORM
434
+ sessions or data SQL over chart and dashboard JSON; `a39867932713` and `07f9a902af1b` run raw `ALTER TABLE` through
435
+ `execute`: a gap) and 8 are candidates.
436
+
437
+ An edit-window check: a new revision added to a copy of polar's `server/migrations` (`op.add_column` with `pass` in
438
+ `downgrade()`) is reported with "186 of the 187 revisions ... implement theirs".
439
+
440
+ Counts: before the review's fixes, the five smaller repositories were run whole with `corpus-run` and polar, dify and
441
+ superset with the engine on their migration directories; after them (a bare `return` is filler, a TODO comment excuses
442
+ nothing), all 8 with `corpus-run` (polar, dify and superset on the review's trimmed copies; runs `alembic-fix-mine-*`):
443
+ the same 3 matches. The per-tree figures come from the engine (a copy of the rule that also reports the tree counts
444
+ and the excused revisions).
445
+
446
+ Mode: `log`. The read matches are all real (code and actionable 3 of 3), but there are only 3, and the exemptions that
447
+ remove the 13 deliberate no-ops are heuristics (a reflection call, a comment).
448
+
449
+ **On #1120's engine (benchmark).** No new matches; dispatch's match is reported the same.