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
12 changes: 8 additions & 4 deletions sdk/python/feast/api/registry/rest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def _get_allowed():

all_projects = fs.registry.list_projects(allow_cache=True)
if not all_projects:
return None
return []

allowed_projects = permitted_resources(
all_projects, AuthzedAction.DESCRIBE
Expand All @@ -205,9 +205,13 @@ def _get_allowed():
if mapped_project in allowed_project_names:
namespaces.add(ext_ns)

return list(namespaces) if namespaces else None
except Exception:
return None
# An empty list means "no namespaces allowed", not "no filter".
return list(namespaces)
except Exception as e:
logger.warning(
f"Denying lineage access, permission check failed: {e}"
)
return []

return _get_allowed

Expand Down
54 changes: 54 additions & 0 deletions sdk/python/feast/batch_feature_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from feast import flags_helper
from feast.aggregation import Aggregation
from feast.base_feature_view import BaseFeatureView
from feast.data_source import DataSource
from feast.entity import Entity
from feast.feature_view import FeatureView
Expand Down Expand Up @@ -195,6 +196,19 @@ def __copy__(self) -> "BatchFeatureView":
fv._raw_feature_transformation_proto = self._raw_feature_transformation_proto
return fv

def _schema_or_udf_changed(self, other: BaseFeatureView) -> bool:
"""Check for BatchFeatureView schema/UDF changes."""
if super()._schema_or_udf_changed(other):
return True

if not isinstance(other, BatchFeatureView):
return True

# A changed UDF must be stored, not treated as a metadata-only update.
return _transformation_changed(
self.feature_transformation, other.feature_transformation
)

def get_feature_transformation(self) -> Optional[Transformation]:
if not self.udf:
return None
Expand All @@ -214,6 +228,46 @@ def get_feature_transformation(self) -> Optional[Transformation]:
)


def _transformation_changed(
new: Optional[Transformation], old: Optional[Transformation]
) -> bool:
if new is None or old is None:
return new is not old
if type(new) is not type(old):
return True
# Some types compare extra state, e.g. a Substrait plan.
if type(new).__eq__ is not object.__eq__ and new != old:
return True
if new.udf_string and old.udf_string:
return new.udf_string != old.udf_string
return _udf_changed(new.udf, old.udf)


def _udf_changed(new_udf: Callable, old_udf: Callable) -> bool:
"""Compare two UDFs that have no source text.

Bytecode alone misses constants: ``lambda _: "SELECT 1"`` and
``lambda _: "SELECT 2"`` share it. The code object also holds the
constants, so compare it whole, plus the default arguments and the values
captured in the closure.
"""

def state(udf: Callable) -> tuple:
closure = tuple(cell.cell_contents for cell in udf.__closure__ or ()) # type: ignore[attr-defined]
return (
udf.__code__, # type: ignore[attr-defined]
udf.__defaults__, # type: ignore[attr-defined]
udf.__kwdefaults__, # type: ignore[attr-defined]
closure,
)

try:
return bool(state(new_udf) != state(old_udf))
except Exception:
# Values that cannot be compared count as a change, so the new UDF is stored.
return True


