diff --git a/changelog.d/ITL-1753.md b/changelog.d/ITL-1753.md new file mode 100644 index 000000000..9be74f518 --- /dev/null +++ b/changelog.d/ITL-1753.md @@ -0,0 +1,3 @@ +### Fixed + +- `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 new file mode 100644 index 000000000..9f1e840a9 --- /dev/null +++ b/docs/dev/design_issues/ITL-1753-FDC1.md @@ -0,0 +1,12 @@ +## `src/orcapod/core/function_pod.py` + +### 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. The resulting data function +used the default type converter and hashers for signatures, schemas, and result identities. + +**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/function_pod.py b/src/orcapod/core/function_pod.py index c435be059..973bc85d8 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -958,6 +958,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 +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 both the pod and its data function. **kwargs: Forwarded to ``_FunctionPodBase.__init__``. Returns: @@ -988,12 +990,14 @@ 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, pod_config=pod_config, ctx_arg_name=ctx_arg_name, label=label, + data_context=data_context, **kwargs, ) 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..c23a98b29 --- /dev/null +++ b/tests/test_core/function_pod/test_function_pod_data_context.py @@ -0,0 +1,299 @@ +"""Function pod entry points use the same data context for identity and execution.""" + +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 +import pytest + +from orcapod import FunctionPod, PipelineJob, contexts +from orcapod.core.data_function import PythonDataFunction +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.databases import InMemoryArrowDatabase +from orcapod.hashing.semantic_hashing.semantic_hasher import SemanticAwarePythonHasher +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, StreamProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +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 increment(x: int) -> int: + """Return a value that works in every test context.""" + return x + 1 + + +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) + + +def _table_snapshot(table: pa.Table | None) -> object: + if table is None: + return None + return (str(table.schema), sorted(map(repr, table.to_pylist()))) + + +def _rows(stream: StreamProtocol) -> object: + def value_repr(value: object) -> str: + return repr(value.value if isinstance(value, Result) else value) + + 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() + ) + + +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, + ) + + 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 + + observe("identity", identity) + + 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})), + ) + + 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)) + ) + 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)), + ) + + 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() + ), + ) + + 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)], + )