From 9a31fb99a8330809fc8818b16bfbc58e98c1eba0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 11:27:17 -0800 Subject: [PATCH 1/5] fix(function-pod): use the data function context consistently --- changelog.d/from-fn-data-context.md | 3 + docs/dev/design_issues/NOISSUE-FDC1.md | 13 + src/orcapod/core/cached_function_pod.py | 1 + src/orcapod/core/data_function.py | 23 +- src/orcapod/core/data_function_proxy.py | 30 +- src/orcapod/core/function_pod.py | 43 ++- src/orcapod/core/nodes/function_node.py | 11 +- src/orcapod/core/nodes/source_node.py | 18 +- src/orcapod/core/result_cache.py | 12 +- src/orcapod/pipeline/pod_invocation.py | 5 +- src/orcapod/pipeline/serialization.py | 11 +- src/orcapod/side_effects.py | 31 +- .../test_function_pod_data_context.py | 288 ++++++++++++++++++ .../test_write_side_registration.py | 89 ++---- 14 files changed, 476 insertions(+), 102 deletions(-) create mode 100644 changelog.d/from-fn-data-context.md create mode 100644 docs/dev/design_issues/NOISSUE-FDC1.md create mode 100644 tests/test_core/function_pod/test_function_pod_data_context.py diff --git a/changelog.d/from-fn-data-context.md b/changelog.d/from-fn-data-context.md new file mode 100644 index 000000000..2edb222a0 --- /dev/null +++ b/changelog.d/from-fn-data-context.md @@ -0,0 +1,3 @@ +### Fixed + +- Function pods now use one data context to construct their data functions, compute identities, and store results. An explicitly supplied pod context must agree with the context of an existing data function. diff --git a/docs/dev/design_issues/NOISSUE-FDC1.md b/docs/dev/design_issues/NOISSUE-FDC1.md new file mode 100644 index 000000000..33950f20c --- /dev/null +++ b/docs/dev/design_issues/NOISSUE-FDC1.md @@ -0,0 +1,13 @@ +## `src/orcapod/core/function_pod.py` + +### FDC1 — Function pods and their data functions used different data contexts +**Status:** resolved +**Severity:** high + +`FunctionPod.from_fn` passed its context only to the pod, while the decorator passed +it only to the data function. That split could use the wrong type converter and +hashers for signatures, schemas, and result identities. + +**Fix:** Forward the context when building the data function, have the pod inherit +it, and reject an explicit mismatch at construction. Carry the context through +function loaders, output streams, and cached result reads. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 30c1d0570..2467ea584 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -78,6 +78,7 @@ def __init__( declaration = function_pod.data_function.declaration self._cache = ResultCache( result_database=result_database, + data_context=self.data_context, record_path=context_result_path(self.uri, self.ctx_arg_name), revision=declaration.revision_component, variation_columns=declaration.variation, diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 286c6a0ea..02202552a 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1402,11 +1402,17 @@ def to_config(self) -> dict[str, Any]: } @classmethod - def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": + def from_config( + cls, + config: dict[str, Any], + *, + data_context: str | DataContext | None = None, + ) -> "PythonDataFunction": """Reconstruct a PythonDataFunction by importing the callable. Args: config: A dict as produced by `to_config`. + data_context: Context used to reconstruct the data function. Returns: A new ``PythonDataFunction`` wrapping the imported callable. @@ -1424,6 +1430,7 @@ def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": function=func, output_keys=inner.get("output_keys"), version=inner.get("version", "v0.0"), + data_context=data_context, ) @@ -1507,16 +1514,25 @@ def to_config(self) -> dict[str, Any]: return self._data_function.to_config() @classmethod - def from_config(cls, config: dict[str, Any]) -> "DataFunctionWrapper": + def from_config( + cls, + config: dict[str, Any], + *, + data_context: str | DataContext | None = None, + ) -> DataFunctionProtocol: """Reconstruct by delegating to the wrapped function type. Args: config: A dict as produced by `to_config`. + data_context: Context passed to the wrapped function's loader. Returns: A new instance reconstructed from *config*. """ - return cls._data_function_class_for_config(config).from_config(config) + function_class = cls._data_function_class_for_config(config) + if data_context is None: + return function_class.from_config(config) + return function_class.from_config(config, data_context=data_context) @staticmethod def _data_function_class_for_config(config: dict[str, Any]) -> type: @@ -1609,6 +1625,7 @@ def __init__( declaration = self.declaration self._cache = ResultCache( result_database=result_database, + data_context=self.data_context, record_path=context_result_path( record_path_prefix + self.uri, context_parameter ), diff --git a/src/orcapod/core/data_function_proxy.py b/src/orcapod/core/data_function_proxy.py index 90f3fd5fa..e3ca3c648 100644 --- a/src/orcapod/core/data_function_proxy.py +++ b/src/orcapod/core/data_function_proxy.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any +from orcapod.contexts import resolve_context from orcapod.core.data_function import DataFunctionBase from orcapod.errors import DataFunctionUnavailableError from orcapod.protocols.core_protocols import DataFunctionProtocol @@ -19,11 +20,13 @@ from orcapod.utils.canonical_type_names import stabilize_type_names if TYPE_CHECKING: + from orcapod.contexts import DataContext from orcapod.protocols.core_protocols import ( DataFunctionExecutorProtocol, DataProtocol, ) from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol + from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol class DataFunctionProxy(DataFunctionBase): @@ -38,6 +41,7 @@ class DataFunctionProxy(DataFunctionBase): ``PythonDataFunction.to_config()``). content_hash_str: Optional stored content hash string. pipeline_hash_str: Optional stored pipeline hash string. + data_context: Context used to restore schemas and interpret data. """ def __init__( @@ -45,26 +49,29 @@ def __init__( config: dict[str, Any], content_hash_str: str | None = None, pipeline_hash_str: str | None = None, + *, + data_context: str | DataContext | None = None, ) -> None: inner = config["config"] self._original_config = config self._data_function_type_id = config["data_function_type_id"] self._canonical_function_name = inner["callable_name"] + context = resolve_context(data_context) # Eagerly deserialize schemas. self._raw_input_schema_dict = inner["input_data_schema"] self._raw_output_schema_dict = inner["output_data_schema"] self._input_data_schema = _deserialize_schema_from_config( - self._raw_input_schema_dict + self._raw_input_schema_dict, context.type_converter ) self._output_data_schema = _deserialize_schema_from_config( - self._raw_output_schema_dict + self._raw_output_schema_dict, context.type_converter ) # Call super().__init__ so that major_version and # output_data_schema_hash are available for URI fallback. version = inner["version"] - super().__init__(version=version) + super().__init__(version=version, data_context=context) # URI: read from config if present, otherwise compute from metadata. uri_list = config.get("uri") @@ -219,7 +226,12 @@ def to_config(self) -> dict[str, Any]: return self._original_config @classmethod - def from_config(cls, config: dict[str, Any]) -> DataFunctionProxy: + def from_config( + cls, + config: dict[str, Any], + *, + data_context: str | DataContext | None = None, + ) -> DataFunctionProxy: """Construct a proxy from a serialized config dict. The URI is read from the config's ``"uri"`` field if present; @@ -227,11 +239,12 @@ def from_config(cls, config: dict[str, Any]) -> DataFunctionProxy: Args: config: A dict as produced by ``PythonDataFunction.to_config()``. + data_context: Context used to restore schemas and interpret data. Returns: A new ``DataFunctionProxy`` instance. """ - return cls(config=config) + return cls(config=config, data_context=data_context) # ==================== Bind / unbind ==================== @@ -322,7 +335,9 @@ def unbind(self) -> None: self._bound_function = None -def _deserialize_schema_from_config(schema_dict: dict[str, str]) -> Schema: +def _deserialize_schema_from_config( + schema_dict: dict[str, str], type_converter: TypeConverterProtocol +) -> Schema: """Reconstruct a Schema from a to_config() schema dict. Handles both ``str(python_type)`` format (e.g. ``""``), @@ -333,6 +348,7 @@ def _deserialize_schema_from_config(schema_dict: dict[str, str]) -> Schema: Args: schema_dict: Dict mapping field names to type strings. + type_converter: Converter from the proxy's data context. Returns: A Schema with Python types reconstructed from the strings. @@ -353,7 +369,7 @@ def _deserialize_schema_from_config(schema_dict: dict[str, str]) -> Schema: if needs_arrow_fallback: arrow_result = deserialize_schema( - {k: schema_dict[k] for k in needs_arrow_fallback} + {k: schema_dict[k] for k in needs_arrow_fallback}, type_converter ) for k, v in arrow_result.items(): # If deserialize_schema fell back to a raw string, coerce to object diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index c435be059..0995fc4f3 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -134,11 +134,20 @@ def __init__( config: OrcapodConfig | None = None, ctx_arg_name: str | None = None, ) -> None: + function_context = getattr(data_function, "data_context", None) + if data_context is None: + data_context = function_context super().__init__( label=label, data_context=data_context, config=config, ) + if function_context is not None and self.data_context != function_context: + raise ValueError( + f"The pod's data context {self.data_context_key!r} differs from " + f"the data function's context {function_context.context_key!r}. " + "Use the same data context for both." + ) self.tracker_manager = tracker_manager or DEFAULT_TRACKER_MANAGER self._data_function = data_function self._post_run_hooks: list[PostRunHook] = [] @@ -958,6 +967,7 @@ def from_fn( version: str = "v0.0", pod_config: PodConfig | None = None, label: str | None = None, + data_context: str | contexts.DataContext | None = None, **kwargs: Any, ) -> "FunctionPod": """Construct a ``FunctionPod`` directly from a callable. @@ -977,6 +987,7 @@ def from_fn( version: Version string (default ``"v0.0"``, as for every entry point). pod_config: Optional per-pod config. label: Optional display label. + data_context: Context for the pod and its data function. **kwargs: Forwarded to ``_FunctionPodBase.__init__``. Returns: @@ -988,6 +999,7 @@ def from_fn( function_name=name or getattr(fn, "__name__", "unknown"), version=version, label=label, + data_context=data_context, ) return cls( data_function=data_function, @@ -1081,6 +1093,7 @@ def from_config( config: dict[str, Any], *, fallback_to_proxy: bool = False, + data_context: str | contexts.DataContext | None = None, ) -> "FunctionPod": """Reconstruct a ``FunctionPod`` from a config dict. @@ -1088,6 +1101,8 @@ def from_config( config: A dict as produced by ``to_config``. fallback_to_proxy: If ``True`` and the data function cannot be resolved, use a ``DataFunctionProxy`` instead of raising. + data_context: Context used to rebuild the function and pod. Supply + the original context when restoring a custom-context pod. Returns: A new ``FunctionPod`` instance. @@ -1103,7 +1118,7 @@ def from_config( pf_config = config["data_function"] data_function = resolve_data_function_from_config( - pf_config, fallback_to_proxy=fallback_to_proxy + pf_config, fallback_to_proxy=fallback_to_proxy, data_context=data_context ) pod_config = None @@ -1243,6 +1258,10 @@ def __init__( ) -> None: self._function_pod = function_pod self._input_stream = input_stream + if "data_context" not in kwargs: + kwargs["data_context"] = getattr( + function_pod, "data_context", function_pod.data_context_key + ) super().__init__(**kwargs) # Iterator acquired lazily on first use to avoid triggering upstream @@ -1975,6 +1994,7 @@ def function_pod( pod_cache_database: ArrowDatabaseProtocol | None = None, executor: DataFunctionExecutorProtocol | None = None, post_run_hooks: Sequence[PostRunHook] | None = None, + data_context: str | contexts.DataContext | None = None, **kwargs: Any, ) -> Callable[..., CallableWithPodProtocol]: """Decorator that attaches a ``FunctionPod`` as a ``pod`` attribute. @@ -1995,6 +2015,7 @@ def function_pod( post_run_hooks: Optional list of post-run hooks to register on the pod after construction. Each entry is either a plain callable ``(PostRunPayload) -> None`` or a ``HookConfig``. + data_context: Context for the pod, its data function and its caches. **kwargs: Forwarded to ``PythonDataFunction``. Returns: @@ -2013,6 +2034,7 @@ def decorator(func: Callable) -> CallableWithPodProtocol: version=version, label=label, executor=executor, + data_context=data_context, **kwargs, ) @@ -2062,9 +2084,10 @@ def __init__( data_context: str | contexts.DataContext | None = None, **kwargs, ) -> None: - # if data_context is not explicitly given, use that of the contained pod if data_context is None: - data_context = function_pod.data_context_key + data_context = getattr( + function_pod, "data_context", function_pod.data_context_key + ) super().__init__( data_function=function_pod.data_function, data_context=data_context, @@ -2206,13 +2229,18 @@ def to_config(self) -> dict[str, Any]: @classmethod def from_config( - cls, config: dict[str, Any], *, fallback_to_proxy: bool = False + cls, + config: dict[str, Any], + *, + fallback_to_proxy: bool = False, + data_context: str | contexts.DataContext | None = None, ) -> "FallThroughPod": """Rebuild the pod from ``to_config``'s output. Args: config: A config written by ``to_config``. fallback_to_proxy: Passed to ``FunctionPod.from_config``. + data_context: Context passed to ``FunctionPod.from_config``. Returns: The fall-through pod over the rebuilt plain pod. @@ -2229,7 +2257,9 @@ def from_config( ) plain = {k: v for k, v in config.items() if k != FALL_THROUGH_TAGS_KEY} return cls( - FunctionPod.from_config(plain, fallback_to_proxy=fallback_to_proxy), + FunctionPod.from_config( + plain, fallback_to_proxy=fallback_to_proxy, data_context=data_context + ), config[FALL_THROUGH_TAGS_KEY], ) @@ -2464,6 +2494,7 @@ def side_effect_function_pod( name: str | None = None, version: str = "v0.0", pod_config: PodConfig | None = None, + data_context: str | contexts.DataContext | None = None, ) -> "FunctionPod | Callable": """Decorator wrapping a callable as a ctx-aware ``FunctionPod``. @@ -2505,6 +2536,7 @@ def my_fn(value: int, ctx: InvocationContext) -> str: name: Optional canonical function name override. version: Version string for the data function (default ``"v0.0"``, as for every entry point). pod_config: Optional per-pod configuration. + data_context: Context for the pod and its data function. Returns: A ``FunctionPod`` with ``ctx_arg_name`` set, or a decorator if ``fn`` @@ -2522,6 +2554,7 @@ def decorator(func: Callable) -> FunctionPod: name=name, version=version, pod_config=pod_config, + data_context=data_context, ) update_wrapper(pod, func) return pod diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3931aab3c..5987ede8a 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -279,7 +279,7 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: return Data( data.as_table(columns={"source": True}), record_uuid=datagram_id, - data_context=data.data_context_key, + data_context=data.data_context, ) @@ -551,7 +551,12 @@ def producer(self) -> FunctionPodProtocol: @property def data_context(self) -> contexts.DataContext: - return contexts.resolve_context(self.data_context_key) + if self._function_pod is None: + return self._data_context + context = getattr(self._function_pod, "data_context", None) + if context is not None: + return context + return contexts.resolve_context(self._function_pod.data_context_key) @property def data_context_key(self) -> str: @@ -3610,7 +3615,7 @@ def as_source( origin=self, source_id=source_id, tags_as_data=tags_as_data, - data_context=self.data_context_key, + data_context=self.data_context, config=self.orcapod_config, _tags_as_data_route="node.as_source()", ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 2e1ec9911..c89ef7965 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1598,6 +1598,7 @@ def from_stream( name=slot_name, tag_schema=tag_schema, data_schema=data_schema, + data_context=getattr(stream, "data_context", stream.data_context_key), arrow_schemas=( stream._given_arrow_schemas # pyright: ignore[reportPrivateUsage] # one slot copied into another if isinstance(stream, SourceNodeBase) @@ -1928,11 +1929,17 @@ def _declared_row( tag_table = form.apply(tag.as_table(columns={"system_tags": True})) data_table = form.apply(data.as_table(columns={"source": True, "meta": True})) new_tag = ( - Tag(tag_table, data_context=tag.data_context_key) + Tag( + tag_table, + data_context=getattr(tag, "data_context", tag.data_context_key), + ) if tag_table.num_columns else tag ) - return new_tag, Data(data_table, data_context=data.data_context_key) + return new_tag, Data( + data_table, + data_context=getattr(data, "data_context", data.data_context_key), + ) def _declared_stream( self, source: StreamProtocol, form: _DeclaredForm, table: pa.Table @@ -2305,6 +2312,7 @@ def from_stream( data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=stream.bound_source, + data_context=stream.data_context, ) node._take_saved_state_of(stream) return node @@ -2316,6 +2324,7 @@ def from_stream( data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=None, + data_context=stream.data_context, ) node._take_saved_state_of(stream) return node @@ -2342,6 +2351,9 @@ def from_stream( data_schema=data_schema, arrow_schemas=typed_arrow_schemas(stream), bound_source=stream, + data_context=getattr( + stream, "data_context", stream.data_context_key + ), ) @classmethod @@ -2365,6 +2377,7 @@ def _from_loaded_slot( name=slot.name, tag_schema=slot.tag_schema, data_schema=slot.data_schema, + data_context=slot.data_context, arrow_schemas=slot._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another ) node._take_saved_state_of(slot) @@ -2382,6 +2395,7 @@ def as_node(self) -> SourceNode: name=self._name, tag_schema=self._tag_schema, data_schema=self._data_schema, + data_context=self.data_context, arrow_schemas=self._given_arrow_schemas, ) node._take_saved_state_of(self) diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index b4bfe48d4..0fe3ba909 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -39,6 +39,7 @@ ) if TYPE_CHECKING: + from orcapod.contexts import DataContext from orcapod.protocols.core_protocols.datagrams import DatagramProtocol logger = logging.getLogger(__name__) @@ -245,6 +246,7 @@ def __init__( name_path: tuple[str, ...] | None = None, *, variation_columns: tuple[StoredColumn, ...] = (), + data_context: DataContext | None = None, ) -> None: """Create a result cache over one result table. @@ -266,6 +268,8 @@ def __init__( ``None`` looks at the paths computed from ``record_path`` only. variation_columns: The type's declared variation columns and their stored nullability. Undeclared columns are nullable. + data_context: Context used to reconstruct cached data when its key + matches the lookup key. """ self._result_database = result_database self._record_path = record_path @@ -273,6 +277,7 @@ def __init__( self._auto_flush = auto_flush self._delivers_side_effects = delivers_side_effects self._name_path = name_path + self._data_context = data_context self._variation_nullability = { column.name: column.nullable for column in variation_columns } @@ -450,11 +455,16 @@ def lookup( if self._records_output_keys: result_table = with_recorded_output_keys(result_table) + context = self._data_context return Data( result_table, record_uuid=record_uuid, meta_info={self.RESULT_COMPUTED_FLAG: False}, - data_context=data_context_key, + data_context=( + context + if context is not None and context.context_key == data_context_key + else data_context_key + ), ) def store( diff --git a/src/orcapod/pipeline/pod_invocation.py b/src/orcapod/pipeline/pod_invocation.py index acad141fe..b496ee7a3 100644 --- a/src/orcapod/pipeline/pod_invocation.py +++ b/src/orcapod/pipeline/pod_invocation.py @@ -84,7 +84,10 @@ def label(self) -> str | None: @property def _identity_hasher(self) -> SemanticHasherProtocol: """Use the same structural hasher as the node for this invocation.""" - return resolve_context(self._pod.data_context_key).semantic_hasher + context = getattr(self._pod, "data_context", None) + if context is None: + context = resolve_context(self._pod.data_context_key) + return context.semantic_hasher def _identity_inputs(self) -> tuple[StreamProtocol, ...]: """Return the recorded arguments in order.""" diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index cb932041a..8f10500f8 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -27,6 +27,7 @@ if TYPE_CHECKING: import pyarrow as pa + from orcapod.contexts import DataContext from orcapod.pipeline.composite_observer import CompositeObserver from orcapod.pipeline.logging_observer import LoggingObserver from orcapod.pipeline.status_observer import StatusObserver @@ -596,6 +597,7 @@ def resolve_data_function_from_config( config: dict[str, Any], *, fallback_to_proxy: bool = False, + data_context: str | DataContext | None = None, ) -> Any: """Reconstruct a data function from a config dict. @@ -605,6 +607,7 @@ def resolve_data_function_from_config( fallback_to_proxy: If ``True`` and reconstruction fails (unknown type, ``ImportError``, ``AttributeError``, etc.), return a ``DataFunctionProxy`` instead of raising. + data_context: Context for the reconstructed function or proxy. Returns: A new data function instance constructed from the config, or a @@ -621,14 +624,16 @@ def resolve_data_function_from_config( if fallback_to_proxy: from orcapod.core.data_function_proxy import DataFunctionProxy - return DataFunctionProxy.from_config(config) + return DataFunctionProxy.from_config(config, data_context=data_context) raise ValueError( f"Unknown data function type: {type_id!r}. " f"Known types: {sorted(DATA_FUNCTION_REGISTRY.keys())}" ) cls = DATA_FUNCTION_REGISTRY[type_id] try: - return cls.from_config(config) + if data_context is None: + return cls.from_config(config) + return cls.from_config(config, data_context=data_context) except (ImportError, ModuleNotFoundError, AttributeError) as exc: if fallback_to_proxy: logger.warning( @@ -638,7 +643,7 @@ def resolve_data_function_from_config( ) from orcapod.core.data_function_proxy import DataFunctionProxy - return DataFunctionProxy.from_config(config) + return DataFunctionProxy.from_config(config, data_context=data_context) raise diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 46d70d5f3..ffc85f85b 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -142,6 +142,7 @@ def __init__( ) -> None: self._pod = side_effect_pod self._input_stream = input_stream + kwargs.setdefault("data_context", side_effect_pod.data_context) super().__init__(**kwargs) @property @@ -628,7 +629,7 @@ def __init__( tracker_manager: TrackerManagerProtocol | None = None, name: str | None = None, label: str | None = None, - data_context: Any = None, + data_context: str | DataContext | None = None, ctx_arg_name: str = "ctx", ) -> None: warn_provisional_pod(provisional_class_name(type(self))) @@ -757,6 +758,7 @@ def side_effect_pod( config: SideEffectPodConfig | None = None, name: str | None = None, ctx_arg_name: str = "ctx", + data_context: str | DataContext | None = None, ) -> SideEffectPod | Callable[[Callable], SideEffectPod]: """Decorator that wraps a callable as a ``SideEffectPod``. @@ -769,13 +771,20 @@ def side_effect_pod( name: Optional canonical function name override (see ``SideEffectPod``). ctx_arg_name: Name of the parameter that receives ``InvocationContext``. Defaults to ``"ctx"``. + data_context: Context used to execute the side effect. Returns: A ``SideEffectPod`` (bare usage) or a decorator (parameterised usage). """ def _wrap(f: Callable) -> SideEffectPod: - return SideEffectPod(f, config=config, name=name, ctx_arg_name=ctx_arg_name) + return SideEffectPod( + f, + config=config, + name=name, + ctx_arg_name=ctx_arg_name, + data_context=data_context, + ) if fn is not None: return _wrap(fn) @@ -788,6 +797,7 @@ def sink_pod( config: SideEffectPodConfig | None = None, name: str | None = None, ctx_arg_name: str = "ctx", + data_context: str | DataContext | None = None, ) -> SideEffectPod | Callable[[Callable], SideEffectPod]: """Decorator preset: ``track_completion=True``, ``drop_on_failure=True``. @@ -800,6 +810,7 @@ def sink_pod( name: Optional canonical function name override (see ``SideEffectPod``). ctx_arg_name: Name of the parameter that receives ``InvocationContext``. Defaults to ``"ctx"``. + data_context: Context used to execute the side effect. Returns: A ``SideEffectPod`` or decorator. @@ -809,7 +820,11 @@ def sink_pod( def _wrap(f: Callable) -> SideEffectPod: return SideEffectPod( - f, config=effective_config, name=name, ctx_arg_name=ctx_arg_name + f, + config=effective_config, + name=name, + ctx_arg_name=ctx_arg_name, + data_context=data_context, ) if fn is not None: @@ -823,6 +838,7 @@ def tap_pod( config: SideEffectPodConfig | None = None, name: str | None = None, ctx_arg_name: str = "ctx", + data_context: str | DataContext | None = None, ) -> SideEffectPod | Callable[[Callable], SideEffectPod]: """Decorator preset: ``track_completion=False``, ``drop_on_failure=False``. @@ -835,6 +851,7 @@ def tap_pod( name: Optional canonical function name override (see ``SideEffectPod``). ctx_arg_name: Name of the parameter that receives ``InvocationContext``. Defaults to ``"ctx"``. + data_context: Context used to execute the side effect. Returns: A ``SideEffectPod`` or decorator. @@ -844,7 +861,11 @@ def tap_pod( def _wrap(f: Callable) -> SideEffectPod: return SideEffectPod( - f, config=effective_config, name=name, ctx_arg_name=ctx_arg_name + f, + config=effective_config, + name=name, + ctx_arg_name=ctx_arg_name, + data_context=data_context, ) if fn is not None: @@ -927,7 +948,7 @@ def __init__( ) -> None: self._pod = side_effect_pod self._input_stream = input_stream - super().__init__(label=label) + super().__init__(label=label, data_context=side_effect_pod.data_context) # ------------------------------------------------------------------ # StreamBase interface diff --git a/tests/test_core/function_pod/test_function_pod_data_context.py b/tests/test_core/function_pod/test_function_pod_data_context.py new file mode 100644 index 000000000..828315fbf --- /dev/null +++ b/tests/test_core/function_pod/test_function_pod_data_context.py @@ -0,0 +1,288 @@ +"""Function pod entry points use the same data context for identity and execution.""" + +from __future__ import annotations + +from dataclasses import replace +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod import FunctionPod, PipelineJob, contexts, function_pod +from orcapod.core.cached_function_pod import CachedFunctionPod +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.function_pod import FallThroughPod, side_effect_function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.hashing.semantic_hashing.semantic_hasher import SemanticAwarePythonHasher +from orcapod.invocation import InvocationContext +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.logical_types.registry import ( + make_arrow_extension_type, + make_polars_extension_type, +) +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.pipeline.serialization import serialize_schema +from orcapod.protocols.core_protocols import DataFunctionProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.side_effects import SideEffectPod, side_effect_pod, sink_pod, tap_pod +from orcapod.sources import DictSource + + +class Result: + """A return type registered only in the custom context.""" + + def __init__(self, value: str) -> None: + self.value = value + + +class ResultType(BaseLogicalType): + """Store a Result as a string.""" + + logical_type_name = "test.function_pod.context_result" + python_type = Result + arrow_type: Any = make_arrow_extension_type( + logical_type_name, pa.large_string(), b'{"value_hash":"stored"}' + ) + polars_type: Any = make_polars_extension_type(logical_type_name, pa.large_string()) + + def get_arrow_extension_type(self) -> pa.ExtensionType: + return self.arrow_type() + + def get_polars_extension_type(self) -> Any: + return self.polars_type() + + def python_to_storage(self, value: Result, converter: Any = None) -> str: + return value.value + + def storage_to_python(self, storage_value: str, converter: Any = None) -> Result: + return Result(storage_value) + + +@pytest.fixture(scope="module") +def custom_context() -> contexts.DataContext: + """Build an isolated context that can convert Result values.""" + base = contexts.create_registry().get_context() + converter = base.type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type(ResultType()) + hasher = SemanticAwarePythonHasher( + hasher_id="test_function_pod_semantic", + type_handler_registry=base.semantic_hasher.type_handler_registry, + ) + hasher.bind_type_converter(converter) + return replace(base, context_key="test:function-pod", semantic_hasher=hasher) + + +def transform(x: int) -> Result: + """Turn an integer into a Result.""" + return Result(str(x + 1)) + + +def contextual_transform(x: int, ctx: InvocationContext) -> Result: + """Accept an injected context and produce a Result.""" + assert isinstance(ctx, InvocationContext) + return transform(x) + + +def _identity( + pod: FunctionPod | CachedFunctionPod | FallThroughPod, +) -> tuple[object, ...]: + """Read the URI, signature hash, and both pod hashes through public methods.""" + return ( + pod.uri, + pod.data_function.get_function_variation_data()["function_signature_hash"], + pod.pipeline_hash(), + pod.content_hash(), + ) + + +@pytest.mark.parametrize( + "entry", + [ + "from_fn", + "decorator", + "data_cache", + "pod_cache", + "from_config", + "legacy", + "contextual_decorator", + ], +) +@pytest.mark.parametrize("async_run", [False, True], ids=["sync", "async"]) +def test_custom_context_function_identity_and_storage( + entry: str, async_run: bool, custom_context: contexts.DataContext +) -> None: + """Every callable-building entry point agrees with explicit construction.""" + ctx_arg = "ctx" if entry in ("legacy", "contextual_decorator") else None + fn = contextual_transform if ctx_arg else transform + data_function = cast( + DataFunctionProtocol, + cast( + object, + PythonDataFunction(fn, output_keys="out", data_context=custom_context), + ), + ) + expected = FunctionPod(data_function, ctx_arg_name=ctx_arg) + store = InMemoryArrowDatabase() + cache = InMemoryArrowDatabase() + if entry == "from_fn": + pod = FunctionPod.from_fn(fn, "out", data_context=custom_context) + elif entry == "from_config": + pod = FunctionPod.from_config(expected.to_config(), data_context=custom_context) + elif entry == "legacy": + pod = side_effect_function_pod( + fn, output_keys="out", data_context=custom_context + ) + assert isinstance(pod, FunctionPod) + else: + pod = function_pod( + output_keys="out", + data_context=custom_context, + ctx_arg=ctx_arg, + result_database=cache if entry == "data_cache" else None, + pod_cache_database=cache if entry == "pod_cache" else None, + )(fn).pod + + assert isinstance(pod, (FunctionPod, CachedFunctionPod)) + assert pod.data_context_key == custom_context.context_key + assert _identity(pod) == _identity(expected) + with pytest.raises(TypeError, match="No LogicalType or LogicalTypeFactory"): + FunctionPod.from_fn(fn, "out", data_context=contexts.get_default_context()) + + job = PipelineJob(name="custom_context", database=store) + with job: + source = DictSource([{"x": 2}], source_id="input", data_context=custom_context) + stream = pod.process(source, label="transformed") + assert stream.data_context_key == custom_context.context_key + + orchestrator = ( + AsyncPipelineOrchestrator() if async_run else SyncPipelineOrchestrator() + ) + job.run(orchestrator=orchestrator) + result_node = job.nodes["transformed"] + _, result = next(iter(result_node.iter_data())) + assert result.data_context_key == custom_context.context_key + value: object = result.as_dict()["out"] + assert isinstance(value, Result) and value.value == "3" + result_paths = [path for path in store.list_sources() if path[-1] == "rdb_v1"] + assert len(result_paths) == 1 + schema_hash = expected.data_function.uri[1] + expected_path_part = f"{schema_hash}:v0:ctx:ctx" if ctx_arg else schema_hash + assert expected_path_part in result_paths[0] + records = store.get_all_records(result_paths[0]) + assert records is not None + assert records["__data_context"].to_pylist() == [custom_context.context_key] + + if entry in ("data_cache", "pod_cache"): + tag, data = next(iter(source.iter_data())) + if entry == "data_cache": + assert isinstance(pod.data_function, CachedDataFunction) + cached_function = pod.data_function + path = cached_function.record_path + # Exercise the decorator cache directly, independently of the job cache. + cached_function.call(data) + hit = cached_function.call(data) + else: + assert isinstance(pod, CachedFunctionPod) + path = pod.record_path + pod.process_data(tag, data) + _, hit = pod.process_data(tag, data) + assert hit is not None + assert hit.data_context_key == custom_context.context_key + cached_value: object = hit.as_dict()["out"] + assert isinstance(cached_value, Result) and cached_value.value == "3" + cached_records = cache.get_all_records(path) + assert cached_records is not None + assert cached_records["__data_context"].to_pylist() == [ + custom_context.context_key + ] + + +def test_explicit_context_must_agree_with_existing_function( + custom_context: contexts.DataContext, +) -> None: + """Reject a mismatch before validating the schemas or building a cache.""" + function = cast( + DataFunctionProtocol, + cast( + object, + PythonDataFunction( + transform, output_keys="out", data_context=custom_context + ), + ), + ) + with pytest.raises(ValueError, match="pod's data context .* differs .* function"): + FunctionPod(function, data_context=contexts.get_default_context()) + pod = FunctionPod(function, data_context=custom_context) + with pytest.raises(ValueError, match="pod's data context .* differs .* function"): + CachedFunctionPod( + pod, InMemoryArrowDatabase(), data_context=contexts.get_default_context() + ) + + +def test_loaders_pass_the_context(custom_context: contexts.DataContext) -> None: + """Data-function, wrapper, fall-through, and proxy loaders forward the context.""" + pod = FunctionPod.from_fn(transform, "out", data_context=custom_context) + config = pod.data_function.to_config() + restored = PythonDataFunction.from_config(config, data_context=custom_context) + assert restored.data_context is custom_context + cached_config_restore = CachedDataFunction.from_config( + config, data_context=custom_context + ) + assert isinstance(cached_config_restore, PythonDataFunction) + assert cached_config_restore.data_context is custom_context + + fall_through = FallThroughPod(pod, ["group"]) + restored_fall_through = FallThroughPod.from_config( + fall_through.to_config(), data_context=custom_context + ) + assert _identity(restored_fall_through) == _identity(fall_through) + assert restored_fall_through.data_context is custom_context + + proxy_config = pod.to_config() + proxy_config["data_function"]["config"]["module_path"] = "unavailable_context_test" + proxy_config["data_function"]["config"]["output_data_schema"] = serialize_schema( + pod.data_function.output_data_schema, custom_context.type_converter + ) + proxy = FunctionPod.from_config( + proxy_config, fallback_to_proxy=True, data_context=custom_context + ) + assert proxy.data_context is custom_context + assert proxy.data_function.uri == pod.data_function.uri + assert ( + proxy.data_function.output_data_schema == pod.data_function.output_data_schema + ) + + +@pytest.mark.parametrize("entry", [side_effect_pod, sink_pod, tap_pod]) +@pytest.mark.parametrize("async_run", [False, True], ids=["sync", "async"]) +def test_side_effect_decorators_forward_data_context( + entry: Any, async_run: bool, custom_context: contexts.DataContext +) -> None: + """Side-effect pods use the supplied context for input and invocation log rows.""" + seen: list[int] = [] + + def deliver(x: int, ctx: InvocationContext) -> None: + seen.append(x) + + pod = entry(data_context=custom_context)(deliver) + assert isinstance(pod, SideEffectPod) + assert pod.data_context is custom_context + + store = InMemoryArrowDatabase() + job = PipelineJob(name="side_effect_context", database=store) + with job: + source = DictSource([{"x": 4}], source_id="input", data_context=custom_context) + stream = pod.process(source, label="effect") + assert stream.data_context_key == custom_context.context_key + orchestrator = ( + AsyncPipelineOrchestrator() if async_run else SyncPipelineOrchestrator() + ) + job.run(orchestrator=orchestrator) + assert seen == [4] + if pod.pod_config.track_completion: + paths = [path for path in store.list_sources() if "side_effects" in path] + assert len(paths) == 1 + rows = store.get_all_records(paths[0]) + assert rows is not None + assert rows["__data_context"].to_pylist() == [custom_context.context_key] diff --git a/tests/test_core/function_pod/test_write_side_registration.py b/tests/test_core/function_pod/test_write_side_registration.py index 9e8279bbe..276a7106b 100644 --- a/tests/test_core/function_pod/test_write_side_registration.py +++ b/tests/test_core/function_pod/test_write_side_registration.py @@ -15,7 +15,6 @@ from orcapod.contexts import get_default_context from orcapod.contexts.core import DataContext -from orcapod.core.data_function import PythonDataFunction from orcapod.core.function_pod import FunctionPod from orcapod.logical_types.protocols import LogicalTypeProtocol from orcapod.logical_types.registry import ( @@ -142,10 +141,7 @@ def test_pod_declaration_triggers_factory_for_input_type(): def my_func(x: _MyChild) -> str: return str(x) - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log assert registry.get_by_python_type(_MyChild) is not None @@ -158,10 +154,7 @@ def test_pod_declaration_triggers_factory_for_output_type(): def my_func(x: int) -> _MyChild: return _MyChild() - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log assert registry.get_by_python_type(_MyChild) is not None @@ -177,10 +170,7 @@ def test_pod_declaration_with_nested_list_input(): def my_func(items: list[_MyChild]) -> str: return "" - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log @@ -197,10 +187,7 @@ def test_pod_declaration_with_doubly_nested_input(): def my_func(mapping: dict[str, list[_MyChild]]) -> str: return "" - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log @@ -212,10 +199,7 @@ def test_pod_declaration_with_optional_input(): def my_func(x: Optional[_MyChild]) -> str: return "" - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log @@ -227,10 +211,7 @@ def test_pod_declaration_with_complex_output(): def my_func(x: str) -> list[_MyChild]: return [] - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log @@ -247,10 +228,7 @@ def test_pod_declaration_with_doubly_nested_output(): def my_func(x: int) -> dict[str, list[_MyChild]]: return {} - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log @@ -265,10 +243,7 @@ def test_pod_declaration_two_classes_one_in_input_one_in_output(): def my_func(x: _MyChild) -> _MyOtherChild: return _MyOtherChild() - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log assert _MyOtherChild in call_log @@ -281,10 +256,7 @@ def test_pod_declaration_two_classes_both_in_input(): def my_func(x: _MyChild, y: _MyOtherChild) -> str: return "" - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log assert _MyOtherChild in call_log @@ -297,13 +269,7 @@ def test_pod_declaration_two_classes_both_in_output(): def my_func(x: int) -> tuple[_MyChild, _MyOtherChild]: return _MyChild(), _MyOtherChild() - FunctionPod( - data_function=PythonDataFunction( - my_func, - output_keys=["first", "second"], - ), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["first", "second"], data_context=ctx) assert _MyChild in call_log assert _MyOtherChild in call_log @@ -316,10 +282,7 @@ def test_pod_declaration_three_classes_mixed(): def my_func(a: _MyChild, b: list[_MyOtherChild]) -> _ThirdChild: return _ThirdChild() - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log assert _MyOtherChild in call_log assert _ThirdChild in call_log @@ -333,10 +296,7 @@ def test_pod_declaration_three_classes_all_in_input(): def my_func(a: _MyChild, b: _MyOtherChild, c: _ThirdChild) -> str: return "" - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log assert _MyOtherChild in call_log assert _ThirdChild in call_log @@ -364,10 +324,7 @@ def my_func(x: int, y: str) -> float: return 0.0 # Should not raise — int, str, float are native - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) def test_pod_declaration_raises_type_error_for_unhandled_class(): @@ -379,10 +336,7 @@ def my_func(x: _MyChild) -> str: return "" with pytest.raises(TypeError, match="No LogicalType or LogicalTypeFactory"): - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) def test_pod_declaration_raises_for_nested_unhandled_class(): @@ -394,10 +348,7 @@ def my_func(items: list[_MyChild]) -> str: return "" with pytest.raises(TypeError, match="No LogicalType or LogicalTypeFactory"): - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) def test_pod_declaration_already_registered_type_no_factory_call(): @@ -410,10 +361,7 @@ def test_pod_declaration_already_registered_type_no_factory_call(): def my_func(x: _MyChild) -> str: return "" - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) # Factory was NOT called — _MyChild was already registered assert _MyChild not in call_log @@ -432,9 +380,6 @@ def test_pod_declaration_with_union_none_syntax(): def my_func(x: _MyChild | None) -> str: return "" - FunctionPod( - data_function=PythonDataFunction(my_func, output_keys=["result"]), - data_context=ctx, - ) + FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) assert _MyChild in call_log assert registry.get_by_python_type(_MyChild) is not None From 06b1263264c667c6124be73201cd934347575dd0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 11:32:46 -0800 Subject: [PATCH 2/5] fix(side-effect): preserve context when loading podless nodes --- src/orcapod/side_effects.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index ffc85f85b..9adeb760c 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -948,7 +948,10 @@ def __init__( ) -> None: self._pod = side_effect_pod self._input_stream = input_stream - super().__init__(label=label, data_context=side_effect_pod.data_context) + # Read-only nodes have no live pod and restore their context from the descriptor. + super().__init__( + label=label, data_context=getattr(side_effect_pod, "data_context", None) + ) # ------------------------------------------------------------------ # StreamBase interface From 1e94433f6b077ad7951c4ef2cd89546fb24d4803 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 11:37:52 -0800 Subject: [PATCH 3/5] docs: link the data context fix to ITL-1753 --- changelog.d/{from-fn-data-context.md => ITL-1753.md} | 0 docs/dev/design_issues/{NOISSUE-FDC1.md => ITL-1753-FDC1.md} | 1 + 2 files changed, 1 insertion(+) rename changelog.d/{from-fn-data-context.md => ITL-1753.md} (100%) rename docs/dev/design_issues/{NOISSUE-FDC1.md => ITL-1753-FDC1.md} (96%) diff --git a/changelog.d/from-fn-data-context.md b/changelog.d/ITL-1753.md similarity index 100% rename from changelog.d/from-fn-data-context.md rename to changelog.d/ITL-1753.md diff --git a/docs/dev/design_issues/NOISSUE-FDC1.md b/docs/dev/design_issues/ITL-1753-FDC1.md similarity index 96% rename from docs/dev/design_issues/NOISSUE-FDC1.md rename to docs/dev/design_issues/ITL-1753-FDC1.md index 33950f20c..8c8dd1f3a 100644 --- a/docs/dev/design_issues/NOISSUE-FDC1.md +++ b/docs/dev/design_issues/ITL-1753-FDC1.md @@ -3,6 +3,7 @@ ### FDC1 — Function pods and their data functions used different data contexts **Status:** resolved **Severity:** high +**Issue:** ITL-1753 `FunctionPod.from_fn` passed its context only to the pod, while the decorator passed it only to the data function. That split could use the wrong type converter and From ec94e3ca26e20fb0c5c4ce0cd66655bcd85b2a1b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 12:41:05 -0800 Subject: [PATCH 4/5] fix(function-pod): narrow custom context forwarding --- changelog.d/ITL-1753.md | 2 +- docs/dev/design_issues/ITL-1753-FDC1.md | 11 +- src/orcapod/core/cached_function_pod.py | 9 +- src/orcapod/core/data_function.py | 23 +- src/orcapod/core/data_function_proxy.py | 30 +- src/orcapod/core/function_pod.py | 35 +-- src/orcapod/core/nodes/function_node.py | 14 +- src/orcapod/core/nodes/source_node.py | 15 +- src/orcapod/core/result_cache.py | 14 +- src/orcapod/pipeline/serialization.py | 11 +- src/orcapod/side_effects.py | 34 +-- .../test_function_pod_data_context.py | 256 +++++++----------- .../test_write_side_registration.py | 89 ++++-- 13 files changed, 213 insertions(+), 330 deletions(-) diff --git a/changelog.d/ITL-1753.md b/changelog.d/ITL-1753.md index 2edb222a0..985d29907 100644 --- a/changelog.d/ITL-1753.md +++ b/changelog.d/ITL-1753.md @@ -1,3 +1,3 @@ ### Fixed -- Function pods now use one data context to construct their data functions, compute identities, and store results. An explicitly supplied pod context must agree with the context of an existing data function. +- `FunctionPod.from_fn` and `side_effect_function_pod` now construct their data functions in the supplied data context. Function jobs read cached results in that context. diff --git a/docs/dev/design_issues/ITL-1753-FDC1.md b/docs/dev/design_issues/ITL-1753-FDC1.md index 8c8dd1f3a..d7df5d6b6 100644 --- a/docs/dev/design_issues/ITL-1753-FDC1.md +++ b/docs/dev/design_issues/ITL-1753-FDC1.md @@ -5,10 +5,9 @@ **Severity:** high **Issue:** ITL-1753 -`FunctionPod.from_fn` passed its context only to the pod, while the decorator passed -it only to the data function. That split could use the wrong type converter and -hashers for signatures, schemas, and result identities. +`FunctionPod.from_fn` passed its context only to the pod. The resulting data function +used the default type converter and hashers for signatures, schemas, and result identities. -**Fix:** Forward the context when building the data function, have the pod inherit -it, and reject an explicit mismatch at construction. Carry the context through -function loaders, output streams, and cached result reads. +**Fix:** Forward the context when building the data function, including through +`side_effect_function_pod`. Preserve the live context through job compilation, +execution, and cached result reads. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 2467ea584..2eba3edd0 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -78,7 +78,6 @@ def __init__( declaration = function_pod.data_function.declaration self._cache = ResultCache( result_database=result_database, - data_context=self.data_context, record_path=context_result_path(self.uri, self.ctx_arg_name), revision=declaration.revision_component, variation_columns=declaration.variation, @@ -201,7 +200,9 @@ def lookup_cached_data(self, data: DataProtocol) -> DataProtocol | None: The cached output ``Data`` (with ``RESULT_COMPUTED_FLAG=False`` appended), or ``None`` if no cached result exists for this input. """ - cached = self._cache.lookup(data, data_context_key=self.data_context_key) + cached = self._cache.lookup( + data, data_context_key=self.data_context_key, data_context=self.data_context + ) if cached is None: return None return cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) @@ -233,7 +234,9 @@ def process_data( A ``(tag, output_data)`` tuple; output_data is ``None`` if the inner function filters the data out. """ - cached = self._cache.lookup(data, data_context_key=self.data_context_key) + cached = self._cache.lookup( + data, data_context_key=self.data_context_key, data_context=self.data_context + ) if cached is not None: module_logger.info("Pod-level cache hit") cached = cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 02202552a..286c6a0ea 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1402,17 +1402,11 @@ def to_config(self) -> dict[str, Any]: } @classmethod - def from_config( - cls, - config: dict[str, Any], - *, - data_context: str | DataContext | None = None, - ) -> "PythonDataFunction": + def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": """Reconstruct a PythonDataFunction by importing the callable. Args: config: A dict as produced by `to_config`. - data_context: Context used to reconstruct the data function. Returns: A new ``PythonDataFunction`` wrapping the imported callable. @@ -1430,7 +1424,6 @@ def from_config( function=func, output_keys=inner.get("output_keys"), version=inner.get("version", "v0.0"), - data_context=data_context, ) @@ -1514,25 +1507,16 @@ def to_config(self) -> dict[str, Any]: return self._data_function.to_config() @classmethod - def from_config( - cls, - config: dict[str, Any], - *, - data_context: str | DataContext | None = None, - ) -> DataFunctionProtocol: + def from_config(cls, config: dict[str, Any]) -> "DataFunctionWrapper": """Reconstruct by delegating to the wrapped function type. Args: config: A dict as produced by `to_config`. - data_context: Context passed to the wrapped function's loader. Returns: A new instance reconstructed from *config*. """ - function_class = cls._data_function_class_for_config(config) - if data_context is None: - return function_class.from_config(config) - return function_class.from_config(config, data_context=data_context) + return cls._data_function_class_for_config(config).from_config(config) @staticmethod def _data_function_class_for_config(config: dict[str, Any]) -> type: @@ -1625,7 +1609,6 @@ def __init__( declaration = self.declaration self._cache = ResultCache( result_database=result_database, - data_context=self.data_context, record_path=context_result_path( record_path_prefix + self.uri, context_parameter ), diff --git a/src/orcapod/core/data_function_proxy.py b/src/orcapod/core/data_function_proxy.py index e3ca3c648..90f3fd5fa 100644 --- a/src/orcapod/core/data_function_proxy.py +++ b/src/orcapod/core/data_function_proxy.py @@ -12,7 +12,6 @@ from typing import TYPE_CHECKING, Any -from orcapod.contexts import resolve_context from orcapod.core.data_function import DataFunctionBase from orcapod.errors import DataFunctionUnavailableError from orcapod.protocols.core_protocols import DataFunctionProtocol @@ -20,13 +19,11 @@ from orcapod.utils.canonical_type_names import stabilize_type_names if TYPE_CHECKING: - from orcapod.contexts import DataContext from orcapod.protocols.core_protocols import ( DataFunctionExecutorProtocol, DataProtocol, ) from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol - from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol class DataFunctionProxy(DataFunctionBase): @@ -41,7 +38,6 @@ class DataFunctionProxy(DataFunctionBase): ``PythonDataFunction.to_config()``). content_hash_str: Optional stored content hash string. pipeline_hash_str: Optional stored pipeline hash string. - data_context: Context used to restore schemas and interpret data. """ def __init__( @@ -49,29 +45,26 @@ def __init__( config: dict[str, Any], content_hash_str: str | None = None, pipeline_hash_str: str | None = None, - *, - data_context: str | DataContext | None = None, ) -> None: inner = config["config"] self._original_config = config self._data_function_type_id = config["data_function_type_id"] self._canonical_function_name = inner["callable_name"] - context = resolve_context(data_context) # Eagerly deserialize schemas. self._raw_input_schema_dict = inner["input_data_schema"] self._raw_output_schema_dict = inner["output_data_schema"] self._input_data_schema = _deserialize_schema_from_config( - self._raw_input_schema_dict, context.type_converter + self._raw_input_schema_dict ) self._output_data_schema = _deserialize_schema_from_config( - self._raw_output_schema_dict, context.type_converter + self._raw_output_schema_dict ) # Call super().__init__ so that major_version and # output_data_schema_hash are available for URI fallback. version = inner["version"] - super().__init__(version=version, data_context=context) + super().__init__(version=version) # URI: read from config if present, otherwise compute from metadata. uri_list = config.get("uri") @@ -226,12 +219,7 @@ def to_config(self) -> dict[str, Any]: return self._original_config @classmethod - def from_config( - cls, - config: dict[str, Any], - *, - data_context: str | DataContext | None = None, - ) -> DataFunctionProxy: + def from_config(cls, config: dict[str, Any]) -> DataFunctionProxy: """Construct a proxy from a serialized config dict. The URI is read from the config's ``"uri"`` field if present; @@ -239,12 +227,11 @@ def from_config( Args: config: A dict as produced by ``PythonDataFunction.to_config()``. - data_context: Context used to restore schemas and interpret data. Returns: A new ``DataFunctionProxy`` instance. """ - return cls(config=config, data_context=data_context) + return cls(config=config) # ==================== Bind / unbind ==================== @@ -335,9 +322,7 @@ def unbind(self) -> None: self._bound_function = None -def _deserialize_schema_from_config( - schema_dict: dict[str, str], type_converter: TypeConverterProtocol -) -> Schema: +def _deserialize_schema_from_config(schema_dict: dict[str, str]) -> Schema: """Reconstruct a Schema from a to_config() schema dict. Handles both ``str(python_type)`` format (e.g. ``""``), @@ -348,7 +333,6 @@ def _deserialize_schema_from_config( Args: schema_dict: Dict mapping field names to type strings. - type_converter: Converter from the proxy's data context. Returns: A Schema with Python types reconstructed from the strings. @@ -369,7 +353,7 @@ def _deserialize_schema_from_config( if needs_arrow_fallback: arrow_result = deserialize_schema( - {k: schema_dict[k] for k in needs_arrow_fallback}, type_converter + {k: schema_dict[k] for k in needs_arrow_fallback} ) for k, v in arrow_result.items(): # If deserialize_schema fell back to a raw string, coerce to object diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 0995fc4f3..92ea47fdd 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -134,20 +134,11 @@ def __init__( config: OrcapodConfig | None = None, ctx_arg_name: str | None = None, ) -> None: - function_context = getattr(data_function, "data_context", None) - if data_context is None: - data_context = function_context super().__init__( label=label, data_context=data_context, config=config, ) - if function_context is not None and self.data_context != function_context: - raise ValueError( - f"The pod's data context {self.data_context_key!r} differs from " - f"the data function's context {function_context.context_key!r}. " - "Use the same data context for both." - ) self.tracker_manager = tracker_manager or DEFAULT_TRACKER_MANAGER self._data_function = data_function self._post_run_hooks: list[PostRunHook] = [] @@ -1006,6 +997,7 @@ def from_fn( pod_config=pod_config, ctx_arg_name=ctx_arg_name, label=label, + data_context=data_context, **kwargs, ) @@ -1041,6 +1033,7 @@ def process( function_pod=self, input_stream=input_stream, label=label, + data_context=self.data_context, ) return output_stream._mark_recorded(self.tracker_manager) @@ -1093,7 +1086,6 @@ def from_config( config: dict[str, Any], *, fallback_to_proxy: bool = False, - data_context: str | contexts.DataContext | None = None, ) -> "FunctionPod": """Reconstruct a ``FunctionPod`` from a config dict. @@ -1101,8 +1093,6 @@ def from_config( config: A dict as produced by ``to_config``. fallback_to_proxy: If ``True`` and the data function cannot be resolved, use a ``DataFunctionProxy`` instead of raising. - data_context: Context used to rebuild the function and pod. Supply - the original context when restoring a custom-context pod. Returns: A new ``FunctionPod`` instance. @@ -1118,7 +1108,7 @@ def from_config( pf_config = config["data_function"] data_function = resolve_data_function_from_config( - pf_config, fallback_to_proxy=fallback_to_proxy, data_context=data_context + pf_config, fallback_to_proxy=fallback_to_proxy ) pod_config = None @@ -1258,10 +1248,6 @@ def __init__( ) -> None: self._function_pod = function_pod self._input_stream = input_stream - if "data_context" not in kwargs: - kwargs["data_context"] = getattr( - function_pod, "data_context", function_pod.data_context_key - ) super().__init__(**kwargs) # Iterator acquired lazily on first use to avoid triggering upstream @@ -1994,7 +1980,6 @@ def function_pod( pod_cache_database: ArrowDatabaseProtocol | None = None, executor: DataFunctionExecutorProtocol | None = None, post_run_hooks: Sequence[PostRunHook] | None = None, - data_context: str | contexts.DataContext | None = None, **kwargs: Any, ) -> Callable[..., CallableWithPodProtocol]: """Decorator that attaches a ``FunctionPod`` as a ``pod`` attribute. @@ -2015,7 +2000,6 @@ def function_pod( post_run_hooks: Optional list of post-run hooks to register on the pod after construction. Each entry is either a plain callable ``(PostRunPayload) -> None`` or a ``HookConfig``. - data_context: Context for the pod, its data function and its caches. **kwargs: Forwarded to ``PythonDataFunction``. Returns: @@ -2034,7 +2018,6 @@ def decorator(func: Callable) -> CallableWithPodProtocol: version=version, label=label, executor=executor, - data_context=data_context, **kwargs, ) @@ -2084,6 +2067,7 @@ def __init__( data_context: str | contexts.DataContext | None = None, **kwargs, ) -> None: + # if data_context is not explicitly given, use that of the contained pod if data_context is None: data_context = getattr( function_pod, "data_context", function_pod.data_context_key @@ -2229,18 +2213,13 @@ def to_config(self) -> dict[str, Any]: @classmethod def from_config( - cls, - config: dict[str, Any], - *, - fallback_to_proxy: bool = False, - data_context: str | contexts.DataContext | None = None, + cls, config: dict[str, Any], *, fallback_to_proxy: bool = False ) -> "FallThroughPod": """Rebuild the pod from ``to_config``'s output. Args: config: A config written by ``to_config``. fallback_to_proxy: Passed to ``FunctionPod.from_config``. - data_context: Context passed to ``FunctionPod.from_config``. Returns: The fall-through pod over the rebuilt plain pod. @@ -2257,9 +2236,7 @@ def from_config( ) plain = {k: v for k, v in config.items() if k != FALL_THROUGH_TAGS_KEY} return cls( - FunctionPod.from_config( - plain, fallback_to_proxy=fallback_to_proxy, data_context=data_context - ), + FunctionPod.from_config(plain, fallback_to_proxy=fallback_to_proxy), config[FALL_THROUGH_TAGS_KEY], ) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 5987ede8a..260eb635e 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -551,12 +551,11 @@ def producer(self) -> FunctionPodProtocol: @property def data_context(self) -> contexts.DataContext: - if self._function_pod is None: - return self._data_context - context = getattr(self._function_pod, "data_context", None) - if context is not None: - return context - return contexts.resolve_context(self._function_pod.data_context_key) + if self._function_pod is not None: + context = getattr(self._function_pod, "data_context", None) + if context is not None: + return context + return contexts.resolve_context(self.data_context_key) @property def data_context_key(self) -> str: @@ -3615,7 +3614,7 @@ def as_source( origin=self, source_id=source_id, tags_as_data=tags_as_data, - data_context=self.data_context, + data_context=self.data_context_key, config=self.orcapod_config, _tags_as_data_route="node.as_source()", ) @@ -4123,6 +4122,7 @@ def _stored_rows_stream( without_tag_kind_marks(joined.drop(drop_cols)), tag_columns=self._stored_tag_keys(fetched), data_tags=fetched.data_tags, + data_context=self.data_context, ) return instance_ids, stream, data_ids diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index c89ef7965..9bc030b02 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1598,7 +1598,6 @@ def from_stream( name=slot_name, tag_schema=tag_schema, data_schema=data_schema, - data_context=getattr(stream, "data_context", stream.data_context_key), arrow_schemas=( stream._given_arrow_schemas # pyright: ignore[reportPrivateUsage] # one slot copied into another if isinstance(stream, SourceNodeBase) @@ -1929,17 +1928,11 @@ def _declared_row( tag_table = form.apply(tag.as_table(columns={"system_tags": True})) data_table = form.apply(data.as_table(columns={"source": True, "meta": True})) new_tag = ( - Tag( - tag_table, - data_context=getattr(tag, "data_context", tag.data_context_key), - ) + Tag(tag_table, data_context=tag.data_context_key) if tag_table.num_columns else tag ) - return new_tag, Data( - data_table, - data_context=getattr(data, "data_context", data.data_context_key), - ) + return new_tag, Data(data_table, data_context=data.data_context_key) def _declared_stream( self, source: StreamProtocol, form: _DeclaredForm, table: pa.Table @@ -2312,7 +2305,6 @@ def from_stream( data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=stream.bound_source, - data_context=stream.data_context, ) node._take_saved_state_of(stream) return node @@ -2324,7 +2316,6 @@ def from_stream( data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=None, - data_context=stream.data_context, ) node._take_saved_state_of(stream) return node @@ -2377,7 +2368,6 @@ def _from_loaded_slot( name=slot.name, tag_schema=slot.tag_schema, data_schema=slot.data_schema, - data_context=slot.data_context, arrow_schemas=slot._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another ) node._take_saved_state_of(slot) @@ -2395,7 +2385,6 @@ def as_node(self) -> SourceNode: name=self._name, tag_schema=self._tag_schema, data_schema=self._data_schema, - data_context=self.data_context, arrow_schemas=self._given_arrow_schemas, ) node._take_saved_state_of(self) diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 0fe3ba909..0b1853495 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -246,7 +246,6 @@ def __init__( name_path: tuple[str, ...] | None = None, *, variation_columns: tuple[StoredColumn, ...] = (), - data_context: DataContext | None = None, ) -> None: """Create a result cache over one result table. @@ -268,8 +267,6 @@ def __init__( ``None`` looks at the paths computed from ``record_path`` only. variation_columns: The type's declared variation columns and their stored nullability. Undeclared columns are nullable. - data_context: Context used to reconstruct cached data when its key - matches the lookup key. """ self._result_database = result_database self._record_path = record_path @@ -277,7 +274,6 @@ def __init__( self._auto_flush = auto_flush self._delivers_side_effects = delivers_side_effects self._name_path = name_path - self._data_context = data_context self._variation_nullability = { column.name: column.nullable for column in variation_columns } @@ -374,6 +370,7 @@ def lookup( additional_constraints: dict[str, Any] | None = None, *, data_context_key: str, + data_context: DataContext | None = None, ) -> DataProtocol | None: """Look up a cached output data for *input_data*. @@ -395,6 +392,8 @@ def lookup( for ``function_name``). data_context_key: Key of the caller's data context. Only rows written under it are matched, and the returned data carries it. + data_context: The caller's live context, if available, for decoding + the cached data without resolving its key through the registry. Returns: The cached output data with ``RESULT_COMPUTED_FLAG: False`` @@ -455,16 +454,11 @@ def lookup( if self._records_output_keys: result_table = with_recorded_output_keys(result_table) - context = self._data_context return Data( result_table, record_uuid=record_uuid, meta_info={self.RESULT_COMPUTED_FLAG: False}, - data_context=( - context - if context is not None and context.context_key == data_context_key - else data_context_key - ), + data_context=data_context if data_context is not None else data_context_key, ) def store( diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 8f10500f8..cb932041a 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -27,7 +27,6 @@ if TYPE_CHECKING: import pyarrow as pa - from orcapod.contexts import DataContext from orcapod.pipeline.composite_observer import CompositeObserver from orcapod.pipeline.logging_observer import LoggingObserver from orcapod.pipeline.status_observer import StatusObserver @@ -597,7 +596,6 @@ def resolve_data_function_from_config( config: dict[str, Any], *, fallback_to_proxy: bool = False, - data_context: str | DataContext | None = None, ) -> Any: """Reconstruct a data function from a config dict. @@ -607,7 +605,6 @@ def resolve_data_function_from_config( fallback_to_proxy: If ``True`` and reconstruction fails (unknown type, ``ImportError``, ``AttributeError``, etc.), return a ``DataFunctionProxy`` instead of raising. - data_context: Context for the reconstructed function or proxy. Returns: A new data function instance constructed from the config, or a @@ -624,16 +621,14 @@ def resolve_data_function_from_config( if fallback_to_proxy: from orcapod.core.data_function_proxy import DataFunctionProxy - return DataFunctionProxy.from_config(config, data_context=data_context) + return DataFunctionProxy.from_config(config) raise ValueError( f"Unknown data function type: {type_id!r}. " f"Known types: {sorted(DATA_FUNCTION_REGISTRY.keys())}" ) cls = DATA_FUNCTION_REGISTRY[type_id] try: - if data_context is None: - return cls.from_config(config) - return cls.from_config(config, data_context=data_context) + return cls.from_config(config) except (ImportError, ModuleNotFoundError, AttributeError) as exc: if fallback_to_proxy: logger.warning( @@ -643,7 +638,7 @@ def resolve_data_function_from_config( ) from orcapod.core.data_function_proxy import DataFunctionProxy - return DataFunctionProxy.from_config(config, data_context=data_context) + return DataFunctionProxy.from_config(config) raise diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 9adeb760c..46d70d5f3 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -142,7 +142,6 @@ def __init__( ) -> None: self._pod = side_effect_pod self._input_stream = input_stream - kwargs.setdefault("data_context", side_effect_pod.data_context) super().__init__(**kwargs) @property @@ -629,7 +628,7 @@ def __init__( tracker_manager: TrackerManagerProtocol | None = None, name: str | None = None, label: str | None = None, - data_context: str | DataContext | None = None, + data_context: Any = None, ctx_arg_name: str = "ctx", ) -> None: warn_provisional_pod(provisional_class_name(type(self))) @@ -758,7 +757,6 @@ def side_effect_pod( config: SideEffectPodConfig | None = None, name: str | None = None, ctx_arg_name: str = "ctx", - data_context: str | DataContext | None = None, ) -> SideEffectPod | Callable[[Callable], SideEffectPod]: """Decorator that wraps a callable as a ``SideEffectPod``. @@ -771,20 +769,13 @@ def side_effect_pod( name: Optional canonical function name override (see ``SideEffectPod``). ctx_arg_name: Name of the parameter that receives ``InvocationContext``. Defaults to ``"ctx"``. - data_context: Context used to execute the side effect. Returns: A ``SideEffectPod`` (bare usage) or a decorator (parameterised usage). """ def _wrap(f: Callable) -> SideEffectPod: - return SideEffectPod( - f, - config=config, - name=name, - ctx_arg_name=ctx_arg_name, - data_context=data_context, - ) + return SideEffectPod(f, config=config, name=name, ctx_arg_name=ctx_arg_name) if fn is not None: return _wrap(fn) @@ -797,7 +788,6 @@ def sink_pod( config: SideEffectPodConfig | None = None, name: str | None = None, ctx_arg_name: str = "ctx", - data_context: str | DataContext | None = None, ) -> SideEffectPod | Callable[[Callable], SideEffectPod]: """Decorator preset: ``track_completion=True``, ``drop_on_failure=True``. @@ -810,7 +800,6 @@ def sink_pod( name: Optional canonical function name override (see ``SideEffectPod``). ctx_arg_name: Name of the parameter that receives ``InvocationContext``. Defaults to ``"ctx"``. - data_context: Context used to execute the side effect. Returns: A ``SideEffectPod`` or decorator. @@ -820,11 +809,7 @@ def sink_pod( def _wrap(f: Callable) -> SideEffectPod: return SideEffectPod( - f, - config=effective_config, - name=name, - ctx_arg_name=ctx_arg_name, - data_context=data_context, + f, config=effective_config, name=name, ctx_arg_name=ctx_arg_name ) if fn is not None: @@ -838,7 +823,6 @@ def tap_pod( config: SideEffectPodConfig | None = None, name: str | None = None, ctx_arg_name: str = "ctx", - data_context: str | DataContext | None = None, ) -> SideEffectPod | Callable[[Callable], SideEffectPod]: """Decorator preset: ``track_completion=False``, ``drop_on_failure=False``. @@ -851,7 +835,6 @@ def tap_pod( name: Optional canonical function name override (see ``SideEffectPod``). ctx_arg_name: Name of the parameter that receives ``InvocationContext``. Defaults to ``"ctx"``. - data_context: Context used to execute the side effect. Returns: A ``SideEffectPod`` or decorator. @@ -861,11 +844,7 @@ def tap_pod( def _wrap(f: Callable) -> SideEffectPod: return SideEffectPod( - f, - config=effective_config, - name=name, - ctx_arg_name=ctx_arg_name, - data_context=data_context, + f, config=effective_config, name=name, ctx_arg_name=ctx_arg_name ) if fn is not None: @@ -948,10 +927,7 @@ def __init__( ) -> None: self._pod = side_effect_pod self._input_stream = input_stream - # Read-only nodes have no live pod and restore their context from the descriptor. - super().__init__( - label=label, data_context=getattr(side_effect_pod, "data_context", None) - ) + super().__init__(label=label) # ------------------------------------------------------------------ # StreamBase interface diff --git a/tests/test_core/function_pod/test_function_pod_data_context.py b/tests/test_core/function_pod/test_function_pod_data_context.py index 828315fbf..752687320 100644 --- a/tests/test_core/function_pod/test_function_pod_data_context.py +++ b/tests/test_core/function_pod/test_function_pod_data_context.py @@ -8,10 +8,9 @@ import pyarrow as pa import pytest -from orcapod import FunctionPod, PipelineJob, contexts, function_pod -from orcapod.core.cached_function_pod import CachedFunctionPod -from orcapod.core.data_function import CachedDataFunction, PythonDataFunction -from orcapod.core.function_pod import FallThroughPod, side_effect_function_pod +from orcapod import FunctionPod, PipelineJob, contexts +from orcapod.core.data_function import PythonDataFunction +from orcapod.core.function_pod import side_effect_function_pod from orcapod.databases import InMemoryArrowDatabase from orcapod.hashing.semantic_hashing.semantic_hasher import SemanticAwarePythonHasher from orcapod.invocation import InvocationContext @@ -21,10 +20,9 @@ make_polars_extension_type, ) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator -from orcapod.pipeline.serialization import serialize_schema from orcapod.protocols.core_protocols import DataFunctionProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter -from orcapod.side_effects import SideEffectPod, side_effect_pod, sink_pod, tap_pod +from orcapod.side_effects import SideEffectPod, SideEffectPodConfig from orcapod.sources import DictSource @@ -85,7 +83,7 @@ def contextual_transform(x: int, ctx: InvocationContext) -> Result: def _identity( - pod: FunctionPod | CachedFunctionPod | FallThroughPod, + pod: FunctionPod, ) -> tuple[object, ...]: """Read the URI, signature hash, and both pod hashes through public methods.""" return ( @@ -96,112 +94,39 @@ def _identity( ) -@pytest.mark.parametrize( - "entry", - [ - "from_fn", - "decorator", - "data_cache", - "pod_cache", - "from_config", - "legacy", - "contextual_decorator", - ], -) -@pytest.mark.parametrize("async_run", [False, True], ids=["sync", "async"]) -def test_custom_context_function_identity_and_storage( - entry: str, async_run: bool, custom_context: contexts.DataContext +@pytest.mark.parametrize("entry", ["from_fn", "legacy"]) +def test_callable_construction_uses_custom_context( + entry: str, custom_context: contexts.DataContext ) -> None: - """Every callable-building entry point agrees with explicit construction.""" - ctx_arg = "ctx" if entry in ("legacy", "contextual_decorator") else None - fn = contextual_transform if ctx_arg else transform - data_function = cast( + """Use the supplied converter and hasher when constructing the function.""" + if entry == "from_fn": + pod = FunctionPod.from_fn(transform, "out", data_context=custom_context) + fn, ctx_arg = transform, None + else: + pod = side_effect_function_pod( + contextual_transform, output_keys="out", data_context=custom_context + ) + assert isinstance(pod, FunctionPod) + fn, ctx_arg = contextual_transform, "ctx" + + leaf = cast( DataFunctionProtocol, cast( object, PythonDataFunction(fn, output_keys="out", data_context=custom_context), ), ) - expected = FunctionPod(data_function, ctx_arg_name=ctx_arg) - store = InMemoryArrowDatabase() - cache = InMemoryArrowDatabase() - if entry == "from_fn": - pod = FunctionPod.from_fn(fn, "out", data_context=custom_context) - elif entry == "from_config": - pod = FunctionPod.from_config(expected.to_config(), data_context=custom_context) - elif entry == "legacy": - pod = side_effect_function_pod( - fn, output_keys="out", data_context=custom_context - ) - assert isinstance(pod, FunctionPod) - else: - pod = function_pod( - output_keys="out", - data_context=custom_context, - ctx_arg=ctx_arg, - result_database=cache if entry == "data_cache" else None, - pod_cache_database=cache if entry == "pod_cache" else None, - )(fn).pod - - assert isinstance(pod, (FunctionPod, CachedFunctionPod)) - assert pod.data_context_key == custom_context.context_key - assert _identity(pod) == _identity(expected) - with pytest.raises(TypeError, match="No LogicalType or LogicalTypeFactory"): - FunctionPod.from_fn(fn, "out", data_context=contexts.get_default_context()) - - job = PipelineJob(name="custom_context", database=store) - with job: - source = DictSource([{"x": 2}], source_id="input", data_context=custom_context) - stream = pod.process(source, label="transformed") - assert stream.data_context_key == custom_context.context_key - - orchestrator = ( - AsyncPipelineOrchestrator() if async_run else SyncPipelineOrchestrator() - ) - job.run(orchestrator=orchestrator) - result_node = job.nodes["transformed"] - _, result = next(iter(result_node.iter_data())) - assert result.data_context_key == custom_context.context_key - value: object = result.as_dict()["out"] - assert isinstance(value, Result) and value.value == "3" - result_paths = [path for path in store.list_sources() if path[-1] == "rdb_v1"] - assert len(result_paths) == 1 - schema_hash = expected.data_function.uri[1] - expected_path_part = f"{schema_hash}:v0:ctx:ctx" if ctx_arg else schema_hash - assert expected_path_part in result_paths[0] - records = store.get_all_records(result_paths[0]) - assert records is not None - assert records["__data_context"].to_pylist() == [custom_context.context_key] - - if entry in ("data_cache", "pod_cache"): - tag, data = next(iter(source.iter_data())) - if entry == "data_cache": - assert isinstance(pod.data_function, CachedDataFunction) - cached_function = pod.data_function - path = cached_function.record_path - # Exercise the decorator cache directly, independently of the job cache. - cached_function.call(data) - hit = cached_function.call(data) - else: - assert isinstance(pod, CachedFunctionPod) - path = pod.record_path - pod.process_data(tag, data) - _, hit = pod.process_data(tag, data) - assert hit is not None - assert hit.data_context_key == custom_context.context_key - cached_value: object = hit.as_dict()["out"] - assert isinstance(cached_value, Result) and cached_value.value == "3" - cached_records = cache.get_all_records(path) - assert cached_records is not None - assert cached_records["__data_context"].to_pylist() == [ - custom_context.context_key - ] + explicit = FunctionPod(leaf, ctx_arg_name=ctx_arg, data_context=custom_context) + assert pod.data_context is custom_context + assert _identity(pod) == _identity(explicit) + source = DictSource([{"x": 1}], source_id="input", data_context=custom_context) + assert pod(source).data_context is custom_context -def test_explicit_context_must_agree_with_existing_function( +def test_ready_function_accepts_context_with_updated_metadata( custom_context: contexts.DataContext, ) -> None: - """Reject a mismatch before validating the schemas or building a cache.""" + """Keep accepting an explicit pod context with the same key and new metadata.""" function = cast( DataFunctionProtocol, cast( @@ -211,78 +136,81 @@ def test_explicit_context_must_agree_with_existing_function( ), ), ) - with pytest.raises(ValueError, match="pod's data context .* differs .* function"): - FunctionPod(function, data_context=contexts.get_default_context()) - pod = FunctionPod(function, data_context=custom_context) - with pytest.raises(ValueError, match="pod's data context .* differs .* function"): - CachedFunctionPod( - pod, InMemoryArrowDatabase(), data_context=contexts.get_default_context() - ) + pod_context = replace(custom_context, description="Updated description") + pod = FunctionPod(function, data_context=pod_context) + assert pod.data_context is pod_context -def test_loaders_pass_the_context(custom_context: contexts.DataContext) -> None: - """Data-function, wrapper, fall-through, and proxy loaders forward the context.""" - pod = FunctionPod.from_fn(transform, "out", data_context=custom_context) - config = pod.data_function.to_config() - restored = PythonDataFunction.from_config(config, data_context=custom_context) - assert restored.data_context is custom_context - cached_config_restore = CachedDataFunction.from_config( - config, data_context=custom_context - ) - assert isinstance(cached_config_restore, PythonDataFunction) - assert cached_config_restore.data_context is custom_context +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_custom_context_survives_persisted_job_cache( + orchestrator: type[SyncPipelineOrchestrator] | type[AsyncPipelineOrchestrator], + custom_context: contexts.DataContext, +) -> None: + """A fresh job reads the stored rows in the original context.""" + calls: list[int] = [] - fall_through = FallThroughPod(pod, ["group"]) - restored_fall_through = FallThroughPod.from_config( - fall_through.to_config(), data_context=custom_context - ) - assert _identity(restored_fall_through) == _identity(fall_through) - assert restored_fall_through.data_context is custom_context + def compute(x: int) -> Result: + calls.append(x) + return transform(x) - proxy_config = pod.to_config() - proxy_config["data_function"]["config"]["module_path"] = "unavailable_context_test" - proxy_config["data_function"]["config"]["output_data_schema"] = serialize_schema( - pod.data_function.output_data_schema, custom_context.type_converter - ) - proxy = FunctionPod.from_config( - proxy_config, fallback_to_proxy=True, data_context=custom_context - ) - assert proxy.data_context is custom_context - assert proxy.data_function.uri == pod.data_function.uri - assert ( - proxy.data_function.output_data_schema == pod.data_function.output_data_schema - ) + store = InMemoryArrowDatabase() + # Repeat the same source to hit the pipeline cache, then use a different + # source with the same values to hit the shared result cache by data hash. + for source_id, expected_calls in (("a", [2, 4, 8]), ("a", []), ("b", [])): + calls.clear() + job = PipelineJob(name="custom_context", database=store) + with job: + source = DictSource( + [{"x": x} for x in (2, 4, 8)], + source_id=source_id, + data_context=custom_context, + ) + FunctionPod.from_fn(compute, "out", data_context=custom_context)( + source, label="transformed" + ) + + job.run(orchestrator=orchestrator()) + rows = [data for _, data in job.nodes["transformed"].iter_data()] + assert sorted(calls) == expected_calls + assert [data.data_context_key for data in rows] == [ + custom_context.context_key + ] * 3 + values = [cast(Result, data.as_dict()["out"]).value for data in rows] + assert sorted(values) == ["3", "5", "9"] -@pytest.mark.parametrize("entry", [side_effect_pod, sink_pod, tap_pod]) -@pytest.mark.parametrize("async_run", [False, True], ids=["sync", "async"]) -def test_side_effect_decorators_forward_data_context( - entry: Any, async_run: bool, custom_context: contexts.DataContext +def test_tracked_side_effect_keeps_its_existing_log_context( + custom_context: contexts.DataContext, ) -> None: - """Side-effect pods use the supplied context for input and invocation log rows.""" + """A custom delivery context leaves the tracked node's log identity intact.""" seen: list[int] = [] def deliver(x: int, ctx: InvocationContext) -> None: seen.append(x) - pod = entry(data_context=custom_context)(deliver) - assert isinstance(pod, SideEffectPod) - assert pod.data_context is custom_context - - store = InMemoryArrowDatabase() - job = PipelineJob(name="side_effect_context", database=store) - with job: - source = DictSource([{"x": 4}], source_id="input", data_context=custom_context) - stream = pod.process(source, label="effect") - assert stream.data_context_key == custom_context.context_key - orchestrator = ( - AsyncPipelineOrchestrator() if async_run else SyncPipelineOrchestrator() + pod = SideEffectPod( + deliver, + config=SideEffectPodConfig(track_completion=True), + data_context=custom_context, ) - job.run(orchestrator=orchestrator) - assert seen == [4] - if pod.pod_config.track_completion: - paths = [path for path in store.list_sources() if "side_effects" in path] - assert len(paths) == 1 - rows = store.get_all_records(paths[0]) - assert rows is not None - assert rows["__data_context"].to_pylist() == [custom_context.context_key] + store = InMemoryArrowDatabase() + for expected_deliveries in ([2, 4, 8], []): + seen.clear() + job = PipelineJob(name="tracked_effect", database=store) + with job: + source = DictSource( + [{"x": x} for x in (2, 4, 8)], + source_id="input", + data_context=custom_context, + ) + pod(source, label="effect") + # The node uses the default hasher for its log path, as on main. + assert ( + job.nodes["effect"].data_context_key == contexts.get_default_context_key() + ) + job.run(orchestrator=AsyncPipelineOrchestrator()) + assert sorted(seen) == expected_deliveries + + assert len([path for path in store.list_sources() if path[-1] == "tdb_v2"]) == 1 diff --git a/tests/test_core/function_pod/test_write_side_registration.py b/tests/test_core/function_pod/test_write_side_registration.py index 276a7106b..9e8279bbe 100644 --- a/tests/test_core/function_pod/test_write_side_registration.py +++ b/tests/test_core/function_pod/test_write_side_registration.py @@ -15,6 +15,7 @@ from orcapod.contexts import get_default_context from orcapod.contexts.core import DataContext +from orcapod.core.data_function import PythonDataFunction from orcapod.core.function_pod import FunctionPod from orcapod.logical_types.protocols import LogicalTypeProtocol from orcapod.logical_types.registry import ( @@ -141,7 +142,10 @@ def test_pod_declaration_triggers_factory_for_input_type(): def my_func(x: _MyChild) -> str: return str(x) - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log assert registry.get_by_python_type(_MyChild) is not None @@ -154,7 +158,10 @@ def test_pod_declaration_triggers_factory_for_output_type(): def my_func(x: int) -> _MyChild: return _MyChild() - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log assert registry.get_by_python_type(_MyChild) is not None @@ -170,7 +177,10 @@ def test_pod_declaration_with_nested_list_input(): def my_func(items: list[_MyChild]) -> str: return "" - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log @@ -187,7 +197,10 @@ def test_pod_declaration_with_doubly_nested_input(): def my_func(mapping: dict[str, list[_MyChild]]) -> str: return "" - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log @@ -199,7 +212,10 @@ def test_pod_declaration_with_optional_input(): def my_func(x: Optional[_MyChild]) -> str: return "" - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log @@ -211,7 +227,10 @@ def test_pod_declaration_with_complex_output(): def my_func(x: str) -> list[_MyChild]: return [] - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log @@ -228,7 +247,10 @@ def test_pod_declaration_with_doubly_nested_output(): def my_func(x: int) -> dict[str, list[_MyChild]]: return {} - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log @@ -243,7 +265,10 @@ def test_pod_declaration_two_classes_one_in_input_one_in_output(): def my_func(x: _MyChild) -> _MyOtherChild: return _MyOtherChild() - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log assert _MyOtherChild in call_log @@ -256,7 +281,10 @@ def test_pod_declaration_two_classes_both_in_input(): def my_func(x: _MyChild, y: _MyOtherChild) -> str: return "" - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log assert _MyOtherChild in call_log @@ -269,7 +297,13 @@ def test_pod_declaration_two_classes_both_in_output(): def my_func(x: int) -> tuple[_MyChild, _MyOtherChild]: return _MyChild(), _MyOtherChild() - FunctionPod.from_fn(my_func, output_keys=["first", "second"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction( + my_func, + output_keys=["first", "second"], + ), + data_context=ctx, + ) assert _MyChild in call_log assert _MyOtherChild in call_log @@ -282,7 +316,10 @@ def test_pod_declaration_three_classes_mixed(): def my_func(a: _MyChild, b: list[_MyOtherChild]) -> _ThirdChild: return _ThirdChild() - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log assert _MyOtherChild in call_log assert _ThirdChild in call_log @@ -296,7 +333,10 @@ def test_pod_declaration_three_classes_all_in_input(): def my_func(a: _MyChild, b: _MyOtherChild, c: _ThirdChild) -> str: return "" - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log assert _MyOtherChild in call_log assert _ThirdChild in call_log @@ -324,7 +364,10 @@ def my_func(x: int, y: str) -> float: return 0.0 # Should not raise — int, str, float are native - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) def test_pod_declaration_raises_type_error_for_unhandled_class(): @@ -336,7 +379,10 @@ def my_func(x: _MyChild) -> str: return "" with pytest.raises(TypeError, match="No LogicalType or LogicalTypeFactory"): - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) def test_pod_declaration_raises_for_nested_unhandled_class(): @@ -348,7 +394,10 @@ def my_func(items: list[_MyChild]) -> str: return "" with pytest.raises(TypeError, match="No LogicalType or LogicalTypeFactory"): - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) def test_pod_declaration_already_registered_type_no_factory_call(): @@ -361,7 +410,10 @@ def test_pod_declaration_already_registered_type_no_factory_call(): def my_func(x: _MyChild) -> str: return "" - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) # Factory was NOT called — _MyChild was already registered assert _MyChild not in call_log @@ -380,6 +432,9 @@ def test_pod_declaration_with_union_none_syntax(): def my_func(x: _MyChild | None) -> str: return "" - FunctionPod.from_fn(my_func, output_keys=["result"], data_context=ctx) + FunctionPod( + data_function=PythonDataFunction(my_func, output_keys=["result"]), + data_context=ctx, + ) assert _MyChild in call_log assert registry.get_by_python_type(_MyChild) is not None From 81fac094860d3efd909158ce0b8628cd726c4988 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 13:23:51 -0800 Subject: [PATCH 5/5] fix(function-pod): limit context forwarding to factory construction --- changelog.d/ITL-1753.md | 2 +- docs/dev/design_issues/ITL-1753-FDC1.md | 5 +- src/orcapod/core/cached_function_pod.py | 8 +- src/orcapod/core/function_pod.py | 10 +- src/orcapod/core/nodes/function_node.py | 7 +- src/orcapod/core/nodes/source_node.py | 3 - src/orcapod/core/result_cache.py | 6 +- src/orcapod/pipeline/pod_invocation.py | 5 +- .../test_function_pod_data_context.py | 327 +++++++++++------- 9 files changed, 215 insertions(+), 158 deletions(-) diff --git a/changelog.d/ITL-1753.md b/changelog.d/ITL-1753.md index 985d29907..9be74f518 100644 --- a/changelog.d/ITL-1753.md +++ b/changelog.d/ITL-1753.md @@ -1,3 +1,3 @@ ### Fixed -- `FunctionPod.from_fn` and `side_effect_function_pod` now construct their data functions in the supplied data context. Function jobs read cached results in that context. +- `FunctionPod.from_fn` now uses the supplied data context for both the pod and its data function, matching explicit construction with `PythonDataFunction`. diff --git a/docs/dev/design_issues/ITL-1753-FDC1.md b/docs/dev/design_issues/ITL-1753-FDC1.md index d7df5d6b6..9f1e840a9 100644 --- a/docs/dev/design_issues/ITL-1753-FDC1.md +++ b/docs/dev/design_issues/ITL-1753-FDC1.md @@ -8,6 +8,5 @@ `FunctionPod.from_fn` passed its context only to the pod. The resulting data function used the default type converter and hashers for signatures, schemas, and result identities. -**Fix:** Forward the context when building the data function, including through -`side_effect_function_pod`. Preserve the live context through job compilation, -execution, and cached result reads. +**Fix:** Give the pod and its data function the same context in `FunctionPod.from_fn`, +matching explicit construction with `PythonDataFunction`. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 2eba3edd0..30c1d0570 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -200,9 +200,7 @@ def lookup_cached_data(self, data: DataProtocol) -> DataProtocol | None: The cached output ``Data`` (with ``RESULT_COMPUTED_FLAG=False`` appended), or ``None`` if no cached result exists for this input. """ - cached = self._cache.lookup( - data, data_context_key=self.data_context_key, data_context=self.data_context - ) + cached = self._cache.lookup(data, data_context_key=self.data_context_key) if cached is None: return None return cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) @@ -234,9 +232,7 @@ def process_data( A ``(tag, output_data)`` tuple; output_data is ``None`` if the inner function filters the data out. """ - cached = self._cache.lookup( - data, data_context_key=self.data_context_key, data_context=self.data_context - ) + cached = self._cache.lookup(data, data_context_key=self.data_context_key) if cached is not None: module_logger.info("Pod-level cache hit") cached = cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 92ea47fdd..973bc85d8 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -978,7 +978,7 @@ def from_fn( version: Version string (default ``"v0.0"``, as for every entry point). pod_config: Optional per-pod config. label: Optional display label. - data_context: Context for the pod and its data function. + data_context: Context for both the pod and its data function. **kwargs: Forwarded to ``_FunctionPodBase.__init__``. Returns: @@ -1033,7 +1033,6 @@ def process( function_pod=self, input_stream=input_stream, label=label, - data_context=self.data_context, ) return output_stream._mark_recorded(self.tracker_manager) @@ -2069,9 +2068,7 @@ def __init__( ) -> None: # if data_context is not explicitly given, use that of the contained pod if data_context is None: - data_context = getattr( - function_pod, "data_context", function_pod.data_context_key - ) + data_context = function_pod.data_context_key super().__init__( data_function=function_pod.data_function, data_context=data_context, @@ -2471,7 +2468,6 @@ def side_effect_function_pod( name: str | None = None, version: str = "v0.0", pod_config: PodConfig | None = None, - data_context: str | contexts.DataContext | None = None, ) -> "FunctionPod | Callable": """Decorator wrapping a callable as a ctx-aware ``FunctionPod``. @@ -2513,7 +2509,6 @@ def my_fn(value: int, ctx: InvocationContext) -> str: name: Optional canonical function name override. version: Version string for the data function (default ``"v0.0"``, as for every entry point). pod_config: Optional per-pod configuration. - data_context: Context for the pod and its data function. Returns: A ``FunctionPod`` with ``ctx_arg_name`` set, or a decorator if ``fn`` @@ -2531,7 +2526,6 @@ def decorator(func: Callable) -> FunctionPod: name=name, version=version, pod_config=pod_config, - data_context=data_context, ) update_wrapper(pod, func) return pod diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index b19132145..9facc8dc3 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -279,7 +279,7 @@ def _with_datagram_id(data: Data, datagram_id: uuid.UUID) -> Data: return Data( data.as_table(columns={"source": True}), record_uuid=datagram_id, - data_context=data.data_context, + data_context=data.data_context_key, ) @@ -554,10 +554,6 @@ def producer(self) -> FunctionPodProtocol: @property def data_context(self) -> contexts.DataContext: - if self._function_pod is not None: - context = getattr(self._function_pod, "data_context", None) - if context is not None: - return context return contexts.resolve_context(self.data_context_key) @property @@ -4167,7 +4163,6 @@ def _stored_rows_stream( without_tag_kind_marks(joined.drop(drop_cols)), tag_columns=self._stored_tag_keys(fetched), data_tags=fetched.data_tags, - data_context=self.data_context, ) return instance_ids, stream, data_ids diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 9bc030b02..2e1ec9911 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -2342,9 +2342,6 @@ def from_stream( data_schema=data_schema, arrow_schemas=typed_arrow_schemas(stream), bound_source=stream, - data_context=getattr( - stream, "data_context", stream.data_context_key - ), ) @classmethod diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 0b1853495..b4bfe48d4 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -39,7 +39,6 @@ ) if TYPE_CHECKING: - from orcapod.contexts import DataContext from orcapod.protocols.core_protocols.datagrams import DatagramProtocol logger = logging.getLogger(__name__) @@ -370,7 +369,6 @@ def lookup( additional_constraints: dict[str, Any] | None = None, *, data_context_key: str, - data_context: DataContext | None = None, ) -> DataProtocol | None: """Look up a cached output data for *input_data*. @@ -392,8 +390,6 @@ def lookup( for ``function_name``). data_context_key: Key of the caller's data context. Only rows written under it are matched, and the returned data carries it. - data_context: The caller's live context, if available, for decoding - the cached data without resolving its key through the registry. Returns: The cached output data with ``RESULT_COMPUTED_FLAG: False`` @@ -458,7 +454,7 @@ def lookup( result_table, record_uuid=record_uuid, meta_info={self.RESULT_COMPUTED_FLAG: False}, - data_context=data_context if data_context is not None else data_context_key, + data_context=data_context_key, ) def store( diff --git a/src/orcapod/pipeline/pod_invocation.py b/src/orcapod/pipeline/pod_invocation.py index b496ee7a3..acad141fe 100644 --- a/src/orcapod/pipeline/pod_invocation.py +++ b/src/orcapod/pipeline/pod_invocation.py @@ -84,10 +84,7 @@ def label(self) -> str | None: @property def _identity_hasher(self) -> SemanticHasherProtocol: """Use the same structural hasher as the node for this invocation.""" - context = getattr(self._pod, "data_context", None) - if context is None: - context = resolve_context(self._pod.data_context_key) - return context.semantic_hasher + return resolve_context(self._pod.data_context_key).semantic_hasher def _identity_inputs(self) -> tuple[StreamProtocol, ...]: """Return the recorded arguments in order.""" diff --git a/tests/test_core/function_pod/test_function_pod_data_context.py b/tests/test_core/function_pod/test_function_pod_data_context.py index 752687320..c23a98b29 100644 --- a/tests/test_core/function_pod/test_function_pod_data_context.py +++ b/tests/test_core/function_pod/test_function_pod_data_context.py @@ -2,7 +2,9 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import replace +from pathlib import Path from typing import Any, cast import pyarrow as pa @@ -10,19 +12,18 @@ from orcapod import FunctionPod, PipelineJob, contexts from orcapod.core.data_function import PythonDataFunction -from orcapod.core.function_pod import side_effect_function_pod +from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.databases import InMemoryArrowDatabase from orcapod.hashing.semantic_hashing.semantic_hasher import SemanticAwarePythonHasher -from orcapod.invocation import InvocationContext +from orcapod.errors import InputValidationError from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.registry import ( make_arrow_extension_type, make_polars_extension_type, ) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator -from orcapod.protocols.core_protocols import DataFunctionProtocol +from orcapod.protocols.core_protocols import DataFunctionProtocol, StreamProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter -from orcapod.side_effects import SideEffectPod, SideEffectPodConfig from orcapod.sources import DictSource @@ -76,141 +77,223 @@ def transform(x: int) -> Result: return Result(str(x + 1)) -def contextual_transform(x: int, ctx: InvocationContext) -> Result: - """Accept an injected context and produce a Result.""" - assert isinstance(ctx, InvocationContext) - return transform(x) +def increment(x: int) -> int: + """Return a value that works in every test context.""" + return x + 1 -def _identity( - pod: FunctionPod, -) -> tuple[object, ...]: - """Read the URI, signature hash, and both pod hashes through public methods.""" - return ( - pod.uri, - pod.data_function.get_function_variation_data()["function_signature_hash"], - pod.pipeline_hash(), - pod.content_hash(), +def _explicit(fn: Callable[[int], object], ctx: contexts.DataContext) -> FunctionPod: + """Construct the reference pod using the two public constructors.""" + leaf = cast( + DataFunctionProtocol, + cast(object, PythonDataFunction(fn, "y", data_context=ctx)), ) + return FunctionPod(leaf, data_context=ctx) -@pytest.mark.parametrize("entry", ["from_fn", "legacy"]) -def test_callable_construction_uses_custom_context( - entry: str, custom_context: contexts.DataContext -) -> None: - """Use the supplied converter and hasher when constructing the function.""" - if entry == "from_fn": - pod = FunctionPod.from_fn(transform, "out", data_context=custom_context) - fn, ctx_arg = transform, None - else: - pod = side_effect_function_pod( - contextual_transform, output_keys="out", data_context=custom_context - ) - assert isinstance(pod, FunctionPod) - fn, ctx_arg = contextual_transform, "ctx" +def _table_snapshot(table: pa.Table | None) -> object: + if table is None: + return None + return (str(table.schema), sorted(map(repr, table.to_pylist()))) - leaf = cast( - DataFunctionProtocol, - cast( - object, - PythonDataFunction(fn, output_keys="out", data_context=custom_context), - ), - ) - explicit = FunctionPod(leaf, ctx_arg_name=ctx_arg, data_context=custom_context) - assert pod.data_context is custom_context - assert _identity(pod) == _identity(explicit) - source = DictSource([{"x": 1}], source_id="input", data_context=custom_context) - assert pod(source).data_context is custom_context +def _rows(stream: StreamProtocol) -> object: + def value_repr(value: object) -> str: + return repr(value.value if isinstance(value, Result) else value) -def test_ready_function_accepts_context_with_updated_metadata( - custom_context: contexts.DataContext, -) -> None: - """Keep accepting an explicit pod context with the same key and new metadata.""" - function = cast( - DataFunctionProtocol, - cast( - object, - PythonDataFunction( - transform, output_keys="out", data_context=custom_context - ), - ), + return sorted( + ( + row.data_context_key, + sorted((key, value_repr(value)) for key, value in row.as_dict().items()), + ) + for _, row in stream.iter_data() ) - pod_context = replace(custom_context, description="Updated description") - pod = FunctionPod(function, data_context=pod_context) - assert pod.data_context is pod_context -@pytest.mark.parametrize( - "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] -) -def test_custom_context_survives_persisted_job_cache( - orchestrator: type[SyncPipelineOrchestrator] | type[AsyncPipelineOrchestrator], - custom_context: contexts.DataContext, -) -> None: - """A fresh job reads the stored rows in the original context.""" - calls: list[int] = [] - - def compute(x: int) -> Result: - calls.append(x) - return transform(x) - - store = InMemoryArrowDatabase() - # Repeat the same source to hit the pipeline cache, then use a different - # source with the same values to hit the shared result cache by data hash. - for source_id, expected_calls in (("a", [2, 4, 8]), ("a", []), ("b", [])): - calls.clear() - job = PipelineJob(name="custom_context", database=store) - with job: - source = DictSource( - [{"x": x} for x in (2, 4, 8)], - source_id=source_id, - data_context=custom_context, - ) - FunctionPod.from_fn(compute, "out", data_context=custom_context)( - source, label="transformed" - ) +def _routes( + pod: FunctionPod, source_context: contexts.DataContext, folder: Path +) -> dict[str, object]: + """Record public results or the existing context errors for each route.""" + observations: dict[str, object] = {} + + def observe(route: str, read: Callable[[], object]) -> None: + try: + observations[route] = read() + except ( + contexts.ContextResolutionError, + InputValidationError, + ValueError, + ) as exc: + observations[route] = (type(exc).__name__, str(exc)) + + def make_source( + source_id: str = "a", *, data_tag: bool = False, empty: bool = False + ) -> DictSource: + data = [{"x": x, "sample": str(x)} if data_tag else {"x": x} for x in (2, 4, 8)] + return DictSource( + [] if empty else data, + source_id=source_id, + tag_columns=["sample"] if data_tag else [], + data_schema={"x": int, "sample": str} if data_tag else {"x": int}, + data_context=source_context, + ) - job.run(orchestrator=orchestrator()) - rows = [data for _, data in job.nodes["transformed"].iter_data()] - assert sorted(calls) == expected_calls - assert [data.data_context_key for data in rows] == [ - custom_context.context_key - ] * 3 - values = [cast(Result, data.as_dict()["out"]).value for data in rows] - assert sorted(values) == ["3", "5", "9"] + def identity() -> object: + leaf = pod.data_function + assert isinstance(leaf, PythonDataFunction) + return ( + pod.data_context_key, + leaf.data_context_key, + str(pod.uri), + str(leaf.get_function_variation_data()["function_signature_hash"]), + str(pod.pipeline_hash()), + str(pod.content_hash()), + ) + def output_node(job: PipelineJob) -> FunctionJobNode: + node = job.nodes["out"] + assert isinstance(node, FunctionJobNode) + return node -def test_tracked_side_effect_keeps_its_existing_log_context( - custom_context: contexts.DataContext, -) -> None: - """A custom delivery context leaves the tracked node's log identity intact.""" - seen: list[int] = [] + observe("identity", identity) - def deliver(x: int, ctx: InvocationContext) -> None: - seen.append(x) + def record_stream(route: str, create: Callable[[], StreamProtocol]) -> None: + observe( + f"{route} identity", + lambda: ( + (stream := create()).data_context_key, + str(stream.pipeline_hash()), + str(stream.content_hash()), + ), + ) + observe(f"{route} rows", lambda: _rows(create())) + observe( + f"{route} table", + lambda: _table_snapshot(create().as_table(columns={"context": True})), + ) - pod = SideEffectPod( - deliver, - config=SideEffectPodConfig(track_completion=True), - data_context=custom_context, + record_stream("call", lambda: pod(make_source())) + record_stream("call with data-tag", lambda: pod(make_source(data_tag=True))) + record_stream( + "call with empty data-tag", lambda: pod(make_source(data_tag=True, empty=True)) ) - store = InMemoryArrowDatabase() - for expected_deliveries in ([2, 4, 8], []): - seen.clear() - job = PipelineJob(name="tracked_effect", database=store) - with job: - source = DictSource( - [{"x": x} for x in (2, 4, 8)], - source_id="input", - data_context=custom_context, + record_stream("process", lambda: pod.process(make_source())) + + folder.mkdir(parents=True, exist_ok=True) + for orchestrator in (SyncPipelineOrchestrator(), AsyncPipelineOrchestrator()): + mode = type(orchestrator).__name__ + store = InMemoryArrowDatabase() + + def make_job(source_id: str = "a") -> PipelineJob: + job = PipelineJob(name="parity", database=store) + with job: + _ = pod(make_source(source_id), label="out") + return job + + def record_job() -> None: + job = make_job() + node = output_node(job) + + def run(job: PipelineJob, *, load_only: bool = False) -> object: + summary = job.run(orchestrator=orchestrator, load_only=load_only) + out = summary.nodes["out"] + return (summary.ok, out.computed, out.reused, _rows(output_node(job))) + + observe(f"{mode} job", lambda: run(job)) + observe( + f"{mode} store", + lambda: ( + sorted(store.list_sources()), + _table_snapshot(node.get_all_records()), + ), + ) + observe(f"{mode} pipeline cache hit", lambda: run(make_job())) + observe(f"{mode} result cache hit", lambda: run(make_job("b"))) + observe(f"{mode} load-only", lambda: run(make_job(), load_only=True)) + observe(f"{mode} as_source rows", lambda: _rows(node.as_source())) + observe( + f"{mode} head", + lambda: ((view := node.head()).status, _table_snapshot(view.table)), ) - pod(source, label="effect") - # The node uses the default hasher for its log path, as on main. - assert ( - job.nodes["effect"].data_context_key == contexts.get_default_context_key() + + descriptor = folder / f"{mode}.json" + observe(f"{mode} save", lambda: job.save(descriptor)) + + def load() -> object: + loaded = output_node(PipelineJob.load(descriptor, database=store)) + return ( + loaded.data_context_key, + str(loaded.pipeline_hash()), + str(loaded.content_hash()), + _table_snapshot(loaded.get_all_records()), + ) + + observe(f"{mode} load", load) + observe( + f"{mode} loaded as_source rows", + lambda: _rows( + output_node( + PipelineJob.load(descriptor, database=store) + ).as_source() + ), + ) + + observe(f"{mode} compile", record_job) + + # A function node can also execute against a concrete source directly. This + # exercises stored custom rows even if compiling the source slot loses its context. + def record_direct_execution() -> None: + source = make_source() + store = InMemoryArrowDatabase() + job = PipelineJob(name="direct", database=store) + with job: + _ = pod(source, label="out") + node = output_node(job) + observe( + "direct node execute", + lambda: _rows(node.execute(source, error_policy="fail_fast")), + ) + observe("direct node store", lambda: _table_snapshot(node.get_all_records())) + observe("direct node as_source rows", lambda: _rows(node.as_source())) + observe( + "direct node as_source table", + lambda: _table_snapshot( + node.as_source().as_table(columns={"context": True}) + ), + ) + descriptor = folder / "direct.json" + job.save(descriptor) + observe( + "direct node loaded as_source rows", + lambda: _rows( + output_node(PipelineJob.load(descriptor, database=store)).as_source() + ), ) - job.run(orchestrator=AsyncPipelineOrchestrator()) - assert sorted(seen) == expected_deliveries - assert len([path for path in store.list_sources() if path[-1] == "tdb_v2"]) == 1 + observe("direct node compile and save", record_direct_execution) + return observations + + +def test_from_fn_matches_explicit_construction( + custom_context: contexts.DataContext, tmp_path: Path +) -> None: + """Match the explicit pod across public routes, including existing context errors.""" + default = contexts.get_default_context() + for case, fn, pod_context, source_context in ( + ("custom", transform, custom_context, custom_context), + ("default", increment, default, default), + ("mixed", increment, default, custom_context), + ): + factory = FunctionPod.from_fn(fn, "y", data_context=pod_context) + explicit = _explicit(fn, pod_context) + assert factory.data_context is pod_context + actual = _routes(factory, source_context, tmp_path / case / "factory") + expected = _routes(explicit, source_context, tmp_path / case / "explicit") + assert actual == expected, case + if case in ("default", "mixed"): + assert actual["SyncPipelineOrchestrator job"] == ( + True, + 3, + 0, + [(default.context_key, [("y", str(y))]) for y in (3, 5, 9)], + )