Files
rag-technical-docs-assistant/data/documents/RAG-Phase1-Database-Design (1).md
T
amirhosein mazaheri baf58da562 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.
2026-10-05 16:38:28 +03:30

23 KiB

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

 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):

{"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):

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.