Skip to content

Commit 36909a0

Browse files
authored
Merge pull request #348 from Tanzania-AI-Community/chore/embedding-transfer-tooling
chore: add tool to transfer re-embedded chunks between databases
2 parents 53111c1 + 01d79c0 commit 36909a0

3 files changed

Lines changed: 541 additions & 0 deletions

File tree

‎docs/embedding-transfer.md‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Transfer existing Google embeddings between Neon branches
2+
3+
`scripts/database/transfer_reembedded_chunks.py` copies an already re-embedded
4+
snapshot into a **new destination staging table**. It does not call Google, update
5+
live chunks, create an old-vector backup, or promote vectors. Promotion remains a
6+
separate operation in `promote_reembedded_chunks.py`.
7+
8+
## Connections and invocation
9+
10+
Run from the Twiga repository with the locked dependencies installed. Put the two
11+
connections in a private file outside the repository, for example
12+
`/tmp/twiga-transfer.env`, with permissions `0600`:
13+
14+
```dotenv
15+
SOURCE_DATABASE_URL=<confirmed dev/adria connection>
16+
DESTINATION_DATABASE_URL=<confirmed production connection used by Render>
17+
```
18+
19+
The source value is the development connection currently stored in
20+
`EVAL_DATABASE_URL`; verify the destination endpoint against Render's production
21+
`DATABASE_URL`. Never paste credentials into chat or commit this file. The script
22+
deliberately does not fall back to `DATABASE_URL` or `EVAL_DATABASE_URL`.
23+
24+
```sh
25+
env -u SOURCE_DATABASE_URL -u DESTINATION_DATABASE_URL \
26+
uv run python -m scripts.database.transfer_reembedded_chunks \
27+
--env-file /tmp/twiga-transfer.env \
28+
--source-table-name chunks_gemini_001_dev_20260918 \
29+
--target-table-name chunks_gemini_001_prod_20260919 \
30+
--batch-size 128
31+
```
32+
33+
The `env -u` options ensure exported shell values cannot override the selected
34+
file. Neon pooled URLs are resolved to their corresponding direct endpoint by
35+
the existing migration utility. Neither the app's `.env` nor Render's connection
36+
configuration is changed.
37+
38+
## Guarantees and failure handling
39+
40+
- Reads the source in a repeatable-read, read-only transaction, requiring the
41+
existing Google migration manifest and complete nonzero 1024-dimensional vectors.
42+
- Creates staging with the live destination table's columns and an ID primary
43+
key. Does not copy its vector index, sequence defaults or foreign keys.
44+
- Streams all fields in bounded batches using PostgreSQL JSON serialization,
45+
avoiding client-side rounding or type conversion of vectors and metadata.
46+
- Verifies row counts and a SHA-256 digest of every ordered record by reading
47+
destination staging back from PostgreSQL. This includes vectors and all metadata.
48+
- Compares staging IDs and all non-embedding fields against the destination's
49+
current live corpus. Missing, extra or changed chunks abort the transfer.
50+
- Publishes the source manifest and commits staging only after every check passes.
51+
- Uses the same advisory-lock key as the migration/promotion scripts. Refuses an
52+
existing target and refuses live/source table names as the destination target.
53+
54+
Progress messages describe uncommitted rows. Unlike the API re-embedding runner,
55+
this transfer uses **one atomic destination transaction**, not resumable batch
56+
commits. Failure before commit removes the entire new table; fix the cause and
57+
rerun. If a connection is lost during commit, inspect whether staging exists before
58+
retrying; an existing table is always protected from overwrite.
59+
60+
The source snapshot and live destination data must correspond. This tool stops
61+
on drift; it does not silently skip or re-embed changed records. Freeze textbook
62+
ingestion during the migration window. Other production tables are untouched.
63+
64+
## After the copy
65+
66+
Successful output is `Copied and verified N chunks. Live embeddings were not
67+
changed.` For the unchanged audited corpus, N should be 72,807.
68+
69+
Use a separate private production migration file containing `DATABASE_URL` and
70+
the existing promotion script to validate the staging table again:
71+
72+
```sh
73+
env -u DATABASE_URL uv run python \
74+
-m scripts.database.promote_reembedded_chunks \
75+
--env-file /tmp/twiga-production-migration.env \
76+
--target-table-name chunks_gemini_001_prod_20260919 \
77+
--backup-table-name chunks_e5_backup_prod_20260919
78+
```
79+
80+
This command is read-only. Only a separately coordinated invocation with
81+
`--apply` backs up old vectors and replaces live embeddings. Do not assume the
82+
successful transfer has fixed production retrieval: it still reads `chunks`.
83+
84+
## Tests
85+
86+
```sh
87+
TWIGA_MIGRATION_TEST_URL=postgresql://user@localhost:55432/postgres \
88+
uv run pytest tests/test_reembedding_database.py -q
89+
```
90+
91+
Use an isolated local test cluster with pgvector available and permission to
92+
create databases. Transfer tests create and remove uniquely named disposable
93+
databases. Coverage includes real cross-database copying, float32/Unicode/JSON/NULL
94+
preservation, compatibility with promotion and backup, drift, incomplete vectors,
95+
invalid manifests, existing targets, schema coercion and interruption/retry.
Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
"""Copy a verified Google snapshot between databases into a new staging table.
2+
3+
Never updates live chunks or calls an embedding API. The destination transaction
4+
commits only after exact copy verification and comparison with its live corpus.
5+
An interrupted/failed transfer rolls back the entire new table; rerun to retry.
6+
"""
7+
8+
import argparse
9+
import asyncio
10+
import hashlib
11+
import json
12+
import logging
13+
from pathlib import Path
14+
15+
from sqlalchemy import text
16+
from sqlalchemy.ext.asyncio import create_async_engine
17+
18+
from app.utils.google_embedder import DOCUMENT_MAX_BYTES
19+
from scripts.database.reembed_chunks_in_db import (
20+
_quote_identifier,
21+
normalize_database_url,
22+
validate_table_name,
23+
)
24+
from scripts.database.reembedding_utils import read_env_value
25+
26+
logger = logging.getLogger(__name__)
27+
28+
29+
def _table(name: str) -> str:
30+
if len(name.encode("utf-8")) > 63:
31+
raise ValueError("Table names must fit PostgreSQL's 63-byte identifier limit.")
32+
return _quote_identifier(validate_table_name(name))
33+
34+
35+
async def transfer_embeddings(
36+
source_database_url: str,
37+
destination_database_url: str,
38+
*,
39+
source_table: str,
40+
target_table: str,
41+
live_table: str = "chunks",
42+
batch_size: int = 128,
43+
model: str = "gemini-embedding-001",
44+
) -> int:
45+
"""Return the verified row count; refuse existing or live-table targets."""
46+
if batch_size < 1:
47+
raise ValueError("batch_size must be positive.")
48+
if target_table in {live_table, source_table, "chunks"}:
49+
raise ValueError(
50+
"Target must be a new staging table, separate from live/source tables."
51+
)
52+
source, target, live = map(_table, (source_table, target_table, live_table))
53+
source_engine = create_async_engine(
54+
normalize_database_url(source_database_url), hide_parameters=True
55+
)
56+
destination_engine = create_async_engine(
57+
normalize_database_url(destination_database_url), hide_parameters=True
58+
)
59+
try:
60+
async with source_engine.begin() as reader:
61+
await reader.execute(
62+
text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
63+
)
64+
comment = (
65+
await reader.execute(
66+
text("SELECT obj_description(to_regclass(:name), 'pg_class')"),
67+
{"name": source},
68+
)
69+
).scalar_one()
70+
manifest = json.loads(comment or "null")
71+
expected = {
72+
"migration": "twiga-reembedding-v1",
73+
"source": live_table,
74+
"provider": "google",
75+
"model": model,
76+
"dimensions": 1024,
77+
"task_type": "RETRIEVAL_DOCUMENT",
78+
"document_max_bytes": DOCUMENT_MAX_BYTES,
79+
"max_token_estimate": None,
80+
}
81+
if not isinstance(manifest, dict) or any(
82+
manifest.get(key) != value for key, value in expected.items()
83+
):
84+
raise ValueError(
85+
"Source manifest does not match the Google configuration."
86+
)
87+
count, invalid = (
88+
await reader.execute(
89+
text(
90+
f"""SELECT count(*), count(*) FILTER (
91+
WHERE embedding IS NULL OR vector_dims(embedding) <> 1024
92+
OR (embedding <#> embedding) >= 0) FROM {source}"""
93+
)
94+
)
95+
).one()
96+
if not count or invalid:
97+
raise ValueError(
98+
"Source snapshot is empty or contains invalid/incomplete vectors."
99+
)
100+
101+
async with destination_engine.begin() as writer:
102+
locked = (
103+
await writer.execute(
104+
text("SELECT pg_try_advisory_xact_lock(hashtext(:name))"),
105+
{"name": target_table},
106+
)
107+
).scalar_one()
108+
if not locked:
109+
raise ValueError("Another migration is using this staging table.")
110+
await writer.execute(text("SET LOCAL lock_timeout = '10s'"))
111+
if (
112+
await writer.execute(
113+
text("SELECT to_regclass(:name)"), {"name": target}
114+
)
115+
).scalar_one() is not None:
116+
raise ValueError(
117+
"Target already exists; it will not be overwritten."
118+
)
119+
# No live vector index, sequence defaults, or foreign keys are copied.
120+
await writer.execute(
121+
text(f"CREATE TABLE {target} (LIKE {live} INCLUDING CONSTRAINTS)")
122+
)
123+
await writer.execute(text(f"ALTER TABLE {target} ADD PRIMARY KEY (id)"))
124+
insert = text(
125+
f"INSERT INTO {target} SELECT * FROM "
126+
f"jsonb_populate_record(NULL::{target}, CAST(:row AS jsonb))"
127+
)
128+
source_digest = hashlib.sha256()
129+
copied = 0
130+
# PostgreSQL's JSON representation round-trips vector float32 values,
131+
# nullable fields and enum/JSON metadata without client-side coercion.
132+
stream = await reader.stream(
133+
text(f"SELECT to_jsonb(s)::text FROM {source} s ORDER BY id"),
134+
execution_options={"yield_per": batch_size},
135+
)
136+
async for batch in stream.partitions(batch_size):
137+
records = []
138+
for (row,) in batch:
139+
source_digest.update(row.encode("utf-8") + b"\n")
140+
records.append({"row": row})
141+
await writer.execute(insert, records)
142+
copied += len(records)
143+
logger.info(
144+
"Transferred %s/%s chunks to staging (not committed)",
145+
copied,
146+
count,
147+
)
148+
149+
destination_digest = hashlib.sha256()
150+
verified = 0
151+
stream = await writer.stream(
152+
text(f"SELECT to_jsonb(t)::text FROM {target} t ORDER BY id"),
153+
execution_options={"yield_per": batch_size},
154+
)
155+
async for batch in stream.partitions(batch_size):
156+
for (row,) in batch:
157+
destination_digest.update(row.encode("utf-8") + b"\n")
158+
verified += 1
159+
if (
160+
copied != count
161+
or verified != count
162+
or source_digest.digest() != destination_digest.digest()
163+
):
164+
raise ValueError(
165+
"Destination copy differs from the source snapshot."
166+
)
167+
mismatches = (
168+
await writer.execute(
169+
text(
170+
f"""SELECT count(*) FROM {live} c
171+
FULL JOIN {target} t USING (id)
172+
WHERE c.id IS NULL OR t.id IS NULL
173+
OR (to_jsonb(c) - 'embedding') IS DISTINCT FROM
174+
(to_jsonb(t) - 'embedding')"""
175+
)
176+
)
177+
).scalar_one()
178+
if mismatches:
179+
raise ValueError(
180+
f"{mismatches} live chunks are missing or changed; staging transfer rolled back."
181+
)
182+
# Publish the recognized manifest only after all checks pass.
183+
literal = json.dumps(manifest, sort_keys=True).replace("'", "''")
184+
await writer.execute(text(f"COMMENT ON TABLE {target} IS '{literal}'"))
185+
logger.info(
186+
"Committed %s verified staging rows; live chunks are unchanged", count
187+
)
188+
return count
189+
finally:
190+
await source_engine.dispose()
191+
await destination_engine.dispose()
192+
193+
194+
def main() -> None:
195+
parser = argparse.ArgumentParser(description=__doc__)
196+
parser.add_argument("--env-file", required=True, type=Path)
197+
parser.add_argument("--source-table-name", required=True)
198+
parser.add_argument("--target-table-name", required=True)
199+
parser.add_argument("--live-table-name", default="chunks")
200+
parser.add_argument("--batch-size", type=int, default=128)
201+
args = parser.parse_args()
202+
# Deliberately never fall back to the app's DATABASE_URL or EVAL_DATABASE_URL.
203+
source_url = read_env_value("SOURCE_DATABASE_URL", env_file=args.env_file)
204+
destination_url = read_env_value("DESTINATION_DATABASE_URL", env_file=args.env_file)
205+
if not source_url or not destination_url:
206+
parser.error("SOURCE_DATABASE_URL and DESTINATION_DATABASE_URL are required.")
207+
try:
208+
count = asyncio.run(
209+
transfer_embeddings(
210+
source_url,
211+
destination_url,
212+
source_table=args.source_table_name,
213+
target_table=args.target_table_name,
214+
live_table=args.live_table_name,
215+
batch_size=args.batch_size,
216+
)
217+
)
218+
except Exception as exc:
219+
# SQL/driver exceptions can contain credentials or full chunk text.
220+
message = str(exc) if isinstance(exc, ValueError) else type(exc).__name__
221+
parser.exit(1, f"Transfer failed; no live vectors were changed: {message}\n")
222+
print(f"Copied and verified {count} chunks. Live embeddings were not changed.")
223+
224+
225+
if __name__ == "__main__":
226+
main()

0 commit comments

Comments
 (0)