Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

test(db): scope the #3299 schema-immutability gates; forbid edits, allow additions (#6245)

LearningCircuitc78ab819baf4
diff --git a/tests/database/schema_change_rule.py b/tests/database/schema_change_rule.py
new file mode 100644
index 0000000000..a831d36477
--- /dev/null
+++ b/tests/database/schema_change_rule.py
@@ -0,0 +1,287 @@
+"""The schema-change rule the migration gates enforce, with no git in it.
+
+``test_migration_chain_integrity.py`` and
+``test_upgrade_from_pre_migration_install.py`` both compare two trees --
+one from the schema's live metadata, one from a directory listing -- and
+then ask the same question of the result. That question lives here, as
+pure functions over ``{path: blob}`` maps, so that:
+
+* both gates enforce ONE rule rather than two that can drift apart, and
+* the rule can be pinned against hand-written inputs
+ (``test_the_schema_change_rule_is_pinned_without_touching_git``) rather
+ than only against whatever the current checkout happens to contain. A
+ git-backed assertion on a clean tree sees no changes at all, so it
+ would pass just as happily if the rule were "anything goes".
+
+The rule, in one sentence: **a shipped revision is immutable, adding a
+revision is ordinary, and a guarded schema source file may only move in a
+change that also adds a revision.**
+
+"Guarded schema source file" is a path set, not a semantic judgement.
+Each caller builds its own -- one from the live ``Base.metadata``
+registry, one from the ``database/models`` directory listing -- and both
+add :data:`DECLARATIVE_BASE_MODULE`, which no mapper walk and no models
+directory listing can reach (see its comment below). The rule is only
+ever as good as the set it is handed; it does not go looking for schema
+sources of its own.
+
+"Revision" means a revision *file*, not any file the callers happen to
+hand over. Both callers build their second map from the whole
+``database/migrations`` subtree, which also holds ``env.py`` and two
+``__init__.py`` package markers. Those three are not revisions: no
+user's ``alembic_version`` row names them, so they are ordinary source
+files that may be edited, and adding one does not migrate anything.
+:func:`is_revision` is what tells the two apart.
+
+Finally, an edit is only an edit if it changes code. A blob hash moves
+when a comment, a docstring or a line wrap moves, and neither Alembic nor
+``create_all()`` can see any of those. :func:`drop_comment_only_edits`
+lets the callers filter those out before asking :func:`violations`, so
+the gate fires on changes that can actually reach a user's database.
+"""
+
+import ast
+from pathlib import PurePosixPath
+
+# The two subtrees the callers diff. Shared here for the same reason the
+# rule is: a gate that watches a directory the other gate does not is a
+# gap nobody notices, and a rename must be made in one place.
+MIGRATIONS_SUBTREE = "src/local_deep_research/database/migrations"
+MODELS_SUBTREE = "src/local_deep_research/database/models"
+
+# The canonical ``Base = declarative_base()``. Guarded explicitly because
+# neither caller's usual discovery reaches it: it defines no mapper, so it
+# is invisible to the ``Base.registry.mappers`` walk in
+# ``test_migration_chain_integrity.py``, and it sits one directory ABOVE
+# MODELS_SUBTREE, so the directory listing in
+# ``test_upgrade_from_pre_migration_install.py`` misses it too
+# (``database/models/base.py`` only re-exports this object). It declares
+# no ``__tablename__`` either, so the source scan in
+# ``test_every_table_declared_under_src_is_either_migrated_or_a_separate_db``
+# skips it as well. Yet giving ``declarative_base()`` a
+# ``metadata=MetaData(naming_convention=...)`` here changes the name of
+# every index and constraint ``0001``'s ``create_all()`` emits for a fresh
+# install, while existing users keep the old names -- exactly the
+# fresh-vs-upgraded divergence this rule exists to catch, and it would
+# have passed with zero violations.
+DECLARATIVE_BASE_MODULE = "src/local_deep_research/database/base.py"
+
+# The directory Alembic loads revisions from. Nothing outside a directory
+# with this name can be a revision, whatever it is called.
+VERSIONS_DIR = "versions"
+
+# Anti-vacuity floors, shared for the same reason the rule is: a "for each
+# file under X" assertion proves nothing when X resolved to nothing, and
+# two gates asking the same question must not disagree about how empty is
+# too empty. Set at or below the real numbers, not below them: today the
+# migrations subtree holds 33 files of which 30 are revisions, the mapper
+# walk resolves 23 schema source files (24 once DECLARATIVE_BASE_MODULE is
+# added), and the database/models listing holds 25 (26 with it).
+# MIN_REVISIONS is therefore exactly today's revision count rather than
+# under it, which is safe in the one direction that matters: a revision
+# that shipped is immutable, so the count only ever grows, and a floor
+# that equals it can only be tripped by a tree that failed to resolve --
+# which is the whole job of these floors. Every floor is still well above
+# the "at least one file" that a collapsed tree can still satisfy.
+MIN_REVISIONS = 30
+MIN_MODEL_FILES = 20
+
+
+def is_revision(path: str) -> bool:
+ """Is ``path`` an Alembic revision file rather than migration plumbing?
+
+ Deliberately the same test ``_revision_files()`` in
+ ``test_migration_chain_integrity.py`` uses to enumerate the chain: a
+ ``.py`` module directly inside a ``versions/`` directory that is not
+ a dunder package marker. Alembic can load nothing else as a revision.
+
+ Not narrowed further to this repository's ``NNNN_name.py`` numbering.
+ The maps here carry blob hashes, not file contents, so "contains
+ ``revision = ``" is not available; and the numbering itself is
+ already pinned by ``test_alembic_migrations.py::
+ test_migration_revision_ids_match_filenames``. Requiring it here
+ would re-enforce naming as a side effect and -- much worse -- would
+ quietly exempt an unconventionally named revision from the
+ immutability rule below, which is the direction that loses user
+ data. This predicate errs wide, so a real revision is always
+ immutable.
+
+ Erring wide is safe only because two other tests fence the wide side,
+ and a future simplification must keep BOTH: ``test_upgrade_from_pre_
+ migration_install.py::test_every_revision_file_is_on_the_single_chain_
+ to_head`` makes Alembic itself reject a non-revision ``.py`` dropped
+ into ``versions/`` (a ``helpers.py`` there is not on the chain), and
+ ``test_only_files_alembic_can_load_as_revisions_count_as_revisions``
+ cross-checks this predicate over an ``rglob`` of the real directory
+ against the ``glob`` the chain walk uses, so the two cannot drift.
+ """
+ parts = PurePosixPath(path).parts
+ if len(parts) < 2 or parts[-2] != VERSIONS_DIR:
+ return False
+ name = parts[-1]
+ return name.endswith(".py") and not name.startswith("__")
+
+
+def classify(before: dict, after: dict) -> dict:
+ """Split two ``{path: blob-hash}`` maps into added / removed / edited.
+
+ Blob hashes rather than names, so an *edited* file is caught as well
+ as an added or deleted one.
+ """
+ return {
+ "added": sorted(set(after) - set(before)),
+ "removed": sorted(set(before) - set(after)),
+ "edited": sorted(
+ path
+ for path in set(before) & set(after)
+ if before[path] != after[path]
+ ),
+ }
+
+
+def _strip_docstrings(tree):
+ """Remove every docstring statement from ``tree``, in place.
+
+ The ``ast.get_docstring`` definition of a docstring and nothing
+ wider: the first statement in a module, class or function body, when
+ it is a bare string constant. A string constant anywhere else stays,
+ because anywhere else it is a value the code can read.
+ """
+ for node in ast.walk(tree):
+ if not isinstance(
+ node,
+ (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef),
+ ):
+ continue
+ body = node.body
+ if (
+ body
+ and isinstance(body[0], ast.Expr)
+ and isinstance(body[0].value, ast.Constant)
+ and isinstance(body[0].value.value, str)
+ ):
+ del body[0]
+ return tree
+
+
+def code_is_unchanged(before_source: str, after_source: str) -> bool:
+ """Do two versions of a ``.py`` file differ only in things Python drops?
+
+ True when the two parse to the same AST once docstrings are stripped
+ -- so comments, docstrings, blank lines, line wrapping and quote
+ style are all invisible here, and nothing else is. ``ast.dump`` is
+ called without ``include_attributes``, so line and column numbers do
+ not enter the comparison either.
+
+ This is the whole reason the gate can be strict without being
+ ignored: a revision file whose comments were reworded ships the same
+ ``upgrade()`` to every user, and a model file whose class docstring
+ grew emits the same DDL from ``create_all()``. Reporting those as
+ schema changes trains people to work around the gate.
+
+ Conservative on failure: anything that does not parse (a syntax
+ error, a file that is not Python at all) is reported as changed, so
+ the filter can only ever be too quiet, never too permissive. A
+ pathologically deep expression can blow the interpreter's recursion
+ limit inside ``ast.parse``/``ast.dump`` rather than raising a normal
+ parse error; that is caught the same way, for the same reason.
+ """
+ try:
+ before = _strip_docstrings(ast.parse(before_source))
+ after = _strip_docstrings(ast.parse(after_source))
+ return ast.dump(before) == ast.dump(after)
+ except (SyntaxError, ValueError, RecursionError):
+ return False
+
+
+def drop_comment_only_edits(changes: dict, read_pair) -> dict:
+ """A :func:`classify` result with cosmetic ``edited`` entries removed.
+
+ ``read_pair(path)`` returns ``(before_source, after_source)`` for one
+ path, or ``None`` if either side cannot be read; a path whose sources
+ are unavailable stays reported. Only ``edited`` is filtered: an added
+ or removed file is a real change no matter what is in it, and a
+ removed revision is the worst case of all.
+
+ Only ``.py`` paths are considered. Nothing else in the guarded sets
+ has an AST, and a non-Python file that changed changed.
+ """
+ kept = []
+ for path in changes["edited"]:
+ if path.endswith(".py"):
+ pair = read_pair(path)
+ if pair is not None and code_is_unchanged(*pair):
+ continue
+ kept.append(path)
+ return {**changes, "edited": kept}
+
+
+def violations(model_changes: dict, revision_changes: dict) -> list:
+ """Every way a change breaks the rule, as actionable sentences.
+
+ Both arguments are :func:`classify` results -- one for the files that
+ feed the shipped schema, one for the Alembic ``migrations`` subtree.
+ An empty list means the change is allowed.
+
+ Only the revision files in ``revision_changes`` are considered, on
+ both halves of the rule (see :func:`is_revision`): editing
+ ``migrations/env.py`` is not editing a shipped revision, and adding
+ ``migrations/README.md`` is not shipping a migration.
+
+ Both callers run their inputs through :func:`drop_comment_only_edits`
+ first, so an ``edited`` path that reaches here changed executable
+ code and not only comments, docstrings or formatting. The messages
+ below say so; they are written for that caller contract, since the
+ hand-written pins are the only other caller.
+
+ Deliberately NOT a violation: an added revision with no model change.
+ Data migrations, backfills, index-only revisions and constraint
+ repairs are ordinary and touch no ORM class.
+
+ Deliberately NOT checked, because a path set cannot see it: whether
+ an added revision has anything to do with the model change it is
+ paired with. See the callers' docstrings -- that is a reviewer's job,
+ and no test in this repository does it.
+ """
+ problems = []
+
+ for kind in ("edited", "removed"):
+ for path in revision_changes[kind]:
+ if not is_revision(path):
+ continue
+ problems.append(
+ f"migration {kind}: {path}. A revision that shipped is "
+ "immutable -- an existing user's alembic_version row "
+ "already names it, so the new body never executes and "
+ "their database is permanently behind the code with "
+ "nothing to indicate it. Add a NEW revision instead. "
+ "(Comment-, docstring- and formatting-only edits are "
+ "filtered out before this check, so this one changes "
+ "the code Alembic runs.)"
+ )
+
+ added_revisions = [
+ path for path in revision_changes["added"] if is_revision(path)
+ ]
+
+ moved = sorted(
+ set(model_changes["added"])
+ | set(model_changes["removed"])
+ | set(model_changes["edited"])
+ )
+ if moved and not added_revisions:
+ problems.append(
+ f"schema source file(s) changed with no migration added: {moved}. "
+ "Revision 0001 builds the baseline by calling "
+ "Base.metadata.create_all(), so a model edit lands in every "
+ "FRESH install immediately while existing users -- who only "
+ "replay the numbered revisions -- never receive it. The two "
+ "populations then run different schemas, and the first query "
+ "against the drifted table raises OperationalError on real "
+ "user data after the upgrade has already happened. Add the "
+ "Alembic revision, or revert the model change. (Comment-, "
+ "docstring- and formatting-only edits are filtered out "
+ "before this check, so the file(s) above changed code.)"
+ )
+
+ return problems
diff --git a/tests/database/test_migration_chain_integrity.py b/tests/database/test_migration_chain_integrity.py
index b6ae2f527a..12b12b7b35 100644
--- a/tests/database/test_migration_chain_integrity.py
+++ b/tests/database/test_migration_chain_integrity.py
@@ -4,8 +4,10 @@
``changelog.d/3299.breaking.md``, that it adds no schema change and can
therefore be rolled back. ``test_upgrade_from_pre_migration_install.py``
already turns the *directory* form of that claim into assertions
-(``test_pr_adds_or_edits_no_migration_revision``,
-``test_pr_changes_no_orm_model``), and ``test_alembic_migrations.py``
+(``test_the_3299_port_added_or_edited_no_migration_revision``,
+``test_the_3299_port_changed_no_orm_model``, and the generalised
+``test_pr_edits_no_shipped_revision_and_ships_a_migration``), and
+``test_alembic_migrations.py``
already covers chain shape (``test_single_head_revision``,
``test_revision_chain_has_no_gaps``, ``test_revision_ids_are_unique``,
``test_migration_revision_ids_match_filenames``), downgrade substance
@@ -20,7 +22,8 @@ that is repeated here.
What is left uncovered, and is what this file asserts:
1. **The byte-identity guarantee is scoped to a directory, not to the
- schema.** ``test_pr_changes_no_orm_model`` watches
+ schema.** ``test_pr_edits_no_shipped_revision_and_ships_a_migration``
+ watches
``src/local_deep_research/database/models``. But the metadata Alembic
actually migrates -- ``Base.metadata``, wired into
``migrations/env.py`` as ``target_metadata`` -- is fed by 23 source
@@ -36,11 +39,28 @@ What is left uncovered, and is what this file asserts:
receives is whatever the model files say **today**, while an existing
user who upgrades receives only revisions ``0002..0030``. Edit a model
without a migration and the two populations silently diverge -- fresh
- installs get the new column, upgraders do not, and the rollback claim
- ("no schema to reverse") becomes false for exactly one of them.
+ installs get the new column, upgraders do not, and the changelog's
+ claim that the release "adds no database schema migration" becomes
+ false for exactly one of them.
Tests here derive the guarded file set *from the live metadata*, so
the guard cannot drift away from the schema again.
+ Two rules follow, and they are deliberately different in scope. The
+ #3299 claim itself is a statement about ONE commit, so it is checked
+ against that commit's own range (``fb4e33b8d^..fb4e33b8d``) and stays
+ a true, re-verified statement forever -- including long after the
+ branch it was written for was merged and forgotten. What every LATER
+ branch has to satisfy is the rule that claim was a special case of,
+ shared with ``test_upgrade_from_pre_migration_install.py`` and defined
+ in ``schema_change_rule.py``: a shipped revision is immutable, adding
+ a revision is ordinary, and a file in the *guarded set* may only move
+ in a branch that also adds one. "Guarded set" and not "any file behind
+ ``Base.metadata``", because that is what is actually enforced: the set
+ is the mapper walk's answer plus ``DECLARATIVE_BASE_MODULE``, and a
+ file that feeds the schema without appearing there is not covered.
+ "Move" means its code moved -- comment-, docstring- and
+ formatting-only edits are filtered out before the rule sees them.
+
2. **Where FK enforcement is actually turned on.** Half the ORM's
referential integrity is ``ondelete="CASCADE"``/``"SET NULL"``, which
SQLite ignores unless ``PRAGMA foreign_keys = ON`` is set **per
@@ -73,9 +93,26 @@ import pytest
from local_deep_research.database.alembic_runner import get_migrations_dir
from local_deep_research.database.models import Base
+from tests.database.schema_change_rule import (
+ DECLARATIVE_BASE_MODULE,
+ MIGRATIONS_SUBTREE,
+ MIN_MODEL_FILES,
+ MIN_REVISIONS,
+ MODELS_SUBTREE,
+ classify,
+ drop_comment_only_edits,
+ is_revision,
+ violations,
+)
+
REPO_ROOT = Path(__file__).resolve().parents[2]
-MIGRATIONS_SUBTREE = "src/local_deep_research/database/migrations"
+# The commit that merged #3299. ``changelog.d/3299.breaking.md`` says that
+# release "adds no database schema migration" and that "No schema
+# downgrade is required" to roll it back -- a claim about THIS commit and
+# nothing else, so it is re-verified against this commit's own range
+# rather than against whatever branch happens to be building.
+PORT_3299_COMMIT = "fb4e33b8d8cba4d62c70cc2704007765ad9f6293"
DATABASE_PKG = REPO_ROOT / "src" / "local_deep_research" / "database"
SRC_ROOT = REPO_ROOT / "src" / "local_deep_research"
@@ -90,12 +127,23 @@ MODEL_FILE_OUTSIDE_THE_GUARDED_DIRECTORY = (
# Discovery floors. Every "for each X" assertion below is worthless if X is
# empty, and an empty discovery is the classic way a chain-integrity test
-# passes while testing nothing. These are deliberately well below the real
-# numbers (69 tables / 23 files / 30 revisions) so ordinary growth does not
-# trip them, but a collapsed discovery does.
+# passes while testing nothing. ``MIN_MODEL_FILES`` and ``MIN_REVISIONS``
+# come from ``schema_change_rule`` so that this gate and the one in
+# ``test_upgrade_from_pre_migration_install.py`` cannot disagree about how
+# empty is too empty. Deliberately well below the real numbers (69 tables /
+# 23 files / 30 revisions) so ordinary growth does not trip them, but a
+# collapsed discovery does.
MIN_METADATA_TABLES = 60
-MIN_MODEL_SOURCE_FILES = 20
-MIN_REVISIONS = 30
+
+# How many of today's guarded schema source files must still resolve at the
+# #3299 range. Not a growth floor but the exact current count: every one of
+# them existed at that commit, so anything less means a file has been
+# renamed since and has silently dropped out of that comparison -- and a
+# renamed file is absent at BOTH ends of the range, so nothing else would
+# report it. Raise this deliberately when the count genuinely grows. The
+# count is the 23 files the mapper walk resolves plus
+# DECLARATIVE_BASE_MODULE, which the walk cannot see.
+MODEL_SOURCE_FILES_AT_3299 = 24
# Tables that must be in Base.metadata. Chosen to span the model files that
# matter: the settings table the upgrade path rewrites, the research tables
@@ -191,10 +239,31 @@ def _require_merge_base():
return out.strip()
pytest.skip(
"no merge base with origin/main or main in this checkout, so the "
- "pre-#3299 baseline cannot be read; run against a full clone"
+ "commit this branch forked from cannot be read and there is "
+ "nothing to compare HEAD against; run against a full clone"
)
+def _require_commit_range(sha):
+ """``(parent, commit)`` for ``sha``, or skip.
+
+ A shallow or sparse CI checkout may not contain a months-old commit;
+ saying so beats passing quietly on an empty comparison.
+ """
+ for rev in (f"{sha}^{{commit}}", f"{sha}^^{{commit}}"):
+ code, _ = _git("rev-parse", "--verify", "--quiet", rev)
+ if code != 0:
+ pytest.skip(
+ f"{rev} does not resolve in this checkout, so the #3299 "
+ "no-schema-change claim cannot be re-verified here. A "
+ "shallow clone is the usual cause: fetch-depth: 0 is "
+ "required for this test to run at all."
+ )
+ code, out = _git("rev-parse", f"{sha}^")
+ assert code == 0
+ return out.strip(), sha
+
+
def _blob(ref, path):
"""The blob hash of one tracked file at ``ref``, or None if absent."""
code, out = _git("cat-file", "-e", f"{ref}:{path}")
@@ -241,6 +310,77 @@ def _metadata_source_files():
return files
+def _guarded_source_files():
+ """Every schema source file this gate watches: metadata plus the Base.
+
+ ``_metadata_source_files()`` walks ``Base.registry.mappers``, so it
+ finds every file that DEFINES a mapped class -- and nothing else.
+ ``DECLARATIVE_BASE_MODULE`` defines no mapper and no ``__tablename__``,
+ so that walk cannot see it, and it sits outside ``MODELS_SUBTREE`` so
+ the directory guard in ``test_upgrade_from_pre_migration_install.py``
+ cannot either. It is nonetheless the most schema-critical file in the
+ package: it holds the canonical ``Base = declarative_base()``, and
+ handing that call a ``metadata=MetaData(naming_convention=...)``
+ renames every index and constraint revision ``0001``'s
+ ``create_all()`` emits for a fresh install, while every existing user
+ keeps the old names -- with zero violations reported. Named, not
+ discovered, because there is nothing to discover it by.
+ """
+ files = dict(_metadata_source_files())
+ files.setdefault(DECLARATIVE_BASE_MODULE, set())
+ return files
+
+
+def _file_text(ref, path):
+ """The contents of one tracked file at ``ref``, or None if unreadable.
+
+ Feeds ``schema_change_rule.drop_comment_only_edits``, which needs the
+ source rather than the blob hash. Decoded with ``errors="strict"``: a
+ file that fails to decode as UTF-8 simply stays reported, rather than
+ silently comparing equal to an unrelated blob that also fails to decode.
+ """
+ completed = subprocess.run(
+ ["git", "show", f"{ref}:{path}"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ check=False,
+ )
+ if completed.returncode != 0:
+ return None
+ try:
+ return completed.stdout.decode("utf-8", errors="strict")
+ except UnicodeDecodeError:
+ return None
+
+
+def _source_pair_reader(before, after):
+ """``read_pair`` for ``drop_comment_only_edits`` over two refs."""
+
+ def read_pair(path):
+ before_text = _file_text(before, path)
+ after_text = _file_text(after, path)
+ if before_text is None or after_text is None:
+ return None
+ return before_text, after_text
+
+ return read_pair
+
+
+def _source_file_blobs(ref, paths):
+ """``{path: blob}`` at ``ref``, skipping paths that do not exist there.
+
+ Absent-at-both-ends means "not part of this comparison" -- e.g. a
+ model file added by a later PR is simply not in either map, so a
+ commit-scoped comparison does not report it.
+ """
+ blobs = {}
+ for path in paths:
+ blob = _blob(ref, path)
+ if blob is not None:
+ blobs[path] = blob
+ return blobs
+
+
def _revision_files():
return sorted(
path
@@ -406,11 +546,30 @@ def test_the_schema_and_its_source_files_are_actually_discoverable():
)
source_files = _metadata_source_files()
- assert len(source_files) >= MIN_MODEL_SOURCE_FILES, (
+ assert len(source_files) >= MIN_MODEL_FILES, (
f"only {len(source_files)} source file(s) resolved behind "
f"{len(tables)} tables: {sorted(source_files)}"
)
+ # The named addition to that walk, checked against the disk rather
+ # than trusted: it defines no mapper, so nothing else here would
+ # notice it being renamed away and silently unguarded.
+ assert (REPO_ROOT / DECLARATIVE_BASE_MODULE).is_file(), (
+ f"{DECLARATIVE_BASE_MODULE} does not exist. It holds the canonical "
+ "Base = declarative_base(); if it moved, update "
+ "schema_change_rule.DECLARATIVE_BASE_MODULE, or the schema gates "
+ "stop watching the file that names every constraint create_all() "
+ "emits."
+ )
+ assert DECLARATIVE_BASE_MODULE not in source_files, (
+ f"{DECLARATIVE_BASE_MODULE} now defines a mapped class, so the "
+ "mapper walk reaches it on its own and _guarded_source_files() no "
+ "longer needs to name it -- re-check that helper's reasoning"
+ )
+ assert DECLARATIVE_BASE_MODULE in _guarded_source_files(), (
+ "the guarded set dropped the declarative_base() module"
+ )
+
revisions = _revision_files()
assert len(revisions) >= MIN_REVISIONS, (
f"only {len(revisions)} revision file(s) found under "
@@ -432,7 +591,7 @@ def test_the_schema_and_its_source_files_are_actually_discoverable():
def test_the_metadata_is_fed_by_a_file_the_directory_guard_cannot_see():
"""This file's reason to exist, asserted rather than assumed.
- ``test_upgrade_from_pre_migration_install.py::test_pr_changes_no_orm_model``
+ ``test_upgrade_from_pre_migration_install.py``'s directory guard
diffs ``src/local_deep_research/database/models``. If every file
behind ``Base.metadata`` were inside that directory, the guarantee
would already be complete and the next test would be duplication. It
@@ -440,7 +599,7 @@ def test_the_metadata_is_fed_by_a_file_the_directory_guard_cannot_see():
``domain_classifications`` from outside it.
"""
source_files = _metadata_source_files()
- guarded_prefix = "src/local_deep_research/database/models/"
+ guarded_prefix = f"{MODELS_SUBTREE}/"
unguarded = sorted(
path for path in source_files if not path.startswith(guarded_prefix)
)
@@ -459,70 +618,369 @@ def test_the_metadata_is_fed_by_a_file_the_directory_guard_cannot_see():
)
-def test_every_file_behind_the_alembic_metadata_is_unchanged_since_the_fork():
- """The rollback claim, applied to the schema instead of a directory.
+def test_the_schema_change_rule_is_pinned_without_touching_git():
+ """The rule itself, exercised on hand-written inputs.
+
+ The git-backed tests below can only report on THIS checkout, and on a
+ clean tree they see no changes at all -- so they would pass just as
+ happily if the rule were "anything goes". These cases pin what the
+ rule actually permits and forbids, independently of any working tree.
+
+ Paths are built from the shared subtree constants rather than written
+ short, because the shape of the path is now load-bearing: both callers
+ hand the rule the WHOLE migrations subtree, which contains three files
+ that are not revisions (``env.py`` and two ``__init__.py`` markers)
+ alongside the thirty that are.
+
+ Cases (a) and (c) below are the discriminators for
+ ``schema_change_rule.is_revision``: delete it, so that every path
+ under the subtree counts as a revision again, and both FAIL -- (a)
+ because an added ``README.md`` would then satisfy "ship a migration"
+ and let an unmigrated model edit through, (c) because editing
+ ``env.py`` would then be reported as editing an immutable revision.
+ Case (b) is the control: it passes under both rules, and it is there
+ so a failure in (a) can be read as "the rule got too permissive"
+ rather than "the rule now rejects everything".
+
+ The last group is the discriminator for
+ ``schema_change_rule.drop_comment_only_edits``: those cases pass the
+ rule a filtered ``edited`` list, and they fail if the filter is
+ removed (a reworded comment is reported again) or if it is widened
+ past docstrings (a real code change goes unreported).
+ """
+ versions = f"{MIGRATIONS_SUBTREE}/versions"
+ models = MODELS_SUBTREE
+
+ nothing = classify({}, {})
+ added_rev = classify({}, {f"{versions}/0031_x.py": "aaa"})
+ edited_model = classify(
+ {f"{models}/a.py": "aaa"}, {f"{models}/a.py": "bbb"}
+ )
+
+ # Touching nothing is fine, and so is a revision on its own: data
+ # migrations and backfills change no ORM class.
+ assert violations(nothing, nothing) == []
+ assert violations(nothing, added_rev) == []
+
+ # A model change WITH a new revision is the shape this rule exists to
+ # allow -- the old gate rejected it outright.
+ assert violations(edited_model, added_rev) == []
- ``changelog.d/3299.breaking.md`` says this PR has "no schema to
- reverse". The schema is ``Base.metadata``, so the thing that must not
- have moved is every file that feeds it -- including the one outside
- ``database/models``. Blob hashes, so an edited file is caught as well
- as an added or deleted one.
+ # A model change with no new revision is the dangerous shape, in all
+ # three of its forms.
+ assert len(violations(edited_model, nothing)) == 1
+ assert (
+ len(violations(classify({}, {f"{models}/b.py": "aaa"}), nothing)) == 1
+ )
+ assert (
+ len(violations(classify({f"{models}/c.py": "aaa"}, {}), nothing)) == 1
+ )
+
+ # (a) Adding a non-revision file under the subtree does NOT satisfy
+ # "ship a migration". Reverting is_revision() makes this case FAIL:
+ # the added README would land in revision_changes["added"], the rule
+ # would see a non-empty set, and an unmigrated model edit would ship
+ # unreported.
+ added_readme = classify({}, {f"{MIGRATIONS_SUBTREE}/README.md": "aaa"})
+ assert len(violations(edited_model, added_readme)) == 1, (
+ "adding a README under the migrations subtree is not a migration"
+ )
+ added_marker = classify({}, {f"{versions}/__init__.py": "aaa"})
+ assert len(violations(edited_model, added_marker)) == 1, (
+ "adding the versions/ package marker is not a migration"
+ )
+
+ # (b) Control, not a discriminator: the same model edit WITH a real
+ # revision file is allowed. It passes under both rules, so when (a)
+ # fails it is because the rule got too permissive and not because the
+ # rule now rejects everything.
+ added_real = classify({}, {f"{versions}/0031_x.py": "aaa"})
+ assert violations(edited_model, added_real) == []
+
+ # (c) The non-revision files under the subtree stay editable. Under
+ # the reverted rule this case FAILS: editing env.py would be reported
+ # as a violation, with a message making the false claim that a user's
+ # alembic_version row names env.py -- so env.py would be permanently
+ # unmodifiable.
+ edited_env = classify(
+ {f"{MIGRATIONS_SUBTREE}/env.py": "aaa"},
+ {f"{MIGRATIONS_SUBTREE}/env.py": "bbb"},
+ )
+ assert violations(nothing, edited_env) == [], (
+ "migrations/env.py is Alembic plumbing, not a shipped revision"
+ )
+ edited_markers = classify(
+ {
+ f"{MIGRATIONS_SUBTREE}/__init__.py": "aaa",
+ f"{versions}/__init__.py": "aaa",
+ },
+ {
+ f"{MIGRATIONS_SUBTREE}/__init__.py": "bbb",
+ f"{versions}/__init__.py": "bbb",
+ },
+ )
+ assert violations(nothing, edited_markers) == []
+
+ # Editing or removing a shipped revision is never allowed, not even
+ # alongside an added one.
+ edited_rev = classify(
+ {f"{versions}/0007_y.py": "aaa"}, {f"{versions}/0007_y.py": "bbb"}
+ )
+ removed_rev = classify({f"{versions}/0007_y.py": "aaa"}, {})
+ assert len(violations(nothing, edited_rev)) == 1
+ assert len(violations(nothing, removed_rev)) == 1
+ assert len(violations(edited_model, removed_rev)) == 2
+
+ # Every violation names the offending path, so the failure is
+ # actionable without re-running git by hand.
+ assert f"{models}/a.py" in violations(edited_model, nothing)[0]
+ assert f"{versions}/0007_y.py" in violations(nothing, edited_rev)[0]
+
+ # The canonical declarative_base() module is in the guarded set both
+ # callers hand over (see _guarded_source_files), and the rule treats
+ # it like any other schema source file: edited with no revision is a
+ # violation. Named here because no mapper walk and no models/
+ # directory listing reaches it, so nothing else would notice it being
+ # dropped from the set.
+ edited_base = classify(
+ {DECLARATIVE_BASE_MODULE: "aaa"}, {DECLARATIVE_BASE_MODULE: "bbb"}
+ )
+ assert len(violations(edited_base, nothing)) == 1
+ assert DECLARATIVE_BASE_MODULE in violations(edited_base, nothing)[0]
+ assert violations(edited_base, added_rev) == []
+
+ # A blob moves when a comment moves, and neither Alembic nor
+ # create_all() can see a comment. drop_comment_only_edits is what
+ # keeps the gate from firing on those; it is the filter both callers
+ # run before asking violations(), so it is pinned at the same level.
+ code = (
+ "def upgrade():\n"
+ ' """Add the column."""\n'
+ " # the column\n"
+ ' op.add_column("t", sa.Column("a", sa.Integer()))\n'
+ )
+ cosmetic = (
+ "def upgrade():\n"
+ ' """Add the column, at last."""\n'
+ " # the new column\n"
+ " op.add_column(\n"
+ ' "t", sa.Column("a", sa.Integer())\n'
+ " )\n"
+ )
+ one_token = code.replace('sa.Column("a"', 'sa.Column("b"')
+
+ def edits(path, before_source, after_source):
+ """``classify`` says edited; the filter gets the two sources."""
+ return drop_comment_only_edits(
+ classify({path: "aaa"}, {path: "bbb"}),
+ lambda _path: (before_source, after_source),
+ )
+
+ revision_path = f"{versions}/0007_y.py"
+ model_path = f"{models}/a.py"
+
+ # A comment- and docstring-only edit of a SHIPPED revision is not an
+ # edit: the body Alembic runs is byte-for-byte the same for every
+ # user. Same for a model file: create_all() emits the same DDL.
+ assert violations(nothing, edits(revision_path, code, cosmetic)) == []
+ assert violations(edits(model_path, code, cosmetic), nothing) == []
+
+ # One token of real code, and both fire again. Without this pair the
+ # filter could widen to "any .py edit is cosmetic" and the whole gate
+ # would go quiet.
+ assert len(violations(nothing, edits(revision_path, code, one_token))) == 1
+ assert len(violations(edits(model_path, code, one_token), nothing)) == 1
+
+ # Additions and removals are never filtered, whatever is in them, and
+ # a file that will not parse is reported rather than assumed cosmetic.
+ added_only = drop_comment_only_edits(
+ classify({}, {model_path: "aaa"}), lambda _path: (code, code)
+ )
+ assert len(violations(added_only, nothing)) == 1
+ unparseable = edits(revision_path, code, "def upgrade(:\n")
+ assert len(violations(nothing, unparseable)) == 1
+
+
+def test_only_files_alembic_can_load_as_revisions_count_as_revisions():
+ """``is_revision`` itself, since both halves of the rule turn on it.
+
+ Alembic loads ``versions/*.py``; everything else in the subtree is
+ plumbing. Getting this wrong in the permissive direction lets an
+ unmigrated model change through (a ``README.md`` counts as the
+ migration); getting it wrong in the restrictive direction makes
+ ordinary files permanently unmodifiable and, worse, would exempt a
+ real revision from the immutability rule.
"""
- base = _require_merge_base()
- source_files = _metadata_source_files()
- assert len(source_files) >= MIN_MODEL_SOURCE_FILES, (
+ versions = f"{MIGRATIONS_SUBTREE}/versions"
+
+ for path in (
+ f"{versions}/0001_initial_schema.py",
+ f"{versions}/0030_default_time_period_all.py",
+ f"{versions}/no_number_in_this_name.py",
+ ):
+ assert is_revision(path), path
+
+ for path in (
+ f"{MIGRATIONS_SUBTREE}/env.py",
+ f"{MIGRATIONS_SUBTREE}/__init__.py",
+ f"{MIGRATIONS_SUBTREE}/README.md",
+ f"{versions}/__init__.py",
+ f"{versions}/notes.md",
+ f"{versions}/subdir/0031_x.py",
+ f"{MODELS_SUBTREE}/research.py",
+ ):
+ assert not is_revision(path), path
+
+ # The live directory agrees with the predicate: applied to every file
+ # the migrations tree actually holds, is_revision() picks out exactly
+ # the chain Alembic walks -- no more (the three plumbing files) and no
+ # less. Read from disk rather than from git, so this stays a
+ # git-independent pin.
+ migrations_dir = get_migrations_dir()
+ on_disk = {
+ f"{MIGRATIONS_SUBTREE}/{path.relative_to(migrations_dir).as_posix()}"
+ for path in migrations_dir.rglob("*")
+ if path.is_file() and "__pycache__" not in path.parts
+ }
+ assert len(on_disk) > MIN_REVISIONS, (
+ f"only {len(on_disk)} file(s) under {migrations_dir} -- the "
+ "migrations directory did not resolve, so the cross-check below "
+ "would compare two empty sets"
+ )
+ classified = {path for path in on_disk if is_revision(path)}
+ expected = {
+ f"{MIGRATIONS_SUBTREE}/versions/{path.name}"
+ for path in _revision_files()
+ }
+ assert classified == expected, (
+ "is_revision() and _revision_files() disagree about what the "
+ f"chain contains: {sorted(classified ^ expected)}"
+ )
+ assert on_disk - classified, (
+ "the migrations directory holds nothing but revisions, so this "
+ "test no longer demonstrates that the plumbing files (env.py, the "
+ "package markers) are excluded -- re-check the rule"
+ )
+
+
+def test_the_3299_port_changed_no_file_behind_the_alembic_metadata():
+ """The rollback claim, re-verified at the commit that made it.
+
+ ``changelog.d/3299.breaking.md`` says that release "adds no database
+ schema migration" and that rolling it back needs no schema downgrade.
+ That is a fact about one merge commit, so it is checked against that
+ commit's own range -- which keeps it verifiable forever AND keeps it
+ from misfiring on every later branch, which the generalised rule
+ below governs instead.
+
+ Scoped to the schema rather than to a directory, which is this
+ file's reason to exist: the guarded set includes
+ ``domain_classifier/models.py`` and ``DECLARATIVE_BASE_MODULE``, both
+ outside the directory the guard in
+ ``test_upgrade_from_pre_migration_install.py`` watches. Paths are
+ today's; a file absent at both ends of the range is simply not part of
+ the comparison.
+
+ Byte-identity, not AST-identity: the claim is that #3299 left the
+ schema alone entirely, so a reworded docstring in a model file would
+ contradict it too. The generalised rule below is the one that filters
+ cosmetic edits out.
+ """
+ before, after = _require_commit_range(PORT_3299_COMMIT)
+ source_files = _guarded_source_files()
+ assert len(source_files) >= MIN_MODEL_FILES, (
"discovery collapsed; see "
"test_the_schema_and_its_source_files_are_actually_discoverable"
)
- changed = {}
- for path in sorted(source_files):
- before = _blob(base, path)
- after = _blob("HEAD", path)
- if before is None:
- changed[path] = "added by this branch (absent at the merge base)"
- elif before != after:
- changed[path] = f"edited ({before[:12]} -> {after[:12]})"
-
- assert changed == {}, (
- "This branch changes the schema its own changelog says it does not "
- f"touch: {changed}. Revision 0001 builds the baseline by calling "
- "Base.metadata.create_all(), so a model edit lands in every FRESH "
- "install immediately while existing users -- who only run "
- "0002..0030 -- never receive it. The two populations then run "
- "different schemas and the 'no schema to reverse' rollback claim "
- "is false for one of them. Revert the model edit, or add the "
- "migration and rewrite the rollback section of "
- "changelog.d/3299.breaking.md."
+ baseline = _source_file_blobs(before, source_files)
+ assert len(baseline) >= MODEL_SOURCE_FILES_AT_3299, (
+ f"only {len(baseline)} of {len(source_files)} schema source file(s) "
+ f"resolved at {before[:12]}, expected at least "
+ f"{MODEL_SOURCE_FILES_AT_3299}. This comparison applies TODAY's "
+ "path list to a months-old range, so a file renamed since then is "
+ "absent at both ends and drops out of it silently -- which is what "
+ "this floor is for. Confirm the missing file(s) were renamed and "
+ "not deleted, then update MODEL_SOURCE_FILES_AT_3299."
)
+ changes = classify(baseline, _source_file_blobs(after, source_files))
+ assert changes == {"added": [], "removed": [], "edited": []}, (
+ f"#3299 ({PORT_3299_COMMIT[:12]}) DID change the schema its "
+ f"changelog says it does not touch: {changes}. Either the commit "
+ "sha above is wrong, or changelog.d/3299.breaking.md is false -- "
+ "both its 'adds no database schema migration' sentence and the "
+ "rollback section's 'No schema downgrade is required' -- and must "
+ "be rewritten to describe the downgrade an operator has to run."
+ )
-def test_no_migration_revision_changed_since_the_fork():
- """The other half: an edited revision is a schema change too.
- Editing a revision users have already applied is worse than adding
- one -- their ``alembic_version`` row still says they ran it, so the
- new body never executes and their database is permanently behind the
- code with nothing to indicate it.
+# The migrations-subtree half of the same claim is NOT repeated here.
+# ``test_upgrade_from_pre_migration_install.py::
+# test_the_3299_port_added_or_edited_no_migration_revision`` runs exactly
+# that comparison -- same subtree, same range, same rule -- and this file
+# exists for what a subtree listing cannot see.
+
+
+def test_this_branch_edits_no_revision_and_migrates_every_model_change():
+ """The generalised rule, applied to whatever this branch changed.
+
+ Scoped to the schema rather than to a directory: the file set comes
+ from the live ``Base.metadata`` registry plus
+ ``DECLARATIVE_BASE_MODULE`` (see ``_guarded_source_files``), so an
+ edit to ``domain_classifier/models.py`` or to the canonical
+ ``declarative_base()`` call counts even though both sit outside
+ ``database/models``.
+
+ Why a model edit needs a revision at all is revision ``0001``: it
+ calls ``Base.metadata.create_all()`` rather than shipping frozen DDL,
+ so the baseline a FRESH install receives tracks the model files as
+ they are today, while an existing user only replays the numbered
+ revisions. Without the revision the two populations silently diverge.
+
+ An added revision on its own is fine and is not reported -- data
+ migrations and backfills touch no ORM class. So is an edit that
+ changes no code: ``drop_comment_only_edits`` compares the two ASTs
+ with docstrings stripped, so rewording a comment in a model file or in
+ a shipped revision is not a schema change. Both callers filter first,
+ for the same reason they share the rule.
+
+ What this does NOT check, in either caller, is whether an added
+ revision has anything to do with the model change it is paired with;
+ nothing in this repository does. See
+ ``test_upgrade_from_pre_migration_install.py::
+ test_pr_edits_no_shipped_revision_and_ships_a_migration``.
"""
base = _require_merge_base()
- before = _blobs_under(base, MIGRATIONS_SUBTREE)
- after = _blobs_under("HEAD", MIGRATIONS_SUBTREE)
+ source_files = _guarded_source_files()
+ assert len(source_files) >= MIN_MODEL_FILES, (
+ "discovery collapsed; see "
+ "test_the_schema_and_its_source_files_are_actually_discoverable"
+ )
- assert len(before) >= MIN_REVISIONS, (
- f"only {len(before)} file(s) under {MIGRATIONS_SUBTREE} at {base} -- "
- "the baseline tree did not resolve, so an added or edited migration "
- "would go unnoticed"
+ revisions_before = _blobs_under(base, MIGRATIONS_SUBTREE)
+ assert len(revisions_before) >= MIN_REVISIONS, (
+ f"only {len(revisions_before)} file(s) under {MIGRATIONS_SUBTREE} "
+ f"at {base} -- the baseline tree did not resolve, so an edited "
+ "migration would go unnoticed"
)
- changed = sorted(
- path
- for path in set(before) | set(after)
- if before.get(path) != after.get(path)
+ read_pair = _source_pair_reader(base, "HEAD")
+ model_changes = drop_comment_only_edits(
+ classify(
+ _source_file_blobs(base, source_files),
+ _source_file_blobs("HEAD", source_files),
+ ),
+ read_pair,
)
- assert changed == [], (
- f"migration files changed on this branch: {changed}. Revisions that "
- "shipped are immutable; add a new revision instead."
+ revision_changes = drop_comment_only_edits(
+ classify(revisions_before, _blobs_under("HEAD", MIGRATIONS_SUBTREE)),
+ read_pair,
+ )
+
+ problems = violations(model_changes, revision_changes)
+ assert problems == [], "\n".join(
+ ["this branch breaks the schema-change rule:", *problems]
)
@@ -565,9 +1023,10 @@ def test_revision_0001_builds_the_baseline_from_live_model_metadata():
assert creates_from_metadata, (
"0001 no longer creates the baseline from Base.metadata "
f"(calls: {sorted(calls)}). That is a good change, but the "
- "fresh-vs-upgraded divergence argument in this module's docstring "
- "and in test_every_file_behind_the_alembic_metadata_is_unchanged_"
- "since_the_fork was written against create_all(); re-check it."
+ "fresh-vs-upgraded divergence argument in this module's docstring, "
+ "in schema_change_rule.violations() and in test_this_branch_edits_"
+ "no_revision_and_migrates_every_model_change was written against "
+ "create_all(); re-check it."
)
@@ -602,7 +1061,7 @@ def test_every_table_declared_under_src_is_either_migrated_or_a_separate_db():
if names:
declared[str(path.relative_to(REPO_ROOT))] = names
- assert len(declared) >= MIN_MODEL_SOURCE_FILES, (
+ assert len(declared) >= MIN_MODEL_FILES, (
f"only {len(declared)} file(s) under {SRC_ROOT} declare "
"__tablename__ -- the source scan found nothing to reconcile"
)
diff --git a/tests/database/test_upgrade_from_pre_migration_install.py b/tests/database/test_upgrade_from_pre_migration_install.py
index 2519d9f53d..31e4c4bd30 100644
--- a/tests/database/test_upgrade_from_pre_migration_install.py
+++ b/tests/database/test_upgrade_from_pre_migration_install.py
@@ -9,22 +9,40 @@ new web layer; this file covers the one thing those cannot see, because it
only happens to a database that predates them.
What makes the upgrade safe is a *negative* fact stated in
-``changelog.d/3299.breaking.md``:
-
- This PR adds no Alembic migrations -- verified:
- ``git diff origin/main...HEAD -- src/.../database/migrations/`` is
- empty -- so there is no schema to reverse and rolling back destroys
- no data.
+``changelog.d/3299.breaking.md``: the release "adds no database schema
+migration", and its rollback section says "No schema downgrade is
+required". In other words there is no schema step in either direction --
+nothing to apply on the way up, nothing to reverse on the way back to the
+Flask release.
That claim is load-bearing for both directions (upgrade *and* the documented
rollback to the Flask release), and a changelog sentence cannot enforce
-itself. The first group of tests turns it into an assertion: no migration
-file added or edited, and -- the other half, which the changelog does not
-state -- no ORM model changed either. A model change with no migration is
-the dangerous shape: the schema on disk is then *behind* the code, and every
+itself. The first group of tests turns it into an assertion -- but it is a
+claim about ONE commit, so it is checked against that commit's own range
+(``fb4e33b8d^..fb4e33b8d``): no migration file added or edited there, and --
+the other half, which the changelog does not state -- no ORM model changed
+there either. Scoping it to the commit keeps it a true, re-verified
+statement forever, instead of quietly turning into "no branch may ever add
+a migration" the moment #3299 landed on main.
+
+What every later change must satisfy is the rule that claim was a special
+case of, shared with ``test_migration_chain_integrity.py`` and defined in
+``schema_change_rule.py``: since the merge base, no shipped revision may be
+edited or removed, adding a revision is ordinary, and any ORM model change
+must ship with an added revision. A model change with no migration is the
+dangerous shape: the schema on disk is then *behind* the code, and every
query against the drifted table fails at runtime, on a real user's data,
after the upgrade has already happened.
+Two qualifications on "changed", both in ``schema_change_rule.py``. The
+guarded path set is this directory plus ``DECLARATIVE_BASE_MODULE`` -- the
+canonical ``declarative_base()`` call sits one level above ``models/`` and
+would otherwise be unguarded, though editing it renames every constraint
+``create_all()`` emits. And a file counts as changed only if its *code*
+changed: ``drop_comment_only_edits`` compares the two ASTs with docstrings
+stripped, so rewording a comment or a docstring in a model or a shipped
+revision is not a schema change and is not reported.
+
The second group runs the chain against a populated database, because a
migration can apply cleanly to an empty one and still bail out or corrupt
rows when data is present.
@@ -87,10 +105,22 @@ from local_deep_research.database.models.research import (
from local_deep_research.database.models.settings import SettingType
from local_deep_research.settings.manager import SettingsManager
+from tests.database.schema_change_rule import (
+ DECLARATIVE_BASE_MODULE,
+ MIGRATIONS_SUBTREE,
+ MIN_MODEL_FILES,
+ MIN_REVISIONS,
+ MODELS_SUBTREE,
+ classify,
+ drop_comment_only_edits,
+ violations,
+)
+
REPO_ROOT = Path(__file__).resolve().parents[2]
-MIGRATIONS_SUBTREE = "src/local_deep_research/database/migrations"
-MODELS_SUBTREE = "src/local_deep_research/database/models"
+# The commit that merged #3299, i.e. the commit
+# ``changelog.d/3299.breaking.md`` is talking about.
+PORT_3299_COMMIT = "fb4e33b8d8cba4d62c70cc2704007765ad9f6293"
# An intermediate revision, used to simulate an operator who skipped a few
# releases before taking this one. `0020` is far enough back that the
@@ -142,11 +172,13 @@ def _git(*args):
def _base_ref():
- """The pre-#3299 commit this branch is measured against.
+ """The commit this branch forked from, which it is measured against.
The *merge base* with main, not main's tip: a migration that lands on
main after this branch forked is not this PR's doing, and comparing
- against the tip would report it as a file this branch deleted.
+ against the tip would report it as a file this branch deleted. #3299
+ is behind that merge base now, so this is not a pre-#3299 tree: what
+ it establishes is what THIS branch changed, nothing about the port.
A shallow or detached CI checkout may have no main ref at all, in which
case the git-based tests cannot run and say so rather than passing
@@ -174,6 +206,26 @@ def _require_base_ref():
return base
+def _require_commit_range(sha):
+ """``(parent, commit)`` for ``sha``, or skip.
+
+ A shallow or sparse CI checkout may not contain a months-old commit;
+ saying so beats passing quietly on an empty comparison.
+ """
+ for rev in (f"{sha}^{{commit}}", f"{sha}^^{{commit}}"):
+ code, _ = _git("rev-parse", "--verify", "--quiet", rev)
+ if code != 0:
+ pytest.skip(
+ f"{rev} does not resolve in this checkout, so the #3299 "
+ "no-schema-change claim cannot be re-verified here. A "
+ "shallow clone is the usual cause: fetch-depth: 0 is "
+ "required for this test to run at all."
+ )
+ code, out = _git("rev-parse", f"{sha}^")
+ assert code == 0
+ return out.strip(), sha
+
+
def _tracked_files(ref, subtree):
"""Blob hashes of every file under ``subtree`` at ``ref``.
@@ -191,6 +243,62 @@ def _tracked_files(ref, subtree):
return entries
+def _file_text(ref, path):
+ """The contents of one tracked file at ``ref``, or None if unreadable.
+
+ Feeds ``schema_change_rule.drop_comment_only_edits``, which needs the
+ source rather than the blob hash: two blobs differ the moment a
+ comment moves, and a moved comment changes nothing a user's database
+ can see. Decoded with ``errors="strict"``: a file that fails to decode
+ as UTF-8 simply stays reported, rather than silently comparing equal
+ to an unrelated blob that also fails to decode.
+ """
+ completed = subprocess.run(
+ ["git", "show", f"{ref}:{path}"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ check=False,
+ )
+ if completed.returncode != 0:
+ return None
+ try:
+ return completed.stdout.decode("utf-8", errors="strict")
+ except UnicodeDecodeError:
+ return None
+
+
+def _source_pair_reader(before, after):
+ """``read_pair`` for ``drop_comment_only_edits`` over two refs."""
+
+ def read_pair(path):
+ before_text = _file_text(before, path)
+ after_text = _file_text(after, path)
+ if before_text is None or after_text is None:
+ return None
+ return before_text, after_text
+
+ return read_pair
+
+
+def _guarded_model_files(ref):
+ """``{path: blob}`` for every schema source file this gate watches.
+
+ The ``database/models`` directory listing plus
+ ``DECLARATIVE_BASE_MODULE``. That one file holds the canonical
+ ``Base = declarative_base()`` -- ``models/base.py`` only re-exports it
+ -- and it lives one directory ABOVE the listing, so a directory-scoped
+ diff cannot see it. Handing ``declarative_base()`` a
+ ``metadata=MetaData(naming_convention=...)`` there changes the name of
+ every index and constraint that revision ``0001``'s ``create_all()``
+ emits for a fresh install while existing users keep the old names,
+ which is precisely the divergence this gate exists to catch.
+ """
+ return {
+ **_tracked_files(ref, MODELS_SUBTREE),
+ **_tracked_files(ref, DECLARATIVE_BASE_MODULE),
+ }
+
+
def _engine(tmp_path, request, name):
engine = create_engine(f"sqlite:///{tmp_path}/{name}.db")
request.addfinalizer(engine.dispose)
@@ -299,10 +407,14 @@ def _seed_old_install(engine, locked=False):
def _old_install_at_head(tmp_path, request, name, locked=False):
"""A pre-#3299 database: schema at head, data seeded, version stale.
- Head, not an older revision, is what an existing user actually has:
- ``main`` ships the same 30 revisions this branch does (that is what
- the first group of tests asserts), so a user who upgraded normally is
- already at head and the upgrade applies no migration at all.
+ Head, not an older revision, is what an existing user actually has: a
+ user who keeps up with releases is already at whatever head shipped
+ last, so the interesting case is an upgrade that applies no migration
+ at all and must still not disturb their data. Nothing here assumes
+ ``main`` and this branch ship the same revisions -- they may not, and
+ ``test_pr_edits_no_shipped_revision_and_ships_a_migration`` allows
+ this branch to add revisions. ``run_migrations`` walks to whatever
+ head THIS checkout has, so the fixture follows the branch.
"""
engine = _engine(tmp_path, request, name)
run_migrations(engine)
@@ -324,68 +436,209 @@ def _schema_fingerprint(engine):
# ---------------------------------------------------------------------------
-# 1. the rollback claim: this PR introduces no schema change
+# 1. schema-change gates: the #3299 rollback claim, re-verified at the commit
+# that made it, and the general rule every later branch must satisfy
# ---------------------------------------------------------------------------
-def test_pr_adds_or_edits_no_migration_revision():
- """``changelog.d/3299.breaking.md``: "no schema to reverse"."""
- base = _require_base_ref()
- before = _tracked_files(base, MIGRATIONS_SUBTREE)
- after = _tracked_files("HEAD", MIGRATIONS_SUBTREE)
+def test_the_3299_port_added_or_edited_no_migration_revision():
+ """``changelog.d/3299.breaking.md``: "adds no database schema migration".
- assert len(before) > 1, (
- f"only {len(before)} file(s) under {MIGRATIONS_SUBTREE} at {base} -- "
- "the baseline did not resolve to a real tree, so an added migration "
- "would not have been noticed"
- )
+ Checked against the range of the commit that made the claim, not
+ against the branch under test: the sentence is a fact about #3299,
+ and it stays checkable after #3299 merged. Later branches are
+ governed by ``test_pr_edits_no_shipped_revision_and_ships_a_migration``
+ below.
- added = sorted(set(after) - set(before))
- removed = sorted(set(before) - set(after))
- edited = sorted(
- path for path in set(before) & set(after) if before[path] != after[path]
- )
-
- assert (added, removed, edited) == ([], [], []), (
- "This PR changed the Alembic migrations, which contradicts the "
- "rollback section of changelog.d/3299.breaking.md ('no schema to "
- f"reverse'). added={added} removed={removed} edited={edited}. "
- "Either revert the schema change or rewrite the rollback section to "
+ The whole subtree, not just ``versions/``: #3299 claimed to have left
+ the Alembic directory alone entirely, so an edit to ``env.py`` there
+ would contradict it just as an added revision would. The generalised
+ rule below is narrower on purpose -- ``env.py`` is not immutable, it
+ simply was not touched by this one commit.
+ """
+ before, after = _require_commit_range(PORT_3299_COMMIT)
+ baseline = _tracked_files(before, MIGRATIONS_SUBTREE)
+
+ assert len(baseline) >= MIN_REVISIONS, (
+ f"only {len(baseline)} file(s) under {MIGRATIONS_SUBTREE} at "
+ f"{before[:12]} -- the baseline did not resolve to a real tree, so "
+ "a migration added by #3299 would not have been noticed"
+ )
+
+ changes = classify(baseline, _tracked_files(after, MIGRATIONS_SUBTREE))
+ assert changes == {"added": [], "removed": [], "edited": []}, (
+ f"#3299 ({PORT_3299_COMMIT[:12]}) changed the Alembic migrations, "
+ "which contradicts changelog.d/3299.breaking.md -- both its "
+ "'adds no database schema migration' sentence and the rollback "
+ f"section's 'No schema downgrade is required': {changes}. Either "
+ "the commit sha above is wrong, or those must be rewritten to "
"describe the downgrade an operator now has to run."
)
-def test_pr_changes_no_orm_model():
- """The other half of "no schema to reverse", which the changelog omits.
+def test_the_3299_port_changed_no_orm_model():
+ """The half of the claim the changelog does not state.
An unmigrated model change is worse than an unmentioned migration: the
upgrade appears to succeed, and then every query against the drifted
table fails at runtime against real user data.
+
+ Byte-identity, not AST-identity: this one is a claim that #3299 left
+ the models alone entirely, so a reworded docstring there would
+ contradict it too. The generalised rule below is the one that filters
+ cosmetic edits out.
+ """
+ before, after = _require_commit_range(PORT_3299_COMMIT)
+ baseline = _guarded_model_files(before)
+
+ assert len(baseline) >= MIN_MODEL_FILES, (
+ f"only {len(baseline)} file(s) under {MODELS_SUBTREE} (plus "
+ f"{DECLARATIVE_BASE_MODULE}) at {before[:12]} -- the baseline did "
+ "not resolve to a real tree, so a model change would not have "
+ "been noticed"
+ )
+ assert DECLARATIVE_BASE_MODULE in baseline, (
+ f"{DECLARATIVE_BASE_MODULE} does not resolve at {before[:12]}, so "
+ "the canonical declarative_base() call was silently dropped from "
+ "this comparison -- confirm it was renamed and update the constant"
+ )
+
+ changes = classify(baseline, _guarded_model_files(after))
+ assert changes == {"added": [], "removed": [], "edited": []}, (
+ f"#3299 ({PORT_3299_COMMIT[:12]}) changed ORM models while adding "
+ f"no Alembic migration: {changes}"
+ )
+
+
+def test_pr_edits_no_shipped_revision_and_ships_a_migration():
+ """The generalised rule, applied to whatever this PR changed.
+
+ Three parts, all enforced by ``schema_change_rule.violations``:
+
+ * a revision *file* under ``migrations/versions`` that shipped may not
+ be edited or removed -- an existing user's ``alembic_version`` row
+ already names it, so the new body never executes and their database
+ is permanently behind the code. ``migrations/env.py`` and the two
+ package markers are not revisions and are ordinary source files;
+ * ADDING a revision is ordinary and is not a finding on its own (data
+ migrations, backfills and index-only revisions change no ORM class);
+ * a change under ``database/models`` must come with an added revision
+ file in the same diff.
+
+ That third part is a rule about the two path sets, and only that. It
+ cannot tell whether the added revision has anything to do with the
+ model change: a branch that edits ``research.py`` and adds an
+ unrelated index-only revision satisfies it. **Nothing automated
+ catches that.** This rule is the only control on the pairing, and
+ what it buys is that the model change cannot land while its author is
+ unaware a migration is owed -- checking that the added revision
+ actually matches the model change is a reviewer's job, and there is
+ no test to fall back on if the review misses it.
+
+ ``test_alembic_migrations.py::test_migrations_produce_schema_matching_models``
+ is not that backstop; it covers the opposite direction only. It
+ upgrades a CLEAN database to head and diffs the result against
+ ``Base.metadata``, and revision ``0001`` builds that clean database by
+ calling ``Base.metadata.create_all()`` (pinned by
+ ``test_migration_chain_integrity.py::
+ test_revision_0001_builds_the_baseline_from_live_model_metadata``). So
+ the fresh schema it inspects IS today's metadata: a model column added
+ with no matching revision is present at both ends and produces no
+ diff, and the unrelated revision's extra index is filtered out by that
+ test's ``remove_index`` exemption. What it does catch is a revision
+ that adds something the models do not declare.
+
+ Directory-scoped plus ``DECLARATIVE_BASE_MODULE``, as this file's
+ ``_guarded_model_files`` builds it. ``test_migration_chain_integrity.py``
+ runs the same rule over the file set derived from the live
+ ``Base.metadata``, which also covers the one model file outside this
+ directory. Both callers filter cosmetic edits first, so a reworded
+ comment in a model file or a shipped revision is not reported.
"""
base = _require_base_ref()
- before = _tracked_files(base, MODELS_SUBTREE)
- after = _tracked_files("HEAD", MODELS_SUBTREE)
- assert len(before) > 1, (
- f"only {len(before)} file(s) under {MODELS_SUBTREE} at {base} -- the "
- "baseline did not resolve to a real tree, so a model change would "
- "not have been noticed"
+ revisions_before = _tracked_files(base, MIGRATIONS_SUBTREE)
+ models_before = _guarded_model_files(base)
+ assert (
+ len(revisions_before) >= MIN_REVISIONS
+ and len(models_before) >= MIN_MODEL_FILES
+ ), (
+ f"only {len(revisions_before)} migration file(s) and "
+ f"{len(models_before)} model file(s) at {base} -- the baseline did "
+ "not resolve to a real tree, so a schema change would not have "
+ "been noticed"
+ )
+ assert DECLARATIVE_BASE_MODULE in models_before, (
+ f"{DECLARATIVE_BASE_MODULE} does not resolve at {base}, so the "
+ "canonical declarative_base() call is no longer guarded here -- "
+ "confirm it was renamed and update the constant"
)
- changed = sorted(
- path
- for path in set(before) | set(after)
- if before.get(path) != after.get(path)
+ read_pair = _source_pair_reader(base, "HEAD")
+ revision_changes = drop_comment_only_edits(
+ classify(revisions_before, _tracked_files("HEAD", MIGRATIONS_SUBTREE)),
+ read_pair,
+ )
+ model_changes = drop_comment_only_edits(
+ classify(models_before, _guarded_model_files("HEAD")), read_pair
)
- assert changed == [], (
- "This PR changes ORM models while adding no Alembic migration: "
- f"{changed}. An existing user's database keeps the old columns, so "
- "the first query against the drifted table raises OperationalError "
- "after the upgrade. Add the migration, or revert the model change."
+ problems = violations(model_changes, revision_changes)
+ assert problems == [], "\n".join(
+ ["this PR breaks the schema-change rule:", *problems]
)
+def test_an_added_revision_without_a_model_change_is_allowed():
+ """Positive control for the "additions are ordinary" half.
+
+ The gate above sees no changes on a clean tree, so it would pass just
+ as happily if the rule had tightened back into "no migrations at
+ all". These hand-written inputs hold regardless of git state and say
+ what this file's gate permits, right next to it. They are a subset:
+ the full truth table -- including the cases that separate a revision
+ file from the rest of the migrations subtree -- lives in
+ ``test_migration_chain_integrity.py::test_the_schema_change_rule_is_pinned_without_touching_git``,
+ which is where a regression in the shared rule is diagnosed.
+
+ Paths are built from the shared subtree constants because their shape
+ is load-bearing (``is_revision`` reads it); only the blob hashes are
+ invented, which is what keeps this independent of any working tree.
+ """
+ models = MODELS_SUBTREE
+ no_model_change = classify(
+ {f"{models}/a.py": "aaa"}, {f"{models}/a.py": "aaa"}
+ )
+ added_revision = classify(
+ {}, {f"{MIGRATIONS_SUBTREE}/versions/0031_new.py": "bbb"}
+ )
+
+ assert violations(no_model_change, added_revision) == []
+ assert (
+ violations(
+ classify({f"{models}/a.py": "aaa"}, {f"{models}/a.py": "bbb"}),
+ added_revision,
+ )
+ == []
+ ), "a model change WITH its migration must be allowed"
+
+ # The guarded set this file hands the rule includes the canonical
+ # declarative_base() module, which sits outside MODELS_SUBTREE. Editing
+ # it with no revision is a violation like any other model edit.
+ assert (
+ len(
+ violations(
+ classify(
+ {DECLARATIVE_BASE_MODULE: "aaa"},
+ {DECLARATIVE_BASE_MODULE: "bbb"},
+ ),
+ classify({}, {}),
+ )
+ )
+ == 1
+ ), "an edit to the declarative_base() module needs a revision too"
+
+
def test_every_revision_file_is_on_the_single_chain_to_head():
"""No orphaned or duplicated revision hiding in ``versions/``.
@@ -402,9 +655,9 @@ def test_every_revision_file_is_on_the_single_chain_to_head():
for path in (migrations_dir / "versions").glob("*.py")
if not path.name.startswith("__")
)
- assert len(version_files) > 1, (
- "found no revision files to walk -- the migrations directory did "
- f"not resolve ({migrations_dir})"
+ assert len(version_files) >= MIN_REVISIONS, (
+ f"only {len(version_files)} revision file(s) to walk -- the "
+ f"migrations directory did not resolve ({migrations_dir})"
)
config = AlembicConfig()