Skip to content

Commit 1183a9a

Browse files
committed
add compute engine
Signed-off-by: HaoXuAI <sduxuhao@gmail.com>
1 parent 81677b2 commit 1183a9a

11 files changed

Lines changed: 607 additions & 0 deletions

File tree

‎sdk/python/feast/batch_feature_view.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ class BatchFeatureView(FeatureView):
5555
entity_columns: List[Field]
5656
features: List[Field]
5757
online: bool
58+
offline: bool
5859
description: str
5960
tags: Dict[str, str]
6061
owner: str
@@ -74,6 +75,7 @@ def __init__(
7475
ttl: Optional[timedelta] = None,
7576
tags: Optional[Dict[str, str]] = None,
7677
online: bool = True,
78+
offline: bool = True,
7779
description: str = "",
7880
owner: str = "",
7981
schema: Optional[List[Field]] = None,
@@ -110,6 +112,7 @@ def __init__(
110112
ttl=ttl,
111113
tags=tags,
112114
online=online,
115+
offline=offline,
113116
description=description,
114117
owner=owner,
115118
schema=schema,

‎sdk/python/feast/feature_view.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ class FeatureView(BaseFeatureView):
9393
entity_columns: List[Field]
9494
features: List[Field]
9595
online: bool
96+
offline: bool
9697
description: str
9798
tags: Dict[str, str]
9899
owner: str
@@ -107,6 +108,7 @@ def __init__(
107108
entities: Optional[List[Entity]] = None,
108109
ttl: Optional[timedelta] = timedelta(days=0),
109110
online: bool = True,
111+
offline: bool = False,
110112
description: str = "",
111113
tags: Optional[Dict[str, str]] = None,
112114
owner: str = "",
@@ -127,6 +129,8 @@ def __init__(
127129
can result in extremely computationally intensive queries.
128130
online (optional): A boolean indicating whether online retrieval is enabled for
129131
this feature view.
132+
offline (optional): A boolean indicating whether write to offline store is enabled for
133+
this feature view.
130134
description (optional): A human-readable description.
131135
tags (optional): A dictionary of key-value pairs to store arbitrary metadata.
132136
owner (optional): The owner of the feature view, typically the email of the
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from abc import ABC
2+
from dataclasses import dataclass
3+
from typing import Union, List
4+
5+
import pandas as pd
6+
import pyarrow as pa
7+
8+
from feast import RepoConfig, BatchFeatureView, StreamFeatureView
9+
from feast.infra.materialization.batch_materialization_engine import MaterializationTask, MaterializationJob
10+
from feast.infra.offline_stores.offline_store import OfflineStore
11+
from feast.infra.online_stores.online_store import OnlineStore
12+
from feast.infra.registry.registry import Registry
13+
14+
15+
@dataclass
16+
class HistoricalRetrievalTask:
17+
entity_df: Union[pd.DataFrame, str]
18+
feature_views: List[Union[BatchFeatureView, StreamFeatureView]]
19+
full_feature_names: bool
20+
registry: Registry
21+
config: RepoConfig
22+
23+
24+
class ComputeEngine(ABC):
25+
"""
26+
The interface that Feast uses to control the compute system that handles materialization and get_historical_features.
27+
"""
28+
29+
def __init__(
30+
self,
31+
*,
32+
registry: Registry,
33+
repo_config: RepoConfig,
34+
offline_store: OfflineStore,
35+
online_store: OnlineStore,
36+
**kwargs,
37+
):
38+
self.registry = registry
39+
self.repo_config = repo_config
40+
self.offline_store = offline_store
41+
self.online_store = online_store
42+
43+
def materialize(self,
44+
task: MaterializationTask) -> MaterializationJob:
45+
raise NotImplementedError
46+
47+
def get_historical_features(self,
48+
task: HistoricalRetrievalTask) -> pa.Table:
49+
raise NotImplementedError
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
from abc import ABC, abstractmethod
2+
from typing import Union
3+
4+
from feast import BatchFeatureView, StreamFeatureView
5+
from feast.infra.compute_engines.dag.plan import ExecutionPlan
6+
from feast.infra.compute_engines.base import HistoricalRetrievalTask
7+
from feast.infra.materialization.batch_materialization_engine import MaterializationTask
8+
9+
10+
class DAGBuilder(ABC):
11+
def __init__(self,
12+
feature_view: Union[BatchFeatureView, StreamFeatureView],
13+
task: Union[MaterializationTask, HistoricalRetrievalTask]
14+
):
15+
self.feature_view = feature_view
16+
self.task = task
17+
self.nodes = []
18+
19+
@abstractmethod
20+
def build_source_node(self):
21+
raise NotImplementedError
22+
23+
@abstractmethod
24+
def build_aggregation_node(self,
25+
input_node):
26+
raise NotImplementedError
27+
28+
@abstractmethod
29+
def build_join_node(self,
30+
input_node):
31+
raise NotImplementedError
32+
33+
@abstractmethod
34+
def build_transformation_node(self,
35+
input_node):
36+
raise NotImplementedError
37+
38+
@abstractmethod
39+
def build_output_nodes(self,
40+
input_node):
41+
raise NotImplementedError
42+
43+
@abstractmethod
44+
def build_validation_node(self,
45+
input_node):
46+
raise
47+
48+
def build(self) -> ExecutionPlan:
49+
last_node = self.build_source_node()
50+
51+
if getattr(self.feature_view.transformation, "requires_aggregation", False):
52+
last_node = self.build_aggregation_node(last_node)
53+
54+
if self._should_join():
55+
last_node = self.build_join_node(last_node)
56+
57+
if self.feature_view.transformation:
58+
last_node = self.build_transformation_node(last_node)
59+
60+
if getattr(self.feature_view, "enable_validation", False):
61+
last_node = self.build_validation_node(last_node)
62+
63+
self.build_output_nodes(last_node)
64+
return ExecutionPlan(self.nodes)
65+
66+
def _should_join(self):
67+
return (
68+
self.feature_view.compute_config.join_strategy == "engine"
69+
or self.task.config.compute_engine.get("point_in_time_join") == "engine"
70+
)
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from enum import Enum
2+
from dataclasses import dataclass, field
3+
import pandas as pd
4+
from typing import Union, List, Dict
5+
6+
from feast.entity import Entity
7+
from feast.infra.offline_stores.offline_store import OfflineStore
8+
from feast.infra.online_stores.online_store import OnlineStore
9+
from feast.repo_config import RepoConfig
10+
from feast.infra.compute_engines.dag.value import DAGValue
11+
12+
13+
class DAGFormat(str, Enum):
14+
SPARK = "spark"
15+
PANDAS = "pandas"
16+
ARROW = "arrow"
17+
18+
19+
@dataclass
20+
class ExecutionContext:
21+
project: str
22+
repo_config: RepoConfig
23+
offline_store: OfflineStore
24+
online_store: OnlineStore
25+
entity_defs: List[Entity]
26+
entity_df: Union[pd.DataFrame, None] = None
27+
node_outputs: Dict[str, DAGValue] = field(default_factory=dict)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from abc import ABC, abstractmethod
2+
from typing import List
3+
4+
from feast.infra.compute_engines.dag.model import ExecutionContext
5+
from infra.compute_engines.dag.value import DAGValue
6+
7+
8+
class DAGNode(ABC):
9+
name: str
10+
inputs: List["DAGNode"]
11+
outputs: List["DAGNode"]
12+
13+
def __init__(self,
14+
name: str):
15+
self.name = name
16+
self.inputs = []
17+
self.outputs = []
18+
19+
def add_input(self,
20+
node: "DAGNode"):
21+
if node in self.inputs:
22+
raise ValueError(f"Input node {node.name} already added to {self.name}")
23+
self.inputs.append(node)
24+
node.outputs.append(self)
25+
26+
@abstractmethod
27+
def execute(self,
28+
context: ExecutionContext) -> DAGValue:
29+
...
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from typing import List
2+
3+
from feast.infra.compute_engines.dag.node import DAGNode
4+
from feast.infra.compute_engines.dag.value import DAGValue
5+
from feast.infra.compute_engines.dag.model import ExecutionContext
6+
7+
8+
class ExecutionPlan:
9+
"""
10+
ExecutionPlan represents an ordered sequence of DAGNodes that together define
11+
a data processing pipeline for feature materialization or historical retrieval.
12+
13+
This plan is constructed as a topological sort of the DAG — meaning that each
14+
node appears after all its input dependencies. The plan is executed in order,
15+
caching intermediate results (`DAGValue`) so that each node can reuse outputs
16+
from upstream nodes without recomputation.
17+
18+
Key Concepts:
19+
- DAGNode: Each node performs a specific logical step (e.g., read, aggregate, join).
20+
- DAGValue: Output of a node, includes data (e.g., Spark DataFrame) and metadata.
21+
- ExecutionContext: Contains runtime information (config, registry, stores, entity_df).
22+
- node_outputs: A cache of intermediate results keyed by node name.
23+
24+
Usage:
25+
plan = ExecutionPlan(dag_nodes)
26+
result = plan.execute(context)
27+
28+
This design enables modular compute backends (e.g., Spark, Pandas, Arrow), where
29+
each node defines its execution logic independently while benefiting from shared
30+
execution orchestration, caching, and context injection.
31+
32+
Example:
33+
DAG:
34+
ReadNode -> AggregateNode -> JoinNode -> TransformNode -> WriteNode
35+
36+
Execution proceeds step by step, passing intermediate DAGValues through
37+
the plan while respecting node dependencies and formats.
38+
39+
This approach is inspired by execution DAGs in systems like Apache Spark,
40+
Apache Beam, and Dask — but specialized for Feast’s feature computation domain.
41+
"""
42+
def __init__(self, nodes: List[DAGNode]):
43+
self.nodes = nodes
44+
45+
def execute(self, context: ExecutionContext) -> DAGValue:
46+
node_outputs: dict[str, DAGValue] = {}
47+
48+
for node in self.nodes:
49+
# Gather input values
50+
for input_node in node.inputs:
51+
if input_node.name not in node_outputs:
52+
node_outputs[input_node.name] = input_node.execute(context)
53+
54+
# Execute this node
55+
output = node.execute(context)
56+
node_outputs[node.name] = output
57+
58+
# Inject into context for downstream access
59+
context.node_outputs = node_outputs
60+
61+
# Return output of final node
62+
return node_outputs[self.nodes[-1].name]
63+
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import Any, Optional
2+
3+
from feast.infra.compute_engines.dag.model import DAGFormat
4+
5+
6+
class DAGValue:
7+
def __init__(self,
8+
data: Any,
9+
format: DAGFormat,
10+
metadata: Optional[dict] = None):
11+
self.data = data
12+
self.format = format
13+
self.metadata = metadata or {}
14+
15+
def assert_format(self,
16+
expected: DAGFormat):
17+
if self.format != expected:
18+
raise ValueError(f"Expected format {expected}, but got {self.format}")
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import pyarrow as pa
2+
from feast.infra.compute_engines.base import ComputeEngine, HistoricalRetrievalTask
3+
from feast.infra.compute_engines.spark.spark_dag_builder import SparkDAGBuilder
4+
from feast.infra.materialization.batch_materialization_engine import MaterializationTask, MaterializationJob, \
5+
MaterializationJobStatus
6+
from feast.infra.materialization.contrib.spark.spark_materialization_engine import SparkMaterializationJob
7+
from feast.infra.compute_engines.dag.model import ExecutionContext
8+
9+
10+
class SparkComputeEngine(ComputeEngine):
11+
def materialize(self, task: MaterializationTask) -> MaterializationJob:
12+
job_id = f"{task.feature_view.name}-{task.start_time}-{task.end_time}"
13+
14+
try:
15+
# ✅ 1. Build typed execution context
16+
entities = []
17+
for entity_name in task.feature_view.entities:
18+
entities.append(self.registry.get_entity(entity_name, task.project))
19+
20+
context = ExecutionContext(
21+
project=task.project,
22+
repo_config=self.repo_config,
23+
offline_store=self.offline_store,
24+
online_store=self.online_store,
25+
entity_defs=entities
26+
)
27+
28+
# ✅ 2. Construct DAG and run it
29+
builder = SparkDAGBuilder(
30+
feature_view=task.feature_view,
31+
task=task,
32+
)
33+
plan = builder.build()
34+
plan.execute(context)
35+
36+
# ✅ 3. Report success
37+
return SparkMaterializationJob(
38+
job_id=job_id,
39+
status=MaterializationJobStatus.SUCCEEDED
40+
)
41+
42+
except Exception as e:
43+
# 🛑 Handle failure
44+
return SparkMaterializationJob(
45+
job_id=job_id,
46+
status=MaterializationJobStatus.ERROR,
47+
error=e
48+
)
49+
50+
def get_historical_features(self, task: HistoricalRetrievalTask) -> pa.Table:
51+
# ✅ 1. Validate input
52+
assert len(task.feature_views) == 1, "Multi-view support not yet implemented"
53+
feature_view = task.feature_views[0]
54+
55+
if isinstance(task.entity_df, str):
56+
raise NotImplementedError("SQL-based entity_df is not yet supported in DAG")
57+
58+
# ✅ 2. Build typed execution context
59+
entity_defs = [
60+
task.registry.get_entity(name, task.config.project)
61+
for name in feature_view.entities
62+
]
63+
64+
context = ExecutionContext(
65+
project=task.config.project,
66+
repo_config=task.config,
67+
offline_store=self.offline_store,
68+
online_store=self.online_store,
69+
entity_defs=entity_defs,
70+
entity_df=task.entity_df,
71+
)
72+
73+
# ✅ 3. Construct and execute DAG
74+
builder = SparkDAGBuilder(feature_view=feature_view, task=task)
75+
plan = builder.build()
76+
77+
result = plan.execute(context=context)
78+
spark_df = result.data # should be a Spark DataFrame
79+
80+
# ✅ 4. Return as Arrow
81+
return spark_df.toPandas().to_arrow()

0 commit comments

Comments
 (0)