def batch_feature_view(
*,
name: Optional[str] = None,
Expand Down
7 changes: 5 additions & 2 deletions sdk/python/feast/feature_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,10 +634,13 @@ def _from_proto_internal(
for view_spec in feature_view_proto.spec.source_views
]

from feast.batch_feature_view import BatchFeatureView

has_transformation = feature_view_proto.spec.HasField("feature_transformation")

if has_transformation and cls == FeatureView:
from feast.batch_feature_view import BatchFeatureView
# BatchFeatureView.from_proto must restore the transformation too, or
# `feast apply` compares a new UDF against a stored copy that has none.
if has_transformation and cls in (FeatureView, BatchFeatureView):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Reapplied batch views crash during deserialization

Reapplying SQL or Flink batch views through Registry.apply_feature_view now raises AttributeError. Neither SQLTransformation nor FlinkTransformation implements from_proto, and the dispatch only catches ValueError and KeyError. Even unchanged definitions cannot be reapplied.

Learn more

The file registry calls the incoming view's concrete class to restore an existing definition before comparing changes in Registry.apply_feature_view. Previously, BatchFeatureView bypassed transformation reconstruction there. The expanded condition now dispatches restoration through the mode-specific class selected by get_transformation_class_from_type. SQLTransformation and FlinkTransformation have no from_proto, including through their Transformation base. Calling that missing method raises AttributeError, which escapes the existing exception handler; Spark wrappers have the same missing deserializer.

Example: Apply a BatchFeatureView with a FileSource, an explicit schema, mode="sql", and a SQL-producing UDF through Registry.apply_feature_view. Applying the identical definition again enters transformation restoration and raises AttributeError: type object 'SQLTransformation' has no attribute 'from_proto'.

Recommended fix: Provide mode-preserving deserialization for every supported transformation wrapper before routing BatchFeatureView restoration through this dispatch. Add round-trip and repeated-apply tests for SQL and Flink, and cover Spark when its dependencies are available. Simply swallowing AttributeError or discarding the transformation would leave the persisted definition incorrect.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

from feast.transformation.factory import get_transformation_class_from_type
from feast.transformation.python_transformation import PythonTransformation
from feast.transformation.substrait_transformation import (
Expand Down
10 changes: 6 additions & 4 deletions sdk/python/feast/lineage_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _get_allowed():

all_projects = store.registry.list_projects(allow_cache=True)
if not all_projects:
return None
return []

allowed_projects = permitted_resources(all_projects, AuthzedAction.DESCRIBE)
ol_ns_config = getattr(ol_config, "namespace", "feast")
Expand All @@ -96,9 +96,11 @@ def _get_allowed():
if mapped_project in allowed_project_names:
namespaces.add(ext_ns)

return list(namespaces) if namespaces else None
except Exception:
return None
# An empty list means "no namespaces allowed", not "no filter".
return list(namespaces)
except Exception as e:
logger.warning(f"Denying lineage access, permission check failed: {e}")
return []

return _get_allowed

Expand Down
19 changes: 18 additions & 1 deletion sdk/python/feast/openlineage/consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ def get_full_lineage_graph(
or matching dataSource URIs).
"""
ns_filter = _get_namespace_filter(get_allowed_namespaces)
allowed_namespaces = ns_filter
if namespace:
if ns_filter is not None and namespace not in ns_filter:
return {"nodes": [], "edges": [], "symlinks": []}
Expand Down Expand Up @@ -360,6 +361,21 @@ def get_full_lineage_graph(

edges = store.get_all_lineage_edges(namespaces=ns_filter)
symlinks = store.get_all_symlinks()
if allowed_namespaces is not None:
# A link is only shown when both of its ends are in namespaces the
# caller may see, so it cannot reveal another team's datasets.
allowed = set(allowed_namespaces)
edges = [
e
for e in edges
if e["source_namespace"] in allowed and e["target_namespace"] in allowed
]
symlinks = [
sl
for sl in symlinks
if sl["dataset_namespace"] in allowed
and sl["linked_namespace"] in allowed
]
for sl in symlinks:
edges.append(
{
Expand Down Expand Up @@ -513,7 +529,8 @@ def _get_namespace_filter(ns_callable) -> Optional[List[str]]:
try:
return ns_callable()
except Exception:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

returning [] still leaves a lineage read path open: get_full_lineage_graph calls store.get_all_symlinks() without a namespace filter, returns those records and appends them to edges. a user with no allowed projects, including a failed permission check, can still read dataset names and namespaces from other teams through /lineage/openlineage/graph. we need to filter symlinks by authorized endpoints and cover this endpoint with denied-access and mixed-namespace regressions.

return None
# Fail closed: a broken RBAC check must not expose every namespace.
return []
return None

return router
14 changes: 7 additions & 7 deletions sdk/python/feast/openlineage/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ def get_events(

if namespace:
query = query.where(tbl.c.job_namespace == namespace)
elif namespaces:
elif namespaces is not None:
query = query.where(tbl.c.job_namespace.in_(namespaces))
if job_name:
query = query.where(tbl.c.job_name == job_name)
Expand All @@ -481,7 +481,7 @@ def get_jobs(
) -> List[Dict[str, Any]]:
tbl = OL_TABLES["jobs"]
query = select(tbl).order_by(tbl.c.updated_at.desc())
if namespaces:
if namespaces is not None:
query = query.where(tbl.c.job_namespace.in_(namespaces))
if limit > 0:
query = query.limit(limit).offset(offset)
Expand All @@ -493,7 +493,7 @@ def get_jobs(
def count_jobs(self, namespaces: Optional[List[str]] = None) -> int:
tbl = OL_TABLES["jobs"]
query = select(func.count()).select_from(tbl)
if namespaces:
if namespaces is not None:
query = query.where(tbl.c.job_namespace.in_(namespaces))
with self._engine.connect() as conn:
return conn.execute(query).scalar() or 0
Expand All @@ -506,7 +506,7 @@ def get_datasets(
) -> List[Dict[str, Any]]:
tbl = OL_TABLES["datasets"]
query = select(tbl).order_by(tbl.c.updated_at.desc())
if namespaces:
if namespaces is not None:
query = query.where(tbl.c.dataset_namespace.in_(namespaces))
if limit > 0:
query = query.limit(limit).offset(offset)
Expand All @@ -518,7 +518,7 @@ def get_datasets(
def count_datasets(self, namespaces: Optional[List[str]] = None) -> int:
tbl = OL_TABLES["datasets"]
query = select(func.count()).select_from(tbl)
if namespaces:
if namespaces is not None:
query = query.where(tbl.c.dataset_namespace.in_(namespaces))
with self._engine.connect() as conn:
return conn.execute(query).scalar() or 0
Expand Down Expand Up @@ -630,7 +630,7 @@ def _traverse(
f"{r['target_type']}:{r['target_namespace']}:{r['target_name']}"
)

if allowed_namespaces:
if allowed_namespaces is not None:
if (
r["source_namespace"] not in allowed_namespaces
or r["target_namespace"] not in allowed_namespaces
Expand Down Expand Up @@ -1644,7 +1644,7 @@ def get_all_lineage_edges(
) -> List[Dict[str, Any]]:
tbl = OL_TABLES["lineage_edges"]
query = select(tbl)
if namespaces:
if namespaces is not None:
query = query.where(
tbl.c.source_namespace.in_(namespaces)
| tbl.c.target_namespace.in_(namespaces)
Expand Down
13 changes: 9 additions & 4 deletions sdk/python/feast/permissions/enforcer.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def enforce_policy(
if evaluator.is_decided():
grant, explanations = evaluator.grant()
if not grant:
if filter_only and p.name_patterns:
if filter_only and (p.name_patterns or p.required_tags):
continue
logger.error(f"Permission denied: {','.join(explanations)}")
raise FeastPermissionError(",".join(explanations))
Expand All @@ -103,13 +103,18 @@ def enforce_policy(
message = f"No permissions defined to manage {actions} on {type(resource)}/{resource.name}."
logger.exception(f"**PERMISSION NOT GRANTED**: {message}")
raise FeastPermissionError(message)
elif not any(p.name_patterns for p in resource_type_permissions):
# Permissions exist for this resource type but no name_patterns - should raise error
elif not any(
p.name_patterns or p.required_tags
for p in resource_type_permissions
):
# Permissions exist for this resource type but none is scoped by
# name_patterns or required_tags - should raise error
message = f"No permissions defined to manage {actions} on {type(resource)}/{resource.name}."
logger.exception(f"**PERMISSION NOT GRANTED**: {message}")
raise FeastPermissionError(message)
else:
# Permissions exist for this resource type with name_patterns - filter out this resource
# Permissions for this resource type are scoped by name_patterns or
# required_tags, so this resource is out of scope - filter it out
logger.debug(
f"Filtering out {type(resource).__name__}:{resource.name} - no matching permissions"
)
Expand Down
27 changes: 12 additions & 15 deletions sdk/python/feast/permissions/matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,22 +79,19 @@ def resource_match_config(
return False

if required_tags:
if hasattr(resource, "required_tags"):
if isinstance(resource.required_tags, dict):
for tag in required_tags.keys():
required_value = required_tags.get(tag)
actual_value = resource.required_tags.get(tag)
if required_value != actual_value:
logger.info(
f"Unmatched value {actual_value} for required tag {tag}: expected {required_value}"
)
return False
else:
logger.warning(
f"Resource {resource} has no `required_tags` attribute of unexpected type {type(resource.required_tags)}"
resource_tags = getattr(resource, "tags", None)
if not isinstance(resource_tags, dict):
logger.info(
f"Resource {resource} has no tags to match required tags {required_tags}"
)
return False
for tag, required_value in required_tags.items():
actual_value = resource_tags.get(tag)
if required_value != actual_value:
logger.info(
f"Unmatched value {actual_value} for required tag {tag}: expected {required_value}"
)
else:
logger.warning(f"Resource {resource} has no `required_tags` attribute")
return False

return True

Expand Down
21 changes: 21 additions & 0 deletions sdk/python/feast/transformation/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,27 @@ def infer_features(self, *args, **kwargs) -> Any:
raise NotImplementedError


def udf_transformation_from_proto(
user_defined_function_proto: UserDefinedFunctionProto,
) -> Transformation:
"""Rebuild a UDF transformation from its proto, keeping its mode.

Shared by the ``from_proto`` of modes that need no extra state (SQL, Flink,
Spark).
"""
from feast.transformation.udf_rehydrate import resolve_udf

udf_string = user_defined_function_proto.body_text or ""
udf = resolve_udf(
udf_string=udf_string,
body=user_defined_function_proto.body or None,
preferred_name=user_defined_function_proto.name or None,
)
return Transformation(
mode=user_defined_function_proto.mode, udf=udf, udf_string=udf_string
)


def transformation(
mode: Union[TransformationMode, str],
name: Optional[str] = None,
Expand Down
11 changes: 10 additions & 1 deletion sdk/python/feast/transformation/flink_transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

from typing import Any, Callable, Optional, cast

from feast.transformation.base import Transformation
from feast.protos.feast.core.Transformation_pb2 import (
UserDefinedFunctionV2 as UserDefinedFunctionProto,
)
from feast.transformation.base import Transformation, udf_transformation_from_proto
from feast.transformation.mode import TransformationMode


Expand Down Expand Up @@ -76,3 +79,9 @@ def transform(self, *inputs: Any) -> Any:

def infer_features(self, *args, **kwargs) -> Any:
pass

@classmethod
def from_proto(
cls, user_defined_function_proto: UserDefinedFunctionProto
) -> Transformation:
return udf_transformation_from_proto(user_defined_function_proto)
11 changes: 10 additions & 1 deletion sdk/python/feast/transformation/spark_transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
import pyspark.sql

from feast.infra.compute_engines.spark.utils import get_or_create_new_spark_session
from feast.transformation.base import Transformation
from feast.protos.feast.core.Transformation_pb2 import (
UserDefinedFunctionV2 as UserDefinedFunctionProto,
)
from feast.transformation.base import Transformation, udf_transformation_from_proto
from feast.transformation.mode import TransformationMode


Expand Down Expand Up @@ -123,3 +126,9 @@ def _transform_spark_udf(self, *inputs: Any) -> pd.DataFrame:

def infer_features(self, *args, **kwargs) -> Any:
pass

@classmethod
def from_proto(
cls, user_defined_function_proto: UserDefinedFunctionProto
) -> Transformation:
return udf_transformation_from_proto(user_defined_function_proto)
Loading
Loading