From 4748ee071f25e97c27a2147dbd512907099f54e3 Mon Sep 17 00:00:00 2001 From: HaoXuAI Date: Sat, 17 Oct 2026 00:10:59 -0700 Subject: [PATCH 1/5] feat: Add DAG change envelopes Signed-off-by: HaoXuAI --- .../feast/infra/compute_engines/dag/change.py | 199 ++++++++++++++++++ .../infra/compute_engines/dag/test_change.py | 108 ++++++++++ 2 files changed, 307 insertions(+) create mode 100644 sdk/python/feast/infra/compute_engines/dag/change.py create mode 100644 sdk/python/tests/unit/infra/compute_engines/dag/test_change.py diff --git a/sdk/python/feast/infra/compute_engines/dag/change.py b/sdk/python/feast/infra/compute_engines/dag/change.py new file mode 100644 index 00000000000..a3cf84659ff --- /dev/null +++ b/sdk/python/feast/infra/compute_engines/dag/change.py @@ -0,0 +1,199 @@ +"""Engine-neutral row change envelopes and keyed in-memory state.""" + +from __future__ import annotations + +import copy +import math +from dataclasses import dataclass +from enum import Enum +from types import MappingProxyType +from typing import Any, Iterable, Mapping, Optional + + +class ChangeOperation(str, Enum): + INSERT = "insert" + UPDATE = "update" + DELETE = "delete" + + +@dataclass(frozen=True) +class ChangeRecord: + operation: ChangeOperation + before: Optional[Mapping[str, Any]] = None + after: Optional[Mapping[str, Any]] = None + + def __post_init__(self) -> None: + if self.operation is ChangeOperation.INSERT and ( + self.after is None or self.before is not None + ): + raise ValueError("INSERT requires after and forbids before") + if self.operation is ChangeOperation.UPDATE and ( + self.before is None or self.after is None + ): + raise ValueError("UPDATE requires before and after") + if self.operation is ChangeOperation.DELETE and ( + self.before is None or self.after is not None + ): + raise ValueError("DELETE requires before and forbids after") + if self.before is not None: + object.__setattr__( + self, "before", MappingProxyType(copy.deepcopy(dict(self.before))) + ) + if self.after is not None: + object.__setattr__( + self, "after", MappingProxyType(copy.deepcopy(dict(self.after))) + ) + + @classmethod + def insert(cls, after: Mapping[str, Any]) -> ChangeRecord: + return cls(ChangeOperation.INSERT, after=after) + + @classmethod + def update( + cls, before: Mapping[str, Any], after: Mapping[str, Any] + ) -> ChangeRecord: + return cls(ChangeOperation.UPDATE, before=before, after=after) + + @classmethod + def delete(cls, before: Mapping[str, Any]) -> ChangeRecord: + return cls(ChangeOperation.DELETE, before=before) + + +@dataclass(frozen=True) +class ChangeSet: + source: str + records: tuple[ChangeRecord, ...] = () + + def __post_init__(self) -> None: + object.__setattr__(self, "records", tuple(self.records)) + + +def _values_equal(left: Any, right: Any) -> bool: + if left is right: + return True + try: + if math.isnan(left) and math.isnan(right): + return True + except (TypeError, ValueError): + pass + result = left == right + return bool(result) if isinstance(result, (bool, int)) else False + + +def rows_equal(left: Mapping[str, Any], right: Mapping[str, Any]) -> bool: + return left.keys() == right.keys() and all( + _values_equal(left[column], right[column]) for column in left + ) + + +class KeyedRows: + """A unique-key row collection with atomic change application.""" + + def __init__( + self, + primary_keys: tuple[str, ...], + rows: Optional[dict[tuple[Any, ...], dict[str, Any]]] = None, + ) -> None: + if not primary_keys: + raise ValueError("KeyedRows requires at least one primary key column") + self.primary_keys = tuple(primary_keys) + self.rows = rows or {} + + @classmethod + def from_rows( + cls, + rows: Iterable[Mapping[str, Any]], + primary_keys: tuple[str, ...], + ) -> KeyedRows: + keyed = cls(primary_keys) + for input_row in rows: + row = copy.deepcopy(dict(input_row)) + key = keyed.key_for(row) + if key in keyed.rows: + raise ValueError(f"Duplicate primary key {key}") + keyed.rows[key] = row + return keyed + + def __eq__(self, other: object) -> bool: + if not isinstance(other, KeyedRows) or self.primary_keys != other.primary_keys: + return False + return self.rows.keys() == other.rows.keys() and all( + rows_equal(self.rows[key], other.rows[key]) for key in self.rows + ) + + def clone(self) -> KeyedRows: + return KeyedRows(self.primary_keys, copy.deepcopy(self.rows)) + + def key_for( + self, + row: Mapping[str, Any], + columns: Optional[tuple[str, ...]] = None, + ) -> tuple[Any, ...]: + key_columns = columns or self.primary_keys + for column in key_columns: + if column not in row: + raise ValueError(f"Missing primary key column '{column}'") + return tuple(row[column] for column in key_columns) + + def apply(self, changes: ChangeSet) -> None: + candidate = self.clone() + for record in changes.records: + candidate._apply_record(record) + self.rows = candidate.rows + + def _apply_record(self, record: ChangeRecord) -> None: + if record.operation is ChangeOperation.INSERT: + assert record.after is not None + new_key = self.key_for(record.after) + if new_key in self.rows: + raise ValueError(f"Primary key {new_key} already exists") + self.rows[new_key] = copy.deepcopy(dict(record.after)) + return + + assert record.before is not None + old_key = self.key_for(record.before) + current = self.rows.get(old_key) + if current is None: + raise ValueError(f"Cannot change unknown primary key {old_key}") + if not rows_equal(current, record.before): + raise ValueError( + f"Before row for primary key {old_key} does not match current state" + ) + if record.operation is ChangeOperation.DELETE: + del self.rows[old_key] + return + + assert record.after is not None + new_key = self.key_for(record.after) + if new_key != old_key and new_key in self.rows: + raise ValueError(f"Primary key {new_key} already exists") + del self.rows[old_key] + self.rows[new_key] = copy.deepcopy(dict(record.after)) + + def rows_for_columns( + self, + columns: tuple[str, ...], + keys: set[tuple[Any, ...]], + ) -> list[dict[str, Any]]: + return [ + copy.deepcopy(row) + for row in self.rows.values() + if self.key_for(row, columns) in keys + ] + + +def diff_keyed_rows(source: str, before: KeyedRows, after: KeyedRows) -> ChangeSet: + if before.primary_keys != after.primary_keys: + raise ValueError("Cannot diff keyed rows with different primary keys") + records: list[ChangeRecord] = [] + for key in sorted(before.rows.keys() | after.rows.keys(), key=repr): + old = before.rows.get(key) + new = after.rows.get(key) + if old is None: + assert new is not None + records.append(ChangeRecord.insert(new)) + elif new is None: + records.append(ChangeRecord.delete(old)) + elif not rows_equal(old, new): + records.append(ChangeRecord.update(old, new)) + return ChangeSet(source, tuple(records)) diff --git a/sdk/python/tests/unit/infra/compute_engines/dag/test_change.py b/sdk/python/tests/unit/infra/compute_engines/dag/test_change.py new file mode 100644 index 00000000000..467ce67d6ab --- /dev/null +++ b/sdk/python/tests/unit/infra/compute_engines/dag/test_change.py @@ -0,0 +1,108 @@ +import math + +import pytest + +from feast.infra.compute_engines.dag.change import ( + ChangeOperation, + ChangeRecord, + ChangeSet, + KeyedRows, + diff_keyed_rows, + rows_equal, +) + + +def test_change_record_requires_operation_specific_rows(): + with pytest.raises(ValueError, match="INSERT requires after"): + ChangeRecord(ChangeOperation.INSERT) + with pytest.raises(ValueError, match="UPDATE requires before and after"): + ChangeRecord(ChangeOperation.UPDATE, before={"id": 1}) + with pytest.raises(ValueError, match="DELETE requires before"): + ChangeRecord(ChangeOperation.DELETE) + + +def test_change_set_is_immutable_and_ordered(): + first = ChangeRecord.insert({"id": 1, "value": 10}) + second = ChangeRecord.delete({"id": 2, "value": 20}) + changes = ChangeSet(source="source", records=(first, second)) + assert changes.records == (first, second) + with pytest.raises(TypeError): + first.after["value"] = 99 # type: ignore[index] + + +def test_keyed_rows_rejects_empty_missing_and_duplicate_primary_keys(): + with pytest.raises(ValueError, match="at least one primary key"): + KeyedRows.from_rows([], ()) + with pytest.raises(ValueError, match="Missing primary key column 'id'"): + KeyedRows.from_rows([{"value": 10}], ("id",)) + with pytest.raises(ValueError, match="Duplicate primary key"): + KeyedRows.from_rows([{"id": 1}, {"id": 1}], ("id",)) + + +def test_keyed_rows_apply_key_changing_update_atomically(): + state = KeyedRows.from_rows([{"id": 1, "value": "old"}], ("id",)) + state.apply( + ChangeSet( + "source", + ( + ChangeRecord.update( + {"id": 1, "value": "old"}, {"id": 2, "value": "new"} + ), + ), + ) + ) + assert state.rows == {(2,): {"id": 2, "value": "new"}} + + +def test_keyed_rows_rolls_back_complete_change_set_on_invalid_second_record(): + state = KeyedRows.from_rows([{"id": 1, "value": 10}], ("id",)) + changes = ChangeSet( + "source", + ( + ChangeRecord.insert({"id": 2, "value": 20}), + ChangeRecord.delete({"id": 999, "value": 0}), + ), + ) + with pytest.raises(ValueError, match="unknown primary key"): + state.apply(changes) + assert state.rows == {(1,): {"id": 1, "value": 10}} + + +def test_keyed_rows_rejects_existing_insert_and_stale_update(): + state = KeyedRows.from_rows([{"id": 1, "value": 10}], ("id",)) + with pytest.raises(ValueError, match="already exists"): + state.apply(ChangeSet("source", (ChangeRecord.insert({"id": 1}),))) + with pytest.raises(ValueError, match="does not match current state"): + state.apply( + ChangeSet( + "source", + (ChangeRecord.update({"id": 1, "value": 9}, {"id": 1}),), + ) + ) + + +def test_rows_equal_treats_paired_nan_as_equal(): + assert rows_equal({"id": 1, "value": math.nan}, {"id": 1, "value": math.nan}) + assert not rows_equal({"id": 1, "value": math.nan}, {"id": 1, "value": 2}) + + +def test_rows_for_columns_selects_matching_rows(): + state = KeyedRows.from_rows( + [{"id": 1, "group": "a"}, {"id": 2, "group": "b"}], ("id",) + ) + assert state.rows_for_columns(("group",), {("b",)}) == [{"id": 2, "group": "b"}] + + +def test_diff_keyed_rows_classifies_insert_update_and_delete(): + before = KeyedRows.from_rows( + [{"id": 1, "value": "delete"}, {"id": 2, "value": "old"}], ("id",) + ) + after = KeyedRows.from_rows( + [{"id": 2, "value": "new"}, {"id": 3, "value": "insert"}], ("id",) + ) + changes = diff_keyed_rows("join", before, after) + assert [record.operation for record in changes.records] == [ + ChangeOperation.DELETE, + ChangeOperation.UPDATE, + ChangeOperation.INSERT, + ] From d8b7c6a192d324d59a4050dc2d60502a5af9f067 Mon Sep 17 00:00:00 2001 From: HaoXuAI Date: Sat, 17 Oct 2026 00:13:48 -0700 Subject: [PATCH 2/5] feat: Add incremental DAG execution Signed-off-by: HaoXuAI --- .../infra/compute_engines/dag/context.py | 4 +- .../feast/infra/compute_engines/dag/node.py | 26 ++- .../feast/infra/compute_engines/dag/plan.py | 78 +++++++- .../compute_engines/test_incremental_plan.py | 166 ++++++++++++++++++ 4 files changed, 271 insertions(+), 3 deletions(-) create mode 100644 sdk/python/tests/unit/infra/compute_engines/test_incremental_plan.py diff --git a/sdk/python/feast/infra/compute_engines/dag/context.py b/sdk/python/feast/infra/compute_engines/dag/context.py index 38b9a788872..9f498cbd61f 100644 --- a/sdk/python/feast/infra/compute_engines/dag/context.py +++ b/sdk/python/feast/infra/compute_engines/dag/context.py @@ -1,5 +1,5 @@ from dataclasses import dataclass, field -from typing import Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, Union import pandas as pd @@ -103,3 +103,5 @@ class ExecutionContext: entity_defs: List[Entity] entity_df: Union[pd.DataFrame, None] = None node_outputs: Dict[str, DAGValue] = field(default_factory=dict) + node_states: Dict[str, Any] = field(default_factory=dict) + incremental_initialized: bool = False diff --git a/sdk/python/feast/infra/compute_engines/dag/node.py b/sdk/python/feast/infra/compute_engines/dag/node.py index 9fb520e7c13..5fde084426d 100644 --- a/sdk/python/feast/infra/compute_engines/dag/node.py +++ b/sdk/python/feast/infra/compute_engines/dag/node.py @@ -1,6 +1,7 @@ from abc import ABC, abstractmethod -from typing import List, Optional +from typing import List, Mapping, Optional +from feast.infra.compute_engines.dag.change import ChangeSet, KeyedRows from feast.infra.compute_engines.dag.context import ExecutionContext from feast.infra.compute_engines.dag.value import DAGValue @@ -48,3 +49,26 @@ def get_single_input_value(self, context: ExecutionContext) -> DAGValue: @abstractmethod def execute(self, context: ExecutionContext) -> DAGValue: ... + + def initialize_incremental( + self, context: ExecutionContext, primary_keys: tuple[str, ...] + ) -> None: + value = context.node_outputs[self.name] + table = getattr(value, "data", None) + if table is None or not hasattr(table, "to_pylist"): + raise TypeError( + f"DAGNode '{self.name}' requires an Arrow-like batch output " + "to initialize incremental state" + ) + context.node_states[self.name] = KeyedRows.from_rows( + table.to_pylist(), primary_keys + ) + + def execute_incremental( + self, + context: ExecutionContext, + input_changes: Mapping[str, ChangeSet], + ) -> ChangeSet: + raise NotImplementedError( + f"DAGNode '{self.name}' does not support incremental execution" + ) diff --git a/sdk/python/feast/infra/compute_engines/dag/plan.py b/sdk/python/feast/infra/compute_engines/dag/plan.py index 31db551e635..a32a40cd0d7 100644 --- a/sdk/python/feast/infra/compute_engines/dag/plan.py +++ b/sdk/python/feast/infra/compute_engines/dag/plan.py @@ -1,5 +1,7 @@ -from typing import List +import copy +from typing import List, Mapping +from feast.infra.compute_engines.dag.change import ChangeSet, KeyedRows from feast.infra.compute_engines.dag.context import ExecutionContext from feast.infra.compute_engines.dag.node import DAGNode from feast.infra.compute_engines.dag.value import DAGValue @@ -53,6 +55,80 @@ def execute(self, context: ExecutionContext) -> DAGValue: return context.node_outputs[self.nodes[-1].name] + def initialize_incremental( + self, + context: ExecutionContext, + primary_keys: Mapping[str, tuple[str, ...]], + ) -> DAGValue: + context.node_outputs = {} + context.node_states = {} + context.incremental_initialized = False + for node in self.nodes: + if node.name not in primary_keys: + raise ValueError(f"Missing primary keys for node '{node.name}'") + output = node.execute(context) + context.node_outputs[node.name] = output + node.initialize_incremental(context, primary_keys[node.name]) + context.incremental_initialized = True + return context.node_outputs[self.nodes[-1].name] + + def execute_incremental( + self, + context: ExecutionContext, + source_changes: Mapping[str, ChangeSet], + ) -> ChangeSet: + self._validate_incremental_request(context, source_changes) + snapshot = copy.deepcopy(context.node_states) + emitted = dict(source_changes) + try: + for node in self.nodes: + if node.name in source_changes: + context.node_states[node.name].apply(source_changes[node.name]) + continue + input_changes = { + input_node.name: emitted[input_node.name] + for input_node in node.inputs + if input_node.name in emitted and emitted[input_node.name].records + } + if input_changes: + emitted[node.name] = node.execute_incremental( + context, input_changes + ) + return emitted.get(self.nodes[-1].name, ChangeSet(self.nodes[-1].name)) + except Exception: + context.node_states = snapshot + raise + + def incremental_result(self, context: ExecutionContext) -> KeyedRows: + if not context.incremental_initialized: + raise RuntimeError("Incremental plan is not initialized") + state = context.node_states[self.nodes[-1].name] + if not isinstance(state, KeyedRows): + output = getattr(state, "output", None) + if isinstance(output, KeyedRows): + return output + raise TypeError("Terminal node state is not keyed row state") + return state + + def _validate_incremental_request( + self, + context: ExecutionContext, + source_changes: Mapping[str, ChangeSet], + ) -> None: + if not context.incremental_initialized: + raise RuntimeError("Incremental plan is not initialized") + nodes = {node.name: node for node in self.nodes} + for node_name, changes in source_changes.items(): + if node_name not in nodes: + raise ValueError(f"Unknown source node '{node_name}'") + if nodes[node_name].inputs: + raise ValueError(f"Node '{node_name}' is not a source node") + if changes.source != node_name: + raise ValueError( + f"ChangeSet source '{changes.source}' does not match " + f"target node '{node_name}'" + ) + def to_sql(self, context: ExecutionContext) -> str: """ Generate SQL query for the entire execution plan. diff --git a/sdk/python/tests/unit/infra/compute_engines/test_incremental_plan.py b/sdk/python/tests/unit/infra/compute_engines/test_incremental_plan.py new file mode 100644 index 00000000000..900aad3b39f --- /dev/null +++ b/sdk/python/tests/unit/infra/compute_engines/test_incremental_plan.py @@ -0,0 +1,166 @@ +import copy +from unittest.mock import MagicMock + +import pyarrow as pa +import pytest + +from feast.infra.compute_engines.dag.change import ChangeRecord, ChangeSet, KeyedRows +from feast.infra.compute_engines.dag.context import ExecutionContext +from feast.infra.compute_engines.dag.node import DAGNode +from feast.infra.compute_engines.dag.plan import ExecutionPlan +from feast.infra.compute_engines.local.arrow_table_value import ArrowTableValue + + +class StaticNode(DAGNode): + def __init__(self, name, rows, inputs=None): + super().__init__(name, inputs) + self.rows = rows + + def execute(self, context): + return ArrowTableValue(pa.Table.from_pylist(self.rows)) + + +class RecordingNode(StaticNode): + def __init__(self, name, rows, inputs=None, fail=False): + super().__init__(name, rows, inputs) + self.received = [] + self.fail = fail + + def execute_incremental(self, context, input_changes): + self.received.append(input_changes) + if self.fail: + context.node_states[self.name].rows[(1,)]["value"] = "corrupt" + raise RuntimeError("downstream failure") + records = tuple( + record for changes in input_changes.values() for record in changes.records + ) + changes = ChangeSet(self.name, records) + context.node_states[self.name].apply(changes) + return changes + + +def create_context(): + return ExecutionContext( + project="test", + repo_config=MagicMock(), + offline_store=MagicMock(), + online_store=MagicMock(), + entity_defs=[], + ) + + +def test_initialize_incremental_seeds_keyed_state(): + source = StaticNode("source", [{"id": 1, "value": "a"}]) + plan = ExecutionPlan([source]) + context = create_context() + + result = plan.initialize_incremental(context, {"source": ("id",)}) + + assert result.data.to_pylist() == [{"id": 1, "value": "a"}] + assert context.incremental_initialized is True + assert context.node_states["source"].rows[(1,)]["value"] == "a" + + +def test_initialize_incremental_requires_primary_keys_for_every_node(): + plan = ExecutionPlan([StaticNode("source", [{"id": 1}])]) + with pytest.raises(ValueError, match="Missing primary keys for node 'source'"): + plan.initialize_incremental(create_context(), {}) + + +def test_execute_incremental_requires_initialization(): + plan = ExecutionPlan([StaticNode("source", [{"id": 1}])]) + with pytest.raises(RuntimeError, match="not initialized"): + plan.execute_incremental(create_context(), {}) + + +def test_execute_incremental_routes_changes_by_input_name_and_skips_other_branch(): + left = StaticNode("left", [{"id": 1, "value": "old"}]) + right = StaticNode("right", [{"id": 2, "value": "stable"}]) + sink = RecordingNode("sink", [{"id": 1, "value": "old"}], inputs=[left, right]) + plan = ExecutionPlan([left, right, sink]) + context = create_context() + plan.initialize_incremental( + context, {"left": ("id",), "right": ("id",), "sink": ("id",)} + ) + left_changes = ChangeSet( + "left", + (ChangeRecord.update({"id": 1, "value": "old"}, {"id": 1, "value": "new"}),), + ) + + result = plan.execute_incremental(context, {"left": left_changes}) + + assert set(sink.received[0]) == {"left"} + assert result.source == "sink" + assert context.node_states["right"].rows[(2,)]["value"] == "stable" + assert plan.incremental_result(context).rows[(1,)]["value"] == "new" + + +def test_execute_incremental_rejects_unknown_or_mismatched_source(): + source = StaticNode("source", [{"id": 1}]) + plan = ExecutionPlan([source]) + context = create_context() + plan.initialize_incremental(context, {"source": ("id",)}) + changes = ChangeSet("source", (ChangeRecord.insert({"id": 2}),)) + + with pytest.raises(ValueError, match="Unknown source node 'missing'"): + plan.execute_incremental(context, {"missing": changes}) + with pytest.raises(ValueError, match="does not match target node"): + plan.execute_incremental(context, {"source": ChangeSet("other")}) + + +def test_execute_incremental_rejects_non_source_target(): + source = StaticNode("source", [{"id": 1}]) + sink = RecordingNode("sink", [{"id": 1}], inputs=[source]) + plan = ExecutionPlan([source, sink]) + context = create_context() + plan.initialize_incremental(context, {"source": ("id",), "sink": ("id",)}) + + with pytest.raises(ValueError, match="not a source node"): + plan.execute_incremental(context, {"sink": ChangeSet("sink")}) + + +def test_execute_incremental_rolls_back_all_state_on_downstream_failure(): + source = StaticNode("source", [{"id": 1, "value": "old"}]) + sink = RecordingNode( + "sink", [{"id": 1, "value": "old"}], inputs=[source], fail=True + ) + plan = ExecutionPlan([source, sink]) + context = create_context() + plan.initialize_incremental(context, {"source": ("id",), "sink": ("id",)}) + before = copy.deepcopy(context.node_states) + changes = ChangeSet( + "source", + (ChangeRecord.update({"id": 1, "value": "old"}, {"id": 1, "value": "new"}),), + ) + + with pytest.raises(RuntimeError, match="downstream failure"): + plan.execute_incremental(context, {"source": changes}) + + assert context.node_states == before + + +def test_batch_only_node_rejects_incremental_changes(): + source = StaticNode("source", [{"id": 1}]) + sink = StaticNode("sink", [{"id": 1}], inputs=[source]) + plan = ExecutionPlan([source, sink]) + context = create_context() + plan.initialize_incremental(context, {"source": ("id",), "sink": ("id",)}) + + with pytest.raises(NotImplementedError, match="does not support incremental"): + plan.execute_incremental( + context, + {"source": ChangeSet("source", (ChangeRecord.insert({"id": 2}),))}, + ) + + +def test_incremental_result_requires_initialization(): + plan = ExecutionPlan([StaticNode("source", [{"id": 1}])]) + with pytest.raises(RuntimeError, match="not initialized"): + plan.incremental_result(create_context()) + + +def test_keyed_rows_type_is_used_for_initialized_state(): + plan = ExecutionPlan([StaticNode("source", [{"id": 1}])]) + context = create_context() + plan.initialize_incremental(context, {"source": ("id",)}) + assert isinstance(plan.incremental_result(context), KeyedRows) From 4c804eb7e1929a215842a9b69d3f5ba2778efcab Mon Sep 17 00:00:00 2001 From: HaoXuAI Date: Sat, 17 Oct 2026 00:17:33 -0700 Subject: [PATCH 3/5] feat: Maintain local joins incrementally Signed-off-by: HaoXuAI --- .../compute_engines/local/incremental_join.py | 142 ++++++++ .../infra/compute_engines/local/nodes.py | 50 ++- .../local/test_incremental_join.py | 328 ++++++++++++++++++ 3 files changed, 519 insertions(+), 1 deletion(-) create mode 100644 sdk/python/feast/infra/compute_engines/local/incremental_join.py create mode 100644 sdk/python/tests/unit/infra/compute_engines/local/test_incremental_join.py diff --git a/sdk/python/feast/infra/compute_engines/local/incremental_join.py b/sdk/python/feast/infra/compute_engines/local/incremental_join.py new file mode 100644 index 00000000000..682a09dd8dd --- /dev/null +++ b/sdk/python/feast/infra/compute_engines/local/incremental_join.py @@ -0,0 +1,142 @@ +"""In-memory incremental inner-join maintenance for the Local engine PoC.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping + +import pyarrow as pa + +from feast.infra.compute_engines.backends.base import DataFrameBackend +from feast.infra.compute_engines.dag.change import ( + ChangeSet, + KeyedRows, + diff_keyed_rows, +) + + +@dataclass +class IncrementalInnerJoinState: + left: KeyedRows + right: KeyedRows + output: KeyedRows + join_keys: tuple[str, ...] + + def clone(self) -> "IncrementalInnerJoinState": + return IncrementalInnerJoinState( + self.left.clone(), + self.right.clone(), + self.output.clone(), + self.join_keys, + ) + + +def _keyed_state(state: Any) -> KeyedRows: + if isinstance(state, KeyedRows): + return state + output = getattr(state, "output", None) + if isinstance(output, KeyedRows): + return output + raise TypeError("Incremental join input does not expose keyed row state") + + +def initialize_inner_join_state( + node_name: str, + input_names: tuple[str, str], + node_states: Mapping[str, Any], + output_rows: list[dict[str, Any]], + output_primary_keys: tuple[str, ...], + join_keys: tuple[str, ...], +) -> IncrementalInnerJoinState: + left = _keyed_state(node_states[input_names[0]]).clone() + right = _keyed_state(node_states[input_names[1]]).clone() + for side_name, side in (("left", left), ("right", right)): + for row in side.rows.values(): + for column in join_keys: + if column not in row: + raise ValueError( + f"Incremental join '{node_name}' {side_name} input " + f"is missing join key '{column}'" + ) + return IncrementalInnerJoinState( + left=left, + right=right, + output=KeyedRows.from_rows(output_rows, output_primary_keys), + join_keys=join_keys, + ) + + +def _affected_join_keys( + changes: ChangeSet, join_keys: tuple[str, ...], node_name: str +) -> set[tuple[Any, ...]]: + affected: set[tuple[Any, ...]] = set() + for record in changes.records: + for row in (record.before, record.after): + if row is None: + continue + missing = [column for column in join_keys if column not in row] + if missing: + raise ValueError( + f"Incremental join '{node_name}' change is missing join key " + f"'{missing[0]}'" + ) + affected.add(tuple(row[column] for column in join_keys)) + return affected + + +def _join_rows( + left_rows: list[dict[str, Any]], + right_rows: list[dict[str, Any]], + join_keys: tuple[str, ...], + backend: DataFrameBackend, +) -> list[dict[str, Any]]: + if not left_rows or not right_rows: + return [] + left = backend.from_arrow(pa.Table.from_pylist(left_rows)) + right = backend.from_arrow(pa.Table.from_pylist(right_rows)) + joined = backend.join(left, right, on=list(join_keys), how="inner") + return backend.to_arrow(joined).to_pylist() + + +def execute_incremental_inner_join( + node_name: str, + input_names: tuple[str, str], + state: IncrementalInnerJoinState, + input_changes: Mapping[str, ChangeSet], + backend: DataFrameBackend, +) -> tuple[IncrementalInnerJoinState, ChangeSet]: + candidate = state.clone() + affected: set[tuple[Any, ...]] = set() + + for input_name, changes in input_changes.items(): + if input_name == input_names[0]: + side = candidate.left + elif input_name == input_names[1]: + side = candidate.right + else: + raise ValueError( + f"Incremental join '{node_name}' received unknown input '{input_name}'" + ) + affected.update(_affected_join_keys(changes, state.join_keys, node_name)) + side.apply(changes) + + old_rows = candidate.output.rows_for_columns(state.join_keys, affected) + old_partition = KeyedRows.from_rows(old_rows, candidate.output.primary_keys) + left_rows = candidate.left.rows_for_columns(state.join_keys, affected) + right_rows = candidate.right.rows_for_columns(state.join_keys, affected) + new_rows = _join_rows(left_rows, right_rows, state.join_keys, backend) + new_partition = KeyedRows.from_rows(new_rows, candidate.output.primary_keys) + + retained = { + key: row + for key, row in candidate.output.rows.items() + if candidate.output.key_for(row, state.join_keys) not in affected + } + for key, row in new_partition.rows.items(): + if key in retained: + raise ValueError( + f"Incremental join '{node_name}' produced duplicate output key {key}" + ) + retained[key] = row + candidate.output.rows = retained + return candidate, diff_keyed_rows(node_name, old_partition, new_partition) diff --git a/sdk/python/feast/infra/compute_engines/local/nodes.py b/sdk/python/feast/infra/compute_engines/local/nodes.py index 71e78a8380e..ac373478108 100644 --- a/sdk/python/feast/infra/compute_engines/local/nodes.py +++ b/sdk/python/feast/infra/compute_engines/local/nodes.py @@ -1,17 +1,23 @@ import json import logging from datetime import datetime, timedelta -from typing import List, Optional, Set, Union +from typing import List, Mapping, Optional, Set, Union import pyarrow as pa from feast import BatchFeatureView, StreamFeatureView from feast.data_source import DataSource from feast.infra.compute_engines.backends.base import DataFrameBackend +from feast.infra.compute_engines.dag.change import ChangeSet from feast.infra.compute_engines.dag.context import ColumnInfo, ExecutionContext from feast.infra.compute_engines.dag.model import DAGFormat from feast.infra.compute_engines.dag.node import DAGNode from feast.infra.compute_engines.local.arrow_table_value import ArrowTableValue +from feast.infra.compute_engines.local.incremental_join import ( + IncrementalInnerJoinState, + execute_incremental_inner_join, + initialize_inner_join_state, +) from feast.infra.compute_engines.local.local_node import LocalNode from feast.infra.compute_engines.utils import ( ENTITY_TS_ALIAS, @@ -113,6 +119,48 @@ def execute(self, context: ExecutionContext) -> ArrowTableValue: result = self.backend.to_arrow(joined_df) return ArrowTableValue(result) + def initialize_incremental( + self, context: ExecutionContext, primary_keys: tuple[str, ...] + ) -> None: + if len(self.inputs) != 2: + raise ValueError( + f"Incremental join '{self.name}' requires exactly two inputs" + ) + if self.how != "inner": + raise ValueError( + f"Incremental join '{self.name}' only supports inner joins" + ) + output = context.node_outputs[self.name] + output.assert_format(DAGFormat.ARROW) + input_names = (self.inputs[0].name, self.inputs[1].name) + context.node_states[self.name] = initialize_inner_join_state( + node_name=self.name, + input_names=input_names, + node_states=context.node_states, + output_rows=output.data.to_pylist(), + output_primary_keys=primary_keys, + join_keys=tuple(self.column_info.join_keys_columns), + ) + + def execute_incremental( + self, + context: ExecutionContext, + input_changes: Mapping[str, ChangeSet], + ) -> ChangeSet: + state = context.node_states[self.name] + if not isinstance(state, IncrementalInnerJoinState): + raise TypeError(f"Incremental join '{self.name}' is not initialized") + input_names = (self.inputs[0].name, self.inputs[1].name) + updated, output_changes = execute_incremental_inner_join( + node_name=self.name, + input_names=input_names, + state=state, + input_changes=input_changes, + backend=self.backend, + ) + context.node_states[self.name] = updated + return output_changes + class LocalFilterNode(LocalNode): def __init__( diff --git a/sdk/python/tests/unit/infra/compute_engines/local/test_incremental_join.py b/sdk/python/tests/unit/infra/compute_engines/local/test_incremental_join.py new file mode 100644 index 00000000000..b3b68a9fdd7 --- /dev/null +++ b/sdk/python/tests/unit/infra/compute_engines/local/test_incremental_join.py @@ -0,0 +1,328 @@ +from unittest.mock import MagicMock + +import pandas as pd +import pyarrow as pa +import pytest + +from feast.infra.compute_engines.backends.pandas_backend import PandasBackend +from feast.infra.compute_engines.dag.change import ( + ChangeOperation, + ChangeRecord, + ChangeSet, +) +from feast.infra.compute_engines.dag.context import ColumnInfo, ExecutionContext +from feast.infra.compute_engines.dag.node import DAGNode +from feast.infra.compute_engines.dag.plan import ExecutionPlan +from feast.infra.compute_engines.local.arrow_table_value import ArrowTableValue +from feast.infra.compute_engines.local.nodes import LocalJoinNode + + +class TableNode(DAGNode): + def __init__(self, name, rows): + super().__init__(name) + self.rows = rows + + def execute(self, context): + return ArrowTableValue(pa.Table.from_pylist(self.rows)) + + +def context(): + return ExecutionContext( + project="test", + repo_config=MagicMock(), + offline_store=MagicMock(), + online_store=MagicMock(), + entity_defs=[], + entity_df=None, + ) + + +def normalized(rows, columns): + if not rows: + return pd.DataFrame(columns=columns).sort_values(columns).reset_index(drop=True) + return ( + pd.DataFrame(rows) + .sort_values(columns) + .reset_index(drop=True) + .sort_index(axis=1) + ) + + +def single_join_plan(how="inner"): + left_rows = [ + {"left_id": 1, "entity_id": 10, "left_value": "a"}, + {"left_id": 2, "entity_id": 99, "left_value": "unmatched"}, + ] + right_rows = [ + {"right_id": 100, "entity_id": 10, "right_value": "x"}, + {"right_id": 200, "entity_id": 20, "right_value": "y"}, + ] + left = TableNode("left", left_rows) + right = TableNode("right", right_rows) + join = LocalJoinNode( + "join", + ColumnInfo(["entity_id"], [], "event_timestamp", None), + PandasBackend(), + inputs=[left, right], + how=how, + ) + plan = ExecutionPlan([left, right, join]) + execution_context = context() + plan.initialize_incremental( + execution_context, + { + "left": ("left_id",), + "right": ("right_id",), + "join": ("left_id", "right_id"), + }, + ) + return plan, execution_context + + +def assert_single_join_matches_batch(plan, execution_context): + left = list(execution_context.node_states["left"].rows.values()) + right = list(execution_context.node_states["right"].rows.values()) + expected = pd.DataFrame(left).merge( + pd.DataFrame(right), on="entity_id", how="inner" + ) + actual = list(plan.incremental_result(execution_context).rows.values()) + pd.testing.assert_frame_equal( + normalized(actual, ["left_id", "right_id"]), + normalized(expected.to_dict("records"), ["left_id", "right_id"]), + check_dtype=False, + ) + + +@pytest.mark.parametrize( + "source,record,operation", + [ + ( + "left", + ChangeRecord.insert( + {"left_id": 3, "entity_id": 20, "left_value": "inserted"} + ), + ChangeOperation.INSERT, + ), + ( + "right", + ChangeRecord.insert( + {"right_id": 300, "entity_id": 99, "right_value": "inserted"} + ), + ChangeOperation.INSERT, + ), + ( + "left", + ChangeRecord.update( + {"left_id": 1, "entity_id": 10, "left_value": "a"}, + {"left_id": 1, "entity_id": 10, "left_value": "updated"}, + ), + ChangeOperation.UPDATE, + ), + ( + "right", + ChangeRecord.update( + {"right_id": 100, "entity_id": 10, "right_value": "x"}, + {"right_id": 100, "entity_id": 10, "right_value": "updated"}, + ), + ChangeOperation.UPDATE, + ), + ( + "left", + ChangeRecord.delete({"left_id": 1, "entity_id": 10, "left_value": "a"}), + ChangeOperation.DELETE, + ), + ( + "right", + ChangeRecord.delete({"right_id": 100, "entity_id": 10, "right_value": "x"}), + ChangeOperation.DELETE, + ), + ], +) +def test_left_and_right_changes_match_batch(source, record, operation): + plan, execution_context = single_join_plan() + result = plan.execute_incremental( + execution_context, {source: ChangeSet(source, (record,))} + ) + assert [change.operation for change in result.records] == [operation] + assert_single_join_matches_batch(plan, execution_context) + + +def test_key_changing_update_retracts_old_match_and_inserts_new_match(): + plan, execution_context = single_join_plan() + result = plan.execute_incremental( + execution_context, + { + "left": ChangeSet( + "left", + ( + ChangeRecord.update( + {"left_id": 1, "entity_id": 10, "left_value": "a"}, + {"left_id": 1, "entity_id": 20, "left_value": "a"}, + ), + ), + ) + }, + ) + assert {record.operation for record in result.records} == { + ChangeOperation.DELETE, + ChangeOperation.INSERT, + } + assert_single_join_matches_batch(plan, execution_context) + + +def test_unmatched_update_becomes_matched(): + plan, execution_context = single_join_plan() + result = plan.execute_incremental( + execution_context, + { + "left": ChangeSet( + "left", + ( + ChangeRecord.update( + {"left_id": 2, "entity_id": 99, "left_value": "unmatched"}, + {"left_id": 2, "entity_id": 20, "left_value": "matched"}, + ), + ), + ) + }, + ) + assert [record.operation for record in result.records] == [ChangeOperation.INSERT] + assert_single_join_matches_batch(plan, execution_context) + + +def test_mixed_micro_batch_matches_batch(): + plan, execution_context = single_join_plan() + plan.execute_incremental( + execution_context, + { + "left": ChangeSet( + "left", + ( + ChangeRecord.update( + {"left_id": 1, "entity_id": 10, "left_value": "a"}, + {"left_id": 1, "entity_id": 10, "left_value": "new"}, + ), + ChangeRecord.insert( + {"left_id": 3, "entity_id": 20, "left_value": "three"} + ), + ), + ), + "right": ChangeSet( + "right", + ( + ChangeRecord.update( + {"right_id": 200, "entity_id": 20, "right_value": "y"}, + {"right_id": 200, "entity_id": 20, "right_value": "new-y"}, + ), + ), + ), + }, + ) + assert_single_join_matches_batch(plan, execution_context) + + +def chained_plan(): + customers = TableNode( + "customers", + [{"customer_id": 1, "region_id": 7, "customer_name": "Ada"}], + ) + orders = TableNode("orders", [{"order_id": 10, "customer_id": 1, "amount": 5}]) + regions = TableNode("regions", [{"region_id": 7, "region_name": "west"}]) + customer_orders = LocalJoinNode( + "customer_orders", + ColumnInfo(["customer_id"], [], "event_timestamp", None), + PandasBackend(), + inputs=[customers, orders], + ) + enriched = LocalJoinNode( + "enriched", + ColumnInfo(["region_id"], [], "event_timestamp", None), + PandasBackend(), + inputs=[customer_orders, regions], + ) + plan = ExecutionPlan([customers, orders, customer_orders, regions, enriched]) + execution_context = context() + plan.initialize_incremental( + execution_context, + { + "customers": ("customer_id",), + "orders": ("order_id",), + "customer_orders": ("order_id",), + "regions": ("region_id",), + "enriched": ("order_id",), + }, + ) + return plan, execution_context + + +def assert_chain_matches_batch(plan, execution_context): + def rows(name): + return list(execution_context.node_states[name].rows.values()) + + expected = pd.DataFrame(rows("customers")).merge( + pd.DataFrame(rows("orders")), on="customer_id" + ) + expected = expected.merge(pd.DataFrame(rows("regions")), on="region_id") + actual = list(plan.incremental_result(execution_context).rows.values()) + pd.testing.assert_frame_equal( + normalized(actual, ["order_id"]), + normalized(expected.to_dict("records"), ["order_id"]), + check_dtype=False, + ) + + +@pytest.mark.parametrize( + "source,record", + [ + ( + "customers", + ChangeRecord.update( + {"customer_id": 1, "region_id": 7, "customer_name": "Ada"}, + {"customer_id": 1, "region_id": 7, "customer_name": "Grace"}, + ), + ), + ( + "orders", + ChangeRecord.update( + {"order_id": 10, "customer_id": 1, "amount": 5}, + {"order_id": 10, "customer_id": 1, "amount": 8}, + ), + ), + ( + "regions", + ChangeRecord.update( + {"region_id": 7, "region_name": "west"}, + {"region_id": 7, "region_name": "coast"}, + ), + ), + ], +) +def test_chained_join_propagates_changes_from_every_source(source, record): + plan, execution_context = chained_plan() + result = plan.execute_incremental( + execution_context, {source: ChangeSet(source, (record,))} + ) + assert result.source == "enriched" + assert [item.operation for item in result.records] == [ChangeOperation.UPDATE] + assert_chain_matches_batch(plan, execution_context) + + +def test_rejects_unsupported_join_mode(): + with pytest.raises(ValueError, match="only supports inner joins"): + single_join_plan(how="left") + + +def test_rejects_missing_join_key_without_mutating_state(): + plan, execution_context = single_join_plan() + before = execution_context.node_states["join"].output.clone() + with pytest.raises(ValueError, match="entity_id"): + plan.execute_incremental( + execution_context, + { + "left": ChangeSet( + "left", + (ChangeRecord.insert({"left_id": 3, "left_value": "missing-key"}),), + ) + }, + ) + assert execution_context.node_states["join"].output == before From 72d51ee3b6740ec202351a86de014d0e988f5e1f Mon Sep 17 00:00:00 2001 From: HaoXuAI Date: Sat, 17 Oct 2026 00:18:54 -0700 Subject: [PATCH 4/5] docs: Draft incremental feature DAG RFC Signed-off-by: HaoXuAI --- .../compute-engine/incremental-dag-poc.md | 138 +++++++++++++ .../change-aware-incremental-feature-dag.md | 187 ++++++++++++++++++ 2 files changed, 325 insertions(+) create mode 100644 docs/reference/compute-engine/incremental-dag-poc.md create mode 100644 docs/rfc/change-aware-incremental-feature-dag.md diff --git a/docs/reference/compute-engine/incremental-dag-poc.md b/docs/reference/compute-engine/incremental-dag-poc.md new file mode 100644 index 00000000000..010e9f49be8 --- /dev/null +++ b/docs/reference/compute-engine/incremental-dag-poc.md @@ -0,0 +1,138 @@ +# Incremental DAG Join Proof of Concept + +This proof of concept adds change-aware inner joins to Feast's Local Compute +Engine. It is an experiment for evaluating DAG contracts, not a supported +FeatureView API or a production CDC pipeline. + +## What is implemented + +The engine-neutral DAG layer defines: + +- `ChangeOperation`: INSERT, UPDATE, or DELETE. +- `ChangeRecord`: immutable before/after row data validated for its operation. +- `ChangeSet`: an ordered micro-batch addressed to a named node. +- `KeyedRows`: unique-primary-key state with atomic change application. +- `ExecutionPlan.initialize_incremental()`: seeds persistent state from one + normal batch execution. +- `ExecutionPlan.execute_incremental()`: validates source changes, routes + emitted deltas in topological order, and rolls back all node state on error. +- `ExecutionPlan.incremental_result()`: returns the terminal keyed result. + +`LocalJoinNode` implements the incremental node contract for two-input inner +equi-joins. Existing `ExecutionPlan.execute()` and Local batch joins are +unchanged. + +## Lifecycle + +A caller constructs a physical plan, declares one primary-key tuple for every +node, and seeds it: + +```python +plan.initialize_incremental( + context, + primary_keys={ + "customers": ("customer_id",), + "orders": ("order_id",), + "customer_orders": ("order_id",), + }, +) +``` + +The caller then submits changes to source nodes: + +```python +changes = ChangeSet( + source="customers", + records=( + ChangeRecord.update( + before={"customer_id": 1, "name": "Ada"}, + after={"customer_id": 1, "name": "Grace"}, + ), + ), +) +output_changes = plan.execute_incremental(context, {"customers": changes}) +current_rows = plan.incremental_result(context) +``` + +Initialization is explicit. Incremental execution before initialization, +changes addressed to a non-source or unknown node, and mismatched +`ChangeSet.source` values fail without modifying persistent state. + +## Join algorithm + +For each micro-batch, the join: + +1. validates changes against cloned input state; +2. collects join keys from every before and after row; +3. snapshots old output rows for those keys; +4. applies the changes to the relevant side or sides; +5. joins only current rows carrying affected keys; +6. replaces only that output partition; +7. diffs old and new rows by the declared output primary key. + +A surviving output identity with changed values emits UPDATE. A removed +identity emits DELETE, and a new identity emits INSERT. A key-changing update +can therefore emit a DELETE and INSERT together. The emitted `ChangeSet` is +addressed to the join node, so a downstream incremental join consumes it in the +same way as a source change. + +## Chained joins + +A plan can route deltas through more than one join: + +```text +customers ----+ + customer_orders ----+ +orders -------+ enriched_orders +regions ---------------------------+ +``` + +An update to `customers` changes `customer_orders`; its output delta becomes +the left input delta for `enriched_orders`. An update to `regions` reaches +only the final join. Nodes and keys on unaffected branches are not recomputed. + +## Supported boundary + +The PoC supports: + +- Local Compute Engine physical plans; +- unique declared primary keys; +- two-input inner equi-joins; +- INSERT, UPDATE, and DELETE on either side; +- updates that change primary or join keys; +- multiple changes in one atomic micro-batch; +- downstream propagation through chained joins. + +It intentionally excludes outer or temporal joins, duplicate-key bag +semantics, incremental aggregations and arbitrary transformations, durable +state, checkpointing, source offsets, schema evolution, distributed engines, +and sink writes. + +## Architecture gaps + +Production support requires decisions and implementation for: + +1. durable row identity distinct from entity join keys; +2. ordered CDC envelopes, source partitions, and offsets; +3. checkpoint, replay, transaction, and exactly-once boundaries; +4. durable state outside job-local `ExecutionContext`; +5. planner capability metadata and batch/incremental boundaries; +6. duplicate-key multiplicity and retractions; +7. unmatched-row and time-index state for outer and temporal joins; +8. aggregation retractions or targeted recomputation; +9. UDF determinism and declared change semantics; +10. atomic sink upsert/delete APIs coordinated with checkpoints; +11. stable schema and collision rules across engines; +12. state sizing, compaction, metrics, backpressure, and recovery. + +## Relationship to tiling + +Feast tiling accelerates time-window aggregations by storing cumulative or +per-hop intermediate values and subtracting compatible cumulative tiles. +That technique is useful for invertible aggregate state, but it is not a +general row-change protocol: it does not identify inserted, updated, or deleted +source rows; route retractions through arbitrary DAG nodes; maintain join-side +indexes; or coordinate source offsets and sink commits. A production +incremental aggregation operator could reuse tiling intermediate +representations after Feast defines the broader state and checkpoint contract. + diff --git a/docs/rfc/change-aware-incremental-feature-dag.md b/docs/rfc/change-aware-incremental-feature-dag.md new file mode 100644 index 00000000000..e2fb16e41de --- /dev/null +++ b/docs/rfc/change-aware-incremental-feature-dag.md @@ -0,0 +1,187 @@ +# RFC: Change-aware Incremental Feature DAGs + +## Summary + +This RFC proposes an opt-in incremental execution model for Feast compute DAGs. +Sources deliver keyed changes, stateful operators emit downstream changes, and +checkpoint-aware sinks commit results with source progress. The Local +change-aware inner-join proof of concept validates row-change and propagation +semantics but does not define a stable public API. + +## Motivation + +Current compute plans process snapshots. Every node receives complete upstream +data and produces a complete output, even when only a few source keys changed. +Tiling optimizes a subset of windowed aggregation work, but Feast has no common +contract for row retractions, operator state, downstream deltas, or recovery. + +A shared model would let engines avoid full recomputation for materialization +and transformation DAGs while keeping results equivalent to a batch run. + +## Current Feast Constraints + +`FeatureResolver` creates a logical FeatureView graph, `FeatureBuilder` +creates engine-specific nodes, and `ExecutionPlan.execute()` walks a +topologically sorted physical plan. `ExecutionContext.node_outputs` is a +per-run cache. It is neither durable state nor a checkpoint. + +Sources expose range/snapshot reads rather than ordered CDC records. Operators +do not declare incremental capabilities. Online and offline stores do not share +an atomic upsert/delete-plus-checkpoint contract. + +## Proposed Concepts + +Introduce four engine-neutral concepts: + +1. **Row identity**: an explicit key for each operator output. +2. **Change envelope**: INSERT, UPDATE(before, after), and DELETE records plus + source partition, offset, schema version, and event metadata. +3. **Stateful operator contract**: initialize from a snapshot, apply a + micro-batch, emit changes, snapshot/restore state, and report capabilities. +4. **Checkpoint coordinator**: atomically binds source progress, operator state, + and sink commits. + +The PoC implements only in-memory row identity, `ChangeOperation`, +`ChangeSet`, `KeyedRows`, incremental plan routing, and Local inner joins. +Offset metadata, durable checkpoints, and sink coordination remain proposals. + +## Row Identity and Change Envelope + +FeatureView entity keys are join keys, not always unique row identities. +Production APIs should require or derive an operator primary key independently +from join keys. A planner must reject a graph when an operator cannot prove the +identity of its output. + +The portable change envelope should include: + +- operation and before/after payloads; +- source/node identifier; +- primary-key values; +- partition and monotonically comparable offset; +- event and ingestion time; +- schema fingerprint or version; +- transaction/batch identifier. + +Duplicate keys require bag or multiplicity semantics rather than the PoC's +unique-key map. The chosen model must specify whether two identical rows are +distinct and how a single deletion identifies its target. + +## Stateful Operator Contract + +An incremental node should declare supported operations, required indexes, +join/aggregation restrictions, state schema, and whether it can consume updates +directly or needs normalized delete-plus-insert records. + +A conceptual contract is: + +```python +initialize(snapshot_inputs, checkpoint) -> OperatorState +apply(input_changes, state) -> (output_changes, new_state) +snapshot(state, checkpoint_id) -> StateHandle +restore(state_handle) -> OperatorState +``` + +A micro-batch is atomic at the plan level. Operators stage state and output; +the coordinator commits only after every downstream operator and sink succeeds. +Retries use batch identifiers and offsets to remain idempotent. + +## Planning and Capability Negotiation + +`FeatureBuilder` should annotate the logical and physical DAG with row +identity, changelog mode, and operator capabilities. The planner can then: + +- select a fully incremental path; +- insert normalization or materialization boundaries; +- fall back to bounded key recomputation; +- reject a graph whose semantics cannot be preserved. + +Fallback must be explicit and observable. Silent conversion to full snapshot +execution makes cost and latency unpredictable. + +## Checkpoint and Sink Semantics + +Production state cannot live only in `ExecutionContext`. Each compute engine +needs a durable state backend and checkpoint integration. A completed +checkpoint must cover source offsets, every stateful operator, and all output +sinks. + +Online and offline sinks need idempotent upsert and delete operations. Where a +sink cannot join the checkpoint transaction, Feast needs a documented +at-least-once protocol plus deduplication keys. Exactly-once should be claimed +only for engine/source/sink combinations that provide the required atomicity. + +## Relationship to Tiling + +Tiling already persists intermediate representations for time-window +aggregations. Sum and count tiles can be subtracted; average, variance, and +standard deviation can be reconstructed from invertible intermediate state. +Max, min, distinct count, and holistic functions need retained hops, +specialized indexes, or targeted recomputation. + +Tiling does not currently consume a general `ChangeSet`, retract arbitrary +source rows, propagate deltas through joins, or checkpoint with source offsets +and sinks. It should become one implementation technique behind an incremental +aggregation operator, not the general change contract itself. + +## Cross-engine Conformance + +The change envelope and observable results should be portable even when state +layouts are engine-specific. A conformance suite should replay the same +snapshot and change stream through Local, Spark, Flink, Ray, and SQL-capable +implementations and compare each checkpoint with batch recomputation. + +Required cases include changes on every join side, key changes, duplicates, +null keys, late and reordered events, schema transitions, replay after +failure, and sink retry behavior. + +## Rollout Plan + +1. Stabilize row identity, change envelopes, capability declarations, and a + batch-equivalence conformance suite. +2. Add checkpointed Local execution and idempotent Local sink upsert/delete + contracts. +3. Add projections, filters, deterministic transformations, and invertible + aggregations, reusing tiling representations where appropriate. +4. Integrate one durable streaming engine and validate recovery semantics. +5. Extend duplicate-key, outer-join, temporal, and late-data behavior. +6. Graduate APIs only after cross-engine compatibility evidence exists. + +## Alternatives Considered + +**Signed row multiplicities.** Differential-dataflow-style integer weights give +elegant compositional join and aggregation rules. They also impose bag +semantics and consolidation machinery unfamiliar to current Feast APIs. They +remain a strong future internal representation. + +**Dirty-key snapshot recomputation.** Tracking changed keys and rerunning +existing operators is easier to adopt, but it does not define downstream +retractions or durable state. It can serve as an explicit planner fallback. + +**Engine-native APIs only.** Letting every engine invent its own changelog +contract reduces initial work but prevents portable planning and conformance. + +## Security and Operational Considerations + +Before/after payloads may contain sensitive feature values. Checkpoints, logs, +dead-letter queues, and metrics must follow Feast's access controls and avoid +recording raw rows by default. State backends need encryption, retention, and +tenant isolation. + +Operators must expose state size, processed offsets, checkpoint age, replay +count, rejected records, and batch latency. Backpressure and state growth need +configured limits; a malformed or adversarial key distribution must not cause +unbounded memory use. + +## Open Questions + +- Where is row identity declared: DataSource, FeatureView, transformation, or + physical plan? +- Are null join keys rejected consistently or represented as non-matching? +- Which duplicate-key/multiplicity model should Feast standardize? +- How are late and out-of-order changes reconciled with point-in-time joins? +- What schema changes are compatible with existing operator state? +- Which source/sink combinations can truthfully provide exactly-once results? +- Should UPDATE remain first-class or always normalize to DELETE plus INSERT? +- How should Python UDFs declare determinism and retraction behavior? +- When should the planner prefer targeted recomputation over maintained state? + From 6f406af0c22a589a9d7a79dd27c8413aaf13fe8a Mon Sep 17 00:00:00 2001 From: HaoXuAI Date: Sat, 17 Oct 2026 00:24:27 -0700 Subject: [PATCH 5/5] docs: Remove trailing RFC whitespace Signed-off-by: HaoXuAI --- docs/reference/compute-engine/incremental-dag-poc.md | 1 - docs/rfc/change-aware-incremental-feature-dag.md | 1 - 2 files changed, 2 deletions(-) diff --git a/docs/reference/compute-engine/incremental-dag-poc.md b/docs/reference/compute-engine/incremental-dag-poc.md index 010e9f49be8..bf51a032c9e 100644 --- a/docs/reference/compute-engine/incremental-dag-poc.md +++ b/docs/reference/compute-engine/incremental-dag-poc.md @@ -135,4 +135,3 @@ source rows; route retractions through arbitrary DAG nodes; maintain join-side indexes; or coordinate source offsets and sink commits. A production incremental aggregation operator could reuse tiling intermediate representations after Feast defines the broader state and checkpoint contract. - diff --git a/docs/rfc/change-aware-incremental-feature-dag.md b/docs/rfc/change-aware-incremental-feature-dag.md index e2fb16e41de..27612607c4a 100644 --- a/docs/rfc/change-aware-incremental-feature-dag.md +++ b/docs/rfc/change-aware-incremental-feature-dag.md @@ -184,4 +184,3 @@ unbounded memory use. - Should UPDATE remain first-class or always normalize to DELETE plus INSERT? - How should Python UDFs declare determinism and retraction behavior? - When should the planner prefer targeted recomputation over maintained state? -