diff --git a/CHANGELOG.md b/CHANGELOG.md index 86461c7..a0316e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ Changes are recorded in [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format. +## [0.9.1] + +### Fixed + +- **`up` could record a migration it never ran.** `ch-migrate new` writes Alembic's template, then replaces it. When both fell in the same second and were the same size, Python kept running the template it had cached, whose `upgrade()` does nothing, and `up` recorded the revision as applied. The size depends on the message, the object name and, with `--irreversible`, the reason, so it took a particular combination: a 41-character message with a 40-character `--dict` name was one. `new --exchange` and `rebase` rewrote files the same way. Every rewrite now drops the cached bytecode, and `up` and `down` drop it for every revision before they start. + + Only the checkout where a revision was created or rebased could be affected: a fresh checkout, such as CI, compiles the final file. If you ran `up` from that checkout on 0.9.0 or earlier: + + 1. Before the first `up` or `down` on 0.9.1, which clear these caches, list the revisions whose cached code is still the template: + + ```bash + sh -c 'for f in migrations/versions/*.py; do grep -q get_db "$f" || grep -l get_db "migrations/versions/__pycache__/$(basename "$f" .py)".*.pyc; done' 2>/dev/null + ``` + + A revision you haven't run yet can be listed too. An empty list doesn't prove none was affected: an edit or a Python upgrade also replaces the cache. + 2. Compare the revisions you created there with the database. Where a change is missing, put the same statements in a new migration. Upgrading doesn't rerun it, because the database says it was applied. + ## [0.9.0] 0.9 declares users, roles and grants in `access.yaml`. `ch-migrate access plan` shows how a server differs from it, and `access apply` makes the server match, logged in as the admin. A new project's migration role holds only what migrations need, with no right to manage users or roles. A normal `pip install -U` reaches 0.9 from 0.8, so read this before upgrading: diff --git a/ch_migrate/__init__.py b/ch_migrate/__init__.py index 2943254..e1c59f4 100644 --- a/ch_migrate/__init__.py +++ b/ch_migrate/__init__.py @@ -5,7 +5,7 @@ from ch_migrate import read_sql, get_db, get_env_config, create_dictionary """ -__version__ = "0.9.0" +__version__ = "0.9.1" from typing import Any diff --git a/ch_migrate/cli.py b/ch_migrate/cli.py index 5c1cb3e..30f3a23 100644 --- a/ch_migrate/cli.py +++ b/ch_migrate/cli.py @@ -428,10 +428,11 @@ def _check_new_options(options: NewOptions) -> None: def _create_sql_first_migration(migration_path: Path, options: NewOptions) -> None: from ch_migrate.authoring import read_revision_header, render_revision, write_sql_files + from ch_migrate.revision_files import write_revision header = read_revision_header(migration_path) files = write_sql_files(Path.cwd() / "migrations" / "sql", header, options) - migration_path.write_text(render_revision(header, files, options.irreversible_reason)) + write_revision(migration_path, render_revision(header, files, options.irreversible_reason)) ui.success(f"Created migration {header.revision[:8]} {header.message}") ui.detail(f"migrations/sql/{files.upgrade}") if files.downgrade: diff --git a/ch_migrate/migration_runner.py b/ch_migrate/migration_runner.py index ca1cbfc..5e2ea67 100644 --- a/ch_migrate/migration_runner.py +++ b/ch_migrate/migration_runner.py @@ -21,6 +21,7 @@ from alembic.config import Config from ch_migrate import ui +from ch_migrate.revision_files import discard_revision_bytecode from ch_migrate.runner import ( _RUNNING, _SELF_DESCRIBING, @@ -63,6 +64,7 @@ def run_upgrade(upgrade: Upgrade) -> int: # Project helpers intentionally read these during migration execution only. saved = {name: os.environ.get(name) for name in ("CH_DATABASE", "CH_CLUSTER")} try: + discard_revision_bytecode(Path.cwd() / "migrations" / "versions") with _restored_loggers("alembic", "ch_migrate"): command.upgrade(config, upgrade.revision) except KeyboardInterrupt: diff --git a/ch_migrate/rebase.py b/ch_migrate/rebase.py index fa8fd74..cd0e0cc 100644 --- a/ch_migrate/rebase.py +++ b/ch_migrate/rebase.py @@ -8,6 +8,8 @@ from pathlib import Path from typing import Any +from ch_migrate.revision_files import write_revision + DownRevisions = tuple[str, ...] _MISSING = object() @@ -305,4 +307,4 @@ def apply_rebase(changes: list[RebaseChange]) -> None: change.old_down_revision, change.new_down_revision, ) - change.migration.path.write_text(new_content) + write_revision(change.migration.path, new_content) diff --git a/ch_migrate/revision_files.py b/ch_migrate/revision_files.py new file mode 100644 index 0000000..0ba8051 --- /dev/null +++ b/ch_migrate/revision_files.py @@ -0,0 +1,35 @@ +"""Writing revision files without leaving stale bytecode behind. + +Python reuses a revision's cached `.pyc` when the source file's size and modified time, +in whole seconds, still match. `new` and `rebase` rewrite a file Alembic may already have +loaded, often in the same second and sometimes at the same size, so the old bytecode would +keep running and a migration could be recorded as applied without sending its SQL. +""" + +from __future__ import annotations + +import contextlib +import glob +import importlib.util +from pathlib import Path + + +def write_revision(path: Path, content: str) -> None: + """Write a revision file, and drop bytecode cached from what it held before.""" + path.write_text(content) + _discard_bytecode(path) + + +def discard_revision_bytecode(versions_dir: Path) -> None: + """Make the next load of every revision compile the file on disk.""" + for path in versions_dir.glob("*.py"): + _discard_bytecode(path) + + +def _discard_bytecode(path: Path) -> None: + # Best effort: a cache that can't be removed, as in a read-only checkout, must not + # stop a command. + with contextlib.suppress(OSError, NotImplementedError): + cache_dir = Path(importlib.util.cache_from_source(str(path))).parent + for cached in cache_dir.glob(f"{glob.escape(path.stem)}.*.pyc"): + cached.unlink(missing_ok=True) diff --git a/ch_migrate/runner.py b/ch_migrate/runner.py index c041daa..9cd2d81 100644 --- a/ch_migrate/runner.py +++ b/ch_migrate/runner.py @@ -20,6 +20,7 @@ from ch_migrate import ui from ch_migrate.config import get_env_config +from ch_migrate.revision_files import discard_revision_bytecode from ch_migrate.sql import clean_database_error _LOG_LINE = re.compile(r"^(?P[A-Z]+)\s+\[(?P[^\]]+)\]\s?(?P.*)$") @@ -37,6 +38,7 @@ def run_migrations(environment: str, args: list[str], *, verbose: bool) -> int: Returns Alembic's exit status. """ progress = _Progress() + discard_revision_bytecode(Path.cwd() / "migrations" / "versions") command = [sys.executable, "-m", "alembic", *args] with subprocess.Popen( command, diff --git a/ch_migrate/scaffold.py b/ch_migrate/scaffold.py index 958e10f..aef6450 100644 --- a/ch_migrate/scaffold.py +++ b/ch_migrate/scaffold.py @@ -7,6 +7,8 @@ from pathlib import Path from typing import Any +from ch_migrate.revision_files import write_revision + def fetch_current_ddl(env_config: dict[str, Any], table_name: str) -> str | None: """Fetch current CREATE TABLE statement from the live database. @@ -246,4 +248,4 @@ def rewrite_migration_file( sql_path=sql_path, dict_names=dict_names, ) - migration_path.write_text(new_content) + write_revision(migration_path, new_content) diff --git a/tests/test_revision_files.py b/tests/test_revision_files.py new file mode 100644 index 0000000..86c11ea --- /dev/null +++ b/tests/test_revision_files.py @@ -0,0 +1,142 @@ +"""A rewritten revision file is always the one that runs.""" + +import importlib.util +import os +import py_compile + +import pytest +from click.testing import CliRunner + +from ch_migrate import migration_runner, runner +from ch_migrate.cli import main +from ch_migrate.rebase import RebaseChange, apply_rebase, parse_migration +from ch_migrate.revision_files import discard_revision_bytecode, write_revision + +_FIRST = "def upgrade():\n return 'empty!'\n" +_SECOND = "def upgrade():\n return 'filled'\n" +_WHEN = 1_700_000_000 + + +@pytest.fixture +def stale(tmp_path): + """A revision rewritten within the second, at the same size, after Python cached it.""" + path = tmp_path / "2026_01_01_0000_add_thing.py" + _write_at(path, _FIRST) + py_compile.compile(str(path)) + assert len(_FIRST) == len(_SECOND) + return path + + +@pytest.fixture +def stale_project(tmp_path, monkeypatch, stale): + """A project whose only revision has a stale cache, as an older version left it.""" + versions = tmp_path / "migrations" / "versions" + versions.mkdir(parents=True) + path = versions / stale.name + _write_at(path, _FIRST) + py_compile.compile(str(path)) + _write_at(path, _SECOND) + monkeypatch.chdir(tmp_path) + return path + + +def test_equal_size_rewrite_in_one_second_would_run_the_old_code(stale): + # The hazard itself: without dropping the cache, Python runs the first version. + _write_at(stale, _SECOND) + assert _load(stale).upgrade() == "empty!" + + +def test_write_revision_runs_what_is_on_disk(stale): + write_revision(stale, _SECOND) + os.utime(stale, (_WHEN, _WHEN)) + assert _load(stale).upgrade() == "filled" + + +def test_discard_revision_bytecode_covers_every_revision(stale): + _write_at(stale, _SECOND) + discard_revision_bytecode(stale.parent) + assert _load(stale).upgrade() == "filled" + + +def test_discard_revision_bytecode_ignores_a_cache_it_cannot_remove(stale, monkeypatch): + def refuse(self, missing_ok=False): + raise PermissionError(str(self)) + + monkeypatch.setattr("pathlib.Path.unlink", refuse) + discard_revision_bytecode(stale.parent) + + +def test_discard_revision_bytecode_accepts_a_missing_directory(tmp_path): + discard_revision_bytecode(tmp_path / "versions") + + +def test_up_drops_a_stale_cache_before_alembic_loads_a_revision(stale_project, monkeypatch): + seen = [] + monkeypatch.setattr(migration_runner, "_alembic_config", lambda *args: None) + monkeypatch.setattr( + migration_runner.command, + "upgrade", + lambda *args: seen.append(_load(stale_project).upgrade()), + ) + migration_runner.run_upgrade(migration_runner.Upgrade("dev")) + assert seen == ["filled"] + + +def test_down_drops_a_stale_cache_before_alembic_loads_a_revision(stale_project, monkeypatch): + seen = [] + + class Process: + stdout = iter(()) + + def __init__(self, *args, **kwargs): + seen.append(_load(stale_project).upgrade()) + + def __enter__(self): + return self + + def __exit__(self, *exc): + return None + + def wait(self): + return 0 + + monkeypatch.setattr(runner, "alembic_env", lambda environment: {}) + monkeypatch.setattr(runner.subprocess, "Popen", Process) + runner.run_migrations("dev", ["downgrade", "-1"], verbose=False) + assert seen == ["filled"] + + +def test_rebase_runs_the_new_parent(tmp_path): + path = tmp_path / "2026_01_01_0000_b.py" + old, new = "aaaaaaaaaaaa", "bbbbbbbbbbbb" + _write_at(path, f"revision = 'cccccccccccc'\ndown_revision = '{old}'\n") + py_compile.compile(str(path)) + migration = parse_migration(path) + apply_rebase([RebaseChange(migration, old, new)]) + os.utime(path, (_WHEN, _WHEN)) + assert _load(path).down_revision == new + + +@pytest.mark.parametrize("options", [[], ["--irreversible", "It drops data"], ["--exchange"]]) +def test_new_leaves_no_bytecode_from_the_template(tmp_path, monkeypatch, options): + assert CliRunner().invoke(main, ["init", str(tmp_path), "--name", "demo"]).exit_code == 0 + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("CH_DEV_MIGRATION_PASSWORD", "test-only") + table = ["--table", "logs"] + result = CliRunner().invoke(main, ["new", "dev", "add_status", *table, *options]) + assert result.exit_code == 0, result.output + [revision] = (tmp_path / "migrations" / "versions").glob("*.py") + cached = importlib.util.cache_from_source(str(revision)) + assert not os.path.exists(cached) + + +def _write_at(path, content): + path.write_text(content) + os.utime(path, (_WHEN, _WHEN)) + + +def _load(path): + spec = importlib.util.spec_from_file_location("revision_under_test", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module