diff --git a/changelog.d/ITL-1254.md b/changelog.d/ITL-1254.md new file mode 100644 index 000000000..fa0fd88e6 --- /dev/null +++ b/changelog.d/ITL-1254.md @@ -0,0 +1,13 @@ +### Breaking changes and migration + +- Functions with several output keys must return an instance of the annotated + container. If a function annotated with a tuple type currently returns a list, + return a tuple with the values in `output_keys` order. Functions that declare + several outputs through `output_schema` without a return annotation must also + return a tuple (ITL-1254). + +### Fixed + +- A function pod that returns a dictionary for a tuple annotation raises + `OutputContainerTypeError` before assigning any values. Previously, the pod + could silently store the dictionary's keys as its outputs (ITL-1254). diff --git a/docs/api/errors.md b/docs/api/errors.md index 868877c42..cd53180f1 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -70,6 +70,8 @@ These exceptions and warnings report problems running pipelines, processing rows ::: orcapod.errors.OutputTypeError +::: orcapod.errors.OutputContainerTypeError + ::: orcapod.errors.NoOutputsDeclaredError ::: orcapod.errors.RowFailuresWarning diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 8eefc68f2..3a758b6fe 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -23,7 +23,12 @@ def compute_bmi(weight: float, height: float) -> float: Key points: - **`output_keys`** names the output data column(s). A single string means one output - column; a list of strings means the function returns multiple values. A function with + column. With two or more keys, Orcapod assigns returned values in key order. The + returned container must be an instance of the annotated container, so + `-> tuple[int, str]` accepts a tuple or a named tuple. Each position needs a + declared type, so `list[int]` cannot declare several outputs. If you supply + `output_schema` without a return annotation, return a tuple. A container mismatch + raises `OutputContainerTypeError` before any outputs are stored. A function with no outputs (it only reads its inputs) is annotated `-> None`, or not annotated, and takes no `output_keys`; its pod has no output columns. `-> None` together with `output_keys` raises `ValueError` when the pod is created, and a value other than diff --git a/docs/dev/design_issues/ITL-1254-OC1.md b/docs/dev/design_issues/ITL-1254-OC1.md new file mode 100644 index 000000000..56714972d --- /dev/null +++ b/docs/dev/design_issues/ITL-1254-OC1.md @@ -0,0 +1,15 @@ +## `src/orcapod/core/data_function.py` — returned values not checked against the declared type + +### OC1 — Multiple outputs were unpacked from the wrong return container +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1254 + +When a function declared several outputs, the parser iterated any returned +iterable. A dictionary returned for a tuple annotation yielded its keys, which +could be stored silently when the declared output types were strings. + +**Fix:** The output parser checks the returned container against the annotation +before unpacking. Functions that declare several outputs through `output_schema` +without a return annotation must return a tuple. A mismatch raises +`OutputContainerTypeError` with the function name, the returned type and the remedy. diff --git a/docs/tutorial/02-function-pods.md b/docs/tutorial/02-function-pods.md index 3473e1cc4..c51315d22 100644 --- a/docs/tutorial/02-function-pods.md +++ b/docs/tutorial/02-function-pods.md @@ -125,7 +125,10 @@ print(units.drop_data_columns(["region", "n_spikes"]).keys()) ## Returning more than one output -Give `output_keys` a list, return a tuple, and annotate the return type as a tuple: +Give `output_keys` a list and annotate one tuple element per key. Return a tuple +or a tuple subclass, such as a named tuple, with the values in the same order +as the keys. A list or dictionary returned for a tuple annotation raises +`OutputContainerTypeError` before any values are stored. ```python @function_pod(output_keys=["depth_mm", "layer"]) diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index c88e74337..7fd1200b0 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -30,6 +30,7 @@ from orcapod.core.result_cache import ResultCache from orcapod.errors import ( NoOutputsDeclaredError, + OutputContainerTypeError, OutputTypeError, UnstorableDatetimeError, ) @@ -37,6 +38,7 @@ from orcapod.protocols.core_protocols.executor import ( DataFunctionExecutorProtocol, PythonFunctionExecutorProtocol, + PythonFunctionReturnCheckProtocol, ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.semantic_types.output_conformance import ( @@ -47,6 +49,10 @@ from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names from orcapod.utils.git_utils import get_git_info_for_python_object +from orcapod.utils.output_containers import ( + UnexpectedOutputContainer, + output_container_mismatch, +) from orcapod.utils.tensor_conversions import describe, tensor_conversions, warn_once from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol @@ -79,7 +85,7 @@ def _get_sync_executor(): def parse_function_outputs( - output_keys: Sequence[str], values: Any + output_keys: Sequence[str], values: Any, return_container: type = tuple ) -> dict[str, DataValue]: """ Map raw function return values to a keyed output dict. @@ -89,30 +95,30 @@ def parse_function_outputs( returned value other than ``None`` before this is called (ITL-1257). - ``output_keys = ["result"]``: any value (including iterables) is stored as-is under the single key. - - ``output_keys = ["a", "b", ...]``: ``values`` must be iterable and its length - must match the number of keys. + - ``output_keys = ["a", "b", ...]``: ``values`` must match the declared container + and hold one value per key. Args: output_keys: Ordered list of output key names. values: Raw return value from the function. + return_container: Runtime type required for several outputs. Returns: Dict mapping each output key to its corresponding value. Raises: - ValueError: If ``values`` is not iterable when multiple keys are given, or if - the number of values does not match the number of keys. + UnexpectedOutputContainer: If the value is not an accepted output container. + ValueError: If the number of values does not match the number of keys. """ if len(output_keys) == 0: output_values: list[Any] = [] elif len(output_keys) == 1: output_values = [values] - elif isinstance(values, Iterable): - output_values = list(values) else: - raise ValueError( - "Values returned by function must be sequence-like if multiple output keys are specified" - ) + returned_type = output_container_mismatch(values, return_container) + if returned_type is not None: + raise UnexpectedOutputContainer(returned_type) + output_values = list(values) if len(output_values) != len(output_keys): raise ValueError( @@ -848,7 +854,12 @@ def __init__( ) # extract input and output schema from the function signature - self._input_schema, self._output_schema = schema_utils.extract_function_schemas( + ( + self._input_schema, + self._output_schema, + self._return_container, + self._container_annotation, + ) = schema_utils.extract_function_schemas_with_container( self._function, self._output_keys, input_typespec=input_schema, @@ -999,7 +1010,12 @@ def _build_output_data(self, values: Any) -> DataProtocol: # No output keys declare an empty return (ITL-1257): a returned value # contradicts the declaration and is refused, never dropped. raise NoOutputsDeclaredError(self.canonical_function_name, values) - output_data = parse_function_outputs(self._output_keys, values) + try: + output_data = parse_function_outputs( + self._output_keys, values, self._return_container + ) + except UnexpectedOutputContainer as exc: + raise self._output_container_error(exc) from exc output_schema = self.output_data_schema for key, value in output_data.items(): mismatch = check_conformance( @@ -1060,6 +1076,25 @@ def _build_output_data(self, values: Any) -> DataProtocol: data_context=self.data_context, ) + def _output_container_error( + self, error: UnexpectedOutputContainer + ) -> OutputContainerTypeError: + """Attach the function and its declaration to a container mismatch.""" + return OutputContainerTypeError( + self.canonical_function_name, + error.returned_type, + self._return_container, + self._container_annotation, + ) + + def _executor_return_options(self) -> dict[str, object] | None: + """Request a container check from an executor that can check before transport.""" + if len(self._output_keys) > 1 and isinstance( + self._executor, PythonFunctionReturnCheckProtocol + ): + return self._executor.return_container_options(self._return_container) + return None + def _convert_outputs( self, output_data: dict[str, DataValue], output_schema: Schema ) -> pa.Table: @@ -1173,9 +1208,15 @@ def call( if self._executor is not None: if not self._active: return None - raw = self._executor.execute_callable( - self._function, {**data.as_dict(), **kwargs}, logger=logger - ) + try: + raw = self._executor.execute_callable( + self._function, + {**data.as_dict(), **kwargs}, + executor_options=self._executor_return_options(), + logger=logger, + ) + except UnexpectedOutputContainer as exc: + raise self._output_container_error(exc) from exc return self._build_output_data(raw) if logger is not None: import warnings @@ -1198,9 +1239,15 @@ async def async_call( if self._executor is not None: if not self._active: return None - raw = await self._executor.async_execute_callable( - self._function, {**data.as_dict(), **kwargs}, logger=logger - ) + try: + raw = await self._executor.async_execute_callable( + self._function, + {**data.as_dict(), **kwargs}, + executor_options=self._executor_return_options(), + logger=logger, + ) + except UnexpectedOutputContainer as exc: + raise self._output_container_error(exc) from exc return self._build_output_data(raw) if logger is not None: import warnings diff --git a/src/orcapod/core/executors/capture_wrapper.py b/src/orcapod/core/executors/capture_wrapper.py index af3b94c3b..8894ce2de 100644 --- a/src/orcapod/core/executors/capture_wrapper.py +++ b/src/orcapod/core/executors/capture_wrapper.py @@ -11,6 +11,11 @@ from collections.abc import Callable from typing import Any +from orcapod.utils.output_containers import output_container_mismatch + + +CaptureResponse = tuple[Any, str, str, str] | tuple[None, str, str, str, str] + def make_capture_wrapper(name: str | None = None) -> Callable[..., Any]: """Return a capture wrapper suitable for remote execution. @@ -23,6 +28,9 @@ def make_capture_wrapper(name: str | None = None) -> Callable[..., Any]: On success the wrapper returns a 4-tuple ``(raw_result, stdout_log, stderr_log, python_logs)``. + If a declared return container does not match, it returns a 5-tuple + ``(None, stdout_log, stderr_log, python_logs, returned_type)`` so the driver + can report the mismatch without serializing the invalid value. On failure the wrapper **raises** a ``_CapturedTaskError`` that carries the captured I/O alongside the original exception. This lets the remote @@ -30,7 +38,11 @@ def make_capture_wrapper(name: str | None = None) -> Callable[..., Any]: while still delivering captured output to the driver. """ - def _capture(fn: Any, kwargs: dict) -> tuple: + check_container = output_container_mismatch + + def _capture( + fn: Any, kwargs: dict[str, Any], return_container: type | None = None + ) -> CaptureResponse: import asyncio import inspect import io @@ -89,6 +101,7 @@ def emit(self, record: logging.LogRecord) -> None: root_logger.addHandler(handler) raw_result = None + returned_type = None exc_info: tuple | None = None try: sys.stdout.flush() @@ -99,13 +112,17 @@ def emit(self, record: logging.LogRecord) -> None: sys.stderr = sys_stderr_buf try: result = fn(**kwargs) - # If fn is async, run the returned coroutine to completion. - # asyncio.run() is safe here: Ray workers run in fresh - # processes with no existing event loop. - if inspect.iscoroutine(result): + # When checking a declared container, await only coroutine + # functions, as the local executor does. A coroutine returned + # by a synchronous function is itself the value to validate. + if inspect.iscoroutine(result) and ( + return_container is None or inspect.iscoroutinefunction(fn) + ): raw_result = asyncio.run(result) else: raw_result = result + if return_container is not None: + returned_type = check_container(raw_result, return_container) except Exception as e: exc_info = (e, _tb.format_exc()) finally: @@ -141,6 +158,8 @@ def emit(self, record: logging.LogRecord) -> None: tb=exc_info[1], ) from exc_info[0] + if returned_type is not None: + return None, cap_stdout, cap_stderr, python_logs, returned_type return raw_result, cap_stdout, cap_stderr, python_logs if name is not None: diff --git a/src/orcapod/core/executors/ray.py b/src/orcapod/core/executors/ray.py index 28ce7ce50..d9d0eef37 100644 --- a/src/orcapod/core/executors/ray.py +++ b/src/orcapod/core/executors/ray.py @@ -3,12 +3,13 @@ import asyncio import threading from collections.abc import Callable -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from orcapod.core.data_function import PYTHON_FUNCTION from orcapod.core.executors.base import PythonFunctionExecutorBase from orcapod.types import Schema -from orcapod.core.executors.capture_wrapper import make_capture_wrapper +from orcapod.core.executors.capture_wrapper import CaptureResponse, make_capture_wrapper +from orcapod.utils.output_containers import UnexpectedOutputContainer if TYPE_CHECKING: from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol @@ -170,6 +171,10 @@ def _build_remote_opts(self) -> dict[str, Any]: """Return a copy of the Ray remote options dict.""" return dict(self._remote_opts) + def return_container_options(self, container: type) -> dict[str, object]: + """Request that the Ray worker check the output container before transport.""" + return {"return_container": container} + def execute_callable( self, fn: Callable[..., Any], @@ -188,23 +193,24 @@ def execute_callable( propagates via ``RayTaskError``. The driver extracts the captured I/O, records it to *logger*, and re-raises the **original** user exception so that Ray's error handling (retries, etc.) is not disrupted. + + If the executor options request a container check, the worker checks + the result before serializing it and the driver reports a mismatch. """ import ray - self._ensure_ray_initialized() - remote_fn = self._get_remote_fn(ray, fn.__name__) - ref = remote_fn.options(name=fn.__name__).remote(fn, kwargs) + ref = self._submit_callable(ray, fn, kwargs, executor_options) try: - raw, stdout_log, stderr_log, python_logs = ray.get(ref) + # This is one reference to a capture-wrapper response. + response = cast(CaptureResponse, cast(object, ray.get(ref))) except Exception as exc: handled = self._handle_worker_error(exc, logger) if handled is exc: raise raise handled from exc - self._record_success(stdout_log, stderr_log, python_logs, logger) - return raw + return self._read_response(response, logger) async def async_execute_callable( self, @@ -217,24 +223,44 @@ async def async_execute_callable( """Async counterpart of `execute_callable`.""" import ray - self._ensure_ray_initialized() - remote_fn = self._get_remote_fn(ray, fn.__name__) - ref = remote_fn.options(name=fn.__name__).remote(fn, kwargs) + ref = self._submit_callable(ray, fn, kwargs, executor_options) try: # In Ray client mode (ray://) ClientObjectRef.future() returns a # concurrent.futures.Future which cannot be directly awaited. # asyncio.wrap_future() handles both Future types correctly. - raw, stdout_log, stderr_log, python_logs = await asyncio.wrap_future( - ref.future() - ) + response = await asyncio.wrap_future(ref.future()) except Exception as exc: handled = self._handle_worker_error(exc, logger) if handled is exc: raise raise handled from exc + return self._read_response(response, logger) + + def _submit_callable( + self, + ray: Any, + fn: Callable[..., Any], + kwargs: dict[str, Any], + executor_options: dict[str, Any] | None, + ) -> Any: + """Dispatch the capture wrapper with the optional return check.""" + self._ensure_ray_initialized() + remote_fn = self._get_remote_fn(ray, fn.__name__).options(name=fn.__name__) + return_container = (executor_options or {}).get("return_container") + if return_container is None: + return remote_fn.remote(fn, kwargs) + return remote_fn.remote(fn, kwargs, return_container) + + def _read_response( + self, response: CaptureResponse, logger: DataExecutionLoggerProtocol | None + ) -> Any: + """Record captured I/O and decode the worker's result or container mismatch.""" + raw, stdout_log, stderr_log, python_logs, *mismatch = response self._record_success(stdout_log, stderr_log, python_logs, logger) + if mismatch: + raise UnexpectedOutputContainer(mismatch[0]) return raw def _get_remote_fn(self, ray: Any, fn_name: str) -> Any: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a00e171ed..23f8dd2af 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -429,11 +429,11 @@ class OutputTypeError(TypeError, ValueError): Attributes: function_name: Name of the function pod's function. - output_key: Name of the output column; ``None`` for ``NoOutputsDeclaredError`` - (the function declares no output). - declared_type: The declared type of that output; ``None`` for - ``NoOutputsDeclaredError``. - value: The value the function returned for that output. + output_key: Name of the output column, or ``None`` if the error concerns + the whole return. + declared_type: The declared type of the output or the whole return, if annotated. + value: The value the function returned for that output. Container mismatches + retain only the returned type's name. detail: Where inside the value the mismatch is, when that is not the whole value; ``None`` otherwise. hint: What the function should return instead, when there is a specific fix. @@ -491,6 +491,72 @@ def __reduce__(self) -> tuple[object, ...]: ) +class OutputContainerTypeError(OutputTypeError): + """A function with multiple output keys returned the wrong container (ITL-1254). + + The mismatch applies to the whole return, before individual outputs are selected. + Only the returned type is retained, since the invalid value may be a generator or + another object that cannot cross an executor boundary. + + Attributes: + returned_type: Display name of the returned value's type. + return_container: Runtime type required for the returned value. + """ + + def __init__( + self, + function_name: str, + returned_type: str, + return_container: type, + annotation: object | None, + ) -> None: + """Create the error for the returned container. + + Args: + function_name: Name of the function pod's function. + returned_type: Display name of the returned value's type. + return_container: Runtime type required for the returned value. + annotation: Declared return annotation, or None if there is none. + """ + self.function_name = function_name + self.output_key = None + self.declared_type = annotation + self.value = None + self.detail = None + self.returned_type = returned_type + self.return_container = return_container + container = type_text(return_container) + target = ( + f"a {container}" + if return_container in (tuple, list) + else f"an instance of {container}" + ) + hint = f"Return {target} with one value per output key, in the order of output_keys" + if annotation is None: + declaration = "has no return annotation" + hint += ", or annotate the return type" + else: + declaration = f"declares {type_text(annotation)}" + self.hint = hint + TypeError.__init__( + self, + f"Function {function_name!r} returned {returned_type} for multiple " + f"output keys and {declaration}. {self.hint}.", + ) + + def __reduce__(self) -> tuple[object, ...]: + """Pickle the diagnostic without serializing the invalid returned value.""" + return ( + type(self), + ( + self.function_name, + self.returned_type, + self.return_container, + self.declared_type, + ), + ) + + class NoOutputsDeclaredError(OutputTypeError): """A function that declares no outputs returned a value (ITL-1257). diff --git a/src/orcapod/protocols/core_protocols/executor.py b/src/orcapod/protocols/core_protocols/executor.py index 5927e39e8..b05e2e7f8 100644 --- a/src/orcapod/protocols/core_protocols/executor.py +++ b/src/orcapod/protocols/core_protocols/executor.py @@ -123,3 +123,12 @@ async def async_execute_callable( The raw return value of *fn*. """ ... + + +@runtime_checkable +class PythonFunctionReturnCheckProtocol(Protocol): + """Optional executor capability for checking returns before serialization.""" + + def return_container_options(self, container: type) -> dict[str, object]: + """Return per-call options that request a check against the given type.""" + ... diff --git a/src/orcapod/utils/output_containers.py b/src/orcapod/utils/output_containers.py new file mode 100644 index 000000000..85664acc6 --- /dev/null +++ b/src/orcapod/utils/output_containers.py @@ -0,0 +1,38 @@ +"""Shared container checks for positional function outputs.""" + +from collections.abc import Callable, Mapping + + +EXCLUDED_OUTPUT_CONTAINERS = (Mapping, str, bytes, bytearray) + + +def _make_output_container_check() -> Callable[[object, type], str | None]: + """Build a check that cloudpickle can send to a worker without imports.""" + excluded = EXCLUDED_OUTPUT_CONTAINERS + + def check(value: object, container: type) -> str | None: + if isinstance(value, container) and not isinstance(value, excluded): + return None + returned = type(value) + if returned.__module__ in ("builtins", "__main__"): + return returned.__qualname__ + return f"{returned.__module__}.{returned.__qualname__}" + + return check + + +output_container_mismatch = _make_output_container_check() +"""Return the type name of an invalid output container, or None on success.""" + + +class UnexpectedOutputContainer(ValueError): + """Report the returned type without retaining an invalid value.""" + + def __init__(self, returned_type: str) -> None: + """Record the name of the returned container type. + + Args: + returned_type: Display name of the value's type. + """ + self.returned_type = returned_type + super().__init__(f"Unexpected output container type {returned_type}") diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index f0322d3f2..419a7b9cc 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -11,6 +11,7 @@ from orcapod.errors import InputValidationError from orcapod.types import ContentHash, Schema, SchemaLike +from orcapod.utils.output_containers import EXCLUDED_OUTPUT_CONTAINERS logger = logging.getLogger(__name__) @@ -161,6 +162,29 @@ def extract_function_schemas( input_typespec: SchemaLike | None = None, output_typespec: SchemaLike | Sequence[type] | None = None, ) -> tuple[Schema, Schema]: + """Extract the input and output schemas of a function. + + Args: + func: Function whose signature supplies inferred types. + output_keys: Output column names in return order. + input_typespec: Overrides for inferred parameter types. + output_typespec: Overrides for inferred output types. + + Returns: + The input and output schemas. + """ + inputs, outputs, _, _ = extract_function_schemas_with_container( + func, output_keys, input_typespec, output_typespec + ) + return inputs, outputs + + +def extract_function_schemas_with_container( + func: Callable[..., object], + output_keys: Collection[str], + input_typespec: SchemaLike | None = None, + output_typespec: SchemaLike | Sequence[type] | None = None, +) -> tuple[Schema, Schema, type, object | None]: """ Extract input and output data types from a function signature. @@ -174,11 +198,11 @@ def extract_function_schemas( return values. For functions returning a single value, provide a single key. For functions returning multiple values (tuple/list), provide keys matching the number of return items. - input_types: Optional mapping of parameter names to their types. If provided, + input_typespec: Optional mapping of parameter names to their types. If provided, these types override any type annotations in the function signature for the specified parameters. If a parameter is not in this mapping and has no annotation, an error is raised. - output_types: Optional type specification for return values. Can be either: + output_typespec: Optional type specification for return values. Can be either: - A dict mapping output keys to types (TypeSpec) - A sequence of types that will be mapped to output_keys in order These types override any inferred types from the function's return annotation. @@ -187,6 +211,8 @@ def extract_function_schemas( A tuple containing: - input_types_dict: Mapping of parameter names to their inferred/specified types - output_types_dict: Mapping of output keys to their inferred/specified types + - return_container: Runtime type required for several outputs, defaulting to tuple. + - container_annotation: Resolved annotation for several outputs, if provided. Raises: ValueError: In various scenarios: @@ -202,41 +228,43 @@ def extract_function_schemas( Examples: >>> def add(x: int, y: int) -> int: ... return x + y - >>> input_types, output_types = extract_function_data_types(add, ['result']) - >>> input_types + >>> input_types, output_types = extract_function_schemas(add, ['result']) + >>> dict(input_types) {'x': , 'y': } - >>> output_types + >>> dict(output_types) {'result': } >>> def process(data: str) -> tuple[int, str]: ... return len(data), data.upper() - >>> input_types, output_types = extract_function_data_types( - ... process, ['length', 'upper_data'] + >>> input_types, output_types, container, annotation = ( + ... extract_function_schemas_with_container(process, ['length', 'upper_data']) ... ) - >>> input_types + >>> dict(input_types) {'data': } - >>> output_types + >>> dict(output_types) {'length': , 'upper_data': } + >>> container is tuple and annotation == tuple[int, str] + True >>> def legacy_func(x, y): # No annotations ... return x + y - >>> input_types, output_types = extract_function_data_types( + >>> input_types, output_types = extract_function_schemas( ... legacy_func, ['sum'], - ... input_types={'x': int, 'y': int}, - ... output_types={'sum': int} + ... input_typespec={'x': int, 'y': int}, + ... output_typespec={'sum': int} ... ) - >>> input_types + >>> dict(input_types) {'x': , 'y': } - >>> output_types + >>> dict(output_types) {'sum': } - >>> def multi_return(data: list) -> tuple[int, float, str]: + >>> def multi_return(data: list[float]) -> tuple[int, float, str]: ... return len(data), sum(data), str(data) - >>> input_types, output_types = extract_function_data_types( + >>> input_types, output_types = extract_function_schemas( ... multi_return, ['count', 'total', 'repr'], - ... output_types=[int, float, str] # Override with sequence + ... output_typespec=[int, float, str] # Override with sequence ... ) - >>> output_types + >>> dict(output_types) {'count': , 'total': , 'repr': } """ verified_output_types: Schema = {} @@ -284,6 +312,8 @@ def extract_function_schemas( # None: the number of outputs is the number of output keys. if _declares_none(return_annot): return_annot = None + return_container: type = tuple + container_annotation = None inferred_output_types: Schema = {} if return_annot is not inspect.Signature.empty and return_annot is not None: output_item_types = [] @@ -294,25 +324,28 @@ def extract_function_schemas( elif len(output_keys) == 1: # if only one return key, the entire annotation is inferred as the return type output_item_types = [return_annot] - elif get_origin(return_annot) in (tuple, list) or ( - isinstance(get_origin(return_annot), type) - and issubclass(get_origin(return_annot), Sequence) - ): - if get_origin(return_annot) is None: - # right type was specified but did not specify the type of items + else: + origin = get_origin(return_annot) + if isinstance(origin, type) and issubclass( + origin, EXCLUDED_OUTPUT_CONTAINERS + ): raise ValueError( - f"Function return type annotation {return_annot} is a Sequence type but does not specify item types." + f"Function return type annotation {return_annot} cannot declare " + "multiple outputs. Use tuple[T1, T2, ...] or a supported " + "sequence annotation with one type per output key." ) + if not isinstance(origin, type) or not issubclass(origin, Sequence): + raise ValueError( + f"Multiple return keys were specified but return type annotation {return_annot} is not a sequence type (list, tuple, Collection)." + ) + return_container = origin + container_annotation = return_annot output_item_types = get_args(return_annot) if len(output_item_types) != len(output_keys): raise ValueError( f"Function return type annotation {return_annot} has {len(output_item_types)} items, " f"but output_keys has {len(output_keys)} items." ) - else: - raise ValueError( - f"Multiple return keys were specified but return type annotation {return_annot} is not a sequence type (list, tuple, Collection)." - ) for key, type_annot in zip(output_keys, output_item_types): inferred_output_types[key] = type_annot elif return_annot is None: @@ -350,8 +383,11 @@ def extract_function_schemas( f"without type parameters. Use e.g. {example} instead." ) - return Schema(param_info, optional_fields=optional_params), Schema( - inferred_output_types + return ( + Schema(param_info, optional_fields=optional_params), + Schema(inferred_output_types), + return_container, + container_annotation, ) diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index 6a2f0b549..8a2d83621 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -17,16 +17,19 @@ from __future__ import annotations +import asyncio import collections import datetime as dt import enum import types import warnings +from abc import ABCMeta +from collections.abc import Sequence from dataclasses import dataclass from decimal import Decimal from fractions import Fraction from pathlib import Path -from typing import Any, Literal, cast +from typing import Any, Literal, NamedTuple, cast import numpy as np import pytest @@ -34,7 +37,9 @@ from pydantic import BaseModel from orcapod import PipelineJob, errors, function_pod +from orcapod.core.data_function import PythonDataFunction from orcapod.core.datagrams import Data +from orcapod.core.function_pod import FunctionPod from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver @@ -269,6 +274,225 @@ def on_data_crash(self, node_label: Any, tag: Any, data: Any, error: Any) -> Non self.crashes.append(error) +def _multi_output_function( + annotation: object, returned: object, *, asynchronous: bool = False +) -> types.FunctionType: + """Build a function with the requested annotation and runtime return value.""" + + def invalid_container(x: int, y: str) -> object: + return returned + + async def async_invalid_container(x: int, y: str) -> object: + return returned + + fn = async_invalid_container if asynchronous else invalid_container + if annotation is None: + del fn.__annotations__["return"] + else: + fn.__annotations__["return"] = annotation + return fn + + +class _NamedOutputs(NamedTuple): + sample_count: int + rate: float + + +_TWO_TEXT = ("first", "second") +_THREE_NUMBERS = ("third", "first", "second") +# The schema extractor already accepts a runtime alias with one type per key. +# A standard list[T] cannot declare the positions of several outputs. +_POSITIONAL_LIST = types.GenericAlias(list, (int, float)) +_POSITIONAL_SEQUENCE = types.GenericAlias(Sequence, (int, int)) + + +@pytest.mark.parametrize( + ("annotation", "returned", "keys"), + [ + pytest.param( + tuple[str, str], {"first": "a", "second": "b"}, _TWO_TEXT, id="dict" + ), + pytest.param(tuple[str, str], {"a", "b"}, _TWO_TEXT, id="set"), + pytest.param(tuple[str, str], frozenset({"a", "b"}), _TWO_TEXT, id="frozenset"), + pytest.param(tuple[str, str], "ab", _TWO_TEXT, id="str"), + pytest.param( + tuple[str, str], lambda: (v for v in ("a", "b")), _TWO_TEXT, id="generator" + ), + pytest.param( + tuple[int, int, float], + {"third": 1, "first": 2, "second": 3.5}, + _THREE_NUMBERS, + id="numeric-dict", + ), + pytest.param(tuple[int, int, float], b"abc", _THREE_NUMBERS, id="bytes"), + pytest.param(tuple[int, int, float], [1, 2, 3.5], _THREE_NUMBERS, id="list"), + pytest.param(_POSITIONAL_LIST, (1, 2.5), _TWO_TEXT, id="tuple-for-list"), + pytest.param(_POSITIONAL_SEQUENCE, "ab", _TWO_TEXT, id="sequence-str"), + pytest.param(_POSITIONAL_SEQUENCE, b"ab", _TWO_TEXT, id="sequence-bytes"), + pytest.param( + _POSITIONAL_SEQUENCE, bytearray(b"ab"), _TWO_TEXT, id="sequence-bytearray" + ), + ], +) +@pytest.mark.parametrize("reverse_keys", [False, True], ids=["as-declared", "reversed"]) +@pytest.mark.parametrize( + ("entrypoint", "asynchronous", "store_kind"), + [ + pytest.param("call", False, "memory", id="call"), + pytest.param("async_call", True, "memory", id="async-call"), + pytest.param("as_table", False, "memory", id="table-sync-function"), + pytest.param("as_table", True, "memory", id="table-async-function"), + pytest.param("run", False, "memory", id="run-memory"), + pytest.param("run_async", True, "memory", id="run-async-memory"), + pytest.param("run", False, "delta", id="run-delta"), + pytest.param("run_async", True, "delta", id="run-async-delta"), + ], +) +def test_multi_output_containers_are_checked_before_values_are_unpacked( + annotation: object, + returned: object, + keys: tuple[str, ...], + entrypoint: str, + asynchronous: bool, + store_kind: str, + reverse_keys: bool, + tmp_path: Path, +) -> None: + """All entry points report the container mismatch and jobs store no rows.""" + if callable(returned): + returned = returned() + if reverse_keys: + keys = keys[::-1] + fn = _multi_output_function(annotation, returned, asynchronous=asynchronous) + source = DictSource( + data=[{"session": "s1", "record": 1, "x": 7, "y": "b"}], + tag_columns=["session", "record"], + tag_only_columns=True, + source_id="multi-output-input", + ) + + if entrypoint in ("run", "run_async"): + pod = FunctionPod.from_fn(fn, output_keys=list(keys)) + observer = _CrashRecorder() + job = PipelineJob(name="multi_output", database=_store(store_kind, tmp_path)) + with job: + _ = pod(source, label="result") + with pytest.warns(errors.RowFailuresWarning, match=fn.__name__): + if asynchronous: + _ = asyncio.run(job.run_async(observer=observer)) + else: + _ = job.run(observer=observer) + node = job.nodes["result"] + assert node.as_table().num_rows == 0 + stored = node.get_all_records() + assert stored is None or stored.num_rows == 0 + [error] = observer.crashes + assert isinstance(error, errors.OutputTypeError) + else: + data_function = PythonDataFunction(fn, output_keys=keys) + data = Data({"x": 7, "y": "b"}) + with pytest.raises(errors.OutputTypeError, match=fn.__name__) as caught: + if entrypoint == "call": + _ = data_function.call(data) + elif entrypoint == "async_call": + _ = asyncio.run(data_function.async_call(data)) + else: + _ = FunctionPod.from_fn(fn, output_keys=list(keys))(source).as_table() + error = caught.value + + message = str(error) + assert fn.__name__ in message + assert f"returned {type(returned).__name__} " in message + assert str(annotation) in message + assert "one value per output key, in the order of output_keys" in message + + +@pytest.mark.parametrize("use_executor", [True, False]) +@pytest.mark.parametrize("asynchronous", [True, False]) +def test_multi_output_generator_is_refused_without_iterating( + use_executor: bool, asynchronous: bool +) -> None: + """Container validation happens before the return value is iterated.""" + + def reject_iteration(): + pytest.fail("The return value was iterated") + yield 1 + + fn = _multi_output_function( + tuple[int, int], reject_iteration(), asynchronous=asynchronous + ) + data_function = PythonDataFunction(fn, output_keys=_TWO_TEXT) + if not use_executor: + data_function.set_executor(None) + data = Data({"x": 7, "y": "b"}) + with pytest.raises(errors.OutputTypeError, match="invalid_container.*generator"): + if asynchronous: + _ = asyncio.run(data_function.async_call(data)) + else: + _ = data_function.call(data) + + +@pytest.mark.parametrize( + ("annotation", "returned"), + [ + pytest.param(tuple[int, float], (1, 2.5), id="tuple"), + pytest.param(tuple[int, float], _NamedOutputs(1, 2.5), id="namedtuple"), + pytest.param(_POSITIONAL_LIST, [1, 2.5], id="list"), + pytest.param(_POSITIONAL_SEQUENCE, range(1, 3), id="sequence"), + pytest.param(None, (1, 2.5), id="unannotated"), + ], +) +def test_multi_output_containers_assign_values_in_output_key_order( + annotation: object, returned: Sequence[object] +) -> None: + fn = _multi_output_function(annotation, returned) + data_function = PythonDataFunction( + fn, + output_keys=("second", "first"), + output_schema={"second": int, "first": float} if annotation is None else None, + ) + result = data_function.call(Data({"x": 7, "y": "b"})) + assert result is not None + assert result.as_dict() == {"second": returned[0], "first": returned[1]} + + +def test_unannotated_multi_output_function_requires_a_tuple() -> None: + fn = _multi_output_function(None, [1, 2.5]) + data_function = PythonDataFunction( + fn, output_keys=_TWO_TEXT, output_schema={"first": int, "second": float} + ) + with pytest.raises( + errors.OutputTypeError, + match="invalid_container.*list.*Return a tuple.*annotate", + ): + _ = data_function.call(Data({"x": 7, "y": "b"})) + + +@pytest.mark.parametrize("annotation", [dict[str, int], list[int]]) +def test_multi_output_annotation_must_declare_position_types( + annotation: object, +) -> None: + fn = _multi_output_function(annotation, []) + with pytest.raises(ValueError, match="return type annotation"): + PythonDataFunction(fn, output_keys=_TWO_TEXT) + + +class _MappingSequence(dict[str, str]): + """A mapping whose class also satisfies the sequence origin check.""" + + +_ = cast(ABCMeta, cast(object, Sequence)).register(_MappingSequence) + + +@pytest.mark.parametrize("origin", [str, bytes, bytearray, _MappingSequence]) +def test_multi_output_excluded_container_annotation_is_refused_at_definition( + origin: type, +) -> None: + fn = _multi_output_function(types.GenericAlias(origin, (str, str)), "ab") + with pytest.raises(ValueError, match=r"return type annotation.*tuple\["): + _ = PythonDataFunction(fn, output_keys=_TWO_TEXT) + + def _half_on_even(x: int) -> int: """Return an int for odd ``x`` and a float (wrong) for even ``x``.""" return x + 0.5 if x % 2 == 0 else x # pyright: ignore[reportReturnType] # the wrong return type is the point of the test diff --git a/tests/test_core/function_pod/test_output_keys_identity.py b/tests/test_core/function_pod/test_output_keys_identity.py index f7d9faf45..fb65038e2 100644 --- a/tests/test_core/function_pod/test_output_keys_identity.py +++ b/tests/test_core/function_pod/test_output_keys_identity.py @@ -560,10 +560,6 @@ def test_a_same_typed_swap_is_never_served_the_other_orders_rows_silently( assert served_its_own or warned -@pytest.mark.xfail( - strict=True, - reason="ITL-1254: a dict returned where a tuple is declared is iterated by its keys", -) def test_a_dict_returned_for_a_tuple_annotation_is_refused() -> None: def first_and_second(a: str, b: str) -> tuple[str, str]: # The defect under test: a dict where the annotation declares a tuple. diff --git a/tests/test_core/test_regression_fixes.py b/tests/test_core/test_regression_fixes.py index 793a64890..e68236643 100644 --- a/tests/test_core/test_regression_fixes.py +++ b/tests/test_core/test_regression_fixes.py @@ -13,6 +13,10 @@ from __future__ import annotations import asyncio +import io +import pickle +from collections.abc import Callable +from concurrent.futures import Future, ThreadPoolExecutor from typing import Any from unittest.mock import MagicMock, patch @@ -21,6 +25,7 @@ from orcapod.channels import Channel from orcapod.core.datagrams import Data +from orcapod.errors import OutputContainerTypeError from orcapod.core.executors import ( LocalPythonFunctionExecutor, PythonFunctionExecutorBase, @@ -678,6 +683,121 @@ def decorator(wrapper): assert captured_wrappers[0].__name__ == "compute_features" +class _SerializesAsTuple: + """A wrong return container that would appear valid after deserialization.""" + + def __reduce__(self) -> tuple[object, ...]: + return tuple, (("wrong-first", "wrong-second"),) + + +@pytest.mark.parametrize( + "returned", + [ + "generator", + "tuple-on-unpickle", + pytest.param( + "coroutine", + marks=pytest.mark.filterwarnings( + "ignore:coroutine .* was never awaited:RuntimeWarning" + ), + ), + "valid", + ], +) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["call", "async-call"]) +def test_ray_checks_multi_output_container_before_serializing( + returned: str, asynchronous: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """Exercise the actual capture wrapper and Ray serializer without a cluster.""" + ray = pytest.importorskip("ray") + from ray import cloudpickle + from ray._private.worker import global_worker + + from orcapod.core.executors.ray import RayExecutor + + async def coroutine_outputs(x: str, y: str) -> tuple[str, str]: + return x, y + + def raw_outputs(x: str, y: str) -> object: + if returned == "generator": + return (value for value in (x, y)) + if returned == "tuple-on-unpickle": + return _SerializesAsTuple() + if returned == "coroutine": + return coroutine_outputs(x, y) + return x, y + + def worker_output(x: str, y: str) -> tuple[str, str]: + return raw_outputs(x, y) # pyright: ignore[reportReturnType] # Deliberate mismatch. + + async def async_worker_output(x: str, y: str) -> tuple[str, str]: + return raw_outputs(x, y) # pyright: ignore[reportReturnType] # Deliberate mismatch. + + class Ref: + def __init__(self, result: Future[object]) -> None: + self.result = result + + def future(self) -> Future[object]: + return self.result + + class WorkerUnpickler(pickle.Unpickler): + def find_class(self, module: str, name: str) -> object: + assert not (module == "orcapod" or module.startswith("orcapod.")) + return super().find_class(module, name) + + class SerializedTransport: + def __init__(self, wrapper: Callable[..., object]) -> None: + self.wrapper = wrapper + + def options(self, *, name: str) -> SerializedTransport: + assert name == self.wrapper.__name__ + return self + + def remote(self, *args: object) -> Ref: + def on_worker() -> object: + # Ray exports the wrapper and arguments before executing the task. + serialized_call = cloudpickle.dumps((self.wrapper, args)) + wrapper, worker_args = WorkerUnpickler( + io.BytesIO(serialized_call) + ).load() + response = wrapper(*worker_args) + _ = global_worker.get_serialization_context().serialize(response) + return cloudpickle.loads(cloudpickle.dumps(response)) + + return Ref(pool.submit(on_worker)) + + fn = async_worker_output if asynchronous else worker_output + data_function = PythonDataFunction(fn, output_keys=("first", "second")) + executor = RayExecutor() + monkeypatch.setattr(executor, "_ensure_ray_initialized", lambda: None) + monkeypatch.setattr(ray, "remote", SerializedTransport) + monkeypatch.setattr(ray, "get", lambda ref: ref.future().result()) + data_function.set_executor(executor) + data = Data({"x": "a", "y": "b"}) + + def call() -> DataProtocol | None: + if asynchronous: + return asyncio.run(data_function.async_call(data)) + return data_function.call(data) + + with ThreadPoolExecutor(max_workers=1) as pool: + if returned == "valid": + result = call() + assert result is not None + assert result.as_dict() == {"first": "a", "second": "b"} + else: + returned_type = ( + "_SerializesAsTuple" if returned == "tuple-on-unpickle" else returned + ) + with pytest.raises(OutputContainerTypeError) as caught: + _ = call() + message = str(caught.value) + assert fn.__name__ in message + assert returned_type in message + assert "tuple[str, str]" in message + assert "Return a tuple with one value per output key" in message + + # =========================================================================== # 6. DataFunctionExecutorProtocol type safety # ===========================================================================