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
7 changes: 7 additions & 0 deletions changelog.d/ITL-1261.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Fixed

- The execution log now records rejected function outputs as failures and includes the validation traceback when the executor supplies a traceback field. Lone surrogates in the traceback are escaped so the log can be stored as UTF-8 (ITL-1261).

### Known limitations

- If a custom executor records only `success=True` and `stdout_log` for a call that returns a string declared as `int`, its execution log records the failure and captured stdout without the validation reason. The job summary reports the original `OutputTypeError` (ITL-1261).
15 changes: 15 additions & 0 deletions docs/dev/design_issues/ITL-1261-OBS1261.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
## `src/orcapod/core/data_function.py` — function output validation

### OBS1261 — The execution log recorded success for rejected output
**Status:** resolved
**Severity:** medium
**Issue:** ITL-1261

Executors recorded a successful function return before the data function checked
the output's shape and type. A job then counted the row as failed while the
execution log still reported success with no traceback.

**Fix:** Defer successful execution records until output validation finishes.
If validation raises, record the failure with the captured I/O and fill the
traceback field when the executor supplies one. Escape lone surrogates in the
traceback so the log can be stored as UTF-8.
91 changes: 70 additions & 21 deletions src/orcapod/core/data_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import re
import sys
import tokenize
import traceback
import types
import uuid
from abc import abstractmethod
from collections.abc import Callable, Iterable, Sequence
from collections.abc import Callable, Iterable, Iterator, Sequence
from contextlib import contextmanager
import typing
from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, TypeVar

Expand Down Expand Up @@ -84,6 +86,51 @@ def _get_sync_executor():
return _sync_executor


class _DeferredSuccessLogger:
"""Hold executor success records until the output has been validated."""

def __init__(self, logger: DataExecutionLoggerProtocol) -> None:
self.logger = logger
self.pending: list[dict[str, Any]] = []

def record(self, **fields: Any) -> None:
"""Save a success record or forward an executor failure as it arrives."""
if fields.get("success") is True:
self.pending.append(fields)
else:
self.logger.record(**fields)


@contextmanager
def _log_validated_outcome(
logger: DataExecutionLoggerProtocol | None,
) -> Iterator[DataExecutionLoggerProtocol | None]:
"""Record captured I/O with the outcome of execution and output validation."""
if logger is None:
yield None
return

deferred = _DeferredSuccessLogger(logger)
try:
yield deferred
except Exception:
if deferred.pending:
failure_traceback = (
traceback.format_exc()
.encode("utf-8", "backslashreplace")
.decode("utf-8")
)
for fields in deferred.pending:
fields["success"] = False
if "traceback" in fields:
fields["traceback"] = failure_traceback
logger.record(**fields)
raise
else:
for fields in deferred.pending:
logger.record(**fields)


