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,83 @@
|
||||
"""Trusted operator bootstrap only. No HTTP authentication or chat initialization."""
|
||||
import argparse
|
||||
from getpass import getpass
|
||||
import json
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.infrastructure.database import check_compatibility, create_database
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
|
||||
|
||||
def bootstrap(connection, *, organization_name, username, password, assistant_name, instruction):
|
||||
username = username.strip().lower()
|
||||
if not username or len(username) > 120:
|
||||
raise ValueError("Username must contain 1-120 characters")
|
||||
if not organization_name.strip() or len(organization_name) > 200:
|
||||
raise ValueError("Organization name must contain 1-200 characters")
|
||||
if not assistant_name.strip() or len(assistant_name) > 120:
|
||||
raise ValueError("Assistant name must contain 1-120 characters")
|
||||
if not password:
|
||||
raise ValueError("Password cannot be empty")
|
||||
# Transaction-level advisory lock serializes concurrent initial bootstrap.
|
||||
connection.execute(text("SELECT pg_advisory_xact_lock(812350019)"))
|
||||
if connection.execute(text("SELECT EXISTS(SELECT 1 FROM organizations)")).scalar_one():
|
||||
raise ValueError("Initial organization already exists; bootstrap never resets credentials")
|
||||
org, user = uuid4(), uuid4()
|
||||
password_hash = PasswordHasher().hash(password)
|
||||
connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,:name)"),
|
||||
{"id": org, "name": organization_name})
|
||||
connection.execute(text("""
|
||||
INSERT INTO users(id,organization_id,username,password_hash,role)
|
||||
VALUES (:id,:org,:username,:hash,'admin')
|
||||
"""), {"id": user, "org": org, "username": username, "hash": password_hash})
|
||||
connection.execute(text("""
|
||||
INSERT INTO organization_settings
|
||||
(organization_id,assistant_name,instruction,updated_by)
|
||||
VALUES (:org,:name,:instruction,:user)
|
||||
"""), {"org": org, "name": assistant_name, "instruction": instruction, "user": user})
|
||||
return {"organization_id": str(org), "administrator_id": str(user)}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--organization-name", required=True)
|
||||
parser.add_argument("--username", required=True)
|
||||
parser.add_argument("--assistant-name", required=True)
|
||||
parser.add_argument("--instruction", required=True)
|
||||
parser.add_argument("--password-stdin", action="store_true",
|
||||
help="Read one password line from a securely supplied pipe")
|
||||
args = parser.parse_args()
|
||||
if args.password_stdin:
|
||||
password = sys.stdin.readline().rstrip("\r\n")
|
||||
else:
|
||||
if not sys.stdin.isatty():
|
||||
parser.error("Use an interactive terminal or explicitly select --password-stdin")
|
||||
password = getpass("Initial administrator password: ")
|
||||
if password != getpass("Confirm password: "):
|
||||
parser.error("Passwords do not match")
|
||||
engine = None
|
||||
try:
|
||||
settings = IngestionSettings()
|
||||
engine = create_database(settings.database_url.get_secret_value())
|
||||
with engine.begin() as connection:
|
||||
check_compatibility(connection, settings.embedding_profile)
|
||||
result = bootstrap(
|
||||
connection, organization_name=args.organization_name,
|
||||
username=args.username, password=password,
|
||||
assistant_name=args.assistant_name, instruction=args.instruction,
|
||||
)
|
||||
print(json.dumps(result))
|
||||
except Exception:
|
||||
# Never print DB parameters, secrets, password hashes or configuration values.
|
||||
parser.exit(1, "Bootstrap failed; verify configuration, schema and initial-account state.\n")
|
||||
finally:
|
||||
if engine is not None:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Lazy SQLAlchemy/Psycopg access. No connections or settings are created on import."""
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.engine import Connection, Engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.modules.documents.types import EmbeddingProfile
|
||||
|
||||
SCHEMA_REVISION = "0001_ingestion_foundation"
|
||||
FOUNDATION_TABLES = (
|
||||
"organizations", "users", "organization_settings", "documents",
|
||||
"ingestion_jobs", "document_chunks", "audit_events",
|
||||
)
|
||||
FOUNDATION_RELATIONS = (*FOUNDATION_TABLES, "alembic_version")
|
||||
|
||||
|
||||
def assert_foundation_scope(connection: Connection, schema: str, *, require_all=True) -> None:
|
||||
"""Check actual name resolution before migrations or disposable-schema writes."""
|
||||
if connection.execute(text("SELECT current_schema()")).scalar_one() != schema:
|
||||
raise CompatibilityError("Unexpected application schema")
|
||||
for name in FOUNDATION_RELATIONS:
|
||||
resolved = connection.execute(text("""
|
||||
SELECT n.nspname, c.relkind
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
|
||||
WHERE c.oid=to_regclass(:name)
|
||||
"""), {"name": name}).one_or_none()
|
||||
if resolved is None:
|
||||
if require_all:
|
||||
raise CompatibilityError("Missing scoped foundation relation")
|
||||
elif resolved[0] != schema or resolved[1] != "r":
|
||||
raise CompatibilityError("Foundation relation resolves outside application schema")
|
||||
|
||||
|
||||
|
||||
class CompatibilityError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def create_database(url: str) -> Engine:
|
||||
from sqlalchemy.engine import make_url
|
||||
if make_url(url).drivername != "postgresql+psycopg":
|
||||
raise ValueError("PostgreSQL with Psycopg is required")
|
||||
return create_engine(url, pool_pre_ping=True, hide_parameters=True)
|
||||
|
||||
|
||||
def register_vector_types(connection: Connection) -> None:
|
||||
"""Register native vector adaptation on this connection after migration."""
|
||||
from pgvector.psycopg import register_vector
|
||||
register_vector(connection.connection.driver_connection)
|
||||
|
||||
|
||||
def session_factory(engine: Engine):
|
||||
return sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
|
||||
def check_compatibility(connection: Connection, profile: EmbeddingProfile) -> None:
|
||||
"""Fail closed on schema, dimension or full embedding identity mismatch."""
|
||||
schema = connection.execute(text("SELECT current_schema()")).scalar_one()
|
||||
assert_foundation_scope(connection, schema)
|
||||
if connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one() != SCHEMA_REVISION:
|
||||
raise CompatibilityError("Unexpected ingestion schema revision")
|
||||
row = connection.execute(text("""
|
||||
SELECT format_type(a.atttypid,a.atttypmod) AS vector_type,
|
||||
col_description(a.attrelid,a.attnum) AS profile
|
||||
FROM pg_attribute a
|
||||
WHERE a.attrelid = to_regclass('document_chunks')
|
||||
AND a.attname = 'embedding' AND NOT a.attisdropped
|
||||
""")).mappings().one_or_none()
|
||||
if row is None or row["vector_type"] != f"vector({profile.dimensions})":
|
||||
raise CompatibilityError("Embedding dimension differs from migrated schema")
|
||||
try:
|
||||
pinned = json.loads(row["profile"])
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise CompatibilityError("Missing or invalid migrated embedding profile") from exc
|
||||
if pinned != asdict(profile):
|
||||
raise CompatibilityError("Embedding identity differs from migrated profile")
|
||||
incompatible = connection.execute(text("""
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM documents
|
||||
WHERE processing_profile->'embedding' IS DISTINCT FROM CAST(:profile AS jsonb)
|
||||
)
|
||||
"""), {"profile": json.dumps(pinned)}).scalar_one()
|
||||
if incompatible:
|
||||
raise CompatibilityError("A document has an incompatible processing profile")
|
||||
|
||||
|
||||
class SqlDocumentRepository:
|
||||
"""Read port bound to the caller's short-lived connection/transaction."""
|
||||
def __init__(self, connection: Connection):
|
||||
self.connection = connection
|
||||
|
||||
def get_document(self, organization_id: UUID, document_id: UUID):
|
||||
return self.connection.execute(text("""
|
||||
SELECT * FROM documents WHERE organization_id=:org AND id=:id
|
||||
"""), {"org": organization_id, "id": document_id}).mappings().one_or_none()
|
||||
|
||||
def get_enabled_administrator(self, user_id: UUID):
|
||||
return self.connection.execute(text("""
|
||||
SELECT id, organization_id, role FROM users
|
||||
WHERE id=:id AND role='admin' AND is_enabled
|
||||
"""), {"id": user_id}).mappings().one_or_none()
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Ports only; concrete intake, embedding and publication arrive in later phases."""
|
||||
from typing import Mapping, Protocol, Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from .types import EmbeddingProfile
|
||||
|
||||
|
||||
class FileStore(Protocol):
|
||||
def put(self, content: bytes) -> str:
|
||||
"""Create a new immutable original under a generated key; never overwrite."""
|
||||
...
|
||||
|
||||
def read(self, storage_key: str) -> bytes: ...
|
||||
|
||||
|
||||
class EmbeddingProvider(Protocol):
|
||||
@property
|
||||
def profile(self) -> EmbeddingProfile: ...
|
||||
|
||||
def embed(self, texts: Sequence[str]) -> Sequence[Sequence[float]]: ...
|
||||
|
||||
|
||||
class DocumentRepository(Protocol):
|
||||
def get_document(
|
||||
self, organization_id: UUID, document_id: UUID
|
||||
) -> Mapping[str, object] | None: ...
|
||||
|
||||
def get_enabled_administrator(self, user_id: UUID) -> Mapping[str, object] | None:
|
||||
"""Resolve scope from a trusted operator's persisted administrator identity."""
|
||||
...
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Explicitly constructed ingestion settings; unrelated to prototype chat credentials."""
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
import re
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from pydantic import Field, SecretStr, ValidationError, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from .types import EmbeddingProfile
|
||||
|
||||
|
||||
class IngestionSettings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="INGEST_", env_file=".env", extra="ignore", hide_input_in_errors=True
|
||||
)
|
||||
database_url: SecretStr
|
||||
embedding_model: str = Field(min_length=1)
|
||||
embedding_dimensions: int = Field(gt=0)
|
||||
embedding_provider: str = Field(min_length=1)
|
||||
embedding_endpoint: str = Field(min_length=1)
|
||||
embedding_api_key: SecretStr | None = None
|
||||
embedding_preprocessing_version: str = Field(default="v1", min_length=1)
|
||||
embedding_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
|
||||
original_directory: Path = Path("data/originals")
|
||||
accepted_formats: tuple[str, ...] = (".pdf", ".md")
|
||||
max_original_bytes: int = Field(default=20 * 1024 * 1024, gt=0)
|
||||
max_pdf_pages: int = Field(default=200, gt=0)
|
||||
max_normalized_characters: int = Field(default=1_000_000, gt=0)
|
||||
max_chunks: int = Field(default=2000, gt=0)
|
||||
chunk_size_characters: int = Field(default=1000, gt=0)
|
||||
chunk_overlap_characters: int = Field(default=200, ge=0)
|
||||
embedding_batch_size: int = Field(default=32, gt=0)
|
||||
max_staged_bytes: int = Field(default=128 * 1024 * 1024, gt=0)
|
||||
worker_concurrency: int = Field(default=1, ge=1, le=1)
|
||||
poll_seconds: float = Field(default=2, gt=0, allow_inf_nan=False)
|
||||
heartbeat_seconds: float = Field(default=20, gt=0, allow_inf_nan=False)
|
||||
lease_seconds: float = Field(default=120, gt=0, allow_inf_nan=False)
|
||||
max_automatic_attempts: int = Field(default=3, gt=0)
|
||||
retry_base_seconds: float = Field(default=2, gt=0, allow_inf_nan=False)
|
||||
retry_cap_seconds: float = Field(default=300, gt=0, allow_inf_nan=False)
|
||||
|
||||
@field_validator(
|
||||
"embedding_model", "embedding_provider",
|
||||
"embedding_preprocessing_version"
|
||||
)
|
||||
@classmethod
|
||||
def nonblank(cls, value):
|
||||
value = value.strip()
|
||||
if not value:
|
||||
raise ValueError("Profile identity cannot be blank")
|
||||
return value
|
||||
|
||||
|
||||
@field_validator("embedding_endpoint", mode="before")
|
||||
@classmethod
|
||||
def supported_endpoint(cls, value):
|
||||
message = "Endpoint must be an absolute HTTP(S) host/port/path URL without authentication, query, fragment or encoded components"
|
||||
if not isinstance(value, str) or not value or any(
|
||||
character.isspace() or ord(character) < 32 for character in value
|
||||
) or any(character in value for character in ("@", "?", "#", "%", "\\", ";")):
|
||||
raise ValueError(message)
|
||||
try:
|
||||
parsed = urlsplit(value)
|
||||
if (parsed.scheme not in ("http", "https") or not parsed.hostname
|
||||
or parsed.username is not None or parsed.password is not None
|
||||
or parsed.query or parsed.fragment or parsed.port == 0
|
||||
or not re.fullmatch(r"/[A-Za-z0-9._~/-]*|", parsed.path)):
|
||||
raise ValueError(message)
|
||||
if not re.fullmatch(r"[A-Za-z0-9.:-]+", parsed.hostname):
|
||||
raise ValueError(message)
|
||||
if parsed.netloc.endswith(":"):
|
||||
raise ValueError(message)
|
||||
except ValueError:
|
||||
raise ValueError(message) from None
|
||||
# Preserve scheme, host casing, explicit ports and path identity.
|
||||
return value
|
||||
|
||||
@field_validator("database_url")
|
||||
@classmethod
|
||||
def postgres_only(cls, value):
|
||||
from sqlalchemy.engine import make_url
|
||||
from sqlalchemy.exc import ArgumentError
|
||||
parsed = None
|
||||
try:
|
||||
parsed = make_url(value.get_secret_value())
|
||||
except (ArgumentError, ValueError, TypeError, OverflowError):
|
||||
# Do not retain the parser exception: its text/context may contain
|
||||
# credentials or a secret supplied as a malformed port.
|
||||
pass
|
||||
# Raise outside the except block to avoid even a suppressed raw context.
|
||||
if (parsed is None or parsed.drivername != "postgresql+psycopg"
|
||||
or (parsed.port is not None and not 1 <= parsed.port <= 65535)):
|
||||
raise ValueError("Database URL must be a valid postgresql+psycopg URL")
|
||||
return value
|
||||
|
||||
@field_validator("accepted_formats")
|
||||
@classmethod
|
||||
def supported_formats(cls, value):
|
||||
if not value or len(set(value)) != len(value) or not set(value) <= {".pdf", ".md"}:
|
||||
raise ValueError("Accepted formats must be a nonempty subset of .pdf and .md")
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def coherent_limits(self):
|
||||
if self.chunk_overlap_characters >= self.chunk_size_characters:
|
||||
raise ValueError("Chunk overlap must be smaller than chunk size")
|
||||
if self.heartbeat_seconds >= self.lease_seconds:
|
||||
raise ValueError("Heartbeat must be shorter than lease")
|
||||
if self.retry_base_seconds > self.retry_cap_seconds:
|
||||
raise ValueError("Retry base must not exceed retry cap")
|
||||
return self
|
||||
|
||||
@property
|
||||
def embedding_profile(self) -> EmbeddingProfile:
|
||||
return EmbeddingProfile(
|
||||
self.embedding_provider, self.embedding_endpoint.rstrip("/"),
|
||||
self.embedding_model, self.embedding_dimensions,
|
||||
self.embedding_preprocessing_version,
|
||||
)
|
||||
|
||||
def processing_profile(self) -> dict:
|
||||
"""Snapshot settings; retries must use this persisted snapshot, not fresh defaults."""
|
||||
return {
|
||||
"extractor": "pypdf-markdown-v1",
|
||||
"normalizer": "unicode-line-endings-v1",
|
||||
"chunker": "paragraph-v1", "size_unit": "characters",
|
||||
"chunk_size": self.chunk_size_characters,
|
||||
"overlap": self.chunk_overlap_characters,
|
||||
"embedding": asdict(self.embedding_profile),
|
||||
"limits": {
|
||||
name: getattr(self, name) for name in (
|
||||
"max_original_bytes", "max_pdf_pages",
|
||||
"max_normalized_characters", "max_chunks",
|
||||
"embedding_batch_size", "max_staged_bytes",
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
def require_embedding_credentials(self) -> None:
|
||||
if self.embedding_api_key is None or not self.embedding_api_key.get_secret_value().strip():
|
||||
raise ValueError("INGEST_EMBEDDING_API_KEY is required for a hosted adapter")
|
||||
|
||||
@model_validator(mode="wrap")
|
||||
@classmethod
|
||||
def redact_validation_inputs(cls, values, handler):
|
||||
try:
|
||||
return handler(values)
|
||||
except ValidationError as exc:
|
||||
# Structured errors otherwise retain raw URL and complete input maps.
|
||||
redacted = ValidationError.from_exception_data(
|
||||
cls.__name__, exc.errors(include_input=False, include_url=False),
|
||||
hide_input=True,
|
||||
)
|
||||
# Raising after leaving the handler drops the raw ValidationError context,
|
||||
# whose structured errors still contain the original settings inputs.
|
||||
raise redacted from None
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Provider-neutral ingestion values. Importing this module performs no I/O."""
|
||||
from dataclasses import dataclass
|
||||
from typing import Mapping
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EmbeddingProfile:
|
||||
provider: str
|
||||
endpoint: str
|
||||
model: str
|
||||
dimensions: int
|
||||
preprocessing_version: str = "v1"
|
||||
|
||||
def __post_init__(self):
|
||||
if self.dimensions <= 0 or not all(
|
||||
value.strip() for value in
|
||||
(self.provider, self.endpoint, self.model, self.preprocessing_version)
|
||||
):
|
||||
raise ValueError("Embedding profile requires explicit identity and dimension")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractedBlock:
|
||||
text: str
|
||||
page: int | None = None
|
||||
section: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ChunkDraft:
|
||||
ordinal: int
|
||||
text: str
|
||||
page: int | None = None
|
||||
section: str | None = None
|
||||
token_count: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StagedDocument:
|
||||
document_id: UUID
|
||||
processing_profile: Mapping[str, object]
|
||||
chunks: tuple[ChunkDraft, ...]
|
||||
vectors: tuple[tuple[float, ...], ...]
|
||||
embedding_profile: EmbeddingProfile
|
||||
Reference in New Issue
Block a user