From 53c76db5864dfb6410bc2595948e131061e0fa0d Mon Sep 17 00:00:00 2001 From: Marcus Rosti Date: Thu, 3 Dec 2026 10:47:17 -0800 Subject: [PATCH 1/2] feat: Implements 'export to arrow batches' for Trino Signed-off-by: Marcus Rosti --- docs/reference/offline-stores/overview.md | 2 +- docs/reference/offline-stores/trino.md | 2 +- .../infra/compute_engines/trino/compute.py | 6 +- .../infra/compute_engines/trino/nodes.py | 6 +- .../infra/compute_engines/trino/utils.py | 56 +--- .../contrib/trino_offline_store/trino.py | 57 +++- .../trino_offline_store/trino_queries.py | 138 ++++++-- .../trino_offline_store/trino_type_map.py | 2 + .../tests/component/trino/test_compute.py | 2 +- .../trino/test_trino_compute_engine.py | 15 +- .../test_trino_streaming.py | 301 ++++++++++++++++++ .../test_trino_type_map.py | 3 + 12 files changed, 494 insertions(+), 96 deletions(-) create mode 100644 sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py diff --git a/docs/reference/offline-stores/overview.md b/docs/reference/offline-stores/overview.md index f80e86887f4..411c08ae978 100644 --- a/docs/reference/offline-stores/overview.md +++ b/docs/reference/offline-stores/overview.md @@ -51,7 +51,7 @@ Below is a matrix indicating which `RetrievalJob`s support what functionality. || --------------------------------- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | || export to dataframe | yes | yes | yes | yes | yes | yes | yes | yes | yes | yes | || export to arrow table | yes | yes | yes | yes | yes | yes | yes | yes | yes | yes | -|| export to arrow batches | no | no | no | yes | no | no | no | no | no | no | +|| export to arrow batches | no | no | no | yes | no | no | yes | no | no | no | || export to SQL | no | yes | yes | yes | yes | no | yes | no | yes | no | || export to data lake (S3, GCS, etc.) | no | no | yes | no | yes | no | no | no | yes | yes | || export to data warehouse | no | yes | yes | yes | yes | no | no | no | yes | no | diff --git a/docs/reference/offline-stores/trino.md b/docs/reference/offline-stores/trino.md index afbc0bf7d7a..dcbf30862d7 100644 --- a/docs/reference/offline-stores/trino.md +++ b/docs/reference/offline-stores/trino.md @@ -100,7 +100,7 @@ Below is a matrix indicating which functionality is supported by `TrinoRetrieval | ----------------------------------------------------- | ----- | | export to dataframe | yes | | export to arrow table | yes | -| export to arrow batches | no | +| export to arrow batches | yes | | export to SQL | yes | | export to data lake (S3, GCS, etc.) | no | | export to data warehouse | no | diff --git a/sdk/python/feast/infra/compute_engines/trino/compute.py b/sdk/python/feast/infra/compute_engines/trino/compute.py index c740b44100b..8eddab089eb 100644 --- a/sdk/python/feast/infra/compute_engines/trino/compute.py +++ b/sdk/python/feast/infra/compute_engines/trino/compute.py @@ -28,14 +28,16 @@ ) from feast.infra.compute_engines.trino.utils import ( get_or_create_trino_client, - stream_trino_arrow_batches, write_arrow_batches_to_online_store, ) from feast.infra.offline_stores.contrib.trino_offline_store.trino import ( AuthConfig, TrinoOfflineStoreConfig, ) -from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import Trino +from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import ( + Trino, + stream_trino_arrow_batches, +) from feast.infra.offline_stores.offline_store import OfflineStore, RetrievalJob from feast.infra.online_stores.online_store import OnlineStore from feast.infra.registry.base_registry import BaseRegistry diff --git a/sdk/python/feast/infra/compute_engines/trino/nodes.py b/sdk/python/feast/infra/compute_engines/trino/nodes.py index 54b35c35112..207ad00f6de 100644 --- a/sdk/python/feast/infra/compute_engines/trino/nodes.py +++ b/sdk/python/feast/infra/compute_engines/trino/nodes.py @@ -27,7 +27,6 @@ _has_unquoted_semicolon, _trino_sql_literal, quote_identifier, - stream_trino_arrow_batches, unique_ordered, write_arrow_batches_to_online_store, ) @@ -38,7 +37,10 @@ from feast.infra.offline_stores.contrib.trino_offline_store.connectors.upload import ( upload_pandas_dataframe_to_trino, ) -from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import Trino +from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import ( + Trino, + stream_trino_arrow_batches, +) from feast.infra.offline_stores.offline_utils import get_temp_entity_table_name logger = logging.getLogger(__name__) diff --git a/sdk/python/feast/infra/compute_engines/trino/utils.py b/sdk/python/feast/infra/compute_engines/trino/utils.py index ad6d0bf18b1..9908b2f9674 100644 --- a/sdk/python/feast/infra/compute_engines/trino/utils.py +++ b/sdk/python/feast/infra/compute_engines/trino/utils.py @@ -8,7 +8,6 @@ Any, Callable, Iterable, - Iterator, Optional, TypeVar, ) @@ -16,14 +15,8 @@ import numpy as np import pandas as pd import pyarrow as pa -from trino.exceptions import TrinoConnectionError, TrinoQueryError -from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import ( - Trino, -) -from feast.infra.offline_stores.contrib.trino_offline_store.trino_type_map import ( - trino_to_pa_value_type, -) +from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import Trino from feast.types import ( Array, PrimitiveFeastType, @@ -213,53 +206,6 @@ def get_or_create_trino_client(config: Any) -> Trino: ) -def stream_trino_arrow_batches( - client: Trino, - query_text: str, - batch_size: int = 10000, -) -> Iterator[pa.RecordBatch]: - """Execute a query and yield PyArrow RecordBatches in streaming chunks. - - Maintains a strictly bounded memory footprint O(batch_size) without - accumulating the entire dataset in Python memory. - """ - cursor = client.get_cursor() - try: - cursor.execute(query_text) - - if not cursor.description: - return - - arrow_schema = pa.schema( - [ - pa.field(str(col[0]), trino_to_pa_value_type(str(col[1]))) - for col in cursor.description - ] - ) - - while rows := cursor.fetchmany(batch_size): - arrays = [ - pa.array( - [row[col_idx] for row in rows], - type=arrow_schema.field(col_idx).type, - ) - for col_idx in range(len(cursor.description)) - ] - yield pa.RecordBatch.from_arrays(arrays, schema=arrow_schema) - except TrinoConnectionError: - # Never swallow connection errors; bubble up immediately to caller - logger.error("Trino connection dropped while streaming batches.") - raise - except TrinoQueryError as e: - logger.debug("Trino query failed during streaming execution: %s", e) - raise - finally: - try: - cursor.close() - except Exception: - pass - - def write_arrow_batches_to_online_store( batches: Iterable[pa.RecordBatch], feature_view: "FeatureView", diff --git a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino.py b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino.py index 7e04cff8d44..949f063c9b4 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino.py +++ b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino.py @@ -6,6 +6,7 @@ from typing import ( Any, Dict, + Iterator, List, Literal, Optional, @@ -33,7 +34,11 @@ from feast.infra.offline_stores.contrib.trino_offline_store.connectors.upload import ( upload_pandas_dataframe_to_trino, ) -from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import Trino +from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import ( + DEFAULT_BATCH_SIZE, + Trino, + stream_trino_arrow_batches, +) from feast.infra.offline_stores.contrib.trino_offline_store.trino_source import ( SavedDatasetTrinoStorage, TrinoSource, @@ -248,17 +253,49 @@ def __del__(self) -> None: self._drop_temp_table() def _to_df_internal(self, timeout: Optional[int] = None) -> pd.DataFrame: - """Return dataset as Pandas DataFrame synchronously including on demand transforms""" - try: - results = self._client.execute_query(query_text=self._query) - self.pyarrow_schema = results.pyarrow_schema - return results.to_dataframe() - finally: - self._drop_temp_table() + """Return dataset as Pandas DataFrame synchronously""" + return self._to_arrow_internal(timeout=timeout).to_pandas() def _to_arrow_internal(self, timeout: Optional[int] = None) -> pyarrow.Table: - """Return payrrow dataset as synchronously including on demand transforms""" - return pyarrow.Table.from_pandas(self._to_df_internal(timeout=timeout)) + """Return dataset as a pyarrow Table synchronously, fetching rows from Trino in batches""" + return self._stream(DEFAULT_BATCH_SIZE).read_all() + + def _stream(self, batch_size: int) -> pyarrow.RecordBatchReader: + # The temp table is dropped only after the query reading it is finished or cancelled. + return stream_trino_arrow_batches( + self._client, self._query, batch_size, on_close=self._drop_temp_table + ) + + def to_arrow_reader( + self, batch_size: int = DEFAULT_BATCH_SIZE + ) -> pyarrow.RecordBatchReader: + """ + Stream the dataset as record batches of up to ``batch_size`` rows. + + Only one batch is held in memory at a time, so results larger than memory can be processed. + The query runs before this returns, so query errors are raised here. + Jobs with on demand feature views fall back to ``to_arrow``, since those transforms are + applied to the full result. Dataset validation isn't applied, and offline store metrics + aren't recorded for streamed results. + """ + if self.on_demand_feature_views: + return self.to_arrow().to_reader(max_chunksize=batch_size) + return self._stream(batch_size) + + def to_arrow_batches( + self, batch_size: int = DEFAULT_BATCH_SIZE + ) -> Iterator[pyarrow.Table]: + """Stream the dataset as pyarrow Tables of up to ``batch_size`` rows; see ``to_arrow_reader``.""" + return ( + pyarrow.Table.from_batches([batch]) + for batch in self.to_arrow_reader(batch_size) + ) + + def to_pandas_batches( + self, batch_size: int = DEFAULT_BATCH_SIZE + ) -> Iterator[pd.DataFrame]: + """Stream the dataset as pandas DataFrames of up to ``batch_size`` rows; see ``to_arrow_reader``.""" + return (batch.to_pandas() for batch in self.to_arrow_reader(batch_size)) def to_sql(self) -> str: """Returns the SQL query that will be executed in Trino to build the historical feature table""" diff --git a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py index 246fea2d066..932191a7bdb 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py +++ b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py @@ -1,10 +1,11 @@ from __future__ import annotations +import json import signal import threading from dataclasses import dataclass from enum import Enum -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence import numpy as np import pandas as pd @@ -53,27 +54,30 @@ def __init__( self._cursor: Optional[Cursor] = None def get_cursor(self) -> Cursor: - """Return an active DB-API Cursor for Trino queries.""" + """Return the client's shared DB-API Cursor for Trino queries.""" if self._cursor is None: - headers = ( - {trino.constants.HEADER_EXTRA_CREDENTIAL: self.extra_credential} - if self.extra_credential - else {} - ) - self._cursor = trino.dbapi.connect( - host=self.host, - port=self.port, - user=self.user, - catalog=self.catalog, - source=self.source, - http_scheme=self.http_scheme, - verify=self.verify, - auth=self.auth, - http_headers=headers, - ).cursor() - + self._cursor = self.new_cursor() return self._cursor + def new_cursor(self) -> Cursor: + """Open a new connection and return its cursor, independent of the shared one.""" + headers = ( + {trino.constants.HEADER_EXTRA_CREDENTIAL: self.extra_credential} + if self.extra_credential + else {} + ) + return trino.dbapi.connect( + host=self.host, + port=self.port, + user=self.user, + catalog=self.catalog, + source=self.source, + http_scheme=self.http_scheme, + verify=self.verify, + auth=self.auth, + http_headers=headers, + ).cursor() + def _get_cursor(self) -> Cursor: return self.get_cursor() @@ -162,3 +166,99 @@ def to_dataframe(self) -> pd.DataFrame: if col_type.startswith("timestamp"): df[col_name] = pd.to_datetime(df[col_name]) return df.fillna(np.nan) + + +def _to_json_string(value: Any) -> Any: + """Serialize Trino ``map`` (dict) and ``row`` (tuple) values, which have no Feast type, as JSON. + + Lists are converted element-wise, so arrays of maps or rows become lists of JSON strings. + """ + if isinstance(value, dict): + return json.dumps({str(k): v for k, v in value.items()}, default=str) + if isinstance(value, tuple): + return json.dumps(list(value), default=str) + if isinstance(value, list): + return [_to_json_string(item) for item in value] + return value + + +def _holds_strings(pa_type: pa.DataType) -> bool: + """Whether a column of this type stores strings, directly or in (nested) lists.""" + return pa.types.is_string(pa_type) or ( + pa.types.is_list(pa_type) and _holds_strings(pa_type.value_type) + ) + + +def _column_to_arrow(values: List[Any], pa_type: pa.DataType) -> pa.Array: + if _holds_strings(pa_type): + return pa.array([_to_json_string(value) for value in values], type=pa_type) + return pa.array(values, type=pa_type) + + +def rows_to_record_batch( + rows: Sequence[Sequence[Any]], schema: pa.Schema +) -> pa.RecordBatch: + """Convert a chunk of Trino result rows into a RecordBatch with the given schema.""" + return pa.RecordBatch.from_arrays( + [ + _column_to_arrow([row[index] for row in rows], field.type) + for index, field in enumerate(schema) + ], + schema=schema, + ) + + +DEFAULT_BATCH_SIZE = 10000 + + +def _schema_from_description(description: Sequence[Sequence[Any]]) -> pa.Schema: + return pa.schema( + [ + pa.field(str(column[0]), trino_to_pa_value_type(str(column[1]))) + for column in description + ] + ) + + +def _query_batches( + client: Trino, + query_text: str, + batch_size: int, + on_close: Callable[[], None], +) -> Iterator[pa.RecordBatch]: + """Run a query on its own connection, yield an empty batch carrying its schema, then its results. + + On exhaustion, close, garbage collection, or failure, the query is canceled and its + connection closed before ``on_close`` runs. + """ + cursor = client.new_cursor() + try: + cursor.execute(query_text) + schema = _schema_from_description(cursor.description or []) + yield pa.RecordBatch.from_pylist([], schema=schema) + while rows := cursor.fetchmany(batch_size): + yield rows_to_record_batch(rows, schema) + finally: + cursor.close() + cursor.connection.close() + on_close() + + +def stream_trino_arrow_batches( + client: Trino, + query_text: str, + batch_size: int = DEFAULT_BATCH_SIZE, + on_close: Callable[[], None] = lambda: None, +) -> pa.RecordBatchReader: + """Execute a query and stream its results as PyArrow RecordBatches of up to ``batch_size`` rows. + + The query runs before this returns, so query errors are raised here. It runs on its own + connection, so closing the reader cancels only this query, never one on the client's shared + cursor. ``on_close`` runs once the query is finished or canceled. + + Only one batch is held in Python memory at a time. Call ``read_all()`` on the returned + reader to collect the full result into a ``pyarrow.Table``, which works for empty results too. + """ + batches = _query_batches(client, query_text, batch_size, on_close) + schema = next(batches).schema + return pa.RecordBatchReader.from_batches(schema, batches) diff --git a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_type_map.py b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_type_map.py index 04c6c19917d..b658ad593b8 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_type_map.py +++ b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_type_map.py @@ -157,6 +157,8 @@ def trino_to_pa_value_type(trino_type_as_str: str) -> pa.DataType: return pa.decimal128(38, 0) if trino_type_as_str.startswith("timestamp"): + if trino_type_as_str.endswith("with time zone"): + return pa.timestamp("us", tz="UTC") return pa.timestamp("us") if trino_type_as_str.startswith("varchar"): diff --git a/sdk/python/tests/component/trino/test_compute.py b/sdk/python/tests/component/trino/test_compute.py index d6902f6ce09..d150f376854 100644 --- a/sdk/python/tests/component/trino/test_compute.py +++ b/sdk/python/tests/component/trino/test_compute.py @@ -193,7 +193,7 @@ def test_trino_compute_engine_materialize(driver_entity, trino_source): ], [], ] - mock_client.get_cursor.return_value = mock_cursor + mock_client.new_cursor.return_value = mock_cursor repo_config = MagicMock() repo_config.batch_engine = TrinoComputeEngineConfig( diff --git a/sdk/python/tests/unit/infra/compute_engines/trino/test_trino_compute_engine.py b/sdk/python/tests/unit/infra/compute_engines/trino/test_trino_compute_engine.py index a06657f2f67..f9aeb63c45d 100644 --- a/sdk/python/tests/unit/infra/compute_engines/trino/test_trino_compute_engine.py +++ b/sdk/python/tests/unit/infra/compute_engines/trino/test_trino_compute_engine.py @@ -1842,32 +1842,37 @@ def test_write_node_offline_merge_fallback_on_missing_keys(self): class TestTrinoUtilsStreamingAndOnlineWrite: def test_stream_trino_arrow_batches_no_columns(self): - from feast.infra.compute_engines.trino.utils import stream_trino_arrow_batches + from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import ( + stream_trino_arrow_batches, + ) mock_client = MagicMock() mock_cursor = MagicMock() mock_cursor.description = None mock_cursor._query = None - mock_client.get_cursor.return_value = mock_cursor + mock_cursor.fetchmany.return_value = [] + mock_client.new_cursor.return_value = mock_cursor batches = list(stream_trino_arrow_batches(mock_client, "SELECT 1")) assert len(batches) == 0 def test_stream_trino_arrow_batches_fetch(self): - from feast.infra.compute_engines.trino.utils import stream_trino_arrow_batches + from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import ( + stream_trino_arrow_batches, + ) mock_client = MagicMock() mock_cursor = MagicMock() mock_cursor.description = [("id", "bigint", None, None, None, None, None)] mock_cursor.fetchmany.side_effect = [[(1,), (2,)], []] - mock_client.get_cursor.return_value = mock_cursor + mock_client.new_cursor.return_value = mock_cursor batches = list( stream_trino_arrow_batches(mock_client, "SELECT id FROM tbl", batch_size=2) ) assert len(batches) == 1 assert batches[0].num_rows == 2 - mock_client.get_cursor.assert_called_once() + mock_client.new_cursor.assert_called_once() def test_write_arrow_batches_to_online_store(self): from feast.infra.compute_engines.trino.utils import ( diff --git a/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py b/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py new file mode 100644 index 00000000000..3453a3b9c6c --- /dev/null +++ b/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py @@ -0,0 +1,301 @@ +import json +from datetime import datetime, timezone +from decimal import Decimal +from typing import Any, List, Sequence, Tuple +from unittest.mock import MagicMock, patch +from zoneinfo import ZoneInfo + +import pyarrow as pa +import pyarrow.compute as pc +import pytest +from trino.exceptions import TrinoQueryError +from trino.types import NamedRowTuple + +from feast.infra.offline_stores.contrib.trino_offline_store.trino import ( + TrinoRetrievalJob, +) +from feast.infra.offline_stores.contrib.trino_offline_store.trino_queries import ( + rows_to_record_batch, + stream_trino_arrow_batches, +) + +TEMP_TABLE = "memory.feast.entity_df_tmp" + + +def _mock_client( + description: Sequence[Tuple[str, str]], rows: List[List[Any]], batch_size: int +) -> Tuple[MagicMock, MagicMock]: + cursor = MagicMock() + cursor.description = [ + (name, type_, None, None, None, None, None) for name, type_ in description + ] + chunks = [rows[i : i + batch_size] for i in range(0, len(rows), batch_size)] + cursor.fetchmany.side_effect = [*chunks, []] + client = MagicMock() + client.new_cursor.return_value = cursor + return client, cursor + + +def _job(client: MagicMock) -> TrinoRetrievalJob: + return TrinoRetrievalJob( + query="SELECT * FROM features", + client=client, + config=MagicMock(), + full_feature_names=False, + temp_table=TEMP_TABLE, + ) + + +def _drop_temp_table_calls(client: MagicMock) -> int: + return sum( + f"DROP TABLE IF EXISTS {TEMP_TABLE}" in str(call) + for call in client.execute_query.call_args_list + ) + + +class TestRowsToRecordBatch: + def test_keeps_nullable_integers_as_integers(self) -> None: + schema = pa.schema([pa.field("id", pa.int64()), pa.field("count", pa.int32())]) + + batch = rows_to_record_batch([[1, None], [2, 7]], schema) + + assert batch.schema == schema + assert batch.column("count").to_pylist() == [None, 7] + + def test_converts_time_zone_aware_timestamps_to_utc(self) -> None: + schema = pa.schema([pa.field("ts", pa.timestamp("us", tz="UTC"))]) + new_york = datetime(2025, 1, 1, 10, tzinfo=ZoneInfo("America/New_York")) + + batch = rows_to_record_batch([[new_york], [None]], schema) + + assert batch.column("ts").to_pylist() == [ + datetime(2025, 1, 1, 15, tzinfo=timezone.utc), + None, + ] + + def test_serializes_maps_and_rows_as_json(self) -> None: + schema = pa.schema([pa.field("m", pa.string()), pa.field("r", pa.string())]) + row = NamedRowTuple([1, "z"], ["a", "b"], ["integer", "varchar"]) + + batch = rows_to_record_batch([[{"k": 1}, row], [None, None]], schema) + + assert json.loads(batch.column("m")[0].as_py()) == {"k": 1} + assert json.loads(batch.column("r")[0].as_py()) == [1, "z"] + assert batch.column("m")[1].as_py() is None + + def test_serializes_maps_and_rows_inside_arrays_as_json(self) -> None: + schema = pa.schema( + [ + pa.field("rows", pa.list_(pa.string())), + pa.field("maps", pa.list_(pa.list_(pa.string()))), + ] + ) + row = NamedRowTuple([1], ["x"], ["integer"]) + + batch = rows_to_record_batch( + [[[row, None], [[{"k": 1}]]], [None, [None, []]]], schema + ) + + assert batch.column("rows").to_pylist() == [["[1]", None], None] + assert batch.column("maps").to_pylist() == [[['{"k": 1}']], [None, []]] + + def test_keeps_decimal_precision(self) -> None: + schema = pa.schema([pa.field("amount", pa.decimal128(10, 2))]) + + batch = rows_to_record_batch([[Decimal("1.25")]], schema) + + assert batch.column("amount").to_pylist() == [Decimal("1.25")] + + +class TestStreamTrinoArrowBatches: + def test_yields_batches_of_at_most_batch_size_and_closes_cursor(self) -> None: + client, cursor = _mock_client( + [("id", "bigint")], [[i] for i in range(5)], batch_size=2 + ) + + batches = list(stream_trino_arrow_batches(client, "SELECT id", batch_size=2)) + + assert [batch.num_rows for batch in batches] == [2, 2, 1] + cursor.fetchmany.assert_called_with(2) + cursor.close.assert_called_once() + + def test_read_all_on_empty_result_keeps_schema(self) -> None: + client, _ = _mock_client([("id", "bigint"), ("ts", "timestamp(3)")], [], 10) + + table = stream_trino_arrow_batches(client, "SELECT id, ts").read_all() + + assert table.num_rows == 0 + assert table.schema == pa.schema( + [pa.field("id", pa.int64()), pa.field("ts", pa.timestamp("us"))] + ) + + def test_closes_cursor_when_query_fails(self) -> None: + client, cursor = _mock_client([("id", "bigint")], [], 10) + cursor.execute.side_effect = TrinoQueryError({"message": "boom"}) + + with pytest.raises(TrinoQueryError): + stream_trino_arrow_batches(client, "SELECT id") + + cursor.close.assert_called_once() + + def test_closes_cursor_when_column_type_is_unsupported(self) -> None: + client, cursor = _mock_client([("id", "uuid")], [], 10) + + with pytest.raises(KeyError): + stream_trino_arrow_batches(client, "SELECT id") + + cursor.close.assert_called_once() + cursor.connection.close.assert_called_once() + + def test_on_close_runs_after_cursor_and_connection_close(self) -> None: + client, cursor = _mock_client([("id", "bigint")], [[1]], 10) + events: List[str] = [] + cursor.close.side_effect = lambda: events.append("cursor") + cursor.connection.close.side_effect = lambda: events.append("connection") + + stream_trino_arrow_batches( + client, "SELECT id", on_close=lambda: events.append("on_close") + ).read_all() + + assert events == ["cursor", "connection", "on_close"] + + def test_on_close_runs_when_query_fails(self) -> None: + client, cursor = _mock_client([("id", "bigint")], [], 10) + cursor.execute.side_effect = TrinoQueryError({"message": "boom"}) + on_close = MagicMock() + + with pytest.raises(TrinoQueryError): + stream_trino_arrow_batches(client, "SELECT id", on_close=on_close) + + on_close.assert_called_once() + + def test_uses_its_own_connection_not_the_shared_cursor(self) -> None: + client, cursor = _mock_client([("id", "bigint")], [[1]], 10) + + stream_trino_arrow_batches(client, "SELECT id").read_all() + + client.get_cursor.assert_not_called() + cursor.connection.close.assert_called_once() + + +class TestTrinoRetrievalJobBatches: + def test_to_arrow_collects_all_batches(self) -> None: + client, cursor = _mock_client( + [("driver_id", "bigint"), ("conv_rate", "double")], + [[i, None if i % 2 else i / 10] for i in range(25000)], + batch_size=10000, + ) + + table = _job(client).to_arrow() + + assert table.num_rows == 25000 + assert table.schema.field("driver_id").type == pa.int64() + assert cursor.fetchmany.call_count == 4 + assert _drop_temp_table_calls(client) == 1 + + def test_to_df_returns_pandas_with_nan_for_null_floats(self) -> None: + client, _ = _mock_client( + [("driver_id", "bigint"), ("conv_rate", "double")], + [[1, 0.5], [2, None]], + batch_size=10000, + ) + + df = _job(client).to_df() + + assert df["driver_id"].tolist() == [1, 2] + assert df["conv_rate"].isna().tolist() == [False, True] + + def test_to_arrow_batches_drops_temp_table_only_after_last_batch(self) -> None: + client, _ = _mock_client( + [("driver_id", "bigint")], [[i] for i in range(5)], batch_size=2 + ) + batches = _job(client).to_arrow_batches(batch_size=2) + + sizes = [] + for table in batches: + assert _drop_temp_table_calls(client) == 0 + sizes.append(table.num_rows) + + assert sizes == [2, 2, 1] + assert _drop_temp_table_calls(client) == 1 + + def test_abandoned_stream_cancels_query_before_dropping_temp_table(self) -> None: + client, cursor = _mock_client( + [("driver_id", "bigint")], [[i] for i in range(5)], batch_size=2 + ) + events = [] + cursor.close.side_effect = lambda: events.append("cancel") + client.execute_query.side_effect = lambda query: events.append(query) + batches = _job(client).to_arrow_batches(batch_size=2) + + next(batches) + del batches + + assert events == ["cancel", f"DROP TABLE IF EXISTS {TEMP_TABLE}"] + + def test_unread_reader_cancels_query_and_drops_temp_table_when_discarded( + self, + ) -> None: + client, cursor = _mock_client( + [("driver_id", "bigint")], [[i] for i in range(5)], batch_size=2 + ) + job = _job(client) + reader = job.to_arrow_reader(batch_size=2) + + del reader + + cursor.close.assert_called_once() + assert _drop_temp_table_calls(client) == 1 + + def test_on_demand_feature_views_fall_back_to_to_arrow(self) -> None: + client, _ = _mock_client( + [("driver_id", "bigint")], [[i] for i in range(3)], batch_size=10000 + ) + odfv = MagicMock() + odfv.name = "doubled" + odfv.transform_arrow.side_effect = lambda table, _: pa.table( + {"driver_id_x2": pc.multiply(table["driver_id"], 2)} + ) + job = TrinoRetrievalJob( + query="SELECT * FROM features", + client=client, + config=MagicMock(), + full_feature_names=False, + on_demand_feature_views=[odfv], + ) + + with patch.object(job, "to_arrow", wraps=job.to_arrow) as to_arrow: + tables = list(job.to_arrow_batches(batch_size=2)) + + to_arrow.assert_called_once() + assert [t.column("driver_id_x2").to_pylist() for t in tables] == [[0, 2], [4]] + + def test_to_pandas_batches(self) -> None: + client, _ = _mock_client( + [("driver_id", "bigint")], [[i] for i in range(3)], batch_size=2 + ) + + dfs = list(_job(client).to_pandas_batches(batch_size=2)) + + assert [df["driver_id"].tolist() for df in dfs] == [[0, 1], [2]] + + +class TestTrinoRetrievalJobArrowReader: + def test_query_errors_are_raised_eagerly_and_drop_temp_table(self) -> None: + client, cursor = _mock_client([("driver_id", "bigint")], [], batch_size=2) + cursor.execute.side_effect = TrinoQueryError({"message": "boom"}) + + with pytest.raises(TrinoQueryError): + _job(client).to_arrow_reader() + + assert _drop_temp_table_calls(client) == 1 + + def test_empty_result_keeps_schema_and_drops_temp_table(self) -> None: + client, _ = _mock_client([("driver_id", "bigint")], [], batch_size=2) + + reader = _job(client).to_arrow_reader() + + assert reader.read_all().schema == pa.schema( + [pa.field("driver_id", pa.int64())] + ) + assert _drop_temp_table_calls(client) == 1 diff --git a/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_type_map.py b/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_type_map.py index e8af1c8c9e3..a269b306a3b 100644 --- a/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_type_map.py +++ b/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_type_map.py @@ -110,6 +110,9 @@ def test_json(self) -> None: def test_timestamp(self) -> None: assert trino_to_pa_value_type("timestamp") == pa.timestamp("us") assert trino_to_pa_value_type("timestamp(3)") == pa.timestamp("us") + assert trino_to_pa_value_type("timestamp(3) with time zone") == pa.timestamp( + "us", tz="UTC" + ) def test_decimal_bare(self) -> None: assert trino_to_pa_value_type("decimal") == pa.decimal128(38, 0) From 0ece994b0da8f37c5bd3eaa46729d1ce9ef69535 Mon Sep 17 00:00:00 2001 From: Marcus Rosti Date: Fri, 4 Dec 2026 15:27:06 -0800 Subject: [PATCH 2/2] fix: Adds a try/finally to trino connections Signed-off-by: Marcus Rosti --- .../trino_offline_store/trino_queries.py | 20 ++++---- .../test_trino_streaming.py | 47 ++++++++++++++++++- 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py index 932191a7bdb..84c0aeb5e28 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py +++ b/sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino_queries.py @@ -231,16 +231,20 @@ def _query_batches( On exhaustion, close, garbage collection, or failure, the query is canceled and its connection closed before ``on_close`` runs. """ - cursor = client.new_cursor() try: - cursor.execute(query_text) - schema = _schema_from_description(cursor.description or []) - yield pa.RecordBatch.from_pylist([], schema=schema) - while rows := cursor.fetchmany(batch_size): - yield rows_to_record_batch(rows, schema) + cursor = client.new_cursor() + try: + cursor.execute(query_text) + schema = _schema_from_description(cursor.description or []) + yield pa.RecordBatch.from_pylist([], schema=schema) + while rows := cursor.fetchmany(batch_size): + yield rows_to_record_batch(rows, schema) + finally: + try: + cursor.close() + finally: + cursor.connection.close() finally: - cursor.close() - cursor.connection.close() on_close() diff --git a/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py b/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py index 3453a3b9c6c..df58809c320 100644 --- a/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py +++ b/sdk/python/tests/unit/infra/offline_stores/contrib/trino_offline_store/test_trino_streaming.py @@ -8,7 +8,7 @@ import pyarrow as pa import pyarrow.compute as pc import pytest -from trino.exceptions import TrinoQueryError +from trino.exceptions import TrinoConnectionError, TrinoQueryError from trino.types import NamedRowTuple from feast.infra.offline_stores.contrib.trino_offline_store.trino import ( @@ -169,6 +169,41 @@ def test_on_close_runs_when_query_fails(self) -> None: on_close.assert_called_once() + def test_connection_and_on_close_still_run_when_cancel_fails(self) -> None: + client, cursor = _mock_client([("id", "bigint")], [[1]], 10) + cursor.close.side_effect = TrinoConnectionError("cancel failed") + on_close = MagicMock() + + with pytest.raises(TrinoConnectionError): + stream_trino_arrow_batches( + client, "SELECT id", on_close=on_close + ).read_all() + + cursor.connection.close.assert_called_once() + on_close.assert_called_once() + + def test_on_close_still_runs_when_closing_the_connection_fails(self) -> None: + client, cursor = _mock_client([("id", "bigint")], [[1]], 10) + cursor.connection.close.side_effect = TrinoConnectionError("close failed") + on_close = MagicMock() + + with pytest.raises(TrinoConnectionError): + stream_trino_arrow_batches( + client, "SELECT id", on_close=on_close + ).read_all() + + on_close.assert_called_once() + + def test_on_close_runs_when_opening_the_connection_fails(self) -> None: + client, _ = _mock_client([("id", "bigint")], [], 10) + client.new_cursor.side_effect = TrinoConnectionError("unreachable") + on_close = MagicMock() + + with pytest.raises(TrinoConnectionError): + stream_trino_arrow_batches(client, "SELECT id", on_close=on_close) + + on_close.assert_called_once() + def test_uses_its_own_connection_not_the_shared_cursor(self) -> None: client, cursor = _mock_client([("id", "bigint")], [[1]], 10) @@ -233,6 +268,16 @@ def test_abandoned_stream_cancels_query_before_dropping_temp_table(self) -> None assert events == ["cancel", f"DROP TABLE IF EXISTS {TEMP_TABLE}"] + def test_temp_table_is_dropped_when_cancel_fails(self) -> None: + client, cursor = _mock_client([("driver_id", "bigint")], [[1]], batch_size=2) + cursor.close.side_effect = TrinoConnectionError("cancel failed") + + with pytest.raises(TrinoConnectionError): + _job(client).to_arrow() + + cursor.connection.close.assert_called_once() + assert _drop_temp_table_calls(client) == 1 + def test_unread_reader_cancels_query_and_drops_temp_table_when_discarded( self, ) -> None: