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
+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})