diff --git a/docs/reference/data-sources/iceberg.md b/docs/reference/data-sources/iceberg.md index 6402a7ec419..4d7dbdb7e73 100644 --- a/docs/reference/data-sources/iceberg.md +++ b/docs/reference/data-sources/iceberg.md @@ -84,6 +84,53 @@ my_uc_source = UnityCatalogSource( When `endpoint` is omitted, it defaults to `{DATABRICKS_HOST}/api/2.1/unity-catalog/iceberg`. When `token_env_var` is omitted, it defaults to `DATABRICKS_TOKEN`. +### PolarisSource (Apache Polaris) {#polaris-source} + +Extends `IcebergSource` for [Apache Polaris](https://polaris.apache.org/). `warehouse` is the Polaris +catalog name. When `endpoint` is omitted it defaults to `$POLARIS_HOST/api/catalog`. + +```python +from feast.infra.data_sources.contrib.iceberg_catalog import PolarisSource + +my_polaris_source = PolarisSource( + warehouse="my_polaris_catalog", + namespace="ml", + table="driver_stats", + timestamp_field="event_timestamp", +) +``` + +Authentication is read from the environment (only the variable *names* are stored in the registry): + +1. OAuth2 client credentials: `POLARIS_CLIENT_ID` and `POLARIS_CLIENT_SECRET` (override the names with + `client_id_env_var` / `client_secret_env_var`). Tokens are refreshed automatically before they expire. +2. Otherwise a bearer token from `POLARIS_TOKEN` (override with `token_env_var`). + +To record Feast metadata on the Polaris tables when you run `feast apply`, select the Polaris provider: + +```yaml +# feature_store.yaml +provider: polaris +``` + +For every feature view backed by a `PolarisSource` (with `sync_metadata=True`, the default) the provider sets +`feast.project`, `feast.feature_view`, `feast.owner`, `feast.description`, `feast.tag.` and +`feast.is_feature_table` as table properties through the standard Iceberg REST `updateTable` operation. +When a feature view is deleted the table is kept and marked `feast.is_feature_table=false` with a +`feast.deleted_at` timestamp. A failed metadata sync is logged and never fails `feast apply`. + +Polaris has no lineage API, so `sync_lineage` is not available. + +To create a source for every table in a catalog: + +```python +sources = PolarisSource.discover( + warehouse="my_polaris_catalog", + namespaces=["ml"], # omit to scan all namespaces + timestamp_fields=("event_timestamp",), # tables without such a column are skipped +) +``` + ### Full Feature View Example ```python @@ -145,6 +192,21 @@ driver_stats_fv = FeatureView( | `register_as_feature_table` | `bool` | Register as UC feature table on `feast apply` (default: `True`) | | `sync_lineage` | `bool` | Sync lineage metadata to Unity Catalog (default: `True`) | +### PolarisSource (additional parameters) + +`PolarisSource` always uses `catalog_type="rest"`; `warehouse` is the Polaris catalog name. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `endpoint` | `str` | Defaults to `$POLARIS_HOST/api/catalog` | +| `token_env_var` | `str` | Bearer token variable (default: `POLARIS_TOKEN`) | +| `client_id_env_var` | `str` | OAuth client id variable (default: `POLARIS_CLIENT_ID`) | +| `client_secret_env_var` | `str` | OAuth client secret variable (default: `POLARIS_CLIENT_SECRET`) | +| `oauth_scope` | `str` | OAuth scope (default: `PRINCIPAL_ROLE:ALL`) | +| `oauth_server_uri` | `str` | Token endpoint if not `/v1/oauth/tokens`, e.g. an external IdP | +| `credential_vending` | `bool` | Request vended storage credentials for reads/writes (default: `True`) | +| `sync_metadata` | `bool` | Sync Feast metadata to table properties on `feast apply` with the `polaris` provider (default: `True`) | + ## Supported Types | Iceberg Type | Feast Type | diff --git a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/__init__.py b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/__init__.py index 2a6d36f87e2..5c3856ecb00 100644 --- a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/__init__.py +++ b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/__init__.py @@ -9,6 +9,12 @@ from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import ( IcebergSource, ) +from feast.infra.data_sources.contrib.iceberg_catalog.polaris_client import ( + PolarisClient, +) +from feast.infra.data_sources.contrib.iceberg_catalog.polaris_source import ( + PolarisSource, +) from feast.infra.data_sources.contrib.iceberg_catalog.uc_client import UCClient from feast.infra.data_sources.contrib.iceberg_catalog.unity_catalog_source import ( UnityCatalogSource, @@ -19,6 +25,8 @@ "IcebergCatalogError", "IcebergRestClient", "IcebergSource", + "PolarisClient", + "PolarisSource", "TableMetadata", "TableNotFoundError", "TempCredential", diff --git a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/iceberg_source.py b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/iceberg_source.py index c93b5db62d1..94a9a38a965 100644 --- a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/iceberg_source.py +++ b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/iceberg_source.py @@ -131,6 +131,38 @@ def get_catalog_client(self): def source_type(self) -> DataSourceProto.SourceType.ValueType: return DataSourceProto.BATCH_ICEBERG + def get_pyiceberg_catalog_config(self) -> Dict[str, str]: + """Return the PyIceberg ``load_catalog`` properties for a REST catalog. + + Subclasses (for example ``PolarisSource``) override this to add + catalog-specific authentication or credential-vending properties. + """ + config: Dict[str, str] = { + "type": "rest", + "uri": self.endpoint, + "warehouse": self.warehouse, + } + if self.token_env_var: + token = os.environ.get(self.token_env_var) + if token: + config["token"] = token + return config + + def load_pyiceberg_table(self): + """Load the backing table as a PyIceberg ``Table``. + + REST sources are loaded from ``get_pyiceberg_catalog_config()``; other + catalog types delegate to ``get_catalog_client()``. + """ + fqn = f"{self.namespace}.{self.iceberg_table}" + if self.catalog_type != "rest": + return self.get_catalog_client().load_table(fqn) + + from pyiceberg.catalog import load_catalog + + catalog = load_catalog(self.catalog_name, **self.get_pyiceberg_catalog_config()) + return catalog.load_table(fqn) + @staticmethod def from_proto(data_source: DataSourceProto) -> Any: cls_type = data_source.data_source_class_type @@ -140,6 +172,12 @@ def from_proto(data_source: DataSourceProto) -> Any: ) return UnityCatalogSource.from_proto(data_source) + if cls_type and "PolarisSource" in cls_type: + from feast.infra.data_sources.contrib.iceberg_catalog.polaris_source import ( + PolarisSource, + ) + + return PolarisSource.from_proto(data_source) custom_options = json.loads( str(data_source.custom_options.configuration, encoding="utf8") diff --git a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_client.py b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_client.py new file mode 100644 index 00000000000..f2800c9c085 --- /dev/null +++ b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_client.py @@ -0,0 +1,216 @@ +# Copyright 2026 The Feast Authors +# +# 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 +# +# https://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 threading +import time +from typing import Dict, List, Optional + +import requests +from requests.auth import AuthBase + +from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_rest_client import ( + CatalogAuthError, + IcebergRestClient, +) + +logger = logging.getLogger(__name__) + +DEFAULT_OAUTH_SCOPE = "PRINCIPAL_ROLE:ALL" +_DEFAULT_TOKEN_TTL_SECONDS = 3600 + + +class OAuthClientCredentialsTokenProvider: + """Fetches and caches OAuth2 client-credentials access tokens. + + The token is re-fetched shortly before it expires so that long-running + jobs (materialization, feature serving) keep working. + """ + + def __init__( + self, + token_url: str, + client_id: str, + client_secret: str, + scope: str = DEFAULT_OAUTH_SCOPE, + timeout: int = 30, + refresh_skew_seconds: int = 60, + ): + self.token_url = token_url + self._client_id = client_id + self._client_secret = client_secret + self.scope = scope + self.timeout = timeout + self.refresh_skew_seconds = refresh_skew_seconds + self._token: Optional[str] = None + self._expires_at: float = 0.0 + self._lock = threading.Lock() + + def get_token(self, force_refresh: bool = False) -> str: + with self._lock: + now = time.monotonic() + if ( + force_refresh + or self._token is None + or now >= self._expires_at - self.refresh_skew_seconds + ): + self._token, ttl = self._fetch_token() + self._expires_at = now + ttl + return self._token + + def _fetch_token(self) -> "tuple[str, float]": + try: + response = requests.post( + self.token_url, + data={ + "grant_type": "client_credentials", + "client_id": self._client_id, + "client_secret": self._client_secret, + "scope": self.scope, + }, + headers={"Accept": "application/json"}, + timeout=self.timeout, + ) + except requests.exceptions.RequestException as e: + raise CatalogAuthError( + f"Failed to reach OAuth token endpoint {self.token_url}: {e}" + ) from e + + if not response.ok: + raise CatalogAuthError( + f"OAuth token request to {self.token_url} failed: " + f"HTTP {response.status_code}", + status_code=response.status_code, + ) + body = response.json() + token = body.get("access_token") + if not token: + raise CatalogAuthError( + f"OAuth token response from {self.token_url} has no access_token" + ) + return token, float(body.get("expires_in", _DEFAULT_TOKEN_TTL_SECONDS)) + + +class _BearerTokenAuth(AuthBase): + """requests auth hook that attaches a fresh bearer token to every request.""" + + def __init__(self, provider: OAuthClientCredentialsTokenProvider): + self._provider = provider + + def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest: + request.headers["Authorization"] = f"Bearer {self._provider.get_token()}" + return request + + +class PolarisClient(IcebergRestClient): + """Apache Polaris client. + + Extends :class:`IcebergRestClient` with: + + - OAuth2 client-credentials authentication with automatic token refresh + (``client_id`` / ``client_secret``), as an alternative to a static token. + - Table property management through the standard Iceberg REST + ``updateTable`` operation (``set-properties`` / ``remove-properties``), + used to record Feast metadata on the Polaris table. + + Polaris serves the Iceberg REST API under ``/api/catalog`` and uses + the Polaris catalog name as the ``/v1/{prefix}`` path segment. + """ + + def __init__( + self, + endpoint: str, + warehouse: str, + token: Optional[str] = None, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + scope: str = DEFAULT_OAUTH_SCOPE, + oauth_server_uri: Optional[str] = None, + credential_vending: bool = True, + timeout: int = 30, + ): + super().__init__( + endpoint=endpoint, + token=None if (client_id and client_secret) else token, + warehouse=warehouse, + credential_vending=credential_vending, + timeout=timeout, + url_style="prefix", + ) + self.token_provider: Optional[OAuthClientCredentialsTokenProvider] = None + if client_id and client_secret: + self.token_provider = OAuthClientCredentialsTokenProvider( + token_url=oauth_server_uri or f"{self.endpoint}/v1/oauth/tokens", + client_id=client_id, + client_secret=client_secret, + scope=scope, + timeout=timeout, + ) + self._session.auth = _BearerTokenAuth(self.token_provider) + + def set_table_properties( + self, namespace: str, table: str, properties: Dict[str, str] + ) -> bool: + """Set properties on a table. Returns True on success. + + Failures are logged and reported as ``False`` so that metadata sync + never aborts ``feast apply``. + """ + if not properties: + return True + return self._commit_updates( + namespace, + table, + [ + { + "action": "set-properties", + "updates": {k: str(v) for k, v in properties.items()}, + } + ], + ) + + def remove_table_properties( + self, namespace: str, table: str, keys: List[str] + ) -> bool: + """Remove properties from a table. Returns True on success.""" + if not keys: + return True + return self._commit_updates( + namespace, table, [{"action": "remove-properties", "removals": keys}] + ) + + def _commit_updates( + self, namespace: str, table: str, updates: List[Dict[str, object]] + ) -> bool: + url = f"{self._base_url}/namespaces/{namespace}/tables/{table}" + try: + response = self._session.post( + url, + json={"requirements": [], "updates": updates}, + timeout=self.timeout, + ) + except (requests.exceptions.RequestException, CatalogAuthError) as e: + logger.warning("Failed to update table %s.%s: %s", namespace, table, e) + return False + + if not response.ok: + logger.warning( + "Failed to update table %s.%s: HTTP %s %s", + namespace, + table, + response.status_code, + response.text[:200], + ) + return False + return True diff --git a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_provider.py b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_provider.py new file mode 100644 index 00000000000..0891b193d24 --- /dev/null +++ b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_provider.py @@ -0,0 +1,125 @@ +# Copyright 2026 The Feast Authors +# +# 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 +# +# https://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. + +"""Polaris Provider: records Feast metadata on Polaris tables. + +Detects :class:`PolarisSource` in feature views during ``feast apply`` and sets +``feast.*`` table properties through the standard Iceberg REST ``updateTable`` +operation. Tables are never dropped; when a feature view is deleted the +properties are updated to mark the table as no longer a feature table. + +Usage in feature_store.yaml:: + + provider: polaris +""" + +import logging +from datetime import datetime, timezone +from typing import Dict, Sequence + +from feast.base_feature_view import BaseFeatureView +from feast.entity import Entity +from feast.feature_view import FeatureView +from feast.infra.data_sources.contrib.iceberg_catalog.polaris_source import ( + PolarisSource, +) +from feast.infra.passthrough_provider import PassthroughProvider + +logger = logging.getLogger(__name__) + +TAG_PREFIX = "feast.tag." + + +class PolarisProvider(PassthroughProvider): + """Provider that syncs Feast metadata to Polaris on ``feast apply``.""" + + def update_infra( + self, + project: str, + tables_to_delete: Sequence[BaseFeatureView], + tables_to_keep: Sequence[BaseFeatureView], + entities_to_delete: Sequence[Entity], + entities_to_keep: Sequence[Entity], + partial: bool, + ): + super().update_infra( + project, + tables_to_delete, + tables_to_keep, + entities_to_delete, + entities_to_keep, + partial, + ) + self._sync_polaris_properties(project, tables_to_keep) + self._mark_polaris_tables_removed(tables_to_delete) + + @staticmethod + def _polaris_source(view: BaseFeatureView): + if not isinstance(view, FeatureView): + return None + source = view.batch_source + if isinstance(source, PolarisSource) and source.sync_metadata: + return source + return None + + @staticmethod + def build_properties(project: str, view: FeatureView) -> Dict[str, str]: + properties: Dict[str, str] = { + "feast.is_feature_table": "true", + "feast.project": project, + "feast.feature_view": view.name, + } + if view.owner: + properties["feast.owner"] = view.owner + if view.description: + properties["feast.description"] = view.description + for key, value in (view.tags or {}).items(): + properties[f"{TAG_PREFIX}{key}"] = value + return properties + + def _sync_polaris_properties( + self, project: str, views: Sequence[BaseFeatureView] + ) -> None: + for view in views: + source = self._polaris_source(view) + if source is None: + continue + assert isinstance(view, FeatureView) + logger.info("Syncing Feast metadata for %s to %s", view.name, source.fqn) + client = source.get_catalog_client() + client.set_table_properties( + source.namespace, + source.iceberg_table, + self.build_properties(project, view), + ) + + def _mark_polaris_tables_removed(self, views: Sequence[BaseFeatureView]) -> None: + for view in views: + source = self._polaris_source(view) + if source is None: + continue + logger.info( + "Feature view %s deleted; keeping Polaris table %s and marking it", + view.name, + source.fqn, + ) + client = source.get_catalog_client() + client.set_table_properties( + source.namespace, + source.iceberg_table, + { + "feast.is_feature_table": "false", + "feast.deleted_at": datetime.now(timezone.utc).isoformat(), + }, + ) diff --git a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_source.py b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_source.py new file mode 100644 index 00000000000..099b4b6a69e --- /dev/null +++ b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/polaris_source.py @@ -0,0 +1,298 @@ +# Copyright 2026 The Feast Authors +# +# 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 +# +# https://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 json +import logging +import os +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from feast.credentials import ConnectionRef +from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import ( + IcebergSource, +) +from feast.infra.data_sources.contrib.iceberg_catalog.polaris_client import ( + DEFAULT_OAUTH_SCOPE, + PolarisClient, +) +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto + +logger = logging.getLogger(__name__) + +DEFAULT_TIMESTAMP_CANDIDATES = ("event_timestamp", "event_ts", "timestamp", "ts") + + +class PolarisSource(IcebergSource): + """Data source backed by an Apache Polaris catalog. + + Extends :class:`IcebergSource` with Polaris-specific behaviour: + + - ``endpoint`` defaults to ``$POLARIS_HOST/api/catalog``. + - Authentication via OAuth2 client credentials (read from the environment + variables named by ``client_id_env_var`` / ``client_secret_env_var``, + with automatic token refresh), falling back to a static bearer token in + ``token_env_var``. Only environment variable *names* are stored in the + registry, never secrets. + - Credential vending (``X-Iceberg-Access-Delegation``) is requested for + reads and writes done through PyIceberg when ``credential_vending`` is set. + - With ``sync_metadata`` set, ``PolarisProvider`` records Feast metadata + (project, feature view, owner, tags) as Polaris table properties on + ``feast apply``. + + ``warehouse`` is the Polaris catalog name. + """ + + def __init__( + self, + *, + warehouse: str, + namespace: str, + table: str, + name: Optional[str] = None, + timestamp_field: Optional[str] = None, + created_timestamp_column: Optional[str] = None, + field_mapping: Optional[Dict[str, str]] = None, + description: Optional[str] = "", + tags: Optional[Dict[str, str]] = None, + owner: Optional[str] = "", + endpoint: Optional[str] = None, + token_env_var: Optional[str] = None, + client_id_env_var: Optional[str] = None, + client_secret_env_var: Optional[str] = None, + oauth_scope: str = DEFAULT_OAUTH_SCOPE, + oauth_server_uri: Optional[str] = None, + credential_vending: bool = True, + catalog_name: str = "feast_polaris", + sync_metadata: bool = True, + connection_ref: Optional[ConnectionRef] = None, + ): + if endpoint is None: + host = os.environ.get("POLARIS_HOST", "").rstrip("/") + if not host: + raise ValueError( + "PolarisSource needs an endpoint: pass `endpoint=` or set " + "the POLARIS_HOST environment variable." + ) + endpoint = f"{host}/api/catalog" + + super().__init__( + warehouse=warehouse, + namespace=namespace, + table=table, + catalog_type="rest", + catalog_name=catalog_name, + endpoint=endpoint, + name=name, + timestamp_field=timestamp_field, + created_timestamp_column=created_timestamp_column, + field_mapping=field_mapping, + description=description, + tags=tags, + owner=owner, + token_env_var=token_env_var or "POLARIS_TOKEN", + credential_vending=credential_vending, + connection_ref=connection_ref, + ) + self.client_id_env_var = client_id_env_var or "POLARIS_CLIENT_ID" + self.client_secret_env_var = client_secret_env_var or "POLARIS_CLIENT_SECRET" + self.oauth_scope = oauth_scope + self.oauth_server_uri = oauth_server_uri + self.sync_metadata = sync_metadata + + def _resolve_client_credentials(self) -> Tuple[Optional[str], Optional[str]]: + client_id = os.environ.get(self.client_id_env_var) + client_secret = os.environ.get(self.client_secret_env_var) + if client_id and client_secret: + return client_id, client_secret + return None, None + + def get_catalog_client(self) -> PolarisClient: # type: ignore[override] + client_id, client_secret = self._resolve_client_credentials() + token = os.environ.get(self.token_env_var) if self.token_env_var else None + if not (client_id and client_secret) and not token: + logger.warning( + "No Polaris credentials found in the environment for source " + "%s (expected OAuth client credentials or a bearer token); " + "requests will be unauthenticated.", + self.name, + ) + return PolarisClient( + endpoint=self.endpoint, + warehouse=self.warehouse, + token=token, + client_id=client_id, + client_secret=client_secret, + scope=self.oauth_scope, + oauth_server_uri=self.oauth_server_uri, + credential_vending=self.credential_vending, + ) + + def get_pyiceberg_catalog_config(self) -> Dict[str, str]: + config: Dict[str, str] = { + "type": "rest", + "uri": self.endpoint, + "warehouse": self.warehouse, + } + client_id, client_secret = self._resolve_client_credentials() + if client_id and client_secret: + config["credential"] = f"{client_id}:{client_secret}" + config["scope"] = self.oauth_scope + if self.oauth_server_uri: + config["oauth2-server-uri"] = self.oauth_server_uri + elif self.token_env_var: + token = os.environ.get(self.token_env_var) + if token: + config["token"] = token + if self.credential_vending: + config["header.X-Iceberg-Access-Delegation"] = "vended-credentials" + return config + + @staticmethod + def discover( + *, + warehouse: str, + endpoint: Optional[str] = None, + namespaces: Optional[Sequence[str]] = None, + timestamp_fields: Sequence[str] = DEFAULT_TIMESTAMP_CANDIDATES, + **source_kwargs: Any, + ) -> List["PolarisSource"]: + """Build a ``PolarisSource`` for every table in the catalog. + + Tables are skipped unless they have a column named in + ``timestamp_fields`` (the first match is used as ``timestamp_field``). + Extra keyword arguments (``token_env_var``, ``client_id_env_var``, + ``tags``, ...) are passed to every created source. Each source is named + ``__``. + """ + probe = PolarisSource( + warehouse=warehouse, + namespace="_", + table="_", + endpoint=endpoint, + **source_kwargs, + ) + client = probe.get_catalog_client() + sources: List[PolarisSource] = [] + for namespace in namespaces or client.list_namespaces(): + for table in client.list_tables(namespace): + columns = {f["name"] for f in client.get_table_schema(namespace, table)} + timestamp_field = next( + (c for c in timestamp_fields if c in columns), None + ) + if timestamp_field is None: + logger.info( + "Skipping %s.%s: no timestamp column among %s", + namespace, + table, + list(timestamp_fields), + ) + continue + sources.append( + PolarisSource( + name=f"{namespace}__{table}", + warehouse=warehouse, + namespace=namespace, + table=table, + endpoint=probe.endpoint, + timestamp_field=timestamp_field, + **source_kwargs, + ) + ) + return sources + + @staticmethod + def from_proto(data_source: DataSourceProto) -> Any: + options = json.loads( + str(data_source.custom_options.configuration, encoding="utf8") + ) + return PolarisSource( + name=data_source.name, + endpoint=options["endpoint"], + warehouse=options["warehouse"], + namespace=options["namespace"], + table=options["table"], + token_env_var=options.get("token_env_var"), + client_id_env_var=options.get("client_id_env_var"), + client_secret_env_var=options.get("client_secret_env_var"), + oauth_scope=options.get("oauth_scope", DEFAULT_OAUTH_SCOPE), + oauth_server_uri=options.get("oauth_server_uri"), + credential_vending=options.get("credential_vending", True), + catalog_name=options.get("catalog_name", "feast_polaris"), + sync_metadata=options.get("sync_metadata", True), + timestamp_field=data_source.timestamp_field, + created_timestamp_column=data_source.created_timestamp_column, + field_mapping=dict(data_source.field_mapping), + description=data_source.description, + tags=dict(data_source.tags), + owner=data_source.owner, + connection_ref=ConnectionRef.from_tags(dict(data_source.tags)), + ) + + def _to_proto_impl(self) -> DataSourceProto: + config_json = json.dumps( + { + "endpoint": self.endpoint, + "warehouse": self.warehouse, + "namespace": self.namespace, + "table": self.iceberg_table, + "token_env_var": self.token_env_var, + "client_id_env_var": self.client_id_env_var, + "client_secret_env_var": self.client_secret_env_var, + "oauth_scope": self.oauth_scope, + "oauth_server_uri": self.oauth_server_uri, + "credential_vending": self.credential_vending, + "catalog_name": self.catalog_name, + "sync_metadata": self.sync_metadata, + } + ) + return DataSourceProto( + name=self.name, + type=DataSourceProto.BATCH_ICEBERG, + data_source_class_type=( + "feast.infra.data_sources.contrib.iceberg_catalog" + ".polaris_source.PolarisSource" + ), + custom_options=DataSourceProto.CustomSourceOptions( + configuration=bytes(config_json, encoding="utf8") + ), + description=self.description, + tags=self.tags, + owner=self.owner, + timestamp_field=self.timestamp_field, + created_timestamp_column=self.created_timestamp_column, + field_mapping=self.field_mapping, + ) + + def __eq__(self, other): + if not isinstance(other, PolarisSource): + return False + if not super().__eq__(other): + return False + return ( + self.client_id_env_var == other.client_id_env_var + and self.client_secret_env_var == other.client_secret_env_var + and self.oauth_scope == other.oauth_scope + and self.oauth_server_uri == other.oauth_server_uri + and self.sync_metadata == other.sync_metadata + ) + + def __hash__(self): + return hash( + ( + self.name, + self.endpoint, + self.warehouse, + self.namespace, + self.iceberg_table, + ) + ) diff --git a/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/tests/test_polaris.py b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/tests/test_polaris.py new file mode 100644 index 00000000000..a78b256e6f1 --- /dev/null +++ b/sdk/python/feast/infra/data_sources/contrib/iceberg_catalog/tests/test_polaris.py @@ -0,0 +1,430 @@ +"""Unit tests for PolarisSource, PolarisClient and PolarisProvider.""" + +import json +from typing import Any, Dict +from unittest.mock import MagicMock, Mock, patch + +import pytest +import requests + +from feast.entity import Entity +from feast.feature_view import FeatureView +from feast.field import Field +from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_rest_client import ( + CatalogAuthError, +) +from feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source import ( + IcebergSource, +) +from feast.infra.data_sources.contrib.iceberg_catalog.polaris_client import ( + OAuthClientCredentialsTokenProvider, + PolarisClient, +) +from feast.infra.data_sources.contrib.iceberg_catalog.polaris_provider import ( + PolarisProvider, +) +from feast.infra.data_sources.contrib.iceberg_catalog.polaris_source import ( + PolarisSource, +) +from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto +from feast.types import Float32 +from feast.value_type import ValueType + +ENDPOINT = "http://polaris:8181/api/catalog" + + +def _source(**kwargs) -> PolarisSource: + defaults: Dict[str, Any] = dict( + endpoint=ENDPOINT, + warehouse="my_catalog", + namespace="ml", + table="driver_stats", + timestamp_field="event_timestamp", + ) + defaults.update(kwargs) + return PolarisSource(**defaults) + + +@pytest.fixture(autouse=True) +def _clean_env(monkeypatch): + for var in ( + "POLARIS_HOST", + "POLARIS_TOKEN", + "POLARIS_CLIENT_ID", + "POLARIS_CLIENT_SECRET", + ): + monkeypatch.delenv(var, raising=False) + + +class TestPolarisSource: + def test_defaults(self): + source = _source() + assert source.catalog_type == "rest" + assert source.token_env_var == "POLARIS_TOKEN" + assert source.client_id_env_var == "POLARIS_CLIENT_ID" + secret_var = source.client_secret_env_var + assert secret_var == "POLARIS_CLIENT_SECRET" # pragma: allowlist secret + assert source.sync_metadata is True + assert source.credential_vending is True + assert source.fqn == "my_catalog.ml.driver_stats" + + def test_is_subclass_of_iceberg_source(self): + assert isinstance(_source(), IcebergSource) + + def test_endpoint_from_polaris_host(self, monkeypatch): + monkeypatch.setenv("POLARIS_HOST", "http://polaris:8181/") + source = PolarisSource(warehouse="w", namespace="n", table="t") + assert source.endpoint == "http://polaris:8181/api/catalog" + + def test_missing_endpoint_raises(self): + with pytest.raises(ValueError, match="POLARIS_HOST"): + PolarisSource(warehouse="w", namespace="n", table="t") + + def test_proto_roundtrip(self): + source = _source( + description="d", + tags={"team": "ml"}, + owner="o@example.com", + client_id_env_var="MY_ID", + client_secret_env_var="MY_SECRET", # pragma: allowlist secret + oauth_scope="PRINCIPAL_ROLE:feast", + oauth_server_uri="http://idp/token", + credential_vending=False, + sync_metadata=False, + ) + proto = source.to_proto() + assert proto.type == DataSourceProto.BATCH_ICEBERG + assert proto.data_source_class_type.endswith("polaris_source.PolarisSource") + options = json.loads(str(proto.custom_options.configuration, "utf8")) + # Only env var names are persisted, never secrets. + assert options["client_id_env_var"] == "MY_ID" + assert "client_secret" not in options + + restored = PolarisSource.from_proto(proto) + assert isinstance(restored, PolarisSource) + assert restored == source + assert restored.oauth_scope == "PRINCIPAL_ROLE:feast" + assert restored.oauth_server_uri == "http://idp/token" + assert restored.sync_metadata is False + assert restored.credential_vending is False + + def test_iceberg_source_from_proto_dispatches_to_polaris(self): + proto = _source().to_proto() + restored = IcebergSource.from_proto(proto) + assert isinstance(restored, PolarisSource) + + def test_equality_considers_polaris_fields(self): + assert _source() == _source() + assert _source(sync_metadata=False) != _source() + assert _source(oauth_scope="PRINCIPAL_ROLE:x") != _source() + + def test_pyiceberg_config_static_token(self, monkeypatch): + monkeypatch.setenv("POLARIS_TOKEN", "tok") + config = _source().get_pyiceberg_catalog_config() + assert config["type"] == "rest" + assert config["uri"] == ENDPOINT + assert config["warehouse"] == "my_catalog" + assert config["token"] == "tok" + assert "credential" not in config + assert config["header.X-Iceberg-Access-Delegation"] == "vended-credentials" + + def test_pyiceberg_config_oauth_wins_over_token(self, monkeypatch): + monkeypatch.setenv("POLARIS_TOKEN", "tok") + monkeypatch.setenv("POLARIS_CLIENT_ID", "cid") + monkeypatch.setenv("POLARIS_CLIENT_SECRET", "sec") + config = _source( + oauth_server_uri="http://idp/token" + ).get_pyiceberg_catalog_config() + assert config["credential"] == "cid:sec" + assert config["scope"] == "PRINCIPAL_ROLE:ALL" + assert config["oauth2-server-uri"] == "http://idp/token" + assert "token" not in config + + def test_pyiceberg_config_without_credential_vending(self, monkeypatch): + monkeypatch.setenv("POLARIS_TOKEN", "tok") + config = _source(credential_vending=False).get_pyiceberg_catalog_config() + assert "header.X-Iceberg-Access-Delegation" not in config + + @patch("pyiceberg.catalog.load_catalog") + def test_load_pyiceberg_table_uses_polaris_config(self, mock_load, monkeypatch): + monkeypatch.setenv("POLARIS_CLIENT_ID", "cid") + monkeypatch.setenv("POLARIS_CLIENT_SECRET", "sec") + _source().load_pyiceberg_table() + name, kwargs = mock_load.call_args[0][0], mock_load.call_args[1] + assert name == "feast_polaris" + assert kwargs["credential"] == "cid:sec" + mock_load.return_value.load_table.assert_called_once_with("ml.driver_stats") + + def test_catalog_client_is_polaris_client(self, monkeypatch): + monkeypatch.setenv("POLARIS_CLIENT_ID", "cid") + monkeypatch.setenv("POLARIS_CLIENT_SECRET", "sec") + client = _source().get_catalog_client() + assert isinstance(client, PolarisClient) + assert client.token_provider is not None + + def test_base_iceberg_source_config_is_unchanged(self, monkeypatch): + monkeypatch.setenv("T", "tok") + source = IcebergSource( + endpoint="http://host/iceberg", + warehouse="w", + namespace="n", + table="t", + token_env_var="T", + ) + assert source.get_pyiceberg_catalog_config() == { + "type": "rest", + "uri": "http://host/iceberg", + "warehouse": "w", + "token": "tok", + } + + +class TestDiscover: + @patch.object(PolarisClient, "get_table_schema") + @patch.object(PolarisClient, "list_tables") + @patch.object(PolarisClient, "list_namespaces") + def test_discover_builds_sources_and_skips_tables_without_timestamp( + self, mock_ns, mock_tables, mock_schema + ): + mock_ns.return_value = ["ml"] + mock_tables.return_value = ["with_ts", "without_ts"] + mock_schema.side_effect = lambda ns, t: ( + [ + {"name": "id", "type": "long"}, + {"name": "event_timestamp", "type": "timestamptz"}, + ] + if t == "with_ts" + else [{"name": "id", "type": "long"}] + ) + sources = PolarisSource.discover( + warehouse="my_catalog", endpoint=ENDPOINT, tags={"team": "ml"} + ) + assert [s.name for s in sources] == ["ml__with_ts"] + assert sources[0].timestamp_field == "event_timestamp" + assert sources[0].tags == {"team": "ml"} + assert sources[0].endpoint == ENDPOINT + + @patch.object(PolarisClient, "list_tables") + @patch.object(PolarisClient, "list_namespaces") + def test_discover_respects_explicit_namespaces(self, mock_ns, mock_tables): + mock_tables.return_value = [] + PolarisSource.discover(warehouse="w", endpoint=ENDPOINT, namespaces=["a", "b"]) + mock_ns.assert_not_called() + assert [c.args[0] for c in mock_tables.call_args_list] == ["a", "b"] + + +class TestPolarisClientAuth: + def test_static_token_header(self): + client = PolarisClient(ENDPOINT, "w", token="tok") + assert client._session.headers["Authorization"] == "Bearer tok" + assert client.token_provider is None + assert client.url_style == "prefix" + + def test_oauth_overrides_static_token(self): + client = PolarisClient( + ENDPOINT, "w", token="tok", client_id="cid", client_secret="sec" + ) + assert "Authorization" not in client._session.headers + assert client.token_provider is not None + assert client.token_provider.token_url == f"{ENDPOINT}/v1/oauth/tokens" + + @patch("requests.post") + def test_token_fetch_and_cache(self, mock_post): + mock_post.return_value = Mock( + ok=True, json=lambda: {"access_token": "abc", "expires_in": 3600} + ) + provider = OAuthClientCredentialsTokenProvider( + "http://idp/token", "cid", "sec", scope="PRINCIPAL_ROLE:ALL" + ) + assert provider.get_token() == "abc" + assert provider.get_token() == "abc" + assert mock_post.call_count == 1 + data = mock_post.call_args.kwargs["data"] + assert data["grant_type"] == "client_credentials" + assert data["client_id"] == "cid" + assert data["scope"] == "PRINCIPAL_ROLE:ALL" + + @patch("requests.post") + def test_token_refreshes_before_expiry(self, mock_post): + mock_post.side_effect = [ + Mock(ok=True, json=lambda: {"access_token": "t1", "expires_in": 100}), + Mock(ok=True, json=lambda: {"access_token": "t2", "expires_in": 100}), + ] + provider = OAuthClientCredentialsTokenProvider( + "http://idp/token", "cid", "sec", refresh_skew_seconds=60 + ) + with patch( + "feast.infra.data_sources.contrib.iceberg_catalog.polaris_client.time.monotonic" + ) as clock: + clock.return_value = 1000.0 + assert provider.get_token() == "t1" + clock.return_value = 1030.0 # 70s left, outside the 60s skew + assert provider.get_token() == "t1" + clock.return_value = 1050.0 # 50s left, inside the skew -> refresh + assert provider.get_token() == "t2" + assert mock_post.call_count == 2 + + @patch("requests.post") + def test_token_http_error_raises_auth_error(self, mock_post): + mock_post.return_value = Mock(ok=False, status_code=401) + provider = OAuthClientCredentialsTokenProvider("http://idp/token", "c", "s") + with pytest.raises(CatalogAuthError): + provider.get_token() + + @patch("requests.post") + def test_token_connection_error_raises_auth_error(self, mock_post): + mock_post.side_effect = requests.exceptions.ConnectionError("down") + provider = OAuthClientCredentialsTokenProvider("http://idp/token", "c", "s") + with pytest.raises(CatalogAuthError): + provider.get_token() + + @patch("requests.post") + def test_missing_access_token_raises(self, mock_post): + mock_post.return_value = Mock(ok=True, json=lambda: {}) + provider = OAuthClientCredentialsTokenProvider("http://idp/token", "c", "s") + with pytest.raises(CatalogAuthError, match="access_token"): + provider.get_token() + + @patch("requests.post") + def test_session_attaches_fresh_bearer_token(self, mock_post): + mock_post.return_value = Mock( + ok=True, json=lambda: {"access_token": "abc", "expires_in": 3600} + ) + client = PolarisClient(ENDPOINT, "w", client_id="cid", client_secret="sec") + prepared = client._session.prepare_request( + requests.Request("GET", f"{ENDPOINT}/v1/w/namespaces") + ) + assert prepared.headers["Authorization"] == "Bearer abc" + + +class TestPolarisClientProperties: + @patch("requests.Session.post") + def test_set_table_properties_request(self, mock_post): + mock_post.return_value = Mock(ok=True) + client = PolarisClient(ENDPOINT, "my_catalog", token="tok") + assert client.set_table_properties("ml", "t", {"feast.project": "p"}) is True + + url = mock_post.call_args.args[0] + assert url == f"{ENDPOINT}/v1/my_catalog/namespaces/ml/tables/t" + assert mock_post.call_args.kwargs["json"] == { + "requirements": [], + "updates": [ + {"action": "set-properties", "updates": {"feast.project": "p"}} + ], + } + + @patch("requests.Session.post") + def test_set_table_properties_noop_when_empty(self, mock_post): + client = PolarisClient(ENDPOINT, "w", token="tok") + assert client.set_table_properties("ml", "t", {}) is True + mock_post.assert_not_called() + + @patch("requests.Session.post") + def test_remove_table_properties_request(self, mock_post): + mock_post.return_value = Mock(ok=True) + client = PolarisClient(ENDPOINT, "w", token="tok") + assert client.remove_table_properties("ml", "t", ["feast.deleted_at"]) + assert mock_post.call_args.kwargs["json"]["updates"] == [ + {"action": "remove-properties", "removals": ["feast.deleted_at"]} + ] + + @patch("requests.Session.post") + def test_http_failure_returns_false_without_raising(self, mock_post): + mock_post.return_value = Mock(ok=False, status_code=403, text="forbidden") + client = PolarisClient(ENDPOINT, "w", token="tok") + assert client.set_table_properties("ml", "t", {"k": "v"}) is False + + @patch("requests.Session.post") + def test_connection_failure_returns_false(self, mock_post): + mock_post.side_effect = requests.exceptions.ConnectionError("down") + client = PolarisClient(ENDPOINT, "w", token="tok") + assert client.set_table_properties("ml", "t", {"k": "v"}) is False + + +def _feature_view(source, **kwargs) -> FeatureView: + return FeatureView( + name="driver_stats", + entities=[ + Entity( + name="driver_id", join_keys=["driver_id"], value_type=ValueType.INT64 + ) + ], + schema=[Field(name="conv_rate", dtype=Float32)], + source=source, + **kwargs, + ) + + +class TestPolarisProvider: + def test_build_properties(self): + view = _feature_view( + _source(), owner="o@example.com", description="stats", tags={"team": "ml"} + ) + assert PolarisProvider.build_properties("proj", view) == { + "feast.is_feature_table": "true", + "feast.project": "proj", + "feast.feature_view": "driver_stats", + "feast.owner": "o@example.com", + "feast.description": "stats", + "feast.tag.team": "ml", + } + + def test_sync_sets_properties_for_polaris_views_only(self): + polaris_source = _source() + client = MagicMock() + view = _feature_view(polaris_source) + other = FeatureView( + name="other", + entities=[ + Entity( + name="driver_id", + join_keys=["driver_id"], + value_type=ValueType.INT64, + ) + ], + schema=[Field(name="x", dtype=Float32)], + source=IcebergSource( + endpoint="http://h", + warehouse="w", + namespace="n", + table="t", + timestamp_field="ts", + ), + ) + provider = object.__new__(PolarisProvider) + with patch.object(PolarisSource, "get_catalog_client", return_value=client): + provider._sync_polaris_properties("proj", [view, other]) + + client.set_table_properties.assert_called_once() + args = client.set_table_properties.call_args.args + assert args[:2] == ("ml", "driver_stats") + assert args[2]["feast.project"] == "proj" + + def test_sync_respects_sync_metadata_flag(self): + client = MagicMock() + view = _feature_view(_source(sync_metadata=False)) + provider = object.__new__(PolarisProvider) + with patch.object(PolarisSource, "get_catalog_client", return_value=client): + provider._sync_polaris_properties("proj", [view]) + client.set_table_properties.assert_not_called() + + def test_deleted_view_marks_table_without_dropping(self): + client = MagicMock() + view = _feature_view(_source()) + provider = object.__new__(PolarisProvider) + with patch.object(PolarisSource, "get_catalog_client", return_value=client): + provider._mark_polaris_tables_removed([view]) + + props = client.set_table_properties.call_args.args[2] + assert props["feast.is_feature_table"] == "false" + assert "feast.deleted_at" in props + assert not client.method_calls or all( + "drop" not in c[0] for c in client.method_calls + ) + + def test_registered_in_provider_map(self): + from feast.infra.provider import PROVIDERS_CLASS_FOR_TYPE + + assert PROVIDERS_CLASS_FOR_TYPE["polaris"].endswith( + "polaris_provider.PolarisProvider" + ) diff --git a/sdk/python/feast/infra/offline_stores/contrib/spark_offline_store/spark.py b/sdk/python/feast/infra/offline_stores/contrib/spark_offline_store/spark.py index 119e67300a5..627e8caced3 100644 --- a/sdk/python/feast/infra/offline_stores/contrib/spark_offline_store/spark.py +++ b/sdk/python/feast/infra/offline_stores/contrib/spark_offline_store/spark.py @@ -1267,25 +1267,7 @@ def _load_pyiceberg_table(data_source: "DataSource"): ) assert isinstance(data_source, IcebergSource) - fqn = f"{data_source.namespace}.{data_source.iceberg_table}" - - if data_source.catalog_type != "rest": - catalog_client = data_source.get_catalog_client() - return catalog_client.load_table(fqn) - - from pyiceberg.catalog import load_catalog - - catalog_config: Dict[str, str] = { - "type": "rest", - "uri": data_source.endpoint, - "warehouse": data_source.warehouse, - } - if data_source.token_env_var: - token = os.environ.get(data_source.token_env_var) - if token: - catalog_config["token"] = token - catalog = load_catalog(data_source.catalog_name, **catalog_config) - return catalog.load_table(fqn) + return data_source.load_pyiceberg_table() def _iceberg_offline_write_batch( diff --git a/sdk/python/feast/infra/offline_stores/duckdb.py b/sdk/python/feast/infra/offline_stores/duckdb.py index 8672f965fe6..90a2537da5d 100644 --- a/sdk/python/feast/infra/offline_stores/duckdb.py +++ b/sdk/python/feast/infra/offline_stores/duckdb.py @@ -140,25 +140,7 @@ def _read_iceberg_catalog_source(data_source: "IcebergSource", repo_path: str) - Loads the table through the configured catalog (REST, SQL, Hive, etc.) and scans it to Arrow. """ - fqn = f"{data_source.namespace}.{data_source.iceberg_table}" - - if data_source.catalog_type != "rest": - catalog_client = data_source.get_catalog_client() - table = catalog_client.load_table(fqn) - else: - from pyiceberg.catalog import load_catalog - - catalog_config: dict = { - "type": "rest", - "uri": data_source.endpoint, - "warehouse": data_source.warehouse, - } - if data_source.token_env_var: - token = os.environ.get(data_source.token_env_var) - if token: - catalog_config["token"] = token - catalog = load_catalog(data_source.catalog_name, **catalog_config) - table = catalog.load_table(fqn) + table = data_source.load_pyiceberg_table() return ibis.memtable(table.scan().to_arrow()) @@ -170,25 +152,7 @@ def _load_pyiceberg_table_for_write(data_source: "IcebergSource"): but returns the raw PyIceberg table instead of an ibis memtable, so the caller can use ``table.append()`` or ``table.overwrite()`` for writes. """ - fqn = f"{data_source.namespace}.{data_source.iceberg_table}" - - if data_source.catalog_type != "rest": - catalog_client = data_source.get_catalog_client() - return catalog_client.load_table(fqn) - - from pyiceberg.catalog import load_catalog - - catalog_config: dict = { - "type": "rest", - "uri": data_source.endpoint, - "warehouse": data_source.warehouse, - } - if data_source.token_env_var: - token = os.environ.get(data_source.token_env_var) - if token: - catalog_config["token"] = token - catalog = load_catalog(data_source.catalog_name, **catalog_config) - return catalog.load_table(fqn) + return data_source.load_pyiceberg_table() def _write_iceberg_data_source( diff --git a/sdk/python/feast/infra/provider.py b/sdk/python/feast/infra/provider.py index 2af6f84f10f..23dfd7ea93b 100644 --- a/sdk/python/feast/infra/provider.py +++ b/sdk/python/feast/infra/provider.py @@ -46,6 +46,7 @@ "azure": "feast.infra.passthrough_provider.PassthroughProvider", "chronon": "feast.infra.chronon_provider.ChrononProvider", "unity_catalog": "feast.infra.data_sources.contrib.iceberg_catalog.uc_provider.UnityCatalogProvider", + "polaris": "feast.infra.data_sources.contrib.iceberg_catalog.polaris_provider.PolarisProvider", }