Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/offline-stores/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/offline-stores/trino.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
6 changes: 4 additions & 2 deletions sdk/python/feast/infra/compute_engines/trino/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions sdk/python/feast/infra/compute_engines/trino/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
_has_unquoted_semicolon,
_trino_sql_literal,
quote_identifier,
stream_trino_arrow_batches,
unique_ordered,
write_arrow_batches_to_online_store,
)
Expand All @@ -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__)
Expand Down
56 changes: 1 addition & 55 deletions sdk/python/feast/infra/compute_engines/trino/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,15 @@
Any,
Callable,
Iterable,
Iterator,
Optional,
TypeVar,
)

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,
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from typing import (
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"""
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -162,3 +166,103 @@ 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.
"""
try:
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:
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)
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down
2 changes: 1 addition & 1 deletion sdk/python/tests/component/trino/test_compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading