"""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; """