Skip to content

[Python] Add a pgvector search enrichment handler for Postgres, AlloyDB and Cloud SQL - #41722

Open
karthik-0306 wants to merge 2 commits into
apache:masterfrom
karthik-0306:pgvector-search-handler
Open

karthik-0306 wants to merge 2 commits into
apache:masterfrom
karthik-0306:pgvector-search-handler

Conversation

@karthik-0306

Copy link
Copy Markdown
Contributor

Fixes #41713

apache_beam.ml.rag can write embeddings to Postgres, AlloyDB and Cloud SQL with PostgresVectorWriterConfig, but had no handler to search them; the search handlers covered BigQuery, Milvus and Qdrant. This adds PostgresVectorSearchEnrichmentHandler for use with Enrichment:

handler = PostgresVectorSearchEnrichmentHandler(
    ExternalSQLDBConnectionConfig(
        db_adapter=DatabaseTypeAdapter.POSTGRESQL,
        host='10.0.0.5', port=5432, user='beam', password='...', db_id='rag'),
    PostgresVectorSearchParameters(
        table_name='embeddings',
        limit=5,
        distance=PostgresVectorDistance.COSINE,
        filter_template="metadata->>'language' = :language",
        filter_params_fn=lambda item: {'language': item.metadata['language']}))
enriched = items | Enrichment(handler)
  • The defaults (id, embedding, content, metadata) match the tables written by PostgresVectorWriterConfig with its default column specs.
  • Supports pgvector's cosine (<=>), L2 (<->) and inner product (<#>) distances.
  • Each batch is searched with one query. Each item gets its own ORDER BY distance LIMIT k subquery, combined with UNION ALL, so a pgvector index is used for every item, and filters can take values from each item.
  • Embeddings and filter values are bind parameters. Table and column names are checked against a strict pattern and used unquoted, like PostgresVectorWriterConfig does.
  • Results use the same shape as the Milvus handler (id, distance, fields) in metadata['enrichment_data'].
  • Statement timeouts and "too many connections" errors are raised as UserCodeTimeoutException and UserCodeQuotaException, so Enrichment retries them.
  • Connections reuse CloudSQLConnectionConfig and ExternalSQLDBConnectionConfig from 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:

  1. Connection settings come from the Cloud SQL enrichment handler, rather than the JDBC ConnectionConfig used by the ingestion side, because this handler runs queries in Python through SQLAlchemy and pg8000.
  2. The default max_batch_size is 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 against pgvector/pgvector:pg16 with testcontainers (marked require_docker_in_docker, like the Qdrant tests): each distance, returned columns, per-item filters including an item with no matches, and an EXPLAIN check that the HNSW index is used for each item. All 5 pass locally in Docker.
  • yapf and ruff are clean on the touched files.

R: @claudevdm

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 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: the CloudSQLConnector background loop created in get_connector_handler() is not closed when the SQLAlchemy engine is disposed.
  • Rejecting NaN / inf values 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) + ']'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot added python size/xl XL: >=1000 lines changed labels Nov 27, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @claudevdm for label python.
Backup reviewer: shunping (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add a pgvector search enrichment handler for Postgres, AlloyDB and Cloud SQL in ml.rag

1 participant