From 321f6540bf6402469f4e9f0f538fff3082f86843 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:35:00 -0800 Subject: [PATCH 1/2] fix(logging): record execution outcome after output validation Fixes ITL-1261 --- changelog.d/ITL-1261.md | 3 + docs/dev/design_issues/ITL-1261-OBS1261.md | 13 +++ src/orcapod/core/data_function.py | 87 ++++++++++++++----- .../test_logging_observer_integration.py | 56 +++++++++++- 4 files changed, 137 insertions(+), 22 deletions(-) create mode 100644 changelog.d/ITL-1261.md create mode 100644 docs/dev/design_issues/ITL-1261-OBS1261.md diff --git a/changelog.d/ITL-1261.md b/changelog.d/ITL-1261.md new file mode 100644 index 000000000..2ce0f5fb5 --- /dev/null +++ b/changelog.d/ITL-1261.md @@ -0,0 +1,3 @@ +### Fixed + +- The execution log now records rejected function outputs as failures and includes the validation traceback (ITL-1261). diff --git a/docs/dev/design_issues/ITL-1261-OBS1261.md b/docs/dev/design_issues/ITL-1261-OBS1261.md new file mode 100644 index 000000000..62ef5903a --- /dev/null +++ b/docs/dev/design_issues/ITL-1261-OBS1261.md @@ -0,0 +1,13 @@ +## `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 and its traceback with the captured I/O. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 7fd1200b0..5e618f3a7 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -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 @@ -84,6 +86,47 @@ 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() + 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]: @@ -1208,16 +1251,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 @@ -1239,16 +1283,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 diff --git a/tests/test_pipeline/test_logging_observer_integration.py b/tests/test_pipeline/test_logging_observer_integration.py index 8e79d461b..f5c407a04 100644 --- a/tests/test_pipeline/test_logging_observer_integration.py +++ b/tests/test_pipeline/test_logging_observer_integration.py @@ -7,14 +7,17 @@ from __future__ import annotations +from typing import cast + import pyarrow as pa import pytest 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, @@ -112,6 +115,57 @@ 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"] +) +def test_rejected_output_logged_as_failure( + orchestrator_type: type[SyncPipelineOrchestrator] | type[AsyncPipelineOrchestrator], + wrong_arity: 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) -> tuple[int, int]: + print(f"returning output for {x}") + return cast("tuple[int, int]", (x,)) + + 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) -> int: + print(f"returning output for {x}") + return cast(int, cast(object, str(x))) + + pod = rejected_type.pod + error_text = "OutputTypeError" + + database = InMemoryArrowDatabase() + job = PipelineJob(name="test_rejected_output", database=database) + with job: + pod(_make_source(1), 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 = 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\n"] + + # --------------------------------------------------------------------------- # 3. Flat log storage — all logs in a single table # --------------------------------------------------------------------------- From b8dc2ca45eabd571db2977110d12848d6c7843ec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:02:33 -0800 Subject: [PATCH 2/2] fix(logging): escape surrogates in validation tracebacks --- changelog.d/ITL-1261.md | 6 +- docs/dev/design_issues/ITL-1261-OBS1261.md | 4 +- src/orcapod/core/data_function.py | 6 +- .../test_logging_observer_integration.py | 74 ++++++++++++++++--- 4 files changed, 78 insertions(+), 12 deletions(-) diff --git a/changelog.d/ITL-1261.md b/changelog.d/ITL-1261.md index 2ce0f5fb5..4f5638343 100644 --- a/changelog.d/ITL-1261.md +++ b/changelog.d/ITL-1261.md @@ -1,3 +1,7 @@ ### Fixed -- The execution log now records rejected function outputs as failures and includes the validation traceback (ITL-1261). +- 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). diff --git a/docs/dev/design_issues/ITL-1261-OBS1261.md b/docs/dev/design_issues/ITL-1261-OBS1261.md index 62ef5903a..19b5d4e95 100644 --- a/docs/dev/design_issues/ITL-1261-OBS1261.md +++ b/docs/dev/design_issues/ITL-1261-OBS1261.md @@ -10,4 +10,6 @@ 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 and its traceback with the captured I/O. +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. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 5e618f3a7..334e57413 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -115,7 +115,11 @@ def _log_validated_outcome( yield deferred except Exception: if deferred.pending: - failure_traceback = traceback.format_exc() + failure_traceback = ( + traceback.format_exc() + .encode("utf-8", "backslashreplace") + .decode("utf-8") + ) for fields in deferred.pending: fields["success"] = False if "traceback" in fields: diff --git a/tests/test_pipeline/test_logging_observer_integration.py b/tests/test_pipeline/test_logging_observer_integration.py index f5c407a04..a1290692c 100644 --- a/tests/test_pipeline/test_logging_observer_integration.py +++ b/tests/test_pipeline/test_logging_observer_integration.py @@ -7,10 +7,12 @@ 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, function_pod @@ -121,35 +123,45 @@ def failing(x: int) -> int: @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) -> tuple[int, int]: - print(f"returning output for {x}") - return cast("tuple[int, int]", (x,)) + 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) -> int: - print(f"returning output for {x}") - return cast(int, cast(object, str(x))) + 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(_make_source(1), label="rejected") + _ = pod(source, label="rejected") observer = LoggingObserver(log_database=database) with pytest.warns(RowFailuresWarning, match=error_text): @@ -160,10 +172,54 @@ def rejected_type(x: int) -> int: logs = observer.get_logs() assert logs is not None assert logs.column("_log_success").to_pylist() == [False] - traceback_text = logs.column("_log_traceback")[0].as_py() + 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\n"] + 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") # ---------------------------------------------------------------------------