From 2eb01a164eba3595ba401bf6a5dbbf6f4d8dd532 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:09:54 -0700 Subject: [PATCH 1/2] feat(scripts): read-only Alembic chain check with cross-chain compare (SEL-531) --- gateway/scripts/check_alembic_chain.py | 230 ++++++++++++++++++++++ gateway/tests/test_check_alembic_chain.py | 221 +++++++++++++++++++++ 2 files changed, 451 insertions(+) create mode 100644 gateway/scripts/check_alembic_chain.py create mode 100644 gateway/tests/test_check_alembic_chain.py diff --git a/gateway/scripts/check_alembic_chain.py b/gateway/scripts/check_alembic_chain.py new file mode 100644 index 000000000..15368dae5 --- /dev/null +++ b/gateway/scripts/check_alembic_chain.py @@ -0,0 +1,230 @@ +"""Check Alembic revision files without importing them or opening a database. + +Usage: python scripts/check_alembic_chain.py [VERSIONS_DIR] [--compare OTHER_VERSIONS_DIR] [--json] +The default directory is gateway/migrations/versions, relative to this file. +""" + +import argparse +import ast +import hashlib +import json +import re +from pathlib import Path + + +DEFAULT_VERSIONS = Path(__file__).resolve().parents[1] / "migrations" / "versions" +NUMBERED_NAME = re.compile(r"^(\d+)_.*$") +# Existing, documented naming anomalies. Keep these exact so new ones still fail. +LEGACY_STEM_MISMATCH = {"022_refresh_tokens.py": "3988bd05deca"} +LEGACY_DUPLICATE_PREFIXES = { + 25: frozenset( + {"025_refresh_token_key_binding.py", "025_remove_plaintext_owner_keys.py"} + ) +} + + +def _assignment(tree: ast.Module, name: str): + values = [] + for node in tree.body: + if isinstance(node, ast.Assign) and any( + isinstance(target, ast.Name) and target.id == name + for target in node.targets + ): + values.append(node.value) + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + if node.target.id == name: + values.append(node.value) + return values + + +def _read_chain(directory: Path): + findings = [] + files = {} + prefixes = {} + for path in sorted(directory.glob("*.py")): + if path.name == "__init__.py": + continue + try: + contents = path.read_bytes() + tree = ast.parse(contents, filename=str(path)) + except (OSError, SyntaxError) as exc: + findings.append(f"{path.name}: cannot parse: {exc}") + continue + + fields = {} + for name in ("revision", "down_revision"): + assignments = _assignment(tree, name) + if len(assignments) != 1 or assignments[0] is None: + findings.append( + f"{path.name}: expected one module-level {name} assignment" + ) + continue + try: + fields[name] = ast.literal_eval(assignments[0]) + except (ValueError, TypeError, MemoryError, RecursionError, SyntaxError): + findings.append(f"{path.name}: {name} must be a literal") + + revision = fields.get("revision") + if not isinstance(revision, str) or not revision: + findings.append(f"{path.name}: revision must be a nonempty string") + continue + down = fields.get("down_revision") + if "down_revision" not in fields or not ( + down is None + or isinstance(down, str) + or isinstance(down, tuple) + and all(isinstance(item, str) for item in down) + ): + findings.append( + f"{path.name}: down_revision must be a string, tuple of strings, or None" + ) + continue + if revision in files: + findings.append( + f"duplicate revision {revision}: {files[revision]['path'].name}, {path.name}" + ) + else: + files[revision] = {"path": path, "down": down, "contents": contents} + + match = NUMBERED_NAME.fullmatch(path.stem) + if match: + prefix = int(match.group(1)) + prefixes.setdefault(prefix, []).append((revision, path)) + if ( + path.stem != revision + and LEGACY_STEM_MISMATCH.get(path.name) != revision + ): + findings.append( + f"{path.name}: filename stem differs from revision {revision}" + ) + + if not files: + findings.append("no revision files found") + for prefix, entries in sorted(prefixes.items()): + if len(entries) > 1 and frozenset(path.name for _, path in entries) != ( + LEGACY_DUPLICATE_PREFIXES.get(prefix) + ): + findings.append( + f"duplicate numeric prefix {prefix:03d}: " + + ", ".join(path.name for _, path in entries) + ) + if prefixes: + for prefix in sorted( + set(range(min(prefixes), max(prefixes) + 1)) - prefixes.keys() + ): + findings.append(f"numeric prefix gap: {prefix:03d}") + + children = {revision: [] for revision in files} + bases = [] + for revision, data in files.items(): + down = data["down"] + if down is None: + bases.append(revision) + for parent in (down,) if isinstance(down, str) else down or (): + if parent not in files: + findings.append(f"{revision}: down_revision {parent} is missing") + else: + children[parent].append(revision) + heads = [revision for revision, successors in children.items() if not successors] + if len(bases) != 1: + findings.append( + f"expected one base; found {len(bases)}: {', '.join(sorted(bases))}" + ) + if len(heads) != 1: + findings.append( + f"expected one head; found {len(heads)}: {', '.join(sorted(heads))}" + ) + for revision, successors in children.items(): + if len(successors) > 1: + findings.append(f"branchpoint {revision}: {', '.join(sorted(successors))}") + if any( + isinstance(data["down"], tuple) and len(data["down"]) > 1 + for data in files.values() + ): + findings.append("merge revision found; chain is not linear") + if len(bases) == 1: + visited = set() + current = bases[0] + while current in files and current not in visited: + visited.add(current) + successors = children[current] + current = successors[0] if len(successors) == 1 else None + if current in visited: + findings.append(f"cycle detected at {current}") + if len(visited) != len(files): + findings.append( + "chain is disconnected or cyclic: " + + ", ".join(sorted(files.keys() - visited)) + ) + return { + "directory": str(directory), + "head": heads[0] if len(heads) == 1 else None, + "findings": findings, + "files": files, + "prefixes": prefixes, + } + + +def _digest(contents: bytes) -> str: + return hashlib.sha256( + contents.replace(b"\r\n", b"\n").replace(b"\r", b"\n") + ).hexdigest() + + +def _compare(left, right): + findings = [] + for prefix in sorted(left["prefixes"].keys() & right["prefixes"].keys()): + left_ids = {revision for revision, _ in left["prefixes"][prefix]} + right_ids = {revision for revision, _ in right["prefixes"][prefix]} + if left_ids != right_ids: + findings.append( + f"numeric prefix {prefix:03d} maps to different revisions: " + f"{', '.join(sorted(left_ids))} vs {', '.join(sorted(right_ids))}" + ) + for label, only in ( + ("first", left["prefixes"].keys() - right["prefixes"].keys()), + ("other", right["prefixes"].keys() - left["prefixes"].keys()), + ): + for prefix in sorted(only): + findings.append(f"numeric prefix {prefix:03d} only in {label} chain") + for revision in sorted(left["files"].keys() & right["files"].keys()): + if _digest(left["files"][revision]["contents"]) != _digest( + right["files"][revision]["contents"] + ): + findings.append(f"revision {revision} has different content") + return findings + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("versions_dir", nargs="?", type=Path, default=DEFAULT_VERSIONS) + parser.add_argument("--compare", type=Path, metavar="OTHER_VERSIONS_DIR") + parser.add_argument( + "--json", action="store_true", help="print machine-readable results" + ) + args = parser.parse_args(argv) + for directory in (args.versions_dir, args.compare): + if directory is not None and not directory.is_dir(): + parser.error(f"not a versions directory: {directory}") + left = _read_chain(args.versions_dir) + right = _read_chain(args.compare) if args.compare else None + findings = [f"{left['directory']}: {item}" for item in left["findings"]] + if right: + findings.extend(f"{right['directory']}: {item}" for item in right["findings"]) + findings.extend(_compare(left, right)) + result = {"head": left["head"], "findings": findings} + if right: + result["other_head"] = right["head"] + if args.json: + print(json.dumps(result, indent=2)) + elif findings: + print("Alembic chain findings:") + for finding in findings: + print(f"- {finding}") + else: + print(f"Alembic chain OK; head: {left['head']}") + return int(bool(findings)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gateway/tests/test_check_alembic_chain.py b/gateway/tests/test_check_alembic_chain.py new file mode 100644 index 000000000..263f8567d --- /dev/null +++ b/gateway/tests/test_check_alembic_chain.py @@ -0,0 +1,221 @@ +"""Exercise the read-only checker against the repository's real migrations.""" + +import ast +import importlib.util +import json +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + + +GATEWAY = Path(__file__).resolve().parents[1] +VERSIONS = GATEWAY / "migrations" / "versions" +SCRIPT = GATEWAY / "scripts" / "check_alembic_chain.py" + + +def _metadata(path): + tree = ast.parse(path.read_bytes()) + values = {} + for node in tree.body: + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + if node.target.id in {"revision", "down_revision"}: + values[node.target.id] = ast.literal_eval(node.value) + elif isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name) and target.id in { + "revision", + "down_revision", + }: + values[target.id] = ast.literal_eval(node.value) + return values + + +def _files(): + return sorted(VERSIONS.glob("[0-9]*_*.py")) + + +def _copy(tmp_path): + destination = tmp_path / "versions" + shutil.copytree(VERSIONS, destination) + return destination + + +def _run(*args): + completed = subprocess.run( + [sys.executable, str(SCRIPT), *map(str, args), "--json"], + check=False, + capture_output=True, + text=True, + ) + return completed.returncode, json.loads(completed.stdout) + + +def _rewrite_down(path, replacement): + source = path.read_text() + tree = ast.parse(source) + for node in tree.body: + if isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + if any( + isinstance(target, ast.Name) and target.id == "down_revision" + for target in targets + ): + lines = source.splitlines(keepends=True) + line = lines[node.lineno - 1] + lines[node.lineno - 1] = re.sub( + r"(=\s*)(?:\"[^\"]+\"|'[^']+'|None|\([^)]*\))", + lambda match: match.group(1) + repr(replacement), + line, + count=1, + ) + path.write_text("".join(lines)) + return + raise AssertionError(f"no down_revision in {path}") + + +def test_real_chain_has_one_highest_numbered_head(capsys): + spec = importlib.util.spec_from_file_location("check_alembic_chain", SCRIPT) + assert spec and spec.loader + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + + result = checker.main(["--json"]) + output = json.loads(capsys.readouterr().out) + highest = max(_files(), key=lambda path: int(path.stem.split("_", 1)[0])) + assert result == 0 + assert output["findings"] == [] + assert output["head"] == _metadata(highest)["revision"] + + +def test_missing_middle_migration_reports_broken_link(tmp_path): + directory = _copy(tmp_path) + files = _files() + middle = files[len(files) // 2] + (directory / middle.name).unlink() + status, output = _run(directory) + assert status == 1 + assert any( + "down_revision" in finding and "missing" in finding + for finding in output["findings"] + ) + + +def test_duplicate_revision(tmp_path): + directory = _copy(tmp_path) + original = _files()[0] + duplicate = directory / f"{original.stem}_copy.py" + shutil.copyfile(directory / original.name, duplicate) + status, output = _run(directory) + assert status == 1 + assert any("duplicate revision" in finding for finding in output["findings"]) + + +def test_multiple_heads_and_branchpoint(tmp_path): + directory = _copy(tmp_path) + files = _files() + victim = files[len(files) // 2] + earlier = files[len(files) // 4] + _rewrite_down(directory / victim.name, _metadata(earlier)["revision"]) + status, output = _run(directory) + assert status == 1 + assert any("expected one head" in finding for finding in output["findings"]) + assert any("branchpoint" in finding for finding in output["findings"]) + + +def test_single_parent_tuple_is_parsed(tmp_path): + directory = _copy(tmp_path) + path = _files()[-1] + parent = _metadata(path)["down_revision"] + _rewrite_down(directory / path.name, (parent,)) + status, output = _run(directory) + assert status == 0 + assert output["findings"] == [] + + +def test_numeric_prefix_gap(tmp_path): + directory = _copy(tmp_path) + files = _files() + counts = {} + for path in files: + prefix = path.stem.split("_", 1)[0] + counts[prefix] = counts.get(prefix, 0) + 1 + middle = next( + path + for path in files[len(files) // 4 : -len(files) // 4] + if counts[path.stem.split("_", 1)[0]] == 1 + ) + (directory / middle.name).unlink() + status, output = _run(directory) + assert status == 1 + assert any("numeric prefix gap" in finding for finding in output["findings"]) + + +def test_identical_copy_compares_cleanly(tmp_path): + directory = _copy(tmp_path) + status, output = _run(VERSIONS, "--compare", directory) + assert status == 0 + assert output["findings"] == [] + + +def test_same_revision_with_changed_content_fails_comparison(tmp_path): + directory = _copy(tmp_path) + path = directory / _files()[-1].name + path.write_bytes(path.read_bytes() + b"\n# comparison change\n") + status, output = _run(VERSIONS, "--compare", directory) + assert status == 1 + assert any("different content" in finding for finding in output["findings"]) + + +def test_same_prefix_with_different_real_revision_fails_comparison(tmp_path): + directory = _copy(tmp_path) + earlier, later = _files()[-2:] + shutil.copyfile(directory / earlier.name, directory / later.name) + status, output = _run(VERSIONS, "--compare", directory) + assert status == 1 + assert any( + "maps to different revisions" in finding for finding in output["findings"] + ) + + +def test_comparison_normalizes_line_endings(tmp_path): + directory = _copy(tmp_path) + path = directory / _files()[-1].name + path.write_bytes(path.read_bytes().replace(b"\n", b"\r\n")) + status, output = _run(VERSIONS, "--compare", directory) + assert status == 0 + assert output["findings"] == [] + + +def test_missing_prefix_is_reported_in_comparison(tmp_path): + directory = _copy(tmp_path) + files = _files() + counts = {} + for path in files: + prefix = path.stem.split("_", 1)[0] + counts[prefix] = counts.get(prefix, 0) + 1 + missing = next( + path for path in reversed(files) if counts[path.stem.split("_", 1)[0]] == 1 + ) + (directory / missing.name).unlink() + status, output = _run(VERSIONS, "--compare", directory) + assert status == 1 + prefix = missing.stem.split("_", 1)[0] + assert any( + f"numeric prefix {prefix} only in first chain" in finding + for finding in output["findings"] + ) + + +@pytest.mark.parametrize("arguments", [["--unknown"], ["missing-versions-directory"]]) +def test_usage_errors_exit_two(arguments): + completed = subprocess.run( + [sys.executable, str(SCRIPT), *arguments], + check=False, + capture_output=True, + text=True, + ) + assert completed.returncode == 2 From 3fa664e3a546f35da2589999e90ab33d4e0a933a Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:18:21 -0700 Subject: [PATCH 2/2] SEL-531: report unnumbered compare-only revisions, name cycle members, test exact allowlists Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/scripts/check_alembic_chain.py | 43 ++++++- gateway/tests/test_check_alembic_chain.py | 150 ++++++++++++++++++++++ 2 files changed, 191 insertions(+), 2 deletions(-) diff --git a/gateway/scripts/check_alembic_chain.py b/gateway/scripts/check_alembic_chain.py index 15368dae5..55680dbba 100644 --- a/gateway/scripts/check_alembic_chain.py +++ b/gateway/scripts/check_alembic_chain.py @@ -2,6 +2,12 @@ Usage: python scripts/check_alembic_chain.py [VERSIONS_DIR] [--compare OTHER_VERSIONS_DIR] [--json] The default directory is gateway/migrations/versions, relative to this file. + +Only module-level ``revision`` and ``down_revision`` literals are read. +``branch_labels`` and ``depends_on`` are ignored: they are not checked and do +not affect bases, heads, branchpoints, cycles, or --compare results. +In --compare mode every revision id present in only one chain is reported, +whether or not its filename has a numeric prefix. """ import argparse @@ -142,6 +148,8 @@ def _read_chain(directory: Path): for data in files.values() ): findings.append("merge revision found; chain is not linear") + for cycle in _cycles(files): + findings.append("cycle detected: " + " -> ".join(cycle + [cycle[0]])) if len(bases) == 1: visited = set() current = bases[0] @@ -149,8 +157,6 @@ def _read_chain(directory: Path): visited.add(current) successors = children[current] current = successors[0] if len(successors) == 1 else None - if current in visited: - findings.append(f"cycle detected at {current}") if len(visited) != len(files): findings.append( "chain is disconnected or cyclic: " @@ -165,6 +171,29 @@ def _read_chain(directory: Path): } +def _cycles(files): + """Return each down_revision cycle once, as revisions in child-to-parent order.""" + cycles = [] + seen = set() + for start in sorted(files): + path = [] + index = {} + current = start + while current in files and current not in seen: + if current in index: + cycle = path[index[current] :] + pivot = cycle.index(min(cycle)) + cycles.append(cycle[pivot:] + cycle[:pivot]) + break + index[current] = len(path) + path.append(current) + down = files[current]["down"] + parents = (down,) if isinstance(down, str) else down or () + current = parents[0] if len(parents) == 1 else None + seen.update(path) + return cycles + + def _digest(contents: bytes) -> str: return hashlib.sha256( contents.replace(b"\r\n", b"\n").replace(b"\r", b"\n") @@ -187,6 +216,16 @@ def _compare(left, right): ): for prefix in sorted(only): findings.append(f"numeric prefix {prefix:03d} only in {label} chain") + for label, only in ( + ("first", left["files"].keys() - right["files"].keys()), + ("other", right["files"].keys() - left["files"].keys()), + ): + for revision in sorted(only): + files = left["files"] if label == "first" else right["files"] + findings.append( + f"revision {revision} only in {label} chain " + f"({files[revision]['path'].name})" + ) for revision in sorted(left["files"].keys() & right["files"].keys()): if _digest(left["files"][revision]["contents"]) != _digest( right["files"][revision]["contents"] diff --git a/gateway/tests/test_check_alembic_chain.py b/gateway/tests/test_check_alembic_chain.py index 263f8567d..1f7cb980c 100644 --- a/gateway/tests/test_check_alembic_chain.py +++ b/gateway/tests/test_check_alembic_chain.py @@ -219,3 +219,153 @@ def test_usage_errors_exit_two(arguments): text=True, ) assert completed.returncode == 2 + + +def _numbered(directory): + return sorted( + path + for path in directory.glob("[0-9]*_*.py") + if path.stem == _metadata(path)["revision"] + ) + + +def _rewrite_line(path, name, replacement): + lines = path.read_text().splitlines(keepends=True) + for number, line in enumerate(lines): + if re.match(rf"{name}\b\s*[:=]", line): + lines[number] = replacement + path.write_text("".join(lines)) + return + raise AssertionError(f"no {name} in {path}") + + +def test_legacy_duplicate_prefix_allowlist_is_exact(tmp_path): + directory = _copy(tmp_path) + source = _numbered(directory)[-1] + moved = directory / ("025_" + source.name.split("_", 1)[1]) + source.rename(moved) + status, output = _run(directory) + assert status == 1 + assert any( + "duplicate numeric prefix 025:" in finding and moved.name in finding + for finding in output["findings"] + ) + + +def test_new_duplicate_prefix_outside_allowlist_fails(tmp_path): + directory = _copy(tmp_path) + numbered = _numbered(directory) + target, source = numbered[-2], numbered[-1] + prefix = target.name.split("_", 1)[0] + moved = directory / (prefix + "_" + source.name.split("_", 1)[1]) + source.rename(moved) + status, output = _run(directory) + assert status == 1 + assert any( + f"duplicate numeric prefix {prefix}:" in finding + for finding in output["findings"] + ) + + +def test_legacy_stem_mismatch_allowlist_is_keyed_by_exact_filename(tmp_path): + directory = _copy(tmp_path) + legacy = directory / "022_refresh_tokens.py" + renamed = directory / "022_refresh_tokens_renamed.py" + legacy.rename(renamed) + status, output = _run(directory) + assert status == 1 + assert any( + f"{renamed.name}: filename stem differs" in finding + for finding in output["findings"] + ) + + +def test_new_stem_mismatch_fails(tmp_path): + directory = _copy(tmp_path) + source = _numbered(directory)[len(_numbered(directory)) // 2] + renamed = directory / f"{source.stem}_renamed.py" + source.rename(renamed) + status, output = _run(directory) + assert status == 1 + assert any( + f"{renamed.name}: filename stem differs" in finding + for finding in output["findings"] + ) + + +def test_syntax_error_is_reported(tmp_path): + directory = _copy(tmp_path) + path = directory / _files()[-1].name + path.write_text(path.read_text() + "\ndef broken(:\n") + status, output = _run(directory) + assert status == 1 + assert any( + f"{path.name}: cannot parse" in finding for finding in output["findings"] + ) + + +def test_missing_revision_assignment_is_reported(tmp_path): + directory = _copy(tmp_path) + path = directory / _files()[-1].name + _rewrite_line(path, "revision", "\n") + status, output = _run(directory) + assert status == 1 + assert any( + f"{path.name}: expected one module-level revision assignment" in finding + for finding in output["findings"] + ) + + +def test_duplicate_revision_assignment_is_reported(tmp_path): + directory = _copy(tmp_path) + path = directory / _files()[-1].name + path.write_text( + path.read_text() + f"\nrevision = {_metadata(path)['revision']!r}\n" + ) + status, output = _run(directory) + assert status == 1 + assert any( + f"{path.name}: expected one module-level revision assignment" in finding + for finding in output["findings"] + ) + + +def test_non_literal_down_revision_is_reported(tmp_path): + directory = _copy(tmp_path) + path = directory / _files()[-1].name + _rewrite_line(path, "down_revision", "down_revision = revision\n") + status, output = _run(directory) + assert status == 1 + assert any( + f"{path.name}: down_revision must be a literal" in finding + for finding in output["findings"] + ) + + +def test_cycle_error_names_every_revision(tmp_path): + directory = _copy(tmp_path) + numbered = _numbered(directory) + first, second = numbered[-2], numbered[-1] + _rewrite_down(first, _metadata(second)["revision"]) + status, output = _run(directory) + assert status == 1 + ids = sorted([_metadata(first)["revision"], _metadata(second)["revision"]]) + expected = f"cycle detected: {ids[0]} -> {ids[1]} -> {ids[0]}" + assert any(finding.endswith(expected) for finding in output["findings"]) + + +def test_unnumbered_revision_only_in_one_chain_is_reported(tmp_path): + left = _copy(tmp_path / "left") + right = _copy(tmp_path / "right") + last = _numbered(left)[-1] + revision = _metadata(last)["revision"] + unnumbered = left / last.name.split("_", 1)[1] + last.rename(unnumbered) + (right / last.name).unlink() + status, output = _run(left, "--compare", right) + assert status == 1 + assert not any("numeric prefix" in f and "only in" in f for f in output["findings"]) + assert ( + f"revision {revision} only in first chain ({unnumbered.name})" + in output["findings"] + )