Skip to content
Merged
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
62 changes: 62 additions & 0 deletions docs/reference/data-sources/iceberg.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<key>` 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
Expand Down Expand Up @@ -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 `<endpoint>/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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -19,6 +25,8 @@
"IcebergCatalogError",
"IcebergRestClient",
"IcebergSource",
"PolarisClient",
"PolarisSource",
"TableMetadata",
"TableNotFoundError",
"TempCredential",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand Down
Original file line number Diff line number Diff line change
@@ -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 ``<host>/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
Loading
Loading