Buckets:

download
raw
18.3 kB
"""Reusable harness for the migration/model lockstep guard.
The fresh-database bootstrap builds the schema with ``create_all()`` from
``Base.metadata`` and then STAMPS Alembic head — asserting, without checking,
that the models and the migration chain describe the same schema. This module
makes that assertion checkable in CI: build a frozen, certified snapshot of the
model schema as a real database and replay the chain over it — the ENTIRE
chain from its initial revision (the whole-history probe), and, separately,
only the migrations added since the freeze from a stamp at the frozen revision
(the fast post-freeze probe) — then compare each result against the current
models in both directions. The seed is always the FROZEN state, never live
``Base.metadata``: a live-model seed already contains any model change whose
migration is missing, hiding exactly the divergence being checked.
It lives in the runtime package (not under ``tests/``) so downstream
deployments that vendor their own Alembic chain — e.g. cognee cloud, whose
chain, model surface, and certified baseline all differ from upstream's — can
reuse it verbatim, varying only:
- the model surface: what ``Base.metadata`` holds after the deployment's
SERVER entrypoint is imported (``server_model_schema``; upstream's is
``cognee.api.client``, a deployment names its own). Location-agnostic by
construction: SQLAlchemy registers a model wherever its class lives, so no
directory convention is involved. A model no process imports touches no
database, and the moment one is imported the probes report its missing
migration;
- ``script_location``: the Alembic scripts directory (upstream tests pass
``packaged_script_location()`` explicitly so the ambient
``COGNEE_ALEMBIC_PATH`` override cannot retarget them; a vendored chain
passes its own path);
- the frozen baseline file, generated by ``generate_baseline`` at that
deployment's own certified revision.
Scope of the guarantee — NAME level, single schema:
- The comparison covers table and column NAMES. Types, nullability, server
defaults, primary/foreign keys, unique constraints, and indexes are out of
scope here (the runtime schema check at startup and a future
``alembic.autogenerate.compare_metadata``-based deep compare cover that
layer). The replay base is likewise built with generic column types.
- Because the baseline stores names only, a post-freeze migration that drops
or alters a PRE-freeze index or constraint by name must be written
existence-guarded (the established house pattern) — on the replay database
those objects do not exist.
- Reflection queries the default schema only; schema-qualified tables are out
of scope (relevant to downstream Postgres deployments).
See ``cognee/tests/e2e/migrations/test_migration_model_lockstep.py`` for the
upstream wiring and the re-freezing rules.
"""
import importlib
import json
import subprocess
import sys
from collections.abc import Callable, Iterable
from pathlib import Path
import sqlalchemy as sa
from sqlalchemy import inspect
# Tables exempt from every comparison:
# - alembic_version: Alembic's own bookkeeping, lives outside the models on purpose;
# - notebooks: known, accepted legacy — the chain creates it but the Notebook
# model was removed without its drop migration ever being written (audited
# 2026-09-01, the chain's only such table); writing that migration retires
# the entry.
IGNORED_TABLES = frozenset({"alembic_version", "notebooks"})
# The entrypoint whose import registers the upstream server's model surface.
SERVER_ENTRYPOINT = "cognee.api.client"
def register_server_models(entrypoint: str = SERVER_ENTRYPOINT) -> None:
"""Register the model surface a real server process starts with, by
importing its entrypoint. In-process: use it only from a fresh interpreter
(``generate_baseline`` via the CLI wrapper), never from a test session that
may already have imported other models — see ``server_model_schema``."""
importlib.import_module(entrypoint)
def server_model_schema(
entrypoint: str = SERVER_ENTRYPOINT, cwd: str | Path | None = None
) -> dict[str, list[str]]:
"""``{table: [column names]}`` as the server registers it, measured in a
CHILD interpreter: ``Base.metadata`` is a global registry, so measuring in
the test process would report whatever the session imported first. The
child inherits the environment; ``cwd`` is put on its ``sys.path`` so a
deployment's own package (``api.server``) resolves."""
code = (
"import importlib, json, os, sys\n"
"sys.path.insert(0, os.getcwd())\n"
f"importlib.import_module({entrypoint!r})\n"
"from cognee.infrastructure.databases.relational import Base\n"
"print(json.dumps({t.name: sorted(c.name for c in t.columns)"
" for t in Base.metadata.sorted_tables}))\n"
)
result = subprocess.run([sys.executable, "-c", code], cwd=cwd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(
f"importing {entrypoint!r} to measure the model surface failed:\n"
+ result.stderr[-3000:]
)
return json.loads(result.stdout.strip().splitlines()[-1])
def packaged_script_location() -> str:
"""cognee's own packaged Alembic directory, resolved explicitly so callers
are hermetic against the ambient ``COGNEE_ALEMBIC_PATH`` override."""
import cognee
return str(Path(cognee.__file__).parent / "alembic")
def collect_model_schema(
register_models: Callable[[], None] = register_server_models,
) -> dict[str, list[str]]:
"""Tables and column names ``Base.metadata`` declares, after registering
the deployment's full model surface IN-PROCESS. For tests prefer
``server_model_schema`` (child interpreter)."""
register_models()
from cognee.infrastructure.databases.relational import Base
return {
table.name: sorted(column.name for column in table.columns)
for table in Base.metadata.sorted_tables
}
def current_head(script_location: str | None = None) -> str:
from alembic.script import ScriptDirectory
from alembic.util.exc import CommandError
from cognee.modules.migrations.startup import _build_alembic_config
script = ScriptDirectory.from_config(_build_alembic_config(script_location))
try:
return script.get_current_head()
except CommandError as error:
raise CommandError(
f"{error} — if this is 'multiple heads', two migration branches merged "
"concurrently; create an `alembic merge` revision, then re-run."
) from error
def anchor_error(revision: str, script_location: str | None = None) -> str | None:
"""Why ``revision`` is NOT a valid baseline anchor, or ``None`` if it is.
A valid anchor must resolve in the chain to EXACTLY the stored id (Alembic
also resolves partial ids and branch labels, which a history rewrite could
leave behind) and must be an ancestor of head — otherwise ``upgrade head``
from the anchor would silently skip part of the chain.
"""
from alembic.script import ScriptDirectory
from alembic.script.revision import ResolutionError
from alembic.util.exc import CommandError
from cognee.modules.migrations.startup import _build_alembic_config
script = ScriptDirectory.from_config(_build_alembic_config(script_location))
try:
resolved = script.get_revision(revision)
except (CommandError, ResolutionError):
# Which of the two is raised varies across alembic versions; both mean
# the same thing here: the id does not resolve in this chain.
return f"revision {revision!r} is not in the Alembic chain"
if resolved is None or resolved.revision != revision:
found = None if resolved is None else resolved.revision
return (
f"revision {revision!r} does not resolve to itself (resolved to {found!r}) — "
"partial-id or branch-label match after a history rewrite?"
)
ancestry = {rev.revision for rev in script.iterate_revisions("heads", "base")}
if revision not in ancestry:
return (
f"revision {revision!r} exists but is NOT an ancestor of head — an upgrade "
"from the baseline would silently skip part of the chain"
)
return None
def generate_baseline(
path: Path,
register_models: Callable[[], None] = register_server_models,
script_location: str | None = None,
) -> dict:
"""Freeze the current model schema at the current chain head. A deliberate
act only: regenerating a baseline erases the guard's memory, so it must be
accompanied by a re-certification that a real chain-migrated database
matches the models exactly. The upstream CLI wrapper refuses to overwrite
an existing baseline without an explicit ``--force``."""
baseline = {
"baseline_revision": current_head(script_location),
"tables": collect_model_schema(register_models),
}
path.write_text(json.dumps(baseline, indent=2, sort_keys=True) + "\n")
return baseline
def load_baseline(path: Path) -> dict:
"""Load and validate a frozen baseline; every failure names the fix."""
try:
baseline = json.loads(path.read_text())
except FileNotFoundError:
raise FileNotFoundError(
f"No frozen baseline at {path}. Generate one at a certified revision with "
"generate_baseline() (see the lockstep module docstring)."
) from None
except json.JSONDecodeError as error:
raise ValueError(
f"Frozen baseline {path} is not valid JSON ({error}) — bad merge-conflict "
"resolution? Restore it from git history; regenerating instead would erase "
"the guard's memory."
) from error
if not isinstance(baseline.get("baseline_revision"), str) or not isinstance(
baseline.get("tables"), dict
):
raise TypeError(
f"Frozen baseline {path} must contain 'baseline_revision' (str) and "
"'tables' (dict). Restore it from git history or regenerate at a "
"certified revision."
)
return baseline
async def replay_from_baseline(
baseline: dict,
database_url: str,
script_location: str | None = None,
ignored_tables: Iterable[str] = IGNORED_TABLES,
) -> dict[str, list[str]]:
"""Build the baseline snapshot as a real database stamped at the baseline
revision, replay every migration above it through cognee's own runner, and
reflect the resulting tables and column names.
Column types in the snapshot are generic (the comparison is by NAME);
what matters is that the migrations added since the freeze run for real
against a base that predates them.
"""
from cognee.infrastructure.databases.relational.sqlalchemy.SqlAlchemyAdapter import (
SQLAlchemyAdapter,
)
adapter = SQLAlchemyAdapter(database_url)
ignored = set(ignored_tables)
try:
async with adapter.engine.begin() as connection:
await _seed_baseline_tables(connection, baseline["tables"])
await connection.execute(
sa.text(
"CREATE TABLE alembic_version (version_num VARCHAR(32) NOT NULL, "
"CONSTRAINT alembic_version_pkc PRIMARY KEY (version_num))"
)
)
await connection.execute(
sa.text("INSERT INTO alembic_version VALUES (:revision)"),
{"revision": baseline["baseline_revision"]},
)
await _upgrade_head_pinned_to(adapter, script_location)
return await _reflect_names(adapter, ignored)
finally:
await adapter.engine.dispose()
async def replay_entire_chain(
baseline: dict,
database_url: str,
script_location: str | None = None,
ignored_tables: Iterable[str] = IGNORED_TABLES,
) -> dict[str, list[str]]:
"""Replay the ENTIRE chain — ``alembic upgrade head`` from the initial
revision, no stamp — over a database seeded from the frozen baseline, and
reflect the resulting tables and columns.
The chain is a delta log: the base tables never came from migrations, so a
truly empty database gives the guarded revisions nothing to attach to. The
frozen snapshot supplies that base — deliberately the FROZEN state, never
live ``Base.metadata``: a live-model seed is a moving target that already
contains any model change whose migration is missing, which would blind
this probe to half of what it exists to catch. No migration file is
touched to make this possible.
Every revision is inspector-guarded (audited file by file), so each one
either no-ops against a frozen object that already exists or does its
genuine first run — which is exactly how anything the chain provides that
the models do not declare (wherever in history it was introduced,
including a downstream chain paired with an older pinned package — the
mis-stamp incident pairing) materializes and shows up as extra. The
reverse direction, a post-freeze model change with no migration, shows up
as missing.
"""
from cognee.infrastructure.databases.relational.sqlalchemy.SqlAlchemyAdapter import (
SQLAlchemyAdapter,
)
adapter = SQLAlchemyAdapter(database_url)
try:
async with adapter.engine.begin() as connection:
await _seed_baseline_tables(connection, baseline["tables"])
await _upgrade_head_pinned_to(adapter, script_location)
return await _reflect_names(adapter, set(ignored_tables))
finally:
await adapter.engine.dispose()
async def _seed_baseline_tables(connection, baseline_tables: dict[str, list[str]]) -> None:
"""Materialize the frozen snapshot as real tables. Column types are
generic (the comparison is by NAME); what matters is that replayed
migrations meet exactly the frozen era's objects, nothing newer."""
def _create(sync_connection):
metadata = sa.MetaData()
for name, columns in baseline_tables.items():
sa.Table(name, metadata, *(sa.Column(col, sa.Text()) for col in columns))
metadata.create_all(sync_connection)
await connection.run_sync(_create)
async def _upgrade_head_pinned_to(adapter, script_location: str | None) -> None:
"""Run ``alembic upgrade head`` with the engine pinned to ``adapter``.
The replay must run against THIS database, whatever the ambient config
says. Both engine-resolution styles present in this chain are pinned:
env.py and most migrations import the package attribute, while some
migrations import the submodule's attribute directly (e.g. 1d0bb7fede17)
— patch both. Migrations that call app helpers which bound the resolver
at their own import time remain out of reach; keep new migrations on one
of the two import styles.
"""
from unittest.mock import patch
from cognee.modules.migrations.startup import run_relational_migrations
with (
patch(
"cognee.infrastructure.databases.relational.get_relational_engine",
return_value=adapter,
),
patch(
"cognee.infrastructure.databases.relational.get_relational_engine."
"get_relational_engine",
return_value=adapter,
),
):
await run_relational_migrations("head", script_location)
async def _reflect_names(adapter, ignored: set[str]) -> dict[str, list[str]]:
async with adapter.engine.connect() as connection:
return await connection.run_sync(
lambda sync_conn: {
table: sorted(column["name"] for column in inspect(sync_conn).get_columns(table))
for table in inspect(sync_conn).get_table_names()
if table not in ignored
}
)
def compare_schemas(
expected: dict[str, list[str]],
actual: dict[str, list[str]],
baseline_tables: dict[str, list[str]] | None = None,
ignored_tables: Iterable[str] = IGNORED_TABLES,
) -> list[str]:
"""Describe every disagreement between the model schema (``expected``) and
the chain-built schema (``actual``), in both directions. Empty = lockstep.
``baseline_tables`` (when given) distinguishes a table the CHAIN added
post-freeze from one merely inherited from the baseline seed, so the
message points at the actual fix. ``ignored_tables`` exempts tables from
BOTH sides of the comparison.
"""
ignored = set(ignored_tables)
expected = {name: cols for name, cols in expected.items() if name not in ignored}
actual = {name: cols for name, cols in actual.items() if name not in ignored}
inherited = set(baseline_tables or ())
problems = []
for table in sorted(set(actual) - set(expected)):
if table in inherited:
problems.append(
f"table '{table}' was inherited from the baseline snapshot but no model "
"declares it anymore (model removed without a drop migration?)"
)
else:
problems.append(
f"the chain creates table '{table}' that no model declares "
"(migration landed without its model change?)"
)
for table in sorted(set(expected) - set(actual)):
problems.append(
f"models declare table '{table}' that no migration creates "
"(model change landed without its migration?)"
)
for table in sorted(set(actual) & set(expected)):
extra = sorted(set(actual[table]) - set(expected[table]))
missing = sorted(set(expected[table]) - set(actual[table]))
if extra:
problems.append(
f"table '{table}': the chain adds column(s) {extra} the models do not "
"declare — fresh databases built by create_all will LACK them while "
"stamped as having them (the mis-stamp incident direction)"
)
if missing:
problems.append(
f"table '{table}': models declare column(s) {missing} that no migration "
"adds — existing databases will never receive them on upgrade"
)
return problems

Xet Storage Details

Size:
18.3 kB
·
Xet hash:
f6fe886f8d07d94445e51e43d7c4f81b28b62b559b3fef2774144818d6012d32

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.