Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions changelog.d/ITL-1254.md
Original file line number Diff line number Diff line change
@@ -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).
2 changes: 2 additions & 0 deletions docs/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion docs/concepts/function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions docs/dev/design_issues/ITL-1254-OC1.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 4 additions & 1 deletion docs/tutorial/02-function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down
83 changes: 65 additions & 18 deletions src/orcapod/core/data_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@
from orcapod.core.result_cache import ResultCache
from orcapod.errors import (
NoOutputsDeclaredError,
OutputContainerTypeError,
OutputTypeError,
UnstorableDatetimeError,
)
from orcapod.protocols.core_protocols import DataFunctionProtocol, DataProtocol
from orcapod.protocols.core_protocols.executor import (
DataFunctionExecutorProtocol,
PythonFunctionExecutorProtocol,
PythonFunctionReturnCheckProtocol,
)
from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
from orcapod.semantic_types.output_conformance import (
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
29 changes: 24 additions & 5 deletions src/orcapod/core/executors/capture_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -23,14 +28,21 @@ 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
framework's normal error handling proceed (retries, error wrapping, etc.)
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
Expand Down Expand Up @@ -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()
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading