trnews-splade-v1 / examples /search_postgres.py
sinanalyuruk's picture
trnews-splade-v1: initial release (source f259aef3)
2f93f0a verified
Raw History Blame Contribute Delete
12.1 kB
#!/usr/bin/env python3
"""PostgreSQL/pgvector example: store pruned document vectors, search exactly.
Install the runtime from the snapshot you downloaded (there is no PyPI package):
pip install "./trnews-splade-v1/runtime[postgres]"
# or, pinned to the tested set:
pip install -r ./trnews-splade-v1/runtime/locks/requirements-postgres.lock.txt \
"./trnews-splade-v1/runtime[postgres]"
Needs a PostgreSQL with the pgvector extension:
docker run --rm -d --name trnews-pg -p 55432:5432 \
-e POSTGRES_USER=trnews -e POSTGRES_PASSWORD=trnews \
-e POSTGRES_DB=trnews_sparse pgvector/pgvector:pg16
export TRNEWS_PG_DSN=postgresql://trnews:trnews@127.0.0.1:55432/trnews_sparse
python examples/search_postgres.py --snapshot ./trnews-splade-v1 \
--index ./trnews-splade-v1/example_index
**This example only ever drops a table it created in this run.** Ownership is
established by the creation itself: a plain `CREATE TABLE`, with no
`IF NOT EXISTS`, succeeds in exactly one session and raises `42P07` in every
other, so the session that returns from it is the one that made the table. The
drop happens in a `finally`, and only when that statement succeeded. A collision
fails without dropping, clearing or inserting into whatever is already there,
and if cleanup itself fails the original error is the one that propagates.
Coordinates are zero-based in this API. The one-based `sparsevec` shift happens
exactly once, inside `sparse_vector()`. Do not shift again.
Exact search runs under the schema's exactness guard: once an HNSW index exists,
the planner will otherwise answer an ORDER BY using the index's own approximate
ordering and return silently approximate results. The guard restores the
caller's previous setting, not the server default.
"""
from __future__ import annotations
import argparse
import hashlib
import os
import sys
import uuid
SCORE_TOLERANCE = 1e-5
DUPLICATE_TABLE = "42P07" # PostgreSQL: relation already exists
IF_NOT_EXISTS = "CREATE TABLE IF NOT EXISTS "
class ParityFailure(RuntimeError):
"""The database disagreed with the local reference scorer."""
def _exclusive_create(pg, sections, version):
"""The schema's own DDL, made an exclusive claim for this example.
The accepted schema says `CREATE TABLE IF NOT EXISTS`, which is right for a
serving migration — re-running it must be harmless — and wrong for
establishing ownership here: it succeeds whether or not *this* session
created the table, so a table another session created a moment earlier is
adopted silently. Counting rows afterwards does not repair that. An empty
table is not an owned table; it is a second look at a shared resource, and
the window between looking and writing is exactly where the race lives.
Plain `CREATE TABLE` is the claim. Exactly one concurrent session returns
from it; the others raise 42P07 and drop nothing. The column definitions
still come from the schema, so this example cannot drift from the accepted
DDL, and the substitution is asserted rather than assumed: if the schema
ever stops matching, this raises instead of quietly creating with
`IF NOT EXISTS` still in place.
"""
sql = pg.statement(sections, "create_version_table", version)
if sql.count(IF_NOT_EXISTS) != 1:
raise RuntimeError(
f"expected exactly one {IF_NOT_EXISTS.strip()!r} in the schema's "
f"create_version_table section, found {sql.count(IF_NOT_EXISTS)}. "
"Refusing to guess how to make creation exclusive.")
exclusive = sql.replace(IF_NOT_EXISTS, "CREATE TABLE ", 1)
if "IF NOT EXISTS" in exclusive.upper():
# not an assert: `python -O` would drop it, and this is the check that
# makes the statement exclusive.
raise RuntimeError(f"creation is still conditional: {exclusive!r}")
return exclusive
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--snapshot", required=True)
ap.add_argument("--index", required=True, help="local index built by search_sparse.py")
ap.add_argument("--version", default=None,
help="index version suffix [a-z0-9_]; default is a unique "
"example_<random> name this run owns")
ap.add_argument("--dsn", default=None)
ap.add_argument("--keep", action="store_true",
help="keep the table this run created (it is still only ever "
"this run's own table)")
args = ap.parse_args()
from trnews_splade import QueryEncoder, SparseIndex
from trnews_splade import postgres as pg
# The manifest is required: without it the query package's bytes are never
# checked, and an altered weight table would load silently.
manifest = os.path.join(args.snapshot, "manifest.json")
if not os.path.exists(manifest):
sys.exit(f"no manifest.json in {args.snapshot}. The published example "
"path requires it; the query package is not loaded unverified.")
encoder = QueryEncoder(os.path.join(args.snapshot, "query"), manifest=manifest)
index = SparseIndex.load(args.index)
index.check_compatible(encoder)
dim = encoder.config["vocabulary_size"]
sections = pg.load_sections()
print(f"schema: {pg.schema_path()}")
print(f"sections: {len(sections)} exact guard: {pg.guard_setting(sections, 'exact_guard')}")
version = pg.check_version(args.version or f"example_{uuid.uuid4().hex[:8]}")
table = f"sparse_documents_{version}"
conn = pg.connect(args.dsn or pg.DEFAULT_DSN, autocommit=True, register=False)
created = False
try:
conn.execute(sections["extension"])
from pgvector.psycopg import register_vector
register_vector(conn)
conn.execute(sections["load_vector_gucs"])
# A courtesy check, so an explicit --version that is already in use
# fails with a readable message rather than an SQLSTATE. It is NOT the
# ownership test: another session can create the table in the gap
# between this statement and the next one.
existing = conn.execute("SELECT to_regclass(%s)", (table,)).fetchone()[0]
if existing is not None:
sys.exit(f"{table} already exists. This example will not drop, clear "
f"or insert into a relation it did not create. Re-run "
f"without --version to get a unique name.")
# Ownership, established atomically. Whoever returns from this statement
# is the session that created the table; everyone else gets 42P07.
try:
conn.execute(_exclusive_create(pg, sections, version))
except Exception as exc: # noqa: BLE001
if getattr(exc, "sqlstate", None) != DUPLICATE_TABLE:
raise
sys.exit(f"{table} was created by another session while this run was "
f"starting up. This example will not adopt, insert into or "
f"drop a relation it did not create. Re-run without "
f"--version to get a unique name.")
created = True
print(f"created {table} (owned by this run)")
# Sanity only, now that ownership is settled: a table this session just
# created cannot hold rows. If it somehow does, something is very wrong
# and inserting more would make it worse.
rows_present = conn.execute(f"SELECT count(*) FROM {table}").fetchone()[0]
if rows_present:
raise RuntimeError(
f"{table} was created by this session but already holds "
f"{rows_present} row(s); refusing to write to it.")
_load_and_compare(conn, pg, sections, version, encoder, index, dim, manifest)
finally:
# Only ever this run's own table, and only when it was actually created.
try:
if created and not args.keep:
conn.execute(pg.statement(sections, "drop_version_table", version))
print(f"\ndropped {table}")
elif created:
print(f"\nkept {table} (--keep)")
else:
print("\nnothing to clean up: no table was created by this run")
except Exception as cleanup_error: # noqa: BLE001
# Never replace the real failure with a bookkeeping one.
print(f"warning: cleanup of {table} failed: {cleanup_error}",
file=sys.stderr)
finally:
conn.close()
return 0
def _load_and_compare(conn, pg, sections, version, encoder, index, dim, manifest):
table = f"sparse_documents_{version}"
manifest_sha = _sha256_file(manifest)
model_version = encoder.config["model_version"]
rows = _document_rows(index)
insert = (f"INSERT INTO {table} "
"(doc_id, model_version, manifest_sha256, text_sha256, text, terms) "
"VALUES (%(doc_id)s, %(model_version)s, %(manifest_sha256)s, "
"%(text_sha256)s, %(text)s, %(terms)s)")
for doc_id, text, terms in rows:
conn.execute(insert, {"doc_id": doc_id, "model_version": model_version,
"manifest_sha256": manifest_sha,
"text_sha256": _sha256_text(text), "text": text,
"terms": pg.sparse_vector(terms, dim)})
print(f"inserted {len(rows)} documents "
f"(model_version={model_version}, manifest={manifest_sha[:12]}…)")
print("\n--- exact search, compared with the local reference scorer ---")
print(f" parity is ASSERTED, not printed: score tolerance {SCORE_TOLERANCE:g}")
for text in ["metro hattı çalışmaları", "güneş enerjisi araştırma", ""]:
terms = encoder.encode_one(text)
db = pg.search_exact(conn, sections, version, terms, dim, k=3)
local = index.search(terms, k=3)
label = repr(text) if text else "'' (empty query)"
print(f"\nquery {label}")
if len(db) != len(local):
raise ParityFailure(
f"{label}: database returned {len(db)} hits, local scorer "
f"{len(local)}")
if not db:
print(" both return no hits")
continue
for rank, (d, l) in enumerate(zip(db, local), 1):
if d["doc_id"] != l["doc_id"]:
raise ParityFailure(
f"{label}: rank {rank} differs — database {d['doc_id']!r}, "
f"local {l['doc_id']!r}")
delta = abs(d["score"] - l["score"])
if delta > SCORE_TOLERANCE:
raise ParityFailure(
f"{label}: rank {rank} score differs by {delta:g} "
f"(> {SCORE_TOLERANCE:g}): database {d['score']!r}, "
f"local {l['score']!r}")
print(f" {rank}. {d['score']:10.6f} {d['doc_id']} "
f"(|db - local| = {delta:.2e})")
print("\nparity holds on every compared hit.")
def _sha256_file(path, chunk=1 << 20):
h = hashlib.sha256()
with open(path, "rb") as f:
for b in iter(lambda: f.read(chunk), b""):
h.update(b)
return h.hexdigest()
def _sha256_text(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _document_rows(index):
"""Term-major postings back to one weight dict per document."""
from scipy.sparse import csc_matrix
vocab = index.meta["vocabulary_size"]
csr = csc_matrix((index.data, index.indices, index.indptr),
shape=(len(index.doc_ids), vocab)).tocsr()
out = []
for i, doc_id in enumerate(index.doc_ids):
s, e = csr.indptr[i], csr.indptr[i + 1]
out.append((doc_id, index.texts[i],
dict(zip(csr.indices[s:e].tolist(),
csr.data[s:e].astype(float).tolist()))))
return out
if __name__ == "__main__":
sys.exit(main())