|
| 1 | +"""Validate staged embeddings and optionally apply them with an atomic backup. |
| 2 | +
|
| 3 | +Retrieval must be paused and the query provider coordinated before --apply. |
| 4 | +Validation is read-only by default. No Google credentials or API calls are needed. |
| 5 | +""" |
| 6 | + |
| 7 | +import argparse |
| 8 | +import asyncio |
| 9 | +import json |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +from sqlalchemy import text |
| 13 | +from sqlalchemy.ext.asyncio import create_async_engine |
| 14 | + |
| 15 | +from app.utils.google_embedder import DOCUMENT_MAX_BYTES |
| 16 | +from scripts.database.reembed_chunks_in_db import ( |
| 17 | + _quote_identifier, |
| 18 | + normalize_database_url, |
| 19 | + rewrite_container_hostname, |
| 20 | + validate_table_name, |
| 21 | +) |
| 22 | +from scripts.database.reembedding_utils import project_root, read_env_value |
| 23 | + |
| 24 | + |
| 25 | +async def promote_embeddings( |
| 26 | + database_url: str, |
| 27 | + target_table: str, |
| 28 | + *, |
| 29 | + source_table: str = "chunks", |
| 30 | + backup_table: str = "chunks_embeddings_before_google", |
| 31 | + model: str = "gemini-embedding-001", |
| 32 | + apply: bool = False, |
| 33 | +) -> int: |
| 34 | + names = [source_table, target_table, backup_table] |
| 35 | + if len(set(names)) != 3: |
| 36 | + raise ValueError("Source, staging and backup tables must be different.") |
| 37 | + source, target, backup = [ |
| 38 | + _quote_identifier(validate_table_name(name)) for name in names |
| 39 | + ] |
| 40 | + engine = create_async_engine( |
| 41 | + normalize_database_url(rewrite_container_hostname(database_url)) |
| 42 | + ) |
| 43 | + try: |
| 44 | + async with engine.begin() as conn: |
| 45 | + if apply: |
| 46 | + locked = ( |
| 47 | + await conn.execute( |
| 48 | + text("SELECT pg_try_advisory_xact_lock(hashtext(:name))"), |
| 49 | + {"name": target_table}, |
| 50 | + ) |
| 51 | + ).scalar_one() |
| 52 | + if not locked: |
| 53 | + raise ValueError("A migration is still using this staging table.") |
| 54 | + await conn.execute(text("SET LOCAL lock_timeout = '10s'")) |
| 55 | + # Block ingestion/staging writes until validation, backup and update commit. |
| 56 | + await conn.execute( |
| 57 | + text(f"LOCK TABLE {source}, {target} IN SHARE ROW EXCLUSIVE MODE") |
| 58 | + ) |
| 59 | + else: |
| 60 | + await conn.execute( |
| 61 | + text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") |
| 62 | + ) |
| 63 | + comment = ( |
| 64 | + await conn.execute( |
| 65 | + text("SELECT obj_description(to_regclass(:name), 'pg_class')"), |
| 66 | + {"name": target}, |
| 67 | + ) |
| 68 | + ).scalar_one() |
| 69 | + manifest = json.loads(comment or "null") |
| 70 | + expected = { |
| 71 | + "migration": "twiga-reembedding-v1", |
| 72 | + "source": source_table, |
| 73 | + "provider": "google", |
| 74 | + "model": model, |
| 75 | + "dimensions": 1024, |
| 76 | + "task_type": "RETRIEVAL_DOCUMENT", |
| 77 | + "document_max_bytes": DOCUMENT_MAX_BYTES, |
| 78 | + "max_token_estimate": None, |
| 79 | + } |
| 80 | + if not isinstance(manifest, dict) or any( |
| 81 | + manifest.get(k) != v for k, v in expected.items() |
| 82 | + ): |
| 83 | + raise ValueError( |
| 84 | + "Staging manifest does not match the requested Google embedding configuration." |
| 85 | + ) |
| 86 | + count = ( |
| 87 | + await conn.execute(text(f"SELECT count(*) FROM {source}")) |
| 88 | + ).scalar_one() |
| 89 | + if not count: |
| 90 | + raise ValueError("Refusing to promote an empty corpus.") |
| 91 | + mismatches = ( |
| 92 | + await conn.execute( |
| 93 | + text( |
| 94 | + f""" |
| 95 | + SELECT count(*) FROM {source} s FULL JOIN {target} t USING (id) |
| 96 | + WHERE s.id IS NULL OR t.id IS NULL |
| 97 | + OR (to_jsonb(s) - 'embedding') IS DISTINCT FROM (to_jsonb(t) - 'embedding') |
| 98 | + OR t.embedding IS NULL OR vector_dims(t.embedding) <> 1024 |
| 99 | + OR (t.embedding <#> t.embedding) >= 0 |
| 100 | + """ |
| 101 | + ) |
| 102 | + ) |
| 103 | + ).scalar_one() |
| 104 | + if mismatches: |
| 105 | + raise ValueError( |
| 106 | + f"{mismatches} chunks are missing, changed or have invalid/incomplete embeddings." |
| 107 | + ) |
| 108 | + if apply: |
| 109 | + # CREATE (without IF NOT EXISTS) prevents overwriting an earlier backup. |
| 110 | + await conn.execute( |
| 111 | + text(f"CREATE TABLE {backup} AS SELECT id, embedding FROM {source}") |
| 112 | + ) |
| 113 | + await conn.execute(text(f"ALTER TABLE {backup} ADD PRIMARY KEY (id)")) |
| 114 | + result = await conn.execute( |
| 115 | + text( |
| 116 | + f"UPDATE {source} s SET embedding = t.embedding FROM {target} t WHERE s.id = t.id" |
| 117 | + ) |
| 118 | + ) |
| 119 | + if result.rowcount != count: |
| 120 | + raise ValueError( |
| 121 | + "Updated row count does not match the validated corpus." |
| 122 | + ) |
| 123 | + return count |
| 124 | + finally: |
| 125 | + await engine.dispose() |
| 126 | + |
| 127 | + |
| 128 | +def main() -> None: |
| 129 | + parser = argparse.ArgumentParser(description=__doc__) |
| 130 | + parser.add_argument("--env-file", type=Path, default=project_root() / ".env") |
| 131 | + parser.add_argument("--target-table-name", default="chunks_tmp_reembed") |
| 132 | + parser.add_argument("--source-table-name", default="chunks") |
| 133 | + parser.add_argument( |
| 134 | + "--backup-table-name", default="chunks_embeddings_before_google" |
| 135 | + ) |
| 136 | + parser.add_argument("--model", default="gemini-embedding-001") |
| 137 | + parser.add_argument( |
| 138 | + "--apply", |
| 139 | + action="store_true", |
| 140 | + help="Apply validated vectors and save old vectors. Requires coordinated retrieval downtime.", |
| 141 | + ) |
| 142 | + args = parser.parse_args() |
| 143 | + database_url = read_env_value("DATABASE_URL", env_file=args.env_file) |
| 144 | + if not database_url: |
| 145 | + raise ValueError("DATABASE_URL is required.") |
| 146 | + count = asyncio.run( |
| 147 | + promote_embeddings( |
| 148 | + database_url, |
| 149 | + args.target_table_name, |
| 150 | + source_table=args.source_table_name, |
| 151 | + backup_table=args.backup_table_name, |
| 152 | + model=args.model, |
| 153 | + apply=args.apply, |
| 154 | + ) |
| 155 | + ) |
| 156 | + print( |
| 157 | + f"{'Applied and backed up' if args.apply else 'Validated'} {count} chunk embeddings." |
| 158 | + ) |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + main() |
0 commit comments