Repository navigation
[Python] Add a pgvector search enrichment handler for Postgres, AlloyDB and Cloud SQL - #41722
karthik-0306 wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
📋 Review Summary
This PR introduces PostgresVectorSearchEnrichmentHandler in apache_beam.ml.rag.enrichment.postgres_search to support vector similarity search (cosine, L2, and inner product) against PostgreSQL, AlloyDB, and Cloud SQL with pgvector. The implementation is well-designed, securely parameterizes queries while preserving HNSW/IVFFlat index scans per item via UNION ALL subqueries, and includes thorough unit and integration test coverage.
🔍 General Feedback
- The query construction, identifier validation, and bind parameter scoping per batch item are clean and effectively prevent SQL injection while ensuring pgvector indexes are utilized.
- Look out for a subtle resource leak when using
CloudSQLConnectionConfig: theCloudSQLConnectorbackground loop created inget_connector_handler()is not closed when the SQLAlchemy engine is disposed. - Rejecting
NaN/infvalues when formatting query vectors in Python will provide clearer failure diagnostics than letting Postgres fail on the entire batch query.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
|
|
||
| def __enter__(self): | ||
| if self._engine is None: | ||
| self._engine = create_engine( |
There was a problem hiding this comment.
🟠 High: CloudSQLConnectionConfig.get_connector_handler() instantiates a google.cloud.sql.connector.Connector inside a closure without exposing a reference to close it. When __exit__ calls self._engine.dispose(), only the pooled DBAPI connections are closed while the Connector's background asyncio event loop thread and aiohttp session remain alive, leaking threads/sockets across bundle teardowns or repeated handler lifecycles.
Consider closing the underlying CloudSQLConnector in __exit__ (either by updating CloudSQLConnectionConfig to manage/close its connector or by extracting the cloudsql_client from the creator closure on teardown).
There was a problem hiding this comment.
Fixed in the latest commit: for CloudSQLConnectionConfig the handler now creates the Cloud SQL Connector itself and closes it in exit, also when disposing the engine fails or when enter fails. I left CloudSQLConnectionConfig unchanged, so the existing CloudSQLEnrichmentHandler is not affected. Added tests for these cases.
| raise ValueError( | ||
| f'Item {item.id} is missing the dense embedding required for vector ' | ||
| 'search') | ||
| return '[' + ','.join(repr(float(x)) for x in embedding) + ']' |
There was a problem hiding this comment.
🟡 Medium: If embedding contains NaN or inf/-inf values, repr(float(x)) formats them as 'nan' or 'inf', which pgvector rejects when casting to vector (e.g., malformed vector literal or inf not allowed in vector), failing the entire batch query without indicating which EmbeddableItem was invalid.
Validating math.isfinite(val) here (or raising a ValueError with item.id) will surface bad embeddings immediately with a clear item-level error.
There was a problem hiding this comment.
Fixed in the latest commit: query vectors with NaN or infinite values now raise a ValueError that names the item, before the query is sent. Added tests for NaN, inf and -inf.
…tgresVectorSearchEnrichmentHandler
|
Assigning reviewers: R: @claudevdm for label python. Note: If you would like to opt out of this review, comment Available commands:
The PR bot will only process comments in the main thread (not review comments). |
Fixes #41713
apache_beam.ml.ragcan write embeddings to Postgres, AlloyDB and Cloud SQL withPostgresVectorWriterConfig, but had no handler to search them; the search handlers covered BigQuery, Milvus and Qdrant. This addsPostgresVectorSearchEnrichmentHandlerfor use withEnrichment:id,embedding,content,metadata) match the tables written byPostgresVectorWriterConfigwith its default column specs.<=>), L2 (<->) and inner product (<#>) distances.ORDER BY distance LIMIT ksubquery, combined withUNION ALL, so a pgvector index is used for every item, and filters can take values from each item.PostgresVectorWriterConfigdoes.id,distance,fields) inmetadata['enrichment_data'].UserCodeTimeoutExceptionandUserCodeQuotaException, soEnrichmentretries them.CloudSQLConnectionConfigandExternalSQLDBConnectionConfigfrom the Cloud SQL enrichment handler, so no new dependency is added.Open questions from #41713, which are easy to change if you prefer another option:
ConnectionConfigused by the ingestion side, because this handler runs queries in Python through SQLAlchemy and pg8000.max_batch_sizeis 100 rather than 1000, since each item adds a subquery.Testing:
postgres_search_test.py: 57 unit tests for parameter validation, the generated SQL and parameters, filters, result grouping, error translation and retries.postgres_search_it_test.py: 5 tests againstpgvector/pgvector:pg16with testcontainers (markedrequire_docker_in_docker, like the Qdrant tests): each distance, returned columns, per-item filters including an item with no matches, and anEXPLAINcheck that the HNSW index is used for each item. All 5 pass locally in Docker.R: @claudevdm