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:
@@ -0,0 +1 @@
|
||||
"""Foundation test package."""
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user