#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Migrate the RAG corpus to a different embedding model. Embeddings are only comparable to other embeddings from the SAME model, so changing models means re-embedding everything. There is no partial state worth having: a corpus half in one vector space and half in another returns confident nonsense with no error anywhere. What this does, in order: 1. Verify the configured remote model really returns EMBED_DIMENSIONS. 2. Drop the HNSW indexes (ALTER TYPE cannot rewrite an indexed vector column). 3. ALTER every *.embedding column to the new width, clearing old vectors. 4. Re-embed every chunk through the configured provider. 5. Rebuild the HNSW indexes. 6. Report anything left unembedded. Run with --dry-run first. Documents whose chunks cannot be re-embedded are left with NULL vectors and reported; they are invisible to retrieval until re-ingested, which is the honest outcome — better than a silently half-indexed corpus. python app_tools/migrate_embedding_model.py --dry-run python app_tools/migrate_embedding_model.py --apply """ from __future__ import annotations import argparse import asyncio import logging import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import httpx from sqlalchemy import text as sql from app.config import get_settings from app.database import get_rag_session, init_db from app.services.embed import EmbedService logging.basicConfig(level=logging.INFO, format="%(levelname)-7s %(message)s") logger = logging.getLogger("migrate") # Every table holding vectors that must move together. # rag_topics carries topic embeddings — it must move with the others, or topic # lookup silently compares vectors from two different models. VECTOR_TABLES = ("rag_chunks", "element_embeddings", "rag_topics") # (index name, table, column) — dropped before the ALTER, rebuilt after. HNSW_INDEXES = ( ("idx_rag_chunks_hnsw", "rag_chunks", "embedding"), ("idx_element_embeddings_hnsw", "element_embeddings", "embedding"), ) async def verify_provider(settings) -> int: """Confirm the configured model returns the width we are about to commit to.""" svc = EmbedService() async with httpx.AsyncClient(timeout=60) as client: result = (await svc._embed_remote_batch(["فحص الأبعاد"], client=client))[0] dims = len(result.embedding) logger.info("Provider %s returned %d dims", settings.EMBED_REMOTE_MODEL, dims) if dims != settings.EMBED_DIMENSIONS: raise SystemExit( f"ABORT: provider returns {dims} dims but EMBED_DIMENSIONS is " f"{settings.EMBED_DIMENSIONS}. Fix the config before migrating." ) return dims async def current_state(session) -> None: rows = (await session.execute(sql(""" SELECT c.relname, a.atttypmod FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname='public' AND a.attname='embedding' AND c.relkind='r' AND a.attnum > 0 """))).fetchall() for r in rows: logger.info(" %-22s vector(%s)", r[0], r[1]) for table in VECTOR_TABLES: n = (await session.execute(sql(f"SELECT count(*) FROM {table}"))).scalar() logger.info(" %-22s %d rows", table, n) async def migrate(dims: int, apply: bool) -> None: settings = get_settings() await init_db() async with get_rag_session() as session: logger.info("Current state:") await current_state(session) if not apply: logger.info("DRY RUN — nothing changed. Re-run with --apply.") return logger.info("Dropping HNSW indexes …") for name, _table, _col in HNSW_INDEXES: await session.execute(sql(f"DROP INDEX IF EXISTS {name}")) logger.info("Altering vector columns to vector(%d) …", dims) for table in VECTOR_TABLES: # Old vectors are unusable in the new space; clearing them first # makes the ALTER cheap and the "not yet re-embedded" state explicit. await session.execute(sql(f"UPDATE {table} SET embedding = NULL")) await session.execute(sql( f"ALTER TABLE {table} ALTER COLUMN embedding TYPE vector({dims})" )) await session.commit() logger.info("Columns migrated.") # ── Re-embed ──────────────────────────────────────────────────────────── svc = EmbedService() async with httpx.AsyncClient(timeout=settings.EMBED_REMOTE_TIMEOUT * 2) as client: async with get_rag_session() as session: rows = (await session.execute(sql( "SELECT id, content FROM rag_chunks " "WHERE embedding IS NULL AND content <> '' ORDER BY document_id, chunk_index" ))).fetchall() logger.info("Re-embedding %d chunks …", len(rows)) done = failed = 0 # Taken from the results themselves rather than config, so the # stored label always names the weights that produced the vectors. model_name = settings.EMBED_REMOTE_MODEL batch = svc._batch_max_items for start in range(0, len(rows), batch): window = rows[start:start + batch] results = await svc.embed_batch([r.content for r in window], client=client) for row, res in zip(window, results): if res is None: failed += 1 continue model_name = res.model # ground truth, not configuration await session.execute( sql("UPDATE rag_chunks SET embedding = CAST(:v AS vector) WHERE id = :id"), {"v": EmbedService.to_vector_literal(res.embedding), "id": row.id}, ) done += 1 await session.commit() logger.info(" %d/%d", min(start + batch, len(rows)), len(rows)) # Topics are few (~100 per document) but must move in the same pass: # a topic embedded under the old model would be compared against # chunks embedded under the new one, which returns confident # nonsense rather than an error. topic_rows = (await session.execute(sql( "SELECT id, title, summary FROM rag_topics WHERE embedding IS NULL" ))).fetchall() if topic_rows: logger.info("Re-embedding %d topics …", len(topic_rows)) texts = [ f"{r.title} — {r.summary}" if r.summary else r.title for r in topic_rows ] results = await svc.embed_batch(texts, client=client) for row, res in zip(topic_rows, results): if res is None: failed += 1 continue await session.execute( sql("UPDATE rag_topics SET embedding = CAST(:v AS vector), " "embedding_model = :m WHERE id = :id"), {"v": EmbedService.to_vector_literal(res.embedding), "m": res.model, "id": row.id}, ) done += 1 await session.commit() async with get_rag_session() as session: logger.info("Rebuilding HNSW indexes …") for name, table, col in HNSW_INDEXES: await session.execute(sql( f"CREATE INDEX IF NOT EXISTS {name} ON {table} " f"USING hnsw ({col} vector_cosine_ops)" )) # Re-label the documents. Leaving rag_documents.embedding_model on the # OLD model after re-embedding is worse than leaving it blank: that # column is exactly what you consult to decide whether a document needs # migrating, so a stale value makes an already-migrated corpus look # unmigrated (and vice versa). Only documents that actually have # vectors are relabelled — anything left stranded keeps its old label # so it still reads as needing attention. relabelled = (await session.execute(sql(""" UPDATE rag_documents SET embedding_model = :model WHERE id IN ( SELECT DISTINCT document_id FROM rag_chunks WHERE embedding IS NOT NULL ) """), {"model": model_name})).rowcount await session.commit() logger.info("Re-labelled %d documents as embedded with %s", relabelled, model_name) stranded = (await session.execute(sql( "SELECT count(*) FROM rag_chunks WHERE embedding IS NULL AND content <> ''" ))).scalar() logger.info("Re-embedded %d chunks, %d failed.", done, failed) if stranded: logger.error( "%d chunks still have no vector — they are invisible to retrieval. " "Re-ingest those documents.", stranded, ) else: logger.info("Every chunk has a vector. Migration complete.") logger.info( "NOTE: element_embeddings were cleared but are NOT re-embedded here — " "they are regenerated by the document-graph stage on re-ingest." ) def main() -> None: ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--apply", action="store_true", help="actually perform the migration") ap.add_argument("--dry-run", action="store_true", help="show current state only") args = ap.parse_args() if not args.apply and not args.dry_run: ap.error("pass --dry-run or --apply") settings = get_settings() logger.info("Target model : %s", settings.EMBED_REMOTE_MODEL) logger.info("Target dims : %d", settings.EMBED_DIMENSIONS) logger.info("Local backend: %s", "enabled" if settings.EMBED_LOCAL_ENABLED else "DISABLED (cloud-only)") dims = asyncio.run(verify_provider(settings)) asyncio.run(migrate(dims, apply=args.apply)) if __name__ == "__main__": main()