def parse_function_outputs(
output_keys: Sequence[str], values: Any, return_container: type = tuple
) -> dict[str, DataValue]:
Expand Down Expand Up @@ -1208,16 +1255,17 @@ def call(
if self._executor is not None:
if not self._active:
return None
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)
with _log_validated_outcome(logger) as execution_logger:
try:
raw = self._executor.execute_callable(
self._function,
{**data.as_dict(), **kwargs},
executor_options=self._executor_return_options(),
logger=execution_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 @@ -1239,16 +1287,17 @@ async def async_call(
if self._executor is not None:
if not self._active:
return None
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)
with _log_validated_outcome(logger) as execution_logger:
try:
raw = await self._executor.async_execute_callable(
self._function,
{**data.as_dict(), **kwargs},
executor_options=self._executor_return_options(),
logger=execution_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
112 changes: 111 additions & 1 deletion tests/test_pipeline/test_logging_observer_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,19 @@

from __future__ import annotations

from collections.abc import Iterator
from typing import cast

import pyarrow as pa
import pytest
from typing_extensions import override

from orcapod.core.executors import LocalPythonFunctionExecutor
from orcapod.core.function_pod import FunctionPod
from orcapod.core.function_pod import FunctionPod, function_pod
from orcapod.core.data_function import PythonDataFunction
from orcapod.core.sources.arrow_table_source import ArrowTableSource
from orcapod.databases import InMemoryArrowDatabase
from orcapod.errors import RowFailuresWarning
from orcapod.pipeline import (
AsyncPipelineOrchestrator,
SyncPipelineOrchestrator,
Expand Down Expand Up @@ -112,6 +117,111 @@ def failing(x: int) -> int:
assert "boom" in tb


@pytest.mark.parametrize(
"orchestrator_type", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator]
)
@pytest.mark.parametrize(
"wrong_arity", [False, True], ids=["wrong-type", "wrong-arity"]
)
@pytest.mark.parametrize("reverse_layout", [False, True], ids=["forward", "reverse"])
def test_rejected_output_logged_as_failure(
orchestrator_type: type[SyncPipelineOrchestrator] | type[AsyncPipelineOrchestrator],
wrong_arity: bool,
reverse_layout: bool,
) -> None:
"""Log the validation failure alongside the captured function output."""
executor = LocalPythonFunctionExecutor()
if wrong_arity:

@function_pod(output_keys=("first", "second"), executor=executor)
def rejected_arity(x: int, y: int) -> tuple[int, int]:
print(f"returning output for {x}, {y}")
return cast("tuple[int, int]", (x + y,))

pod = rejected_arity.pod
error_text = "does not match number of values"
else:

@function_pod(output_keys="result", executor=executor)
def rejected_type(x: int, y: int) -> int:
print(f"returning output for {x}, {y}")
return cast(int, cast(object, str(x + y)))

pod = rejected_type.pod
error_text = "OutputTypeError"

database = InMemoryArrowDatabase()
job = PipelineJob(name="test_rejected_output", database=database)
table = pa.table({"id": ["0"], "x": [10], "region": ["west"], "y": [20]})
tag_columns = ["id", "region"]
if reverse_layout:
table = table.select(table.column_names[::-1])
tag_columns.reverse()
source = ArrowTableSource(
table, tag_columns=tag_columns, infer_nullable=True, tag_only_columns=True
)
with job:
_ = pod(source, label="rejected")

observer = LoggingObserver(log_database=database)
with pytest.warns(RowFailuresWarning, match=error_text):
summary = job.run(orchestrator=orchestrator_type(), observer=observer)

assert summary.nodes["rejected"].computed == 0
assert summary.nodes["rejected"].failed == 1
logs = observer.get_logs()
assert logs is not None
assert logs.column("_log_success").to_pylist() == [False]
traceback_text: object = logs.column("_log_traceback")[0].as_py()
assert isinstance(traceback_text, str)
assert error_text in traceback_text
assert logs.column("_log_stdout_log").to_pylist() == [
"returning output for 10, 20\n"
]
assert logs.column("id").to_pylist() == ["0"]
assert logs.column("region").to_pylist() == ["west"]


@pytest.mark.parametrize(
"orchestrator_type", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator]
)
def test_validation_traceback_with_lone_surrogate(
orchestrator_type: type[SyncPipelineOrchestrator] | type[AsyncPipelineOrchestrator],
) -> None:
"""Store UTF-8 log text and preserve the original row error."""
error_text = "validation failed on \ud800"

class RejectedList(list[int]):
@override
def __iter__(self) -> Iterator[int]:
raise ValueError(error_text)

@function_pod(output_keys="result", executor=LocalPythonFunctionExecutor())
def rejected_list(x: int) -> list[int]:
return RejectedList([x])

database = InMemoryArrowDatabase()
job = PipelineJob(name="test_validation_traceback", database=database)
with job:
_ = rejected_list.pod(_make_source(1), label="rejected")

observer = LoggingObserver(log_database=database)
with pytest.warns(RowFailuresWarning):
summary = job.run(orchestrator=orchestrator_type(), observer=observer)

node = summary.nodes["rejected"]
assert node.computed == 0
assert node.failed == 1
assert type(node.first_error) is ValueError
assert str(node.first_error) == error_text
logs = observer.get_logs()
assert logs is not None
assert logs.column("_log_success").to_pylist() == [False]
traceback_text: object = logs.column("_log_traceback")[0].as_py()
assert isinstance(traceback_text, str)
assert traceback_text.endswith(r"ValueError: validation failed on \ud800" + "\n")


# ---------------------------------------------------------------------------
# 3. Flat log storage — all logs in a single table
# ---------------------------------------------------------------------------
Expand Down
Loading