feat(ingestion): add Phase 1 database and application foundation

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.
This commit is contained in:
amirhosein mazaheri
2026-10-05 16:38:28 +03:30
parent cb54a35c90
commit baf58da562
50 changed files with 4628 additions and 3 deletions
+30
View File
@@ -0,0 +1,30 @@
# Test layout
- unit/: provider-free configuration, URL security, imports and test-environment regressions.
- integration/: PostgreSQL constraints, migration/profile lifecycle, concurrency, native vectors and schema isolation.
- support/: reusable PostgreSQL lifecycle and row helpers; helpers do not live in test modules.
- conftest.py: shared settings, isolated environment and acceptance option.
- integration/conftest.py: database fixtures and postgres marker for all integration cases.
- postgres_prerequisites.py: unchanged prerequisite command entry point.
Run ordinary tests:
~~~powershell
.venv/Scripts/python -m pytest -m "not postgres"
~~~
For database tests, configure an isolated TEST_DATABASE_URL as described in
[foundation setup](../docs/ingestion-foundation-setup.md), then run:
~~~powershell
.venv/Scripts/python -m tests.postgres_prerequisites
.venv/Scripts/python -m pytest -m postgres --require-postgres
~~~
Use .venv/minimum/Scripts/python for the minimum pgvector dependency environment.
The same commands and assertions apply. Missing database configuration fails
explicit acceptance; skipped database cases are not passing evidence.
Organization validation: installed environment full suite 163 passed; minimum
pgvector 0.3.6 PostgreSQL suite 48 passed. Both prerequisite checks passed.
Production code and migration history were unchanged.
+1
View File
@@ -0,0 +1 @@
"""Foundation regression tests."""
+26
View File
@@ -0,0 +1,26 @@
"""Shared settings isolation and pytest acceptance option."""
import os
import pytest
from app.modules.documents.settings import IngestionSettings
def pytest_addoption(parser):
parser.addoption("--require-postgres", action="store_true",
help="Fail rather than skip when TEST_DATABASE_URL is missing")
@pytest.fixture(autouse=True)
def isolated_ingestion_environment(monkeypatch):
"""Each test starts without deployment overrides; explicit env tests set their own."""
for name in tuple(os.environ):
if name.upper().startswith("INGEST_"):
monkeypatch.delenv(name)
@pytest.fixture
def settings():
return IngestionSettings(
_env_file=None, database_url="postgresql+psycopg://unused/unused",
embedding_provider="test", embedding_endpoint="https://test.invalid/v1",
embedding_model="deterministic-test", embedding_dimensions=3,
)
+1
View File
@@ -0,0 +1 @@
"""Foundation test package."""
+31
View File
@@ -0,0 +1,31 @@
"""PostgreSQL-only fixtures and marker; ordinary tests need no database."""
import os
from pathlib import Path
import pytest
from tests.support.postgres import disposable_database, validated_test_url
@pytest.fixture
def test_database_url(request):
url = os.environ.get("TEST_DATABASE_URL")
if not url:
message = "TEST_DATABASE_URL is required for PostgreSQL acceptance"
if request.config.getoption("--require-postgres"):
pytest.fail(message)
pytest.skip(message + "; skipped tests are not acceptance evidence")
try:
return validated_test_url(url)
except ValueError as exc:
pytest.fail(str(exc))
@pytest.fixture
def migrated_db(settings, test_database_url):
with disposable_database(test_database_url, settings) as database:
yield database
def pytest_collection_modifyitems(items):
for item in items:
if Path(__file__).parent in item.path.parents:
item.add_marker(pytest.mark.postgres)
+74
View File
@@ -0,0 +1,74 @@
"""Independent PostgreSQL connections enforce replay and bootstrap invariants."""
from uuid import uuid4
import pytest
from sqlalchemy import text
from tests.support.database_rows import seed
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
from argon2 import PasswordHasher
from sqlalchemy.exc import IntegrityError
from app.bootstrap import bootstrap
@pytest.mark.parametrize("kind", ["chunk", "job", "upload", "audit"])
def test_concurrent_uniqueness(migrated_db, kind):
engine, _ = migrated_db
with engine.begin() as connection:
org, actor, doc = seed(connection)
barrier = Barrier(2)
request = uuid4()
def insert_once():
params = {"id": uuid4(), "org": org, "actor": actor, "doc": doc,
"request": request, "key": str(uuid4()), "hash": "a" * 64}
sql = {
"chunk": """INSERT INTO document_chunks
(id,organization_id,document_id,ordinal,text,embedding)
VALUES (:id,:org,:doc,0,'test','[1,2,3]')""",
"job": """INSERT INTO ingestion_jobs(id,organization_id,document_id)
VALUES (:id,:org,:doc)""",
"upload": """INSERT INTO documents(id,organization_id,uploaded_by,title,
original_filename,upload_request_id,upload_payload_hash,storage_key,
file_sha256,mime_type,size_bytes)
VALUES (:id,:org,:actor,'test','test.md',:request,:hash,:key,:hash,'text/markdown',1)""",
"audit": """INSERT INTO audit_events(id,organization_id,actor_user_id,
action,target_id,idempotency_key)
VALUES (:id,:org,:actor,'ingestion_retry',:doc,:request)""",
}[kind]
try:
with engine.begin() as connection:
connection.execute(text("SET LOCAL statement_timeout='10s'"))
barrier.wait(timeout=10)
connection.execute(text(sql), params)
return "committed"
except IntegrityError:
return "rejected"
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda _: insert_once(), range(2)))
assert sorted(results) == ["committed", "rejected"]
def test_concurrent_bootstrap_and_hashing(migrated_db):
engine, _ = migrated_db
barrier = Barrier(2)
def run(index):
try:
with engine.begin() as connection:
connection.execute(text("SET LOCAL statement_timeout='10s'"))
barrier.wait(timeout=10)
return bootstrap(
connection, organization_name="test", username=f"ADMIN{index}",
password="test-only-secret", assistant_name="Assistant", instruction="",
)
except ValueError:
return None
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(run, range(2)))
assert sum(item is not None for item in results) == 1
with engine.connect() as connection:
user = connection.execute(text("SELECT * FROM users")).mappings().one()
assert user["username"] == user["username"].lower()
assert user["role"] == "admin" and user["is_enabled"]
assert PasswordHasher().verify(user["password_hash"], "test-only-secret")
settings = connection.execute(text("SELECT * FROM organization_settings")).mappings().one()
assert (settings["revision"], settings["knowledge_revision"], settings["access_epoch"]) == (1, 1, 1)
+131
View File
@@ -0,0 +1,131 @@
"""Real PostgreSQL scoped foreign keys, states and uniqueness."""
from uuid import uuid4
import pytest
from sqlalchemy import text
from tests.support.database_rows import seed, rejected
from app.infrastructure.database import SqlDocumentRepository
@pytest.mark.parametrize("sql", [
"UPDATE users SET role='superuser' WHERE id=:actor",
"UPDATE documents SET status='unknown' WHERE id=:doc",
"UPDATE documents SET status='ready' WHERE id=:doc",
"UPDATE documents SET is_active=true WHERE id=:doc",
"UPDATE documents SET size_bytes=0 WHERE id=:doc",
"UPDATE documents SET chunk_count=-1 WHERE id=:doc",
"UPDATE ingestion_jobs SET status='unknown' WHERE document_id=:doc",
"UPDATE ingestion_jobs SET stage='unknown' WHERE document_id=:doc",
"UPDATE ingestion_jobs SET attempt_count=-1 WHERE document_id=:doc",
"UPDATE ingestion_jobs SET retry_generation=-1 WHERE document_id=:doc",
"UPDATE ingestion_jobs SET status='processing' WHERE document_id=:doc",
"UPDATE ingestion_jobs SET claim_token=:token WHERE document_id=:doc",
"UPDATE organization_settings SET access_epoch=0 WHERE organization_id=:org",
"UPDATE organization_settings SET revision=0 WHERE organization_id=:org",
"UPDATE organization_settings SET knowledge_revision=0 WHERE organization_id=:org",
"UPDATE users SET username='UPPERCASE' WHERE id=:actor",
"UPDATE users SET username='' WHERE id=:actor",
"UPDATE documents SET upload_payload_hash='invalid' WHERE id=:doc",
"UPDATE documents SET file_sha256='invalid' WHERE id=:doc",
"UPDATE ingestion_jobs SET lease_expires_at=now() WHERE document_id=:doc",
"UPDATE ingestion_jobs SET status='processing',claim_token=:token WHERE document_id=:doc",
"UPDATE ingestion_jobs SET status='processing',lease_expires_at=now() WHERE document_id=:doc",
])
def test_invalid_states_rejected(migrated_db, sql):
engine, _ = migrated_db
with engine.begin() as connection:
org, actor, doc = seed(connection)
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 organization_settings(organization_id,assistant_name,instruction)
VALUES (:org,'test','')
"""), {"org": org})
rejected(engine, sql, {"org": org, "actor": actor, "doc": doc, "token": uuid4()})
def test_all_scoped_foreign_keys(migrated_db):
engine, _ = migrated_db
with engine.begin() as connection:
org, actor, doc = seed(connection)
other_org, other_actor, other_doc = seed(connection)
connection.execute(text("""
INSERT INTO organization_settings(organization_id,assistant_name,instruction)
VALUES (:org,'test','')
"""), {"org": org})
for sql in (
"UPDATE users SET organization_id=:org WHERE id=:actor",
"UPDATE documents SET uploaded_by=:actor WHERE id=:doc",
"UPDATE organization_settings SET updated_by=:actor WHERE organization_id=:org",
"""INSERT INTO ingestion_jobs(id,organization_id,document_id)
VALUES (:id,:org,:other_doc)""",
"""INSERT INTO document_chunks(id,organization_id,document_id,ordinal,text,embedding)
VALUES (:id,:org,:other_doc,0,'test','[1,2,3]')""",
"""INSERT INTO audit_events(id,organization_id,actor_user_id,action)
VALUES (:id,:org,:actor,'upload')""",
):
rejected(engine, sql, {"id": uuid4(), "org": org, "actor": other_actor,
"doc": doc, "other_doc": other_doc})
with engine.connect() as connection:
repository = SqlDocumentRepository(connection)
assert repository.get_document(other_org, doc) is None
assert repository.get_document(org, doc)["id"] == doc
assert repository.get_enabled_administrator(actor)["organization_id"] == org
@pytest.mark.parametrize("ordinal,content,location,vector,tokens", [
(-1, "test", "{}", "[1,2,3]", None),
(0, "", "{}", "[1,2,3]", None),
(0, "test", '{"page":0}', "[1,2,3]", None),
(0, "test", '{"page":1.5}', "[1,2,3]", None),
(0, "test", '{"page":"1"}', "[1,2,3]", None),
(0, "test", "[]", "[1,2,3]", None),
(0, "test", "{}", "[1,2]", None),
(0, "test", "{}", "[1,2,3]", -1),
])
def test_chunk_constraints(migrated_db, ordinal, content, location, vector, tokens):
engine, _ = migrated_db
with engine.begin() as connection:
org, _, doc = seed(connection)
rejected(engine, """
INSERT INTO document_chunks(id,organization_id,document_id,ordinal,text,
location,embedding,token_count)
VALUES (:id,:org,:doc,:ordinal,:content,CAST(:location AS jsonb),
CAST(:vector AS vector),:tokens)
""", {"id": uuid4(), "org": org, "doc": doc, "ordinal": ordinal,
"content": content, "location": location, "vector": vector, "tokens": tokens})
@pytest.mark.parametrize("fields", [
{"action": "unknown"},
{"action": "document_deleted", "target": None, "key": None},
{"action": "ingestion_retry", "actor": None},
{"request_hash": "invalid"},
])
def test_audit_constraints(migrated_db, fields):
engine, _ = migrated_db
with engine.begin() as connection:
org, actor, doc = seed(connection)
params = {"id": uuid4(), "org": org, "actor": actor, "action": "upload",
"target": doc, "key": uuid4(), "request_hash": "a" * 64, **fields}
rejected(engine, """
INSERT INTO audit_events(id,organization_id,actor_user_id,action,target_id,
idempotency_key,request_hash)
VALUES (:id,:org,:actor,:action,:target,:key,:request_hash)
""", params)
def test_global_username_and_original_storage_key_uniqueness(migrated_db):
engine, _ = migrated_db
with engine.begin() as connection:
org, actor, doc = seed(connection)
_, other_actor, other_doc = seed(connection)
username = connection.execute(text("SELECT username FROM users WHERE id=:id"),
{"id": actor}).scalar_one()
storage = connection.execute(text("SELECT storage_key FROM documents WHERE id=:id"),
{"id": doc}).scalar_one()
rejected(engine, "UPDATE users SET username=:name WHERE id=:id",
{"id": other_actor, "name": username})
rejected(engine, "UPDATE documents SET storage_key=:key WHERE id=:id",
{"id": other_doc, "key": storage})
+136
View File
@@ -0,0 +1,136 @@
"""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
+61
View File
@@ -0,0 +1,61 @@
"""Alembic schema lifecycle and full embedding-profile compatibility."""
import json
import pytest
from sqlalchemy import text
from tests.support.database_rows import seed
from dataclasses import replace
from alembic import command
from app.infrastructure.database import CompatibilityError, check_compatibility
def test_empty_migration_tables_and_pinned_profile(migrated_db, settings):
engine, config = migrated_db
with engine.connect() as connection:
check_compatibility(connection, settings.embedding_profile)
tables = connection.execute(text("""
SELECT tablename FROM pg_tables WHERE schemaname=current_schema()
""")).scalars().all()
assert set(tables) == {
"alembic_version", "organizations", "users", "organization_settings",
"documents", "ingestion_jobs", "document_chunks", "audit_events",
}
for changed in (
replace(settings.embedding_profile, model="different-model"),
replace(settings.embedding_profile, dimensions=4),
replace(settings.embedding_profile, endpoint="https://other.invalid"),
replace(settings.embedding_profile, provider="other-provider"),
replace(settings.embedding_profile, preprocessing_version="v2"),
):
with pytest.raises(CompatibilityError):
check_compatibility(connection, changed)
config.attributes["ingestion_settings"] = settings.model_copy(
update={"embedding_dimensions": 4, "embedding_model": "changed"}
)
with engine.begin() as connection:
config.attributes["connection"] = connection
with pytest.raises(CompatibilityError):
command.upgrade(config, "head")
check_compatibility(connection, settings.embedding_profile)
def test_document_profile_mismatch(migrated_db, settings):
engine, _ = migrated_db
with engine.begin() as connection:
_, _, doc = seed(connection)
with pytest.raises(CompatibilityError):
check_compatibility(connection, settings.embedding_profile)
connection.execute(text("""
UPDATE documents SET processing_profile=CAST(:profile AS jsonb) WHERE id=:doc
"""), {"doc": doc, "profile": json.dumps(settings.processing_profile())})
check_compatibility(connection, settings.embedding_profile)
def test_initial_migration_round_trip(migrated_db, settings):
engine, config = migrated_db
with engine.begin() as connection:
config.attributes["connection"] = connection
command.downgrade(config, "base")
assert connection.execute(text("SELECT to_regclass('document_chunks')")).scalar_one() is None
command.upgrade(config, "head")
check_compatibility(connection, settings.embedding_profile)
+42
View File
@@ -0,0 +1,42 @@
"""Native pgvector adaptation for supported dependency versions."""
from uuid import uuid4
import json
from sqlalchemy import text
from tests.support.database_rows import seed, rejected
def test_valid_vectors_locations_and_claim_state(migrated_db):
try:
from pgvector import Vector
native_input = Vector([1, 2, 3])
except ImportError:
# 0.3.6's supported native input is NumPy (a dependency of that release).
import numpy as np
native_input = np.array([1, 2, 3], dtype=np.float32)
from app.infrastructure.database import register_vector_types
engine, _ = migrated_db
with engine.begin() as connection:
org, _, doc = seed(connection)
register_vector_types(connection)
connection.execute(text("""
INSERT INTO document_chunks
(id,organization_id,document_id,ordinal,text,location,embedding)
VALUES (:id,:org,:doc,0,'test',CAST(:location AS jsonb),:vector)
"""), {"id": uuid4(), "org": org, "doc": doc, "vector": native_input,
"location": json.dumps({"page": None, "section": "Intro"})})
vector = connection.execute(text("SELECT embedding FROM document_chunks")).scalar_one()
# pgvector 0.3.6 loads NumPy arrays; 0.5 loads native Vector.
values = vector.to_list() if hasattr(vector, "to_list") else vector.tolist()
assert list(values) == [1, 2, 3]
connection.execute(text("""
INSERT INTO ingestion_jobs
(id,organization_id,document_id,status,claim_token,lease_expires_at)
VALUES (:id,:org,:doc,'processing',:token,now()+interval '120 seconds')
"""), {"id": uuid4(), "org": org, "doc": doc, "token": uuid4()})
connection.execute(text("""
UPDATE documents SET status='ready',chunk_count=1,ready_at=now(),is_active=true
WHERE id=:doc
"""), {"doc": doc})
rejected(engine, "UPDATE documents SET deleted_at=now() WHERE id=:doc", {"doc": doc})
rejected(engine, "UPDATE documents SET content_purged_at=now() WHERE id=:doc", {"doc": doc})
rejected(engine, "UPDATE ingestion_jobs SET status='succeeded' WHERE document_id=:doc", {"doc": doc})
+56
View File
@@ -0,0 +1,56 @@
"""Check dedicated PostgreSQL/pgvector prerequisites without printing credentials."""
import os
import sys
from sqlalchemy import create_engine, text
from tests.support.postgres import (
fresh_test_database, prepare_extension, validated_test_url,
)
def main():
engine = None
failed = False
versions = None
try:
raw = os.environ.get("TEST_DATABASE_URL")
if not raw:
raise ValueError("Missing isolated test database configuration")
url = validated_test_url(raw)
engine = create_engine(url, hide_parameters=True,
connect_args={"connect_timeout": 5})
with engine.begin() as connection:
server = connection.execute(text("SHOW server_version")).scalar_one()
can_create_db = connection.execute(text("""
SELECT rolsuper OR rolcreatedb FROM pg_roles WHERE rolname=current_user
""")).scalar_one()
if not can_create_db:
raise ValueError("Test role requires database creation privileges")
prepare_extension(connection)
vector = connection.execute(text("""
SELECT extversion FROM pg_extension WHERE extname='vector'
""")).scalar_one()
versions = (server, vector)
# Exercise actual CREATE/DROP DATABASE and extension privileges up front.
with fresh_test_database(url) as scratch:
scratch_engine = create_engine(scratch, hide_parameters=True)
try:
with scratch_engine.begin() as connection:
prepare_extension(connection)
finally:
scratch_engine.dispose()
except Exception:
failed = True
finally:
if engine is not None:
engine.dispose()
if failed:
print("PostgreSQL prerequisites failed: verify TEST_DATABASE_URL, connectivity, isolated _test database, pgvector namespace and CREATE DATABASE/extension privileges.", file=sys.stderr)
return 1
print(f"PostgreSQL prerequisites passed: server {versions[0]}, vector {versions[1]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+1
View File
@@ -0,0 +1 @@
"""Foundation test package."""
+29
View File
@@ -0,0 +1,29 @@
"""Shared database seed and rejection helpers; no test imports."""
from uuid import uuid4
import pytest
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError, DataError
def seed(connection):
org, actor, document = uuid4(), uuid4(), uuid4()
connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'test')"), {"id": org})
connection.execute(text("""
INSERT INTO users(id,organization_id,username,password_hash,role)
VALUES (:id,:org,:name,'test-only','admin')
"""), {"id": actor, "org": org, "name": str(actor)})
connection.execute(text("""
INSERT INTO documents(id,organization_id,uploaded_by,title,original_filename,
upload_request_id,upload_payload_hash,storage_key,file_sha256,mime_type,
size_bytes,processing_profile)
VALUES (:id,:org,:actor,'test','test.md',:request,:hash,:key,:hash,'text/markdown',
1,CAST(:profile AS jsonb))
"""), {"id": document, "org": org, "actor": actor, "request": uuid4(),
"hash": "a" * 64, "key": str(document), "profile": "{}"})
return org, actor, document
def rejected(engine, sql, params):
with pytest.raises((IntegrityError, DataError)):
with engine.begin() as connection:
connection.execute(text(sql), params)
+116
View File
@@ -0,0 +1,116 @@
"""Disposable PostgreSQL schemas with no public application-table fallback."""
from contextlib import contextmanager
from pathlib import Path
from uuid import uuid4
from alembic import command
from alembic.config import Config
from sqlalchemy import create_engine, event, text
from sqlalchemy.engine import make_url
from app.infrastructure.database import (
FOUNDATION_RELATIONS, CompatibilityError, assert_foundation_scope,
)
ROOT = Path(__file__).resolve().parents[2]
EXTENSION_SCHEMA = "test_vector"
def validated_test_url(url):
try:
parsed = make_url(url)
except Exception:
raise ValueError("Invalid isolated test database configuration") from None
if (parsed.drivername != "postgresql+psycopg" or not parsed.database
or not parsed.database.endswith("_test")):
raise ValueError("Use Psycopg and a dedicated database name ending in _test")
return parsed
def prepare_extension(connection):
existing = connection.execute(text("""
SELECT n.nspname FROM pg_extension e
JOIN pg_namespace n ON n.oid=e.extnamespace WHERE e.extname='vector'
""")).scalar_one_or_none()
if existing is None:
connection.execute(text(f'CREATE SCHEMA IF NOT EXISTS "{EXTENSION_SCHEMA}"'))
connection.execute(text(f'CREATE EXTENSION vector WITH SCHEMA "{EXTENSION_SCHEMA}"'))
elif existing != EXTENSION_SCHEMA:
raise RuntimeError("Test vector extension must be installed in test_vector; use a fresh dedicated test database")
for name in FOUNDATION_RELATIONS:
exists = connection.execute(text("""
SELECT EXISTS (
SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
WHERE n.nspname=:schema AND c.relname=:name
)
"""), {"schema": EXTENSION_SCHEMA, "name": name}).scalar_one()
if exists:
raise CompatibilityError("Extension namespace contains an application relation")
def migration_config(settings, schema):
config = Config(str(ROOT / "alembic.ini"))
config.set_main_option("script_location", str(ROOT / "migrations"))
config.attributes["ingestion_settings"] = settings
config.attributes["application_schema"] = schema
return config
@contextmanager
def disposable_database(url, settings):
parsed = validated_test_url(url)
schema = "test_" + uuid4().hex
admin = create_engine(parsed, hide_parameters=True)
engine = None
created = False
try:
with admin.begin() as connection:
prepare_extension(connection)
connection.execute(text(f'CREATE SCHEMA "{schema}"'))
created = True
engine = create_engine(
parsed, hide_parameters=True,
connect_args={"options": f"-csearch_path={schema},{EXTENSION_SCHEMA}"},
)
config = migration_config(settings, schema)
with engine.begin() as connection:
config.attributes["connection"] = connection
command.upgrade(config, "head")
assert_foundation_scope(connection, schema)
config.attributes.pop("connection")
@event.listens_for(engine, "engine_connect")
def verify_before_use(connection):
# Validate every test connection before its first mutation.
assert_foundation_scope(connection, schema)
connection.rollback()
yield engine, config
finally:
if engine is not None:
engine.dispose()
if created:
with admin.begin() as connection:
connection.execute(text(f'SET LOCAL search_path="{schema}",{EXTENSION_SCHEMA}'))
assert_foundation_scope(connection, schema, require_all=False)
connection.execute(text(f'DROP SCHEMA "{schema}" CASCADE'))
admin.dispose()
@contextmanager
def fresh_test_database(url):
"""Public-schema regression gets its own DB; never modifies caller's public."""
parsed = validated_test_url(url)
name = "foundation_" + uuid4().hex + "_test"
admin = create_engine(parsed, isolation_level="AUTOCOMMIT", hide_parameters=True)
created = False
try:
with admin.connect() as connection:
connection.execute(text(f'CREATE DATABASE "{name}"'))
created = True
yield parsed.set(database=name)
finally:
if created:
with admin.connect() as connection:
connection.execute(text(f'DROP DATABASE "{name}" WITH (FORCE)'))
admin.dispose()
+1
View File
@@ -0,0 +1 @@
"""Foundation test package."""
+73
View File
@@ -0,0 +1,73 @@
"""Ingestion defaults, limits and explicit deployment inputs."""
import json
import os
import pytest
from pydantic import ValidationError
from app.modules.documents.settings import IngestionSettings
def test_explicit_profile_and_no_secrets_in_snapshot(settings):
profile = settings.processing_profile()
assert profile["size_unit"] == "characters"
assert profile["embedding"]["model"] == "deterministic-test"
assert profile["embedding"]["dimensions"] == 3
assert "api_key" not in json.dumps(profile)
assert settings.max_original_bytes == 20 * 1024 * 1024
assert settings.max_staged_bytes == 128 * 1024 * 1024
with pytest.raises(ValueError):
settings.require_embedding_credentials()
@pytest.mark.parametrize("override", [
{"chunk_overlap_characters": 1000}, {"max_pdf_pages": 0},
{"heartbeat_seconds": 120}, {"worker_concurrency": 2},
{"accepted_formats": (".exe",)}, {"retry_base_seconds": 301},
{"embedding_model": " "}, {"embedding_dimensions": 0},
{"database_url": "sqlite://"},
])
def test_invalid_configuration(settings, override):
values = settings.model_dump()
values.update(override)
with pytest.raises(ValidationError):
IngestionSettings(_env_file=None, **values)
def test_model_dimension_are_required(monkeypatch):
for key in tuple(os.environ):
if key.startswith("INGEST_"):
monkeypatch.delenv(key)
with pytest.raises(ValidationError) as exc:
IngestionSettings(_env_file=None)
missing = {error["loc"][0] for error in exc.value.errors()}
assert {"embedding_model", "embedding_dimensions"} <= missing
def test_environment_limits_override(monkeypatch, settings):
monkeypatch.setenv("INGEST_MAX_CHUNKS", "12")
monkeypatch.setenv("INGEST_ACCEPTED_FORMATS", '[".md"]')
values = settings.model_dump()
values.pop("max_chunks")
values.pop("accepted_formats")
configured = IngestionSettings(_env_file=None, **values)
assert configured.max_chunks == 12
assert configured.accepted_formats == (".md",)
DURATIONS = (
"embedding_timeout_seconds", "poll_seconds", "heartbeat_seconds",
"lease_seconds", "retry_base_seconds", "retry_cap_seconds",
)
@pytest.mark.parametrize("field", DURATIONS)
@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])
@pytest.mark.parametrize("source", ["direct", "environment"])
def test_nonfinite_durations_rejected(settings, monkeypatch, field, value, source):
values = settings.model_dump()
if source == "environment":
values.pop(field)
monkeypatch.setenv("INGEST_" + field.upper(), str(value))
else:
values[field] = value
with pytest.raises(ValidationError):
IngestionSettings(_env_file=None, **values)
+77
View File
@@ -0,0 +1,77 @@
"""Database URL validation and exception redaction."""
import pytest
from pydantic import ValidationError
from app.modules.documents.settings import IngestionSettings
def assert_secret_free_exception(exc, secret):
pending = [exc]
seen = set()
while pending:
error = pending.pop()
if id(error) in seen:
continue
seen.add(id(error))
outputs = [str(error), repr(error)]
if isinstance(error, ValidationError):
outputs += [error.json(), repr(error.errors())]
for item in error.errors():
contextual = item.get("ctx", {}).get("error")
if isinstance(contextual, BaseException):
pending.append(contextual)
assert all(secret not in output for output in outputs)
pending.extend(item for item in (error.__context__, error.__cause__)
if item is not None)
@pytest.mark.parametrize("url", [
"postgresql+psycopg://dummy-user:dummy-password@host:dummy-url-secret/db",
"postgresql+psycopg://dummy-url-secret:dummy-password@host:invalid-port/db",
"postgresql+psycopg://dummy-user:dummy-url-secret@host:invalid-port/db",
"dummy-url-secret-not-a-url",
"postgresql+psycopg:/dummy-url-secret",
"://dummy-url-secret",
"postgresql+psycopg://u:dummy-url-secret@host:99999/db",
"postgresql+psycopg://u:dummy-url-secret@host:-1/db",
])
@pytest.mark.parametrize("source", ["direct", "environment"])
def test_malformed_database_urls_are_generic_secret_free_validation_errors(
settings, monkeypatch, url, source
):
values = settings.model_dump()
if source == "environment":
values.pop("database_url")
monkeypatch.setenv("INGEST_DATABASE_URL", url)
else:
values["database_url"] = url
with pytest.raises(ValidationError) as caught:
IngestionSettings(_env_file=None, **values)
error = caught.value
assert "Database URL must be a valid postgresql+psycopg URL" in str(error)
assert_secret_free_exception(error, "dummy-url-secret")
assert_secret_free_exception(error, "dummy-password")
assert error.__context__ is None
assert error.__cause__ is None
for item in error.errors():
contextual = item.get("ctx", {}).get("error")
if isinstance(contextual, BaseException):
assert contextual.__context__ is None
assert contextual.__cause__ is None
@pytest.mark.parametrize("url", [
"postgresql+psycopg://user:dummy-password@localhost:5432/database",
"postgresql+psycopg://user:p%40ss@localhost:6543/database?sslmode=require",
"postgresql+psycopg:///database?host=/var/run/postgresql",
"postgresql+psycopg://user@localhost/database",
])
@pytest.mark.parametrize("source", ["direct", "environment"])
def test_valid_psycopg_urls_preserve_identity(settings, monkeypatch, url, source):
values = settings.model_dump()
if source == "environment":
values.pop("database_url")
monkeypatch.setenv("INGEST_DATABASE_URL", url)
else:
values["database_url"] = url
configured = IngestionSettings(_env_file=None, **values)
assert configured.database_url.get_secret_value() == url
+66
View File
@@ -0,0 +1,66 @@
"""Embedding endpoint identity and secret-free validation."""
import json
import pytest
from pydantic import ValidationError
from app.modules.documents.settings import IngestionSettings
@pytest.mark.parametrize("endpoint", [
"https://dummy-user:dummy-url-secret@example.invalid/v1",
"https://dummy-url-secret@example.invalid/v1",
"https://example.invalid/v1?api_key=dummy-url-secret",
"https://example.invalid/v1#dummy-url-secret",
"https://example.invalid/v1;api_key=dummy-url-secret",
"https://example.invalid/%64ummy-url-secret",
"https://example.invalid/v1?dummy-url-secret",
"https://example.invalid/v1?","https://example.invalid/v1#",
"https://example.invalid\\\\dummy-url-secret",
"https://example.invalid/v1\t",
"ftp://example.invalid/v1", "//example.invalid/v1",
"https:///v1", "https://example.invalid:99999/v1",
"https://example.invalid:/v1",
])
@pytest.mark.parametrize("source", ["direct", "environment"])
def test_unsafe_endpoints_rejected_without_secret_output(settings, monkeypatch, endpoint, source):
values = settings.model_dump()
values["embedding_api_key"] = "dummy-separate-secret"
if source == "environment":
values.pop("embedding_endpoint")
monkeypatch.setenv("INGEST_EMBEDDING_ENDPOINT", endpoint)
else:
values["embedding_endpoint"] = endpoint
with pytest.raises(ValidationError) as exc:
IngestionSettings(_env_file=None, **values)
for output in (str(exc.value), repr(exc.value), exc.value.json(),
repr(exc.value.errors())):
assert "dummy-url-secret" not in output
assert "dummy-separate-secret" not in output
@pytest.mark.parametrize("endpoint", [
"https://api.example.invalid/v1",
"https://Example.invalid:8443/tenant/deployment-01/v1/",
"http://localhost:8080/v1", "http://127.0.0.1:8000",
"http://[::1]:8000/v1",
])
def test_valid_endpoint_identity_and_separate_secret(settings, endpoint):
configured = IngestionSettings(
_env_file=None,
**{**settings.model_dump(), "embedding_endpoint": endpoint,
"embedding_api_key": "dummy-separate-secret"},
)
assert configured.embedding_endpoint == endpoint
assert configured.processing_profile()["embedding"]["endpoint"] == endpoint.rstrip("/")
assert "dummy-separate-secret" not in json.dumps(configured.processing_profile())
assert "dummy-separate-secret" not in repr(configured)
def test_cross_field_failure_does_not_echo_secret_mapping(settings):
with pytest.raises(ValidationError) as exc:
IngestionSettings(
_env_file=None,
**{**settings.model_dump(), "chunk_overlap_characters": 1000,
"embedding_api_key": "dummy-separate-secret"},
)
assert "dummy-separate-secret" not in str(exc.value)
assert "dummy-separate-secret" not in exc.value.json()
+29
View File
@@ -0,0 +1,29 @@
"""Ingestion imports do not initialize providers or chat."""
import os
import subprocess
import sys
def test_ingestion_imports_do_not_initialize_chat_or_io():
script = """
import importlib, sys
class BlockImports:
def find_spec(self, fullname, *args):
if fullname.startswith(("app.services", "app.core.config", "openai",
"fastembed", "langchain", "chromadb")):
raise AssertionError("Forbidden import: " + fullname)
sys.meta_path.insert(0, BlockImports())
def audit(event, args):
if event in ("socket.connect", "os.walk", "os.scandir"):
raise AssertionError("Unexpected I/O: " + event)
sys.addaudithook(audit)
for name in ("app.modules.documents.settings", "app.modules.documents.types",
"app.modules.documents.ports", "app.infrastructure.database", "app.bootstrap"):
importlib.import_module(name)
assert "app.core.config" not in sys.modules
"""
environment = {k: v for k, v in os.environ.items()
if not k.startswith(("INGEST_", "API_KEY", "LLM_"))}
result = subprocess.run([sys.executable, "-c", script], env=environment,
capture_output=True, text=True)
assert result.returncode == 0, result.stderr
+50
View File
@@ -0,0 +1,50 @@
"""Test isolation and explicit PostgreSQL acceptance requirements."""
import os
from app.modules.documents.settings import IngestionSettings
import subprocess
import sys
def test_acceptance_mode_requires_database_configuration(monkeypatch):
environment = {k: v for k, v in os.environ.items() if k != "TEST_DATABASE_URL"}
result = subprocess.run(
[sys.executable, "-m", "pytest", "--require-postgres",
"tests/integration/test_migrations.py::test_empty_migration_tables_and_pinned_profile"],
env=environment, capture_output=True, text=True,
)
assert result.returncode != 0
assert "TEST_DATABASE_URL is required" in result.stdout
assert "1 error" in result.stdout
def test_baseline_settings_use_defaults_and_preserve_database_acceptance(settings):
assert settings.max_original_bytes == 20 * 1024 * 1024
assert settings.max_staged_bytes == 128 * 1024 * 1024
assert settings.poll_seconds == 2
assert settings.heartbeat_seconds == 20
assert settings.lease_seconds == 120
def test_explicit_environment_loading_is_preserved(settings, monkeypatch):
monkeypatch.setenv("INGEST_POLL_SECONDS", "7")
values = settings.model_dump()
values.pop("poll_seconds")
assert IngestionSettings(_env_file=None, **values).poll_seconds == 7
def test_ordinary_suite_ignores_ambient_ingestion_configuration():
# Re-run the complete ordinary suite once, excluding this recursion driver.
environment = dict(os.environ, INGEST_MAX_ORIGINAL_BYTES="1024",
INGEST_MAX_STAGED_BYTES="4096", INGEST_MAX_CHUNKS="10",
INGEST_POLL_SECONDS="5", INGEST_HEARTBEAT_SECONDS="10",
INGEST_LEASE_SECONDS="60", INGEST_RETRY_BASE_SECONDS="1",
INGEST_RETRY_CAP_SECONDS="10", INGEST_EMBEDDING_TIMEOUT_SECONDS="15")
result = subprocess.run(
[sys.executable, "-m", "pytest", "-m", "not postgres", "-q",
"-k", "not test_ordinary_suite_ignores_ambient_ingestion_configuration"],
env=environment, capture_output=True, text=True,
)
assert result.returncode == 0, result.stdout + result.stderr
assert "failed" not in result.stdout
assert "passed" in result.stdout