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
+214
View File
@@ -0,0 +1,214 @@
# Ingestion foundation setup
This implements ingestion pipeline phase 1 only: schema, settings, ports and trusted
initial-account bootstrap. Import/status/retry CLI, extraction, embedding adapter,
worker, publication and retrieval are subsequent phases. Prototype chat still uses
Chroma and its separate credentials.
## Install
Use Python 3.11+ and PostgreSQL with pgvector installed on the server.
The migration role needs CREATE EXTENSION privileges (or a DBA must preinstall
vector), plus schema/table creation privileges.
~~~powershell
python -m venv .venv
.venv/Scripts/python -m pip install -e ".[test]"
~~~
Optional prototype dependencies: pip install -e ".[prototype]". Foundation
installation neither imports the prototype nor downloads an embedding model.
This manifest uses bounded dependency ranges, not a reproducible lockfile.
## Configure and migrate
Copy .env.example to .env. Supply INGEST_DATABASE_URL with the
postgresql+psycopg:// scheme and explicitly select provider, endpoint, model and
dimension. No production embedding model or dimension is supplied by default.
Keep secrets out of shell history and source control. Foundation/bootstrap need
no embedding API key; the future hosted adapter requires its separate key.
~~~powershell
.venv/Scripts/alembic upgrade head
~~~
The initial migration explicitly creates vector(D) using the configured positive
dimension and stores the full provider/endpoint/model/dimension/preprocessing
identity as a column comment. Applied migration files are never regenerated when
configuration changes. Subsequent upgrade head verifies the pinned profile;
changing environment settings cannot alter an existing schema. Model changes
require an explicit new migration/reindexing design, even for equal dimensions.
Do not manually edit the comment to bypass compatibility checks. The future worker
must call check_compatibility before processing. SQLAlchemy connections can call register_vector_types after migration for native Psycopg pgvector values.
Migration downgrade drops these tables and their content; use forward migrations
once data exists. The extension is retained.
## Initial trusted administrator
Run from an interactive terminal; the password is prompted twice without echo:
~~~powershell
.venv/Scripts/python -m app.bootstrap --organization-name "Example" --username admin --assistant-name "Assistant" --instruction "Answer from organization documents."
~~~
For automation, --password-stdin reads one line from a securely supplied pipe.
There is deliberately no password argument or password environment variable.
Bootstrap creates organization, enabled lowercase administrator (Argon2id hash),
and settings with all three revisions at 1 in one transaction. A transaction
advisory lock serializes concurrent bootstrap. It refuses an existing organization
and never resets credentials. Output contains only the new organization/admin IDs.
This is operator tooling, not HTTP authentication.
## Tests
Ordinary tests are deterministic and do not call providers:
~~~powershell
.venv/Scripts/python -m pytest -m "not postgres"
~~~
Database tests require a dedicated disposable PostgreSQL database whose name ends
in _test; never point them at production. They create a randomly named schema
for each test, migrate it, use independent connections for concurrency checks,
and remove only that schema on teardown. They install vector into the dedicated test_vector namespace, never relocate an existing extension, and refuse a database with vector in another namespace. Use a fresh dedicated test database if vector was previously installed in public. The application search path contains the disposable schema and test_vector only; it never includes public. Every test connection checks relation ownership before use, and migrations explicitly qualify their version table and validate relation resolution before downgrade. The extension namespace must contain no foundation relations.
Example local service (requires working Docker):
~~~powershell
docker run --name rag-foundation-test -e POSTGRES_PASSWORD=test-only -e POSTGRES_DB=rag_foundation_test -p 127.0.0.1:55432:5432 -d pgvector/pgvector:pg16
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:test-only@127.0.0.1:55432/rag_foundation_test"
.venv/Scripts/python -m tests.postgres_prerequisites
.venv/Scripts/python -m pytest -m postgres --require-postgres
~~~
Wait for PostgreSQL readiness before tests. Stop/remove the explicitly named
test container after use. The acceptance command fails if TEST_DATABASE_URL is missing; it must never be interpreted as successful acceptance from skips. Running the general suite without this flag skips PostgreSQL tests with an explicit non-acceptance reason. A configured unavailable database fails rather than replacing it with mocks. The public-table preservation regression also needs CREATEDB permission: it creates its own UUID-named database ending in _test, installs pre-existing public foundation tables/data there, exercises disposable-schema setup, writes, downgrade/upgrade and normal/exception teardown, compares public OIDs/rows/constraints/profile comments, then drops only that generated database.
Required evidence covers scoped foreign keys, state/counter checks, vector
dimension, duplicate requests/jobs/chunk ordinals/audit replay under concurrency,
profile compatibility and serialized bootstrap.
INGEST_ACCEPTED_FORMATS is a JSON array, for example [".md"].
All configured limits are validated when IngestionSettings is explicitly
constructed. Worker concurrency is constrained to one document for this milestone.
Retry policy is bounded exponential backoff with jitter in a later worker phase;
this phase only supplies validated base/cap/attempt settings. The processing
snapshot uses character units, retains extraction/chunking/embedding metadata and
excludes credentials. Types/ports do not claim to validate or publish complete
staged results yet. Immutable original storage is a FileStore contract; its
concrete adapter arrives with intake, and no file is modified by this foundation.
## Endpoint structure and secret handling
Supported endpoints are absolute HTTP or HTTPS URLs with an ASCII DNS/IP host,
optional valid nonzero port, and an optional path made of ASCII letters, digits,
slashes, dots, underscores, tildes and hyphens. For example
https://api.example.invalid/v1 or http://localhost:8080/tenant/deployment-01/v1.
IPv6 literals use brackets. Host casing, explicit ports and path identity are
preserved; the existing profile convention strips trailing slashes only.
User information, query strings (including an empty query marker), fragments,
path parameters, percent-encoded components, backslashes, control characters and
whitespace are rejected rather than stripped or persisted. Supply authentication
only through INGEST_EMBEDDING_API_KEY (SecretStr). Printed and structured settings
validation errors omit input values. Snapshots contain no credentials.
All duration settings require finite positive numbers; NaN and both infinities
are invalid in direct construction and environment configuration.
Existing applied profile comments/document profiles are not silently rewritten.
No affected historical deployment has been identified or remediated by this work.
Do not change existing profile comments, document profiles or original files merely
because they could contain a historical credential. If a deployment is identified:
first record a redacted inventory and obtain explicit remediation authorization.
Then rotate the exposed credential through the deployment's secret-management
process. With that authorization, prepare a reviewed forward migration targeting
only affected profile metadata and the matching pinned comment. Preserve provider,
model, dimensions, preprocessing identity, original bytes and unrelated revisions;
agree the credential-free endpoint identity explicitly rather than stripping URL
components silently. If the service/model identity changes, design reindexing
before claiming compatibility. Restrict affected backup/log access and handle
their cleanup only under an authorized retention policy. Verify compatibility
and absence of credentials afterward. Never edit the initial migration or
claim rotation/metadata cleanup occurred without evidence.
## Declared pgvector compatibility
The manifest retains pgvector >=0.3.6,<1. Native vector acceptance handles the
NumPy loader in 0.3.6 and the Vector loader in 0.5.0, preserving equal numeric
round-trip assertions. Run the same PostgreSQL tests in both environments:
~~~powershell
python -m venv .venv/minimum
.venv/minimum/Scripts/python -m pip install -e ".[test]" "pgvector==0.3.6"
.venv/minimum/Scripts/python -m tests.postgres_prerequisites
.venv/minimum/Scripts/python -m pytest -m postgres --require-postgres
.venv/Scripts/python -m tests.postgres_prerequisites
.venv/Scripts/python -m pytest -m postgres --require-postgres
~~~
Native vector round trips have now passed against real PostgreSQL in both versions. The 0.3.6 test uses its supported NumPy input/output adapter; 0.5.0 uses native Vector. The numeric assertions are identical. Package imports alone are not adaptation evidence.
## Current acceptance status (2026-10-05)
Docker is now operational. A dedicated localhost-only temporary
pgvector/pgvector:pg16 container provided PostgreSQL 16.15 and extension 0.8.7.
Both prerequisite commands passed, including actual CREATE/DROP DATABASE and
extension installation privileges. The database was rag_foundation_test on the
temporary localhost port 54918. Test credentials belonged only to this container.
Exact checks (all final test runs have zero failures/errors/skips):
- .venv/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
- .venv/minimum/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected (pgvector Python 0.5.0).
- .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected (pgvector Python 0.3.6).
- .venv/Scripts/python -m pytest --require-postgres -q: 163 passed.
- Both environments' python -m tests.postgres_prerequisites: passed.
- Both environments' python -m pip check: no broken requirements.
- .venv/Scripts/alembic history: unchanged initial revision discovered.
Database tests prove empty-schema upgrade, scoped FKs, state/uniqueness
constraints, full profile compatibility, concurrent bootstrap, native vectors,
pre-existing public-table/data preservation and scoped downgrade/upgrade.
Initial real-DB runs exposed test defects: inline JSON was mistaken for a bind
parameter; deparsed constraints varied with search_path; 0.3.6 lacked the root
Vector export. JSON now uses a bind, public constraints are compared through
stable complete catalog rows, and native vector inputs match each supported
adapter. No assertion was weakened.
Malformed database URLs now produce one generic settings validation error;
raw SQLAlchemy parser exceptions are discarded before raising. str/repr/json,
structured errors and exposed context/cause chains are checked with dummy
credentials in direct and environment construction. Valid Psycopg URLs retain
their identity. Tests clear ambient INGEST_* overrides (case-insensitively) per
test while preserving TEST_DATABASE_URL. Explicit environment tests install
their own values, and the ordinary suite is also rerun under external valid
limit/duration overrides. Production environment loading is unchanged.
The initial migration's bytes and SHA-256 remain unchanged. These repairs
require no persisted schema changes or forward migration. No historical metadata
was changed. Test acceptance is local evidence only: no deployment, real-provider
quality, HTTP authentication or later ingestion phase is validated.
Final cleanup/inspection: the dedicated database reported zero leftover disposable
schemas, zero generated foundation_*_test databases and zero public application
tables. The temporary acceptance container and its anonymous test volume were
removed; no other container was touched. git diff --check passed, syntax and
new-file whitespace checks passed, and the original migration hash was preserved.
Test organization: tests/unit contains provider-free configuration, endpoint,
database URL, import and test-environment cases. tests/integration contains
PostgreSQL migrations/profile, constraints, concurrency, vector and isolation
cases, with database-only fixtures and a directory-wide postgres marker.
tests/support contains reusable PostgreSQL and row helpers; tests never import
helpers from another test module. Shared settings fixtures remain in root
conftest.py. The tests.postgres_prerequisites command remains unchanged.
Organization validation: .venv/Scripts/python -m pytest --require-postgres -q:
163 passed. .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres
-q: 48 passed, 115 deselected. Both prerequisite commands passed on a temporary
dedicated PostgreSQL/pgvector container. Final runs had no failures/errors/skips.
The first moved-helper run exposed a repository-root path error, which was fixed
before these final checks. Initial migration hash, test syntax/whitespace and
git diff --check passed. See [test layout](../tests/README.md).