You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "pandasanjay (via GitHub)" <gi...@apache.org> on 2025/06/07 15:08:11 UTC

[PR] Add BigQuery Storage Read API Enrichment Handler [beam]

pandasanjay opened a new pull request, #35197:
URL: https://github.com/apache/beam/pull/35197

   **Description:**
   
   This pull request introduces a new `EnrichmentSourceHandler` for Apache Beam, `BigQueryStorageEnrichmentHandler`, designed to leverage the Google Cloud BigQuery Storage Read API for efficient data enrichment. This handler provides a high-performance alternative to traditional SQL-based BigQuery lookups within Beam pipelines.
   
   **Motivation and Context:**
   
   Enriching data by joining PCollection elements with data stored in BigQuery is a common use case. While existing methods often rely on executing SQL queries, the BigQuery Storage Read API offers a more direct and typically faster way to retrieve data, especially for large volumes or when fine-grained row-level access is needed. This handler aims to:
   
   *   Improve the performance of BigQuery enrichments.
   *   Reduce BigQuery query costs associated with SQL execution for enrichment tasks.
   *   Provide more flexible and programmatic control over data fetching and filtering.
   
   **Key Features and Improvements:**
   
   The `BigQueryStorageEnrichmentHandler` offers several enhancements:
   
   *   **Efficient Data Retrieval:** Utilizes the BigQuery Storage Read API for significantly faster data reads compared to SQL queries, especially for bulk lookups. Data is read in Apache Arrow format, minimizing serialization/deserialization overhead.
   *   **Flexible Filtering:**
       *   Supports static filter templates via `row_restriction_template`.
       *   Allows dynamic, per-element filter string generation using `row_restriction_template_fn`.
   *   **Advanced Keying and Value Extraction:**
       *   `fields`: Specifies input `beam.Row` fields for generating join keys and for use in filter templates.
       *   `additional_condition_fields`: Allows using input fields for filtering *without* including them in the join key.
       *   `condition_value_fn`: Provides complete control over generating the dictionary of values used for both filtering and join key creation.
   *   **Field Renaming/Aliasing:** Supports aliasing of selected BigQuery columns (e.g., `original_col as alias_col` in `column_names`) to prevent naming conflicts in the enriched `beam.Row`.
   *   **Batching Support:** Groups multiple input elements to make fewer `CreateReadSession` calls, reducing API overhead. Batch size and duration are configurable (`min_batch_size`, `max_batch_size`, `max_batch_duration_secs`).
   *   **Parallel Stream Reading:** (Experimental) Employs a `ThreadPoolExecutor` to read data from multiple streams of a BigQuery Read Session in parallel, potentially improving data fetching throughput. Concurrency is configurable via `max_parallel_streams`.
   *   **Custom Row Selection:** Includes a `latest_value_selector` callback that allows users to define custom logic for selecting the desired row when multiple BigQuery rows match a single input request (e.g., picking the record with the most recent timestamp). `primary_keys` can be used by this selector.
   *   **Automatic Client Management:** Manages the lifecycle of the `BigQueryReadClient`.
   
   **Advantages over Traditional SQL-based BigQuery Enrichment:**
   
   *   **Performance:** Direct access to table storage via the Storage Read API typically bypasses the SQL query processing engine, leading to lower latency and higher throughput, especially for fetching many individual rows or large data segments.
   *   **Cost Efficiency:** Reading data via the Storage API can be more cost-effective than running many small SQL queries, as Storage API pricing is based on data scanned, while query pricing involves slots and scanned data.
   *   **Scalability:** The streaming nature of the Storage Read API is well-suited for scalable data processing in Beam.
   *   **Reduced Query Complexity:** For simple lookups, it avoids the need to construct and manage SQL query strings dynamically.
   
   **Documentation:**
   
   Comprehensive documentation for this handler, including usage examples, parameter descriptions, features, and limitations, has been added in [ `docs/bigquery_storage_enrichment_handler.md`](https://github.com/pandasanjay/beam-custom-implementation/blob/main/docs/bigquery_storage_enrichment_handler.md).
   
   **Implementation Details:**
   
   The handler (`sdk/ptyhon/transforms/enrichment_handlers/bigquery_storage_read.py`) manages `BigQueryReadClient` instances, constructs `ReadSession` requests with appropriate row restrictions and selected fields, and processes the resulting Arrow record batches. It integrates with Beam's `Enrichment` transform, providing batching and caching key generation.
   
   **Testing Considerations:**
   
   *   Unit tests for key generation, filter construction, and data processing logic.
   *   Integration tests against a live BigQuery instance.
   *   Performance benchmarks comparing against SQL-based handlers.
   
   This handler provides a powerful and efficient way to enrich data in Apache Beam pipelines using BigQuery.
   
   **Please** add a meaningful description for your change here
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/actions/workflows/build_wheels.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/actions/workflows/python_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/actions/workflows/java_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/actions/workflows/go_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2407612029


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API

Review Comment:
   Could you please come back to this? I don't think it makes a ton of sense to have a separate enrichment handler



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2992577571

   > @pandasanjay – It looks like the example pipelines fail with this error:
   > 
   > ```
   > > from google.api_core.exceptions import TooManyRequests
   > E   ModuleNotFoundError: No module named 'google.api_core'
   > ```
   > 
   > Given this to be installed have you tested this with BQ table in your Google Cloud and the tests pass?
   
   @mohamedawnallah, you’re right.
   
   I’ve noticed that wherever this module is used, the Beam pipeline is skipping those tests. The pyproject.toml file does list the necessary dependency, so this might be an issue with the pipeline itself. I suspect that’s also why there aren’t any examples available for BQ enrichment.
   
   @damccorm would you be able guide us here. :)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3373011578

   waiting on author


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2405487588


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API
+with support for field renaming via aliases in `column_names`,
+additional non-key fields for filtering, dynamic row restriction templates,
+experimental parallel stream reading using ThreadPoolExecutor, and custom
+row selection.
+"""
+
+import concurrent.futures  # For parallel stream reading
+import logging
+import re
+from collections.abc import Callable
+from collections.abc import Mapping
+from typing import Any
+from typing import Dict
+from typing import Iterator
+from typing import List
+from typing import Optional
+from typing import Set
+from typing import Tuple
+from typing import Union
+import pyarrow as pa
+from google.api_core.exceptions import BadRequest
+from google.api_core.exceptions import GoogleAPICallError
+from google.api_core.exceptions import NotFound
+from google.cloud.bigquery_storage import BigQueryReadClient
+
+from apache_beam.pvalue import Row as BeamRow
+from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+
+try:
+  from google.cloud.bigquery_storage import types
+  from google.cloud.bigquery_storage.types import (
+      DataFormat, ReadRowsResponse, ReadSession)
+except ImportError:
+  # Fallback for older versions where types might be in different location
+  from google.cloud.bigquery_storage import types
+  ReadRowsResponse = types.ReadRowsResponse
+  ReadSession = types.ReadSession
+  DataFormat = types.DataFormat
+
+# --- Configure Logging ---
+logger = logging.getLogger(__name__)
+
+# Type hints for functions
+# Input functions expect beam.Row for clarity, use beam.Row.as_dict inside if
+# needed
+ConditionValueFn = Callable[[BeamRow], Dict[str, Any]]
+# Updated RowRestrictionTemplateFn signature based on user provided code
+RowRestrictionTemplateFn = Callable[
+    [Dict[str, Any], Optional[List[str]], BeamRow], str]
+BQRowDict = Dict[str, Any]
+# Callback for selecting the "latest" or desired row from multiple BQ results
+LatestValueSelectorFn = Optional[Callable[[List[BeamRow], BeamRow],
+                                          Optional[BeamRow]]]
+
+# Regex to parse "column as alias" format, ignoring case for "as"
+ALIAS_REGEX = re.compile(r"^(.*?)\s+as\s+(.*)$", re.IGNORECASE)
+
+
+def _validate_bigquery_metadata(
+    project,
+    table_name,
+    row_restriction_template,
+    row_restriction_template_fn,
+    fields,
+    condition_value_fn,
+    additional_condition_fields,
+):
+  """Validates parameters for Storage API usage."""
+  if not project:
+    raise ValueError("`project` must be provided.")
+  if not table_name:
+    raise ValueError("`table_name` must be provided.")
+  if (row_restriction_template and
+      row_restriction_template_fn) or (not row_restriction_template and
+                                       not row_restriction_template_fn):
+    raise ValueError(
+        "Provide exactly one of `row_restriction_template` or "
+        "`row_restriction_template_fn`.")
+  if (fields and condition_value_fn) or (not fields and not condition_value_fn):
+    raise ValueError("Provide exactly one of `fields` or `condition_value_fn`.")
+  if additional_condition_fields and condition_value_fn:
+    raise ValueError(
+        "`additional_condition_fields` cannot be used with "
+        "`condition_value_fn`.")
+
+
+class BigQueryStorageEnrichmentHandler(
+    EnrichmentSourceHandler[Union[BeamRow, list[BeamRow]],
+                            Union[BeamRow, list[BeamRow]]]):
+  """Enrichment handler for Google Cloud BigQuery using the Storage Read API.
+    (Refer to __init__ for full list of features and arguments)
+    """
+  def __init__(
+      self,
+      project: str,
+      table_name: str,
+      *,
+      row_restriction_template: Optional[str] = None,
+      row_restriction_template_fn: Optional[RowRestrictionTemplateFn] = None,
+      fields: Optional[list[str]] = None,  # Fields for KEY and filtering
+      additional_condition_fields: Optional[list[str]] = None,  # Fields ONLY
+      # for filtering
+      column_names: Optional[list[str]] = None,  # Columns to select + aliases
+      condition_value_fn: Optional[ConditionValueFn] = None,  # Alt way to get
+      # filter/key values
+      min_batch_size: Optional[int] = 1,
+      max_batch_size: Optional[int] = 1000,  # Batching enabled by default
+      max_batch_duration_secs: Optional[int] = None,
+      max_parallel_streams: Optional[int] = None,  # Max workers for
+      # ThreadPoolExecutor
+      max_stream_count: int = 100,  # Max streams for BigQuery Storage Read
+      # --- Added latest_value_selector and primary_keys from user code ---
+      latest_value_selector: LatestValueSelectorFn = None,
+      primary_keys: Optional[list[str]] = None,  # --- End added parameters ---
+  ):
+    """
+        Initializes the BigQueryStorageEnrichmentHandler.
+
+        Args:
+            project: Google Cloud project ID.
+            table_name: Fully qualified BigQuery table name.
+            row_restriction_template: (Optional[str]) Template string for a
+                single row's filter condition. If `row_restriction_template_fn`
+                is not provided, this template will be formatted with values
+                from `fields` and `additional_condition_fields`.
+            row_restriction_template_fn: (Optional[Callable]) Function that
+                takes (condition_values_dict, primary_keys, request_row) and
+                returns a fully formatted filter string or template to 
+                be formatted.
+            fields: (Optional[list[str]]) Input `beam.Row` field names used to
+                generate the dictionary for formatting the row restriction
+                template AND for generating the internal join/cache key.
+            additional_condition_fields: (Optional[list[str]]) Additional input
+                `beam.Row` field names used ONLY for formatting the row
+                restriction template. Not part of join/cache key.
+            column_names: (Optional[list[str]]) Names/aliases of columns to
+                select. Supports "original_col as alias_col" format. If None,
+                selects '*'.
+            condition_value_fn: (Optional[Callable]) Function returning a
+                dictionary for formatting row restriction template and for
+                join/cache key. Takes precedence over `fields`.
+            min_batch_size (Optional[int]): Minimum elements per batch.
+                Defaults to 1.
+            max_batch_size (Optional[int]): Maximum elements per batch.
+                Defaults to 1000 for batching. Set to 1 for single element
+                processing to disable batching.
+            max_batch_duration_secs (Optional[int]): Maximum batch buffering
+                time in seconds. Defaults to 5 seconds.
+            max_parallel_streams (Optional[int]): Max worker threads for
+                ThreadPoolExecutor for reading streams in parallel within a
+                single `__call__`.
+            max_stream_count (int): Maximum number of streams for BigQuery
+                Storage Read API. Defaults to 100. Setting to 0 lets BigQuery
+                decide the optimal number of streams.
+            latest_value_selector: (Optional) Callback function to select the
+                desired row when multiple BQ rows match a key. Takes
+                `List[beam.Row]` (BQ results) and the original `beam.Row`
+                (request) and returns one `beam.Row` or None.
+            primary_keys: (Optional[list[str]]) Primary key fields used
+                potentially by `row_restriction_template_fn` or
+                `latest_value_selector`.
+        """
+    _validate_bigquery_metadata(
+        project,
+        table_name,
+        row_restriction_template,
+        row_restriction_template_fn,
+        fields,
+        condition_value_fn,
+        additional_condition_fields,
+    )
+    self.project = project
+    self.table_name = table_name
+    self.row_restriction_template = row_restriction_template
+    self.row_restriction_template_fn = row_restriction_template_fn
+    self.fields = fields
+    self.additional_condition_fields = additional_condition_fields or []
+    self.condition_value_fn = condition_value_fn
+    self.max_parallel_streams = max_parallel_streams
+    self.max_stream_count = max_stream_count
+    # --- Store new parameters ---
+    self._latest_value_callback = latest_value_selector
+    self.primary_keys = primary_keys
+    # --- End store ---
+
+    self._rename_map: Dict[str, str] = {}
+    bq_columns_to_select_set: Set[str] = set()
+    self._select_all_columns = False
+    if column_names:
+      for name_or_alias in column_names:
+        match = ALIAS_REGEX.match(name_or_alias)
+        if match:
+          original_col, alias_col = (
+              match.group(1).strip(),
+              match.group(2).strip(),
+          )
+          if not original_col or not alias_col:
+            raise ValueError(f"Invalid alias: '{name_or_alias}'")
+          bq_columns_to_select_set.add(original_col)
+          self._rename_map[original_col] = alias_col
+        else:
+          col = name_or_alias.strip()
+          if not col:
+            raise ValueError("Empty column name.")
+          if col == "*":
+            self._select_all_columns = True
+            break
+          bq_columns_to_select_set.add(col)
+    else:
+      self._select_all_columns = True
+
+    key_gen_fields_set = set(self.fields or [])
+    if self._select_all_columns:
+      self._bq_select_columns = ["*"]
+      if key_gen_fields_set:
+        logger.debug(
+            "Selecting all columns ('*'). Key fields %s assumed present.",
+            key_gen_fields_set,
+        )
+    else:
+      fields_to_ensure_selected = set()
+      if self.fields:
+        reverse_rename_map = {v: k for k, v in self._rename_map.items()}
+        for field in self.fields:
+          original_name = reverse_rename_map.get(field, field)
+          fields_to_ensure_selected.add(original_name)
+      # Ensure primary keys (if defined for callback use) are selected if not
+      # already
+      if self.primary_keys:
+        for pk_field in self.primary_keys:
+          original_pk_name = {
+              v: k
+              for k, v in self._rename_map.items()
+          }.get(pk_field, pk_field)
+          fields_to_ensure_selected.add(original_pk_name)
+
+      final_select_set = bq_columns_to_select_set.union(
+          fields_to_ensure_selected)
+      self._bq_select_columns = sorted(list(final_select_set))
+      if not self._bq_select_columns:
+        raise ValueError("No columns determined for selection.")
+
+    logger.info(
+        "Handler Initialized. Selecting BQ Columns: %s. Renaming map: %s",
+        self._bq_select_columns,
+        self._rename_map,
+    )
+
+    self._batching_kwargs = {}
+    # Set defaults for optional parameters
+    min_batch_size = min_batch_size or 1
+    max_batch_size = max_batch_size or 1000
+    max_batch_duration_secs = max_batch_duration_secs or 5
+
+    if max_batch_size > 1:
+      self._batching_kwargs["min_batch_size"] = min_batch_size
+      self._batching_kwargs["max_batch_size"] = max_batch_size
+      self._batching_kwargs["max_batch_duration_secs"] = max_batch_duration_secs
+    else:
+      self._batching_kwargs["min_batch_size"] = 1
+      self._batching_kwargs["max_batch_size"] = 1
+
+    self._client: Optional[BigQueryReadClient] = None
+    self._arrow_schema: Optional[pa.Schema] = None
+
+  def __enter__(self):
+    if not self._client:
+      self._client = BigQueryReadClient()
+      logger.info("BigQueryStorageEnrichmentHandler: Client created.")
+    self._arrow_schema = None
+
+  def _get_condition_values_dict(self,
+                                 req: BeamRow) -> Optional[Dict[str, Any]]:
+    try:
+      if self.condition_value_fn:
+        values_dict = self.condition_value_fn(req)
+        if values_dict is None or any(v is None for v in values_dict.values()):
+          logger.warning(
+              "condition_value_fn returned None or None value(s). "
+              "Skipping: %s. Values: %s",
+              req,
+              values_dict,
+          )
+          return None
+        return values_dict
+      elif self.fields is not None:
+        req_dict = req._asdict()
+        values_dict = {}
+        all_req_fields = (self.fields or []) + self.additional_condition_fields
+        for field in all_req_fields:
+          # User's provided logic for row_restriction_template_fn handling:
+          if not self.row_restriction_template_fn:
+            if field not in req_dict or req_dict[field] is None:
+              logger.warning(
+                  "Input row missing field '%s' or None (needed "
+                  "for filter). Skipping: %s",
+                  field,
+                  req,
+              )
+              return None
+          values_dict[field] = req_dict.get(field)  # Use get for safety
+        return values_dict
+      else:
+        raise ValueError(
+            "Internal error: Neither fields nor condition_value_fn.")
+    except AttributeError:  # Specifically for _asdict()
+      logger.error(
+          "Failed to call _asdict() on element. Type: %s. Element: "
+          "%s. Ensure input is beam.Row.",
+          type(req),
+          req,
+      )
+      return None
+    except Exception as e:
+      logger.error(
+          "Error getting condition values for row %s: %s",
+          req,
+          e,
+          exc_info=True)
+      return None
+
+  def _build_single_row_filter(
+      self, req_row: BeamRow, condition_values_dict: Dict[str, Any]) -> str:
+    """Builds the filter string part for a single row."""
+    try:
+      if self.row_restriction_template_fn:
+        # User's provided signature for row_restriction_template_fn
+        template_or_filter = self.row_restriction_template_fn(
+            condition_values_dict, self.primary_keys, req_row)
+        if not isinstance(template_or_filter, str):
+          raise TypeError(
+              "row_restriction_template_fn must return a string "
+              "(filter or template to be formatted)")
+        # Assuming if it takes condition_values_dict, it might be returning
+        # the final filter or a template. If it's a template, it still needs
+        # .format(). For now, assume it's a template that might still need
+        # formatting OR the final filter string. Let's assume it's the final
+        # filter string as per user's code.
+        # Directly return what the user's function gives.
+        return template_or_filter
+      elif self.row_restriction_template:
+        return self.row_restriction_template.format(**condition_values_dict)
+      else:
+        raise ValueError(
+            "Internal Error: No template or template function available.")
+    except KeyError as e:  # if user's fn returns template and format fails
+      raise ValueError(
+          f"Placeholder {{{e}}} in template not found in "
+          f"condition values: {condition_values_dict.keys()}")
+    except Exception as e:
+      logger.error(
+          "Error building filter for row %s with values %s: %s",
+          req_row,
+          condition_values_dict,
+          e,
+          exc_info=True,
+      )
+      return ""
+
+  def _apply_renaming(self, bq_row_dict: BQRowDict) -> BQRowDict:
+    if not self._rename_map:
+      return bq_row_dict
+    return {self._rename_map.get(k, k): v for k, v in bq_row_dict.items()}
+
+  def _arrow_to_dicts(self, response: ReadRowsResponse) -> Iterator[BQRowDict]:
+    # Now uses self._arrow_schema directly
+    if response.arrow_record_batch:
+      if not self._arrow_schema:
+        logger.error(
+            "Cannot process Arrow batch: Schema not "
+            "available/cached in handler.")
+        return
+      try:
+        serialized_batch = response.arrow_record_batch.serialized_record_batch
+        record_batch = pa.ipc.read_record_batch(
+            pa.py_buffer(serialized_batch), self._arrow_schema)
+        arrow_table = pa.Table.from_batches([record_batch])
+        yield from arrow_table.to_pylist()
+      except Exception as e:
+        logger.error(
+            "Error converting Arrow batch to dicts: %s", e, exc_info=True)
+
+  def _execute_storage_read(self, combined_row_filter: str) -> List[BQRowDict]:
+    if not self._client:
+      self.__enter__()
+    if not self._client:
+      raise RuntimeError("BQ Client failed to initialize.")
+    if not combined_row_filter:
+      logger.warning("Empty filter, skipping BQ read.")
+      return []
+
+    try:
+      table_project, dataset_id, table_id = self.table_name.split(".")
+    except ValueError:
+      raise ValueError(
+          f"Invalid table_name: '{self.table_name}'. Expected "
+          "'project.dataset.table'.")
+    parent_project = self.project
+    table_resource = (
+        f"projects/{table_project}/datasets/{dataset_id}/tables/{table_id}")
+
+    session = None
+    try:
+      # TODO: Improve max_stream_count to be dynamic based on input size,
+      # data volume, and query complexity for optimal performance
+      req = {
+          "parent": f"projects/{parent_project}",
+          "read_session": ReadSession(
+              table=table_resource,
+              data_format=DataFormat.ARROW,
+              read_options=ReadSession.TableReadOptions(
+                  row_restriction=combined_row_filter,
+                  selected_fields=self._bq_select_columns,
+              ),
+          ),
+          "max_stream_count": self.max_stream_count,
+      }
+      session = self._client.create_read_session(request=req)
+      logger.debug(
+          "Session with %s streams. Filter: %s",
+          len(session.streams),
+          combined_row_filter,
+      )
+      if session.streams and session.arrow_schema:
+        if not self._arrow_schema:
+          self._arrow_schema = pa.ipc.read_schema(
+              pa.py_buffer(session.arrow_schema.serialized_schema))
+          logger.debug("Deserialized Arrow schema for current call.")
+      elif session.streams:
+        logger.error("Session has streams but no schema.")
+        return []
+    except (BadRequest, NotFound, GoogleAPICallError) as e:
+      logger.error(
+          "BQ API error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+      )
+      return []
+    except Exception as e:
+      logger.error(
+          "Unexpected error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+          exc_info=True,
+      )
+      return []
+
+    if not session or not session.streams:
+      logger.warning("No streams for filter: %s", combined_row_filter)
+      return []
+
+    def _read_single_stream_worker(stream_name: str) -> List[BQRowDict]:
+      worker_results = []
+      if not self._client or not self._arrow_schema:
+        logger.error("Stream %s: Client/schema missing in worker.", stream_name)
+        return worker_results
+      try:
+        reader = self._client.read_rows(stream_name)
+        for response in reader:
+          worker_results.extend(self._arrow_to_dicts(response))  # Uses
+          # self._arrow_schema
+      except Exception as e:
+        logger.error(
+            "Error reading stream %s in worker: %s",
+            stream_name,
+            e,
+            exc_info=True,
+        )
+      return worker_results
+
+    all_bq_rows_original_keys = []
+    num_api_streams = len(session.streams)
+    max_workers = num_api_streams
+    if self.max_parallel_streams is not None and self.max_parallel_streams > 0:
+      max_workers = min(num_api_streams, self.max_parallel_streams)
+    if max_workers <= 0:
+      max_workers = 1
+    logger.debug(
+        "Reading %s API streams using %s threads.",
+        num_api_streams,
+        max_workers)
+    futures = []
+    try:
+      with concurrent.futures.ThreadPoolExecutor(
+          max_workers=max_workers) as executor:
+        for stream in session.streams:
+          futures.append(
+              executor.submit(_read_single_stream_worker, stream.name))
+        for future in concurrent.futures.as_completed(futures):
+          try:
+            all_bq_rows_original_keys.extend(future.result())
+          except Exception as e:
+            logger.error("Error processing future result: %s", e, exc_info=True)
+    except Exception as pool_error:
+      logger.error("ThreadPool error: %s", pool_error, exc_info=True)
+    logger.debug("Fetched %s rows from BQ.", len(all_bq_rows_original_keys))
+    return all_bq_rows_original_keys

Review Comment:
   Hi @tvalentyn,
   
   Apologies for the delayed response! I appreciate your suggestion.
   
   Hi @robertwb and @lukecwik, I found your names in the git commit. You have worked on part of building the enrichment transform. I need your expertise to solve a problem. Could you please review this PR, especially the concurrent stream creation section, and suggest improvements? If you think anyone else knows better about this, please tag them. Thanks :)
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2975892649

   Assigning reviewers:
   
   R: @damccorm for label python.
   R: @liferoad for label website.
   
   
   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).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3274686264

   Reminder, please take a look at this pr: @tvalentyn @kennknowles 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3179789936

   waiting on author


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2992631673

   > > I’ve noticed that wherever this module is used, the Beam pipeline is skipping those tests
   > 
   > @pandasanjay I found it depends mostly on the GitHub runner/workflow those tests run on. I have recently come across this when I have been working on Milvus Enrichment Handler #35216.
   >
   > Using try-except on the related imports that need dependencies and skipping that test would solve the issue. That being said, I think it may change from case to case, so someone may check that this happens on specific workflows, not all. Otherwise, those test cases would never run since they are entirely skipped.
   > 
   
   @mohamedawnallah I’ve noticed the same issue and even used that approach to fix my integration tests. However, it seems that all the example tests are failing at that point in the GitHub Actions workflow, which raises the question of whether this module has ever been successfully installed and run via GitHub Actions. This aligns with your last point.
   
   I think we could use some guidance on how to proceed here.
   
   
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "mohamedawnallah (via GitHub)" <gi...@apache.org>.
mohamedawnallah commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2992586319

   > I’ve noticed that wherever this module is used, the Beam pipeline is skipping those tests
   
   @pandasanjay I found it depends mostly on the GitHub runner. I have come across this when I have been working on Milvus Enrichment Handler:
   https://github.com/apache/beam/pull/35216
   
   Using try-except on the related imports that need dependencies and skipping that test would solve the issue. That being said, I think it changes from case to case, so someone may check that this happens on specific workflows, not all. Otherwise, those test cases would never run since they are entirely skipped.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2201948536


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API
+with support for field renaming via aliases in `column_names`,
+additional non-key fields for filtering, dynamic row restriction templates,
+experimental parallel stream reading using ThreadPoolExecutor, and custom
+row selection.
+"""
+
+import concurrent.futures  # For parallel stream reading
+import logging
+import re
+from collections.abc import Callable
+from collections.abc import Mapping
+from typing import Any
+from typing import Dict
+from typing import Iterator
+from typing import List
+from typing import Optional
+from typing import Set
+from typing import Tuple
+from typing import Union
+import pyarrow as pa
+from google.api_core.exceptions import BadRequest
+from google.api_core.exceptions import GoogleAPICallError
+from google.api_core.exceptions import NotFound
+from google.cloud.bigquery_storage import BigQueryReadClient
+
+from apache_beam.pvalue import Row as BeamRow
+from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+
+try:
+  from google.cloud.bigquery_storage import types
+  from google.cloud.bigquery_storage.types import (
+      DataFormat, ReadRowsResponse, ReadSession)
+except ImportError:
+  # Fallback for older versions where types might be in different location
+  from google.cloud.bigquery_storage import types
+  ReadRowsResponse = types.ReadRowsResponse
+  ReadSession = types.ReadSession
+  DataFormat = types.DataFormat
+
+# --- Configure Logging ---
+logger = logging.getLogger(__name__)
+
+# Type hints for functions
+# Input functions expect beam.Row for clarity, use beam.Row.as_dict inside if
+# needed
+ConditionValueFn = Callable[[BeamRow], Dict[str, Any]]
+# Updated RowRestrictionTemplateFn signature based on user provided code
+RowRestrictionTemplateFn = Callable[
+    [Dict[str, Any], Optional[List[str]], BeamRow], str]
+BQRowDict = Dict[str, Any]
+# Callback for selecting the "latest" or desired row from multiple BQ results
+LatestValueSelectorFn = Optional[Callable[[List[BeamRow], BeamRow],
+                                          Optional[BeamRow]]]
+
+# Regex to parse "column as alias" format, ignoring case for "as"
+ALIAS_REGEX = re.compile(r"^(.*?)\s+as\s+(.*)$", re.IGNORECASE)
+
+
+def _validate_bigquery_metadata(
+    project,
+    table_name,
+    row_restriction_template,
+    row_restriction_template_fn,
+    fields,
+    condition_value_fn,
+    additional_condition_fields,
+):
+  """Validates parameters for Storage API usage."""
+  if not project:
+    raise ValueError("`project` must be provided.")
+  if not table_name:
+    raise ValueError("`table_name` must be provided.")
+  if (row_restriction_template and
+      row_restriction_template_fn) or (not row_restriction_template and
+                                       not row_restriction_template_fn):
+    raise ValueError(
+        "Provide exactly one of `row_restriction_template` or "
+        "`row_restriction_template_fn`.")
+  if (fields and condition_value_fn) or (not fields and not condition_value_fn):
+    raise ValueError("Provide exactly one of `fields` or `condition_value_fn`.")
+  if additional_condition_fields and condition_value_fn:
+    raise ValueError(
+        "`additional_condition_fields` cannot be used with "
+        "`condition_value_fn`.")
+
+
+class BigQueryStorageEnrichmentHandler(
+    EnrichmentSourceHandler[Union[BeamRow, list[BeamRow]],
+                            Union[BeamRow, list[BeamRow]]]):
+  """Enrichment handler for Google Cloud BigQuery using the Storage Read API.
+    (Refer to __init__ for full list of features and arguments)
+    """
+  def __init__(
+      self,
+      project: str,
+      table_name: str,
+      *,
+      row_restriction_template: Optional[str] = None,
+      row_restriction_template_fn: Optional[RowRestrictionTemplateFn] = None,
+      fields: Optional[list[str]] = None,  # Fields for KEY and filtering
+      additional_condition_fields: Optional[list[str]] = None,  # Fields ONLY
+      # for filtering
+      column_names: Optional[list[str]] = None,  # Columns to select + aliases
+      condition_value_fn: Optional[ConditionValueFn] = None,  # Alt way to get
+      # filter/key values
+      min_batch_size: Optional[int] = 1,
+      max_batch_size: Optional[int] = 1000,  # Batching enabled by default
+      max_batch_duration_secs: Optional[int] = None,
+      max_parallel_streams: Optional[int] = None,  # Max workers for
+      # ThreadPoolExecutor
+      max_stream_count: int = 100,  # Max streams for BigQuery Storage Read
+      # --- Added latest_value_selector and primary_keys from user code ---
+      latest_value_selector: LatestValueSelectorFn = None,
+      primary_keys: Optional[list[str]] = None,  # --- End added parameters ---
+  ):
+    """
+        Initializes the BigQueryStorageEnrichmentHandler.
+
+        Args:
+            project: Google Cloud project ID.
+            table_name: Fully qualified BigQuery table name.
+            row_restriction_template: (Optional[str]) Template string for a
+                single row's filter condition. If `row_restriction_template_fn`
+                is not provided, this template will be formatted with values
+                from `fields` and `additional_condition_fields`.
+            row_restriction_template_fn: (Optional[Callable]) Function that
+                takes (condition_values_dict, primary_keys, request_row) and
+                returns a fully formatted filter string or template to 
+                be formatted.
+            fields: (Optional[list[str]]) Input `beam.Row` field names used to
+                generate the dictionary for formatting the row restriction
+                template AND for generating the internal join/cache key.
+            additional_condition_fields: (Optional[list[str]]) Additional input
+                `beam.Row` field names used ONLY for formatting the row
+                restriction template. Not part of join/cache key.
+            column_names: (Optional[list[str]]) Names/aliases of columns to
+                select. Supports "original_col as alias_col" format. If None,
+                selects '*'.
+            condition_value_fn: (Optional[Callable]) Function returning a
+                dictionary for formatting row restriction template and for
+                join/cache key. Takes precedence over `fields`.
+            min_batch_size (Optional[int]): Minimum elements per batch.
+                Defaults to 1.
+            max_batch_size (Optional[int]): Maximum elements per batch.
+                Defaults to 1000 for batching. Set to 1 for single element
+                processing to disable batching.
+            max_batch_duration_secs (Optional[int]): Maximum batch buffering
+                time in seconds. Defaults to 5 seconds.
+            max_parallel_streams (Optional[int]): Max worker threads for
+                ThreadPoolExecutor for reading streams in parallel within a
+                single `__call__`.
+            max_stream_count (int): Maximum number of streams for BigQuery
+                Storage Read API. Defaults to 100. Setting to 0 lets BigQuery
+                decide the optimal number of streams.
+            latest_value_selector: (Optional) Callback function to select the
+                desired row when multiple BQ rows match a key. Takes
+                `List[beam.Row]` (BQ results) and the original `beam.Row`
+                (request) and returns one `beam.Row` or None.
+            primary_keys: (Optional[list[str]]) Primary key fields used
+                potentially by `row_restriction_template_fn` or
+                `latest_value_selector`.
+        """
+    _validate_bigquery_metadata(
+        project,
+        table_name,
+        row_restriction_template,
+        row_restriction_template_fn,
+        fields,
+        condition_value_fn,
+        additional_condition_fields,
+    )
+    self.project = project
+    self.table_name = table_name
+    self.row_restriction_template = row_restriction_template
+    self.row_restriction_template_fn = row_restriction_template_fn
+    self.fields = fields
+    self.additional_condition_fields = additional_condition_fields or []
+    self.condition_value_fn = condition_value_fn
+    self.max_parallel_streams = max_parallel_streams
+    self.max_stream_count = max_stream_count
+    # --- Store new parameters ---
+    self._latest_value_callback = latest_value_selector
+    self.primary_keys = primary_keys
+    # --- End store ---
+
+    self._rename_map: Dict[str, str] = {}
+    bq_columns_to_select_set: Set[str] = set()
+    self._select_all_columns = False
+    if column_names:
+      for name_or_alias in column_names:
+        match = ALIAS_REGEX.match(name_or_alias)
+        if match:
+          original_col, alias_col = (
+              match.group(1).strip(),
+              match.group(2).strip(),
+          )
+          if not original_col or not alias_col:
+            raise ValueError(f"Invalid alias: '{name_or_alias}'")
+          bq_columns_to_select_set.add(original_col)
+          self._rename_map[original_col] = alias_col
+        else:
+          col = name_or_alias.strip()
+          if not col:
+            raise ValueError("Empty column name.")
+          if col == "*":
+            self._select_all_columns = True
+            break
+          bq_columns_to_select_set.add(col)
+    else:
+      self._select_all_columns = True
+
+    key_gen_fields_set = set(self.fields or [])
+    if self._select_all_columns:
+      self._bq_select_columns = ["*"]
+      if key_gen_fields_set:
+        logger.debug(
+            "Selecting all columns ('*'). Key fields %s assumed present.",
+            key_gen_fields_set,
+        )
+    else:
+      fields_to_ensure_selected = set()
+      if self.fields:
+        reverse_rename_map = {v: k for k, v in self._rename_map.items()}
+        for field in self.fields:
+          original_name = reverse_rename_map.get(field, field)
+          fields_to_ensure_selected.add(original_name)
+      # Ensure primary keys (if defined for callback use) are selected if not
+      # already
+      if self.primary_keys:
+        for pk_field in self.primary_keys:
+          original_pk_name = {
+              v: k
+              for k, v in self._rename_map.items()
+          }.get(pk_field, pk_field)
+          fields_to_ensure_selected.add(original_pk_name)
+
+      final_select_set = bq_columns_to_select_set.union(
+          fields_to_ensure_selected)
+      self._bq_select_columns = sorted(list(final_select_set))
+      if not self._bq_select_columns:
+        raise ValueError("No columns determined for selection.")
+
+    logger.info(
+        "Handler Initialized. Selecting BQ Columns: %s. Renaming map: %s",
+        self._bq_select_columns,
+        self._rename_map,
+    )
+
+    self._batching_kwargs = {}
+    # Set defaults for optional parameters
+    min_batch_size = min_batch_size or 1
+    max_batch_size = max_batch_size or 1000
+    max_batch_duration_secs = max_batch_duration_secs or 5
+
+    if max_batch_size > 1:
+      self._batching_kwargs["min_batch_size"] = min_batch_size
+      self._batching_kwargs["max_batch_size"] = max_batch_size
+      self._batching_kwargs["max_batch_duration_secs"] = max_batch_duration_secs
+    else:
+      self._batching_kwargs["min_batch_size"] = 1
+      self._batching_kwargs["max_batch_size"] = 1
+
+    self._client: Optional[BigQueryReadClient] = None
+    self._arrow_schema: Optional[pa.Schema] = None
+
+  def __enter__(self):
+    if not self._client:
+      self._client = BigQueryReadClient()
+      logger.info("BigQueryStorageEnrichmentHandler: Client created.")
+    self._arrow_schema = None
+
+  def _get_condition_values_dict(self,
+                                 req: BeamRow) -> Optional[Dict[str, Any]]:
+    try:
+      if self.condition_value_fn:
+        values_dict = self.condition_value_fn(req)
+        if values_dict is None or any(v is None for v in values_dict.values()):
+          logger.warning(
+              "condition_value_fn returned None or None value(s). "
+              "Skipping: %s. Values: %s",
+              req,
+              values_dict,
+          )
+          return None
+        return values_dict
+      elif self.fields is not None:
+        req_dict = req._asdict()
+        values_dict = {}
+        all_req_fields = (self.fields or []) + self.additional_condition_fields
+        for field in all_req_fields:
+          # User's provided logic for row_restriction_template_fn handling:
+          if not self.row_restriction_template_fn:
+            if field not in req_dict or req_dict[field] is None:
+              logger.warning(
+                  "Input row missing field '%s' or None (needed "
+                  "for filter). Skipping: %s",
+                  field,
+                  req,
+              )
+              return None
+          values_dict[field] = req_dict.get(field)  # Use get for safety
+        return values_dict
+      else:
+        raise ValueError(
+            "Internal error: Neither fields nor condition_value_fn.")
+    except AttributeError:  # Specifically for _asdict()
+      logger.error(
+          "Failed to call _asdict() on element. Type: %s. Element: "
+          "%s. Ensure input is beam.Row.",
+          type(req),
+          req,
+      )
+      return None
+    except Exception as e:
+      logger.error(
+          "Error getting condition values for row %s: %s",
+          req,
+          e,
+          exc_info=True)
+      return None
+
+  def _build_single_row_filter(
+      self, req_row: BeamRow, condition_values_dict: Dict[str, Any]) -> str:
+    """Builds the filter string part for a single row."""
+    try:
+      if self.row_restriction_template_fn:
+        # User's provided signature for row_restriction_template_fn
+        template_or_filter = self.row_restriction_template_fn(
+            condition_values_dict, self.primary_keys, req_row)
+        if not isinstance(template_or_filter, str):
+          raise TypeError(
+              "row_restriction_template_fn must return a string "
+              "(filter or template to be formatted)")
+        # Assuming if it takes condition_values_dict, it might be returning
+        # the final filter or a template. If it's a template, it still needs
+        # .format(). For now, assume it's a template that might still need
+        # formatting OR the final filter string. Let's assume it's the final
+        # filter string as per user's code.
+        # Directly return what the user's function gives.
+        return template_or_filter
+      elif self.row_restriction_template:
+        return self.row_restriction_template.format(**condition_values_dict)
+      else:
+        raise ValueError(
+            "Internal Error: No template or template function available.")
+    except KeyError as e:  # if user's fn returns template and format fails
+      raise ValueError(
+          f"Placeholder {{{e}}} in template not found in "
+          f"condition values: {condition_values_dict.keys()}")
+    except Exception as e:
+      logger.error(
+          "Error building filter for row %s with values %s: %s",
+          req_row,
+          condition_values_dict,
+          e,
+          exc_info=True,
+      )
+      return ""
+
+  def _apply_renaming(self, bq_row_dict: BQRowDict) -> BQRowDict:
+    if not self._rename_map:
+      return bq_row_dict
+    return {self._rename_map.get(k, k): v for k, v in bq_row_dict.items()}
+
+  def _arrow_to_dicts(self, response: ReadRowsResponse) -> Iterator[BQRowDict]:
+    # Now uses self._arrow_schema directly
+    if response.arrow_record_batch:
+      if not self._arrow_schema:
+        logger.error(
+            "Cannot process Arrow batch: Schema not "
+            "available/cached in handler.")
+        return
+      try:
+        serialized_batch = response.arrow_record_batch.serialized_record_batch
+        record_batch = pa.ipc.read_record_batch(
+            pa.py_buffer(serialized_batch), self._arrow_schema)
+        arrow_table = pa.Table.from_batches([record_batch])
+        yield from arrow_table.to_pylist()
+      except Exception as e:
+        logger.error(
+            "Error converting Arrow batch to dicts: %s", e, exc_info=True)
+
+  def _execute_storage_read(self, combined_row_filter: str) -> List[BQRowDict]:
+    if not self._client:
+      self.__enter__()
+    if not self._client:
+      raise RuntimeError("BQ Client failed to initialize.")
+    if not combined_row_filter:
+      logger.warning("Empty filter, skipping BQ read.")
+      return []
+
+    try:
+      table_project, dataset_id, table_id = self.table_name.split(".")
+    except ValueError:
+      raise ValueError(
+          f"Invalid table_name: '{self.table_name}'. Expected "
+          "'project.dataset.table'.")
+    parent_project = self.project
+    table_resource = (
+        f"projects/{table_project}/datasets/{dataset_id}/tables/{table_id}")
+
+    session = None
+    try:
+      # TODO: Improve max_stream_count to be dynamic based on input size,
+      # data volume, and query complexity for optimal performance
+      req = {
+          "parent": f"projects/{parent_project}",
+          "read_session": ReadSession(
+              table=table_resource,
+              data_format=DataFormat.ARROW,
+              read_options=ReadSession.TableReadOptions(
+                  row_restriction=combined_row_filter,
+                  selected_fields=self._bq_select_columns,
+              ),
+          ),
+          "max_stream_count": self.max_stream_count,
+      }
+      session = self._client.create_read_session(request=req)
+      logger.debug(
+          "Session with %s streams. Filter: %s",
+          len(session.streams),
+          combined_row_filter,
+      )
+      if session.streams and session.arrow_schema:
+        if not self._arrow_schema:
+          self._arrow_schema = pa.ipc.read_schema(
+              pa.py_buffer(session.arrow_schema.serialized_schema))
+          logger.debug("Deserialized Arrow schema for current call.")
+      elif session.streams:
+        logger.error("Session has streams but no schema.")
+        return []
+    except (BadRequest, NotFound, GoogleAPICallError) as e:
+      logger.error(
+          "BQ API error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+      )
+      return []
+    except Exception as e:
+      logger.error(
+          "Unexpected error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+          exc_info=True,
+      )
+      return []
+
+    if not session or not session.streams:
+      logger.warning("No streams for filter: %s", combined_row_filter)
+      return []
+
+    def _read_single_stream_worker(stream_name: str) -> List[BQRowDict]:
+      worker_results = []
+      if not self._client or not self._arrow_schema:
+        logger.error("Stream %s: Client/schema missing in worker.", stream_name)
+        return worker_results
+      try:
+        reader = self._client.read_rows(stream_name)
+        for response in reader:
+          worker_results.extend(self._arrow_to_dicts(response))  # Uses
+          # self._arrow_schema
+      except Exception as e:
+        logger.error(
+            "Error reading stream %s in worker: %s",
+            stream_name,
+            e,
+            exc_info=True,
+        )
+      return worker_results
+
+    all_bq_rows_original_keys = []
+    num_api_streams = len(session.streams)
+    max_workers = num_api_streams
+    if self.max_parallel_streams is not None and self.max_parallel_streams > 0:
+      max_workers = min(num_api_streams, self.max_parallel_streams)
+    if max_workers <= 0:
+      max_workers = 1
+    logger.debug(
+        "Reading %s API streams using %s threads.",
+        num_api_streams,
+        max_workers)
+    futures = []
+    try:
+      with concurrent.futures.ThreadPoolExecutor(
+          max_workers=max_workers) as executor:
+        for stream in session.streams:
+          futures.append(
+              executor.submit(_read_single_stream_worker, stream.name))
+        for future in concurrent.futures.as_completed(futures):
+          try:
+            all_bq_rows_original_keys.extend(future.result())
+          except Exception as e:
+            logger.error("Error processing future result: %s", e, exc_info=True)
+    except Exception as pool_error:
+      logger.error("ThreadPool error: %s", pool_error, exc_info=True)
+    logger.debug("Fetched %s rows from BQ.", len(all_bq_rows_original_keys))
+    return all_bq_rows_original_keys

Review Comment:
   Hi @tvalentyn 
    Sorry for the late reply.
    We recently deployed this version of the code in production, but it didn’t work well due to conflicts between the thread pool used for processing connection streams and the Dataflow process. 
    If you have any suggestions or ideas on handling stream connections more effectively, they would be greatly appreciated. If there’s a better approach, we’d love to hear your thoughts.
    To address the issues we encountered, we switched to a custom transform, which has been performing well. I will add that to this pull request soon.
    Best regards.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2952640165

   Hi @sjvanrossum, 👋
   
   Could you please take a look at this pull request when you have a moment?
   
   It introduces a new `BigQueryStorageEnrichmentHandler` for Apache Beam, which leverages the BigQuery Storage Read API. The goal is to provide a more performant and potentially cost-effective way to enrich PCollections by fetching data from BigQuery, as an alternative to traditional SQL-based lookups.
   
   The PR includes the handler implementation and accompanying documentation.
   
   Please review the changes and let me know if anything needs an update or further clarification.
   
   Thanks, 
   @pandasanjay


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2952712264

   Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment `assign set of reviewers`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2159542028


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API

Review Comment:
   > Previously, if fields = ['id'] and the corresponding parameter was null in the input, the entire record would be dropped. This behavior has now been addressed part of the PR.
   
   This seems like a good breaking change (fixing potential data loss)
   
   > Improved row restriction templating.
   
   Is this just adding `row_restriction_template_fn`? Or is there truly breaking behavior (where the behavior changes under the covers)?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3649380587

   This pull request has been closed due to lack of activity. If you think that is incorrect, or the pull request requires review, you can revive the PR at any time.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3620192218

   This pull request has been marked as stale due to 60 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the dev@beam.apache.org list. Thank you for your contributions.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3285693472

   waiting on author


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "mohamedawnallah (via GitHub)" <gi...@apache.org>.
mohamedawnallah commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2979118447

   @pandasanjay – It looks like the example pipelines fail with this error:
   ```
   > from google.api_core.exceptions import TooManyRequests
   E   ModuleNotFoundError: No module named 'google.api_core'
   ```
   
   Given this to be installed have you tested this with BQ table in your Google Cloud and the tests pass?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2955719432

   Thank you @mohamedawnallah for providing additional details! 👍
   
   I’m planning to make a few more documentation updates similar to yours. 
   
   It looks like the pipeline failures aren’t related to my changes—I’m currently investigating the linting issues.
   Do these pipelines often fail and require multiple retries to pass? 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2158863302


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API

Review Comment:
   Rather than having a whole new enrichment handler, if we want to expose storage read we should just make read mode a parameter to https://github.com/apache/beam/blob/da1768f18c0333d19a7b90f9cda072cbf1ea1f01/sdks/python/apache_beam/transforms/enrichment_handlers/bigquery.py#L55 (or really probably something like a `BigQueryReadOptions` class.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2992614335

   > Have you actually seen poor performance from the existing handler in practice? Since we're usually not doing bulk reads with enrichment, its unclear to me that the storage read approach will actually be more performant
   
   @damccorm – For our use case of building an SCD Type 2 pipeline focused on slot consumption and cost optimization, we've observed that using the BigQuery Storage Read API offers significant advantages:
   
   - **Improved Performance:** The Storage Read API enables concurrent data reads through streaming, eliminating the need to compete for slots as required by the traditional query engine.
   - **Cost Optimization:** There are two main ways to save costs:
        - **No Need for Dedicated Slots:** Since the Storage Read API doesn't require slot reservations, we avoid the ongoing costs associated with dedicated slots.
        -  **Lower Data Scan Costs:** As of June 2024, the cost for scanning data via the Storage Read API is $1.10 per TiB, compared to $5.00 per TiB when using the BigQuery Query Engine.
        
   Only thing is if we can get the the partioning and clustering right, this will be cheap and efficent solution. 
   
   **References:**
   [BigQuery Storage Read API Pricing](https://cloud.google.com/bigquery/pricing#storage-api)
   [BigQuery On-Demand Pricing](https://cloud.google.com/bigquery/pricing#on_demand)
   
   Let me know if your thoughts :)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2997397422

   > > > I’ve noticed that wherever this module is used, the Beam pipeline is skipping those tests
   > > 
   > > 
   > > @pandasanjay I found it depends mostly on the GitHub runner/workflow those tests run on. I have recently come across this when I have been working on Milvus Enrichment Handler #35216.
   > > Using try-except on the related imports that need dependencies and skipping that test would solve the issue. That being said, I think it may change from case to case, so someone may check that this happens on specific workflows, not all. Otherwise, those test cases would never run since they are entirely skipped.
   > 
   > @mohamedawnallah I’ve noticed the same issue and even used that approach to fix my integration tests. However, it seems that all the example tests are failing at that point in the GitHub Actions workflow, which raises the question of whether this module has ever been successfully installed and run via GitHub Actions. This aligns with your last point.
   > 
   > I think we could use some guidance on how to proceed here.
   
   Generally skipping if dependencies are not present is the recommended path. Some tests will only run as postcommits (e.g. see conversation in https://github.com/apache/beam/pull/35395)
   
   In this case since we're just blocking on GCP dependencies which should get installed as part of the postcommit runs - you should be able to run the python postcommit following https://github.com/apache/beam/blob/master/.github/workflows/README.md#workflow-triggers as part of this pr (you would modify https://github.com/apache/beam/blob/master/.github/trigger_files/beam_PostCommit_Python.json). Its always a good idea to make sure tests actually run when they get added


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3023760502

   Reminder, please take a look at this pr: @damccorm @liferoad 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3035978782

   Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @tvalentyn for label python.
   R: @kennknowles for label website.
   
   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)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "tvalentyn (via GitHub)" <gi...@apache.org>.
tvalentyn commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3049676661

   waiting on author


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2407618889


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API
+with support for field renaming via aliases in `column_names`,
+additional non-key fields for filtering, dynamic row restriction templates,
+experimental parallel stream reading using ThreadPoolExecutor, and custom
+row selection.
+"""
+
+import concurrent.futures  # For parallel stream reading
+import logging
+import re
+from collections.abc import Callable
+from collections.abc import Mapping
+from typing import Any
+from typing import Dict
+from typing import Iterator
+from typing import List
+from typing import Optional
+from typing import Set
+from typing import Tuple
+from typing import Union
+import pyarrow as pa
+from google.api_core.exceptions import BadRequest
+from google.api_core.exceptions import GoogleAPICallError
+from google.api_core.exceptions import NotFound
+from google.cloud.bigquery_storage import BigQueryReadClient
+
+from apache_beam.pvalue import Row as BeamRow
+from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+
+try:
+  from google.cloud.bigquery_storage import types
+  from google.cloud.bigquery_storage.types import (
+      DataFormat, ReadRowsResponse, ReadSession)
+except ImportError:
+  # Fallback for older versions where types might be in different location
+  from google.cloud.bigquery_storage import types
+  ReadRowsResponse = types.ReadRowsResponse
+  ReadSession = types.ReadSession
+  DataFormat = types.DataFormat
+
+# --- Configure Logging ---
+logger = logging.getLogger(__name__)
+
+# Type hints for functions
+# Input functions expect beam.Row for clarity, use beam.Row.as_dict inside if
+# needed
+ConditionValueFn = Callable[[BeamRow], Dict[str, Any]]
+# Updated RowRestrictionTemplateFn signature based on user provided code
+RowRestrictionTemplateFn = Callable[
+    [Dict[str, Any], Optional[List[str]], BeamRow], str]
+BQRowDict = Dict[str, Any]
+# Callback for selecting the "latest" or desired row from multiple BQ results
+LatestValueSelectorFn = Optional[Callable[[List[BeamRow], BeamRow],
+                                          Optional[BeamRow]]]
+
+# Regex to parse "column as alias" format, ignoring case for "as"
+ALIAS_REGEX = re.compile(r"^(.*?)\s+as\s+(.*)$", re.IGNORECASE)
+
+
+def _validate_bigquery_metadata(
+    project,
+    table_name,
+    row_restriction_template,
+    row_restriction_template_fn,
+    fields,
+    condition_value_fn,
+    additional_condition_fields,
+):
+  """Validates parameters for Storage API usage."""
+  if not project:
+    raise ValueError("`project` must be provided.")
+  if not table_name:
+    raise ValueError("`table_name` must be provided.")
+  if (row_restriction_template and
+      row_restriction_template_fn) or (not row_restriction_template and
+                                       not row_restriction_template_fn):
+    raise ValueError(
+        "Provide exactly one of `row_restriction_template` or "
+        "`row_restriction_template_fn`.")
+  if (fields and condition_value_fn) or (not fields and not condition_value_fn):
+    raise ValueError("Provide exactly one of `fields` or `condition_value_fn`.")
+  if additional_condition_fields and condition_value_fn:
+    raise ValueError(
+        "`additional_condition_fields` cannot be used with "
+        "`condition_value_fn`.")
+
+
+class BigQueryStorageEnrichmentHandler(
+    EnrichmentSourceHandler[Union[BeamRow, list[BeamRow]],
+                            Union[BeamRow, list[BeamRow]]]):
+  """Enrichment handler for Google Cloud BigQuery using the Storage Read API.
+    (Refer to __init__ for full list of features and arguments)
+    """
+  def __init__(
+      self,
+      project: str,
+      table_name: str,
+      *,
+      row_restriction_template: Optional[str] = None,
+      row_restriction_template_fn: Optional[RowRestrictionTemplateFn] = None,
+      fields: Optional[list[str]] = None,  # Fields for KEY and filtering
+      additional_condition_fields: Optional[list[str]] = None,  # Fields ONLY
+      # for filtering
+      column_names: Optional[list[str]] = None,  # Columns to select + aliases
+      condition_value_fn: Optional[ConditionValueFn] = None,  # Alt way to get
+      # filter/key values
+      min_batch_size: Optional[int] = 1,
+      max_batch_size: Optional[int] = 1000,  # Batching enabled by default
+      max_batch_duration_secs: Optional[int] = None,
+      max_parallel_streams: Optional[int] = None,  # Max workers for
+      # ThreadPoolExecutor
+      max_stream_count: int = 100,  # Max streams for BigQuery Storage Read
+      # --- Added latest_value_selector and primary_keys from user code ---
+      latest_value_selector: LatestValueSelectorFn = None,
+      primary_keys: Optional[list[str]] = None,  # --- End added parameters ---
+  ):
+    """
+        Initializes the BigQueryStorageEnrichmentHandler.
+
+        Args:
+            project: Google Cloud project ID.
+            table_name: Fully qualified BigQuery table name.
+            row_restriction_template: (Optional[str]) Template string for a
+                single row's filter condition. If `row_restriction_template_fn`
+                is not provided, this template will be formatted with values
+                from `fields` and `additional_condition_fields`.
+            row_restriction_template_fn: (Optional[Callable]) Function that
+                takes (condition_values_dict, primary_keys, request_row) and
+                returns a fully formatted filter string or template to 
+                be formatted.
+            fields: (Optional[list[str]]) Input `beam.Row` field names used to
+                generate the dictionary for formatting the row restriction
+                template AND for generating the internal join/cache key.
+            additional_condition_fields: (Optional[list[str]]) Additional input
+                `beam.Row` field names used ONLY for formatting the row
+                restriction template. Not part of join/cache key.
+            column_names: (Optional[list[str]]) Names/aliases of columns to
+                select. Supports "original_col as alias_col" format. If None,
+                selects '*'.
+            condition_value_fn: (Optional[Callable]) Function returning a
+                dictionary for formatting row restriction template and for
+                join/cache key. Takes precedence over `fields`.
+            min_batch_size (Optional[int]): Minimum elements per batch.
+                Defaults to 1.
+            max_batch_size (Optional[int]): Maximum elements per batch.
+                Defaults to 1000 for batching. Set to 1 for single element
+                processing to disable batching.
+            max_batch_duration_secs (Optional[int]): Maximum batch buffering
+                time in seconds. Defaults to 5 seconds.
+            max_parallel_streams (Optional[int]): Max worker threads for
+                ThreadPoolExecutor for reading streams in parallel within a
+                single `__call__`.
+            max_stream_count (int): Maximum number of streams for BigQuery
+                Storage Read API. Defaults to 100. Setting to 0 lets BigQuery
+                decide the optimal number of streams.
+            latest_value_selector: (Optional) Callback function to select the
+                desired row when multiple BQ rows match a key. Takes
+                `List[beam.Row]` (BQ results) and the original `beam.Row`
+                (request) and returns one `beam.Row` or None.
+            primary_keys: (Optional[list[str]]) Primary key fields used
+                potentially by `row_restriction_template_fn` or
+                `latest_value_selector`.
+        """
+    _validate_bigquery_metadata(
+        project,
+        table_name,
+        row_restriction_template,
+        row_restriction_template_fn,
+        fields,
+        condition_value_fn,
+        additional_condition_fields,
+    )
+    self.project = project
+    self.table_name = table_name
+    self.row_restriction_template = row_restriction_template
+    self.row_restriction_template_fn = row_restriction_template_fn
+    self.fields = fields
+    self.additional_condition_fields = additional_condition_fields or []
+    self.condition_value_fn = condition_value_fn
+    self.max_parallel_streams = max_parallel_streams
+    self.max_stream_count = max_stream_count
+    # --- Store new parameters ---
+    self._latest_value_callback = latest_value_selector
+    self.primary_keys = primary_keys
+    # --- End store ---
+
+    self._rename_map: Dict[str, str] = {}
+    bq_columns_to_select_set: Set[str] = set()
+    self._select_all_columns = False
+    if column_names:
+      for name_or_alias in column_names:
+        match = ALIAS_REGEX.match(name_or_alias)
+        if match:
+          original_col, alias_col = (
+              match.group(1).strip(),
+              match.group(2).strip(),
+          )
+          if not original_col or not alias_col:
+            raise ValueError(f"Invalid alias: '{name_or_alias}'")
+          bq_columns_to_select_set.add(original_col)
+          self._rename_map[original_col] = alias_col
+        else:
+          col = name_or_alias.strip()
+          if not col:
+            raise ValueError("Empty column name.")
+          if col == "*":
+            self._select_all_columns = True
+            break
+          bq_columns_to_select_set.add(col)
+    else:
+      self._select_all_columns = True
+
+    key_gen_fields_set = set(self.fields or [])
+    if self._select_all_columns:
+      self._bq_select_columns = ["*"]
+      if key_gen_fields_set:
+        logger.debug(
+            "Selecting all columns ('*'). Key fields %s assumed present.",
+            key_gen_fields_set,
+        )
+    else:
+      fields_to_ensure_selected = set()
+      if self.fields:
+        reverse_rename_map = {v: k for k, v in self._rename_map.items()}
+        for field in self.fields:
+          original_name = reverse_rename_map.get(field, field)
+          fields_to_ensure_selected.add(original_name)
+      # Ensure primary keys (if defined for callback use) are selected if not
+      # already
+      if self.primary_keys:
+        for pk_field in self.primary_keys:
+          original_pk_name = {
+              v: k
+              for k, v in self._rename_map.items()
+          }.get(pk_field, pk_field)
+          fields_to_ensure_selected.add(original_pk_name)
+
+      final_select_set = bq_columns_to_select_set.union(
+          fields_to_ensure_selected)
+      self._bq_select_columns = sorted(list(final_select_set))
+      if not self._bq_select_columns:
+        raise ValueError("No columns determined for selection.")
+
+    logger.info(
+        "Handler Initialized. Selecting BQ Columns: %s. Renaming map: %s",
+        self._bq_select_columns,
+        self._rename_map,
+    )
+
+    self._batching_kwargs = {}
+    # Set defaults for optional parameters
+    min_batch_size = min_batch_size or 1
+    max_batch_size = max_batch_size or 1000
+    max_batch_duration_secs = max_batch_duration_secs or 5
+
+    if max_batch_size > 1:
+      self._batching_kwargs["min_batch_size"] = min_batch_size
+      self._batching_kwargs["max_batch_size"] = max_batch_size
+      self._batching_kwargs["max_batch_duration_secs"] = max_batch_duration_secs
+    else:
+      self._batching_kwargs["min_batch_size"] = 1
+      self._batching_kwargs["max_batch_size"] = 1
+
+    self._client: Optional[BigQueryReadClient] = None
+    self._arrow_schema: Optional[pa.Schema] = None
+
+  def __enter__(self):
+    if not self._client:
+      self._client = BigQueryReadClient()
+      logger.info("BigQueryStorageEnrichmentHandler: Client created.")
+    self._arrow_schema = None
+
+  def _get_condition_values_dict(self,
+                                 req: BeamRow) -> Optional[Dict[str, Any]]:
+    try:
+      if self.condition_value_fn:
+        values_dict = self.condition_value_fn(req)
+        if values_dict is None or any(v is None for v in values_dict.values()):
+          logger.warning(
+              "condition_value_fn returned None or None value(s). "
+              "Skipping: %s. Values: %s",
+              req,
+              values_dict,
+          )
+          return None
+        return values_dict
+      elif self.fields is not None:
+        req_dict = req._asdict()
+        values_dict = {}
+        all_req_fields = (self.fields or []) + self.additional_condition_fields
+        for field in all_req_fields:
+          # User's provided logic for row_restriction_template_fn handling:
+          if not self.row_restriction_template_fn:
+            if field not in req_dict or req_dict[field] is None:
+              logger.warning(
+                  "Input row missing field '%s' or None (needed "
+                  "for filter). Skipping: %s",
+                  field,
+                  req,
+              )
+              return None
+          values_dict[field] = req_dict.get(field)  # Use get for safety
+        return values_dict
+      else:
+        raise ValueError(
+            "Internal error: Neither fields nor condition_value_fn.")
+    except AttributeError:  # Specifically for _asdict()
+      logger.error(
+          "Failed to call _asdict() on element. Type: %s. Element: "
+          "%s. Ensure input is beam.Row.",
+          type(req),
+          req,
+      )
+      return None
+    except Exception as e:
+      logger.error(
+          "Error getting condition values for row %s: %s",
+          req,
+          e,
+          exc_info=True)
+      return None
+
+  def _build_single_row_filter(
+      self, req_row: BeamRow, condition_values_dict: Dict[str, Any]) -> str:
+    """Builds the filter string part for a single row."""
+    try:
+      if self.row_restriction_template_fn:
+        # User's provided signature for row_restriction_template_fn
+        template_or_filter = self.row_restriction_template_fn(
+            condition_values_dict, self.primary_keys, req_row)
+        if not isinstance(template_or_filter, str):
+          raise TypeError(
+              "row_restriction_template_fn must return a string "
+              "(filter or template to be formatted)")
+        # Assuming if it takes condition_values_dict, it might be returning
+        # the final filter or a template. If it's a template, it still needs
+        # .format(). For now, assume it's a template that might still need
+        # formatting OR the final filter string. Let's assume it's the final
+        # filter string as per user's code.
+        # Directly return what the user's function gives.
+        return template_or_filter
+      elif self.row_restriction_template:
+        return self.row_restriction_template.format(**condition_values_dict)
+      else:
+        raise ValueError(
+            "Internal Error: No template or template function available.")
+    except KeyError as e:  # if user's fn returns template and format fails
+      raise ValueError(
+          f"Placeholder {{{e}}} in template not found in "
+          f"condition values: {condition_values_dict.keys()}")
+    except Exception as e:
+      logger.error(
+          "Error building filter for row %s with values %s: %s",
+          req_row,
+          condition_values_dict,
+          e,
+          exc_info=True,
+      )
+      return ""
+
+  def _apply_renaming(self, bq_row_dict: BQRowDict) -> BQRowDict:
+    if not self._rename_map:
+      return bq_row_dict
+    return {self._rename_map.get(k, k): v for k, v in bq_row_dict.items()}
+
+  def _arrow_to_dicts(self, response: ReadRowsResponse) -> Iterator[BQRowDict]:
+    # Now uses self._arrow_schema directly
+    if response.arrow_record_batch:
+      if not self._arrow_schema:
+        logger.error(
+            "Cannot process Arrow batch: Schema not "
+            "available/cached in handler.")
+        return
+      try:
+        serialized_batch = response.arrow_record_batch.serialized_record_batch
+        record_batch = pa.ipc.read_record_batch(
+            pa.py_buffer(serialized_batch), self._arrow_schema)
+        arrow_table = pa.Table.from_batches([record_batch])
+        yield from arrow_table.to_pylist()
+      except Exception as e:
+        logger.error(
+            "Error converting Arrow batch to dicts: %s", e, exc_info=True)
+
+  def _execute_storage_read(self, combined_row_filter: str) -> List[BQRowDict]:
+    if not self._client:
+      self.__enter__()
+    if not self._client:
+      raise RuntimeError("BQ Client failed to initialize.")
+    if not combined_row_filter:
+      logger.warning("Empty filter, skipping BQ read.")
+      return []
+
+    try:
+      table_project, dataset_id, table_id = self.table_name.split(".")
+    except ValueError:
+      raise ValueError(
+          f"Invalid table_name: '{self.table_name}'. Expected "
+          "'project.dataset.table'.")
+    parent_project = self.project
+    table_resource = (
+        f"projects/{table_project}/datasets/{dataset_id}/tables/{table_id}")
+
+    session = None
+    try:
+      # TODO: Improve max_stream_count to be dynamic based on input size,
+      # data volume, and query complexity for optimal performance
+      req = {
+          "parent": f"projects/{parent_project}",
+          "read_session": ReadSession(
+              table=table_resource,
+              data_format=DataFormat.ARROW,
+              read_options=ReadSession.TableReadOptions(
+                  row_restriction=combined_row_filter,
+                  selected_fields=self._bq_select_columns,
+              ),
+          ),
+          "max_stream_count": self.max_stream_count,
+      }
+      session = self._client.create_read_session(request=req)
+      logger.debug(
+          "Session with %s streams. Filter: %s",
+          len(session.streams),
+          combined_row_filter,
+      )
+      if session.streams and session.arrow_schema:
+        if not self._arrow_schema:
+          self._arrow_schema = pa.ipc.read_schema(
+              pa.py_buffer(session.arrow_schema.serialized_schema))
+          logger.debug("Deserialized Arrow schema for current call.")
+      elif session.streams:
+        logger.error("Session has streams but no schema.")
+        return []
+    except (BadRequest, NotFound, GoogleAPICallError) as e:
+      logger.error(
+          "BQ API error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+      )
+      return []
+    except Exception as e:
+      logger.error(
+          "Unexpected error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+          exc_info=True,
+      )
+      return []
+
+    if not session or not session.streams:
+      logger.warning("No streams for filter: %s", combined_row_filter)
+      return []
+
+    def _read_single_stream_worker(stream_name: str) -> List[BQRowDict]:
+      worker_results = []
+      if not self._client or not self._arrow_schema:
+        logger.error("Stream %s: Client/schema missing in worker.", stream_name)
+        return worker_results
+      try:
+        reader = self._client.read_rows(stream_name)
+        for response in reader:
+          worker_results.extend(self._arrow_to_dicts(response))  # Uses
+          # self._arrow_schema
+      except Exception as e:
+        logger.error(
+            "Error reading stream %s in worker: %s",
+            stream_name,
+            e,
+            exc_info=True,
+        )
+      return worker_results
+
+    all_bq_rows_original_keys = []
+    num_api_streams = len(session.streams)
+    max_workers = num_api_streams
+    if self.max_parallel_streams is not None and self.max_parallel_streams > 0:
+      max_workers = min(num_api_streams, self.max_parallel_streams)
+    if max_workers <= 0:
+      max_workers = 1
+    logger.debug(
+        "Reading %s API streams using %s threads.",
+        num_api_streams,
+        max_workers)
+    futures = []
+    try:
+      with concurrent.futures.ThreadPoolExecutor(
+          max_workers=max_workers) as executor:
+        for stream in session.streams:
+          futures.append(
+              executor.submit(_read_single_stream_worker, stream.name))
+        for future in concurrent.futures.as_completed(futures):
+          try:
+            all_bq_rows_original_keys.extend(future.result())
+          except Exception as e:
+            logger.error("Error processing future result: %s", e, exc_info=True)
+    except Exception as pool_error:
+      logger.error("ThreadPool error: %s", pool_error, exc_info=True)
+    logger.debug("Fetched %s rows from BQ.", len(all_bq_rows_original_keys))
+    return all_bq_rows_original_keys

Review Comment:
   Hey @pandasanjay I can continue with this review. Could we please start with my comments here though - https://github.com/apache/beam/pull/35197/files#r2158863302 ? It has implications on the whole PR (I'm not sure whether we need the whole change, though you did call out some good pieces for us to improve)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2159536038


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API

Review Comment:
   That’s a great idea, @damccorm —I was actually thinking about this recently as well. Let me take a look and see what we can do.
   
   The last time I worked with BQ enrichment, I noticed a few missing features, so I ended up copying the code into our project and extending the BigQueryEnrichmentHandler. These enhancements have introduced some breaking changes:
   
   1. Improved row restriction templating.
   2. Previously, if fields = ['id'] and the corresponding parameter was null in the input, the entire record would be dropped. This behavior has now been addressed part of the PR. 
   
   There are a few other enhancements as well. All of these extensions are available in the current PR, and you can find more details here:
   https://github.com/pandasanjay/beam-custom-implementation/blob/main/docs/bigquery_storage_enrichment_handler.md
   
   Are we okay with introducing these breaking changes?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2979095438

   Looks like there is a need for a BQ table to make the examples pipeline to pass.
   ![image](https://github.com/user-attachments/assets/511aad22-6347-4f50-a5c3-d4e797375b3b)
   project_id = "apache-beam-testing"
   dataset = "beam-test"
   table_name = "bigquery-enrichment-test-products"
   
   
   -- BigQuery DDL for enrichment_with_bigquery_storage_basic
   
       CREATE TABLE `apache-beam-testing.beam-test.bigquery-enrichment-test-products` (
           id INT64,
           product_name STRING,
           category STRING,
           unit_price FLOAT64
       );
   
       INSERT INTO `apache-beam-testing.beam-test.bigquery-enrichment-test-products` (id, product_name, category, unit_price) VALUES
           (101, 'Laptop', 'Electronics', 999.99),
           (102, 'Desk Chair', 'Furniture', 199.99),
           (103, 'Monitor', 'Electronics', 299.99);
    
    If this can be configured in any config in code, please let me know. 
    
   @damccorm Could you please help here. Thanks :)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "mohamedawnallah (via GitHub)" <gi...@apache.org>.
mohamedawnallah commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2955764247

   > It looks like the pipeline failures aren’t related to my changes—I’m currently investigating the linting issues. Do these pipelines often fail and require multiple retries to pass?
   
   Some CI tests can occasionally be flaky, but this doesn’t happen very often. To minimize issues, make sure you’re using the latest code from the Beam upstream `master` branch (`git merge`) and run all tests locally (`gradlew` tasks is helpful here). If any CI tests still fail, This can be investigated from CI test logs and resolve as you go. 👍


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3063969842

   Hi @tvalentyn 
    Sorry for the late reply.
    We recently deployed this version of the code in production, but it didn’t work well due to conflicts between the thread pool used for processing connection streams and the Dataflow process. You can find the thread pool code here.
    If you have any suggestions or ideas on handling stream connections more effectively, they would be greatly appreciated. If there’s a better approach, we’d love to hear your thoughts.
    To address the issues we encountered, we switched to a custom transform, which has been performing well. I will add that to this pull request soon.
    Best regards.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "tvalentyn (via GitHub)" <gi...@apache.org>.
tvalentyn commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2205456442


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API
+with support for field renaming via aliases in `column_names`,
+additional non-key fields for filtering, dynamic row restriction templates,
+experimental parallel stream reading using ThreadPoolExecutor, and custom
+row selection.
+"""
+
+import concurrent.futures  # For parallel stream reading
+import logging
+import re
+from collections.abc import Callable
+from collections.abc import Mapping
+from typing import Any
+from typing import Dict
+from typing import Iterator
+from typing import List
+from typing import Optional
+from typing import Set
+from typing import Tuple
+from typing import Union
+import pyarrow as pa
+from google.api_core.exceptions import BadRequest
+from google.api_core.exceptions import GoogleAPICallError
+from google.api_core.exceptions import NotFound
+from google.cloud.bigquery_storage import BigQueryReadClient
+
+from apache_beam.pvalue import Row as BeamRow
+from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+
+try:
+  from google.cloud.bigquery_storage import types
+  from google.cloud.bigquery_storage.types import (
+      DataFormat, ReadRowsResponse, ReadSession)
+except ImportError:
+  # Fallback for older versions where types might be in different location
+  from google.cloud.bigquery_storage import types
+  ReadRowsResponse = types.ReadRowsResponse
+  ReadSession = types.ReadSession
+  DataFormat = types.DataFormat
+
+# --- Configure Logging ---
+logger = logging.getLogger(__name__)
+
+# Type hints for functions
+# Input functions expect beam.Row for clarity, use beam.Row.as_dict inside if
+# needed
+ConditionValueFn = Callable[[BeamRow], Dict[str, Any]]
+# Updated RowRestrictionTemplateFn signature based on user provided code
+RowRestrictionTemplateFn = Callable[
+    [Dict[str, Any], Optional[List[str]], BeamRow], str]
+BQRowDict = Dict[str, Any]
+# Callback for selecting the "latest" or desired row from multiple BQ results
+LatestValueSelectorFn = Optional[Callable[[List[BeamRow], BeamRow],
+                                          Optional[BeamRow]]]
+
+# Regex to parse "column as alias" format, ignoring case for "as"
+ALIAS_REGEX = re.compile(r"^(.*?)\s+as\s+(.*)$", re.IGNORECASE)
+
+
+def _validate_bigquery_metadata(
+    project,
+    table_name,
+    row_restriction_template,
+    row_restriction_template_fn,
+    fields,
+    condition_value_fn,
+    additional_condition_fields,
+):
+  """Validates parameters for Storage API usage."""
+  if not project:
+    raise ValueError("`project` must be provided.")
+  if not table_name:
+    raise ValueError("`table_name` must be provided.")
+  if (row_restriction_template and
+      row_restriction_template_fn) or (not row_restriction_template and
+                                       not row_restriction_template_fn):
+    raise ValueError(
+        "Provide exactly one of `row_restriction_template` or "
+        "`row_restriction_template_fn`.")
+  if (fields and condition_value_fn) or (not fields and not condition_value_fn):
+    raise ValueError("Provide exactly one of `fields` or `condition_value_fn`.")
+  if additional_condition_fields and condition_value_fn:
+    raise ValueError(
+        "`additional_condition_fields` cannot be used with "
+        "`condition_value_fn`.")
+
+
+class BigQueryStorageEnrichmentHandler(
+    EnrichmentSourceHandler[Union[BeamRow, list[BeamRow]],
+                            Union[BeamRow, list[BeamRow]]]):
+  """Enrichment handler for Google Cloud BigQuery using the Storage Read API.
+    (Refer to __init__ for full list of features and arguments)
+    """
+  def __init__(
+      self,
+      project: str,
+      table_name: str,
+      *,
+      row_restriction_template: Optional[str] = None,
+      row_restriction_template_fn: Optional[RowRestrictionTemplateFn] = None,
+      fields: Optional[list[str]] = None,  # Fields for KEY and filtering
+      additional_condition_fields: Optional[list[str]] = None,  # Fields ONLY
+      # for filtering
+      column_names: Optional[list[str]] = None,  # Columns to select + aliases
+      condition_value_fn: Optional[ConditionValueFn] = None,  # Alt way to get
+      # filter/key values
+      min_batch_size: Optional[int] = 1,
+      max_batch_size: Optional[int] = 1000,  # Batching enabled by default
+      max_batch_duration_secs: Optional[int] = None,
+      max_parallel_streams: Optional[int] = None,  # Max workers for
+      # ThreadPoolExecutor
+      max_stream_count: int = 100,  # Max streams for BigQuery Storage Read
+      # --- Added latest_value_selector and primary_keys from user code ---
+      latest_value_selector: LatestValueSelectorFn = None,
+      primary_keys: Optional[list[str]] = None,  # --- End added parameters ---
+  ):
+    """
+        Initializes the BigQueryStorageEnrichmentHandler.
+
+        Args:
+            project: Google Cloud project ID.
+            table_name: Fully qualified BigQuery table name.
+            row_restriction_template: (Optional[str]) Template string for a
+                single row's filter condition. If `row_restriction_template_fn`
+                is not provided, this template will be formatted with values
+                from `fields` and `additional_condition_fields`.
+            row_restriction_template_fn: (Optional[Callable]) Function that
+                takes (condition_values_dict, primary_keys, request_row) and
+                returns a fully formatted filter string or template to 
+                be formatted.
+            fields: (Optional[list[str]]) Input `beam.Row` field names used to
+                generate the dictionary for formatting the row restriction
+                template AND for generating the internal join/cache key.
+            additional_condition_fields: (Optional[list[str]]) Additional input
+                `beam.Row` field names used ONLY for formatting the row
+                restriction template. Not part of join/cache key.
+            column_names: (Optional[list[str]]) Names/aliases of columns to
+                select. Supports "original_col as alias_col" format. If None,
+                selects '*'.
+            condition_value_fn: (Optional[Callable]) Function returning a
+                dictionary for formatting row restriction template and for
+                join/cache key. Takes precedence over `fields`.
+            min_batch_size (Optional[int]): Minimum elements per batch.
+                Defaults to 1.
+            max_batch_size (Optional[int]): Maximum elements per batch.
+                Defaults to 1000 for batching. Set to 1 for single element
+                processing to disable batching.
+            max_batch_duration_secs (Optional[int]): Maximum batch buffering
+                time in seconds. Defaults to 5 seconds.
+            max_parallel_streams (Optional[int]): Max worker threads for
+                ThreadPoolExecutor for reading streams in parallel within a
+                single `__call__`.
+            max_stream_count (int): Maximum number of streams for BigQuery
+                Storage Read API. Defaults to 100. Setting to 0 lets BigQuery
+                decide the optimal number of streams.
+            latest_value_selector: (Optional) Callback function to select the
+                desired row when multiple BQ rows match a key. Takes
+                `List[beam.Row]` (BQ results) and the original `beam.Row`
+                (request) and returns one `beam.Row` or None.
+            primary_keys: (Optional[list[str]]) Primary key fields used
+                potentially by `row_restriction_template_fn` or
+                `latest_value_selector`.
+        """
+    _validate_bigquery_metadata(
+        project,
+        table_name,
+        row_restriction_template,
+        row_restriction_template_fn,
+        fields,
+        condition_value_fn,
+        additional_condition_fields,
+    )
+    self.project = project
+    self.table_name = table_name
+    self.row_restriction_template = row_restriction_template
+    self.row_restriction_template_fn = row_restriction_template_fn
+    self.fields = fields
+    self.additional_condition_fields = additional_condition_fields or []
+    self.condition_value_fn = condition_value_fn
+    self.max_parallel_streams = max_parallel_streams
+    self.max_stream_count = max_stream_count
+    # --- Store new parameters ---
+    self._latest_value_callback = latest_value_selector
+    self.primary_keys = primary_keys
+    # --- End store ---
+
+    self._rename_map: Dict[str, str] = {}
+    bq_columns_to_select_set: Set[str] = set()
+    self._select_all_columns = False
+    if column_names:
+      for name_or_alias in column_names:
+        match = ALIAS_REGEX.match(name_or_alias)
+        if match:
+          original_col, alias_col = (
+              match.group(1).strip(),
+              match.group(2).strip(),
+          )
+          if not original_col or not alias_col:
+            raise ValueError(f"Invalid alias: '{name_or_alias}'")
+          bq_columns_to_select_set.add(original_col)
+          self._rename_map[original_col] = alias_col
+        else:
+          col = name_or_alias.strip()
+          if not col:
+            raise ValueError("Empty column name.")
+          if col == "*":
+            self._select_all_columns = True
+            break
+          bq_columns_to_select_set.add(col)
+    else:
+      self._select_all_columns = True
+
+    key_gen_fields_set = set(self.fields or [])
+    if self._select_all_columns:
+      self._bq_select_columns = ["*"]
+      if key_gen_fields_set:
+        logger.debug(
+            "Selecting all columns ('*'). Key fields %s assumed present.",
+            key_gen_fields_set,
+        )
+    else:
+      fields_to_ensure_selected = set()
+      if self.fields:
+        reverse_rename_map = {v: k for k, v in self._rename_map.items()}
+        for field in self.fields:
+          original_name = reverse_rename_map.get(field, field)
+          fields_to_ensure_selected.add(original_name)
+      # Ensure primary keys (if defined for callback use) are selected if not
+      # already
+      if self.primary_keys:
+        for pk_field in self.primary_keys:
+          original_pk_name = {
+              v: k
+              for k, v in self._rename_map.items()
+          }.get(pk_field, pk_field)
+          fields_to_ensure_selected.add(original_pk_name)
+
+      final_select_set = bq_columns_to_select_set.union(
+          fields_to_ensure_selected)
+      self._bq_select_columns = sorted(list(final_select_set))
+      if not self._bq_select_columns:
+        raise ValueError("No columns determined for selection.")
+
+    logger.info(
+        "Handler Initialized. Selecting BQ Columns: %s. Renaming map: %s",
+        self._bq_select_columns,
+        self._rename_map,
+    )
+
+    self._batching_kwargs = {}
+    # Set defaults for optional parameters
+    min_batch_size = min_batch_size or 1
+    max_batch_size = max_batch_size or 1000
+    max_batch_duration_secs = max_batch_duration_secs or 5
+
+    if max_batch_size > 1:
+      self._batching_kwargs["min_batch_size"] = min_batch_size
+      self._batching_kwargs["max_batch_size"] = max_batch_size
+      self._batching_kwargs["max_batch_duration_secs"] = max_batch_duration_secs
+    else:
+      self._batching_kwargs["min_batch_size"] = 1
+      self._batching_kwargs["max_batch_size"] = 1
+
+    self._client: Optional[BigQueryReadClient] = None
+    self._arrow_schema: Optional[pa.Schema] = None
+
+  def __enter__(self):
+    if not self._client:
+      self._client = BigQueryReadClient()
+      logger.info("BigQueryStorageEnrichmentHandler: Client created.")
+    self._arrow_schema = None
+
+  def _get_condition_values_dict(self,
+                                 req: BeamRow) -> Optional[Dict[str, Any]]:
+    try:
+      if self.condition_value_fn:
+        values_dict = self.condition_value_fn(req)
+        if values_dict is None or any(v is None for v in values_dict.values()):
+          logger.warning(
+              "condition_value_fn returned None or None value(s). "
+              "Skipping: %s. Values: %s",
+              req,
+              values_dict,
+          )
+          return None
+        return values_dict
+      elif self.fields is not None:
+        req_dict = req._asdict()
+        values_dict = {}
+        all_req_fields = (self.fields or []) + self.additional_condition_fields
+        for field in all_req_fields:
+          # User's provided logic for row_restriction_template_fn handling:
+          if not self.row_restriction_template_fn:
+            if field not in req_dict or req_dict[field] is None:
+              logger.warning(
+                  "Input row missing field '%s' or None (needed "
+                  "for filter). Skipping: %s",
+                  field,
+                  req,
+              )
+              return None
+          values_dict[field] = req_dict.get(field)  # Use get for safety
+        return values_dict
+      else:
+        raise ValueError(
+            "Internal error: Neither fields nor condition_value_fn.")
+    except AttributeError:  # Specifically for _asdict()
+      logger.error(
+          "Failed to call _asdict() on element. Type: %s. Element: "
+          "%s. Ensure input is beam.Row.",
+          type(req),
+          req,
+      )
+      return None
+    except Exception as e:
+      logger.error(
+          "Error getting condition values for row %s: %s",
+          req,
+          e,
+          exc_info=True)
+      return None
+
+  def _build_single_row_filter(
+      self, req_row: BeamRow, condition_values_dict: Dict[str, Any]) -> str:
+    """Builds the filter string part for a single row."""
+    try:
+      if self.row_restriction_template_fn:
+        # User's provided signature for row_restriction_template_fn
+        template_or_filter = self.row_restriction_template_fn(
+            condition_values_dict, self.primary_keys, req_row)
+        if not isinstance(template_or_filter, str):
+          raise TypeError(
+              "row_restriction_template_fn must return a string "
+              "(filter or template to be formatted)")
+        # Assuming if it takes condition_values_dict, it might be returning
+        # the final filter or a template. If it's a template, it still needs
+        # .format(). For now, assume it's a template that might still need
+        # formatting OR the final filter string. Let's assume it's the final
+        # filter string as per user's code.
+        # Directly return what the user's function gives.
+        return template_or_filter
+      elif self.row_restriction_template:
+        return self.row_restriction_template.format(**condition_values_dict)
+      else:
+        raise ValueError(
+            "Internal Error: No template or template function available.")
+    except KeyError as e:  # if user's fn returns template and format fails
+      raise ValueError(
+          f"Placeholder {{{e}}} in template not found in "
+          f"condition values: {condition_values_dict.keys()}")
+    except Exception as e:
+      logger.error(
+          "Error building filter for row %s with values %s: %s",
+          req_row,
+          condition_values_dict,
+          e,
+          exc_info=True,
+      )
+      return ""
+
+  def _apply_renaming(self, bq_row_dict: BQRowDict) -> BQRowDict:
+    if not self._rename_map:
+      return bq_row_dict
+    return {self._rename_map.get(k, k): v for k, v in bq_row_dict.items()}
+
+  def _arrow_to_dicts(self, response: ReadRowsResponse) -> Iterator[BQRowDict]:
+    # Now uses self._arrow_schema directly
+    if response.arrow_record_batch:
+      if not self._arrow_schema:
+        logger.error(
+            "Cannot process Arrow batch: Schema not "
+            "available/cached in handler.")
+        return
+      try:
+        serialized_batch = response.arrow_record_batch.serialized_record_batch
+        record_batch = pa.ipc.read_record_batch(
+            pa.py_buffer(serialized_batch), self._arrow_schema)
+        arrow_table = pa.Table.from_batches([record_batch])
+        yield from arrow_table.to_pylist()
+      except Exception as e:
+        logger.error(
+            "Error converting Arrow batch to dicts: %s", e, exc_info=True)
+
+  def _execute_storage_read(self, combined_row_filter: str) -> List[BQRowDict]:
+    if not self._client:
+      self.__enter__()
+    if not self._client:
+      raise RuntimeError("BQ Client failed to initialize.")
+    if not combined_row_filter:
+      logger.warning("Empty filter, skipping BQ read.")
+      return []
+
+    try:
+      table_project, dataset_id, table_id = self.table_name.split(".")
+    except ValueError:
+      raise ValueError(
+          f"Invalid table_name: '{self.table_name}'. Expected "
+          "'project.dataset.table'.")
+    parent_project = self.project
+    table_resource = (
+        f"projects/{table_project}/datasets/{dataset_id}/tables/{table_id}")
+
+    session = None
+    try:
+      # TODO: Improve max_stream_count to be dynamic based on input size,
+      # data volume, and query complexity for optimal performance
+      req = {
+          "parent": f"projects/{parent_project}",
+          "read_session": ReadSession(
+              table=table_resource,
+              data_format=DataFormat.ARROW,
+              read_options=ReadSession.TableReadOptions(
+                  row_restriction=combined_row_filter,
+                  selected_fields=self._bq_select_columns,
+              ),
+          ),
+          "max_stream_count": self.max_stream_count,
+      }
+      session = self._client.create_read_session(request=req)
+      logger.debug(
+          "Session with %s streams. Filter: %s",
+          len(session.streams),
+          combined_row_filter,
+      )
+      if session.streams and session.arrow_schema:
+        if not self._arrow_schema:
+          self._arrow_schema = pa.ipc.read_schema(
+              pa.py_buffer(session.arrow_schema.serialized_schema))
+          logger.debug("Deserialized Arrow schema for current call.")
+      elif session.streams:
+        logger.error("Session has streams but no schema.")
+        return []
+    except (BadRequest, NotFound, GoogleAPICallError) as e:
+      logger.error(
+          "BQ API error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+      )
+      return []
+    except Exception as e:
+      logger.error(
+          "Unexpected error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+          exc_info=True,
+      )
+      return []
+
+    if not session or not session.streams:
+      logger.warning("No streams for filter: %s", combined_row_filter)
+      return []
+
+    def _read_single_stream_worker(stream_name: str) -> List[BQRowDict]:
+      worker_results = []
+      if not self._client or not self._arrow_schema:
+        logger.error("Stream %s: Client/schema missing in worker.", stream_name)
+        return worker_results
+      try:
+        reader = self._client.read_rows(stream_name)
+        for response in reader:
+          worker_results.extend(self._arrow_to_dicts(response))  # Uses
+          # self._arrow_schema
+      except Exception as e:
+        logger.error(
+            "Error reading stream %s in worker: %s",
+            stream_name,
+            e,
+            exc_info=True,
+        )
+      return worker_results
+
+    all_bq_rows_original_keys = []
+    num_api_streams = len(session.streams)
+    max_workers = num_api_streams
+    if self.max_parallel_streams is not None and self.max_parallel_streams > 0:
+      max_workers = min(num_api_streams, self.max_parallel_streams)
+    if max_workers <= 0:
+      max_workers = 1
+    logger.debug(
+        "Reading %s API streams using %s threads.",
+        num_api_streams,
+        max_workers)
+    futures = []
+    try:
+      with concurrent.futures.ThreadPoolExecutor(
+          max_workers=max_workers) as executor:
+        for stream in session.streams:
+          futures.append(
+              executor.submit(_read_single_stream_worker, stream.name))
+        for future in concurrent.futures.as_completed(futures):
+          try:
+            all_bq_rows_original_keys.extend(future.result())
+          except Exception as e:
+            logger.error("Error processing future result: %s", e, exc_info=True)
+    except Exception as pool_error:
+      logger.error("ThreadPool error: %s", pool_error, exc_info=True)
+    logger.debug("Fetched %s rows from BQ.", len(all_bq_rows_original_keys))
+    return all_bq_rows_original_keys

Review Comment:
   thanks, i'd defer to other reviewers first who looked more closely into your change and have context. happy to take another look if you don't get a response



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "mohamedawnallah (via GitHub)" <gi...@apache.org>.
mohamedawnallah commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2955483653

   Thanks for the PR, @pandasanjay 🙏
   
   You might want to take a look at the CI test results. Also, this guide could help address some of the linting issues:
   🔗 [https://cwiki.apache.org/confluence/display/BEAM/Python+Tips](https://cwiki.apache.org/confluence/display/BEAM/Python+Tips)
   
   Additionally, you can check out my PR for the CloudSQL Enrichment Handler (#34398). I believe some of the feedback there could be relevant and applicable here as well.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2975889271

   assign set of reviewers


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "liferoad (via GitHub)" <gi...@apache.org>.
liferoad commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-2954102641

   Please fix the failed workflows.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "ahmedabu98 (via GitHub)" <gi...@apache.org>.
ahmedabu98 commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3245743308

   hey @pandasanjay, is this PR still relevant?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "pandasanjay (via GitHub)" <gi...@apache.org>.
pandasanjay commented on PR #35197:
URL: https://github.com/apache/beam/pull/35197#issuecomment-3247805448

   > hey @pandasanjay, is this PR still relevant?
   
   Hi @ahmedabu98, Yes..
   thanks for taking a look.
    I explored two approaches internally:
    1. Enrichment — This implementation runs into Dataflow worker instability because it manages threads manually and doesn’t play well with streaming parallel processing. I could use help here: do you know of any recommended patterns or examples to safely handle concurrent enrichment in streaming DoFns (or alternatives that avoid manual thread management)?
    2. Custom transformers — This approach works reliably. I’ll add that implementation.
    I’m currently on annual leave and will push the changes when I return. If you have suggestions while I’m away, please share and I’ll incorporate them once I’m back. Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #35197:
URL: https://github.com/apache/beam/pull/35197#discussion_r2395075134


##########
sdks/python/apache_beam/examples/snippets/transforms/elementwise/enrichment_test.py:
##########
@@ -57,32 +70,65 @@
 
 
 def validate_enrichment_with_bigtable():
-  expected = '''[START enrichment_with_bigtable]
-Row(sale_id=1, customer_id=1, product_id=1, quantity=1, product={'product_id': '1', 'product_name': 'pixel 5', 'product_stock': '2'})
-Row(sale_id=3, customer_id=3, product_id=2, quantity=3, product={'product_id': '2', 'product_name': 'pixel 6', 'product_stock': '4'})
-Row(sale_id=5, customer_id=5, product_id=4, quantity=2, product={'product_id': '4', 'product_name': 'pixel 8', 'product_stock': '10'})
-  [END enrichment_with_bigtable]'''.splitlines()[1:-1]
+  expected = (
+      """[START enrichment_with_bigtable]
+Row(sale_id=1, customer_id=1, product_id=1, quantity=1, """
+      """product={'product_id': '1', 'product_name': 'pixel 5', 'product_stock': '2'})
+Row(sale_id=3, customer_id=3, product_id=2, quantity=3, """
+      """product={'product_id': '2', 'product_name': 'pixel 6', 'product_stock': '4'})
+Row(sale_id=5, customer_id=5, product_id=4, quantity=2, """
+      """product={'product_id': '4', 'product_name': 'pixel 8', 'product_stock': '10'})
+  [END enrichment_with_bigtable]""").splitlines()[1:-1]
   return expected
 
 
 def validate_enrichment_with_vertex_ai():
-  expected = '''[START enrichment_with_vertex_ai]
-Row(user_id='2963', product_id=14235, sale_price=15.0, age=12.0, state='1', gender='1', country='1')
-Row(user_id='21422', product_id=11203, sale_price=12.0, age=12.0, state='0', gender='0', country='0')
-Row(user_id='20592', product_id=8579, sale_price=9.0, age=12.0, state='2', gender='1', country='2')
-  [END enrichment_with_vertex_ai]'''.splitlines()[1:-1]
+  expected = (
+      """[START enrichment_with_vertex_ai]
+Row(user_id='2963', product_id=14235, sale_price=15.0, """
+      """age=12.0, state='1', gender='1', country='1')
+Row(user_id='21422', product_id=11203, sale_price=12.0, """
+      """age=12.0, state='0', gender='0', country='0')
+Row(user_id='20592', product_id=8579, sale_price=9.0, """
+      """age=12.0, state='2', gender='1', country='2')
+  [END enrichment_with_vertex_ai]""").splitlines()[1:-1]
   return expected
 
 
 def validate_enrichment_with_vertex_ai_legacy():
-  expected = '''[START enrichment_with_vertex_ai_legacy]
+  expected = """[START enrichment_with_vertex_ai_legacy]
 Row(entity_id='movie_01', title='The Shawshank Redemption', genres='Drama')
 Row(entity_id='movie_02', title='The Shining', genres='Horror')
 Row(entity_id='movie_04', title='The Dark Knight', genres='Action')
-  [END enrichment_with_vertex_ai_legacy]'''.splitlines()[1:-1]
+  [END enrichment_with_vertex_ai_legacy]""".splitlines()[1:-1]
+  return expected
+
+
+def validate_enrichment_with_bigquery_storage_basic():
+  expected = (
+      """[START enrichment_with_bigquery_storage_basic]
+Row(sale_id=1001, product_id=101, customer_id=501, quantity=2, """
+      """product_id=101, product_name='Laptop Pro', category='Electronics', unit_price=999.99)
+Row(sale_id=1002, product_id=102, customer_id=502, quantity=1, """
+      """product_id=102, product_name='Wireless Mouse', category='Electronics', unit_price=29.99)
+Row(sale_id=1003, product_id=103, customer_id=503, quantity=5, """
+      """product_id=103, product_name='Office Chair', category='Furniture', unit_price=199.99)
+  [END enrichment_with_bigquery_storage_basic]""").splitlines()[1:-1]
+  return expected
+
+
+def validate_enrichment_with_bigquery_storage_custom_function():
+  expected = (
+      """[START enrichment_with_bigquery_storage_custom_function]
+Row(sale_id=1002, product_id=102, category='Electronics', customer_id=502, """
+      """quantity=4, prod_id=102, name='Wireless Mouse', category='Electronics', price=29.99)
+Row(sale_id=1004, product_id=101, category='Electronics', customer_id=504, """
+      """quantity=6, prod_id=101, name='Laptop Pro', category='Electronics', price=999.99)
+  [END enrichment_with_bigquery_storage_custom_function]""").splitlines()[1:-1]
   return expected
 
 
+@mock.patch("sys.stdout", new_callable=StringIO)

Review Comment:
   Function definition is missing proper indentation and parameter. The function should be a method with `self` parameter and proper indentation within the test class, not a standalone function with a decorator.
   ```suggestion
   
   ```



##########
website/www/site/content/en/documentation/transforms/python/elementwise/enrichment.md:
##########
@@ -39,6 +39,9 @@ This transform is available in Apache Beam 2.54.0 and later versions.
 The following examples demonstrate how to create a pipeline that use the enrichment transform to enrich data from external services.
 
 {{< table >}}
+| Service                            | Example                                                                                                                        |
+|:-----------------------------------|:-------------------------------------------------------------------------------------------------------------------------------|
+| BigQuery Storage Read API           | [Enrichment with BigQuery Storage Read API](/documentation/transforms/python/elementwise/enrichment-bigquery-storage/#example)  |
 | Service                            | Example                                                                                                                                                                      |
 |:-----------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Review Comment:
   Duplicate table header row creates malformed table structure. The second header row at line 45 should be removed as it duplicates the header from line 42.
   ```suggestion
   
   ```



##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API
+with support for field renaming via aliases in `column_names`,
+additional non-key fields for filtering, dynamic row restriction templates,
+experimental parallel stream reading using ThreadPoolExecutor, and custom
+row selection.
+"""
+
+import concurrent.futures  # For parallel stream reading
+import logging
+import re
+from collections.abc import Callable
+from collections.abc import Mapping
+from typing import Any
+from typing import Dict
+from typing import Iterator
+from typing import List
+from typing import Optional
+from typing import Set
+from typing import Tuple
+from typing import Union
+import pyarrow as pa
+from google.api_core.exceptions import BadRequest
+from google.api_core.exceptions import GoogleAPICallError
+from google.api_core.exceptions import NotFound
+from google.cloud.bigquery_storage import BigQueryReadClient
+
+from apache_beam.pvalue import Row as BeamRow
+from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+
+try:
+  from google.cloud.bigquery_storage import types
+  from google.cloud.bigquery_storage.types import (
+      DataFormat, ReadRowsResponse, ReadSession)
+except ImportError:
+  # Fallback for older versions where types might be in different location
+  from google.cloud.bigquery_storage import types
+  ReadRowsResponse = types.ReadRowsResponse
+  ReadSession = types.ReadSession
+  DataFormat = types.DataFormat
+
+# --- Configure Logging ---
+logger = logging.getLogger(__name__)
+
+# Type hints for functions
+# Input functions expect beam.Row for clarity, use beam.Row.as_dict inside if
+# needed
+ConditionValueFn = Callable[[BeamRow], Dict[str, Any]]
+# Updated RowRestrictionTemplateFn signature based on user provided code
+RowRestrictionTemplateFn = Callable[
+    [Dict[str, Any], Optional[List[str]], BeamRow], str]
+BQRowDict = Dict[str, Any]
+# Callback for selecting the "latest" or desired row from multiple BQ results
+LatestValueSelectorFn = Optional[Callable[[List[BeamRow], BeamRow],
+                                          Optional[BeamRow]]]
+
+# Regex to parse "column as alias" format, ignoring case for "as"
+ALIAS_REGEX = re.compile(r"^(.*?)\s+as\s+(.*)$", re.IGNORECASE)
+
+
+def _validate_bigquery_metadata(
+    project,
+    table_name,
+    row_restriction_template,
+    row_restriction_template_fn,
+    fields,
+    condition_value_fn,
+    additional_condition_fields,
+):
+  """Validates parameters for Storage API usage."""
+  if not project:
+    raise ValueError("`project` must be provided.")
+  if not table_name:
+    raise ValueError("`table_name` must be provided.")
+  if (row_restriction_template and
+      row_restriction_template_fn) or (not row_restriction_template and
+                                       not row_restriction_template_fn):
+    raise ValueError(
+        "Provide exactly one of `row_restriction_template` or "
+        "`row_restriction_template_fn`.")
+  if (fields and condition_value_fn) or (not fields and not condition_value_fn):
+    raise ValueError("Provide exactly one of `fields` or `condition_value_fn`.")
+  if additional_condition_fields and condition_value_fn:
+    raise ValueError(
+        "`additional_condition_fields` cannot be used with "
+        "`condition_value_fn`.")
+
+
+class BigQueryStorageEnrichmentHandler(
+    EnrichmentSourceHandler[Union[BeamRow, list[BeamRow]],
+                            Union[BeamRow, list[BeamRow]]]):
+  """Enrichment handler for Google Cloud BigQuery using the Storage Read API.
+    (Refer to __init__ for full list of features and arguments)
+    """
+  def __init__(
+      self,
+      project: str,
+      table_name: str,
+      *,
+      row_restriction_template: Optional[str] = None,
+      row_restriction_template_fn: Optional[RowRestrictionTemplateFn] = None,
+      fields: Optional[list[str]] = None,  # Fields for KEY and filtering
+      additional_condition_fields: Optional[list[str]] = None,  # Fields ONLY
+      # for filtering
+      column_names: Optional[list[str]] = None,  # Columns to select + aliases
+      condition_value_fn: Optional[ConditionValueFn] = None,  # Alt way to get
+      # filter/key values
+      min_batch_size: Optional[int] = 1,
+      max_batch_size: Optional[int] = 1000,  # Batching enabled by default
+      max_batch_duration_secs: Optional[int] = None,
+      max_parallel_streams: Optional[int] = None,  # Max workers for
+      # ThreadPoolExecutor
+      max_stream_count: int = 100,  # Max streams for BigQuery Storage Read
+      # --- Added latest_value_selector and primary_keys from user code ---
+      latest_value_selector: LatestValueSelectorFn = None,
+      primary_keys: Optional[list[str]] = None,  # --- End added parameters ---
+  ):
+    """
+        Initializes the BigQueryStorageEnrichmentHandler.
+
+        Args:
+            project: Google Cloud project ID.
+            table_name: Fully qualified BigQuery table name.
+            row_restriction_template: (Optional[str]) Template string for a
+                single row's filter condition. If `row_restriction_template_fn`
+                is not provided, this template will be formatted with values
+                from `fields` and `additional_condition_fields`.
+            row_restriction_template_fn: (Optional[Callable]) Function that
+                takes (condition_values_dict, primary_keys, request_row) and
+                returns a fully formatted filter string or template to 
+                be formatted.
+            fields: (Optional[list[str]]) Input `beam.Row` field names used to
+                generate the dictionary for formatting the row restriction
+                template AND for generating the internal join/cache key.
+            additional_condition_fields: (Optional[list[str]]) Additional input
+                `beam.Row` field names used ONLY for formatting the row
+                restriction template. Not part of join/cache key.
+            column_names: (Optional[list[str]]) Names/aliases of columns to
+                select. Supports "original_col as alias_col" format. If None,
+                selects '*'.
+            condition_value_fn: (Optional[Callable]) Function returning a
+                dictionary for formatting row restriction template and for
+                join/cache key. Takes precedence over `fields`.
+            min_batch_size (Optional[int]): Minimum elements per batch.
+                Defaults to 1.
+            max_batch_size (Optional[int]): Maximum elements per batch.
+                Defaults to 1000 for batching. Set to 1 for single element
+                processing to disable batching.
+            max_batch_duration_secs (Optional[int]): Maximum batch buffering
+                time in seconds. Defaults to 5 seconds.
+            max_parallel_streams (Optional[int]): Max worker threads for
+                ThreadPoolExecutor for reading streams in parallel within a
+                single `__call__`.
+            max_stream_count (int): Maximum number of streams for BigQuery
+                Storage Read API. Defaults to 100. Setting to 0 lets BigQuery
+                decide the optimal number of streams.
+            latest_value_selector: (Optional) Callback function to select the
+                desired row when multiple BQ rows match a key. Takes
+                `List[beam.Row]` (BQ results) and the original `beam.Row`
+                (request) and returns one `beam.Row` or None.
+            primary_keys: (Optional[list[str]]) Primary key fields used
+                potentially by `row_restriction_template_fn` or
+                `latest_value_selector`.
+        """
+    _validate_bigquery_metadata(
+        project,
+        table_name,
+        row_restriction_template,
+        row_restriction_template_fn,
+        fields,
+        condition_value_fn,
+        additional_condition_fields,
+    )
+    self.project = project
+    self.table_name = table_name
+    self.row_restriction_template = row_restriction_template
+    self.row_restriction_template_fn = row_restriction_template_fn
+    self.fields = fields
+    self.additional_condition_fields = additional_condition_fields or []
+    self.condition_value_fn = condition_value_fn
+    self.max_parallel_streams = max_parallel_streams
+    self.max_stream_count = max_stream_count
+    # --- Store new parameters ---
+    self._latest_value_callback = latest_value_selector
+    self.primary_keys = primary_keys
+    # --- End store ---
+

Review Comment:
   [nitpick] Comments like '--- Store new parameters ---' and '--- End store ---' are unnecessary and don't add value. These should be removed for cleaner code.
   ```suggestion
       self._latest_value_callback = latest_value_selector
       self.primary_keys = primary_keys
   ```



##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read.py:
##########
@@ -0,0 +1,763 @@
+# -*- coding: utf-8 -*-
+# Copyright 2024 Google LLC & Apache Software Foundation (Original License
+# Header)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""
+BigQuery Enrichment Source Handler using the BigQuery Storage Read API
+with support for field renaming via aliases in `column_names`,
+additional non-key fields for filtering, dynamic row restriction templates,
+experimental parallel stream reading using ThreadPoolExecutor, and custom
+row selection.
+"""
+
+import concurrent.futures  # For parallel stream reading
+import logging
+import re
+from collections.abc import Callable
+from collections.abc import Mapping
+from typing import Any
+from typing import Dict
+from typing import Iterator
+from typing import List
+from typing import Optional
+from typing import Set
+from typing import Tuple
+from typing import Union
+import pyarrow as pa
+from google.api_core.exceptions import BadRequest
+from google.api_core.exceptions import GoogleAPICallError
+from google.api_core.exceptions import NotFound
+from google.cloud.bigquery_storage import BigQueryReadClient
+
+from apache_beam.pvalue import Row as BeamRow
+from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+
+try:
+  from google.cloud.bigquery_storage import types
+  from google.cloud.bigquery_storage.types import (
+      DataFormat, ReadRowsResponse, ReadSession)
+except ImportError:
+  # Fallback for older versions where types might be in different location
+  from google.cloud.bigquery_storage import types
+  ReadRowsResponse = types.ReadRowsResponse
+  ReadSession = types.ReadSession
+  DataFormat = types.DataFormat
+
+# --- Configure Logging ---
+logger = logging.getLogger(__name__)
+
+# Type hints for functions
+# Input functions expect beam.Row for clarity, use beam.Row.as_dict inside if
+# needed
+ConditionValueFn = Callable[[BeamRow], Dict[str, Any]]
+# Updated RowRestrictionTemplateFn signature based on user provided code
+RowRestrictionTemplateFn = Callable[
+    [Dict[str, Any], Optional[List[str]], BeamRow], str]
+BQRowDict = Dict[str, Any]
+# Callback for selecting the "latest" or desired row from multiple BQ results
+LatestValueSelectorFn = Optional[Callable[[List[BeamRow], BeamRow],
+                                          Optional[BeamRow]]]
+
+# Regex to parse "column as alias" format, ignoring case for "as"
+ALIAS_REGEX = re.compile(r"^(.*?)\s+as\s+(.*)$", re.IGNORECASE)
+
+
+def _validate_bigquery_metadata(
+    project,
+    table_name,
+    row_restriction_template,
+    row_restriction_template_fn,
+    fields,
+    condition_value_fn,
+    additional_condition_fields,
+):
+  """Validates parameters for Storage API usage."""
+  if not project:
+    raise ValueError("`project` must be provided.")
+  if not table_name:
+    raise ValueError("`table_name` must be provided.")
+  if (row_restriction_template and
+      row_restriction_template_fn) or (not row_restriction_template and
+                                       not row_restriction_template_fn):
+    raise ValueError(
+        "Provide exactly one of `row_restriction_template` or "
+        "`row_restriction_template_fn`.")
+  if (fields and condition_value_fn) or (not fields and not condition_value_fn):
+    raise ValueError("Provide exactly one of `fields` or `condition_value_fn`.")
+  if additional_condition_fields and condition_value_fn:
+    raise ValueError(
+        "`additional_condition_fields` cannot be used with "
+        "`condition_value_fn`.")
+
+
+class BigQueryStorageEnrichmentHandler(
+    EnrichmentSourceHandler[Union[BeamRow, list[BeamRow]],
+                            Union[BeamRow, list[BeamRow]]]):
+  """Enrichment handler for Google Cloud BigQuery using the Storage Read API.
+    (Refer to __init__ for full list of features and arguments)
+    """
+  def __init__(
+      self,
+      project: str,
+      table_name: str,
+      *,
+      row_restriction_template: Optional[str] = None,
+      row_restriction_template_fn: Optional[RowRestrictionTemplateFn] = None,
+      fields: Optional[list[str]] = None,  # Fields for KEY and filtering
+      additional_condition_fields: Optional[list[str]] = None,  # Fields ONLY
+      # for filtering
+      column_names: Optional[list[str]] = None,  # Columns to select + aliases
+      condition_value_fn: Optional[ConditionValueFn] = None,  # Alt way to get
+      # filter/key values
+      min_batch_size: Optional[int] = 1,
+      max_batch_size: Optional[int] = 1000,  # Batching enabled by default
+      max_batch_duration_secs: Optional[int] = None,
+      max_parallel_streams: Optional[int] = None,  # Max workers for
+      # ThreadPoolExecutor
+      max_stream_count: int = 100,  # Max streams for BigQuery Storage Read
+      # --- Added latest_value_selector and primary_keys from user code ---
+      latest_value_selector: LatestValueSelectorFn = None,
+      primary_keys: Optional[list[str]] = None,  # --- End added parameters ---
+  ):
+    """
+        Initializes the BigQueryStorageEnrichmentHandler.
+
+        Args:
+            project: Google Cloud project ID.
+            table_name: Fully qualified BigQuery table name.
+            row_restriction_template: (Optional[str]) Template string for a
+                single row's filter condition. If `row_restriction_template_fn`
+                is not provided, this template will be formatted with values
+                from `fields` and `additional_condition_fields`.
+            row_restriction_template_fn: (Optional[Callable]) Function that
+                takes (condition_values_dict, primary_keys, request_row) and
+                returns a fully formatted filter string or template to 
+                be formatted.
+            fields: (Optional[list[str]]) Input `beam.Row` field names used to
+                generate the dictionary for formatting the row restriction
+                template AND for generating the internal join/cache key.
+            additional_condition_fields: (Optional[list[str]]) Additional input
+                `beam.Row` field names used ONLY for formatting the row
+                restriction template. Not part of join/cache key.
+            column_names: (Optional[list[str]]) Names/aliases of columns to
+                select. Supports "original_col as alias_col" format. If None,
+                selects '*'.
+            condition_value_fn: (Optional[Callable]) Function returning a
+                dictionary for formatting row restriction template and for
+                join/cache key. Takes precedence over `fields`.
+            min_batch_size (Optional[int]): Minimum elements per batch.
+                Defaults to 1.
+            max_batch_size (Optional[int]): Maximum elements per batch.
+                Defaults to 1000 for batching. Set to 1 for single element
+                processing to disable batching.
+            max_batch_duration_secs (Optional[int]): Maximum batch buffering
+                time in seconds. Defaults to 5 seconds.
+            max_parallel_streams (Optional[int]): Max worker threads for
+                ThreadPoolExecutor for reading streams in parallel within a
+                single `__call__`.
+            max_stream_count (int): Maximum number of streams for BigQuery
+                Storage Read API. Defaults to 100. Setting to 0 lets BigQuery
+                decide the optimal number of streams.
+            latest_value_selector: (Optional) Callback function to select the
+                desired row when multiple BQ rows match a key. Takes
+                `List[beam.Row]` (BQ results) and the original `beam.Row`
+                (request) and returns one `beam.Row` or None.
+            primary_keys: (Optional[list[str]]) Primary key fields used
+                potentially by `row_restriction_template_fn` or
+                `latest_value_selector`.
+        """
+    _validate_bigquery_metadata(
+        project,
+        table_name,
+        row_restriction_template,
+        row_restriction_template_fn,
+        fields,
+        condition_value_fn,
+        additional_condition_fields,
+    )
+    self.project = project
+    self.table_name = table_name
+    self.row_restriction_template = row_restriction_template
+    self.row_restriction_template_fn = row_restriction_template_fn
+    self.fields = fields
+    self.additional_condition_fields = additional_condition_fields or []
+    self.condition_value_fn = condition_value_fn
+    self.max_parallel_streams = max_parallel_streams
+    self.max_stream_count = max_stream_count
+    # --- Store new parameters ---
+    self._latest_value_callback = latest_value_selector
+    self.primary_keys = primary_keys
+    # --- End store ---
+
+    self._rename_map: Dict[str, str] = {}
+    bq_columns_to_select_set: Set[str] = set()
+    self._select_all_columns = False
+    if column_names:
+      for name_or_alias in column_names:
+        match = ALIAS_REGEX.match(name_or_alias)
+        if match:
+          original_col, alias_col = (
+              match.group(1).strip(),
+              match.group(2).strip(),
+          )
+          if not original_col or not alias_col:
+            raise ValueError(f"Invalid alias: '{name_or_alias}'")
+          bq_columns_to_select_set.add(original_col)
+          self._rename_map[original_col] = alias_col
+        else:
+          col = name_or_alias.strip()
+          if not col:
+            raise ValueError("Empty column name.")
+          if col == "*":
+            self._select_all_columns = True
+            break
+          bq_columns_to_select_set.add(col)
+    else:
+      self._select_all_columns = True
+
+    key_gen_fields_set = set(self.fields or [])
+    if self._select_all_columns:
+      self._bq_select_columns = ["*"]
+      if key_gen_fields_set:
+        logger.debug(
+            "Selecting all columns ('*'). Key fields %s assumed present.",
+            key_gen_fields_set,
+        )
+    else:
+      fields_to_ensure_selected = set()
+      if self.fields:
+        reverse_rename_map = {v: k for k, v in self._rename_map.items()}
+        for field in self.fields:
+          original_name = reverse_rename_map.get(field, field)
+          fields_to_ensure_selected.add(original_name)
+      # Ensure primary keys (if defined for callback use) are selected if not
+      # already
+      if self.primary_keys:
+        for pk_field in self.primary_keys:
+          original_pk_name = {
+              v: k
+              for k, v in self._rename_map.items()
+          }.get(pk_field, pk_field)
+          fields_to_ensure_selected.add(original_pk_name)
+
+      final_select_set = bq_columns_to_select_set.union(
+          fields_to_ensure_selected)
+      self._bq_select_columns = sorted(list(final_select_set))
+      if not self._bq_select_columns:
+        raise ValueError("No columns determined for selection.")
+
+    logger.info(
+        "Handler Initialized. Selecting BQ Columns: %s. Renaming map: %s",
+        self._bq_select_columns,
+        self._rename_map,
+    )
+
+    self._batching_kwargs = {}
+    # Set defaults for optional parameters
+    min_batch_size = min_batch_size or 1
+    max_batch_size = max_batch_size or 1000
+    max_batch_duration_secs = max_batch_duration_secs or 5
+
+    if max_batch_size > 1:
+      self._batching_kwargs["min_batch_size"] = min_batch_size
+      self._batching_kwargs["max_batch_size"] = max_batch_size
+      self._batching_kwargs["max_batch_duration_secs"] = max_batch_duration_secs
+    else:
+      self._batching_kwargs["min_batch_size"] = 1
+      self._batching_kwargs["max_batch_size"] = 1
+
+    self._client: Optional[BigQueryReadClient] = None
+    self._arrow_schema: Optional[pa.Schema] = None
+
+  def __enter__(self):
+    if not self._client:
+      self._client = BigQueryReadClient()
+      logger.info("BigQueryStorageEnrichmentHandler: Client created.")
+    self._arrow_schema = None
+
+  def _get_condition_values_dict(self,
+                                 req: BeamRow) -> Optional[Dict[str, Any]]:
+    try:
+      if self.condition_value_fn:
+        values_dict = self.condition_value_fn(req)
+        if values_dict is None or any(v is None for v in values_dict.values()):
+          logger.warning(
+              "condition_value_fn returned None or None value(s). "
+              "Skipping: %s. Values: %s",
+              req,
+              values_dict,
+          )
+          return None
+        return values_dict
+      elif self.fields is not None:
+        req_dict = req._asdict()
+        values_dict = {}
+        all_req_fields = (self.fields or []) + self.additional_condition_fields
+        for field in all_req_fields:
+          # User's provided logic for row_restriction_template_fn handling:
+          if not self.row_restriction_template_fn:
+            if field not in req_dict or req_dict[field] is None:
+              logger.warning(
+                  "Input row missing field '%s' or None (needed "
+                  "for filter). Skipping: %s",
+                  field,
+                  req,
+              )
+              return None
+          values_dict[field] = req_dict.get(field)  # Use get for safety
+        return values_dict
+      else:
+        raise ValueError(
+            "Internal error: Neither fields nor condition_value_fn.")
+    except AttributeError:  # Specifically for _asdict()
+      logger.error(
+          "Failed to call _asdict() on element. Type: %s. Element: "
+          "%s. Ensure input is beam.Row.",
+          type(req),
+          req,
+      )
+      return None
+    except Exception as e:
+      logger.error(
+          "Error getting condition values for row %s: %s",
+          req,
+          e,
+          exc_info=True)
+      return None
+
+  def _build_single_row_filter(
+      self, req_row: BeamRow, condition_values_dict: Dict[str, Any]) -> str:
+    """Builds the filter string part for a single row."""
+    try:
+      if self.row_restriction_template_fn:
+        # User's provided signature for row_restriction_template_fn
+        template_or_filter = self.row_restriction_template_fn(
+            condition_values_dict, self.primary_keys, req_row)
+        if not isinstance(template_or_filter, str):
+          raise TypeError(
+              "row_restriction_template_fn must return a string "
+              "(filter or template to be formatted)")
+        # Assuming if it takes condition_values_dict, it might be returning
+        # the final filter or a template. If it's a template, it still needs
+        # .format(). For now, assume it's a template that might still need
+        # formatting OR the final filter string. Let's assume it's the final
+        # filter string as per user's code.
+        # Directly return what the user's function gives.
+        return template_or_filter
+      elif self.row_restriction_template:
+        return self.row_restriction_template.format(**condition_values_dict)
+      else:
+        raise ValueError(
+            "Internal Error: No template or template function available.")
+    except KeyError as e:  # if user's fn returns template and format fails
+      raise ValueError(
+          f"Placeholder {{{e}}} in template not found in "
+          f"condition values: {condition_values_dict.keys()}")
+    except Exception as e:
+      logger.error(
+          "Error building filter for row %s with values %s: %s",
+          req_row,
+          condition_values_dict,
+          e,
+          exc_info=True,
+      )
+      return ""
+
+  def _apply_renaming(self, bq_row_dict: BQRowDict) -> BQRowDict:
+    if not self._rename_map:
+      return bq_row_dict
+    return {self._rename_map.get(k, k): v for k, v in bq_row_dict.items()}
+
+  def _arrow_to_dicts(self, response: ReadRowsResponse) -> Iterator[BQRowDict]:
+    # Now uses self._arrow_schema directly
+    if response.arrow_record_batch:
+      if not self._arrow_schema:
+        logger.error(
+            "Cannot process Arrow batch: Schema not "
+            "available/cached in handler.")
+        return
+      try:
+        serialized_batch = response.arrow_record_batch.serialized_record_batch
+        record_batch = pa.ipc.read_record_batch(
+            pa.py_buffer(serialized_batch), self._arrow_schema)
+        arrow_table = pa.Table.from_batches([record_batch])
+        yield from arrow_table.to_pylist()
+      except Exception as e:
+        logger.error(
+            "Error converting Arrow batch to dicts: %s", e, exc_info=True)
+
+  def _execute_storage_read(self, combined_row_filter: str) -> List[BQRowDict]:
+    if not self._client:
+      self.__enter__()
+    if not self._client:
+      raise RuntimeError("BQ Client failed to initialize.")
+    if not combined_row_filter:
+      logger.warning("Empty filter, skipping BQ read.")
+      return []
+
+    try:
+      table_project, dataset_id, table_id = self.table_name.split(".")
+    except ValueError:
+      raise ValueError(
+          f"Invalid table_name: '{self.table_name}'. Expected "
+          "'project.dataset.table'.")
+    parent_project = self.project
+    table_resource = (
+        f"projects/{table_project}/datasets/{dataset_id}/tables/{table_id}")
+
+    session = None
+    try:
+      # TODO: Improve max_stream_count to be dynamic based on input size,
+      # data volume, and query complexity for optimal performance
+      req = {
+          "parent": f"projects/{parent_project}",
+          "read_session": ReadSession(
+              table=table_resource,
+              data_format=DataFormat.ARROW,
+              read_options=ReadSession.TableReadOptions(
+                  row_restriction=combined_row_filter,
+                  selected_fields=self._bq_select_columns,
+              ),
+          ),
+          "max_stream_count": self.max_stream_count,
+      }
+      session = self._client.create_read_session(request=req)
+      logger.debug(
+          "Session with %s streams. Filter: %s",
+          len(session.streams),
+          combined_row_filter,
+      )
+      if session.streams and session.arrow_schema:
+        if not self._arrow_schema:
+          self._arrow_schema = pa.ipc.read_schema(
+              pa.py_buffer(session.arrow_schema.serialized_schema))
+          logger.debug("Deserialized Arrow schema for current call.")
+      elif session.streams:
+        logger.error("Session has streams but no schema.")
+        return []
+    except (BadRequest, NotFound, GoogleAPICallError) as e:
+      logger.error(
+          "BQ API error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+      )
+      return []
+    except Exception as e:
+      logger.error(
+          "Unexpected error creating session. Filter: '%s'. Error: %s",
+          combined_row_filter,
+          e,
+          exc_info=True,
+      )
+      return []
+
+    if not session or not session.streams:
+      logger.warning("No streams for filter: %s", combined_row_filter)
+      return []
+
+    def _read_single_stream_worker(stream_name: str) -> List[BQRowDict]:
+      worker_results = []
+      if not self._client or not self._arrow_schema:
+        logger.error("Stream %s: Client/schema missing in worker.", stream_name)
+        return worker_results
+      try:
+        reader = self._client.read_rows(stream_name)
+        for response in reader:
+          worker_results.extend(self._arrow_to_dicts(response))  # Uses
+          # self._arrow_schema
+      except Exception as e:
+        logger.error(
+            "Error reading stream %s in worker: %s",
+            stream_name,
+            e,
+            exc_info=True,
+        )
+      return worker_results
+
+    all_bq_rows_original_keys = []
+    num_api_streams = len(session.streams)
+    max_workers = num_api_streams
+    if self.max_parallel_streams is not None and self.max_parallel_streams > 0:
+      max_workers = min(num_api_streams, self.max_parallel_streams)
+    if max_workers <= 0:
+      max_workers = 1
+    logger.debug(
+        "Reading %s API streams using %s threads.",
+        num_api_streams,
+        max_workers)
+    futures = []
+    try:
+      with concurrent.futures.ThreadPoolExecutor(
+          max_workers=max_workers) as executor:
+        for stream in session.streams:
+          futures.append(
+              executor.submit(_read_single_stream_worker, stream.name))
+        for future in concurrent.futures.as_completed(futures):
+          try:
+            all_bq_rows_original_keys.extend(future.result())
+          except Exception as e:
+            logger.error("Error processing future result: %s", e, exc_info=True)
+    except Exception as pool_error:
+      logger.error("ThreadPool error: %s", pool_error, exc_info=True)
+    logger.debug("Fetched %s rows from BQ.", len(all_bq_rows_original_keys))
+    return all_bq_rows_original_keys
+
+  def create_row_key(self,
+                     row: BeamRow,
+                     is_bq_result: bool = False) -> Optional[tuple]:
+    try:
+      if self.condition_value_fn:
+        key_values_dict = self.condition_value_fn(row)
+      elif self.fields is not None:
+        row_dict = row._asdict()  # Assumes row is BeamRow
+
+        # If this is a BQ result row with aliased columns, map field names
+        # to aliases
+        fields_to_use = self.fields
+        if is_bq_result and self._rename_map:
+          # Map original field names to their aliases
+          fields_to_use = [self._rename_map.get(f, f) for f in self.fields]
+
+        key_values_dict = {
+            # Use original field name as key, but get value using appropriate
+            # field name
+            self.fields[i]: row_dict[field_name]
+            for i, field_name in enumerate(fields_to_use)
+            if field_name in row_dict and row_dict[field_name] is not None
+        }
+        if len(key_values_dict) != len(self.fields):  # Ensure all key fields
+          # found and not None
+          logger.debug(
+              "Row missing key field(s) or None. Cannot generate key: %s", row)
+          return None
+      else:
+        raise ValueError(
+            "Internal error: Neither fields nor condition_value_fn for key.")
+      if key_values_dict is None:
+        return None
+      return tuple(sorted(key_values_dict.items()))
+    except AttributeError:
+      logger.error(
+          "Failed _asdict() for key gen. Type: %s. Ensure input is beam.Row.",
+          type(row),
+      )
+      return None
+    except Exception as e:
+      logger.error("Error generating key for row %s: %s", row, e, exc_info=True)
+      return None
+
+  def _process_bq_results_for_batch(
+      self,
+      bq_results_list_orig_keys: List[BQRowDict]) -> Dict[tuple, List[BeamRow]]:
+    """Process BQ results and create a mapping from keys to renamed rows."""
+    bq_results_key_map: Dict[tuple, List[BeamRow]] = {}
+    for bq_row_dict_orig_keys in bq_results_list_orig_keys:
+      try:
+        renamed_bq_row_dict = self._apply_renaming(bq_row_dict_orig_keys)
+        bq_row_renamed_keys_temp = BeamRow(**renamed_bq_row_dict)
+        resp_key = self.create_row_key(
+            bq_row_renamed_keys_temp, is_bq_result=True)
+        if resp_key:
+          if resp_key not in bq_results_key_map:
+            bq_results_key_map[resp_key] = []
+          bq_results_key_map[resp_key].append(bq_row_renamed_keys_temp)
+      except Exception as e:
+        logger.warning(
+            "Error processing BQ response row %s: %s. Cannot map.",
+            bq_row_dict_orig_keys,
+            e,
+        )
+    return bq_results_key_map
+
+  def _select_response_row(
+      self, matching_bq_rows: List[BeamRow], req_row: BeamRow) -> BeamRow:
+    """Select the appropriate response row from matching BQ rows."""
+    if not matching_bq_rows:
+      return BeamRow()
+
+    if self._latest_value_callback:
+      try:
+        return (
+            self._latest_value_callback(matching_bq_rows, req_row) or BeamRow())
+      except Exception as cb_error:
+        logger.error(
+            "Error in latest_value_selector: %s. Using first BQ row.",
+            cb_error,
+            exc_info=True,
+        )
+        return matching_bq_rows[0]
+    else:
+      return matching_bq_rows[0]  # Default to first
+
+  def _process_batch_request(
+      self, request: list[BeamRow]) -> List[Tuple[BeamRow, BeamRow]]:
+    """
+        Process a batch of requests efficiently using a single BigQuery query.
+
+        This method optimizes batch processing by:
+        1. Deduplicating requests with identical keys
+        2. Building individual row filters for each unique request
+        3. Combining all filters into a single OR query to minimize API calls
+        4. Mapping BigQuery results back to original requests
+
+        Args:
+            request: List of BeamRow objects to enrich with BigQuery data
+
+        Returns:
+            List of tuples containing (original_request, enriched_response)
+            pairs
+        """
+    # Initialize collections for processing
+    batch_responses: List[Tuple[BeamRow, BeamRow]] = []  # Final results
+    requests_map: Dict[tuple, BeamRow] = {}  # Unique key -> request mapping
+    single_row_filters: List[str] = []  # Individual SQL filter conditions
+
+    # Phase 1: Process each request row and build individual filters
+    for req_row in request:
+      # Extract condition values (e.g., key fields) from the request row
+      condition_values = self._get_condition_values_dict(req_row)
+      if condition_values is None:
+        # Missing required fields - add empty response and skip processing
+        batch_responses.append((req_row, BeamRow()))
+        continue
+
+      # Generate a unique key for this request (used for deduplication)
+      req_key = self.create_row_key(req_row)
+      if req_key is None:
+        # Cannot generate key - add empty response and skip processing
+        batch_responses.append((req_row, BeamRow()))
+        continue
+
+      # Handle duplicate detection and filter building
+      if req_key not in requests_map:
+        # New unique request - store it and build its filter
+        requests_map[req_key] = req_row
+        single_filter = self._build_single_row_filter(req_row, condition_values)
+        if single_filter:
+          # Wrap in parentheses for safe OR combination
+          single_row_filters.append(f"({single_filter})")
+        else:
+          # Filter generation failed - add empty response
+          batch_responses.append((req_row, BeamRow()))
+          del requests_map[req_key]  # Clean up
+      else:
+        # Duplicate key detected - log warning and return empty response
+        logger.warning(
+            "Duplicate key '%s' in batch. Processing first instance.", req_key)
+        batch_responses.append((req_row, BeamRow()))
+
+    # Phase 2: Execute combined BigQuery query if we have valid filters
+    bq_results_key_map: Dict[tuple,
+                             List[BeamRow]] = {}  # Key -> BQ results mapping
+    if single_row_filters:
+      # Combine all individual filters with OR to create single query
+      # Example: "(id = 1) OR (id = 2) OR (id = 3)"
+      combined_filter = " OR ".join(single_row_filters)
+
+      # Execute single BigQuery Storage Read API call
+      bq_results_list_orig_keys = self._execute_storage_read(combined_filter)
+
+      # Process raw BigQuery results: apply column renaming and group by key
+      bq_results_key_map = self._process_bq_results_for_batch(
+          bq_results_list_orig_keys)
+
+    # Phase 3: Match BigQuery results back to original requests
+    for req_key, req_row in requests_map.items():
+      # Find all BigQuery rows that match this request's key
+      matching_bq_rows = bq_results_key_map.get(req_key, [])
+
+      # Select the best response row (first match or custom selector result)
+      selected_response_row = self._select_response_row(
+          matching_bq_rows, req_row)
+
+      # Add the (request, response) pair to final results
+      batch_responses.append((req_row, selected_response_row))
+
+    return batch_responses
+
+  def _process_single_request(self,
+                              request: BeamRow) -> Tuple[BeamRow, BeamRow]:
+    """Process a single request using a direct BQ query."""
+    req_row = request
+    condition_values = self._get_condition_values_dict(req_row)
+    if condition_values is None:
+      return (req_row, BeamRow())
+    single_filter = self._build_single_row_filter(req_row, condition_values)
+    if not single_filter:
+      return (req_row, BeamRow())
+    bq_results_orig_keys = self._execute_storage_read(single_filter)
+    response_row = BeamRow()
+    if bq_results_orig_keys:
+      # For single request, apply selector if provided, else take first
+      renamed_bq_rows = [
+          BeamRow(**self._apply_renaming(d)) for d in bq_results_orig_keys
+      ]
+      if self._latest_value_callback and renamed_bq_rows:
+        try:
+          response_row = (
+              self._latest_value_callback(renamed_bq_rows, req_row) or
+              BeamRow())
+        except Exception as cb_error:
+          logger.error(
+              "Error in latest_value_selector for single req: %s. "
+              "Using first BQ row.",
+              cb_error,
+              exc_info=True,
+          )
+          response_row = renamed_bq_rows[0]
+      elif renamed_bq_rows:
+        response_row = renamed_bq_rows[0]
+      if len(bq_results_orig_keys) > 1 and not (
+          self._latest_value_callback and
+          response_row != BeamRow()):  # Log if multiple and
+        # default/callback didn't pick one specifically
+        logger.warning(
+            "Single request -> %s BQ rows. Used selected/first. Filter:'%s'",
+            len(bq_results_orig_keys),
+            single_filter,
+        )
+    return (req_row, response_row)
+
+  def __call__(  # type: ignore[override]
+      self, request: Union[BeamRow, list[BeamRow]], *args, **kwargs
+  ) -> Union[Tuple[BeamRow, BeamRow], List[Tuple[BeamRow, BeamRow]]]:
+    self._arrow_schema = None  # Reset schema
+
+    if isinstance(request, list):
+      return self._process_batch_request(request)
+    else:
+      return self._process_single_request(request)
+
+  def __exit__(self, exc_type, exc_val, exc_tb):
+    if self._client:
+      logger.info("BigQueryStorageEnrichmentHandler: Releasing client.")
+      self._client = None
+
+  def get_cache_key(self, request: Union[BeamRow, list[BeamRow]]) -> str:
+    # TODO: Add proper caching functionality with TTL, cache size limits,
+    # and configurable cache policies to improve performance and reduce
+    # BigQuery API calls for repeated requests.

Review Comment:
   [nitpick] TODO comments should include issue numbers or assignees for tracking. Consider creating a GitHub issue for this caching enhancement and referencing it in the TODO.
   ```suggestion
       # TODO(#1234): Add proper caching functionality with TTL, cache size limits,
       # and configurable cache policies to improve performance and reduce
       # BigQuery API calls for repeated requests. See: https://github.com/apache/beam/issues/1234
   ```



##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_storage_read_it_test.py:
##########
@@ -0,0 +1,494 @@
+#
+
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import logging
+import secrets
+import time
+import unittest
+from typing import Any
+from typing import Dict
+from typing import List
+from typing import Optional
+import pytest
+
+import apache_beam as beam
+from apache_beam.io.gcp.bigquery_tools import BigQueryWrapper
+from apache_beam.io.gcp.internal.clients import bigquery
+from apache_beam.testing.test_pipeline import TestPipeline
+from apache_beam.testing.util import assert_that
+from apache_beam.testing.util import equal_to
+
+# pylint: disable=ungrouped-imports
+try:
+  from apitools.base.py.exceptions import HttpError
+  from google.api_core.exceptions import BadRequest, GoogleAPICallError
+
+  # Removed NotFound from import as it is unused

Review Comment:
   Comment indicates NotFound was removed due to being unused, but NotFound is actually imported and used on line 42 and line 451. This comment is misleading and should be removed.
   ```suggestion
   
   ```



##########
sdks/python/apache_beam/examples/snippets/transforms/elementwise/enrichment_test.py:
##########
@@ -33,6 +34,18 @@
 
 # pylint: disable=unused-import
 try:
+  from apache_beam.examples.snippets.transforms.elementwise.enrichment import (
+      enrichment_with_bigtable,
+      enrichment_with_vertex_ai_legacy,
+  )
+  from apache_beam.examples.snippets.transforms.elementwise.enrichment import (
+      enrichment_with_vertex_ai, )
+  from apache_beam.examples.snippets.transforms.elementwise.enrichment import (
+      enrichment_with_bigquery_storage_basic,
+      enrichment_with_bigquery_storage_custom_function,
+  )
+except ImportError:
+  raise unittest.SkipTest("RequestResponseIO dependencies are not installed")

Review Comment:
   Import statements are incorrectly placed inside a try block. The imports on lines 37-46 should be moved after the existing imports that start at line 49, as they are currently inside a try block that will cause syntax issues.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add BigQuery Storage Read API Enrichment Handler [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #35197: Add BigQuery Storage Read API Enrichment Handler
URL: https://github.com/apache/beam/pull/35197


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org