Add the scoped PostgreSQL/pgvector schema, independent ingestion settings and ports, embedding profile checks, and trusted administrator bootstrap. Include repository contracts and guidance, organized provider-free and PostgreSQL tests, deployment setup, and byte-preserving migration attributes. Validation: 163 tests passed; all 48 PostgreSQL cases passed with pgvector Python 0.5.0 and 0.3.6. No production schema or historical metadata was changed.
137 lines
6.5 KiB
Python
137 lines
6.5 KiB
Python
"""Real-DB regression: disposable migrations never touch pre-existing public data."""
|
|
import json
|
|
from uuid import uuid4
|
|
|
|
from alembic import command
|
|
import pytest
|
|
from sqlalchemy import create_engine, text
|
|
|
|
from app.infrastructure.database import (
|
|
FOUNDATION_RELATIONS, CompatibilityError, assert_foundation_scope,
|
|
)
|
|
from tests.support.postgres import (
|
|
disposable_database, fresh_test_database, migration_config, prepare_extension,
|
|
)
|
|
from tests.support.database_rows import seed
|
|
|
|
pytestmark = pytest.mark.postgres
|
|
|
|
|
|
def public_snapshot(connection):
|
|
result = {}
|
|
for name in FOUNDATION_RELATIONS:
|
|
oid = connection.execute(text("SELECT to_regclass(:name)::oid"),
|
|
{"name": f"public.{name}"}).scalar_one()
|
|
rows = connection.execute(text(
|
|
f"SELECT to_jsonb(t)::text FROM public.{name} t ORDER BY to_jsonb(t)::text"
|
|
)).scalars().all()
|
|
result[name] = (oid, rows)
|
|
# Catalog identities/expressions stay stable across search_path changes;
|
|
# deparsed definitions change qualification even without any schema mutation.
|
|
constraints = connection.execute(text("""
|
|
SELECT to_jsonb(c)::text
|
|
FROM pg_constraint c JOIN pg_namespace n ON n.oid=c.connamespace
|
|
WHERE n.nspname='public' ORDER BY c.conname,c.oid
|
|
""")).all()
|
|
comments = connection.execute(text("""
|
|
SELECT col_description('public.document_chunks'::regclass, attnum)
|
|
FROM pg_attribute WHERE attrelid='public.document_chunks'::regclass
|
|
AND attname='embedding'
|
|
""")).scalar_one()
|
|
return result, constraints, comments
|
|
|
|
|
|
def populate_public(engine, settings):
|
|
with engine.begin() as connection:
|
|
prepare_extension(connection)
|
|
connection.execute(text("SET LOCAL search_path=public,test_vector"))
|
|
config = migration_config(settings, "public")
|
|
config.attributes["connection"] = connection
|
|
command.upgrade(config, "head")
|
|
org, actor, doc = seed(connection)
|
|
connection.execute(text("""
|
|
UPDATE documents SET processing_profile=CAST(:profile AS jsonb)
|
|
WHERE id=:doc
|
|
"""), {"profile": json.dumps(settings.processing_profile()), "doc": doc})
|
|
connection.execute(text("""
|
|
INSERT INTO organization_settings(organization_id,assistant_name,instruction)
|
|
VALUES (:org,'preserve public','public instruction')
|
|
"""), {"org": org})
|
|
connection.execute(text("""
|
|
INSERT INTO ingestion_jobs(id,organization_id,document_id)
|
|
VALUES (:id,:org,:doc)
|
|
"""), {"id": uuid4(), "org": org, "doc": doc})
|
|
connection.execute(text("""
|
|
INSERT INTO document_chunks(id,organization_id,document_id,ordinal,text,embedding)
|
|
VALUES (:id,:org,:doc,0,'preserve public chunk','[1,2,3]')
|
|
"""), {"id": uuid4(), "org": org, "doc": doc})
|
|
connection.execute(text("""
|
|
INSERT INTO audit_events(id,organization_id,actor_user_id,action)
|
|
VALUES (:id,:org,:actor,'upload')
|
|
"""), {"id": uuid4(), "org": org, "actor": actor})
|
|
|
|
|
|
def test_public_tables_survive_disposable_setup_execution_and_teardown(test_database_url, settings):
|
|
with fresh_test_database(test_database_url) as url:
|
|
public = create_engine(url, hide_parameters=True)
|
|
try:
|
|
populate_public(public, settings)
|
|
with public.connect() as connection:
|
|
before = public_snapshot(connection)
|
|
with disposable_database(url, settings) as (engine, config):
|
|
with engine.begin() as connection:
|
|
schema = config.attributes["application_schema"]
|
|
assert_foundation_scope(connection, schema)
|
|
assert "public" not in connection.execute(text("SHOW search_path")).scalar_one()
|
|
org, _, _ = seed(connection)
|
|
connection.execute(text("UPDATE organizations SET name='disposable' WHERE id=:id"),
|
|
{"id": org})
|
|
assert public_snapshot(connection) == before
|
|
config.attributes["connection"] = connection
|
|
command.downgrade(config, "base")
|
|
assert connection.execute(text("SELECT to_regclass('documents')")).scalar_one() is None
|
|
assert public_snapshot(connection) == before
|
|
command.upgrade(config, "head")
|
|
assert_foundation_scope(connection, schema)
|
|
assert public_snapshot(connection) == before
|
|
with public.connect() as connection:
|
|
assert public_snapshot(connection) == before
|
|
assert connection.execute(text("SELECT to_regnamespace(:schema)"),
|
|
{"schema": schema}).scalar_one() is None
|
|
# Exception teardown must preserve the same public relations and data.
|
|
with pytest.raises(RuntimeError, match="intentional fixture failure"):
|
|
with disposable_database(url, settings):
|
|
raise RuntimeError("intentional fixture failure")
|
|
with public.connect() as connection:
|
|
assert public_snapshot(connection) == before
|
|
finally:
|
|
public.dispose()
|
|
|
|
|
|
def test_migration_refuses_public_fallback_before_downgrade(test_database_url, settings):
|
|
with fresh_test_database(test_database_url) as url:
|
|
engine = create_engine(url, hide_parameters=True)
|
|
schema = "test_" + uuid4().hex
|
|
try:
|
|
populate_public(engine, settings)
|
|
with engine.begin() as connection:
|
|
before = public_snapshot(connection)
|
|
connection.execute(text(f'CREATE SCHEMA "{schema}"'))
|
|
connection.execute(text(f'SET LOCAL search_path="{schema}",public,test_vector'))
|
|
config = migration_config(settings, schema)
|
|
config.attributes["connection"] = connection
|
|
with pytest.raises(CompatibilityError, match="outside application schema"):
|
|
command.downgrade(config, "base")
|
|
assert public_snapshot(connection) == before
|
|
finally:
|
|
engine.dispose()
|
|
|
|
|
|
def test_test_connections_refuse_missing_scoped_relation(migrated_db):
|
|
engine, _ = migrated_db
|
|
with engine.begin() as connection:
|
|
connection.execute(text("DROP TABLE audit_events"))
|
|
with pytest.raises(CompatibilityError, match="Missing scoped foundation relation"):
|
|
with engine.begin():
|
|
pass
|