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,38 @@
|
||||
---
|
||||
name: implement-feature
|
||||
description: "Implement or modify a scoped application capability in this repository, including necessary regression tests. Use for behavior changes; exclude tests-only requests, review-only requests, and skill authoring."
|
||||
---
|
||||
|
||||
# Implement a Phase 1 feature
|
||||
|
||||
Read applicable AGENTS.md instructions and the [shared reference map](../../../data/documents/agent-reference-map.md). Use its implement-feature reading route and current implementation inventory; planned modules are not proof of existing code.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Identify the requested behavior, acceptance criteria, and Phase 1 boundary. Select the relevant plan, workflow, API, and database sections. Use scenario examples for observable behavior, not as a replacement for contracts.
|
||||
2. Inspect Git status, affected code, callers, tests/fixtures, and integration boundaries. Preserve unrelated changes. Recheck the map's inventory before choosing commands or introducing tooling.
|
||||
3. State a short plan proportional to the change and continue without routine permission requests. Isolate genuinely missing product decisions; continue independent work while requesting the needed decision.
|
||||
4. Implement the smallest complete behavior across affected transport, application, persistence/provider, and UI boundaries. Do not create layers or edit consumers the task does not affect. Preserve provider-neutral application interfaces and one retrieval implementation for text and Live.
|
||||
5. For affected flows, implement permissions, state transitions, error mapping, bounded failure handling, and concurrency/replay contracts together. Read the precise contract before choosing status codes, schema fields, locking, or retry behavior.
|
||||
6. Add meaningful tests for changed behavior and regressions using existing fixtures and conventions. Test externally observable results or invariants, not private implementation wording. No test harness exists in the initial inventory; do not claim a runner is available without checking.
|
||||
7. Run targeted repository checks and necessary integration checks. Verify PostgreSQL-specific behavior on isolated PostgreSQL/pgvector when applicable; mocks are not database constraint evidence. Keep ordinary tests deterministic and network-free. Treat real-provider quality evaluation as separate, authorized work with prerequisites.
|
||||
8. For an intentional contract change, update API/schema documentation, affected consumers, and tests coherently. Do not rewrite expected behavior to hide a defect. Update the map when source locations or verified commands change.
|
||||
9. Inspect the final diff for unrelated edits, leaked secrets, broken links, and incomplete behavior. Report actual checks and limitations.
|
||||
|
||||
## Relevant contract checks
|
||||
|
||||
Select checks according to the affected flow; do not mechanically expand scope.
|
||||
|
||||
- Upload/retry: independent identity, stable replay, changed-payload conflict, same-document retry, no searchable partial chunks.
|
||||
- Worker: durable claim, lease/token fencing, duplicate-free atomic publication, bounded retries, provider calls outside long transactions.
|
||||
- Search: backend-derived scope, ready/active/undeleted filtering, compatible embeddings, document/chunk evidence identities.
|
||||
- Conversations: owner checks, deduplicated turns/provider work, source references unique across the turn, stale-context invalidation and finalization races.
|
||||
- Live: shared retrieval, trusted tool dispatch, duplicate events, observable close/failure, server-side secrets; consult provisional provider contracts before implementation.
|
||||
|
||||
## Stop or narrow work
|
||||
|
||||
If a required reference is missing, mark its dependent work blocked and name the missing path. If authoritative contracts conflict, surface the concrete conflict instead of inventing policy. Missing provider access blocks live validation, not unrelated implementation. Do not claim release readiness from mocks or absent checks. Do not implement deferred roadmap features to complete a scoped task.
|
||||
|
||||
## Report
|
||||
|
||||
State changed behavior and acceptance coverage, list affected files, give exact checks with outcomes, and identify remaining decisions, unrun checks, or risks. Separate completed implementation from unverified runtime behavior. Do not invoke other skills recursively.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: review-change
|
||||
description: "Review a repository diff, implementation, or proposed merge for actionable defects and Phase 1 contract violations. Review-only by default; use when review is requested, not to implement features or write tests."
|
||||
---
|
||||
|
||||
# Review a Phase 1 change
|
||||
|
||||
Read applicable AGENTS.md instructions and the [shared reference map](../../../data/documents/agent-reference-map.md). Follow its review-change reading route, including Phase 1 exclusions and the distinction between the prototype and planned design.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Resolve the requested scope and base. Inspect Git status and the actual diff, including relevant untracked files when in scope. For a merge review, establish the intended target and merge base; do not silently assume a branch. If the base cannot be determined, ask a focused question and continue independent inspection.
|
||||
2. Read affected surrounding code, callers, tests, and governing document sections. For an implementation review without a diff, state the inspected paths. Distinguish pre-existing gaps from defects introduced by the change.
|
||||
3. Check correctness, authorization, API/schema contract alignment, data integrity, failure behavior, and relevant concurrency/retry semantics. Inspect consumers when contracts intentionally change.
|
||||
4. For changed retrieval or lifecycle code, trace a concrete failure path for inactive/deleted document exposure, forged scope, stale context, invalid citations, or duplicate provider work. Check document/chunk identity and provider/application boundaries.
|
||||
5. For changed jobs or persistence, check claim/lease fencing, atomic publication, lock order, replay uniqueness, and interruption recovery against database contracts. Do not infer constraint correctness from mocks.
|
||||
6. For changed conversations or Live code, check owner authorization, turn/source mapping, epoch rechecks, shared retrieval, duplicate tool events, and close/failure states. Treat live signaling as provisional until the documented provider proof exists.
|
||||
7. Validate suspected findings using targeted read-only inspection or checks safe for the requested scope. Do not execute production writes. Ordinary app imports can initialize embeddings/storage; inspect command side effects first. If a check needs repository mutation or unavailable services, report the limitation.
|
||||
8. Prioritize actionable defects over style. Require a reproducible trigger or concrete failure path and material impact. Do not invent findings to populate the report.
|
||||
9. Report findings before the summary, ordered by severity. State review scope, checks performed, and untested risks even when no defects are found.
|
||||
|
||||
## Scope and stopping conditions
|
||||
|
||||
Default to review-only: do not modify files or fix defects unless the user requests fixes. Do not recursively invoke implementation or testing skills. Missing references or unresolved contract decisions limit only dependent conclusions; disclose the exact gap and continue unrelated review.
|
||||
|
||||
Do not report deferred roadmap features as bugs. Use the Phase 1 plan to distinguish missing scoped functionality from intentional exclusions, and the current task to distinguish introduced defects from unrelated prototype limitations. Existing code is not authority for conflicting contracts; documentation changes cannot excuse an unintended bug.
|
||||
|
||||
## Findings format
|
||||
|
||||
For each finding include:
|
||||
|
||||
- Severity: critical, high, medium, or low, proportionate to impact and likelihood.
|
||||
- Actual file and line/location, with the smallest useful affected location.
|
||||
- Concrete trigger and failure path.
|
||||
- User/data/security impact.
|
||||
- Recommended correction direction and supporting contract or observed check.
|
||||
|
||||
Close with scope/base, checks and their outcomes, and residual risks. If no actionable defects are found, say so explicitly without implying comprehensive correctness or execution of unavailable tests.
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
name: write-tests
|
||||
description: "Create or improve tests for repository behavior, regressions, or release risks. Also use for real-question RAG evaluation before a demo; keep real-provider evaluation optional and separate from ordinary tests."
|
||||
---
|
||||
|
||||
# Test Phase 1 behavior
|
||||
|
||||
Read applicable AGENTS.md instructions and the [shared reference map](../../../data/documents/agent-reference-map.md). Follow its write-tests reading route. The initial repository has no automated test runner or fixtures; inspect current files before selecting a harness or reporting commands.
|
||||
|
||||
## Automated test workflow
|
||||
|
||||
1. Read intended behavior, affected contracts, existing implementation, and tests before choosing assertions. Identify the failure or release risk and acceptance criterion.
|
||||
2. Choose the smallest useful level: unit, integration, contract, or end-to-end. Reuse the repository's runner, naming, fixtures, and dependency conventions. If still absent, establish a minimal suitable harness within the requested test scope and explain the choice; do not present an invented command as existing.
|
||||
3. Select relevant success, failure, and boundary cases. Assert behavior and important invariants rather than mechanically enumerating combinations or mirroring implementation details.
|
||||
4. Mock external providers at adapter/transport boundaries where appropriate. Do not mock the behavior under test. Avoid importing application singletons that can index files, download embeddings, or contact providers during collection.
|
||||
5. Use an isolated PostgreSQL/pgvector test environment for database-specific constraints, vector queries, transactions, or races. Verify the target is a disposable test database before destructive fixtures. A fake database or SQLite is not evidence for PostgreSQL semantics; never use production.
|
||||
6. Keep ordinary automated tests deterministic and network-free by default. Control time, retries, and randomness through injected dependencies where supported; use explicit synchronization for concurrency assertions.
|
||||
7. Run targeted tests and inspect failures. Do not weaken assertions, skip regressions, or change expected behavior solely to make the suite pass.
|
||||
8. Distinguish product bugs, test defects, and unavailable environments. Report product bugs exposed by tests without silently expanding a tests-only request into a production fix. Explain any regression test that remains failing.
|
||||
9. Inspect the diff and record actual results, including tests not run and why. Do not claim mock output establishes real-model quality.
|
||||
|
||||
## Choose relevant cases
|
||||
|
||||
- Upload: admin authorization, invalid files, empty/failed extraction, no partial publication; same upload replay and changed-payload conflict.
|
||||
- Search: authorized ready/active/undeleted scope, forged model scope arguments, compatible embedding profile, source document/chunk identity.
|
||||
- Worker: expired leases, stale claim rejection, retry on the same document/job, duplicate-free publication, deletion during processing.
|
||||
- Turns: conversation ownership, repeated chat replay, changed-payload conflict, concurrent submissions, interruption/recovery, evidence mapping across multiple searches.
|
||||
- Revocation: document deactivation/delete, stale context, epoch race during finalization, retained historical answers without reuse.
|
||||
- Live: dispatch through shared retrieval, duplicate/conflicting tool events, trusted state transitions, close/control failure and revocation.
|
||||
|
||||
Read the precise API/database rules for the cases selected. Do not silently treat the prototype's current behavior as the contract.
|
||||
|
||||
## Real-provider RAG evaluation
|
||||
|
||||
This is optional and separate from the default automated suite. Use when real-output quality is requested or release readiness requires it, with authorized environment and data access.
|
||||
|
||||
1. Check credentials without exposing them, approved corpus, runnable service, selected text/embedding/live profiles, and authorized network/cost limits. For voice, require an actual browser/microphone/WebRTC interaction or explicitly label voice not run.
|
||||
2. Prepare a small, isolated corpus and questions with expected facts and evidence identities. Cover Persian paraphrases, direct facts, missing knowledge, ambiguous questions, follow-ups, and inactive-document cases as relevant. The plan proposes 15-20 questions; do not invent a passing quality threshold.
|
||||
3. Bound requests, tool calls, retries, time, and spend using existing authorization. Stop when the agreed bound or provider failure is reached; do not loop indefinitely or upload sensitive data to unapproved destinations.
|
||||
4. Check extraction separately: recovered text, sections/pages actually available, empty extraction, and chunk boundaries.
|
||||
5. Check retrieval separately: expected evidence is returned, excluded documents remain absent, and document/chunk IDs resolve. Record observed evidence rather than treating plausible prose as successful retrieval.
|
||||
6. Check answers separately: factual support, uncertainty on missing knowledge, follow-up consistency, and citation identity. Prefer fact/evidence assertions over exact full-answer wording.
|
||||
7. Run and report text and voice separately. Voice requires a real backend tool call and spoken result; text-only execution is not voice evidence. Distinguish retrieved voice sources from verified spoken citations.
|
||||
8. Label model-based judging and human checks explicitly. They are assessment methods, not deterministic proof. Record corpus/profile, question, expected evidence, observed extraction/retrieval/answer/source outcome, and failure category; report metrics only from executed cases with denominators.
|
||||
9. If credentials, corpus, service, authorization, or voice interaction are unavailable, mark the affected evaluation not run with the precise prerequisite. Never substitute cached or mock results as real execution.
|
||||
|
||||
Protect secrets and sensitive text in artifacts. Preserve only approved evidence and redacted diagnostics. Do not change application features just to complete an evaluation.
|
||||
|
||||
## Stop or narrow work
|
||||
|
||||
Missing authoritative behavior blocks dependent assertions; name the missing reference or product decision and continue independent cases. A provider outage or missing database is an environment limitation, not a passing result. A discovered product bug stays reported unless fixing it is within the user's scope.
|
||||
|
||||
## Report
|
||||
|
||||
Give tested behavior and level, changed test files, exact commands/outcomes, and defects or environment limitations. For real-provider work, add executed case counts, evidence-based observations, text/voice status, judging method, and unrun checks. Do not invoke other skills recursively.
|
||||
@@ -16,3 +16,32 @@ CHUNK_SIZE=1000
|
||||
CHUNK_OVERLAP=200
|
||||
DOCS_DIR="./data/documents"
|
||||
CHROMA_PERSIST_DIR="./data/vector_db"
|
||||
|
||||
# Independent ingestion settings. Choose the real deployment profile explicitly.
|
||||
INGEST_DATABASE_URL="postgresql+psycopg://user:password@localhost:5432/rag"
|
||||
INGEST_EMBEDDING_PROVIDER=""
|
||||
# HTTP(S) host/optional port/path only; no userinfo/query/fragment/encoded components.
|
||||
INGEST_EMBEDDING_ENDPOINT=""
|
||||
INGEST_EMBEDDING_MODEL=""
|
||||
INGEST_EMBEDDING_DIMENSIONS=
|
||||
# Not needed for schema/bootstrap; required by the future hosted adapter.
|
||||
INGEST_EMBEDDING_API_KEY=""
|
||||
INGEST_EMBEDDING_PREPROCESSING_VERSION="v1"
|
||||
INGEST_EMBEDDING_TIMEOUT_SECONDS=60
|
||||
INGEST_ORIGINAL_DIRECTORY="data/originals"
|
||||
INGEST_ACCEPTED_FORMATS='[".pdf", ".md"]'
|
||||
INGEST_MAX_ORIGINAL_BYTES=20971520
|
||||
INGEST_MAX_PDF_PAGES=200
|
||||
INGEST_MAX_NORMALIZED_CHARACTERS=1000000
|
||||
INGEST_MAX_CHUNKS=2000
|
||||
INGEST_CHUNK_SIZE_CHARACTERS=1000
|
||||
INGEST_CHUNK_OVERLAP_CHARACTERS=200
|
||||
INGEST_EMBEDDING_BATCH_SIZE=32
|
||||
INGEST_MAX_STAGED_BYTES=134217728
|
||||
INGEST_WORKER_CONCURRENCY=1
|
||||
INGEST_POLL_SECONDS=2
|
||||
INGEST_HEARTBEAT_SECONDS=20
|
||||
INGEST_LEASE_SECONDS=120
|
||||
INGEST_MAX_AUTOMATIC_ATTEMPTS=3
|
||||
INGEST_RETRY_BASE_SECONDS=2
|
||||
INGEST_RETRY_CAP_SECONDS=300
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Preserve immutable migration snapshots byte-for-byte across platforms.
|
||||
/migrations/versions/*.py -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
|
||||
@@ -83,3 +83,6 @@ Thumbs.db
|
||||
logs/
|
||||
tmp/
|
||||
temp/
|
||||
|
||||
# Immutable ingestion originals (may contain private uploaded content)
|
||||
data/originals/
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Repository guidance
|
||||
|
||||
## Phase 1 development
|
||||
|
||||
Use the [shared reference map](data/documents/agent-reference-map.md) for document authority, current source locations, commands, and unresolved decisions. Read applicable nested instructions before editing.
|
||||
|
||||
- Deliver Phase 1 with a modular FastAPI backend and a separate ingestion worker from the same codebase. The current prototype does not yet implement that target.
|
||||
- Each upload creates an independent document; never overwrite its original content in place. Do not introduce `document_versions`, `version_id`, or `version_no` for document content.
|
||||
- Chunks and ingestion jobs reference `document_id`; answer sources reference `document_id` and `chunk_id`. Retry processes the same eligible failed document and job.
|
||||
- Only authorized, ready, active, undeleted documents are searchable. Backend-derived identity and scope cannot be overridden by model arguments.
|
||||
- Text and Live use the same backend search implementation. Keep persistent provider secrets server-side and provider-specific objects behind adapters.
|
||||
- Follow the documented request deduplication, worker claim/lease fencing, atomic publication, and context invalidation rules for affected workflows.
|
||||
- Preserve configuration revisions, knowledge selection revisions, access epochs, and embedding profile metadata; these are not document-content versioning.
|
||||
- Keep API/schema documentation and consumers aligned with intentional contract changes. Never change a contract merely to excuse a bug.
|
||||
- Avoid unnecessary dependencies, services, abstractions, and unrelated refactoring. Preserve unrelated working-tree changes.
|
||||
|
||||
The Phase 1 plan governs scope, API/database documents govern their contracts, and the implementation guide governs workflows. Broader architecture is context, not authorization for deferred features. Existing code is evidence, not proof that conflicting behavior is correct. Surface material contradictions; isolate missing product decisions and continue independent work.
|
||||
|
||||
## Skills and checks
|
||||
|
||||
Repository skills live in `.agents/skills/`: `implement-feature`, `write-tests`, and `review-change`. Implementation includes necessary validation; tests-only work reports product defects without silently fixing them; review is read-only unless fixes are requested. Do not recursively dispatch between skills.
|
||||
|
||||
Verified inspection commands from the repository root: `git status --short`, `git diff --check`, and `rg --files --hidden -g '!.git/**'`. The dependency manifest is pyproject.toml; provider-free checks use .venv/Scripts/python -m pytest -m "not postgres". PostgreSQL acceptance uses .venv/Scripts/python -m pytest -m postgres --require-postgres with an isolated TEST_DATABASE_URL. Missing configuration must fail acceptance; ordinary-suite skips do not prove database behavior. No build/lint pipeline exists. See the reference map and docs/ingestion-foundation-setup.md for setup and actual results. Treat applied revisions as immutable.
|
||||
@@ -1,3 +1,5 @@
|
||||
For the new ingestion foundation (independent of prototype chat), see [setup and validation](docs/ingestion-foundation-setup.md). Only ingestion phase 1 is implemented; database acceptance must be verified on PostgreSQL/pgvector.
|
||||
|
||||
# 🤖 Technical Documentation Assistant (RAG Agent)
|
||||
|
||||
[](https://fastapi.tiangolo.com)
|
||||
@@ -5,7 +7,7 @@
|
||||
[](https://github.com/langchain-ai/langchain)
|
||||
[](https://www.trychroma.com/)
|
||||
[-blue.svg?style=flat-square)](https://github.com/qdrant/fastembed)
|
||||
[](https://www.python.org/)
|
||||
[](https://www.python.org/)
|
||||
[](LICENSE)
|
||||
|
||||
An intelligent, production-ready **Retrieval-Augmented Generation (RAG)** assistant built with **FastAPI**, **LangGraph**, **LangChain**, and **ChromaDB**. The assistant is specialized in indexing, searching, and reasoning over technical documentation to provide developers with accurate, source-grounded answers and production-ready code examples with zero hallucinations.
|
||||
@@ -132,7 +134,7 @@ rag-technical-docs-assistant/
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Python 3.10+** installed on your machine.
|
||||
- **Python 3.11+** installed on your machine.
|
||||
- An API key for an OpenAI-compatible provider (such as [OpenRouter](https://openrouter.ai/) or [OpenAI](https://platform.openai.com/)).
|
||||
|
||||
### Installation
|
||||
@@ -156,7 +158,7 @@ rag-technical-docs-assistant/
|
||||
|
||||
3. **Install dependencies:**
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
pip install -e ".[prototype]"
|
||||
```
|
||||
*(Or install the core packages: `fastapi uvicorn langgraph langchain langchain-openai langchain-chroma chromadb fastembed pydantic-settings`)*
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
[alembic]
|
||||
script_location = %(here)s/migrations
|
||||
prepend_sys_path = .
|
||||
path_separator = os
|
||||
@@ -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
|
||||
@@ -0,0 +1,631 @@
|
||||
# Organization Knowledge Assistant — Software Architecture
|
||||
|
||||
| Document field | Value |
|
||||
| --- | --- |
|
||||
| Version | 1.1 — simplified document lifecycle |
|
||||
| Date | 2026-10-05 |
|
||||
| Status | Proposed implementation design; open decisions are listed in Section 19 |
|
||||
| Audience | Project management, technical mentor, backend, frontend and AI developers |
|
||||
| Application | Organization-managed document RAG with text and direct live voice conversations |
|
||||
| Source baseline | Project requirements and architecture decisions recorded during design |
|
||||
|
||||
Document lifecycle decision (revision 1.1): every upload is an independent immutable document. Chunks and ingestion jobs reference it directly; answer sources use document/chunk IDs. Content versioning is not a current requirement. Settings revisions and embedding profile metadata remain technical controls, not document versions.
|
||||
|
||||
## 1. Purpose and Scope
|
||||
|
||||
The system enables authenticated users to ask questions in Persian, including conversational wording, and receive answers grounded in reference documents selected by their organization. It supports text chat and direct speech-to-speech interaction with a live AI model. Organization administrators manage the knowledge base without changing application code.
|
||||
|
||||
The initial business use case is a reliable demonstration and subsequent organizational service. Business success depends on understandable answers, verifiable sources, document coverage and dependable operation. This architecture does not guarantee commercial outcomes or zero hallucinations.
|
||||
|
||||
### 1.1 Confirmed design constraints
|
||||
|
||||
- PostgreSQL with pgvector stores application data and document embeddings.
|
||||
- OpenAI supplies embedding and text generation capabilities; exact model identifiers remain configurable and must be evaluated.
|
||||
- Voice conversations use a live speech-to-speech model and WebRTC. There is no separate application ASR or TTS pipeline.
|
||||
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
|
||||
- Documents are dynamically uploaded, updated and selected by the organization.
|
||||
- The only initial knowledge tool is `search_documents`. A separate read-document tool is excluded.
|
||||
- Text and voice have separate entry points but share retrieval, access rules, configuration and persistent history services.
|
||||
- The dashboard includes login, document management, model configuration, text entry and microphone controls.
|
||||
|
||||
### 1.2 Proposed implementation choices
|
||||
|
||||
A modular monolith built with Python and FastAPI, plus a separate ingestion worker from the same codebase, is the proposed deployment baseline. PostgreSQL-backed jobs avoid requiring a separate broker initially. LangGraph may continue to orchestrate text-agent turns. The provider-native live session performs the voice conversation loop; LangGraph does not need to process every audio frame.
|
||||
|
||||
These choices are architecture recommendations, not claims that the existing repository already implements them. File formats, live provider/model, authentication integration, retention rules, capacity targets and delivery dates require confirmation.
|
||||
|
||||
### 1.3 Scope boundaries
|
||||
|
||||
The initial system includes document ingestion, organization-scoped retrieval, text and live voice conversations, citations, configuration, operational logging and basic administration. Fine-tuning, autonomous database writes by the model, internet search, arbitrary tools, CTI integration and a separate audio transcription service are outside the current scope. Raw audio recording is not a baseline requirement.
|
||||
|
||||
## 2. Architecture Principles
|
||||
|
||||
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
|
||||
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
|
||||
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
|
||||
4. **Direct live audio:** browser-to-provider media is separate from backend session control and tool execution.
|
||||
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
|
||||
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
|
||||
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
|
||||
8. **Incremental implementation:** add extraction strategies and retrieval refinements based on actual documents and evaluation results.
|
||||
|
||||
## 3. System Context and Deployment Boundaries
|
||||
|
||||
| Component | Responsibilities | Deployment |
|
||||
| --- | --- | --- |
|
||||
| Web dashboard | Login, chat, microphone/speaker, captions, sources, document and settings screens | Browser over HTTPS |
|
||||
| FastAPI application | Authorization, text orchestration, live session control, tools, document APIs and history | Backend process |
|
||||
| Ingestion worker | Extraction, chunking, embedding, retries and publication | Separate process from the same codebase |
|
||||
| PostgreSQL + pgvector | Metadata, jobs, history, configuration, chunks and vectors | Persistent database |
|
||||
| File storage | Original uploaded document bytes | Durable volume or object storage |
|
||||
| Text/embedding provider | Text-agent inference and vector generation | External OpenAI API |
|
||||
| Live provider | Direct audio understanding and speech generation | External live model service |
|
||||
|
||||
A provider adapter is backend code. It is not the provider service. The browser connects to the provider's WebRTC media endpoint, while the backend owns credentials, session policy and private tool execution.
|
||||
|
||||
The two presentation diagrams are retained in Appendix A. They show logical responsibilities; they do not imply that the live model runs inside the backend deployment.
|
||||
|
||||
## 4. Backend Modules and Dependency Rules
|
||||
|
||||
| Module | Owns | Public application operations |
|
||||
| --- | --- | --- |
|
||||
| Identity | Users, organization memberships and session authorization | Authenticate user; resolve organization and role |
|
||||
| Documents | File metadata, ingestion state and selection | Upload independent document; list; activate; deactivate |
|
||||
| Knowledge | Chunk retrieval and evidence construction | Search authorized knowledge |
|
||||
| Conversations | Conversations, turns, messages, citations and summaries | Start; submit turn; read history; close |
|
||||
| Live Sessions | Provider session mapping, connection state and live event handling | Create; connect control channel; process event; close |
|
||||
| Configuration | Allowed model profiles and retrieval settings | Read and update versioned settings |
|
||||
| Audit/Operations | Administrative events, traces and health | Record audit event; expose operational status |
|
||||
|
||||
API handlers validate transport data, authenticate and call application services. Application services coordinate domain rules through interfaces. Provider clients, SQLAlchemy repositories and file-storage implementations belong to infrastructure. Tools call application services rather than API endpoints inside the same process.
|
||||
|
||||
Shared organization context is created from authenticated identity. Client input and model arguments cannot override it. Cross-module access uses explicit operations rather than arbitrary writes to another module's tables.
|
||||
|
||||
### 4.1 Suggested code organization
|
||||
|
||||
| Path | Purpose |
|
||||
| --- | --- |
|
||||
| `app/main.py` | API bootstrap and dependency wiring |
|
||||
| `app/worker.py` | Ingestion worker entry point |
|
||||
| `app/api/v1/` | HTTP and application event endpoints |
|
||||
| `app/modules/identity/` | Authentication and authorization |
|
||||
| `app/modules/documents/` | Document lifecycle |
|
||||
| `app/modules/knowledge/` | Retrieval and search tool contracts |
|
||||
| `app/modules/conversations/` | Text turns and persistent history |
|
||||
| `app/modules/live/` | Live session controller |
|
||||
| `app/modules/configuration/` | Model profiles and organization settings |
|
||||
| `app/integrations/ai/` | Text, embedding and live provider adapters |
|
||||
| `app/infrastructure/db/` | Repositories, migrations and database sessions |
|
||||
| `app/infrastructure/storage/` | Original-file access |
|
||||
| `app/infrastructure/jobs/` | Durable job claiming and retry implementation |
|
||||
| `tests/` | Unit, integration, contract and scenario evaluations |
|
||||
|
||||
Use application/domain/infrastructure subdivisions where module complexity warrants them. Do not introduce empty abstractions solely to match the proposed directory structure.
|
||||
|
||||
## 5. Agentic Conversation Design
|
||||
|
||||
### 5.1 Agent responsibilities
|
||||
|
||||
The agent interprets the user's wording and conversation context, asks clarification when meaning is ambiguous, and calls `search_documents` for organization-specific facts. It can answer greetings and conversational coordination without retrieval. For factual questions about the documents, it is instructed to obtain supporting evidence before answering.
|
||||
|
||||
The agent may reformulate queries while preserving dates, negation, location, units and other constraints. It must distinguish, for example, general opening hours from Thursday-specific hours. It can issue another search when initial results are incomplete, subject to configured call and time limits.
|
||||
|
||||
Document content is evidence, not executable instructions. Retrieved text cannot grant permissions, change tools or override the agent policy. Answers should identify uncertainty and conflicting sources rather than silently resolve a policy dispute.
|
||||
|
||||
### 5.2 Agentic behavior and enforcement
|
||||
|
||||
The model's choice to search is probabilistic. A system prompt alone cannot guarantee that every factual response is grounded. The application enforces tool authorization, budgets and source validity; evaluation checks whether the model calls the tool appropriately and supports its claims.
|
||||
|
||||
For text responses, validate structured source references before finalizing a turn. If the model returns invalid references, use a bounded repair attempt or return a controlled error. A stricter pre-release factuality gate can be added if evaluation requires it.
|
||||
|
||||
For direct live speech, audio may reach the user before a server-side validation step finishes. This architecture therefore does not claim a prevalidated guarantee for every spoken sentence. If that guarantee becomes mandatory, the audio release/control design must be revisited and its latency impact accepted explicitly.
|
||||
|
||||
### 5.3 Text turn sequence
|
||||
|
||||
1. Authenticate the request and verify conversation ownership.
|
||||
2. Persist the user message using a client request ID to detect retries.
|
||||
3. Load bounded conversation context and a configuration/document-selection snapshot.
|
||||
4. Run the text agent with the registered search tool.
|
||||
5. Validate and execute tool calls through the shared knowledge service.
|
||||
6. Return tool evidence to the same agent loop.
|
||||
7. Produce a response, validate reference IDs and persist the assistant message and citations.
|
||||
8. Return the final answer or stream supported application events.
|
||||
|
||||
A failed turn is recorded explicitly and does not appear as a completed assistant answer. Retrying a completed request returns the existing result instead of creating duplicate messages.
|
||||
|
||||
## 6. Search Tool Contract
|
||||
|
||||
### 6.1 Model-visible interface
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "search_documents",
|
||||
"description": "Search the organization's selected reference documents for evidence relevant to a question.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "A focused search question preserving the user's constraints."}
|
||||
},
|
||||
"required": ["query"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The tool does not accept organization IDs, arbitrary document paths, SQL, credentials or a model-selected permission scope. The backend supplies identity, allowed documents, embedding profile, retrieval limits and trace identifiers through trusted execution context.
|
||||
|
||||
### 6.2 Result contract
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"search_id": "search_example",
|
||||
"selection_revision": 7,
|
||||
"results": [
|
||||
{
|
||||
"source_ref": "S1",
|
||||
"document_id": "doc_example",
|
||||
"chunk_id": "chunk_example",
|
||||
"title": "Working Hours Policy",
|
||||
"page": 3,
|
||||
"section": "Thursday Schedule",
|
||||
"text": "Illustrative evidence text from the uploaded document."
|
||||
}
|
||||
],
|
||||
"warnings": []
|
||||
}
|
||||
```
|
||||
|
||||
The sample IDs and content are illustrative. Page and section are nullable when extraction cannot identify them. References are scoped to a turn/search; persistent citations use stable document/chunk IDs. Never fabricate page numbers.
|
||||
|
||||
Tool statuses distinguish `ok`, `no_results`, `knowledge_unavailable` and `error`. An empty authorized knowledge base is different from an unrelated query; a provider failure must not be presented as proof that no relevant document exists.
|
||||
|
||||
### 6.3 Execution pipeline
|
||||
|
||||
1. Validate non-empty query and enforce configured length/call budgets.
|
||||
2. Resolve organization access and selected documents from trusted state.
|
||||
3. Recheck current document permissions and deactivation before retrieval.
|
||||
4. Normalize Persian query text without changing semantic constraints.
|
||||
5. Embed the query using the compatible embedding profile of the active index.
|
||||
6. Run filtered vector retrieval and optionally combine lexical results.
|
||||
7. Deduplicate, select relevant chunks and cap the evidence token budget.
|
||||
8. Build references from stored metadata and persist retrieval provenance.
|
||||
9. Return evidence to the requesting text or live agent.
|
||||
|
||||
The semantic baseline is required. Lexical fusion and reranking are optional improvements enabled after measurement. Persian lexical behavior must be tested with actual data; a generic full-text configuration is not assumed to provide Persian stemming automatically.
|
||||
|
||||
Similarity values are ranking signals, not probabilities that an answer is correct. Any relevance threshold is calibrated against the evaluation set. For small datasets, exact vector search is an acceptable baseline. Approximate index choice, filtered recall and performance are measured before deployment.
|
||||
|
||||
## 7. Dynamic Document Lifecycle
|
||||
|
||||
### 7.1 Upload and extraction
|
||||
|
||||
The API validates the configured file allowlist, size and basic file signature, stores the original under a generated storage key, calculates a checksum, creates an independent document and enqueues a durable ingestion job. Client filenames are display metadata and never trusted filesystem paths.
|
||||
|
||||
Accepted formats remain an open requirement. The extraction interface supports implementations chosen after representative files are received. OCR is enabled only if scanned material requires it. Empty or unreadable extraction must fail visibly rather than publishing an empty index. Table structure and units must be preserved where needed by the actual corpus.
|
||||
|
||||
### 7.2 Document processing states
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> queued
|
||||
queued --> processing
|
||||
processing --> ready
|
||||
processing --> failed
|
||||
failed --> queued: Retry
|
||||
ready --> deleted: Delete
|
||||
```
|
||||
|
||||
Activation/selection is separate from processing state: a ready document can remain unselected. Only selected ready documents can be searched.
|
||||
|
||||
### 7.3 Chunking and embedding
|
||||
|
||||
Each chunk preserves its document identity, order, text and available source location. Chunk size and overlap are configurable and recorded as processing metadata. The design must avoid splitting meaningful table rows or dropping headings when those structures carry meaning.
|
||||
|
||||
Embedding profiles record provider, model, dimensions and preprocessing version. Documents and queries must use the same compatible profile. Changing the embedding model creates a new index generation: re-embed, verify completion and switch the active generation atomically. Equal vector dimensions do not make two embedding models interchangeable.
|
||||
|
||||
### 7.4 Publication, updates and selection
|
||||
|
||||
Each upload creates a new independent document; there is no document-version entity or in-place content replacement. Upload the changed file, wait until it is ready, then deactivate the old document and activate the new one. The old document remains inactive for historical reference. Failure of the new upload leaves the old active document usable. Retry processes only the same failed document and creates no new identity.
|
||||
|
||||
An administrator selects ready document IDs for the organization. Every turn records the effective selection revision and the source document/chunk IDs. A selection change applies to subsequent turns. Current access revocation/deactivation overrides cached or snapshotted access immediately for new tool operations; sensitive in-flight results must be rechecked before delivery.
|
||||
|
||||
Previously sent evidence cannot be recalled from a provider context. On document revocation during a live conversation, invalidate affected context and reset or close the provider session when necessary. Previously delivered speech cannot be withdrawn. The UI must not imply that changing selection rewrites old answers.
|
||||
|
||||
Deletion first excludes the document from retrieval. Physical deletion follows the retention policy, including chunks, vectors, originals and derived copies. Historical citations retain minimal tombstone metadata when permitted; access to retained content still requires authorization.
|
||||
|
||||
### 7.5 Durable worker behavior
|
||||
|
||||
The worker claims jobs with a lease and claim token, updates progress and publishes only if it still owns the claim. Expired leases allow recovery after a crash. External embedding calls occur outside long database transactions. Idempotent chunk writes and publication prevent duplicate indexed chunks after retries.
|
||||
|
||||
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
|
||||
|
||||
## 8. Live Voice and WebRTC
|
||||
|
||||
### 8.1 Connection responsibilities
|
||||
|
||||
| Channel | Participants | Purpose |
|
||||
| --- | --- | --- |
|
||||
| HTTPS session request | Browser and FastAPI | Authenticate and initialize an authorized live session |
|
||||
| WebRTC media | Browser and live provider | Microphone input and generated speech |
|
||||
| Trusted control connection | Backend and live provider | Tool calls/results, policy updates and session events |
|
||||
| Application event channel | Backend and browser | Source references, status and normalized captions when available |
|
||||
|
||||
OpenAI's WebRTC and server-control documentation establish the direct browser media and trusted server connection patterns [R1, R2]. Exact events and signaling depend on the selected API family. The adapter must implement one tested provider contract; event names from different API families must not be mixed.
|
||||
|
||||
### 8.2 Session establishment
|
||||
|
||||
1. The authenticated browser obtains microphone permission and creates a WebRTC offer.
|
||||
2. The Live Session API verifies ownership, role, usage limits and selected knowledge.
|
||||
3. The backend creates a local session record, resolves model/prompt/tool configuration and performs provider signaling.
|
||||
4. The controller attaches the trusted control connection and confirms that private tool execution is ready.
|
||||
5. The browser receives the session ID and signaling response, then establishes media.
|
||||
6. The dashboard presents connected/listening states and enables conversation.
|
||||
|
||||
A provider-supported short-lived credential flow may replace server signaling. Persistent provider keys remain on the server. Failed setup triggers cleanup of any partially created provider/local session. Readiness of the control path is required before allowing organization-knowledge conversation.
|
||||
|
||||
### 8.3 Voice tool cycle
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as Browser
|
||||
participant L as Live Model
|
||||
participant B as Backend Controller
|
||||
participant K as Knowledge Service
|
||||
U->>L: Audio over WebRTC
|
||||
L->>B: search_documents call
|
||||
B->>B: Validate identity, scope and call
|
||||
B->>K: Execute search
|
||||
K-->>B: Evidence and sources
|
||||
B-->>L: Correlated tool result
|
||||
B-->>U: Source references
|
||||
L-->>U: Generated speech
|
||||
```
|
||||
|
||||
The controller invokes the same search application service used by the text agent. Tool results are correlated by provider session and call ID, and executed once or replayed from a saved result on duplicate events. Allow only registered tool names. Partial argument events are accumulated until the call is complete and validated.
|
||||
|
||||
### 8.4 Turn-taking, interruption and disconnects
|
||||
|
||||
The live provider handles speech input and output. Its turn-detection and interruption capabilities are configured and tested for Persian conversation. When interrupted, the UI stops queued playback using supported provider/browser controls; history distinguishes a completed response from an interrupted one. Generated text must not automatically be treated as fully heard speech.
|
||||
|
||||
Closing the session stops microphone tracks, closes the peer connection and provider control connection, and records termination reason and known usage. Abandoned sessions expire. Reconnection creates or resumes a provider session only when supported; it must not imply transparent recovery after a backend restart.
|
||||
|
||||
If the control connection fails while media remains connected, pause or close knowledge conversation rather than continuing unsupported answers. Late tool results for canceled turns are discarded or recorded without triggering a new response. The dashboard can offer text chat when voice setup fails.
|
||||
|
||||
### 8.5 History and audio limitations
|
||||
|
||||
No separate ASR service is introduced for persistence. Save transcripts/captions only when supplied by the provider, with their source and completion state. Missing transcript events remain missing; do not invent them. Provider captions may differ from what a user meant or actually heard.
|
||||
|
||||
The backend does not automatically possess audio bytes because media travels directly to the provider. Recording audio would require a separate explicit feature and retention decision. Durable history survives a provider session, but continuing a conversation requires explicitly restoring selected history or a summary into the new model context.
|
||||
|
||||
## 9. Logical Data Model
|
||||
|
||||
This is a proposed model for the RAG service, independent of the earlier CTI module's database. Exact SQL migrations follow review of these invariants.
|
||||
|
||||
| Entity | Important fields and purpose |
|
||||
| --- | --- |
|
||||
| organizations | ID, name, status |
|
||||
| users / memberships | Identity, organization, role and active state |
|
||||
| organization_settings | Revision, allowed model profiles, retrieval limits, active selection revision |
|
||||
| documents | Organization, display name, checksum, storage key, MIME, processing status/profile, selected flag, deletion state |
|
||||
| ingestion_jobs | Document, stage, state, attempts, lease owner/token, lease expiry, next attempt, error |
|
||||
| embedding_profiles | Provider/model, dimensions, preprocessing version, index generation and active state |
|
||||
| chunks | Document, ordinal, original and normalized text, page/section, processing profile |
|
||||
| chunk_embeddings | Chunk, embedding profile/generation and vector |
|
||||
| conversations | Organization, owner, title, mode, state and timestamps |
|
||||
| turns | Conversation, sequence, client request ID, configuration/selection snapshot, state |
|
||||
| messages | Turn, role, content, modality, provider item ID, completion/interruption state |
|
||||
| tool_calls | Turn/session, provider call ID, validated query, execution state, result references and latency |
|
||||
| message_sources | Message, document/chunk, source reference and supporting excerpt if allowed |
|
||||
| live_sessions | Conversation, provider session ID, controller owner, model, connection state and timestamps |
|
||||
| audit_events | Actor, organization, action, target, timestamp and redacted metadata |
|
||||
|
||||
All organization-owned access must enforce organization scope. Use foreign keys and constraints to prevent cross-organization relationships, not only API checks. Add unique constraints for chunk ordinals per document, client request IDs per conversation and provider event/call IDs in their proper scope.
|
||||
|
||||
Use relational columns for identifiers, statuses and queryable fields; JSONB holds variable provider metadata and processing details. Do not store secrets in metadata. Use timezone-aware timestamps in UTC and display localized time in the UI. Page numbering semantics must be recorded by the extractor.
|
||||
|
||||
Vector dimension and storage type must match the chosen embedding profile. Separate incompatible vector generations by table/partition or another explicitly tested strategy. Index foreign keys and frequent organization/status filters. Select approximate vector indexes only after measuring filtered recall and query latency [R4].
|
||||
|
||||
## 10. Application API Contracts
|
||||
|
||||
These are proposed application endpoints, not provider API endpoints. The three core business capabilities are document ingestion, text chat and live voice; supporting administration requires additional routes.
|
||||
|
||||
| Method and route | Purpose | Result |
|
||||
| --- | --- | --- |
|
||||
| `POST /api/v1/auth/login` | Local login if local authentication is selected | Secure session; final identity contract TBD |
|
||||
| `POST /api/v1/auth/logout` | End authenticated session | 204 |
|
||||
| `GET /api/v1/me` | Current identity and organization roles | 200 |
|
||||
| `POST /api/v1/documents` | Multipart file upload | 202 with document/job IDs |
|
||||
| `GET /api/v1/documents` | Paginated organization documents | 200 |
|
||||
| `GET /api/v1/documents/{id}` | Metadata and processing state | 200 |
|
||||
| `PATCH /api/v1/knowledge-selection` | Replace selected document IDs using expected revision | 200 or 409 |
|
||||
| `DELETE /api/v1/documents/{id}` | Exclude and schedule permitted cleanup | 202 |
|
||||
| `GET /api/v1/configuration` | Read organization settings and capabilities | 200 |
|
||||
| `PATCH /api/v1/configuration` | Admin settings update using expected revision | 200 or 409 |
|
||||
| `POST /api/v1/conversations` | Start text, voice or mixed conversation | 201 |
|
||||
| `GET /api/v1/conversations/{id}/messages` | Authorized, paginated history | 200 |
|
||||
| `POST /api/v1/chat` | Submit a text turn | JSON result, or explicit SSE mode |
|
||||
| `POST /api/v1/voice/sessions` | Initialize live session and signaling | 201 |
|
||||
| `POST /api/v1/voice/sessions/{id}/close` | Idempotent close | 200 |
|
||||
| `GET /api/v1/conversations/{id}/events` | Authorized application event stream | SSE |
|
||||
| `GET /health/live` | Process liveness | 200 |
|
||||
| `GET /health/ready` | Ability to serve required dependencies | 200 or 503 |
|
||||
|
||||
All IDs from clients are checked for ownership. Pagination and upload limits are bounded. The internal search tool is not an unauthenticated public endpoint. Final endpoint names can evolve before frontend contract freeze.
|
||||
|
||||
### 10.1 Text turn example
|
||||
|
||||
```json
|
||||
{
|
||||
"conversation_id": "conv_example",
|
||||
"client_request_id": "request_example",
|
||||
"message": "What are the organization's Thursday working hours?"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"conversation_id": "conv_example",
|
||||
"turn_id": "turn_example",
|
||||
"message_id": "msg_example",
|
||||
"status": "answered",
|
||||
"answer": "An answer grounded in the selected reference documents.",
|
||||
"sources": [
|
||||
{"source_ref": "S1", "document_id": "doc_example", "chunk_id": "chunk_example", "page": 3}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Final application statuses include `answered`, `needs_clarification`, `insufficient_information` and `failed`. Streaming text is provisional until the completion event validates the final source mapping. The UI must preserve errors or interruption instead of implying successful completion.
|
||||
|
||||
### 10.2 Upload response example
|
||||
|
||||
```json
|
||||
{
|
||||
"document_id": "doc_example",
|
||||
"job_id": "job_example",
|
||||
"status": "queued",
|
||||
"searchable": false
|
||||
}
|
||||
```
|
||||
|
||||
### 10.3 Live session application contract
|
||||
|
||||
The baseline request carries `conversation_id`, `client_request_id` and a WebRTC SDP offer. The response carries an application session ID, the provider adapter's signaling answer and normalized connection state. If a credential-based setup is selected, define a separate validated response variant. Never expose a persistent provider key. Do not log SDP or temporary credentials by default.
|
||||
|
||||
### 10.4 Error envelope
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "KNOWLEDGE_NOT_READY",
|
||||
"message": "Selected documents are not ready for search.",
|
||||
"request_id": "req_example",
|
||||
"retryable": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use 401 for unauthenticated access, 403/404 according to the resource-disclosure policy, 409 for revision/idempotency conflict, 413 for size limit, 415 for unsupported type, 422 for invalid input, 429 for quotas and 503 for unavailable dependencies. Never return internal exception strings or credentials.
|
||||
|
||||
## 11. Configuration and Model Boundaries
|
||||
|
||||
Separate text, live and embedding model profiles. Changing the response model does not rebuild embeddings; changing the embedding profile does. A live profile must support the chosen media and trusted tool-control features. The UI exposes only administrator-approved, capability-compatible models.
|
||||
|
||||
Configuration is revisioned. Record model, prompt, tool schema, retrieval profile and selection revision per turn/session. Apply ordinary model changes to new turns or sessions; do not silently mutate an active live session. Document access revocation is handled immediately as described in Section 7.
|
||||
|
||||
Provider adapters normalize completion events, tool calls, timeouts, rate limits, usage and error categories. They must not assume every model implements identical event schemas. Business services depend on interfaces such as TextModel, EmbeddingProvider, LiveSessionProvider, KnowledgeRepository and FileStore.
|
||||
|
||||
## 12. Security and Organization Isolation
|
||||
|
||||
Authenticate every application entry point and authorize every tool operation. Proposed roles are organization administrator and conversation user; additional roles require a product need. Ordinary users cannot change model credentials or organization selections.
|
||||
|
||||
Use HTTPS, server-managed secrets, controlled CORS origins and an explicit session expiration policy. If cookies are selected, apply secure/HttpOnly attributes and CSRF protection to mutations. If external SSO is selected, replace local credential handling while preserving application membership checks.
|
||||
|
||||
Treat uploads, model arguments and extracted content as untrusted input. Validate upload paths, avoid executing embedded content, limit parser resources and refuse unregistered tools. Restrict client ability to update provider session instructions or inject trusted tool outputs using available provider permissions. Validate remaining access assumptions during the live integration spike.
|
||||
|
||||
Document bodies and full prompts are not ordinary operational logs. Log IDs, stage, latency and redacted errors by default. Access to stored message content and citations follows organization membership and resource permissions. Administrative changes generate audit records.
|
||||
|
||||
## 13. Reliability and Concurrency
|
||||
|
||||
| Failure | Required behavior |
|
||||
| --- | --- |
|
||||
| Embedding rate limit | Bounded retry; preserve job state |
|
||||
| Unsupported/unreadable file | Failed document with actionable reason |
|
||||
| Replacement ingestion failure | Keep prior active document available |
|
||||
| Database outage | Reject dependent operations explicitly; do not invent answers |
|
||||
| Search timeout | Return tool error; distinguish it from no evidence |
|
||||
| Duplicate tool event | Reuse correlated result; avoid duplicate execution/history |
|
||||
| Lost live control channel | Pause or close knowledge interaction and notify UI |
|
||||
| Browser disconnect | Cleanup after grace period and record uncertain completion |
|
||||
| Worker crash | Recover expired lease and continue idempotently |
|
||||
| Invalid citation | Repair within budget or fail the response |
|
||||
|
||||
Serialize mutating turns per conversation in the initial implementation. A text turn must not race with an active voice turn against the same context. Keep live session control owned by one backend process; multi-instance deployment requires routing/ownership and a defined restart policy.
|
||||
|
||||
Retries of text generation and live session creation can incur duplicate provider work after an ambiguous timeout. Correlate application requests, reconcile known provider state where supported and avoid blind automatic recreation. Idempotency keys include a payload hash; reusing a key with a different request returns a conflict.
|
||||
|
||||
## 14. Observability and Performance
|
||||
|
||||
Correlate request, organization, conversation, turn, live session, tool call, document and job IDs. Measure text time to first output, total turn latency, query embedding latency, retrieval latency, live tool turnaround, available audio latency measurements, ingestion duration, error rates and provider usage.
|
||||
|
||||
Do not treat server tool latency as end-to-end voice latency. Browser measurements are required to include microphone, network and playback behavior. Usage may be incomplete if a session terminates before final provider events; represent it as partial rather than zero.
|
||||
|
||||
Capacity targets remain to be agreed: concurrent text users, active voice sessions, corpus size, ingestion throughput, maximum upload size and acceptable percentile latency. Test on the intended deployment network and representative Persian documents. Connection pools, evidence budgets and concurrency limits should be tuned from measurements.
|
||||
|
||||
## 15. Deployment and Operations
|
||||
|
||||
The first deployment consists of the dashboard/HTTPS entry point, one FastAPI service, one ingestion worker, PostgreSQL with pgvector and durable file storage. API and worker share code and configuration but run as separate processes. Redis and an external broker are optional future components, not baseline dependencies.
|
||||
|
||||
Apply reviewed database migrations as an explicit deployment step. Keep separate development, test and production credentials. Readiness checks should validate required local dependencies without making expensive model calls on every health probe. Perform provider connectivity checks as controlled diagnostics.
|
||||
|
||||
Backups must cover both the database and original files with a restorable mapping. Test restoration and reindexing. Recovery objectives, retention schedules and backup frequency are operational decisions requiring approval; no numeric guarantee is implied by this document.
|
||||
|
||||
Graceful shutdown stops new sessions/jobs, drains active work within a configured deadline and records interrupted work. Live sessions cannot be assumed migratable between processes. Monitor disk space, job backlog, database connections and external provider quotas.
|
||||
|
||||
## 16. Validation and Acceptance
|
||||
|
||||
Build a reference evaluation set from approved organization documents and expected answers before tuning prompts. Include natural Persian variants, follow-up pronouns, dates, numbers, conflicting documents, absent information and questions about unselected documents.
|
||||
|
||||
| Area | Acceptance evidence |
|
||||
| --- | --- |
|
||||
| Retrieval | Expected evidence appears for representative questions; numeric recall target agreed with stakeholders |
|
||||
| Grounding | Answer claims supported by cited passages; unsupported questions handled explicitly |
|
||||
| Agent behavior | Appropriate search calls, bounded retries and clarification for ambiguity |
|
||||
| Isolation | Cross-organization IDs and model-supplied scope cannot expose documents |
|
||||
| Dynamic documents | Upload, select, replace, deactivate and delete reflected in new retrieval |
|
||||
| Text history | Retry does not duplicate messages; restart preserves completed conversations |
|
||||
| Voice | Direct speech-to-speech, searchable document answers, interruption, reconnect and close tested |
|
||||
| Control security | Client cannot escalate tool access or change protected session policy |
|
||||
| Ingestion recovery | Crashes and provider failures recover without duplicate publication |
|
||||
| Deployment | HTTPS/microphone behavior, backups and demonstration network verified |
|
||||
|
||||
Use unit tests for permissions and state transitions, integration tests with PostgreSQL/pgvector, provider contract tests, and a small controlled live evaluation. Stub-only tests do not validate actual provider signaling or Persian audio quality. Evaluate text and voice independently even though retrieval is shared.
|
||||
|
||||
## 17. Migration from the Existing Repository
|
||||
|
||||
The earlier review inspected commit `cb54a35`; this mapping refers to that snapshot and is not a claim about a newer branch.
|
||||
|
||||
| Existing area | Required evolution |
|
||||
| --- | --- |
|
||||
| `app/services/retriever.py` | Replace Chroma/FastEmbed with repository and embedding interfaces backed by pgvector/OpenAI |
|
||||
| `app/services/doc_processor.py` | Replace folder-only Markdown ingestion with registered extraction strategies and document-linked jobs |
|
||||
| `app/services/tools/retriever_tool.py` | Enforce trusted organization scope and structured evidence output |
|
||||
| `app/services/agent/exec.py` | Retain the agentic tool loop; add bounded execution, injected services and durable context |
|
||||
| `app/services/agent/prompt.py` | Replace technical-documentation persona with organization-knowledge policy |
|
||||
| `app/schemas/chat.py` | Add conversation/turn identity, structured sources and explicit outcomes |
|
||||
| `app/api/v1/chat.py` | Add authorization, idempotency, safe errors and optional streaming |
|
||||
| `app/core/config.py` | Separate secrets from versioned organization/model settings |
|
||||
| `app/main.py` | Explicit lifecycle initialization, bounded CORS and readiness |
|
||||
|
||||
Remove indexing side effects from module imports. Re-embed the source documents into the new compatible index; do not copy incompatible existing vectors. Treat in-memory conversation state as temporary unless explicitly migrated. Add dependency manifests, migrations, operational packaging and meaningful tests before claiming a reproducible release.
|
||||
|
||||
## 18. Implementation Sequence
|
||||
|
||||
1. Confirm representative documents, question set, live provider capabilities and UI expectations.
|
||||
2. Implement a small WebRTC spike demonstrating direct audio plus a trusted backend tool call.
|
||||
3. Establish the modular backend, database migrations, identity boundary and provider interfaces.
|
||||
4. Implement ingestion, document lifecycle, pgvector retrieval and the search tool contract.
|
||||
5. Deliver the text agent with evidence, durable history and evaluation.
|
||||
6. Connect the live controller to the same tool service; add interruption, sources and failure behavior.
|
||||
7. Deliver organization administration, document selection and model configuration.
|
||||
8. Validate isolation, performance, recovery and the actual presentation environment.
|
||||
|
||||
The text path provides an inspectable foundation while the early voice spike exposes provider/network risk. Final calendar dates depend on the confirmed meeting year, corpus and capacity; this document does not infer a deadline from an ambiguous date.
|
||||
|
||||
## 19. Open Decisions and Owners
|
||||
|
||||
| Decision | Suggested owner | Architectural impact |
|
||||
| --- | --- | --- |
|
||||
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
|
||||
| Organization-wide versus per-assistant document selections | Product owner | Selection model and API scope |
|
||||
| Live provider/model and supported trusted control features | AI/backend team | Adapter, WebRTC signaling and tool execution |
|
||||
| Text and embedding model profiles | AI team | Quality, cost and vector dimensions |
|
||||
| Local authentication or SSO | IT / backend | Login contract and identity integration |
|
||||
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
|
||||
| Concurrent sessions and latency targets | Product / IT | Capacity, scaling and quotas |
|
||||
| Whether spoken answers require pre-release validation | Product / AI | Compatibility with direct live audio |
|
||||
| Hosting, outbound connectivity and data transfer approval | IT / organization | Provider reachability and deployment |
|
||||
| Backup policy and recovery objectives | IT | Operations and restoration testing |
|
||||
| Final UI details | Product owner / Mr. Siavash | Frontend flow and review |
|
||||
| Meeting year and IT handover date | Project manager | Delivery plan |
|
||||
|
||||
These items must be resolved by their owners rather than silently converted into product policy.
|
||||
|
||||
## 20. Reference Documentation
|
||||
|
||||
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
|
||||
|
||||
- **[R1]** [OpenAI — WebRTC](https://developers.openai.com/api/docs/guides/voice-webrtc): browser media connection and signaling patterns.
|
||||
- **[R2]** [OpenAI — Server-side controls](https://developers.openai.com/api/docs/guides/voice-server-controls): trusted backend control connection and private tool execution.
|
||||
- **[R3]** [OpenAI — Realtime with tools](https://developers.openai.com/api/docs/guides/realtime-mcp): function tool calls and correlated results.
|
||||
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
|
||||
|
||||
## Appendix A. Presentation Diagrams
|
||||
|
||||
The following diagrams retain the previously agreed overview. Detailed security, lifecycle and failure requirements are defined in the main sections.
|
||||
|
||||
### A.1 Agentic AI and Dynamic Documents
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
USER["User — Text or Live Voice"] --> AGENT["AI Agent"]
|
||||
|
||||
subgraph AI["Agentic Conversation"]
|
||||
AGENT --> DECISION{"Need Document Knowledge?"}
|
||||
DECISION -->|"Yes"| CALL["Call Search Tool with Search Query"]
|
||||
DECISION -->|"Ready to Answer"| ANSWER["Generate Response with Sources"]
|
||||
end
|
||||
|
||||
subgraph TOOL["Tool: search_documents"]
|
||||
CALL --> SCOPE["Apply Organization and Selected Document Filters"]
|
||||
SCOPE --> QUERY["Embed Search Query"]
|
||||
QUERY --> SEARCH["Semantic Search"]
|
||||
SEARCH --> SELECT["Select Relevant Chunks"]
|
||||
SELECT --> RESULT["Return Content, Document IDs and Sources"]
|
||||
end
|
||||
|
||||
RESULT -->|"Tool Result"| AGENT
|
||||
ANSWER --> USER
|
||||
|
||||
subgraph DOCS["Dynamic Organization Documents"]
|
||||
ADMIN["Organization Admin"] --> MANAGE["Upload, Update and Select Documents"]
|
||||
MANAGE --> PROCESS["Extract, Chunk and Embed"]
|
||||
PROCESS --> DB[("PostgreSQL + pgvector")]
|
||||
MANAGE --> ACTIVE["Active Document Selection"]
|
||||
end
|
||||
|
||||
ACTIVE --> SCOPE
|
||||
SEARCH <-->|"Retrieve Matching Chunks"| DB
|
||||
```
|
||||
|
||||
### A.2 Layered Backend Overview
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph L1["1. Presentation"]
|
||||
UI["Web Dashboard"]
|
||||
end
|
||||
|
||||
subgraph L2["2. Backend API — FastAPI"]
|
||||
CHAT["Text Chat"]
|
||||
SESSION["Live Session"]
|
||||
DOCS["Documents and Configuration"]
|
||||
end
|
||||
|
||||
subgraph L3["3. Agentic AI"]
|
||||
TEXT["Text AI Agent"]
|
||||
LIVE["Live AI Model"]
|
||||
TOOL["Search Documents Tool"]
|
||||
|
||||
TEXT <-->|"Tool Calls and Evidence"| TOOL
|
||||
LIVE <-->|"Tool Calls and Evidence via Backend"| TOOL
|
||||
end
|
||||
|
||||
subgraph L4["4. Knowledge Management"]
|
||||
INGEST["Extract, Chunk and Embed"]
|
||||
SEARCH["Search Organization-selected Documents"]
|
||||
end
|
||||
|
||||
subgraph L5["5. Storage"]
|
||||
FILES[("Document Files")]
|
||||
DB[("PostgreSQL + pgvector — Documents and Chat History")]
|
||||
end
|
||||
|
||||
UI --> CHAT
|
||||
UI --> SESSION
|
||||
UI --> DOCS
|
||||
|
||||
CHAT <--> TEXT
|
||||
SESSION -->|"Initialize and Control"| LIVE
|
||||
UI <-->|"Direct Live Audio — WebRTC"| LIVE
|
||||
|
||||
TOOL <--> SEARCH
|
||||
SEARCH <--> DB
|
||||
|
||||
DOCS -->|"Upload and Update"| INGEST
|
||||
DOCS -->|"Active Document Selection"| SEARCH
|
||||
DOCS -->|"Store Original Files"| FILES
|
||||
FILES --> INGEST
|
||||
INGEST --> DB
|
||||
```
|
||||
@@ -0,0 +1,231 @@
|
||||
# Organization Knowledge Assistant — Phase 1 Delivery Plan
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Version | 1.1 |
|
||||
| Date | 2026-10-05 |
|
||||
| Status | Proposed delivery baseline based on the agreed 7–10 day target |
|
||||
| Parent document | RAG-AI-Architecture.md, architecture baseline v1.1 |
|
||||
| Capacity assumption | One primary developer, reusing working code and a simple UI |
|
||||
| Milestone | Demonstrable integrated release by Day 7; stabilization through Day 10 |
|
||||
| Scope authority | This document defines Phase 1 delivery scope; the parent defines the longer-term architecture |
|
||||
|
||||
## 1. Release Objective
|
||||
|
||||
Deliver an authenticated organization knowledge assistant that supports text chat and live voice. The model decides when to call `search_documents`; the backend executes retrieval against ready, active documents and returns evidence. An administrator can change the knowledge available to the assistant without changing application code.
|
||||
|
||||
The delivery target is a working, deployed demonstration with real documents and real provider calls. It is not a claim of general production readiness, unrestricted file support or capacity certification.
|
||||
|
||||
The schedule uses numbered implementation days. The actual start date, working calendar and presentation date must be confirmed before converting these into calendar commitments. Days 8–10 are stabilization time, not spare capacity for additional features.
|
||||
|
||||
## 2. Delivery Assumptions and Day 1 Decisions
|
||||
|
||||
The estimate depends on access to provider credentials, a deployment environment, representative files, and time for both backend and frontend work. Existing repository components may be reused only after checking their current behavior; prior architecture mappings do not certify the present codebase.
|
||||
|
||||
| Decision or dependency | Required outcome by end of Day 1 |
|
||||
| --- | --- |
|
||||
| Document samples | A small approved corpus and 1–2 explicitly supported formats |
|
||||
| Extraction | Verify that the sample text can be extracted; scans and complex tables are excluded unless already working |
|
||||
| Text and embedding models | One configured profile for each, tested with Persian samples |
|
||||
| Live provider | Real WebRTC audio plus a backend-executed tool call proven together |
|
||||
| Deployment | Confirm HTTPS, microphone access and outbound provider connectivity in the intended environment |
|
||||
| Evaluation questions | A small reference set covering supported, unsupported and follow-up questions |
|
||||
| Identity | One organization and pre-created administrator/user accounts |
|
||||
|
||||
If native WebRTC plus trusted backend tool execution fails, resolve the provider choice on Day 1. Removing voice from the release or routing all audio through the backend is a scope decision requiring product agreement, not a silent implementation fallback.
|
||||
|
||||
## 3. Included and Deferred Scope
|
||||
|
||||
| Area | Phase 1 | Deferred |
|
||||
| --- | --- | --- |
|
||||
| Identity | Simple login, fixed organization, pre-created accounts, admin/user permissions | Registration, invitations, SSO, multi-organization administration |
|
||||
| Documents | Upload, list, status, activate/deactivate and logical delete | Document versioning (not required); automatic replacement workflows |
|
||||
| Formats | 1–2 formats validated against real samples | General-purpose ingestion, OCR and complex table support |
|
||||
| Processing | Separate worker, durable jobs, extraction, chunking, embedding, bounded retry | Distributed worker fleet and separate message broker |
|
||||
| Search | One `search_documents` tool with organization and active-document filtering | Read-document tools, web tools and advanced retrieval tuning |
|
||||
| Text | Agent tool loop, grounded answers, sources, clarification and insufficient-information response | Autonomous actions and advanced agent workflows |
|
||||
| Voice | Start/end WebRTC session, live speech response, same backend search tool, visible connection state | Seamless reconnect, session migration and cross-mode continuation |
|
||||
| History | Durable text messages and citations; live session/tool diagnostics | Guaranteed full live transcript, raw audio recording and unified text/voice history |
|
||||
| Settings | Assistant name and organization instruction | Model selector, voice catalogue, retrieval tuning and retention controls |
|
||||
| Models | Fixed server-configured text, embedding and live profiles | Multiple selectable providers and automatic failover |
|
||||
| Deployment | One environment, basic health checks, logs, migrations and durable volumes | High availability, autoscaling and formal load/SLA certification |
|
||||
|
||||
Active-document controls live on the Documents page to avoid duplicating the same setting across screens. Organization instructions may shape tone and domain behavior but cannot override authorization or search scope.
|
||||
|
||||
## 4. User Interface
|
||||
|
||||
| Screen | Required elements |
|
||||
| --- | --- |
|
||||
| Login | Credentials, login action, clear invalid-login feedback and logout |
|
||||
| Conversation | Text input, messages, loading/error state, evidence sources, conversation list, new conversation, voice start/end and connection status |
|
||||
| Documents — admin | Upload, filename, processing state, readable failure reason, active toggle, delete and retry for eligible failures |
|
||||
| Settings — admin | Assistant name, organization instruction, save and discard changes |
|
||||
|
||||
Live captions are optional if provider support is immediately available; they are not a release dependency. Display retrieved sources for a voice turn without claiming that every retrieved source was necessarily spoken or cited by the model. Mark them as retrieved sources when exact answer attribution is unavailable.
|
||||
|
||||
## 5. Phase 1 Implementation Architecture
|
||||
|
||||
Use one FastAPI modular application, one ingestion worker from the same codebase, PostgreSQL with pgvector, and durable file storage. Keep conversation, document, knowledge and live-session responsibilities separate in code. Do not introduce a separate service per module.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
UI["Web Dashboard"]
|
||||
API["FastAPI Application"]
|
||||
TOOL["Shared Search Documents Tool"]
|
||||
WORKER["Document Worker"]
|
||||
DB[("PostgreSQL + pgvector")]
|
||||
FILES[("Document Files")]
|
||||
LIVE["External Live Model"]
|
||||
|
||||
UI <-->|"Authenticated APIs"| API
|
||||
API <-->|"Text and Voice Tool Execution"| TOOL
|
||||
TOOL <--> DB
|
||||
API -->|"Jobs and History"| DB
|
||||
API -->|"Uploads"| FILES
|
||||
WORKER <-->|"Claim Jobs and Publish Chunks"| DB
|
||||
FILES --> WORKER
|
||||
UI <-->|"WebRTC Audio"| LIVE
|
||||
API <-->|"Session Control and Tool Results"| LIVE
|
||||
```
|
||||
|
||||
The diagram shows deployment responsibilities. Text inference and document/query embeddings use backend provider adapters and are omitted from the diagram for readability. The live model is an external service, not a process inside the backend.
|
||||
|
||||
### 5.1 Text and search
|
||||
|
||||
1. Authenticate the request and load the user's conversation history.
|
||||
2. Give the model the current question, relevant history and the registered search tool.
|
||||
3. For organization-document claims, require evidence before answering. Greetings and clarification can avoid search.
|
||||
4. Validate tool arguments. Resolve organization and active-document scope in the backend, never from model authority.
|
||||
5. Embed the query with the same compatible embedding profile as document chunks.
|
||||
6. Return relevant text, document identity, chunk identity and available source location.
|
||||
7. Generate the answer; record messages and citations. If evidence is insufficient, say so or ask a clarifying question.
|
||||
|
||||
Set a small configurable tool-call limit, request timeout and result-size limit. Exhaustion returns a clear failure or insufficient-information result instead of looping indefinitely. Do not fabricate page numbers when the extractor only provides section or chunk locations.
|
||||
|
||||
### 5.2 Voice
|
||||
|
||||
The backend authenticates and establishes the session using the selected provider's supported signaling/control mechanism. Browser audio uses WebRTC directly to the provider. Long-lived provider credentials remain on the server. The backend executes live tool calls against the same search service as text chat.
|
||||
|
||||
On connection loss, show a disconnected state and allow the user to start a new session. Automatic recovery of provider context is deferred. Test speaking interruption using the selected provider's supported behavior; custom interruption orchestration is outside the initial scope.
|
||||
|
||||
### 5.3 Worker reliability
|
||||
|
||||
Persist jobs before processing. A worker claims a job with a lease/token, records progress and publishes only while it owns the claim. Retry transient provider/network errors within configured limits. Reject unsupported or unreadable input visibly. Repeated execution must not duplicate published chunks.
|
||||
|
||||
Keep provider calls outside long database transactions. Index only after processing succeeds; a partial set of chunks is not searchable. A simple maintenance operation can reconcile abandoned uploads; a dedicated reconciliation service is deferred.
|
||||
|
||||
## 6. Document Lifecycle and Updates
|
||||
|
||||
Processing state is `queued → processing → ready` or `failed`. Selection is a separate active flag. A ready document can remain inactive. Deleted, inactive, failed and partially processed documents must not enter new retrieval.
|
||||
|
||||
Phase 1 replacement procedure:
|
||||
|
||||
1. Upload the replacement as a separate document, initially inactive.
|
||||
2. Wait for successful processing and inspect its extracted/searchable content.
|
||||
3. Deactivate the old document and activate the new document.
|
||||
4. Start a new conversation to demonstrate the new knowledge.
|
||||
|
||||
During manual replacement, a brief interval with neither document active is acceptable and must produce an insufficient-information response. Do not describe this as atomic version replacement. Document versioning is not required by the current architecture; a future change would need an explicit product decision.
|
||||
|
||||
Each upload creates a new immutable document ID. Store chunks and jobs directly against that document ID, and citations against document/chunk IDs. Do not overwrite a ready document; retry only processes the same failed upload. Historical references retain their original document identity. No version table or version-number fields are required.
|
||||
|
||||
Selection changes take effect on new tool operations. Before delivering an in-flight tool result, recheck document eligibility. On deactivation or deletion, mark affected text context stale and require a new conversation; close affected live sessions, or conservatively close organization live sessions if precise tracking is not implemented. New sessions must not receive revoked evidence from old history. Historical messages may remain visible according to authorized history access, but must not be silently reused as current evidence.
|
||||
|
||||
Delete first removes retrieval eligibility. Physical cleanup of files/chunks follows an explicit configured policy; automatic retention management and a retention settings UI are deferred. This document does not invent a retention duration.
|
||||
|
||||
## 7. Minimum Persistent Data
|
||||
|
||||
Use migrations and retain extension points without building unused administration features.
|
||||
|
||||
| Record | Minimum responsibility |
|
||||
| --- | --- |
|
||||
| Organization and users | Fixed organization identity, account, role and secure credential handling |
|
||||
| Documents | Organization, filename, storage key, checksum, processing state, active/deleted flags and processing profile |
|
||||
| Chunks | Document identity, text, source location, embedding and order |
|
||||
| Ingestion jobs | Stage, status, lease/token, attempt count, next retry and error |
|
||||
| Conversations and messages | Owner, organization, ordered text turns, status and timestamps |
|
||||
| Citations/tool results | Evidence identity linked to the relevant turn |
|
||||
| Organization settings | Assistant name, instruction and configuration revision |
|
||||
| Live session metadata | User, provider session mapping, state and diagnostic identifiers; no raw audio |
|
||||
|
||||
These are logical records, not a demand for one table per row. Align physical tables with the parent architecture and the current repository. No unsupported assumption is made that these migrations already exist.
|
||||
|
||||
## 8. Delivery Schedule and Checkpoints
|
||||
|
||||
| Day | Work | Required checkpoint |
|
||||
| --- | --- | --- |
|
||||
| 1 | Confirm files and questions; real WebRTC and backend tool spike; inspect reusable code | Audio and a trusted tool call work together; supported formats and provider chosen |
|
||||
| 2 | Application/database setup, migration, login, upload and early deployment skeleton | Authenticated upload persists across restart |
|
||||
| 3 | Worker, extraction, chunks, embeddings and job status | A real uploaded document reaches ready; unreadable input fails visibly |
|
||||
| 4 | Scoped search tool and source payload | Relevant chunks returned; inactive documents excluded |
|
||||
| 5 | Text agent, grounded responses and durable text history | Complete text scenario with citations and unsupported-question handling |
|
||||
| 6 | Connect live session to real shared retrieval | Spoken document question produces an evidence-based spoken answer |
|
||||
| 7 | Finish four screens, settings and deployed integration | End-to-end demonstration on the actual target environment; feature freeze |
|
||||
| 8 | Evaluate reference questions and improve retrieval/prompting | Main content failures corrected; text and voice tested separately |
|
||||
| 9 | Error handling, access, restart and deactivation tests | No known critical access, duplication or stale-evidence defects |
|
||||
| 10 | Fix remaining blockers, seed demo data, document startup and rehearse | Tagged/reproducible release and successful demonstration rehearsal |
|
||||
|
||||
Day 7 is a constrained demo milestone, not permission to skip critical tests. If only seven days are available, perform essential acceptance checks continuously on Days 2–7 and disclose the narrower validation coverage. Move optional UI polish and captions out first. Do not cut authorization or falsely mark unfinished voice as delivered.
|
||||
|
||||
## 9. Acceptance Criteria
|
||||
|
||||
| ID | Test | Pass condition |
|
||||
| --- | --- | --- |
|
||||
| P1-01 | Login and admin access | Unauthenticated requests fail; normal users cannot change documents/settings |
|
||||
| P1-02 | Upload and readiness | Supported document persists and becomes ready; failed extraction cannot be activated |
|
||||
| P1-03 | Dynamic selection | Newly active content is searchable; inactive/deleted content is absent from new tool results |
|
||||
| P1-04 | Agentic search | Document questions trigger a real tool call; greeting/clarification does not require artificial retrieval |
|
||||
| P1-05 | Text grounding | Curated answerable questions have correct supported answers with resolvable sources |
|
||||
| P1-06 | Missing knowledge | Curated unsupported questions do not receive invented organization facts |
|
||||
| P1-07 | Voice | Real browser WebRTC session invokes backend search and returns a spoken answer; start/end work |
|
||||
| P1-08 | Failure recovery | Voice disconnect is visible and a new session can start; provider failure produces understandable feedback |
|
||||
| P1-09 | Persistence | Text history survives restart; interrupted ingestion recovers without duplicate published chunks |
|
||||
| P1-10 | Revocation | Deactivation prevents reuse in new retrieval and invalidates affected ongoing context as defined in Section 6 |
|
||||
| P1-11 | Secrets and scope | Server keys absent from browser payloads; caller/model cannot override authorized organization scope |
|
||||
| P1-12 | Deployment | Demo works over HTTPS with microphone and provider connectivity in the intended environment |
|
||||
|
||||
Use a proposed reference set of 15–20 questions, covering direct facts, Persian paraphrases, follow-ups, missing information and deactivated documents. Record expected evidence and observed outcomes. Agree any quantitative quality target with the product owner; passing a small demo set is not a general accuracy guarantee.
|
||||
|
||||
Automate authorization, active-document filtering, job retry/publication and persistence checks where practical. Validate actual text and live provider integration with real calls; stub tests alone do not establish readiness.
|
||||
|
||||
## 10. Demonstration Script
|
||||
|
||||
1. Log in as administrator and upload a prepared organization document.
|
||||
2. Show queued/processing/ready state, then activate it.
|
||||
3. Ask a text question; show the answer and its source.
|
||||
4. Ask a follow-up to demonstrate conversation context.
|
||||
5. Ask an unsupported question; show explicit insufficient information.
|
||||
6. Start voice, ask an equivalent document question and hear the answer.
|
||||
7. Deactivate the document; show affected session/context reset.
|
||||
8. Start a new conversation and verify that the document is no longer used.
|
||||
9. Optionally demonstrate a prepared replacement using the manual procedure.
|
||||
|
||||
Prepare both already-processed sample data and an upload example. If an external provider is unavailable during the presentation, disclose it; recorded or cached output must not be represented as a live execution.
|
||||
|
||||
## 11. Risks and Scope Control
|
||||
|
||||
| Risk | Response |
|
||||
| --- | --- |
|
||||
| Voice integration fails late | Prove WebRTC plus backend tool execution on Day 1 |
|
||||
| File complexity exceeds estimate | Limit formats using real samples; reject unsupported inputs clearly |
|
||||
| Backend plus UI exceeds one developer's capacity | Reuse working components; use basic screens; remove optional polish before core scope |
|
||||
| Retrieval produces weak evidence | Test a small corpus early; preserve headings/source locations; tune against the reference set |
|
||||
| Demo network/provider differs from development | Deploy early and rehearse on the actual environment |
|
||||
| New feature requests consume stabilization | Freeze features at Day 7; track additions in the next-phase backlog |
|
||||
|
||||
A change that removes text, dynamic document selection or live voice changes the release promise and must be recorded explicitly. Additional features require either removing equivalent scope or moving the deadline.
|
||||
|
||||
## 12. Expansion After Phase 1
|
||||
|
||||
1. **Lifecycle and reliability:** cleanup policy, stronger recovery, better extraction and larger evaluation sets.
|
||||
2. **Voice and conversation continuity:** provider-supported transcript capture, reconnect, unified history and safe context restoration.
|
||||
3. **Administration:** model/voice selection, richer roles, SSO and multi-organization operations with validated isolation.
|
||||
4. **Retrieval and scale:** richer search based on measured failures, capacity testing, additional workers and a broker only when operational need justifies it.
|
||||
|
||||
Keep provider calls behind small adapters, reuse one search service, persist stable document/chunk references and use migrations from the beginning. These boundaries support expansion without implementing the full product before the first demonstration.
|
||||
|
||||
## 13. Release Handoff
|
||||
|
||||
Deliver the deployed application, repository release identifier, migration/startup instructions, environment-variable template without secrets, sample corpus and question set, acceptance results, known limitations, and next-phase backlog.
|
||||
|
||||
The parent architecture remains the target design. For Phase 1, this document deliberately narrows model configuration, live history and operational scope. Implementations must not claim those deferred capabilities merely because they appear in the parent document.
|
||||
@@ -0,0 +1,266 @@
|
||||
# RAG Assistant — Phase 1 API Catalog
|
||||
|
||||
Version 1.1 · 2026-10-05 · Proposed application contract; no running endpoints are claimed.
|
||||
|
||||
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-Scenario-Report-FA.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.
|
||||
|
||||
## 1. Transport and common conventions
|
||||
|
||||
Base path `/api/v1`; UTF-8 JSON except multipart upload; same-origin HTTPS. UUIDs identify application records. Timestamps are UTC RFC3339. `null` means unavailable, not an invented source location. Unexpected request fields return 422. Example UUIDs are illustrative.
|
||||
|
||||
Secure HttpOnly `rag_session` cookie authenticates requests. Login and all mutations enforce trusted Origin; authenticated mutations also require `X-CSRF-Token`. `/me` returns a CSRF token for refresh. No frontend persistent provider key, organization ID override or model override is accepted.
|
||||
|
||||
Roles: `admin` and `user`. Both can chat and read their own history/live state. Only admin manages documents, selection and settings. Hidden resource access returns 404. Admin does not implicitly own all conversations.
|
||||
|
||||
Lists use `limit` (default 20, maximum 100) and opaque `cursor`. Stable ordering is `(created_at DESC,id DESC)` except messages, ordered by ascending `sequence_no`. Responses use `{items:[],next_cursor:null}`. Unknown/invalid cursor returns 422. No total count is promised.
|
||||
|
||||
`X-Request-ID` response header and `error.request_id` correlate logs. Servers generate one if none is valid. `Idempotency-Key` is required on upload, manual ingestion retry and delete; UUID `client_request_id` is required in create-conversation, chat and create-live bodies. Keys are scoped to actor/organization and operation as specified below. Reuse with different normalized input returns 409.
|
||||
|
||||
Proposed field limits: text message 8000 characters; assistant name 120; instruction 8000; search query 2000; conversation title 120; document title 200. File limits/formats and SDP byte cap come from deployment configuration and are exposed as capabilities where useful. These are implementation defaults to confirm, not provider guarantees.
|
||||
|
||||
## 2. Endpoint inventory
|
||||
|
||||
| ID | Method and path | Access | Success |
|
||||
| --- | --- | --- | --- |
|
||||
| A01 | POST `/auth/login` | Public, trusted Origin | 200 + cookie |
|
||||
| A02 | POST `/auth/logout` | Authenticated; expired/missing session accepted | 204 |
|
||||
| A03 | GET `/me` | Authenticated | 200 |
|
||||
| D01 | POST `/documents` | Admin | 202 |
|
||||
| D02 | GET `/documents` | Admin | 200 |
|
||||
| D03 | GET `/documents/{document_id}` | Admin | 200 |
|
||||
| D04 | POST `/documents/{document_id}/retry` | Admin | 202 |
|
||||
| D05 | DELETE `/documents/{document_id}?expected_revision=N` | Admin | 202 |
|
||||
| K01 | GET `/knowledge-selection` | Admin | 200 |
|
||||
| K02 | PATCH `/knowledge-selection` | Admin | 200 |
|
||||
| F01 | GET `/configuration` | Authenticated | 200 |
|
||||
| F02 | PATCH `/configuration` | Admin | 200 |
|
||||
| C01 | POST `/conversations` | Authenticated | 201 |
|
||||
| C02 | GET `/conversations` | Owner | 200 |
|
||||
| C03 | GET `/conversations/{conversation_id}/messages` | Owner | 200 |
|
||||
| T01 | POST `/chat` | Owner of text conversation | 200 or 202 |
|
||||
| T02 | GET `/conversations/{conversation_id}/turns/{client_request_id}` | Owner | 200 |
|
||||
| V01 | POST `/voice/sessions` | Owner of voice conversation | 201 or 202 |
|
||||
| V02 | GET `/voice/sessions/{session_id}` | Owner | 200 |
|
||||
| V03 | GET `/voice/sessions/by-request/{client_request_id}` | Owner | 200 |
|
||||
| V04 | POST `/voice/sessions/{session_id}/close` | Owner | 200 |
|
||||
| H01 | GET `/health/live` | Deployment health access | 200 |
|
||||
| H02 | GET `/health/ready` | Deployment health access | 200 or 503 |
|
||||
|
||||
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_documents` is internal and has no public HTTP route.
|
||||
|
||||
## 3. Authentication
|
||||
|
||||
### A01 — Login
|
||||
|
||||
```json
|
||||
{"username":"demo.admin","password":"<password>"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"user":{"id":"01000000-0000-4000-8000-000000000001","username":"demo.admin","role":"admin","organization_id":"02000000-0000-4000-8000-000000000001"},"csrf_token":"<session-csrf-token>","expires_at":"2026-10-05T18:00:00Z"}
|
||||
```
|
||||
|
||||
Credentials invalid: 401 `INVALID_CREDENTIALS`; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login.
|
||||
|
||||
### A02 — Logout
|
||||
|
||||
No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation.
|
||||
|
||||
### A03 — Current identity
|
||||
|
||||
No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 `AUTH_REQUIRED`.
|
||||
|
||||
## 4. Documents and selected knowledge
|
||||
|
||||
### D01 — Upload
|
||||
|
||||
`multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive.
|
||||
|
||||
```json
|
||||
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false}
|
||||
```
|
||||
|
||||
202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header `Idempotency-Replayed: true`. Scope key to organization; hash bytes and normalized title. 413 `FILE_TOO_LARGE`, 415 `UNSUPPORTED_FILE_TYPE`, 422 `INVALID_FILE`, 409 `IDEMPOTENCY_CONFLICT`. A parser failure after acceptance is represented by document status, not a later HTTP response to upload.
|
||||
|
||||
### D02 — List
|
||||
|
||||
Query: common pagination; optional `status=queued|processing|ready|failed`, `is_active=true|false`. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current `knowledge_revision` alongside the list.
|
||||
|
||||
### D03 — Detail / processing polling
|
||||
|
||||
```json
|
||||
{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}
|
||||
```
|
||||
|
||||
`searchable = ready AND active AND not deleted`. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
|
||||
|
||||
### D04 — Retry failed processing
|
||||
|
||||
No body; required `Idempotency-Key`. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice.
|
||||
|
||||
```json
|
||||
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","retry_generation":1}
|
||||
```
|
||||
|
||||
409 `DOCUMENT_NOT_RETRYABLE` for running/ready/permanent failure; 404 hidden/deleted. The retry-key record is retained in audit metadata with a database uniqueness constraint.
|
||||
|
||||
### D05 — Delete
|
||||
|
||||
Required `expected_revision` is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response.
|
||||
|
||||
```json
|
||||
{"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"}
|
||||
```
|
||||
|
||||
202; 409 `REVISION_CONFLICT` on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility.
|
||||
|
||||
### K01 — Get selection
|
||||
|
||||
```json
|
||||
{"revision":1,"access_epoch":1,"document_ids":[]}
|
||||
```
|
||||
|
||||
### K02 — Replace selected set
|
||||
|
||||
This replaces the entire set, not a delta. UI reads current selection before toggling a document.
|
||||
|
||||
```json
|
||||
{"expected_revision":1,"document_ids":["10000000-0000-4000-8000-000000000001"]}
|
||||
```
|
||||
|
||||
```json
|
||||
{"revision":2,"access_epoch":1,"document_ids":["10000000-0000-4000-8000-000000000001"],"conversations_invalidated":false}
|
||||
```
|
||||
|
||||
Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected IDs in details; no partial update. Hidden ID: 404. Stale revision: 409 `REVISION_CONFLICT`. No-op preserves revision. Removing an active ID increments epoch and sets `conversations_invalidated=true`; all older organization conversations become unusable for new turns. After a timeout GET current state instead of blindly repeating with an old revision.
|
||||
|
||||
## 5. Configuration
|
||||
|
||||
### F01 — Read
|
||||
|
||||
```json
|
||||
{"revision":1,"assistant_name":"Organization Assistant","instruction":"پاسخها کوتاه و بر اساس اسناد سازمان باشند.","capabilities":{"text":true,"voice":true,"captions":false,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":null}}
|
||||
```
|
||||
|
||||
Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
|
||||
|
||||
### F02 — Update
|
||||
|
||||
```json
|
||||
{"expected_revision":1,"assistant_name":"HR Assistant","instruction":"فارسی و رسمی پاسخ بده؛ نبود اطلاعات را اعلام کن."}
|
||||
```
|
||||
|
||||
200 returns F01 with incremented revision. Both fields are required; no-op preserves revision. Stale value: 409 `REVISION_CONFLICT`. Text applies on subsequent turns; existing live session keeps its snapshot until restarted. Settings cannot relax system authorization or grounding rules.
|
||||
|
||||
## 6. Conversations and text
|
||||
|
||||
### C01 — Create
|
||||
|
||||
```json
|
||||
{"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"id":"60000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours","status":"active","access_epoch":1,"created_at":"2026-10-05T09:05:00Z"}
|
||||
```
|
||||
|
||||
`mode` is text or voice, never mixed. Title optional. Idempotency scope `(owner,client_request_id)`; same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1.
|
||||
|
||||
### C02 — List own conversations
|
||||
|
||||
Common pagination, optional `mode`. Items use C01 response plus `updated_at`; derive `status=stale` when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role.
|
||||
|
||||
### C03 — Read messages
|
||||
|
||||
Common pagination, ascending sequence. Voice can return no messages because transcripts are not guaranteed. Old text history remains viewable even when stale.
|
||||
|
||||
```json
|
||||
{"conversation_id":"60000000-0000-4000-8000-000000000001","conversation_status":"active","items":[{"id":"70000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","sequence_no":1,"role":"user","content":"پنجشنبه تا چه ساعتی باز هستید؟","created_at":"2026-10-05T09:06:00Z","sources":[]}],"next_cursor":null}
|
||||
```
|
||||
|
||||
Assistant items also expose `turn_status` and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status.
|
||||
|
||||
### T01 — Submit text turn
|
||||
|
||||
```json
|
||||
{"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"پنجشنبه تا چه ساعتی باز هستید؟"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"conversation_id":"60000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","status":"answered","message_id":"70000000-0000-4000-8000-000000000002","answer":"طبق سند ساعات کاری، پنجشنبهها تا ساعت ۱۲ باز هستیم.","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"پنجشنبهها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null},"available":true}],"error":null}
|
||||
```
|
||||
|
||||
200 returns terminal execution: answered, needs_clarification, insufficient_information or failed. `answer`/`message_id` are null on failed, with normalized error. A successfully processed unsupported question uses insufficient_information, human-readable answer and usually empty sources. Failed generation is not reported as a successful answer.
|
||||
|
||||
202 returns a running turn shape with `answer:null`, `message_id:null`, empty sources, `error:null` and `Location` pointing to T02. This occurs on duplicate running request or when the initial response deadline expires while the owned task is still running. Do not start a second task. Client disconnection must not silently create duplicate execution.
|
||||
|
||||
Scope key `(conversation_id,client_request_id)`. Changed message under same key: 409. Another different request while one runs: 409 `CONVERSATION_BUSY`. Wrong mode: 409 `MODE_MISMATCH`. Stale epoch: 409 `CONVERSATION_STALE`. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID.
|
||||
|
||||
### T02 — Recover/poll turn
|
||||
|
||||
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
|
||||
|
||||
## 7. Voice contract — provisional signaling, fixed ownership rules
|
||||
|
||||
The SDP variant below is the target application contract, conditional on Day 1 provider proof. It is not a claim that every Live provider supports it. Freeze a compatible variant before frontend implementation.
|
||||
|
||||
### V01 — Create session
|
||||
|
||||
```json
|
||||
{"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001","sdp_offer":"<browser-generated SDP>"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"session_id":"a0000000-0000-4000-8000-000000000001","conversation_id":"61000000-0000-4000-8000-000000000001","status":"connecting","sdp_answer":"<provider-generated SDP>","expires_at":"2026-10-05T09:30:00Z","poll_url":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"}
|
||||
```
|
||||
|
||||
Conversation must be voice, current epoch and owned by caller. Scope key `(owner,client_request_id)`; hash conversation and SDP. Changed offer under same key is 409. One nonterminal session per conversation. A duplicate during creation returns 202 with session ID/state and null SDP answer, never another provider session. Completed replay returns 201 and the same short-lived answer while still valid. Closed/failed/expired reservations return 409 `LIVE_SESSION_UNUSABLE`; start a fresh request after resolving the old one.
|
||||
|
||||
Persist only encrypted short-lived SDP answer for replay, purge at close/expiry; do not store raw offer or log SDP. Provider creation timeout marks failed/uncertain, never blind automatic recreation. Validate trusted tool-control availability before returning usable signaling. 503 may be used for pre-reservation provider capability failure; a persisted reservation can be inspected with V03.
|
||||
|
||||
### V02 — Poll state and recent retrieved sources
|
||||
|
||||
```json
|
||||
{"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-05T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-05T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"پنجشنبهها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null},"available":true}]}]}
|
||||
```
|
||||
|
||||
Return at most 20 recent tool results in chronological order; clients deduplicate by tool_call_id. This is a bounded status snapshot, not a durable full event stream. Sources are retrieved evidence, not guaranteed spoken citations. Redact excerpts of revoked sources and mark unavailable. State is creating, connecting, connected, closed or failed. UI polling suggested every 2 seconds; terminal state stops polling. No client route can claim a session connected or inject a trusted tool result.
|
||||
|
||||
### V03 — Recover creation by request ID
|
||||
|
||||
200 returns V01 signaling shape while creating/connecting and still eligible; connected/terminal returns state with null SDP answer if replay is no longer useful. Owner-only; 404 if no reservation. This lookup does not create sessions. A client that has lost its peer connection must close/reconcile the old session before starting another, not apply an old SDP answer to a new offer.
|
||||
|
||||
### V04 — Close
|
||||
|
||||
No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Idempotent: already closed/failed returns its existing terminal state. Mark locally closed and attempt provider cleanup; unresolved cleanup is logged and bounded by provider expiry. Revocation/auth expiry/control loss can also terminate sessions; UI displays returned reason.
|
||||
|
||||
## 8. Health
|
||||
|
||||
H01: 200 `{"status":"ok"}` when the process is alive. H02: 200 `{"status":"ready","ingestion":"available"}` or degraded ingestion marker if worker heartbeat is stale; 503 `{"status":"not_ready"}` for required DB/schema/storage failure. Health responses never disclose connection strings or provider keys. Provider outages surface in relevant business operations, not liveness.
|
||||
|
||||
## 9. Error envelope and mapping
|
||||
|
||||
```json
|
||||
{"error":{"code":"REVISION_CONFLICT","message":"Selection changed; reload and try again.","request_id":"req-example","retryable":false,"details":{"current_revision":3}}}
|
||||
```
|
||||
|
||||
| HTTP | Codes / use | Client action |
|
||||
| --- | --- | --- |
|
||||
| 401 | AUTH_REQUIRED, INVALID_CREDENTIALS | Login; do not retry provider work |
|
||||
| 403 | FORBIDDEN, CSRF_INVALID | Show denial or refresh session token |
|
||||
| 404 | NOT_FOUND | Stop; do not expose ownership details |
|
||||
| 409 | REVISION_CONFLICT | Read latest selection/configuration |
|
||||
| 409 | IDEMPOTENCY_CONFLICT | Correct client request/key handling |
|
||||
| 409 | CONVERSATION_BUSY, CONVERSATION_STALE, MODE_MISMATCH | Poll current turn, start fresh conversation, or correct mode |
|
||||
| 409 | DOCUMENT_NOT_READY, DOCUMENT_NOT_RETRYABLE, LIVE_SESSION_UNUSABLE | Follow returned state |
|
||||
| 413/415/422 | FILE_TOO_LARGE, UNSUPPORTED_FILE_TYPE, VALIDATION_ERROR | Correct input |
|
||||
| 429 | RATE_LIMITED | Honor Retry-After; reuse key when retrying same operation |
|
||||
| 503 | DEPENDENCY_UNAVAILABLE | Show service failure; reconcile state before retry |
|
||||
|
||||
Inside persisted failed turns/jobs, normalized codes include PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, SEARCH_FAILED, INVALID_CITATION, PROCESS_INTERRUPTED and CONVERSATION_STALE. An HTTP 200 failed-turn result still represents application failure. Technical retryability does not authorize automatic regeneration under a new key.
|
||||
|
||||
## 10. Frontend implementation order and exclusions
|
||||
|
||||
Build A01/A03 and upload polling first, selection next, then C01/T01/T02/messages, then voice and settings. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context.
|
||||
|
||||
Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses.
|
||||
@@ -0,0 +1,327 @@
|
||||
# RAG Assistant — Phase 1 Database Design
|
||||
|
||||
Version 1.1 · 2026-10-05 · Proposed physical schema and migration specification; not executed migration SQL.
|
||||
|
||||
Companions: `RAG-Phase1-Implementation-Guide.md` and `RAG-Phase1-API-Catalog.md`. Scope: PostgreSQL + pgvector, one organization at launch, durable text history and ingestion jobs, live metadata. No existing database was inspected; compare this proposal with actual migrations before applying it.
|
||||
|
||||
Schema revision 1.1 removes document versioning. The schema now contains 14 tables. Original-file and processing fields are merged into documents; chunks, jobs and citations reference documents directly. Configuration revisions and processing-profile identifiers remain unrelated technical metadata.
|
||||
|
||||
## 1. Conventions
|
||||
|
||||
All IDs are application-generated UUIDs. `uuid PK` means primary key. Timestamps are `timestamptz` in UTC; `created_at` defaults to database now. Unless marked nullable, fields are NOT NULL. JSON defaults are `{}` or `[]` as appropriate. Status fields use text plus CHECK constraints for simple evolution. Hashes use lowercase SHA-256 hex (`char(64)`), except password hashes which use the selected password library's encoded format. Counters use integer/bigint and CHECK >= 0; revisions/sequence numbers start at 1.
|
||||
|
||||
Tables other than settings have a UUID `id` PK. Settings uses `organization_id` as PK. Every organization-owned table has `organization_id uuid` referencing organizations, even where derivable. For all referenced scoped entities add `UNIQUE(organization_id,id)` and use composite scoped foreign keys. This prevents a valid UUID from another organization being attached accidentally. Do not treat UUID unpredictability as access control.
|
||||
|
||||
Use RESTRICT/NO ACTION for normal deletion; no broad CASCADE from users/documents into historical chats. Soft deletion and explicit cleanup control lifecycle. Owners/roles are checked by application queries. Single-organization deployment does not justify dropping organization filtering. Row-level security is deferred, not claimed to be enabled.
|
||||
|
||||
## 2. Relationship overview
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
documents ||--o{ document_chunks : contains
|
||||
documents ||--|| ingestion_jobs : processes
|
||||
conversations ||--o{ turns : contains
|
||||
turns ||--o{ messages : records
|
||||
turns ||--o{ citations : supports
|
||||
conversations ||--o{ live_sessions : hosts
|
||||
turns |o--o{ tool_calls : text_calls
|
||||
live_sessions |o--o{ tool_calls : voice_calls
|
||||
```
|
||||
|
||||
The diagram omits identity/configuration/audit for readability. Each tool call belongs to exactly one text turn OR one live session. A citation also references the exact tool call/evidence that produced its chunk. These relationships are defined below.
|
||||
|
||||
## 3. Identity and organization tables
|
||||
|
||||
### 3.1 organizations
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id | uuid PK | Fixed seeded organization |
|
||||
| name | varchar(200) | Display name |
|
||||
| created_at | timestamptz now | Creation |
|
||||
|
||||
### 3.2 users
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id | uuid | Identity and organization |
|
||||
| username | varchar(120) | Canonical lowercase login name |
|
||||
| password_hash | text | Salted adaptive password hash; never plaintext |
|
||||
| role | text | admin or user |
|
||||
| is_enabled | boolean true | Account authorization |
|
||||
| created_at, updated_at | timestamptz | Audit timestamps |
|
||||
|
||||
Unique username globally for simple login without organization selector. CHECK role. Add UNIQUE(organization_id,id). Disabling a user revokes sessions and closes live sessions; account-management UI is deferred (maintenance command only).
|
||||
|
||||
### 3.3 auth_sessions
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, user_id | uuid | Session owner |
|
||||
| token_hash | char(64) UNIQUE | Hash of opaque cookie token |
|
||||
| created_at, expires_at, last_seen_at | timestamptz | Lifetime |
|
||||
| revoked_at | timestamptz nullable | Explicit revocation |
|
||||
|
||||
Composite FK to users. CHECK expires_at > created_at. Index expires_at for cleanup. Never store raw cookie. Derive CSRF token from raw session cookie using a separate server-side HMAC secret (or an equivalent reviewed synchronizer mechanism); compare in constant time. `/me` can reproduce it without persisting a raw CSRF token.
|
||||
|
||||
### 3.4 organization_settings
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| organization_id | uuid PK/FK | One row per organization |
|
||||
| assistant_name | varchar(120) | UI/model name |
|
||||
| instruction | text | Organization instruction, API length limit |
|
||||
| revision | bigint 1 | Settings optimistic revision |
|
||||
| knowledge_revision | bigint 1 | Selected-set revision |
|
||||
| access_epoch | bigint 1 | Invalidation counter for removals |
|
||||
| updated_by | uuid nullable | Actor; scoped FK to users |
|
||||
| updated_at | timestamptz | Last configuration/selection mutation |
|
||||
|
||||
CHECK all counters >= 1. Selection uses documents.is_active; no assignment table in Phase 1. Lock this row first for selection, context creation and finalization to impose a consistent order.
|
||||
|
||||
## 4. Knowledge tables
|
||||
|
||||
### 4.1 documents
|
||||
|
||||
Each upload is one independent immutable document. This table owns file metadata and processing state directly. There is no document-version table or version-number field. Replacement means a new upload/document ID, followed by active-selection change after readiness. The same idempotent upload replay returns the original ID.
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, uploaded_by | uuid | Identity and admin actor |
|
||||
| title | varchar(200) | Display title |
|
||||
| original_filename | text | Display only, never trusted path |
|
||||
| upload_request_id | uuid | Upload Idempotency-Key |
|
||||
| upload_payload_hash | char(64) | File bytes + normalized metadata digest |
|
||||
| storage_key | text UNIQUE | Generated original-file reference |
|
||||
| file_sha256 | char(64) | Original bytes hash |
|
||||
| mime_type | text | Validated MIME |
|
||||
| size_bytes | bigint | Original size > 0 |
|
||||
| status | text queued | queued, processing, ready, failed |
|
||||
| processing_profile | jsonb | Extractor/chunk/embedding settings |
|
||||
| chunk_count | integer 0 | Published chunk count |
|
||||
| ready_at | timestamptz nullable | Successful publication |
|
||||
| is_active | boolean false | Organization selection |
|
||||
| deleted_at | timestamptz nullable | Soft deletion |
|
||||
| content_purged_at | timestamptz nullable | Explicit future cleanup marker |
|
||||
| created_at, updated_at | timestamptz | Timestamps |
|
||||
|
||||
UNIQUE(organization_id,upload_request_id). Scoped FK uploaded_by→users. CHECK size_bytes > 0, chunk_count >= 0. CHECK ready implies ready_at IS NOT NULL and chunk_count > 0. CHECK is_active implies status='ready', deleted_at IS NULL and content_purged_at IS NULL. Storage keys are generated and unique; no automatic same-hash deduplication between documents.
|
||||
|
||||
Do not overwrite the original bytes or republish a ready document. Manual retry accepts only eligible failed documents; first successful publication fixes the source/chunk identities. If content changes, upload a new independent document. Physical purging must first deactivate the document; retained metadata is a tombstone, never eligible search content.
|
||||
|
||||
Profile example (illustrative values, confirm Day 1):
|
||||
|
||||
```json
|
||||
{"extractor":"approved-parser-v1","chunker":"paragraph-v1","chunk_size":800,"overlap":100,"size_unit":"tokens","embedding":{"provider":"openai","model":"<selected-model>","dimensions":1536,"preprocessing_version":"v1"}}
|
||||
```
|
||||
|
||||
1536 is an example, not a model selection. Deployment must freeze actual dimension D and compatible profile before creating `vector(D)` and indexing. Do not mix equal-length vectors from different models.
|
||||
|
||||
### 4.2 document_chunks
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, document_id | uuid | Source identity |
|
||||
| ordinal | integer | 0-based order |
|
||||
| text | text | Extracted evidence |
|
||||
| location | jsonb | `{page: integer-or-null, section: string-or-null}` |
|
||||
| token_count | integer nullable | Actual tokenizer count if available |
|
||||
| embedding | vector(D) | Model-compatible vector |
|
||||
| created_at | timestamptz | Publication |
|
||||
|
||||
UNIQUE(document_id,ordinal); CHECK ordinal >= 0 and length(text)>0; token_count >= 0 when set. FK document scoped. Page is positive when present. Do not invent a page index for a format without pages.
|
||||
|
||||
Index document_id; initial small-corpus search uses exact cosine distance after eligibility joins. Defer ANN/HNSW until measured latency requires it. If later added, validate filtered-search recall. Example query is parameterized and conceptual (D is a migration parameter):
|
||||
|
||||
```sql
|
||||
SELECT c.id, c.text, c.location, d.id AS document_id,
|
||||
c.embedding <=> CAST(:query_vector AS vector) AS distance
|
||||
FROM document_chunks c
|
||||
JOIN documents d ON d.id = c.document_id AND d.organization_id = c.organization_id
|
||||
WHERE d.organization_id = :organization_id
|
||||
AND d.is_active = true AND d.deleted_at IS NULL
|
||||
AND d.status = 'ready' AND d.content_purged_at IS NULL
|
||||
ORDER BY c.embedding <=> CAST(:query_vector AS vector), c.id
|
||||
LIMIT :top_k;
|
||||
```
|
||||
|
||||
Server validates profile, dimension and bounded top_k before query. A nearest neighbor is not automatically sufficient evidence; no universal distance threshold is assumed.
|
||||
|
||||
### 4.3 ingestion_jobs
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, document_id | uuid | One job per document |
|
||||
| status | text queued | queued, processing, succeeded, failed |
|
||||
| stage | text extract | extract, chunk, embed, publish |
|
||||
| attempt_count | integer 0 | Claims within current retry generation |
|
||||
| retry_generation | integer 0 | Manual retries |
|
||||
| next_attempt_at | timestamptz now | Backoff scheduling |
|
||||
| claim_token | uuid nullable | Fencing token |
|
||||
| lease_expires_at | timestamptz nullable | Worker lease |
|
||||
| claimed_by | text nullable | Worker process identifier |
|
||||
| error_code, error_message | text nullable | Redacted failure |
|
||||
| error_retryable | boolean false | Eligibility hint |
|
||||
| created_at, updated_at | timestamptz | Timestamps |
|
||||
|
||||
UNIQUE(document_id). CHECK processing requires claim_token and lease_expires_at; non-processing clears them. Index `(status,next_attempt_at)` and partial lease expiry for processing. Claim eligible rows with row lock/SKIP LOCKED, regenerate token and increment attempt count. Recovery excludes deleted documents and reclaims expired jobs within retry budget. Final publication locks job and checks token plus lease; an expired worker cannot publish even if its provider call completed. Manual retry uses audit idempotency record and updates this same job atomically.
|
||||
|
||||
## 5. Conversation and evidence tables
|
||||
|
||||
### 5.1 conversations
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, owner_user_id | uuid | Ownership |
|
||||
| client_request_id | uuid | Create idempotency key |
|
||||
| request_hash | char(64) | Normalized create payload |
|
||||
| mode | text | text or voice |
|
||||
| title | varchar(120) nullable | Optional display label |
|
||||
| status | text active | active, stale, closed |
|
||||
| access_epoch | bigint | Knowledge-removal snapshot |
|
||||
| created_at, updated_at | timestamptz | Ordering |
|
||||
|
||||
UNIQUE(owner_user_id,client_request_id). Scoped FK owner. Index owner/created_at/id. Effective status is stale if epoch differs even before explicit row updates; this closes races in invalidation maintenance. Stale/closed history remains read-only.
|
||||
|
||||
### 5.2 turns
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, conversation_id | uuid | Text turn identity |
|
||||
| client_request_id | uuid | Chat retry correlation |
|
||||
| request_hash | char(64) | Conversation/message digest |
|
||||
| status | text running | running, answered, needs_clarification, insufficient_information, failed |
|
||||
| settings_revision, knowledge_revision, access_epoch | bigint | Actual snapshots |
|
||||
| execution_profile | jsonb | Model, actual organization instruction, prompt version, tool schema version and limits |
|
||||
| started_at, deadline_at | timestamptz | Execution timeout |
|
||||
| finished_at | timestamptz nullable | Terminal completion |
|
||||
| error_code, error_message | text nullable | Normalized failure |
|
||||
| error_retryable | boolean false | Technical retry hint |
|
||||
| created_at | timestamptz | Creation |
|
||||
|
||||
UNIQUE(conversation_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status='running'. CHECK terminal iff finished_at is not null; deadline_at > started_at. Scoped FK conversation. Mode=text is an application invariant checked while locking conversation. Message text resides in messages, not duplicated here. Reconstruct API response from messages/citations; replay does not call provider again. Startup/deadline cleanup marks interrupted turns failed.
|
||||
|
||||
### 5.3 messages
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, conversation_id, turn_id | uuid | Ownership and text turn |
|
||||
| sequence_no | bigint | Stable conversation order, >=1 |
|
||||
| role | text | user or assistant |
|
||||
| content | text | Message body |
|
||||
| created_at | timestamptz | Creation |
|
||||
|
||||
UNIQUE(conversation_id,sequence_no), UNIQUE(turn_id,role). Both roles may exist for completed turn; failed turn can have user only. Add UNIQUE(organization_id,conversation_id,id) as needed for matching references. Enforce `(organization_id,conversation_id,turn_id)` FK to a corresponding unique key on turns, not independent FKs that could attach a message to the wrong conversation. Allocate sequence while holding conversation row lock; no model tool/system messages in this table.
|
||||
|
||||
### 5.4 tool_calls
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id | uuid | Identity |
|
||||
| turn_id | uuid nullable | Text parent |
|
||||
| live_session_id | uuid nullable | Voice parent |
|
||||
| external_call_id | text | Provider/orchestrator correlation |
|
||||
| tool_name | text | search_documents only |
|
||||
| arguments | jsonb | Validated query, no trusted scope from model |
|
||||
| request_hash | char(64) | Canonical arguments digest |
|
||||
| status | text running | running, succeeded, failed |
|
||||
| knowledge_revision, access_epoch | bigint | Retrieval snapshots |
|
||||
| result_json | jsonb nullable | Evidence IDs, text, locations or normalized tool error |
|
||||
| error_code | text nullable | Failure |
|
||||
| created_at | timestamptz | Creation |
|
||||
| completed_at | timestamptz nullable | Completion |
|
||||
|
||||
CHECK exactly one parent is non-null. Separate partial unique indexes `(turn_id,external_call_id)` WHERE turn_id IS NOT NULL and `(live_session_id,external_call_id)` WHERE live_session_id IS NOT NULL. Scoped FKs to both parent types. CHECK terminal iff completed_at not null. Duplicate event with same hash reuses result; a different hash is conflict. Duplicate running event waits/polls, never executes twice. Failure/no_evidence distinction is retained in result_json. Evidence payload is sensitive retained content and must be covered by purge policy.
|
||||
|
||||
### 5.5 citations
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, turn_id, tool_call_id | uuid | Answer/evidence correlation |
|
||||
| source_ref | text | S1, S2... unique across all searches within this turn |
|
||||
| document_id, chunk_id | uuid | Stable actual source IDs |
|
||||
| title_snapshot | text | Title at answer time |
|
||||
| location_snapshot | jsonb | Actual source locator |
|
||||
| excerpt | text nullable | Display evidence; cleared if policy requires purge |
|
||||
| created_at | timestamptz | Answer commit |
|
||||
|
||||
UNIQUE(turn_id,source_ref). Scoped FKs for sources plus chain-consistent composite FKs: chunk belongs to the cited document, tool call belongs to the same turn. Add referenced unique keys on these chains. Application verifies source_ref belongs to tool result, not arbitrary model output. No assistant_message_id needed: UNIQUE(turn_id,role) resolves the assistant. Only terminal non-failed answers can have final citations (transaction invariant).
|
||||
|
||||
Keep source identity rows as tombstones if allowed. `available` in API is computed from current access and retention state; revoked source excerpts are not emitted by source endpoints. Old answer prose cannot be retroactively withdrawn and remains owner-visible under history policy. Do not hard-delete referenced chunks through ordinary application DELETE.
|
||||
|
||||
## 6. Live and audit tables
|
||||
|
||||
### 6.1 live_sessions
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, conversation_id, owner_user_id, auth_session_id | uuid | Session ownership and logout correlation |
|
||||
| client_request_id | uuid | Creation correlation |
|
||||
| request_hash | char(64) | Conversation + SDP-offer digest |
|
||||
| provider, model | text | Chosen live profile |
|
||||
| provider_session_id | text nullable | External reference |
|
||||
| status | text creating | creating, connecting, connected, closed, failed |
|
||||
| settings_revision, knowledge_revision, access_epoch | bigint | Creation snapshots |
|
||||
| execution_profile | jsonb | Instruction/prompt profile snapshot |
|
||||
| sdp_answer_ciphertext | bytea nullable | Short-lived encrypted replay material |
|
||||
| expires_at, created_at, updated_at | timestamptz | TTL/lifecycle |
|
||||
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
|
||||
| close_reason, error_code | text nullable | Normalized reason |
|
||||
|
||||
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set and sdp_answer_ciphertext cleared. Store no raw SDP offer or audio. Provider credentials are server configuration, never database plaintext. Encryption key is outside database.
|
||||
|
||||
API instance owns live control in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript.
|
||||
|
||||
### 6.2 audit_events
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, actor_user_id | uuid (actor nullable) | Administrator/system action |
|
||||
| action | text | upload, selection_changed, document_deleted, ingestion_retry, configuration_changed, session_revoked |
|
||||
| target_id | uuid nullable | Referenced object; polymorphic diagnostic field |
|
||||
| request_id | text nullable | HTTP tracing |
|
||||
| idempotency_key | uuid nullable | Delete/retry idempotency |
|
||||
| request_hash | char(64) nullable | Mutation payload hash |
|
||||
| response_json | jsonb nullable | Replay of delete/retry outcome |
|
||||
| metadata | jsonb | Changed IDs/revisions, redacted reason |
|
||||
| created_at | timestamptz | Event time |
|
||||
|
||||
Partial UNIQUE(organization_id,actor_user_id,action,target_id,idempotency_key) WHERE idempotency_key IS NOT NULL. Delete/retry APIs require non-null actor and target. Insert audit replay record in SAME transaction as the mutation. Concurrent unique conflict reloads committed response. Preserve these records for the supported retry window; no cleanup duration is assumed. Avoid document text/secrets in audit metadata.
|
||||
|
||||
## 7. Transaction boundaries and invariant enforcement
|
||||
|
||||
| Operation | One database transaction | Outside transaction |
|
||||
| --- | --- | --- |
|
||||
| Upload | Document + job + audit | File staging/write; reconcile orphans |
|
||||
| Claim | Row lock, new token/lease, attempt increment | Extraction and provider calls |
|
||||
| Publish | Lock document/job; verify token/lease; replace chunks; ready/succeeded | Already prepared embeddings |
|
||||
| Selection | Settings lock, expected revision, active flags, revision/epoch, stale conversations, audit | Best-effort closing provider sessions after logical invalidation |
|
||||
| Chat admission | Settings/conversation locks, request lookup, turn + user message | Provider inference/tool loop |
|
||||
| Chat completion | Settings/conversation locks, epoch validation, assistant + citations + terminal status | Browser delivery after commit |
|
||||
| Live create | Reservation/idempotency/ownership first; state update after provider | Provider creation and trusted control |
|
||||
| Delete/retry | State change + unique audit replay result | Physical cleanup or future worker execution |
|
||||
|
||||
Use consistent lock order where resources overlap: organization settings → conversation or document → job or turn/session. Do not hold settings lock during remote calls. Publication does not acquire settings after a document lock; it leaves selection unchanged. Retry/publish paths lock document then job to avoid inversion. Claims lock only jobs and commit quickly.
|
||||
|
||||
On active-document removal: database epoch invalidation is authoritative immediately for new operations. After transaction, notify/close provider sessions and discard stale pending evidence. Cannot recall previously delivered live audio. Session close failure remains observable and bounded by TTL; it is not represented as guaranteed erasure at the provider.
|
||||
|
||||
## 8. Migration plan
|
||||
|
||||
| Migration | Content | Gate |
|
||||
| --- | --- | --- |
|
||||
| 001_identity | organizations, users, auth_sessions, settings | Seed one org and admin/user securely |
|
||||
| 002_knowledge | documents, jobs; enable vector extension; chunks with confirmed D | Real embedding profile dimension fixed |
|
||||
| 003_conversations | conversations, turns, messages, live_sessions, tool_calls, citations | Ownership/chain constraints and partial unique indexes checked |
|
||||
| 004_audit_indexes | audit_events and remaining query indexes | Upload/delete/retry transaction tests |
|
||||
|
||||
For a database already created from revision 1.0: first verify that each document has exactly one content row, copy its file/status/profile fields to documents, backfill direct document references for chunks/jobs/citations, validate counts and constraints, and only then remove the legacy content-version table/columns. Preserve document and chunk IDs. If more than one content row exists per document, stop and design an explicit data migration; do not silently discard rows. No migration has been run as part of this documentation edit.
|
||||
|
||||
These can be combined while no deployment exists; once applied, use new migrations rather than editing history. Create tables in FK dependency order (live_sessions before tool_calls; tool_calls before citations). Migration rollback that drops content is destructive; prefer forward fixes after data exists. Confirm extension privileges and back up before real deployment changes.
|
||||
|
||||
## 9. Essential database validation
|
||||
|
||||
Test: cross-org FK rejection; one running turn/session under concurrency; duplicate request hash conflict; same upload replay; stale worker publication; manual retry once per key; ready/active filtering; epoch race during answer finalization; deletion tombstone with old citation; matching document/chunk source chain; restart interruption states. The schema above is a reviewable design, not evidence that these tests have passed.
|
||||
|
||||
## 10. Deliberately absent from Phase 1
|
||||
|
||||
No per-organization vector database, message broker tables, raw audio blobs, arbitrary tool schema registry, retention scheduler, multi-version assignment workflow or model catalogue. Full document bodies are in file storage/chunks; original files and recordings are not PostgreSQL byte arrays. Keep no production capacity or retention claim until stakeholders supply those requirements.
|
||||
@@ -0,0 +1,152 @@
|
||||
# RAG Assistant — Phase 1 Implementation Guide
|
||||
|
||||
Version 1.1 · 2026-10-05 · Proposed implementation contract, not an implementation-completion report.
|
||||
|
||||
## 1. Purpose and authority
|
||||
|
||||
Implement the 7–10 day release described in `RAG-AI-Phase1-Delivery-Plan.md`. Use `RAG-Phase1-API-Catalog.md` for HTTP contracts and `RAG-Phase1-Database-Design.md` for persistence. `RAG-Phase1-Scenario-Report-FA.md` explains the same design through scenarios. These companion documents refine the delivery plan; they do not expand the release to the full parent architecture.
|
||||
|
||||
Assumptions: one primary developer, one organization, pre-created admin/user accounts, one backend instance, one ingestion worker, one PostgreSQL database with pgvector and persistent file storage. Reuse working application/UI components after inspection. No source repository was inspected in preparing this package, and no application or migration was executed.
|
||||
|
||||
## 2. Decisions for this implementation
|
||||
|
||||
| Topic | Phase 1 decision |
|
||||
| --- | --- |
|
||||
| Backend | FastAPI modular monolith; worker entry point in the same codebase |
|
||||
| UI delivery | Same-origin HTTPS UI and API; four screens from the phase plan |
|
||||
| Identity | Opaque server-side cookie sessions; admin/user roles; no signup |
|
||||
| Jobs | PostgreSQL polling, lease and fenced publication; no Redis/broker |
|
||||
| Text | Non-streaming JSON answer; durable turn status for timeout recovery |
|
||||
| Agent | Retain existing orchestration if usable; do not add a framework only for this release |
|
||||
| Voice | Browser/provider WebRTC; trusted server-side control and shared search; validate provider compatibility on Day 1 |
|
||||
| Live UI updates | Poll application session state and recent tool evidence; SSE and durable captions deferred |
|
||||
| Knowledge selection | Full selected-document ID set with optimistic revision; accessed through Documents UI |
|
||||
| Document identity | No document versioning; every upload creates an independent immutable document |
|
||||
| Retrieval | Exact semantic search initially; vector acceleration only after measurement |
|
||||
| History | Durable text; live session/tool diagnostics only |
|
||||
| Models | Fixed server profiles; text/embedding from planned OpenAI integration; live provider remains a Day 1 choice |
|
||||
|
||||
## 3. Modules and ports
|
||||
|
||||
| Module / suggested path | Responsibility | Allowed dependencies |
|
||||
| --- | --- | --- |
|
||||
| `app/api/v1/` | Transport DTOs, cookies, CSRF, HTTP error mapping | Application services |
|
||||
| `modules/identity/` | Login, sessions, actor context | Users/session repository, password verifier |
|
||||
| `modules/documents/` | Upload, status, selection, delete/retry | FileStore, document/job repository |
|
||||
| `modules/knowledge/` | Search and evidence validation | EmbeddingProvider, knowledge repository |
|
||||
| `modules/conversations/` | Turns, history, agent loop, citations | TextModel, search service, conversation repository |
|
||||
| `modules/live/` | Signaling, control, tool dispatch, close/poll | LiveProvider, shared search, live repository |
|
||||
| `modules/configuration/` | Assistant name/instruction and revisions | Settings repository |
|
||||
| `infrastructure/` | SQLAlchemy, file I/O, provider clients, job claiming | Domain/application ports |
|
||||
| `app/worker.py` | Claim and execute ingestion jobs | Document processing service |
|
||||
|
||||
Keep interfaces small: `TextModel.run_turn`, `EmbeddingProvider.embed`, `LiveProvider.create/control/close`, `FileStore.put/read`, and `KnowledgeRepository.search`. Their precise SDK calls depend on selected providers. Application services must not import provider-native response objects. The provider model emits a tool call; the dispatcher validates it; the search service queries storage. Models never receive SQL/database credentials.
|
||||
|
||||
## 4. Implementation order and deliverables
|
||||
|
||||
| Day | Build | Concrete exit condition |
|
||||
| --- | --- | --- |
|
||||
| 1 | Inspect reusable code; sample files; real voice/tool spike; freeze formats and live signaling | A real browser voice session causes one trusted backend tool execution |
|
||||
| 2 | Database migrations, seed accounts, auth, upload, minimal deployment | Login and stored upload survive restart |
|
||||
| 3 | Extractor, chunking, embedding, durable worker | Ready document and clear unreadable-file failure |
|
||||
| 4 | Shared search, selection revision, scope checks | Selected ready chunks returned with source identities |
|
||||
| 5 | Conversations, turns, agent loop, citations, recovery | Text question returns evidence-based answer; retry cannot duplicate a turn |
|
||||
| 6 | Live adapter connected to real search | Spoken document question answered; disconnect/close visible |
|
||||
| 7 | Four screens, settings, deployed scenario | Demo on intended HTTPS environment; feature freeze |
|
||||
| 8–10 | Quality evaluation, defect fixes, failure checks, rehearsal | Acceptance evidence and reproducible release |
|
||||
|
||||
Complete meaningful checks during development, not only after Day 7. A provider delay or unextractable corpus changes the estimate; resolve it early. Do not silently drop voice to claim this plan was delivered.
|
||||
|
||||
## 5. Identity and request context
|
||||
|
||||
Login verifies a stored password hash using a maintained password-hashing implementation. Generate an unpredictable session token; store only its hash. Cookie `rag_session` is HttpOnly, Secure and SameSite=Lax. Restrict Origin on login and mutations. Return a session CSRF token after login and through `/me`; require `X-CSRF-Token` on authenticated mutations. Configure session expiry at deployment; no business retention period is assumed here.
|
||||
|
||||
Resolve `(user_id, organization_id, role)` exclusively from the session. Check owner for conversation/turn/live endpoints, including administrator requests: admin status does not automatically grant access to other users' chats. Return 404 for hidden resource IDs, 403 for an authenticated non-admin calling an admin-only collection operation. Rate-limit login/provider operations with conservative single-instance limits.
|
||||
|
||||
## 6. Document upload and ingestion
|
||||
|
||||
1. Validate admin access, idempotency key, size, approved MIME/signature and safe display filename.
|
||||
2. Hash file bytes and normalized metadata. Write original to a generated storage key using temporary storage then atomic move where supported. Never use user filenames as paths.
|
||||
3. In a short transaction create document and queued job. A unique organization/upload key detects repeated upload; changed payload under the same key returns 409. Clean unused staged bytes on replay.
|
||||
4. Worker claims a queued eligible job or expired processing job with a fresh token and lease. Increment attempts. Extract, normalize and chunk outside a long transaction.
|
||||
5. Preserve headings and available page/section positions. Empty extraction is failure. Unsupported scans/tables must not look successfully indexed.
|
||||
6. Build embeddings with the configured profile. Stage vectors in worker memory for the bounded corpus, or temporary non-queryable storage if necessary.
|
||||
7. In one transaction lock document/job, verify claim token and non-expired lease, recheck non-deletion, publish that document's chunks, mark document ready and job succeeded. Document remains inactive until selected.
|
||||
|
||||
In Phase 1, rerun the whole pipeline after a crash instead of building checkpoint orchestration. Uniqueness on `(document_id, ordinal)` and a single final publication transaction prevent duplicates. Heartbeat during long provider calls; a worker that loses its claim must discard its result.
|
||||
|
||||
For transient network/rate-limit errors, schedule bounded exponential backoff with jitter using `next_attempt_at`; after configured attempts, mark failed. For invalid input, fail immediately. Manual retry requeues the same job, resets attempt budget and increments `retry_generation`; audit the action. It does not change original file bytes.
|
||||
|
||||
Database and files are not one transaction. A maintenance command reports orphan file keys and missing originals; safe cleanup uses a grace interval. Soft deletion is immediate retrieval exclusion. Physical content purging awaits an explicit retention policy.
|
||||
|
||||
## 7. Selection, revisions and revocation
|
||||
|
||||
`organization_settings` has three counters: `revision` for assistant configuration, `knowledge_revision` for selected-set changes, and `access_epoch` for knowledge removals. All begin at 1.
|
||||
|
||||
Selection update locks the settings row, checks `expected_revision` against `knowledge_revision`, validates every selected document is ready/not deleted, and updates the selected flags atomically. If the set changes, increment `knowledge_revision`. If any document is removed, increment `access_epoch` too. A no-op preserves counters. Activation alone does not invalidate old conversations; new turns use the current selected set.
|
||||
|
||||
Each conversation records `access_epoch` on creation. For simple safe Phase 1 revocation, any active-document removal invalidates ALL older organization conversations for new turns. Close running live sessions and fail/stop running text turns; preserve old history for authorized viewing. UI asks the user to start a new conversation. No full history is copied into it.
|
||||
|
||||
Use settings-row serialization when creating/finalizing turns and initiating live sessions. Text finalization rechecks epoch while holding that row lock; commits before a removal are historical answers, and commits after it must fail as stale. Live tool results are rechecked before sending. Direct audio already sent cannot be recalled; provider close is best effort and must be tested. Logout and session expiry also close owned active live sessions.
|
||||
|
||||
## 8. Text turn execution
|
||||
|
||||
The UI creates a `mode=text` conversation, then sends `POST /chat` with a UUID `client_request_id`.
|
||||
|
||||
In a short transaction: authenticate, lock settings/conversation consistently, verify active conversation/current epoch, resolve the request key, reject another running turn, insert running turn and user message. Set a processing deadline. Then release database locks before provider calls.
|
||||
|
||||
Build model context from completed authorized turns within the token budget. Add assistant instruction, tool schema and current question. Treat document text as untrusted evidence, not instructions. A search query argument contains only query text; the server determines organization and selection.
|
||||
|
||||
Loop within configured tool-call and time limits. Store normalized tool results and correlate call IDs. Assign source references uniquely across the entire text turn (not separately as S1 for every search); remap tool evidence before returning it to the model. Persist the actual organization instruction in the execution snapshot so a later settings change does not destroy traceability. For substantive document claims, require current search evidence. Validate each cited source against evidence returned during this turn. Structural validation does not prove semantic accuracy; the reference evaluation set checks factual support.
|
||||
|
||||
At completion recheck epoch, write assistant message/citations and terminal turn status in one transaction. Terminal statuses: `answered`, `needs_clarification`, `insufficient_information`, `failed`. Search/provider errors produce `failed`, not `insufficient_information`.
|
||||
|
||||
If the browser times out, it queries the turn by client request ID. Retrying the same payload returns the existing result or 202 running state. Same key plus different payload returns 409. No automatic regeneration after an ambiguous provider timeout. An interrupted run is marked failed; a new user retry uses a new key. On API restart mark its interrupted running turns failed; periodic deadline cleanup handles stalled tasks. This is intentionally simpler than a durable text job queue.
|
||||
|
||||
## 9. Live lifecycle
|
||||
|
||||
Create a fresh `mode=voice` conversation. Proposed signaling is an SDP-offer request and SDP-answer response via backend. This shape is provisional until the Day 1 integration proves provider support; if credential-based signaling is required, revise the live API section before frontend freeze.
|
||||
|
||||
Persist a `creating` session reservation and request hash before calling the provider. Establish server control and install approved tools/instructions before returning the answer. An SDP answer means signaling is ready, not that audio is connected. State becomes connected only on trusted provider/adapter confirmation.
|
||||
|
||||
Route each tool event to the SAME search service with session owner and current epoch. Deduplicate by provider call ID and return the same result for duplicates; conflicting payloads fail. Persist recent tool evidence for UI polling. Live transcripts/captions are not required durable records.
|
||||
|
||||
States: `creating → connecting → connected → closed`; any nonterminal state can become `failed` or `closed`. Connection/control timeout closes provider resources. Browser can start a new session after failure, not automatically replay old signaling. On process restart, mark previously nonterminal sessions failed and attempt provider cleanup. One active live session per conversation; use configured session TTL to bound abandoned sessions.
|
||||
|
||||
## 10. Internal search contract
|
||||
|
||||
```json
|
||||
{"name":"search_documents","arguments":{"query":"ساعت کاری پنجشنبه"}}
|
||||
```
|
||||
|
||||
Only `query` is model-supplied. Reject extra scope fields. Proposed limit: 1–2000 characters. Server defaults for this demo: top 5 chunks and maximum 12000 evidence characters; tune using the corpus, not as a quality guarantee.
|
||||
|
||||
```json
|
||||
{"status":"ok","knowledge_revision":2,"sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","text":"پنجشنبهها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null}}]}
|
||||
```
|
||||
|
||||
Empty evidence: `status=no_evidence`, empty sources. Failure: `status=error` with normalized error code/retryability, never a fake empty-success result. Returned text must pass a final active/document/epoch check. Retrieval scope is ready active undeleted organization documents only. Use the same embedding profile for query and corpus. A new embedding profile requires reindexing; Phase 1 has no UI for it.
|
||||
|
||||
## 11. Deployment and configuration
|
||||
|
||||
Deploy UI/reverse proxy, one API process, one worker process and PostgreSQL. Mount persistent originals and database volumes. Configure HTTPS, cookie domain/origin, provider secrets, approved file formats, size cap, model profile IDs, embedding dimension, tool limits, request deadlines, job lease/retry budget and session TTL. Do not commit secrets. File-size/retention/session durations are deployment choices, not silently approved organization policy.
|
||||
|
||||
Readiness checks DB/schema/vector availability and writable/available required storage; report worker heartbeat age as a degraded ingestion indicator. For the single-host release, the worker can update a small heartbeat file on the shared durable volume; a separate heartbeat table is unnecessary. Liveness does not call AI providers. Provider failure must not make login/history unavailable by design. Log request/turn/job/session IDs and redacted error categories; avoid document bodies, SDP, prompts, cookies and keys.
|
||||
|
||||
## 12. Tests and handoff
|
||||
|
||||
| Test group | Required evidence |
|
||||
| --- | --- |
|
||||
| Access | User cannot mutate docs/settings or read another conversation; forged organization IDs ineffective |
|
||||
| Ingestion | Empty extraction fails; crash/lease expiry recovered; stale claim cannot publish |
|
||||
| Selection | Atomic revision conflict, inactive exclusion, revocation invalidates old context |
|
||||
| Turns | Same-key replay, changed-payload conflict, concurrent-turn rejection and timeout lookup |
|
||||
| Grounding | Answerable, absent, ambiguous and follow-up questions against curated evidence |
|
||||
| Voice | Real WebRTC plus real tool call, provider/control loss, close, epoch revocation |
|
||||
| Persistence | Restart preserves history and recovers jobs; active voice/text interruption is explicit |
|
||||
|
||||
Map results to P1-01 through P1-12 in the delivery plan. Hand off startup/migration/seed commands, secret-free environment example, API examples, known limitations, reference questions, release revision and actual test results. Do not report these tests as passed until implementation runs them.
|
||||
|
||||
## 13. Decisions still requiring confirmation
|
||||
|
||||
File formats and limits; text/embedding/live model identifiers; vector dimension; actual live signaling/control capabilities; hosting and provider reachability; account/session/retention policy; final quality threshold and delivery date. Technical defaults above are proposals to make work concrete, not assertions of client approval.
|
||||
@@ -0,0 +1,256 @@
|
||||
# گزارش فاز یک دستیار اسناد سازمان — پیادهسازی، API و دیتابیس با سناریو
|
||||
|
||||
نسخه ۱.۱ — تاریخ ۲۰۲۶/۱۰/۰۵
|
||||
|
||||
این گزارش طراحی پیشنهادی پیادهسازی است؛ به معنی ساختهشدن برنامه، اجرای مایگریشن یا موفقیت تستها نیست. بازه تحویل همان ۷ تا ۱۰ روز و فرض ظرفیت، یک توسعهدهنده اصلی است.
|
||||
|
||||
## ۱. این مجموعه سند دقیقاً چه چیزی تحویل میدهد؟
|
||||
|
||||
| سند | کاربرد |
|
||||
| --- | --- |
|
||||
| `RAG-Phase1-Implementation-Guide.md` | توسعهدهنده بداند چه ماژولهایی بسازد، ترتیب کار چیست و هر جریان چگونه اجرا شود |
|
||||
| `RAG-Phase1-API-Catalog.md` | فرانت و بکاند روی آدرسها، ورودی، خروجی، دسترسی، وضعیت و خطا توافق کنند |
|
||||
| `RAG-Phase1-Database-Design.md` | جداول، ستونها، ارتباطها، محدودیتها و ترتیب مایگریشن مشخص باشند |
|
||||
| همین گزارش | جریان محصول و ارتباط API، منطق و دیتابیس با مثال قابل فهم باشد |
|
||||
|
||||
مبنای محدوده، `RAG-AI-Phase1-Delivery-Plan.md` است. سند معماری اصلی مسیر محصول کامل را نگه میدارد؛ امکاناتی که آنجا آمدهاند الزاماً در فاز یک پیاده نمیشوند.
|
||||
|
||||
سه سند فنی انگلیسیاند تا برای داکیومنت پروژه و توسعه قابل استفاده باشند. این گزارش فارسی است. قراردادهای تازه مثل روش احراز هویت و جزئیات جدولها، پیشنهاد فنی مشخص برای شروعاند و تأیید قبلی کارفرما فرض نشده است.
|
||||
|
||||
## ۲. محصولی که در پایان فاز یک نشان میدهیم
|
||||
|
||||
مدیر وارد سامانه میشود، سند سازمان را آپلود میکند، آمادهشدن آن را میبیند و فعالش میکند. کاربر از طریق متن یا صوت سؤال میپرسد. مدل تصمیم میگیرد ابزار سرچ را اجرا کند؛ بکاند شواهد را از اسناد فعال پیدا میکند و مدل بر اساس آن پاسخ میدهد.
|
||||
|
||||
چهار صفحه داریم: ورود، گفتگو، اسناد و تنظیمات. در تنظیمات فقط نام و دستورالعمل دستیار تغییر میکند. انتخاب اسناد در صفحه اسناد است. مدلها از تنظیمات سرور تعیین میشوند. مدیریت مدل، نسخهبندی خودکار سند، OCR عمومی، SSO، ثبتنام و تاریخچه کامل صوتی به این تحویل اضافه نشدهاند.
|
||||
|
||||
تصمیم سادهسازی: جدول نسخهها حذف شده است. هر آپلود یک سند مستقل میسازد؛ قطعات و کار پردازش مستقیم به آن متصلاند. برای اصلاح محتوا، فایل جدید آپلود و پس از آمادهشدن جای سند فعال قبلی انتخاب میشود. Retry همان سند را دوباره پردازش میکند و سند تازه نمیسازد. تعداد جدولها اکنون ۱۴ است.
|
||||
|
||||
## ۳. تقسیم کار سیستم با زبان ساده
|
||||
|
||||
| جزء | کار واقعی |
|
||||
| --- | --- |
|
||||
| مرورگر | فرمها، نمایش چت و منابع، میکروفون و پخش صوت |
|
||||
| API | دریافت درخواست، بررسی هویت و دسترسی و برگرداندن نتیجه |
|
||||
| سرویس گفتگو | اجرای نوبت متنی، نگهداری سابقه و مدیریت درخواست تکراری |
|
||||
| مدل | تشخیص نیاز به سرچ و تولید پاسخ با شواهد |
|
||||
| ابزار سرچ | اجرای جستوجو در اسناد آماده و فعال؛ مدل SQL اجرا نمیکند |
|
||||
| Worker | استخراج متن و ساخت قطعات و Embedding در پسزمینه |
|
||||
| PostgreSQL + pgvector | کاربران، اسناد، کارها، بردارها، گفتگوها و وضعیتها |
|
||||
| مخزن فایل | نگهداری فایل اصلی آپلودشده |
|
||||
| کنترلکننده Live | ساخت و بستن جلسه صوتی و اجرای ابزارها در بکاند |
|
||||
|
||||
همه ماژولهای بکاند در یک کدبیساند. Worker یک فرایند جدا از API است تا پردازش فایل، پاسخگویی UI را معطل نکند. صف کارها همان جدول دیتابیس است و در این فاز Redis یا RabbitMQ لازم نشده است.
|
||||
|
||||
## ۴. سناریو اول: مدیر سند ساعات کاری را آپلود میکند
|
||||
|
||||
فرض کنیم فرمت فایل نمونه در روز اول تأیید شده و متن آن قابل استخراج است. سند میگوید: «پنجشنبهها از ساعت ۸ تا ۱۲».
|
||||
|
||||
| قدم | درخواست یا رفتار | اتفاق در دیتابیس | نتیجه UI |
|
||||
| --- | --- | --- | --- |
|
||||
| ۱ | `POST /api/v1/auth/login` | نشست احراز هویت در `auth_sessions` | ورود موفق |
|
||||
| ۲ | `POST /api/v1/documents` با فایل | یک سند مستقل در `documents` و کار متصل به همان سند در `ingestion_jobs` ساخته میشود | «در صف پردازش» |
|
||||
| ۳ | Worker کار را میگیرد | وضعیت job و سند processing میشود | «در حال پردازش» |
|
||||
| ۴ | استخراج، قطعهبندی و Embedding | هنوز قطعات ناقص وارد سرچ نمیشوند | کاربر منتظر وضعیت آماده میماند |
|
||||
| ۵ | انتشار موفق | قطعات در `document_chunks`؛ سند ready؛ job succeeded | «آماده، غیرفعال» |
|
||||
| ۶ | مدیر فعال میکند | مجموعه انتخابشده با `PATCH /knowledge-selection` تغییر میکند | «فعال برای پاسخگویی» |
|
||||
|
||||
آپلود پاسخ ۲۰۲ میدهد؛ یعنی فایل و کار پردازش ثبت شدهاند، نه اینکه مدل همان لحظه آن را میشناسد. فرانت با `GET /documents/{id}` وضعیت را میخواند.
|
||||
|
||||
سند آماده ولی غیرفعال قابل سرچ نیست. این دو وضعیت مستقلاند: یکی میگوید پردازش انجام شده، دیگری میگوید سازمان اجازه استفاده داده است.
|
||||
|
||||
اگر فایل تصویر اسکنشده باشد و OCR در فرمتهای تأییدشده نباشد، وضعیت failed با توضیح قابل فهم نمایش داده میشود. سند خالی به عنوان «آماده» ثبت نمیشود.
|
||||
|
||||
## ۵. سناریو دوم: کاربر متنی سؤال میپرسد
|
||||
|
||||
کاربر مینویسد: «پنجشنبه تا چه ساعتی باز هستید؟»
|
||||
|
||||
۱. فرانت با `POST /conversations` یک گفتگوی text میسازد.
|
||||
۲. سؤال را همراه `conversation_id` و `client_request_id` به `POST /chat` میدهد.
|
||||
۳. بکاند یک `turn` به معنی «یک نوبت سؤال و پاسخ» ثبت میکند. سؤال کاربر در `messages` ذخیره میشود.
|
||||
۴. مدل میبیند برای پاسخ به اطلاعات سازمان نیاز دارد و ابزار `search_documents` را با کوئری «ساعت کاری پنجشنبه» صدا میزند.
|
||||
۵. ابزار هویت سازمان را از نشست معتبر میگیرد؛ خود مدل نمیتواند سازمان یا اسناد مجاز را عوض کند.
|
||||
۶. سؤال به بردار تبدیل میشود و قطعات مرتبط از اسناد آماده و فعال پیدا میشوند.
|
||||
۷. متن قطعه، شناسه سند و قطعه و محل منبع به مدل برمیگردد.
|
||||
۸. مدل پاسخ میدهد: «طبق سند ساعات کاری، پنجشنبهها تا ساعت ۱۲ باز هستیم.»
|
||||
۹. پاسخ در `messages` و ارجاع آن در `citations` ذخیره میشود؛ turn به answered میرسد.
|
||||
۱۰. UI پاسخ و منبع را نمایش میدهد.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as User
|
||||
participant B as Backend
|
||||
participant M as AI Model
|
||||
participant S as Search Tool
|
||||
participant D as Database
|
||||
U->>B: Text question
|
||||
B->>D: Save running turn
|
||||
B->>M: Question and tool schema
|
||||
M->>B: Search tool call
|
||||
B->>S: Execute authorized search
|
||||
S->>D: Retrieve selected ready chunks
|
||||
D-->>S: Evidence
|
||||
S-->>B: Content and sources
|
||||
B->>M: Tool result
|
||||
M-->>B: Grounded answer
|
||||
B->>D: Save answer and citations
|
||||
B-->>U: Answer and sources
|
||||
```
|
||||
|
||||
ایجنتیک بودن همین است: برای «سلام» لازم نیست سرچ انجام شود، اما برای ادعای مربوط به سند سازمان شواهد لازم است. ابزار جواب نهایی را تولید نمیکند؛ اطلاعات لازم را میآورد.
|
||||
|
||||
## ۶. سناریو سوم: اطلاعات پیدا نمیشود یا سؤال مبهم است
|
||||
|
||||
| سؤال/وضعیت | رفتار درست | وضعیت نوبت |
|
||||
| --- | --- | --- |
|
||||
| «پنجشنبه تا چند باز هستید؟» و سند مربوط موجود است | پاسخ مستند | answered |
|
||||
| «اون روز تا چند باز هستید؟» بدون زمینه کافی | «منظورتان کدام روز است؟» | needs_clarification |
|
||||
| «مبلغ پاداش امسال چقدره؟» و سندی درباره آن نیست | اعلام نبود اطلاعات در اسناد | insufficient_information |
|
||||
| سرویس Embedding قطع است | اعلام مشکل سرویس؛ نه ادعای نبود اطلاعات | failed |
|
||||
|
||||
تفاوت دو ردیف آخر مهم است: «جستوجو انجام شد و مدرک نبود» با «جستوجو نتوانست اجرا شود» یکی نیست. API و دیتابیس این تفاوت را حفظ میکنند تا UI پیام اشتباه نشان ندهد.
|
||||
|
||||
## ۷. سناریو چهارم: کاربر دوبار ارسال میزند یا پاسخ HTTP گم میشود
|
||||
|
||||
فرض کنیم سؤال ثبت شده و مدل در حال پاسخ است، ولی اینترنت مرورگر برای لحظهای قطع میشود.
|
||||
|
||||
فرانت نباید فوراً یک سؤال جدید با شناسه جدید بسازد. همان `client_request_id` را نگه میدارد و از این مسیر وضعیت را میپرسد:
|
||||
|
||||
`GET /api/v1/conversations/{conversation_id}/turns/{client_request_id}`
|
||||
|
||||
- اگر running باشد، منتظر میماند.
|
||||
- اگر answered باشد، همان جواب ثبتشده را نمایش میدهد.
|
||||
- اگر failed باشد، خطا را نشان میدهد؛ تلاش جدید آگاهانه با شناسه جدید انجام میشود.
|
||||
- اگر هنوز رکورد ثبت نشده باشد، همان درخواست و همان شناسه را دوباره میفرستد.
|
||||
|
||||
در دیتابیس ترکیب گفتگوی مشخص و شناسه درخواست یکتا است. بنابراین دو بار ارسال یک درخواست، دو نوبت مستقل نمیسازد. این همان کاربرد عملی Idempotency است.
|
||||
|
||||
اگر سؤال با همان شناسه عوض شود، ۴۰۹ میگیریم؛ این خطای برنامه فرانت است. اگر در یک گفتگو یک نوبت در حال اجرا باشد و سؤال جدید با شناسه دیگر برسد، `CONVERSATION_BUSY` برمیگردد. در فاز یک نوبتهای یک گفتگو همزمان اجرا نمیشوند.
|
||||
|
||||
## ۸. سناریو پنجم: کاربر صوتی سؤال میپرسد
|
||||
|
||||
۱. کاربر دکمه شروع مکالمه را میزند و دسترسی میکروفون میدهد.
|
||||
۲. یک گفتگوی voice ساخته میشود.
|
||||
۳. مرورگر اطلاعات برقراری WebRTC را به `POST /voice/sessions` میدهد.
|
||||
۴. بکاند جلسه مدل Live و کانال کنترل معتبر را آماده میکند.
|
||||
۵. پاسخ اتصال به مرورگر میرسد؛ صوت مستقیم میان مرورگر و ارائهدهنده منتقل میشود.
|
||||
۶. کاربر میگوید: «پنجشنبه تا چند باز هستید؟»
|
||||
۷. مدل Live ابزار سرچ را درخواست میکند؛ بکاند همان سرویس سرچ متن را اجرا میکند.
|
||||
۸. شواهد به مدل Live میرسند و مدل پاسخ صوتی میدهد.
|
||||
۹. UI از وضعیت جلسه و نتایج اخیر ابزار، منابع بازیابیشده را نشان میدهد.
|
||||
|
||||
**صوت از API ما عبور نمیکند؛ ولی جستوجو و کنترل دسترسی از بکاند میگذرد.** هیچ کلید دائمی ارائهدهنده در مرورگر قرار نمیگیرد.
|
||||
|
||||
جزئیات SDP در کاتالوگ یک قرارداد پیشنهادی است. روز اول باید با ارائهدهنده منتخب واقعاً تست شود؛ حمایت از WebRTC و کنترل معتبر ابزار برای همه ارائهدهندگان فرض نشده است.
|
||||
|
||||
در فاز یک تاریخچه کامل صوتی و ادامه بیوقفه جلسه پس از قطعی نداریم. اگر اتصال قطع شود، UI اعلام میکند و کاربر جلسه جدید میسازد. منابع نمایشدادهشده در صوت «منابع بازیابیشده» هستند؛ ادعا نمیکنیم تکتک آنها دقیقاً در جمله صوتی استفاده شدهاند.
|
||||
|
||||
## ۹. سناریو ششم: سازمان سند ساعات کاری را عوض میکند
|
||||
|
||||
سند قدیمی ساعت پایان را ۱۲ نوشته؛ سند جدید ساعت ۱۳ را اعلام میکند.
|
||||
|
||||
۱. مدیر سند جدید را جداگانه آپلود میکند و منتظر آمادهشدن میماند.
|
||||
۲. سند قدیمی را از انتخاب خارج و جدید را فعال میکند. API میتواند مجموعه نهایی انتخابها را در یک تغییر ثبت کند؛ هر دو فایل سند مستقلاند و هیچ شماره نسخه یا جدول نسخهای نداریم.
|
||||
۳. شمارنده تغییر منابع افزایش پیدا میکند.
|
||||
۴. چون سندی حذف شده، شمارنده اعتبار زمینه گفتگو هم تغییر میکند.
|
||||
۵. گفتگوهای قبلی سازمان برای سؤال جدید stale میشوند؛ UI دکمه «گفتگوی جدید» نشان میدهد.
|
||||
۶. جلسههای صوتی قبلی بسته میشوند تا زمینه قدیمی دوباره استفاده نشود.
|
||||
۷. گفتگوی جدید سؤال را از سند جدید جواب میدهد: ساعت ۱۳.
|
||||
|
||||
برای سرعت و سادگی فاز یک، هنگام حذف یک منبع فعال همه گفتگوهای قدیمی سازمان برای ادامه نامعتبر میشوند؛ نه فقط گفتگوهایی که قطعاً از همان سند استفاده کردهاند. این رفتار محافظهکارانه است و در فاز بعد میتوان دقیقترش کرد.
|
||||
|
||||
پاسخ قبلی که «۱۲» گفته، در تاریخچه همان پاسخ قبلی باقی میماند؛ با تغییر سند بازنویسی نمیشود. صوتی که قبلاً پخش شده هم قابل پسگرفتن نیست. کنترل ما روی استفاده بعدی از اطلاعات است.
|
||||
|
||||
## ۱۰. سه عدد revision چه فرقی دارند؟
|
||||
|
||||
| فیلد | چه وقت تغییر میکند؟ | کاربرد |
|
||||
| --- | --- | --- |
|
||||
| revision | تغییر نام یا دستورالعمل دستیار | جلوگیری از ذخیره همزمان روی تنظیمات قدیمی |
|
||||
| knowledge_revision | تغییر مجموعه اسناد فعال | مشخصکردن مجموعه دانش هر نوبت |
|
||||
| access_epoch | خارجکردن سند فعال یا حذف آن | نامعتبرکردن زمینههای قدیمی گفتگو |
|
||||
|
||||
مثال: فقط سندی اضافه کنیم، knowledge_revision تغییر میکند و سؤال بعدی آن را میبیند. سند فعالی را برداریم، access_epoch هم تغییر میکند تا اطلاعات قدیمی از حافظه گفتگو دوباره وارد پاسخ نشوند.
|
||||
|
||||
اگر دو مدیر همزمان تنظیمات را باز کنند، درخواست دوم که revision قدیمی دارد ۴۰۹ میگیرد. UI تنظیمات تازه را میخواند تا تغییر مدیر اول ناخواسته از بین نرود.
|
||||
|
||||
## ۱۱. سناریو هفتم: Worker وسط کار قطع میشود
|
||||
|
||||
Worker فایل را گرفته و مشغول Embedding است. فرایند قطع میشود.
|
||||
|
||||
کار در دیتابیس مانده است. Worker برای مدت محدود اجازه پردازش داشته که Lease نام دارد. بعد از تمامشدن این مدت، کار قابل گرفتن دوباره است. دریافتکننده جدید یک claim token تازه میگیرد.
|
||||
|
||||
اگر Worker قبلی دیر برگردد، توکنش دیگر معتبر نیست و حق انتشار ندارد. Worker جدید میتواند پردازش را از ابتدا انجام دهد. در این فاز ادامهدادن دقیق از هر قطعه را پیاده نمیکنیم؛ انتشار نهایی یکپارچه است و محدودیت یکتایی، ساخت قطعات تکراری را میگیرد.
|
||||
|
||||
برای خطای موقت، تلاش مجدد با فاصله انجام میشود. برای فایل خراب، ادامه دادن بیفایده است و failed نمایش داده میشود. مدیر فقط برای خطای قابل تلاش مجدد میتواند Retry بزند. خود Retry هم کلید یکتا دارد تا دوبار کلیک، دو بار بودجه تلاش را بازنشانی نکند.
|
||||
|
||||
## ۱۲. چرا این جدولها لازماند؟
|
||||
|
||||
| گروه | جدولها | مثال ساده |
|
||||
| --- | --- | --- |
|
||||
| هویت | organizations، users، auth_sessions | چه کسی وارد شده و چه اجازهای دارد؟ |
|
||||
| تنظیمات | organization_settings | اسم دستیار و نسخه تنظیمات و منابع چیست؟ |
|
||||
| اسناد | documents | این فایل چیست، کجا ذخیره شده و آماده پاسخگویی است؟ |
|
||||
| پردازش | ingestion_jobs | چه فایلی منتظر است و چرا پردازشش شکست خورده؟ |
|
||||
| دانش | document_chunks | کدام تکه متن و بردار باید جستوجو شود؟ |
|
||||
| گفتگو | conversations، turns، messages | کدام مکالمه، کدام نوبت، چه سؤال و پاسخی؟ |
|
||||
| شواهد | tool_calls، citations | چه سرچهایی انجام شد و جواب به چه منبعی استناد کرد؟ |
|
||||
| صوت | live_sessions | کدام جلسه وصل است و چرا بسته شده؟ |
|
||||
| تغییرات مدیریتی | audit_events | چه کسی سند را غیرفعال یا Retry کرده؟ |
|
||||
|
||||
تعداد جدولها به معنی تعداد سرویس یا برنامه جدا نیست. برای مثال سه جدول گفتگو لازماند چون «گفتگو»، «اجرای یک سؤال» و «متن پیام» وضعیت و مسئولیت متفاوت دارند. نگهداری صرف متن پیام برای تشخیص timeout و درخواست تکراری کافی نیست.
|
||||
|
||||
فایل اصلی در مخزن فایل است؛ مسیر تولیدشده آن در خود سند ذخیره میشود. بردارها در pgvector داخل همان PostgreSQL هستند. فایل صوتی خام ذخیره نمیکنیم.
|
||||
|
||||
## ۱۳. سناریو هشتم: حذف سند
|
||||
|
||||
مدیر حذف را تأیید میکند. ابتدا سند از سرچ خارج و deleted ثبت میشود. اگر فعال بوده، زمینه گفتگوها هم نامعتبر میشود. پاسخ API صریحاً میگوید پاکسازی فیزیکی منتظر سیاست نگهداری است؛ «حذف از پاسخگویی» را با «پاکشدن فوری تمام فایلها و تاریخچه» یکی نمیکنیم.
|
||||
|
||||
دلیل نگهداشتن شناسه منبع این است که جواب قدیمی همچنان قابل ردیابی باشد. اینکه متن قطعات، فایل اصلی یا excerptها چه زمانی واقعاً پاک شوند، باید از سازمان مشخص شود. در این اسناد عدد دلخواه برای مدت نگهداری ننوشتهایم.
|
||||
|
||||
منبع غیرفعال/حذفشده در نمایش منابع جدید متن قابل دسترس ارائه نمیکند. تاریخچه پاسخهای قبلی متعلق به کاربر، طبق دسترسی تاریخچه باقی میماند؛ وارد زمینه گفتگوی جدید نمیشود.
|
||||
|
||||
## ۱۴. برنامه عملی توسعه و معیار پیشرفت
|
||||
|
||||
| بازه | چیزی که باید بتوانیم نشان دهیم |
|
||||
| --- | --- |
|
||||
| روز ۱ | صوت واقعی و اجرای ابزار در بکاند؛ فرمت فایل و مدلها مشخص |
|
||||
| روز ۲ | ورود و آپلود ماندگار |
|
||||
| روز ۳ | تبدیل فایل به سند ready و خطای قابل فهم برای فایل نامعتبر |
|
||||
| روز ۴ | سرچ فقط روی اسناد فعال با منبع درست |
|
||||
| روز ۵ | چت متنی و بازیابی وضعیت درخواست پس از timeout |
|
||||
| روز ۶ | سؤال صوتی و سرچ واقعی در همان دانش |
|
||||
| روز ۷ | چهار صفحه و دموی کامل روی HTTPS |
|
||||
| روز ۸ تا ۱۰ | اصلاح کیفیت، تست شکستها، آمادهسازی نسخه ارائه |
|
||||
|
||||
این زمانبندی تضمین بدون شرط نیست. اگر UI از صفر و فایلها پیچیده باشند یا اتصال مدل Live حل نشود، ریسک زمان بالا میرود. اول امکانات تزئینی و اختیاری حذف میشوند؛ دسترسی صحیح و سه قابلیت اصلی نباید پنهانی حذف شوند.
|
||||
|
||||
## ۱۵. چکلیست ارائه و پذیرش
|
||||
|
||||
- کاربر عادی نتواند تنظیمات یا اسناد را تغییر دهد و گفتگوی دیگری را بخواند.
|
||||
- فایل آمادهنشده وارد سرچ نشود.
|
||||
- سؤال مستند جواب و منبع درست داشته باشد.
|
||||
- سؤال بیپاسخ با اطلاعات ساختگی جواب داده نشود.
|
||||
- ارسال تکراری، نوبت یا کار پردازشی تکراری نسازد.
|
||||
- قطع Worker باعث از دست رفتن کار پذیرفتهشده نشود.
|
||||
- مکالمه صوتی واقعاً از WebRTC و ابزار بکاند استفاده کند.
|
||||
- خروج کاربر، پایان جلسه یا تغییر منابع فعال، وضعیت Live را درست تغییر دهد.
|
||||
- تاریخچه متن بعد از restart باقی بماند.
|
||||
- دمو روی شبکه و مرورگر محیط ارائه تمرین شده باشد.
|
||||
|
||||
۱۵ تا ۲۰ سؤال مرجع از اسناد واقعی آماده میکنیم؛ برای هرکدام جواب مورد انتظار و قطعه منبع را مینویسیم. نتیجه اجرای متن و صوت جدا ثبت میشود. این مجموعه کوچک، تضمین دقت عمومی محصول نیست.
|
||||
|
||||
## ۱۶. مواردی که قبل از شروع باید قطعی شوند
|
||||
|
||||
| سؤال | مسئول پیشنهادی |
|
||||
| --- | --- |
|
||||
| فایلهای واقعی چه فرمت و ساختاری دارند و حداکثر اندازه چیست؟ | صاحب محصول + توسعهدهنده |
|
||||
| مدل Live منتخب اتصال و کنترل ابزار مورد نیاز را پشتیبانی میکند؟ | توسعهدهنده/تیم AI با آزمایش واقعی |
|
||||
| مدل Embedding و تعداد ابعادش چیست؟ | تیم AI قبل از مایگریشن بردار |
|
||||
| محیط HTTPS و دسترسی به ارائهدهنده آماده است؟ | توسعهدهنده/زیرساخت |
|
||||
| مدت نشست و نگهداری فایل/گفتگو چقدر است؟ | صاحب محصول/سازمان |
|
||||
| شروع کار و تاریخ ارائه دقیقاً چه روزی است؟ | مدیر پروژه |
|
||||
|
||||
## ۱۷. نحوه استفاده از اسناد توسط توسعهدهنده
|
||||
|
||||
ابتدا Implementation Guide برای ترتیب کار و مرز ماژولها؛ سپس API Catalog برای DTO و هماهنگی فرانت؛ بعد Database Design برای مدلهای ORM و مایگریشن. سناریوهای این گزارش باید تبدیل به تستهای یکپارچه شوند.
|
||||
|
||||
قراردادها در این مجموعه با هم هماهنگ شدهاند، اما هنوز تصمیمهای روز اول بازند. پس از تأیید فرمت و مدل و اتصال Live، همین اسناد نسخه جدید میگیرند. افزودن قابلیت محصول کامل به کارهای این فاز باید با تغییر صریح محدوده یا زمانبندی انجام شود.
|
||||
@@ -0,0 +1,193 @@
|
||||
# Prompt: Create Repository Skills for the Phase 1 RAG Assistant
|
||||
|
||||
Paste the following prompt into the coding agent with the project repository open. Make the six current project documents available in the repository first; their exact directory is discovered by the agent. This prompt creates development skills, not application features.
|
||||
|
||||
---
|
||||
|
||||
You are working inside my Organization Knowledge Assistant repository. Create three practical, repository-scoped development skills:
|
||||
|
||||
1. `implement-feature`
|
||||
2. `write-tests`
|
||||
3. `review-change`
|
||||
|
||||
Integrate relevant real-provider RAG evaluation into `write-tests`; do not create a separate `verify-rag-flow` skill.
|
||||
|
||||
Implement the skill files and necessary references now. Do not stop at a proposal or print hypothetical file contents. Do not implement product features while creating these skills.
|
||||
|
||||
## 1. Inspect the repository and agent environment
|
||||
|
||||
Before writing:
|
||||
|
||||
- Locate the repository root and inspect Git status. Preserve unrelated modifications.
|
||||
- Read applicable root and nested `AGENTS.md` files and any existing skill-authoring instructions.
|
||||
- Inspect the agent's actual supported repository skill location and existing skill conventions. Use that supported location; do not assume a directory merely because it appears in an example. If no project skill discovery mechanism is available, create reusable skill documents in a clearly identified repository directory and report that automatic discovery is unverified. Do not claim installation without evidence.
|
||||
- Inspect existing skills by frontmatter name. Update equivalent project-owned skills rather than creating duplicate names. Do not modify system, plugin or globally installed skills.
|
||||
- Inspect the application tree, dependency manifests, test configuration, CI and existing commands. Do not prescribe a new framework or test runner when suitable conventions already exist.
|
||||
- Prefer `rg` and `rg --files` for discovery.
|
||||
|
||||
Do not hardcode paths from another machine, ChatGPT scratch directories, Library IDs or inaccessible sandbox links.
|
||||
|
||||
## 2. Resolve the actual project references
|
||||
|
||||
Find these exact filenames, wherever they are located in the repository:
|
||||
|
||||
| Document | Purpose |
|
||||
| --- | --- |
|
||||
| `RAG-AI-Phase1-Delivery-Plan.md` | Phase 1 scope, delivery sequence and acceptance criteria |
|
||||
| `RAG-Phase1-Implementation-Guide.md` | Modules, responsibilities, workflows and implementation boundaries |
|
||||
| `RAG-Phase1-API-Catalog.md` | Routes, DTOs, permissions, errors, retry and idempotency contracts |
|
||||
| `RAG-Phase1-Database-Design.md` | Current schema, constraints, transactions and migration approach |
|
||||
| `RAG-Phase1-Scenario-Report-FA.md` | Business scenarios and Persian explanations |
|
||||
| `RAG-AI-Architecture.md` | Wider architecture and future direction |
|
||||
|
||||
Read enough of each to verify it is the current simplified design. The current design has independent uploaded documents and no document-content versioning. Do not select an obsolete document just because its filename matches. Resolve duplicates using content, repository context and document status; ask a focused question only when competing authoritative copies cannot be distinguished.
|
||||
|
||||
Create or update one small shared reference index in the repository's existing documentation area. If there is no convention, use `docs/development/agent-reference-map.md`. Record:
|
||||
|
||||
- The actual relative path to each document and what it governs.
|
||||
- Which sections each skill should consult, preferably with verified heading anchors or heading names.
|
||||
- Actual relevant source/test directories and verified development commands.
|
||||
- Any missing references or unresolved contradictions, explicitly labelled.
|
||||
|
||||
Do not copy whole documents into the skills. Do not fabricate missing contents, executable commands, schema fields or approval decisions. If a required document is missing, continue building the available skill structure; label the relevant workflow blocked on that reference and report exactly what is missing. Do not leave a broken link disguised as an existing reference.
|
||||
|
||||
Every skill must link directly to this reference index using a valid relative link from its own `SKILL.md`. Within the index, resolve links relative to the index file. Verify every path and any heading anchor you create. Avoid machine-specific absolute paths and symlinks outside the repository.
|
||||
|
||||
Reference authority:
|
||||
|
||||
- Follow governing instructions and the user's explicit current task.
|
||||
- Use the Phase 1 plan for scope; API and database documents for their contracts; implementation guide for workflows.
|
||||
- Treat the broader architecture as context, not permission to implement deferred features.
|
||||
- Treat existing code as implementation evidence, not automatic proof that conflicting behavior is correct.
|
||||
- Surface material contradictions; do not silently rewrite policy or expand scope. Continue unrelated work when a decision blocks only one part.
|
||||
|
||||
## 3. Keep shared project rules in AGENTS.md
|
||||
|
||||
Preserve existing instructions. Add a concise section only where the rules belong; avoid duplicating nested instructions. Include these current invariants:
|
||||
|
||||
- Deliver within Phase 1 scope using the existing modular backend and separate ingestion worker.
|
||||
- Each upload creates an independent document; content is not overwritten in place.
|
||||
- Do not introduce `document_versions`, `version_id` or `version_no` for document content.
|
||||
- Chunks and ingestion jobs reference `document_id`; answer sources reference `document_id` and `chunk_id`.
|
||||
- Retry processes the same eligible failed document; it does not create a new document identity.
|
||||
- Only authorized, ready, active and undeleted documents are searchable.
|
||||
- The backend derives trusted identity and search scope. Model arguments cannot override them.
|
||||
- Text and Live use the same backend search implementation.
|
||||
- Keep persistent provider secrets server-side.
|
||||
- Follow documented request deduplication, worker claim/lease rules and context invalidation behavior where relevant.
|
||||
- Keep API/schema documentation aligned with intentional contract changes. Never alter contracts just to excuse a bug.
|
||||
- Avoid unnecessary dependencies, services, abstractions and unrelated refactoring.
|
||||
|
||||
Configuration revisions and embedding profile metadata are not document-content versioning and must not be removed accidentally.
|
||||
|
||||
Link to the shared reference map instead of embedding all requirements into AGENTS.md. Add verified project commands only; label commands not yet runnable rather than guessing that they work.
|
||||
|
||||
## 4. Skill structure and authoring requirements
|
||||
|
||||
For each skill create a `SKILL.md` with valid YAML frontmatter:
|
||||
|
||||
- `name`: exactly the requested skill name.
|
||||
- `description`: concise purpose and specific triggering situations, including when not to use it if needed to prevent over-triggering.
|
||||
|
||||
Follow the actual agent's supported metadata schema. Add UI metadata only if supported and useful; validate it using the available authoring guidance. Never invent metadata keys.
|
||||
|
||||
Keep each skill procedural, specific and concise; aim for approximately 100–200 lines or less. Include relevant references, the workflow, verification requirements, stopping conditions and an output format. Do not add filler README files, duplicate manuals, unused resources or scripts that only wrap a single ordinary command.
|
||||
|
||||
Skills must not recursively invoke one another in a loop. Implementation includes its necessary validation; test-writing develops tests; review is read-only unless fixing is explicitly requested.
|
||||
|
||||
### Skill A: implement-feature
|
||||
|
||||
Trigger: implement or modify a scoped application capability in this repository.
|
||||
|
||||
Workflow:
|
||||
|
||||
1. Identify requested behavior, acceptance criteria and relevant references.
|
||||
2. Inspect the existing implementation, test patterns and affected integration boundaries.
|
||||
3. State a short implementation plan proportional to the task. Continue without routine permission requests.
|
||||
4. Implement the smallest complete change across the necessary API, application, persistence/provider and UI boundaries. Do not force edits into layers the task does not affect.
|
||||
5. Handle relevant permissions, state transitions, errors and concurrency/idempotency requirements.
|
||||
6. Preserve provider-neutral application boundaries and shared retrieval.
|
||||
7. Add meaningful tests for changed behavior and regressions. Reuse existing fixtures.
|
||||
8. Run relevant checks using repository commands; update affected docs for intentional contract changes.
|
||||
9. Report changed behavior, files, actual checks and remaining limitations.
|
||||
|
||||
If the task explicitly changes a contract, update its documentation and consumers coherently. If a product decision is genuinely missing, isolate it and request that decision without inventing it. Do not ask for permission for ordinary reversible implementation choices.
|
||||
|
||||
### Skill B: write-tests
|
||||
|
||||
Trigger: create, extend or improve tests for an identified behavior, regression or release risk.
|
||||
|
||||
Workflow:
|
||||
|
||||
1. Read the intended behavior and existing tests before choosing assertions.
|
||||
2. Select the smallest useful test level: unit, integration, contract or end-to-end.
|
||||
3. Cover relevant success, failure and boundary cases; avoid mechanically enumerating irrelevant combinations.
|
||||
4. Use the repository's runner, fixtures and naming conventions.
|
||||
5. Mock external providers at the adapter/transport boundary where appropriate. Do not mock the behavior under test or treat a fake database as proof of PostgreSQL constraints.
|
||||
6. Use an isolated PostgreSQL/pgvector test environment when testing database-specific transactions, vector queries or constraints; never run destructive fixtures against production.
|
||||
7. Keep ordinary automated tests deterministic and network-free by default. Control clocks and retries through injected dependencies where the code supports them.
|
||||
8. Run the targeted tests and explain failures. Do not weaken assertions, skip regressions or change expected behavior merely to make the suite pass.
|
||||
9. Distinguish a product bug, a test defect and an unavailable environment. Report an exposed product bug without silently expanding a tests-only task into a production fix.
|
||||
|
||||
Choose relevant cases from:
|
||||
|
||||
- Authorized upload, invalid files, failed extraction and no publication of partial chunks.
|
||||
- Duplicate upload/chat request replay and changed-payload conflicts.
|
||||
- Active/ready/deleted filtering and forged scope arguments.
|
||||
- Worker lease expiry, stale claim rejection and duplicate-free publication.
|
||||
- Turn state, conversation ownership, interruption and source mapping.
|
||||
- Document deactivation and stale context handling.
|
||||
- Live tool dispatch using shared retrieval, duplicate tool events and close/failure state.
|
||||
|
||||
Add a clearly separate optional section: **Real-provider RAG evaluation**.
|
||||
|
||||
Use it when real-output quality is requested or release readiness requires it and the environment/data access is authorized. Prepare a small corpus and questions with expected evidence, including paraphrases, missing knowledge and follow-ups. Check extraction, retrieved evidence, answer support and source identity separately. Test text and voice separately. Prefer factual assertions over exact full-answer wording. Label any model-based judging and human checks; do not present them as deterministic proof.
|
||||
|
||||
Use bounded requests, protect sensitive data and honor existing cost/network authorization. If credentials, corpus, a runnable service or required voice interaction are unavailable, report the evaluation as not run. Never fabricate metrics or claim mock results establish real-model quality. Keep this optional evaluation out of the default unit-test run.
|
||||
|
||||
### Skill C: review-change
|
||||
|
||||
Trigger: review a diff, implementation or proposed merge for defects and contract violations.
|
||||
|
||||
Workflow:
|
||||
|
||||
1. Resolve the requested review scope and base. Inspect the diff and relevant surrounding code/tests/docs.
|
||||
2. Check correctness, authorization, contract alignment, data integrity, failure behavior and relevant concurrency/retry issues.
|
||||
3. Pay particular attention to inactive-document leaks, stale context, duplicate provider work, invalid citations and application/provider boundary mistakes where those areas changed.
|
||||
4. Use targeted read-only inspection or checks to validate suspected findings. Do not execute production writes.
|
||||
5. Prioritize actionable defects over stylistic preferences; avoid speculative findings without a concrete failure path.
|
||||
6. Report each finding with severity, actual file and location, trigger, impact and recommended correction direction.
|
||||
7. If no defects are found, say so with the review scope and untested risks. Do not invent findings to populate the report.
|
||||
|
||||
Default to review-only. Do not modify code unless the user asks for fixes. Do not report unimplemented roadmap features as bugs when the Phase 1 plan defers them.
|
||||
|
||||
## 5. Validate the created skills
|
||||
|
||||
Validate in the repository where the skills will be used:
|
||||
|
||||
- Frontmatter parses; names match; descriptions distinguish the three workflows.
|
||||
- All referenced files and heading anchors resolve from their actual locations.
|
||||
- No scratch paths, fabricated commands, stale document-version requirements or placeholder links remain.
|
||||
- Existing instructions and unrelated modifications are preserved.
|
||||
- The three skills route these representative requests correctly:
|
||||
- “Implement document upload and processing status.” → implement-feature.
|
||||
- “Add regression tests for repeated chat submissions.” → write-tests.
|
||||
- “Review this change for inactive-document exposure.” → review-change.
|
||||
- “Evaluate these real questions before the demo.” → optional RAG evaluation within write-tests, with prerequisites checked.
|
||||
- Review hypothetical behavior for missing docs, unavailable providers and a discovered product bug. Do not implement those product scenarios as part of skill creation.
|
||||
|
||||
Use the agent's available skill validator when present. If unavailable, validate YAML and links using existing tools and state the limitation. Do not install an unrelated toolchain merely for validation. If you add a reusable validation script, actually run it and verify its output.
|
||||
|
||||
Do not commit, push, deploy or install skills globally unless governing repository instructions or the user's authorization require it. Creating files is not evidence that the agent has discovered them: verify discovery if possible, otherwise explain how to invoke the files explicitly and label automatic discovery unverified.
|
||||
|
||||
## 6. Final report
|
||||
|
||||
Return:
|
||||
|
||||
1. The created/updated file tree and actual paths.
|
||||
2. A brief explanation of each skill and one invocation example using this agent's supported syntax.
|
||||
3. The actual project-document reference mapping.
|
||||
4. Validation performed and results.
|
||||
5. Any missing documents, unresolved decisions or discovery limitations.
|
||||
|
||||
Keep the final report concise. Do the file work before returning it.
|
||||
@@ -0,0 +1,179 @@
|
||||
# Phase 1 agent reference map
|
||||
|
||||
Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Inventory verified on 2026-10-05; recheck it as implementation grows. Latest evidence: 163 combined tests passed, including 48 real PostgreSQL cases in both supported pgvector environments. The final acceptance section below supersedes earlier unavailable-database reports.
|
||||
|
||||
## Authority and document resolution
|
||||
|
||||
Follow governing instructions and the user's current task. The plan sets Phase 1 scope; API and database specifications set contracts; the implementation guide sets workflows. The Persian report explains scenarios. Architecture supplies context only. Code and README describe the prototype, not approval to override the Phase 1 contracts.
|
||||
|
||||
The six requested unsuffixed filenames do not exist. The only corresponding copies are the ` (1).md` files linked below. Content confirms the 2026-10-05 simplified design: independent immutable uploads, direct document references, no content versions, and retained technical revisions. English specifications identify revision 1.1 and proposed status; the Persian report explains the same lifecycle in sections 9-11. No competing copies were found. Preserve their names and untracked status unless the user requests otherwise.
|
||||
|
||||
Section numbers and heading names below are verified against these files; no inferred fragment anchors are used.
|
||||
|
||||
| Requested document | Actual file | Authority and sections to consult |
|
||||
| --- | --- | --- |
|
||||
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](<RAG-AI-Phase1-Delivery-Plan (1).md>) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Updates; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
|
||||
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](<RAG-Phase1-Implementation-Guide (1).md>) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
|
||||
| `RAG-Phase1-API-Catalog.md` | [API catalog](<RAG-Phase1-API-Catalog (1).md>) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and text; 7. Voice contract — provisional signaling, fixed ownership rules; 9. Error envelope and mapping |
|
||||
| `RAG-Phase1-Database-Design.md` | [Database design](<RAG-Phase1-Database-Design (1).md>) | Schema/constraints/transactions: 4. Knowledge tables; 5. Conversation and evidence tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
|
||||
| `RAG-Phase1-Scenario-Report-FA.md` | [Persian scenarios](<RAG-Phase1-Scenario-Report-FA (1).md>) | Business examples: sections 4-8 (upload, text, missing knowledge, duplicate submission, voice), 9-11 (replacement, revisions, worker crash), 13 (delete), 15 (acceptance), 16 (open decisions) |
|
||||
| `RAG-AI-Architecture.md` | [Architecture](<RAG-AI-Architecture (1).md>) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Migration from the Existing Repository; 19. Open Decisions and Owners |
|
||||
|
||||
## Reading by workflow
|
||||
|
||||
- `implement-feature`: Plan 3/8/9 for boundaries and acceptance; guide 3 and the affected workflow in 5-10; API endpoint and error sections; database affected tables plus 7/8. Use Persian scenarios to clarify observable behavior and architecture 17 for migration context.
|
||||
- `write-tests`: Plan 9/10; guide 12 and affected workflow; API replay/error/permission rules; database 7/9 for races and constraints; Persian scenarios 4-11/13/15 for concrete cases. Consult architecture only for relevant context.
|
||||
- `review-change`: Plan 3/9 to avoid roadmap findings; guide 5-10 for changed boundaries; exact API contracts and database 7/8/9. Use Persian scenarios for trigger/impact and architecture dependency rules only where relevant.
|
||||
|
||||
## Actual implementation and commands
|
||||
|
||||
| Existing path | Observed responsibility |
|
||||
| --- | --- |
|
||||
| [Application entry point](../../app/main.py) | FastAPI routes, CORS, static health response |
|
||||
| [API directory](../../app/api/v1/) and [schemas](../../app/schemas/) | Prototype chat transport and DTOs |
|
||||
| [Services](../../app/services/) | Document loading/chunking and Chroma/FastEmbed retrieval |
|
||||
| [Agent](../../app/services/agent/) and [tools](../../app/services/tools/) | LangGraph text loop, in-memory history, retrieval tool |
|
||||
| [Configuration](../../app/core/config.py) and [environment example](../../.env.example) | Settings and provider configuration |
|
||||
| [README](../../README.md) | Prototype startup instructions; not Phase 1 implementation evidence |
|
||||
| [Document processor](../../app/services/doc_processor.py) | Recursively ingests Markdown under this documentation directory |
|
||||
|
||||
Ingestion foundation now exists: [manifest](../../pyproject.toml), [settings/types/ports](../../app/modules/documents/), [database access](../../app/infrastructure/database.py), [initial migration](../../migrations/versions/0001_ingestion_foundation.py), [Alembic environment](../../migrations/env.py), [trusted bootstrap](../../app/bootstrap.py), and [tests](../../tests/). Read [foundation setup](../../docs/ingestion-foundation-setup.md) before migration/bootstrap/database testing. Only the seven requested foundation tables are implemented; no auth sessions, conversation or Live tables. There is still no lockfile, CI, frontend, ingestion intake CLI, concrete FileStore/embedding adapter or worker. Redis/broker and a new orchestration framework are unnecessary.
|
||||
|
||||
| Command from repository root | Verification status |
|
||||
| --- | --- |
|
||||
| `git status --short` | Executed for working-tree inspection |
|
||||
| `git diff --check` | Executed for tracked whitespace validation; untracked new files need separate inspection |
|
||||
| `rg --files --hidden -g '!.git/**'` | Executed for file discovery |
|
||||
| `uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload` | README example and entry point verified statically; runtime not verified |
|
||||
| `python -m app.services.agent.exec` | README example and CLI entry point verified statically; provider smoke harness, not automated regression tests; not run |
|
||||
|
||||
Runtime prerequisites remain unverified: dependencies, configured credentials, approved corpus, writable vector storage, and provider/model access. Importing the application creates settings/retrieval singletons and can load embeddings/index documents. Do not use imports as a supposedly network-free smoke test. README installation now uses pyproject.toml extras. Foundation imports are independent of those prototype prerequisites. Verified foundation commands are listed below; no worker is implemented; see the latest local database acceptance evidence below.
|
||||
|
||||
## Gaps and decisions
|
||||
|
||||
- Required document content is available under suffixed names; no reference-dependent workflow is currently blocked by missing content. If a linked document later disappears, mark only dependent contract work blocked, report its exact path, and continue unrelated work without inventing it.
|
||||
- Material implementation gap: Chroma/local Markdown/in-memory history and the prototype chat DTO differ from the Phase 1 PostgreSQL/pgvector, uploaded documents, authenticated durable turns, and separate worker target. README production-readiness claims are not acceptance evidence. Skill creation does not implement that migration.
|
||||
- Open decisions: approved formats/size limits, model IDs and vector dimension, live provider/signaling/control proof, hosting/connectivity, account/session/retention policy, quality threshold, and delivery date. See guide 13 and plan 2. Do not turn proposals into recorded approvals.
|
||||
- Live SDP signaling is provisional; resolve compatibility before freezing frontend contracts. Broader architecture features must not override Phase 1 exclusions such as model selectors and guaranteed voice transcripts.
|
||||
- Documentation shares the prototype ingestion directory, so this index may enter its Markdown corpus. Use a deliberately isolated, approved corpus for real-provider evaluation and report this limitation; do not silently change product ingestion during skill authoring.
|
||||
|
||||
## Skill discovery
|
||||
|
||||
Skills are stored at repository-root `.agents/skills/<name>/SKILL.md`, the repository location documented in [official Codex skill guidance](https://learn.chatgpt.com/docs/build-skills). No equivalent project-owned skills or prior AGENTS.md files were found.
|
||||
|
||||
Use `$implement-feature`, `$write-tests`, or `$review-change` in Codex. Automatic discovery was verified on 2026-10-05: all three repository skills appeared in this session's available-skills catalog after creation. In another client/session where selection is unavailable, explicitly ask Codex to read the relevant SKILL.md by repository path and follow it. No global installation or optional UI metadata is required.
|
||||
|
||||
|
||||
## Ingestion foundation commands and evidence (2026-10-05)
|
||||
|
||||
- python -m venv .venv and .venv/Scripts/python -m pip install -e ".[test]": executed successfully with Python 3.14.6.
|
||||
- .venv/Scripts/python -m pytest -m "not postgres": 13 passed; no real providers.
|
||||
- .venv/Scripts/alembic history: initial revision discovered successfully.
|
||||
- .venv/Scripts/python -m pytest -m postgres: requires TEST_DATABASE_URL targeting a dedicated database ending in _test. PostgreSQL tests use disposable schemas and real independent connections. Ordinary-suite missing configuration skips them with a non-acceptance reason; add --require-postgres to the acceptance command so missing configuration fails.
|
||||
- .venv/Scripts/alembic upgrade head: operator command, not yet executed against PostgreSQL. Requires explicit INGEST embedding identity/dimension; initial vector(D) and profile are frozen in the database. Equal dimensions with a different model fail compatibility.
|
||||
- .venv/Scripts/python -m app.bootstrap: trusted initial organization/admin command; requires explicit display/settings arguments and an interactive password prompt or --password-stdin. No HTTP authentication is implemented.
|
||||
- docker info --format '{{.ServerVersion}}': failed both inside and outside the sandbox because Docker Desktop WSL bootstrap could not start. PostgreSQL/pgvector acceptance is unverified in this environment.
|
||||
- git diff --check: tracked whitespace validation only; newly added files also need separate inspection.
|
||||
|
||||
The ingestion pipeline plan remains an untracked specification; its later phases are not implemented by foundation work. All seven tables use the database contract's direct document identities, scoped FKs, state constraints and uniqueness. The initial revision already exists and must be treated as potentially applied. Repair work does not assume it is unapplied: preserve it byte-for-byte and use forward revisions for any future persisted changes. Processing-profile snapshots contain character units and embedding identity without secrets. Compatibility and native vector registration are explicit functions; importing ingestion modules opens no database/provider connection or corpus.
|
||||
|
||||
- Final .venv/Scripts/python -m pytest: 13 passed, 31 PostgreSQL tests skipped because TEST_DATABASE_URL was absent. .venv/Scripts/python -m pip check: no broken requirements. Database migration/constraint/concurrency/bootstrap runtime remains unverified.
|
||||
|
||||
|
||||
## Phase 1 repair evidence (2026-10-05)
|
||||
|
||||
Scope is foundation repair only. No intake, worker, HTTP authentication,
|
||||
conversation/Live tables or chat behavior was added.
|
||||
|
||||
- Settings reject credential-bearing or unsupported endpoint URLs, preserving supported endpoint identity. Error strings and structured validation errors omit raw input values. Credentials remain separate SecretStr values. Every floating-point duration rejects NaN and both infinities in direct and environment construction.
|
||||
- [PostgreSQL fixture support](../../tests/support/postgres.py) keeps public out of disposable search paths. pgvector resides in the dedicated test_vector namespace; an existing extension elsewhere is refused, not relocated. Alembic explicitly scopes version_table_schema. Every foundation relation is checked before test connections are used and before migration/downgrade. [Isolation regressions](../../tests/integration/test_isolation.py) create their own temporary database to prove public tables/data survive setup, mutation, downgrade/upgrade and teardown.
|
||||
- Manifest support remains pgvector >=0.3.6,<1. Vector acceptance handles both NumPy (0.3.6) and Vector (0.5.0) results. The minimum was installed in .venv/minimum; package imports/provider-free checks are not real database adaptation proof.
|
||||
- Initial revision SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567. No revision file or persisted schema was changed; no forward data migration was needed for these code/config/test repairs. Historical URL-secret cleanup is unresolved if an older deployment actually persisted such inputs.
|
||||
- Provider-free commands .venv/Scripts/python -m pytest -m "not postgres" and .venv/minimum/Scripts/python -m pytest -m "not postgres": 88 passed in each environment (pgvector 0.5.0 and 0.3.6).
|
||||
- Explicit PostgreSQL acceptance commands in both environments, -m postgres --require-postgres --tb=no, fail fixture setup when TEST_DATABASE_URL is absent. Docker info still fails inside and outside the sandbox with DockerDesktop/Wsl/ExecError and WSL bootstrap exit 0x40010004. No PostgreSQL migration/constraint/isolation/concurrency/vector evidence is claimed.
|
||||
- README now agrees with requires-python >=3.11. Pipeline inventory and AGENTS.md point to the actual manifest, migrations and tests.
|
||||
|
||||
|
||||
Final repair checks:
|
||||
- .venv/Scripts/python -m pytest: 88 passed, 48 skipped. Skips are PostgreSQL cases with missing TEST_DATABASE_URL and do not count as acceptance.
|
||||
- .venv/Scripts/python -m pytest -m postgres --require-postgres --tb=no -q and the same command using .venv/minimum/Scripts/python: 48 setup errors in each environment, zero PostgreSQL passes/skips; database configuration is absent. An earlier run before constraint coverage expansion had 34 setup errors.
|
||||
- .venv/Scripts/python -m pip check and .venv/minimum/Scripts/python -m pip check: no broken requirements.
|
||||
- .venv/Scripts/alembic history: unchanged initial revision discovered.
|
||||
- git diff --check: passed; new-file syntax/whitespace inspection is separate.
|
||||
|
||||
|
||||
## Final foundation acceptance evidence (2026-10-05)
|
||||
|
||||
Remaining settings defects were reproduced first: malformed port values leaked
|
||||
dummy secrets into Pydantic output/context, malformed URL structure escaped as
|
||||
SQLAlchemy ArgumentError, and valid ambient limit overrides broke baseline tests.
|
||||
[Settings](../../app/modules/documents/settings.py) now converts parser failures
|
||||
to a generic validation error outside the parser handler and raises sanitized
|
||||
ValidationError outside its handler, retaining no raw parser/input exception
|
||||
chain. [Regressions](../../tests/unit/test_database_urls.py) inspect str/repr/json,
|
||||
errors and context/cause, exercise valid Psycopg URLs and rerun the ordinary suite
|
||||
with external overrides. [Fixtures](../../tests/conftest.py) clear ambient
|
||||
INGEST_* variables per test without changing production loading or TEST_DATABASE_URL.
|
||||
|
||||
Docker became available. A dedicated temporary PostgreSQL/pgvector container,
|
||||
rag-foundation-acceptance-7e382b6f, ran on localhost:54918 with the dedicated
|
||||
rag_foundation_test database. The server was PostgreSQL 16.15; pgvector extension
|
||||
0.8.7. Python adapter versions were 0.5.0 and minimum 0.3.6.
|
||||
[Prerequisite check](../../tests/postgres_prerequisites.py) verifies connectivity,
|
||||
dedicated database configuration, CREATE/DROP DATABASE and extension privileges,
|
||||
and the safe extension namespace before the suite. Both environments passed it.
|
||||
No existing deployment/database or metadata was changed.
|
||||
|
||||
Final commands/results:
|
||||
- .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.
|
||||
- .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected.
|
||||
- .venv/Scripts/python -m pytest --require-postgres -q: 163 passed.
|
||||
- .venv/Scripts/python -m tests.postgres_prerequisites and .venv/minimum/Scripts/python -m tests.postgres_prerequisites: passed.
|
||||
- Both environments' python -m pip check: no broken requirements.
|
||||
- .venv/Scripts/alembic history: initial revision discovered.
|
||||
All final test runs had zero failures, setup errors or skips.
|
||||
|
||||
First real-DB run: 46 passed/2 failed in 0.5.0; first 0.3.6 run after initial test
|
||||
repairs: 47 passed/1 failed. Repaired test SQL JSON binding, replaced
|
||||
search-path-dependent deparsed constraint comparisons with complete stable
|
||||
catalog comparisons, and used 0.3.6's supported NumPy native input. Assertions
|
||||
continue to prove numeric vector values and unchanged public relations/data.
|
||||
Public preservation, scoped downgrade/upgrade, constraints, profile checks and
|
||||
concurrent bootstrap now have real PostgreSQL evidence.
|
||||
|
||||
The initial revision remains byte-for-byte unchanged with SHA-256
|
||||
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
|
||||
No persisted schema change or forward migration was needed. Historical credential
|
||||
remediation is conditional on identifying an affected deployment and explicit
|
||||
authorization; see setup instructions for rotation and targeted forward metadata
|
||||
migration while preserving agreed embedding identity. No remediation is claimed.
|
||||
|
||||
Remaining limits: local acceptance does not prove production deployment,
|
||||
real-provider compatibility/quality or any later ingestion phase. The standalone
|
||||
operator migration/bootstrap commands remain separately documented; the suite
|
||||
executes the real Alembic migration path and bootstrap database function.
|
||||
|
||||
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).
|
||||
@@ -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).
|
||||
@@ -0,0 +1,316 @@
|
||||
# Document ingestion pipeline: six implementation phases
|
||||
|
||||
## 1. Target and boundaries
|
||||
|
||||
Build this pipeline:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["Import PDF or Markdown"] --> B["Save immutable original + queued job"]
|
||||
B --> C["Worker claims job"]
|
||||
C --> D["Extract and normalize"]
|
||||
D --> E["Chunk"]
|
||||
E --> F["Embed batches"]
|
||||
F --> G["Stage all results in memory"]
|
||||
G --> H{"Every chunk valid?"}
|
||||
H -->|Yes| I["One transaction: insert chunks + mark ready"]
|
||||
H -->|No| J["Discard staging; retry or fail"]
|
||||
I --> K["PostgreSQL + pgvector"]
|
||||
```
|
||||
|
||||
**Publication is atomic per document.** If a document produces 100 chunks, all 100 embeddings must succeed before any chunk is committed to `document_chunks`.
|
||||
|
||||
Document metadata and its ingestion job are persisted before processing. After publication, the document is `ready` but remains inactive.
|
||||
|
||||
This milestone includes a local import/status/retry CLI and a separate worker. Authenticated upload APIs, selection controls, and replacing the existing Chroma chat retriever are later milestones. Completing this pipeline will not yet make chat search pgvector.
|
||||
|
||||
The prototype has Markdown loading, character chunking, and Chroma/FastEmbed indexing. Ingestion Phase 1 now has a pyproject.toml manifest, Alembic foundation migration, independent settings/ports/database access, trusted bootstrap, and pytest regressions. Local PostgreSQL foundation acceptance has now passed in both supported pgvector Python environments; see the setup guide for exact results and remaining deployment/provider limitations. There is no ingestion intake CLI or worker yet; Phases 2-6 remain planned. See [foundation setup](ingestion-foundation-setup.md).
|
||||
|
||||
## 2. Shared implementation decisions
|
||||
|
||||
Use the repository's database and workflow contracts through [the reference map](../data/documents/agent-reference-map.md).
|
||||
|
||||
- Implement application services under `app/modules/documents/`, storage/database/provider adapters under `app/infrastructure/`, and worker orchestration in `app/worker.py`.
|
||||
- Use PostgreSQL jobs, SQLAlchemy, Alembic, Psycopg, and pgvector. No message broker or staging table.
|
||||
- Use a PDF parser such as `pypdf` for text-based PDFs; UTF-8 decoding for Markdown. OCR and complex table reconstruction remain excluded.
|
||||
- Define small internal types: extracted blocks, chunk drafts, embedding profile, and a complete staged document. Keep provider response objects inside the embedding adapter.
|
||||
- Preserve immutable originals and direct `document_id` references. Do not add document-content versions.
|
||||
- Record extraction, normalization, chunking, and embedding settings in `documents.processing_profile`. Retries use that recorded profile.
|
||||
- Keep the new ingestion entry points independent of the prototype retriever and its import-time indexing.
|
||||
|
||||
**Configuration defaults**
|
||||
|
||||
All limits are environment-configurable, validated at startup, and documented in `.env.example`.
|
||||
|
||||
| Setting | Initial default |
|
||||
| --- | --- |
|
||||
| Accepted formats | `.pdf`, `.md` |
|
||||
| Maximum original size | 20 MiB |
|
||||
| Maximum PDF pages | 200 |
|
||||
| Maximum normalized characters | 1,000,000 |
|
||||
| Maximum chunks per document | 2,000 |
|
||||
| Chunk size / overlap | 1,000 / 200 characters |
|
||||
| Embedding batch size | 32 chunks |
|
||||
| Maximum staged payload | 128 MiB, measured using text bytes and packed vector storage |
|
||||
| Worker concurrency | One document |
|
||||
| Poll / heartbeat / lease | 2 / 20 / 120 seconds |
|
||||
| Maximum automatic attempts | 3 |
|
||||
| Retry delay | Exponential backoff with jitter, capped at 300 seconds |
|
||||
|
||||
Keep character units explicit; leave `token_count` null unless actually calculated. The adapter must additionally enforce the selected model's input and batch limits.
|
||||
|
||||
Embedding endpoint, API key, model, and vector dimension are required deployment configuration, with no silently chosen production model. Freeze dimension before creating `vector(D)`; worker startup must reject schema/profile incompatibility. Equal dimensions alone do not establish model compatibility.
|
||||
|
||||
The hosted adapter must map returned vectors using response indexes and only send optional dimension parameters when supported. These requirements follow the [official embedding API contract](https://developers.openai.com/api/reference/resources/embeddings/methods/create). Other compatible endpoints require their own compatibility check.
|
||||
|
||||
## 3. Phases and implementation prompts
|
||||
|
||||
Run these phases sequentially. For each phase, use the following shared instruction followed by its phase prompt.
|
||||
|
||||
**Shared instruction**
|
||||
|
||||
```text
|
||||
Use $implement-feature. Read AGENTS.md, applicable nested instructions, and
|
||||
data/documents/agent-reference-map.md. Follow the referenced Phase 1
|
||||
database and ingestion workflow contracts.
|
||||
|
||||
Implement only the requested phase and its necessary tests. Inspect the
|
||||
current repository and previous phase outputs first. Preserve unrelated
|
||||
working-tree changes, including untracked specifications.
|
||||
|
||||
Keep original documents immutable, use direct document_id references,
|
||||
and preserve processing-profile metadata. Keep the ingestion CLI and
|
||||
worker independent of the prototype chat/retriever initialization.
|
||||
|
||||
Do not add upload APIs, selection UI, a broker, document versions, or
|
||||
chat/Live changes. Ordinary tests must not call real providers. Test
|
||||
database constraints and concurrency against isolated PostgreSQL with
|
||||
pgvector.
|
||||
|
||||
Update setup instructions and the reference map when commands or source
|
||||
locations change. Report implemented behavior, exact checks and results,
|
||||
and remaining limitations. Do not claim unexecuted checks passed.
|
||||
```
|
||||
|
||||
### Phase 1 — Database and application foundation
|
||||
|
||||
**Outcome:** A reproducible database schema and isolated ingestion configuration.
|
||||
|
||||
```text
|
||||
Implement Phase 1: ingestion foundation.
|
||||
|
||||
Create a dependency manifest and pytest setup. Add SQLAlchemy/Psycopg
|
||||
database access, Alembic migrations, and pgvector support.
|
||||
|
||||
Create the contract-defined organizations, users, organization_settings,
|
||||
documents, ingestion_jobs, document_chunks, and audit_events tables in
|
||||
dependency order. Include scoped foreign keys, state checks, request-key
|
||||
uniqueness, one job per document, and unique document/ordinal chunks.
|
||||
Do not create conversation or Live tables for this milestone.
|
||||
|
||||
Require the embedding model and dimension as deployment inputs. Configure
|
||||
vector(D) explicitly at initial migration; never rewrite applied migrations
|
||||
when environment settings change. Add schema/profile compatibility checks.
|
||||
|
||||
Implement the configurable limits from this plan and separate ingestion
|
||||
settings from prototype chat credentials. Add provider-neutral processing
|
||||
types and narrow repository/FileStore/EmbeddingProvider interfaces.
|
||||
|
||||
Provide a trusted operator bootstrap command for the initial organization
|
||||
and administrator, using a securely supplied password and maintained
|
||||
password hashing. Do not implement HTTP authentication yet.
|
||||
|
||||
Acceptance: migrations work on an empty PostgreSQL/pgvector database;
|
||||
invalid states, cross-organization references, and duplicate chunk
|
||||
ordinals are rejected. Ingestion modules import without provider calls,
|
||||
model downloads, corpus scanning, or chat credentials.
|
||||
```
|
||||
|
||||
### Phase 2 — Durable document intake
|
||||
|
||||
**Outcome:** Importing a file safely creates one immutable original and one queued job.
|
||||
|
||||
```text
|
||||
Implement Phase 2: local document intake.
|
||||
|
||||
Add `python -m app.ingest import`, accepting an explicit file path,
|
||||
administrator ID, UUID idempotency key, and optional title. Resolve the
|
||||
organization from the enabled administrator record. This is a trusted
|
||||
operator command, not an HTTP authorization substitute.
|
||||
|
||||
Validate size, supported format, safe display filename, and content/type
|
||||
consistency. Store originals using generated keys, temporary writes,
|
||||
and atomic finalization. Hash original bytes and normalized title.
|
||||
|
||||
Create document, queued job, and upload audit in one short transaction.
|
||||
Snapshot the processing profile. Same key and payload returns the same
|
||||
document/job IDs; changed payload conflicts. Different keys create
|
||||
independent documents even for identical bytes.
|
||||
|
||||
Add `python -m app.ingest status` with structured document/job output.
|
||||
New documents are inactive, with zero published chunks.
|
||||
|
||||
Handle duplicate-import races and unused temporary files. Provide a
|
||||
report-only reconciliation command for orphan files and missing originals;
|
||||
do not introduce physical document purging.
|
||||
|
||||
Acceptance: originals survive restart, replay is stable under concurrency,
|
||||
changed-payload conflicts work, filenames cannot escape storage, and
|
||||
failed database writes cannot create acknowledged jobs.
|
||||
```
|
||||
|
||||
### Phase 3 — Extraction, normalization, and chunking
|
||||
|
||||
**Outcome:** A stored original produces deterministic, traceable chunk drafts.
|
||||
|
||||
```text
|
||||
Implement Phase 3: PDF/Markdown processing.
|
||||
|
||||
Read originals through FileStore. Verify retained bytes against the stored
|
||||
hash. Extract PDF text page by page and decode Markdown as UTF-8.
|
||||
|
||||
Normalize line endings and Unicode conservatively. Preserve Persian
|
||||
characters and ZWNJ, Markdown code indentation, paragraphs, and headings.
|
||||
Avoid destructive whitespace collapsing or rewriting document meaning.
|
||||
|
||||
Create extracted blocks with page/section metadata. PDF pages are 1-based;
|
||||
Markdown has page=null. Never invent unavailable locations. Fail empty,
|
||||
corrupt, encrypted, and detected unsupported scanned content visibly.
|
||||
Report extraction limitations instead of claiming OCR or table fidelity.
|
||||
|
||||
Chunk deterministically within page/section boundaries, preferring
|
||||
paragraph and line boundaries. Default to 1000 characters with 200
|
||||
characters overlap; validate overlap < size. Split oversized blocks,
|
||||
discard empty output, and assign contiguous zero-based ordinals.
|
||||
Preserve heading context and source location.
|
||||
|
||||
Enforce configured page, extracted-character, and chunk limits during
|
||||
processing. Exceeding a limit fails the document; never silently truncate.
|
||||
|
||||
Acceptance: fixtures cover Markdown headings/code, English and Persian,
|
||||
text PDFs, blank/scanned PDFs, malformed input, overlap, oversized
|
||||
paragraphs, deterministic ordering, and configurable limits.
|
||||
```
|
||||
|
||||
### Phase 4 — Embeddings and memory staging
|
||||
|
||||
**Outcome:** Every chunk has a validated vector before publication is possible.
|
||||
|
||||
```text
|
||||
Implement Phase 4: embedding adapter and staging.
|
||||
|
||||
Implement one OpenAI-compatible hosted embedding adapter with separately
|
||||
configured endpoint, secret, model, dimension, timeout, and batch limits.
|
||||
Keep credentials server-side and provider objects inside the adapter.
|
||||
|
||||
Implement profile-specific input/batch limit validation. Require compatible
|
||||
token counting where the selected endpoint uses token limits. Do not
|
||||
assume character count equals token count or silently truncate inputs.
|
||||
|
||||
Embed batches outside database transactions. Map responses by returned
|
||||
index and validate completeness, unique indexes, dimension, finite values,
|
||||
and nonzero vectors suitable for cosine distance.
|
||||
|
||||
Accumulate chunk text, metadata, and vectors in a bounded in-memory staged
|
||||
document. Require exactly one vector per ordinal and one consistent
|
||||
profile. Exceeding the memory budget fails explicitly.
|
||||
|
||||
Do not write document_chunks here. Any failed batch makes the staged
|
||||
document unpublishable. Release staging after completion or failure.
|
||||
Normalize provider errors into transient and permanent categories; leave
|
||||
automatic job retries to the worker to avoid stacked retry budgets.
|
||||
|
||||
Acceptance: fake-provider tests cover shuffled responses, missing and
|
||||
duplicate indexes, wrong dimensions, NaN/infinite/zero vectors, timeouts,
|
||||
rate limits, permanent errors, and staging limits. A failed final batch
|
||||
must leave zero published chunks.
|
||||
```
|
||||
|
||||
### Phase 5 — Durable worker and atomic publication
|
||||
|
||||
**Outcome:** The full pipeline runs safely across failures and restarts.
|
||||
|
||||
```text
|
||||
Implement Phase 5: worker orchestration and atomic publication.
|
||||
|
||||
Add `python -m app.worker`, with continuous polling and a --once mode
|
||||
that processes at most one eligible job.
|
||||
|
||||
Claim eligible queued or expired jobs with SKIP LOCKED, a fresh claim
|
||||
token, lease, and incremented attempt count. Exclude deleted documents.
|
||||
Commit claims quickly and use the documented document-before-job lock
|
||||
order for subsequent updates.
|
||||
|
||||
Run extract -> chunk -> embed -> publish with durable stage reporting.
|
||||
Maintain heartbeats during extraction and provider waits. Fence all
|
||||
progress, heartbeat, retry, failure, and publication writes by the claim
|
||||
token and valid lease. A stale worker must discard its results.
|
||||
|
||||
Publish in one transaction: lock document then job; verify ownership,
|
||||
unexpired lease, eligible document state, non-deletion, original/profile
|
||||
compatibility, and complete staged results; insert all chunks; update
|
||||
chunk_count/ready_at/status and mark the job succeeded. Keep is_active=false.
|
||||
Never republish a ready document.
|
||||
|
||||
Rollback everything on publication failure. Recover ambiguous commit
|
||||
outcomes by re-reading durable state before retrying. A successful commit
|
||||
followed by a worker crash must not duplicate chunks.
|
||||
|
||||
Schedule transient failures with bounded backoff/jitter. Fail permanent
|
||||
errors immediately and exhausted jobs terminally. Crash recovery reruns
|
||||
the entire document; no batch checkpoints.
|
||||
|
||||
Add `python -m app.ingest retry` for eligible failed documents, with an
|
||||
idempotency key and administrator validation. Reuse the same document/job,
|
||||
reset attempts, increment retry_generation once, and audit atomically.
|
||||
|
||||
Acceptance: real database tests cover concurrent claims, lease expiry,
|
||||
stale worker writes, late provider responses, exhausted recovery,
|
||||
publication rollback, ambiguous completion, and retry replay.
|
||||
```
|
||||
|
||||
### Phase 6 — Integration proof and handoff
|
||||
|
||||
**Outcome:** A reproducible demonstration proves the pipeline's guarantees.
|
||||
|
||||
```text
|
||||
Implement Phase 6: integration validation and operator handoff.
|
||||
|
||||
Build end-to-end tests using isolated PostgreSQL/pgvector, a temporary
|
||||
original-file directory, real extractors, and a deterministic fake
|
||||
embedding provider.
|
||||
|
||||
Prove that chunks remain absent while embedding batches are incomplete,
|
||||
then appear together with ready/succeeded state after publication.
|
||||
Verify exact row count, contiguous ordinals, source locations, profile,
|
||||
and vector dimension. Confirm documents remain inactive.
|
||||
|
||||
Exercise crashes before publication and after commit, a failed final
|
||||
embedding batch, expired claims, deletion before publication, missing
|
||||
originals, duplicate imports, and idempotent manual retry.
|
||||
|
||||
Add worker heartbeat reporting and redacted logs containing document/job
|
||||
IDs and stage/error categories. Document setup, migration, bootstrap,
|
||||
import, status, retry, worker, and reconciliation commands.
|
||||
|
||||
Provide a separate opt-in real-provider smoke command requiring explicit
|
||||
corpus and provider configuration. Keep it out of ordinary tests and
|
||||
report provider compatibility and extraction quality separately.
|
||||
|
||||
Update README and the reference map. Clearly document that the existing
|
||||
chat retriever still uses Chroma and that pgvector search/selection is
|
||||
the next milestone.
|
||||
```
|
||||
|
||||
## 4. Final acceptance criteria
|
||||
|
||||
This milestone is complete when:
|
||||
|
||||
- A PDF or Markdown import creates a durable, independent document and job.
|
||||
- Extraction and chunking preserve usable evidence locations.
|
||||
- **Every chunk is embedded before any chunk is published.**
|
||||
- Publication commits all chunks and completion state together.
|
||||
- Failures, restarts, duplicate requests, and stale workers cannot create partial or duplicate publication.
|
||||
- Configuration overrides work and processing profiles remain traceable.
|
||||
- Published documents remain inactive until a later authorized selection workflow.
|
||||
- Automated PostgreSQL evidence and documented operator commands support these claims; real-provider validation is reported separately.
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Online migrations scope bookkeeping and validate relation ownership before writes."""
|
||||
from alembic import context
|
||||
from sqlalchemy import create_engine, pool, text
|
||||
|
||||
from app.infrastructure.database import assert_foundation_scope, check_compatibility
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
|
||||
|
||||
def migrate(connection, settings):
|
||||
schema = context.config.attributes.get("application_schema")
|
||||
if schema is None:
|
||||
schema = connection.execute(text("SELECT current_schema()")).scalar_one()
|
||||
if not schema:
|
||||
raise RuntimeError("An existing application schema is required")
|
||||
# Historical SQL stays unchanged; check its name resolution before downgrade.
|
||||
assert_foundation_scope(connection, schema, require_all=False)
|
||||
if connection.dialect.has_table(connection, "alembic_version", schema=schema):
|
||||
quoted = connection.dialect.identifier_preparer.quote_schema(schema)
|
||||
revision = connection.execute(text(
|
||||
f"SELECT version_num FROM {quoted}.alembic_version"
|
||||
)).scalar_one_or_none()
|
||||
if revision is not None:
|
||||
assert_foundation_scope(connection, schema)
|
||||
if context.config.attributes.get("connection") is None:
|
||||
# Preflight reads must not keep the standalone CLI transaction open.
|
||||
connection.commit()
|
||||
context.configure(connection=connection, version_table_schema=schema)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations(settings=settings)
|
||||
assert_foundation_scope(connection, schema, require_all=False)
|
||||
if connection.dialect.has_table(connection, "document_chunks", schema=schema):
|
||||
check_compatibility(connection, settings.embedding_profile)
|
||||
|
||||
|
||||
def run_migrations():
|
||||
if context.is_offline_mode():
|
||||
raise RuntimeError("Use online migration so the pinned profile can be verified")
|
||||
settings = context.config.attributes.get("ingestion_settings") or IngestionSettings()
|
||||
supplied = context.config.attributes.get("connection")
|
||||
if supplied is not None:
|
||||
migrate(supplied, settings)
|
||||
return
|
||||
engine = create_engine(
|
||||
settings.database_url.get_secret_value(), poolclass=pool.NullPool,
|
||||
hide_parameters=True,
|
||||
)
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
migrate(connection, settings)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
run_migrations()
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Initial ingestion schema. This revision is a frozen snapshot, not runtime metadata."""
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0001_ingestion_foundation"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade(settings, **kwargs):
|
||||
dimension = settings.embedding_dimensions
|
||||
if not isinstance(dimension, int) or dimension <= 0:
|
||||
raise ValueError("An explicit positive embedding dimension is required")
|
||||
op.execute("CREATE EXTENSION IF NOT EXISTS vector")
|
||||
# Integer validation above is required before interpolation into a SQL type.
|
||||
sql = SCHEMA.replace("vector(D)", f"vector({dimension})")
|
||||
for statement in sql.split(";"):
|
||||
if statement.strip():
|
||||
op.execute(statement)
|
||||
# The column comment pins full model identity without an extra product table.
|
||||
profile = json.dumps(asdict(settings.embedding_profile), sort_keys=True)
|
||||
escaped = profile.replace("'", "''")
|
||||
op.get_bind().exec_driver_sql(f"COMMENT ON COLUMN document_chunks.embedding IS '{escaped}'")
|
||||
|
||||
|
||||
def downgrade(**kwargs):
|
||||
for table in (
|
||||
"audit_events", "document_chunks", "ingestion_jobs", "documents",
|
||||
"organization_settings", "users", "organizations",
|
||||
):
|
||||
op.execute(f"DROP TABLE {table}")
|
||||
# Do not remove an extension potentially shared with other schemas.
|
||||
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE organizations (
|
||||
id uuid PRIMARY KEY, name varchar(200) NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY, organization_id uuid NOT NULL REFERENCES organizations(id),
|
||||
username varchar(120) NOT NULL UNIQUE,
|
||||
password_hash text NOT NULL, role text NOT NULL CHECK (role IN ('admin','user')),
|
||||
is_enabled boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (organization_id,id),
|
||||
CHECK (username = lower(username) AND length(trim(username)) > 0)
|
||||
);
|
||||
CREATE TABLE organization_settings (
|
||||
organization_id uuid PRIMARY KEY REFERENCES organizations(id),
|
||||
assistant_name varchar(120) NOT NULL, instruction text NOT NULL,
|
||||
revision bigint NOT NULL DEFAULT 1 CHECK (revision >= 1),
|
||||
knowledge_revision bigint NOT NULL DEFAULT 1 CHECK (knowledge_revision >= 1),
|
||||
access_epoch bigint NOT NULL DEFAULT 1 CHECK (access_epoch >= 1),
|
||||
updated_by uuid, updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
FOREIGN KEY (organization_id,updated_by) REFERENCES users(organization_id,id)
|
||||
);
|
||||
CREATE TABLE documents (
|
||||
id uuid PRIMARY KEY, organization_id uuid NOT NULL REFERENCES organizations(id),
|
||||
uploaded_by uuid NOT NULL, title varchar(200) NOT NULL, original_filename text NOT NULL,
|
||||
upload_request_id uuid NOT NULL,
|
||||
upload_payload_hash char(64) NOT NULL CHECK (upload_payload_hash ~ '^[0-9a-f]{64}$'),
|
||||
storage_key text NOT NULL UNIQUE,
|
||||
file_sha256 char(64) NOT NULL CHECK (file_sha256 ~ '^[0-9a-f]{64}$'),
|
||||
mime_type text NOT NULL, size_bytes bigint NOT NULL CHECK (size_bytes > 0),
|
||||
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','processing','ready','failed')),
|
||||
processing_profile jsonb NOT NULL DEFAULT '{}',
|
||||
chunk_count integer NOT NULL DEFAULT 0 CHECK (chunk_count >= 0),
|
||||
ready_at timestamptz, is_active boolean NOT NULL DEFAULT false,
|
||||
deleted_at timestamptz, content_purged_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (organization_id,id), UNIQUE (organization_id,upload_request_id),
|
||||
FOREIGN KEY (organization_id,uploaded_by) REFERENCES users(organization_id,id),
|
||||
CHECK (status <> 'ready' OR (ready_at IS NOT NULL AND chunk_count > 0)),
|
||||
CHECK (NOT is_active OR (status = 'ready' AND deleted_at IS NULL AND content_purged_at IS NULL))
|
||||
);
|
||||
CREATE TABLE ingestion_jobs (
|
||||
id uuid PRIMARY KEY, organization_id uuid NOT NULL REFERENCES organizations(id),
|
||||
document_id uuid NOT NULL UNIQUE,
|
||||
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','processing','succeeded','failed')),
|
||||
stage text NOT NULL DEFAULT 'extract' CHECK (stage IN ('extract','chunk','embed','publish')),
|
||||
attempt_count integer NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
|
||||
retry_generation integer NOT NULL DEFAULT 0 CHECK (retry_generation >= 0),
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
claim_token uuid, lease_expires_at timestamptz, claimed_by text,
|
||||
error_code text, error_message text, error_retryable boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (organization_id,id),
|
||||
FOREIGN KEY (organization_id,document_id) REFERENCES documents(organization_id,id),
|
||||
CHECK ((status = 'processing' AND claim_token IS NOT NULL AND lease_expires_at IS NOT NULL)
|
||||
OR (status <> 'processing' AND claim_token IS NULL AND lease_expires_at IS NULL))
|
||||
);
|
||||
CREATE INDEX ingestion_jobs_eligible ON ingestion_jobs(status,next_attempt_at);
|
||||
CREATE INDEX ingestion_jobs_expired ON ingestion_jobs(lease_expires_at) WHERE status = 'processing';
|
||||
CREATE TABLE document_chunks (
|
||||
id uuid PRIMARY KEY, organization_id uuid NOT NULL REFERENCES organizations(id),
|
||||
document_id uuid NOT NULL, ordinal integer NOT NULL CHECK (ordinal >= 0),
|
||||
text text NOT NULL CHECK (length(text) > 0), location jsonb NOT NULL DEFAULT '{}',
|
||||
token_count integer CHECK (token_count >= 0),
|
||||
embedding vector(D) NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (organization_id,id), UNIQUE (document_id,ordinal),
|
||||
FOREIGN KEY (organization_id,document_id) REFERENCES documents(organization_id,id),
|
||||
CHECK (jsonb_typeof(location) = 'object'),
|
||||
CHECK (NOT (location ? 'page') OR location->'page' = 'null'::jsonb OR
|
||||
(jsonb_typeof(location->'page') = 'number'
|
||||
AND (location->>'page') ~ '^[1-9][0-9]*$'))
|
||||
);
|
||||
CREATE INDEX document_chunks_document ON document_chunks(document_id);
|
||||
CREATE TABLE audit_events (
|
||||
id uuid PRIMARY KEY, organization_id uuid NOT NULL REFERENCES organizations(id),
|
||||
actor_user_id uuid, action text NOT NULL, target_id uuid, request_id text,
|
||||
idempotency_key uuid,
|
||||
request_hash char(64) CHECK (request_hash IS NULL OR request_hash ~ '^[0-9a-f]{64}$'),
|
||||
response_json jsonb, metadata jsonb NOT NULL DEFAULT '{}',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (organization_id,id),
|
||||
FOREIGN KEY (organization_id,actor_user_id) REFERENCES users(organization_id,id),
|
||||
CHECK (action IN ('upload','selection_changed','document_deleted','ingestion_retry',
|
||||
'configuration_changed','session_revoked')),
|
||||
CHECK (action NOT IN ('document_deleted','ingestion_retry')
|
||||
OR (actor_user_id IS NOT NULL AND target_id IS NOT NULL AND idempotency_key IS NOT NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX audit_events_replay
|
||||
ON audit_events(organization_id,actor_user_id,action,target_id,idempotency_key)
|
||||
WHERE idempotency_key IS NOT NULL;
|
||||
"""
|
||||
@@ -0,0 +1,30 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=75"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "rag-technical-docs-assistant"
|
||||
version = "0.1.0"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"SQLAlchemy>=2.0.36,<2.1", "psycopg[binary]>=3.2.3,<4",
|
||||
"alembic>=1.14,<2", "pgvector>=0.3.6,<1",
|
||||
"pydantic-settings>=2.7,<3", "argon2-cffi>=23.1,<26",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = ["pytest>=8.3,<10"]
|
||||
prototype = [
|
||||
"fastapi>=0.115,<1", "uvicorn>=0.34,<1", "langgraph>=1,<2",
|
||||
"langchain>=1,<2", "langchain-openai>=1,<2", "langchain-chroma>=1,<2",
|
||||
"langchain-community>=0.4,<1", "langchain-text-splitters>=1,<2",
|
||||
"chromadb>=1,<2", "fastembed>=0.7,<1",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["app*"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-ra"
|
||||
markers = ["postgres: requires an isolated PostgreSQL database with pgvector"]
|
||||
@@ -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.
|
||||
@@ -0,0 +1 @@
|
||||
"""Foundation regression tests."""
|
||||
@@ -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,
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""Foundation test package."""
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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})
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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})
|
||||
@@ -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())
|
||||
@@ -0,0 +1 @@
|
||||
"""Foundation test package."""
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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