From 9bf80e76cf704461d66f422fad999d51fff1bef1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 22:06:23 -0800 Subject: [PATCH 01/16] fix(observers): report observer events a run could not record (ITL-1556) Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-1556.md | 24 + docs/api/errors.md | 2 + docs/api/pipeline.md | 2 + docs/concepts/pipeline-job.md | 5 +- docs/dev/design_issues/ITL-1556-OBS1.md | 28 ++ docs/troubleshooting.md | 13 + src/orcapod/errors.py | 14 + src/orcapod/pipeline/__init__.py | 2 + src/orcapod/pipeline/job.py | 33 +- src/orcapod/pipeline/logging_observer.py | 6 +- src/orcapod/pipeline/observer_losses.py | 124 +++++ src/orcapod/pipeline/run_summary.py | 84 +++- src/orcapod/pipeline/status_observer.py | 20 +- .../test_observer_event_losses.py | 426 ++++++++++++++++++ 14 files changed, 764 insertions(+), 19 deletions(-) create mode 100644 changelog.d/ITL-1556.md create mode 100644 docs/dev/design_issues/ITL-1556-OBS1.md create mode 100644 src/orcapod/pipeline/observer_losses.py create mode 100644 tests/test_pipeline/test_observer_event_losses.py diff --git a/changelog.d/ITL-1556.md b/changelog.d/ITL-1556.md new file mode 100644 index 000000000..3064544d3 --- /dev/null +++ b/changelog.d/ITL-1556.md @@ -0,0 +1,24 @@ +### Added + +- **A run reports the observer events it could not record** — `RunSummary` has a new + attribute, `lost_observer_events`: per observer kind (`"status"` for a `StatusObserver`, + `"logging"` for a `LoggingObserver`), a `LostObserverEvents` (exported from + `orcapod.pipeline`) with the number of events that were not written and the first error's + text; it is empty when every event was recorded. The summary's text and notebook display + show it as one line. A run with lost events issues one new warning, + `ObserverEventsLostWarning` (`orcapod.errors`), at the end of the run, at the line that + started it. (ITL-1556) + +### Fixed + +- **A failed observer write is no longer silent** — when a `StatusObserver` or a + `LoggingObserver` could not write an event to its database (a store that refuses the + rows, or one that fails partway through a run), the observer logged the error and the job + finished as if nothing had happened: nothing in the result or the summary said that the + status and log records were incomplete. The run still continues and its results, its + other summary counts and its exit are unchanged, and each failed write is still logged + with its traceback; the loss is now counted in `RunSummary.lost_observer_events` and + reported by one `ObserverEventsLostWarning` per run, on the sync and the async + orchestrator, for `job.run()`, `job.run_async()` and load-only runs, and for the + observers inside a `CompositeObserver`. A job node's own `run()` takes no observer, so + its summary lists none. (ITL-1556) diff --git a/docs/api/errors.md b/docs/api/errors.md index cd53180f1..73fa7a29d 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -76,6 +76,8 @@ These exceptions and warnings report problems running pipelines, processing rows ::: orcapod.errors.RowFailuresWarning +::: orcapod.errors.ObserverEventsLostWarning + ::: orcapod.errors.RestrictedAggregationWarning ::: orcapod.errors.SemiJoinIgnoredColumnWarning diff --git a/docs/api/pipeline.md b/docs/api/pipeline.md index 4bc0d429e..478a64be2 100644 --- a/docs/api/pipeline.md +++ b/docs/api/pipeline.md @@ -21,6 +21,8 @@ blueprint; `PipelineJob` binds a pipeline to sources and a database and runs it. ::: orcapod.pipeline.NodeRunSummary +::: orcapod.pipeline.LostObserverEvents + ::: orcapod.pipeline.SyncPipelineOrchestrator ::: orcapod.pipeline.AsyncPipelineOrchestrator diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 68672e28c..1afd5a439 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -64,7 +64,10 @@ Among `job.run()`'s optional arguments, the tutorial default policy skips failed rows and continues) and `observer=` (`StatusObserver`, `LoggingObserver`) to record what happened during the run. Both observers raise `SpiralDBObserverNotSupportedError` at setup if given a SpiralDB store, so give them -another database such as Delta (ITL-1540). An observer only watches: one +another database such as Delta (ITL-1540). An observer that cannot write an event to its +database does not stop the run: the failure is logged, the run summary counts the lost +events per observer kind in `lost_observer_events`, and one `ObserverEventsLostWarning` is +issued at the end of the run (ITL-1556). An observer only watches: one that changes the job, its nodes or its bound sources during a run is unsupported, and what the run then does is undefined (ITL-1369). `load_only=True` fills the nodes from what is already stored and computes nothing; see diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md new file mode 100644 index 000000000..6ad1a8f3e --- /dev/null +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -0,0 +1,28 @@ +## `src/orcapod/pipeline/status_observer.py`, `logging_observer.py` — failed event writes + +### OBS1 — Observers swallowed every failure to write an event; the run said nothing +**Status:** resolved +**Severity:** high +**Issue:** ITL-1556 + +`StatusObserver` (both write variants, the root and the contextualized one) and the +`DataLogger` of `LoggingObserver` caught every exception of `add_record` and only logged it. +A job whose observer database refused its rows, or failed partway through a run, finished +successfully with its status and log records missing or incomplete, and nothing in the +`RunSummary` or in a warning said so. ITL-1540 refuses a SpiralDB store at setup; that is +one case only (a SQLite-backed store is accepted at setup and refuses every event row). + +**Fix:** Developer decision (November 28, 2026): the observers continue, and the loss is +reported. A job run opens a record of lost events under its run id +(`pipeline/observer_losses.py`, `collecting_lost_events`); an observer that fails to write +adds to the record of its run (`record_lost_event`) after the log line it always wrote. The +run puts the record in `RunSummary.lost_observer_events` (per observer kind: count and first +error's text) and issues one `ObserverEventsLostWarning` at the end of the run, after the +summary is kept, at the caller's line. The end and not the first loss: the counts are +complete then, the warning turned into an error loses no result, and the first loss happens +inside a node, possibly on a worker thread. Additive: no existing field changed meaning, and +the run's result and exit are unchanged. A run that raises reports nothing beyond the log +lines. A job node's own `run()` takes no observer, so it has nothing to lose. An observer +handed directly to an orchestrator or to `node.execute` has no job run to report for it: its +failed writes are logged only. A re-contextualized status observer now keeps its run id. +Which stores observers work on (the SQLite case) stays open on the issue. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index fed7b5d4b..80793b4fd 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -205,6 +205,19 @@ same (`Run of job '...': 1 row failed.`). `orcapod.pipeline`) so that the first failure stops the run and raises. See the tutorial [Handling errors](tutorial/handling-errors.md). +### `ObserverEventsLostWarning: Observer events were not recorded in this run: ...` + +**Cause.** A `StatusObserver` or `LoggingObserver` could not write some of its rows to its +database (the store refused the write, or failed partway through the run). The run does +not stop for that: its results are complete and are not affected. Only the status and log +records of the run are incomplete. The warning is issued once, at the end of the run, and +gives, per observer kind, how many events were lost and the first error. + +**Fix.** Read the first error in the message; each failed write is also logged with its +traceback (logger `orcapod.pipeline`). The counts are in the run summary: +`job.last_run.lost_observer_events`. Give the observer a database that accepts its rows +(in-memory or Delta), then run again if you need the records. + ### `TypeError: ...() got an unexpected keyword argument 'ctx'` from a `sink_pod` **Cause.** A function decorated with `@sink_pod`, `@tap_pod` or `@side_effect_pod` must diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 23f8dd2af..8f439737c 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -782,6 +782,20 @@ class RowFailuresWarning(UserWarning): """ +class ObserverEventsLostWarning(UserWarning): + """Issued once at the end of a job run whose observers lost events (ITL-1556). + + A ``StatusObserver`` and a ``LoggingObserver`` record run events as rows in a + database. A write that fails does not stop the run, whose results do not depend on + those rows: the failure is logged with its traceback when it happens, and the run + goes on. At the end of the run (``job.run()``, ``job.run_async()``) this warning + says how many events of each observer kind were not recorded and gives each kind's + first error. The run's ``RunSummary`` (returned by the run, kept as + ``job.last_run``) holds the same counts in ``lost_observer_events``. The run's + result and summary are complete and kept before the warning is issued. + """ + + class SourceCheckFailedWarning(UserWarning): """A source could not be checked for new data at the start of a run (ITL-1102). diff --git a/src/orcapod/pipeline/__init__.py b/src/orcapod/pipeline/__init__.py index 235ec5778..bd0c01353 100644 --- a/src/orcapod/pipeline/__init__.py +++ b/src/orcapod/pipeline/__init__.py @@ -6,6 +6,7 @@ from .graph import Pipeline from .job import PipelineJob from .logging_observer import LoggingObserver, DataLogger +from .observer_losses import LostObserverEvents from .run_summary import NodeRunSummary, RunSummary from .serialization import ( LoadStatus, @@ -22,6 +23,7 @@ "GraphProtocol", "LoadStatus", "LoggingObserver", + "LostObserverEvents", "NodeRunSummary", "DataLogger", "OrcaDAG", diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 82f59257c..4c266b5e1 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -32,6 +32,7 @@ clear_run_rows, plan_run, ) +from orcapod.pipeline.observer_losses import collecting_lost_events from orcapod.pipeline.restrictions import ( refuse_restricted_operator_caches, refuse_restriction_conflicts, @@ -42,6 +43,7 @@ RunCountingObserver, RunSummary, run_node_summaries, + warn_lost_observer_events, warn_row_failures, ) from orcapod.protocols import core_protocols as cp @@ -50,11 +52,13 @@ from orcapod.utils.database_errors import database_write_path, flush_best_effort if TYPE_CHECKING: + from collections.abc import Mapping from pathlib import Path from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline + from orcapod.pipeline.observer_losses import LostObserverEvents from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol @@ -1085,7 +1089,12 @@ def run( counter = RunCountingObserver() effective_orchestrator = orchestrator or SyncPipelineOrchestrator() is_sync = isinstance(effective_orchestrator, SyncPipelineOrchestrator) - with self._executing(prepared, plan, commit_every_rows, load_only=load_only): + # Observer events that cannot be written do not stop the run; they are + # counted under the run's id and reported at its end (ITL-1556). + with ( + collecting_lost_events(prepared.run_id) as losses, + self._executing(prepared, plan, commit_every_rows, load_only=load_only), + ): if is_sync: # Held nodes give their output streams on the sync path (ITL-1347). _ = effective_orchestrator.run( @@ -1115,9 +1124,13 @@ def run( load_only=load_only, unchecked_sources=prepared.unchecked_sources, asynchronous=not is_sync, + lost_observer_events=losses.by_kind(), ) + caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warnings are shown if not summary.ok: - warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown + warn_row_failures(summary, caller) + if summary.lost_observer_events: + warn_lost_observer_events(summary, caller) return summary async def run_async( @@ -1170,7 +1183,11 @@ async def run_async( # The state rule (ITL-1095): a node that holds a current run is not run again. plan = prepared.plan counter = RunCountingObserver() - with self._executing(prepared, plan, commit_every_rows, load_only=load_only): + # Lost observer events are counted under the run's id, as in ``run`` (ITL-1556). + with ( + collecting_lost_events(prepared.run_id) as losses, + self._executing(prepared, plan, commit_every_rows, load_only=load_only), + ): _ = await orchestrator.run_async( plan.dag, observer=_with_counter(observer, counter), @@ -1187,9 +1204,13 @@ async def run_async( load_only=load_only, unchecked_sources=prepared.unchecked_sources, asynchronous=True, + lost_observer_events=losses.by_kind(), ) + caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warnings are shown if not summary.ok: - warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown + warn_row_failures(summary, caller) + if summary.lost_observer_events: + warn_lost_observer_events(summary, caller) return summary def _prepare_run( @@ -1490,6 +1511,7 @@ def _finish_run( load_only: bool = False, unchecked_sources: tuple[str, ...] = (), asynchronous: bool, + lost_observer_events: Mapping[str, LostObserverEvents], ) -> RunSummary: """Commit the run's last writes, mark the job as run and keep its summary. @@ -1503,6 +1525,8 @@ def _finish_run( load_only: Whether the run loaded stored results only. unchecked_sources: The sources the start-of-run check could not check. asynchronous: Whether the async orchestrator executed the run. + lost_observer_events: The observer events the run could not record, by + observer kind. Returns: The run's summary, also kept as ``last_run``. @@ -1567,6 +1591,7 @@ def _finish_run( ran_nothing=not plan.to_run, restricted_sources=restrictions_in_force(prepared.exec_dag.nodes()), asynchronous=asynchronous, + lost_observer_events=lost_observer_events, ) return self._last_run diff --git a/src/orcapod/pipeline/logging_observer.py b/src/orcapod/pipeline/logging_observer.py index b812af8bf..730bd1e76 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -53,6 +53,7 @@ from orcapod.pipeline._observer_database import require_observer_database from orcapod.pipeline.logging_capture import install_capture_streams +from orcapod.pipeline.observer_losses import LOGGING_EVENTS, record_lost_event from orcapod.protocols.core_protocols import DataProtocol, TagProtocol if TYPE_CHECKING: @@ -129,10 +130,13 @@ def record(self, **kwargs: Any) -> None: row = pa.table(columns) try: self._db.add_record(self._log_path, log_id, row, flush=True) - except Exception: + except Exception as error: + # The run goes on: its results do not depend on this row. The loss is + # logged here and reported by the run (ITL-1556). logger.exception( "LoggingObserver: failed to write log row", ) + record_lost_event(self._run_id, LOGGING_EVENTS, error) class LoggingObserver: diff --git a/src/orcapod/pipeline/observer_losses.py b/src/orcapod/pipeline/observer_losses.py new file mode 100644 index 000000000..241e89b4f --- /dev/null +++ b/src/orcapod/pipeline/observer_losses.py @@ -0,0 +1,124 @@ +"""Observer events a run could not record (ITL-1556). + +The status and logging observers record run events as rows in a database. A write that +fails does not stop the run: its results do not depend on those rows. The loss is +reported instead. A run opens a record under its run id (``collecting_lost_events``), an +observer that fails to write an event adds to the record of its run +(``record_lost_event``), and the run puts the record in its ``RunSummary`` and warns once +at its end. + +The record is found by run id, which every observer of a run is given +(``on_run_start``), so it holds for each contextualized copy of an observer and for an +observer inside a ``CompositeObserver`` alike. An event lost outside an open record (an +observer handed to an orchestrator or a node directly, with no job run to report it) is +only logged by its observer. +""" + +from __future__ import annotations + +import threading +from contextlib import contextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterator + +STATUS_EVENTS = "status" +"""The kind of the events a ``StatusObserver`` records.""" + +LOGGING_EVENTS = "logging" +"""The kind of the events a ``LoggingObserver`` records.""" + + +@dataclass(frozen=True) +class LostObserverEvents: + """The events of one observer kind that a run could not record. + + Attributes: + kind: The observer kind: ``"status"`` (a ``StatusObserver``'s state + transitions) or ``"logging"`` (a ``LoggingObserver``'s log rows). + count: How many events of that kind were not recorded. + first_error: The first failed write's error, as ``Type: message``. + """ + + kind: str + count: int + first_error: str + + +class RunLosses: + """The lost observer events of one run, counted per observer kind. + + Observer hooks may be called from several threads, so the counts are updated under + a lock. + """ + + def __init__(self) -> None: + """Start with no lost event.""" + self._lock: threading.Lock = threading.Lock() + self._counts: dict[str, int] = {} + self._first_errors: dict[str, str] = {} + + def record(self, kind: str, error: BaseException) -> None: + """Count one lost event of ``kind``; keep the kind's first error. + + Args: + kind: The observer kind. + error: What the failed write raised. + """ + text = f"{type(error).__name__}: {error}" + with self._lock: + self._counts[kind] = self._counts.get(kind, 0) + 1 + _ = self._first_errors.setdefault(kind, text) + + def by_kind(self) -> dict[str, LostObserverEvents]: + """The lost events so far, by observer kind, in kind order. + + Returns: + One entry per kind that lost an event; empty when none was lost. + """ + with self._lock: + return { + kind: LostObserverEvents(kind, count, self._first_errors[kind]) + for kind, count in sorted(self._counts.items()) + } + + +_open_lock = threading.Lock() +_open_records: dict[str, RunLosses] = {} + + +@contextmanager +def collecting_lost_events(run_id: str) -> Iterator[RunLosses]: + """Keep a record of the observer events lost under ``run_id`` while the block runs. + + Args: + run_id: The run's id, as the run gives it to its observers. + + Yields: + The run's record; read it (``by_kind``) once the run's nodes have finished. + """ + losses = RunLosses() + with _open_lock: + _open_records[run_id] = losses + try: + yield losses + finally: + with _open_lock: + if _open_records.get(run_id) is losses: + del _open_records[run_id] + + +def record_lost_event(run_id: str, kind: str, error: BaseException) -> None: + """Add one lost event to the record of run ``run_id``, if a run keeps one. + + Args: + run_id: The run the observer was started for. + kind: The observer kind (``STATUS_EVENTS`` or ``LOGGING_EVENTS``). + error: What the failed write raised. + """ + with _open_lock: + losses = _open_records.get(run_id) + if losses is not None: + losses.record(kind, error) diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 638334871..25df10088 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -22,6 +22,7 @@ from collections.abc import Mapping, Sequence from types import FrameType + from orcapod.pipeline.observer_losses import LostObserverEvents from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.pipeline.restrictions import RestrictedSource from orcapod.types import Condition, SchemaLike @@ -104,6 +105,13 @@ class RunSummary: ran_nothing: Whether the run ran no node: every node held a current run (ITL-1095). Decided by the run's plan, which counts every kind of node, so a run that ran only a side-effect or operator node is not "nothing to do". + lost_observer_events: The observer events the run could not record, by + observer kind (``"status"``, ``"logging"``), each with its count and its + first error's text (ITL-1556); empty when every event was recorded. A + failed write of a ``StatusObserver`` or ``LoggingObserver`` does not stop + the run and changes none of its results or other counts; an + ``ObserverEventsLostWarning`` reports the same at the end of the run. A + job node's own ``run()`` takes no observer, so its summary lists none. """ def __init__( @@ -117,6 +125,7 @@ def __init__( ran_nothing: bool = False, restricted_sources: Mapping[str, RestrictedSource] | None = None, asynchronous: bool = False, + lost_observer_events: Mapping[str, LostObserverEvents] | None = None, ) -> None: """Build the summary. @@ -132,6 +141,8 @@ def __init__( (``restrictions.restrictions_in_force``). Displayed by slot name or direct source label. asynchronous: Whether the async orchestrator executed the run. + lost_observer_events: The observer events the run could not record, by + observer kind. """ self.job_name: str = job_name self.nodes: Mapping[str, NodeRunSummary] = {node.label: node for node in nodes} @@ -139,6 +150,9 @@ def __init__( self.target: str | None = target self.unchecked_sources: tuple[str, ...] = tuple(unchecked_sources) self.ran_nothing: bool = ran_nothing + self.lost_observer_events: Mapping[str, LostObserverEvents] = dict( + sorted((lost_observer_events or {}).items()) + ) self._attribution_note: str = ( _ASYNC_ATTRIBUTION_NOTE if asynchronous and not load_only and not ran_nothing and nodes @@ -250,11 +264,32 @@ def _restrictions_line(self) -> str | None: for slot, source_id in self.restricted_source_ids.items() ) + def lost_observer_events_message(self) -> str: + """Each observer kind's lost events and first error, for the run's warning. + + Returns: + One clause per kind, joined, or ``""`` when no event was lost. + """ + return "; ".join( + f"{lost.count} {lost.kind} {'event' if lost.count == 1 else 'events'} " + f"(first error: {_first_line(lost.first_error)})" + for lost in self.lost_observer_events.values() + ) + + def _lost_events_line(self) -> str | None: + """The line counting the observer events that were not recorded, if any.""" + if not self.lost_observer_events: + return None + return "observer events not recorded: " + self.lost_observer_events_message() + def _source_lines_html(self) -> str: - """The unchecked and restricted source lines as HTML paragraphs, or ``""``.""" + """The source and lost-event lines as HTML paragraphs, or ``""``.""" restricted = self._restrictions_line() - return self._unchecked_html() + ( - "" if restricted is None else f"

{html.escape(restricted)}

" + lost = self._lost_events_line() + return ( + self._unchecked_html() + + ("" if restricted is None else f"

{html.escape(restricted)}

") + + ("" if lost is None else f"

{html.escape(lost)}

") ) def _unchecked_html(self) -> str: @@ -271,6 +306,9 @@ def __repr__(self) -> str: restricted = self._restrictions_line() if restricted is not None: lines.append(f" {restricted}") + lost = self._lost_events_line() + if lost is not None: + lines.append(f" {lost}") if self._attribution_note: lines.append(f" {self._attribution_note}") for node in self.nodes.values(): @@ -374,15 +412,18 @@ def _rows(n: int) -> str: return f"{n} row" if n == 1 else f"{n} rows" +def _first_line(text: str) -> str: + """The first line of ``text``, marked with ``...`` when more lines follow.""" + lines = text.splitlines() + first = lines[0] if lines else "" + return f"{first} ..." if len(lines) > 1 else first + + def _error_line(error: BaseException | None) -> str: """``Type: first line of the message``.""" if error is None: return "" - message = str(error) - lines = message.splitlines() - first = lines[0] if lines else "" - if len(lines) > 1: - first += " ..." + first = _first_line(str(error)) return f"{type(error).__name__}: {first}" if first else type(error).__name__ @@ -414,6 +455,33 @@ def warn_row_failures(summary: RunSummary, caller: FrameType) -> None: warn_at_frame(summary.failures_message(), RowFailuresWarning, caller) +def warn_lost_observer_events(summary: RunSummary, caller: FrameType) -> None: + """Issue the run's ``ObserverEventsLostWarning``, at the end of the run (ITL-1556). + + At the end and not at the first loss: the count and each kind's first error are + complete then, the run's rows and summary are already kept (the warning turned into + an error loses nothing), and it is shown at the line that started the run, where + the first loss happens inside a node, possibly on a worker thread. Each failed + write is still logged by its observer when it happens. + + Args: + summary: The run's summary, with lost observer events. + caller: The frame that called ``run``; the warning is shown at its line. + """ + from orcapod.errors import ObserverEventsLostWarning + from orcapod.utils.warning_utils import warn_at_frame + + warn_at_frame( + "Observer events were not recorded in this run: " + + f"{summary.lost_observer_events_message()}. The run's results are not " + + "affected, but its status and log records are incomplete. Each failed " + + "write was logged with its traceback; the counts are in the run " + + "summary's lost_observer_events.", + ObserverEventsLostWarning, + caller, + ) + + class RunCountingObserver: """Counts, per node label, the rows computed, reused and failed in one run. diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index d5e093cc5..0800a244b 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -60,6 +60,7 @@ from orcapod.pipeline._observer_database import require_observer_database from orcapod.pipeline.observer import NoOpLogger +from orcapod.pipeline.observer_losses import STATUS_EVENTS, record_lost_event from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import SchemaLike @@ -301,12 +302,15 @@ def _write_event( row = pa.table(columns) try: self._db.add_record(DEFAULT_STATUS_PATH, status_id, row, flush=True) - except Exception: + except Exception as error: + # The run goes on: its results do not depend on this row. The loss is + # logged here and reported by the run (ITL-1556). logger.exception( "StatusObserver: failed to write status event for node=%s state=%s", node_label, state, ) + record_lost_event(self._current_run_id, STATUS_EVENTS, error) class _ContextualizedStatusObserver: @@ -331,7 +335,12 @@ def __init__( def contextualize(self, *identity_path: str) -> "_ContextualizedStatusObserver": """Re-contextualize with a new identity path (scopes the DB).""" - return _ContextualizedStatusObserver(self._db.at(*identity_path)) + ctx = _ContextualizedStatusObserver(self._db.at(*identity_path)) + # The copy belongs to the same run: its events carry, and its losses are + # reported under, that run's id. + ctx._current_run_id = self._current_run_id + ctx._current_pipeline_uri = self._current_pipeline_uri + return ctx def on_run_start( self, @@ -427,14 +436,15 @@ def _write_event( ) row = pa.table(columns) - # TODO: re-evaluate broad exception absorption — ideally narrow to DB-specific - # errors (e.g. IOError, ArrowInvalid) once the full set of failure modes is known. try: self._db.add_record(DEFAULT_STATUS_PATH, status_id, row, flush=True) - except Exception: + except Exception as error: + # The run goes on; the loss is logged here and reported by the run + # (ITL-1556). logger.exception( "_ContextualizedStatusObserver: failed to write status event " "for node=%s state=%s", node_label, state, ) + record_lost_event(self._current_run_id, STATUS_EVENTS, error) diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py new file mode 100644 index 000000000..7250b2012 --- /dev/null +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -0,0 +1,426 @@ +"""A run says which observer events it could not record (ITL-1556). + +The status and logging observers record run events as rows in a database. A write that +fails does not stop the run (its results do not depend on those rows), but the loss must +not be silent: the run's ``RunSummary`` counts the lost events per observer kind with the +first error's text, and one ``ObserverEventsLostWarning`` is issued at the end of the run. +""" + +from __future__ import annotations + +import asyncio +import logging +import threading +import warnings +from collections.abc import Callable +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ObserverEventsLostWarning +from orcapod.pipeline import ( + AsyncPipelineOrchestrator, + CompositeObserver, + LoggingObserver, + LostObserverEvents, + RunSummary, + StatusObserver, + SyncPipelineOrchestrator, +) +from tests.test_core.operators.several_items import ( + DATA_FIRST_REVERSED, + MAIN, + MIXED, + PLAIN, + TAGS_FIRST, + Arrangement, + make_source, +) + +ORCHESTRATORS: dict[str, Callable[[], Any]] = { + "sync": SyncPipelineOrchestrator, + "async": AsyncPipelineOrchestrator, +} + +# Three tag and three data columns, in two arrangements (tag order, layout, roles). +ARRANGEMENTS = [ + Arrangement(MAIN.tags, TAGS_FIRST, PLAIN), + Arrangement(tuple(reversed(MAIN.tags)), DATA_FIRST_REVERSED, MIXED), +] +N_ROWS = 6 +LABEL = "described" + + +@function_pod(output_keys=("n", "s")) +def describe(d1: int, d3: str) -> tuple[int, str]: + """Return ``d1 + 1`` and ``d3`` doubled.""" + return d1 + 1, d3 + d3 + + +class _Refusals: + """Which writes a ``_RefusingDatabase`` and its scoped views refuse. + + Attributes: + accept_first: The number of writes accepted before every later one is refused; + ``None`` accepts every write. + writes: The writes attempted so far. + """ + + def __init__(self, accept_first: int | None) -> None: + self.accept_first: int | None = accept_first + self.writes: int = 0 + # Observer hooks may be called from several threads. + self.lock: threading.Lock = threading.Lock() + + +class _RefusingDatabase: + """A database that refuses ``add_record`` as its ``_Refusals`` says. + + Everything else is the wrapped in-memory database's; a scoped view (``at``) shares + the refusals, so a write counts whichever node made it. + """ + + def __init__(self, database: InMemoryArrowDatabase, refusals: _Refusals) -> None: + self._database = database + self.refusals = refusals + + def at(self, *path: str) -> _RefusingDatabase: + """Return the scoped view, refusing by the same rule.""" + return _RefusingDatabase(self._database.at(*path), self.refusals) + + def add_record(self, *args: Any, **kwargs: Any) -> None: + """Write, or refuse with an ``OSError``.""" + refusals = self.refusals + with refusals.lock: + refusals.writes += 1 + refused = ( + refusals.accept_first is not None + and refusals.writes > refusals.accept_first + ) + if refused: + raise OSError("store refuses writes") + self._database.add_record(*args, **kwargs) + + def __getattr__(self, name: str) -> Any: + return getattr(self._database, name) + + +def _database(accept_first: int | None = 0) -> Any: + """A database refusing every write after the first ``accept_first``.""" + return _RefusingDatabase(InMemoryArrowDatabase(), _Refusals(accept_first)) + + +def _job(arrangement: Arrangement, store: Any = None) -> PipelineJob: + """``MAIN`` in ``arrangement`` feeding ``describe`` under ``LABEL``.""" + job = PipelineJob(name="losses", database=store or InMemoryArrowDatabase()) + with job: + describe.pod(make_source(MAIN, arrangement), label=LABEL) + return job + + +def _rows(job: PipelineJob) -> list[tuple[Any, ...]]: + """The node's rows, as sorted ``(t1, t2, t3, n, s)``.""" + return sorted( + (row["t1"], row["t2"], row["t3"], row["n"], row["s"]) + for row in job.nodes[LABEL].as_table().to_pylist() + ) + + +EXPECTED_ROWS = sorted( + (t1, t2, t3, d1 + 1, d3 + d3) + for t1, t2, t3, d1, d3 in zip( + *(MAIN.columns[name].to_pylist() for name in ("t1", "t2", "t3", "d1", "d3")) + ) +) + + +def _run_losing(job: PipelineJob, **kwargs: Any) -> tuple[RunSummary, list[str]]: + """Run ``job``; return its summary and the lost-events warnings' messages.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + summary = job.run(**kwargs) + return summary, [ + str(w.message) + for w in caught + if issubclass(w.category, ObserverEventsLostWarning) + ] + + +@pytest.fixture(params=list(ORCHESTRATORS)) +def orchestrator(request: pytest.FixtureRequest) -> Any: + """Each orchestrator, freshly built.""" + return ORCHESTRATORS[request.param]() + + +@pytest.fixture(params=ARRANGEMENTS, ids=lambda arrangement: arrangement.id) +def arrangement(request: pytest.FixtureRequest) -> Arrangement: + """Each arrangement of the source's columns.""" + return request.param + + +def test_a_store_that_refuses_every_write_is_reported( + orchestrator: Any, arrangement: Arrangement +) -> None: + """Every lost status and log event is counted; the run and its rows are unchanged.""" + observer = CompositeObserver( + StatusObserver(_database()), LoggingObserver(_database()) + ) + job = _job(arrangement) + + summary, messages = _run_losing(job, orchestrator=orchestrator, observer=observer) + + # RUNNING and SUCCESS per row; one log row per row. + assert summary.lost_observer_events == { + "status": LostObserverEvents( + "status", 2 * N_ROWS, "OSError: store refuses writes" + ), + "logging": LostObserverEvents( + "logging", N_ROWS, "OSError: store refuses writes" + ), + } + assert summary.ok + node = summary.nodes[LABEL] + assert (node.computed, node.reused, node.failed) == (N_ROWS, 0, 0) + assert _rows(job) == EXPECTED_ROWS + assert job.last_run is summary + + assert len(messages) == 1 + assert f"{2 * N_ROWS} status events" in messages[0] + assert f"{N_ROWS} logging events" in messages[0] + assert "OSError: store refuses writes" in messages[0] + assert "lost_observer_events" in messages[0] + + +@pytest.mark.parametrize("kind", ["status", "logging"]) +def test_one_observer_alone_reports_its_kind_only( + kind: str, orchestrator: Any, arrangement: Arrangement +) -> None: + """A status or a logging observer given on its own reports its own events.""" + observer: Any = ( + StatusObserver(_database()) + if kind == "status" + else LoggingObserver(_database()) + ) + job = _job(arrangement) + + summary, messages = _run_losing(job, orchestrator=orchestrator, observer=observer) + + count = 2 * N_ROWS if kind == "status" else N_ROWS + assert summary.lost_observer_events == { + kind: LostObserverEvents(kind, count, "OSError: store refuses writes") + } + assert len(messages) == 1 + assert _rows(job) == EXPECTED_ROWS + + +def test_observers_nested_in_composites_are_reported( + orchestrator: Any, arrangement: Arrangement +) -> None: + """A composite inside a composite, and two observers of one kind, all count.""" + observer = CompositeObserver( + CompositeObserver(StatusObserver(_database())), + StatusObserver(_database()), + LoggingObserver(_database()), + ) + job = _job(arrangement) + + summary, messages = _run_losing(job, orchestrator=orchestrator, observer=observer) + + assert { + kind: lost.count for kind, lost in summary.lost_observer_events.items() + } == {"status": 4 * N_ROWS, "logging": N_ROWS} + assert list(summary.lost_observer_events) == ["logging", "status"] + assert len(messages) == 1 + + +def test_a_store_that_fails_partway_reports_only_the_events_after( + orchestrator: Any, arrangement: Arrangement +) -> None: + """Events written before the store failed are kept and not counted as lost.""" + status_database = _database(accept_first=5) + logging_database = _database(accept_first=2) + status = StatusObserver(status_database) + logs = LoggingObserver(logging_database) + job = _job(arrangement) + + summary, messages = _run_losing( + job, orchestrator=orchestrator, observer=CompositeObserver(status, logs) + ) + + assert summary.lost_observer_events == { + "status": LostObserverEvents( + "status", 2 * N_ROWS - 5, "OSError: store refuses writes" + ), + "logging": LostObserverEvents( + "logging", N_ROWS - 2, "OSError: store refuses writes" + ), + } + assert len(messages) == 1 + stored_status = status.get_status() + assert stored_status is not None and stored_status.num_rows == 5 + stored_logs = logs.get_logs() + assert stored_logs is not None and stored_logs.num_rows == 2 + assert _rows(job) == EXPECTED_ROWS + + +def test_a_run_that_records_every_event_reports_nothing( + orchestrator: Any, arrangement: Arrangement +) -> None: + """No loss: an empty mapping and no warning.""" + observer = CompositeObserver( + StatusObserver(_database(accept_first=None)), + LoggingObserver(_database(accept_first=None)), + ) + job = _job(arrangement) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + summary = job.run(orchestrator=orchestrator, observer=observer) + + assert summary.lost_observer_events == {} + assert "observer events" not in repr(summary) + assert "observer events" not in summary._repr_html_() + + +def test_run_async_reports_lost_events(arrangement: Arrangement) -> None: + """``await job.run_async()`` reports and warns as ``job.run()`` does.""" + observer = CompositeObserver( + StatusObserver(_database()), LoggingObserver(_database()) + ) + job = _job(arrangement) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + summary = asyncio.run(job.run_async(observer=observer)) + + assert { + kind: lost.count for kind, lost in summary.lost_observer_events.items() + } == {"status": 2 * N_ROWS, "logging": N_ROWS} + lost_warnings = [ + w for w in caught if issubclass(w.category, ObserverEventsLostWarning) + ] + assert len(lost_warnings) == 1 + assert _rows(job) == EXPECTED_ROWS + + +def test_a_load_only_run_reports_lost_events( + orchestrator: Any, arrangement: Arrangement +) -> None: + """A load-only run's status events (RUNNING and CACHED per loaded row) count too.""" + store = InMemoryArrowDatabase() + _ = _job(arrangement, store).run() + job = _job(arrangement, store) + observer = CompositeObserver( + StatusObserver(_database()), LoggingObserver(_database()) + ) + + summary, messages = _run_losing( + job, orchestrator=orchestrator, observer=observer, load_only=True + ) + + # No function is called in a load-only run, so there is no log row to lose. + assert summary.load_only + assert summary.lost_observer_events == { + "status": LostObserverEvents( + "status", 2 * N_ROWS, "OSError: store refuses writes" + ) + } + assert summary.nodes[LABEL].reused == N_ROWS + assert len(messages) == 1 + assert _rows(job) == EXPECTED_ROWS + + +def test_each_run_reports_its_own_losses( + orchestrator: Any, arrangement: Arrangement +) -> None: + """A later run with the same observer does not repeat an earlier run's losses.""" + status_database = _database() + observer = StatusObserver(status_database) + store = InMemoryArrowDatabase() + + first, first_messages = _run_losing( + _job(arrangement, store), orchestrator=orchestrator, observer=observer + ) + status_database.refusals.accept_first = None + second_job = _job(arrangement, store) + with warnings.catch_warnings(): + warnings.simplefilter("error") + second = second_job.run(orchestrator=orchestrator, observer=observer) + # Every node now holds a current run: nothing runs and nothing can be lost. + held = second_job.run(orchestrator=orchestrator, observer=observer) + + assert first.lost_observer_events["status"].count == 2 * N_ROWS + assert len(first_messages) == 1 + assert second.lost_observer_events == {} + assert held.ran_nothing and held.lost_observer_events == {} + + +def test_a_job_nodes_own_run_takes_no_observer_and_reports_no_loss( + arrangement: Arrangement, +) -> None: + """``node.run()`` has no observer argument, so its summary lists no lost event.""" + job = _job(arrangement) + node: Any = job.nodes[LABEL] + + with warnings.catch_warnings(): + warnings.simplefilter("error") + _ = node.run() + full = node.last_run + node.clear_cache() + _ = node.run(load_only=True) + loaded = node.last_run + + assert full.lost_observer_events == {} + assert loaded.load_only and loaded.lost_observer_events == {} + + +def test_the_summary_shows_the_lost_events(arrangement: Arrangement) -> None: + """``repr`` and the notebook display name each kind, its count and first error.""" + observer = CompositeObserver( + StatusObserver(_database()), LoggingObserver(_database()) + ) + summary, _ = _run_losing(_job(arrangement), observer=observer) + + line = ( + f"observer events not recorded: {N_ROWS} logging events (first error: " + f"OSError: store refuses writes); {2 * N_ROWS} status events (first error: " + "OSError: store refuses writes)" + ) + assert line in repr(summary) + assert line in summary._repr_html_() + # The headline still speaks of rows only: no existing field changed meaning. + assert "all rows succeeded" in repr(summary) + + +def test_the_log_line_of_each_failed_write_is_kept( + arrangement: Arrangement, caplog: pytest.LogCaptureFixture +) -> None: + """Each failed write is still logged with its traceback, when it happens.""" + observer = CompositeObserver( + StatusObserver(_database()), LoggingObserver(_database()) + ) + with caplog.at_level(logging.ERROR, logger="orcapod.pipeline"): + _ = _run_losing(_job(arrangement), observer=observer) + + status_lines = [r for r in caplog.records if "status event" in r.getMessage()] + log_lines = [r for r in caplog.records if "log row" in r.getMessage()] + assert len(status_lines) == 2 * N_ROWS + assert len(log_lines) == N_ROWS + assert all(r.exc_info is not None for r in status_lines + log_lines) + + +def test_the_warning_can_be_turned_into_an_error_after_the_run_is_kept( + arrangement: Arrangement, +) -> None: + """With the warning as an error, the run is complete and kept before it raises.""" + job = _job(arrangement) + with warnings.catch_warnings(): + warnings.simplefilter("error", ObserverEventsLostWarning) + with pytest.raises(ObserverEventsLostWarning): + _ = job.run(observer=StatusObserver(_database())) + + assert job.last_run is not None + assert job.last_run.lost_observer_events["status"].count == 2 * N_ROWS + assert _rows(job) == EXPECTED_ROWS From 9ef05a9f385e4148012245744aced71c1477290a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 23:48:43 -0800 Subject: [PATCH 02/16] test(observers): a re-contextualized status observer keeps its run (ITL-1556) Co-Authored-By: Claude Fable 5.2 --- .../test_observer_event_losses.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index 7250b2012..a0e202dbb 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -424,3 +424,26 @@ def test_the_warning_can_be_turned_into_an_error_after_the_run_is_kept( assert job.last_run is not None assert job.last_run.lost_observer_events["status"].count == 2 * N_ROWS assert _rows(job) == EXPECTED_ROWS + + +def test_a_recontextualized_status_observer_keeps_its_run() -> None: + """A copy contextualized twice writes its run's id and reports under it.""" + from orcapod.core.datagrams import Tag + from orcapod.pipeline.observer_losses import collecting_lost_events + + stored = StatusObserver(InMemoryArrowDatabase()) + stored.on_run_start("run-1", pipeline_uri="p@1") + tag: Any = Tag({"t1": "a", "t2": 1}) + stored.contextualize("a").contextualize("b").on_data_start("n", tag, None) # pyright: ignore[reportArgumentType] # the status observer does not read the data + table = stored.get_status() + assert table is not None + assert table.column("_status_run_id").to_pylist() == ["run-1"] + assert table.column("_status_pipeline_uri").to_pylist() == ["p@1"] + + refusing = StatusObserver(_database()) + refusing.on_run_start("run-2") + with collecting_lost_events("run-2") as losses: + refusing.contextualize("a").contextualize("b").on_data_start("n", tag, None) # pyright: ignore[reportArgumentType] # as above + assert losses.by_kind() == { + "status": LostObserverEvents("status", 1, "OSError: store refuses writes") + } From 3f380c5b9f1d8966780939f7f24607aa429c8d14 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 00:43:10 -0800 Subject: [PATCH 03/16] fix(observers): isolate event losses per job execution --- docs/dev/design_issues/ITL-1556-OBS1.md | 7 +- src/orcapod/pipeline/composite_observer.py | 20 +- src/orcapod/pipeline/job.py | 32 +-- src/orcapod/pipeline/logging_observer.py | 33 ++- src/orcapod/pipeline/observer_losses.py | 79 +++--- src/orcapod/pipeline/status_observer.py | 31 ++- .../test_observer_event_losses.py | 237 +++++++++++++++++- 7 files changed, 347 insertions(+), 92 deletions(-) diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md index 6ad1a8f3e..5dca7664a 100644 --- a/docs/dev/design_issues/ITL-1556-OBS1.md +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -13,9 +13,10 @@ successfully with its status and log records missing or incomplete, and nothing one case only (a SQLite-backed store is accepted at setup and refuses every event row). **Fix:** Developer decision (November 28, 2026): the observers continue, and the loss is -reported. A job run opens a record of lost events under its run id -(`pipeline/observer_losses.py`, `collecting_lost_events`); an observer that fails to write -adds to the record of its run (`record_lost_event`) after the log line it always wrote. The +reported. A job creates a counter for its execution (`pipeline/observer_losses.py`, +`RunLosses`) and gives it to copies of the built-in observers. Node-scoped observers and +data loggers carry that counter, so overlapping executions remain independent even when +they share an observer or a run id. A failed write is counted and logged. The run puts the record in `RunSummary.lost_observer_events` (per observer kind: count and first error's text) and issues one `ObserverEventsLostWarning` at the end of the run, after the summary is kept, at the caller's line. The end and not the first loss: the counts are diff --git a/src/orcapod/pipeline/composite_observer.py b/src/orcapod/pipeline/composite_observer.py index 655866c64..dc683e682 100644 --- a/src/orcapod/pipeline/composite_observer.py +++ b/src/orcapod/pipeline/composite_observer.py @@ -22,12 +22,17 @@ from __future__ import annotations -from typing import Any, cast +from copy import copy +from typing import TYPE_CHECKING, Any, Self, cast from orcapod.pipeline.observer import NoOpLogger +from orcapod.pipeline.observer_losses import RunLossObserver from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import SchemaLike +if TYPE_CHECKING: + from orcapod.pipeline.observer_losses import RunLosses + _NOOP_LOGGER = NoOpLogger() @@ -52,6 +57,19 @@ def contextualize(self, *identity_path: str) -> "CompositeObserver": *[o.contextualize(*identity_path) for o in self._observers] ) + def _with_run_losses(self, losses: RunLosses) -> Self: + """Copy this composite and bind its built-in children to a job execution.""" + observer = copy(self) + observer._observers = [ + child._with_run_losses(losses) + if isinstance(child, CompositeObserver) + else child.with_run_losses(losses) + if isinstance(child, RunLossObserver) + else child + for child in self._observers + ] + return observer + def on_run_start(self, run_id: str, **kwargs: Any) -> None: for o in self._observers: o.on_run_start(run_id, **kwargs) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 4c266b5e1..b448ce4ac 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -32,7 +32,7 @@ clear_run_rows, plan_run, ) -from orcapod.pipeline.observer_losses import collecting_lost_events +from orcapod.pipeline.observer_losses import RunLosses from orcapod.pipeline.restrictions import ( refuse_restricted_operator_caches, refuse_restriction_conflicts, @@ -108,13 +108,16 @@ class _PreparedRun: def _with_counter( - observer: "ExecutionObserverProtocol | None", counter: RunCountingObserver + observer: "ExecutionObserverProtocol | None", + counter: RunCountingObserver, + losses: RunLosses, ) -> "ExecutionObserverProtocol": """The observer a run passes to its orchestrator: the user's, plus the row counter. Args: observer: The observer the user passed to ``run``, if any. counter: The run's row counter. + losses: The run's observer write losses. Returns: ``counter`` alone, or a ``CompositeObserver`` calling ``observer`` then ``counter``. @@ -123,7 +126,7 @@ def _with_counter( return counter from orcapod.pipeline.composite_observer import CompositeObserver - return CompositeObserver(observer, counter) # pyright: ignore[reportReturnType] # forwards every hook; its **kwargs signatures do not match the protocol structurally + return CompositeObserver(observer, counter)._with_run_losses(losses) # pyright: ignore[reportPrivateUsage, reportReturnType] # forwards every hook; its **kwargs signatures do not match the protocol structurally class PipelineJob(AbstractPipelineBase[JobNode]): @@ -1090,16 +1093,15 @@ def run( effective_orchestrator = orchestrator or SyncPipelineOrchestrator() is_sync = isinstance(effective_orchestrator, SyncPipelineOrchestrator) # Observer events that cannot be written do not stop the run; they are - # counted under the run's id and reported at its end (ITL-1556). - with ( - collecting_lost_events(prepared.run_id) as losses, - self._executing(prepared, plan, commit_every_rows, load_only=load_only), - ): + # counted by the run's observers and reported at its end (ITL-1556). + losses = RunLosses() + run_observer = _with_counter(observer, counter, losses) + with self._executing(prepared, plan, commit_every_rows, load_only=load_only): if is_sync: # Held nodes give their output streams on the sync path (ITL-1347). _ = effective_orchestrator.run( plan.dag, - observer=_with_counter(observer, counter), + observer=run_observer, run_id=prepared.run_id, pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, @@ -1110,7 +1112,7 @@ def run( # The async path sends the rows the plan took (until stage 5). _ = effective_orchestrator.run( plan.dag, - observer=_with_counter(observer, counter), + observer=run_observer, run_id=prepared.run_id, pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, @@ -1183,14 +1185,12 @@ async def run_async( # The state rule (ITL-1095): a node that holds a current run is not run again. plan = prepared.plan counter = RunCountingObserver() - # Lost observer events are counted under the run's id, as in ``run`` (ITL-1556). - with ( - collecting_lost_events(prepared.run_id) as losses, - self._executing(prepared, plan, commit_every_rows, load_only=load_only), - ): + losses = RunLosses() + run_observer = _with_counter(observer, counter, losses) + with self._executing(prepared, plan, commit_every_rows, load_only=load_only): _ = await orchestrator.run_async( plan.dag, - observer=_with_counter(observer, counter), + observer=run_observer, run_id=prepared.run_id, pipeline_uri=prepared.pipeline_uri, materialize_results=materialize_results, diff --git a/src/orcapod/pipeline/logging_observer.py b/src/orcapod/pipeline/logging_observer.py index 730bd1e76..5786c300c 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -53,7 +53,12 @@ from orcapod.pipeline._observer_database import require_observer_database from orcapod.pipeline.logging_capture import install_capture_streams -from orcapod.pipeline.observer_losses import LOGGING_EVENTS, record_lost_event +from orcapod.pipeline.observer_losses import ( + LOGGING_EVENTS, + RunLosses, + RunLossObserver, + report_lost_event, +) from orcapod.protocols.core_protocols import DataProtocol, TagProtocol if TYPE_CHECKING: @@ -86,11 +91,14 @@ def __init__( log_path: tuple[str, ...], run_id: str, tag_data: dict[str, Any], + *, + losses: RunLosses | None = None, ) -> None: self._db = db self._log_path = log_path self._run_id = run_id self._tag_data = tag_data + self._run_losses = losses def record(self, **kwargs: Any) -> None: """Write one log row to the database. @@ -133,13 +141,16 @@ def record(self, **kwargs: Any) -> None: except Exception as error: # The run goes on: its results do not depend on this row. The loss is # logged here and reported by the run (ITL-1556). - logger.exception( + report_lost_event( + self._run_losses, + LOGGING_EVENTS, + error, + logger, "LoggingObserver: failed to write log row", ) - record_lost_event(self._run_id, LOGGING_EVENTS, error) -class LoggingObserver: +class LoggingObserver(RunLossObserver): """Writes data-level logs to a pre-scoped log database. Instantiate once, outside the pipeline, and pass to the orchestrator:: @@ -185,7 +196,7 @@ def contextualize(self, *identity_path: str) -> "_ContextualizedLoggingObserver" "LoggingObserver.contextualize() requires a non-empty identity_path." ) return _ContextualizedLoggingObserver( - self._db.at(*identity_path), self._current_run_id + self._db.at(*identity_path), self._current_run_id, self._run_losses ) # -- lifecycle hooks -- @@ -237,6 +248,7 @@ def create_data_logger( log_path=DEFAULT_LOG_PATH, run_id=self._current_run_id, tag_data=dict(tag), + losses=self._run_losses, ) # -- convenience -- @@ -311,7 +323,7 @@ def from_config( return cls(db) -class _ContextualizedLoggingObserver: +class _ContextualizedLoggingObserver(RunLossObserver): """ExecutionObserverProtocol implementation bound to a specific node identity path. One instance per node per run, created via LoggingObserver.contextualize(). @@ -325,16 +337,20 @@ def __init__( self, db: ArrowDatabaseProtocol, run_id: str = "", + losses: RunLosses | None = None, ) -> None: self._db = db self._run_id = run_id + self._run_losses = losses def contextualize(self, *identity_path: str) -> "_ContextualizedLoggingObserver": """Re-contextualize with a new identity path (scopes the DB).""" - return _ContextualizedLoggingObserver(self._db.at(*identity_path), self._run_id) + return _ContextualizedLoggingObserver( + self._db.at(*identity_path), self._run_id, self._run_losses + ) def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: - pass + self._run_id = run_id def on_run_end(self, run_id: str) -> None: pass @@ -382,4 +398,5 @@ def create_data_logger( log_path=DEFAULT_LOG_PATH, run_id=self._run_id, tag_data=tag_data, + losses=self._run_losses, ) diff --git a/src/orcapod/pipeline/observer_losses.py b/src/orcapod/pipeline/observer_losses.py index 241e89b4f..557567cb6 100644 --- a/src/orcapod/pipeline/observer_losses.py +++ b/src/orcapod/pipeline/observer_losses.py @@ -1,28 +1,20 @@ """Observer events a run could not record (ITL-1556). -The status and logging observers record run events as rows in a database. A write that -fails does not stop the run: its results do not depend on those rows. The loss is -reported instead. A run opens a record under its run id (``collecting_lost_events``), an -observer that fails to write an event adds to the record of its run -(``record_lost_event``), and the run puts the record in its ``RunSummary`` and warns once -at its end. - -The record is found by run id, which every observer of a run is given -(``on_run_start``), so it holds for each contextualized copy of an observer and for an -observer inside a ``CompositeObserver`` alike. An event lost outside an open record (an -observer handed to an orchestrator or a node directly, with no job run to report it) is -only logged by its observer. +Each job execution gives its built-in observers a shared counter. Their contextualized +copies and data loggers carry the counter with them, including onto worker threads. +An observer used directly by an orchestrator or node only logs failed writes. """ from __future__ import annotations import threading -from contextlib import contextmanager +from copy import copy from dataclasses import dataclass from typing import TYPE_CHECKING if TYPE_CHECKING: - from collections.abc import Iterator + import logging + from typing import Self STATUS_EVENTS = "status" """The kind of the events a ``StatusObserver`` records.""" @@ -67,7 +59,11 @@ def record(self, kind: str, error: BaseException) -> None: kind: The observer kind. error: What the failed write raised. """ - text = f"{type(error).__name__}: {error}" + try: + message = str(error) + except Exception: + message = "" + text = f"{type(error).__name__}: {message}" with self._lock: self._counts[kind] = self._counts.get(kind, 0) + 1 _ = self._first_errors.setdefault(kind, text) @@ -85,40 +81,31 @@ def by_kind(self) -> dict[str, LostObserverEvents]: } -_open_lock = threading.Lock() -_open_records: dict[str, RunLosses] = {} +class RunLossObserver: + """A built-in observer whose copy can collect losses for one job execution.""" + _run_losses: RunLosses | None = None -@contextmanager -def collecting_lost_events(run_id: str) -> Iterator[RunLosses]: - """Keep a record of the observer events lost under ``run_id`` while the block runs. + def with_run_losses(self, losses: RunLosses) -> Self: + """Copy the observer with a counter for this job's execution.""" + observer = copy(self) + observer._run_losses = losses + return observer - Args: - run_id: The run's id, as the run gives it to its observers. - Yields: - The run's record; read it (``by_kind``) once the run's nodes have finished. - """ - losses = RunLosses() - with _open_lock: - _open_records[run_id] = losses - try: - yield losses - finally: - with _open_lock: - if _open_records.get(run_id) is losses: - del _open_records[run_id] - - -def record_lost_event(run_id: str, kind: str, error: BaseException) -> None: - """Add one lost event to the record of run ``run_id``, if a run keeps one. - - Args: - run_id: The run the observer was started for. - kind: The observer kind (``STATUS_EVENTS`` or ``LOGGING_EVENTS``). - error: What the failed write raised. - """ - with _open_lock: - losses = _open_records.get(run_id) +def report_lost_event( + losses: RunLosses | None, + kind: str, + error: Exception, + logger: logging.Logger, + message: str, + *args: str, +) -> None: + """Count a failed observer write and log the exception from its handler.""" if losses is not None: losses.record(kind, error) + try: + logger.exception(message, *args, stacklevel=2) + except Exception: + # An application log handler can raise. The observer write remains nonfatal. + pass diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index 0800a244b..740be687d 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -60,7 +60,11 @@ from orcapod.pipeline._observer_database import require_observer_database from orcapod.pipeline.observer import NoOpLogger -from orcapod.pipeline.observer_losses import STATUS_EVENTS, record_lost_event +from orcapod.pipeline.observer_losses import ( + STATUS_EVENTS, + RunLossObserver, + report_lost_event, +) from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import SchemaLike @@ -77,7 +81,7 @@ _NOOP_LOGGER = NoOpLogger() -class StatusObserver: +class StatusObserver(RunLossObserver): """Writes node execution status to a pre-scoped status database. Instantiate once, outside the pipeline, and pass to the orchestrator:: @@ -124,6 +128,7 @@ def contextualize(self, *identity_path: str) -> "_ContextualizedStatusObserver": ctx = _ContextualizedStatusObserver(self._db.at(*identity_path)) ctx._current_run_id = self._current_run_id ctx._current_pipeline_uri = self._current_pipeline_uri + ctx._run_losses = self._run_losses return ctx # -- lifecycle hooks -- @@ -135,7 +140,7 @@ def on_run_start( ) -> None: self._current_run_id = run_id self._current_pipeline_uri = pipeline_uri - self._tag_schema_per_node.clear() + self._tag_schema_per_node = {} def on_run_end(self, run_id: str) -> None: self._tag_schema_per_node.clear() @@ -305,15 +310,18 @@ def _write_event( except Exception as error: # The run goes on: its results do not depend on this row. The loss is # logged here and reported by the run (ITL-1556). - logger.exception( + report_lost_event( + self._run_losses, + STATUS_EVENTS, + error, + logger, "StatusObserver: failed to write status event for node=%s state=%s", node_label, state, ) - record_lost_event(self._current_run_id, STATUS_EVENTS, error) -class _ContextualizedStatusObserver: +class _ContextualizedStatusObserver(RunLossObserver): """ExecutionObserverProtocol implementation bound to a specific node identity path. One instance is created per node per run via StatusObserver.contextualize(). @@ -336,10 +344,10 @@ def __init__( def contextualize(self, *identity_path: str) -> "_ContextualizedStatusObserver": """Re-contextualize with a new identity path (scopes the DB).""" ctx = _ContextualizedStatusObserver(self._db.at(*identity_path)) - # The copy belongs to the same run: its events carry, and its losses are - # reported under, that run's id. + # The copy belongs to the same execution and keeps its metadata and counter. ctx._current_run_id = self._current_run_id ctx._current_pipeline_uri = self._current_pipeline_uri + ctx._run_losses = self._run_losses return ctx def on_run_start( @@ -441,10 +449,13 @@ def _write_event( except Exception as error: # The run goes on; the loss is logged here and reported by the run # (ITL-1556). - logger.exception( + report_lost_event( + self._run_losses, + STATUS_EVENTS, + error, + logger, "_ContextualizedStatusObserver: failed to write status event " "for node=%s state=%s", node_label, state, ) - record_lost_event(self._current_run_id, STATUS_EVENTS, error) diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index a0e202dbb..63c814762 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -13,9 +13,12 @@ import threading import warnings from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace from typing import Any import pytest +from typing_extensions import override from orcapod import PipelineJob, function_pod from orcapod.databases import InMemoryArrowDatabase @@ -29,6 +32,7 @@ StatusObserver, SyncPipelineOrchestrator, ) +from orcapod.pipeline.observer import NoOpObserver from tests.test_core.operators.several_items import ( DATA_FIRST_REVERSED, MAIN, @@ -68,8 +72,11 @@ class _Refusals: writes: The writes attempted so far. """ - def __init__(self, accept_first: int | None) -> None: + def __init__( + self, accept_first: int | None, error: type[OSError] = OSError + ) -> None: self.accept_first: int | None = accept_first + self.error = error self.writes: int = 0 # Observer hooks may be called from several threads. self.lock: threading.Lock = threading.Lock() @@ -100,16 +107,16 @@ def add_record(self, *args: Any, **kwargs: Any) -> None: and refusals.writes > refusals.accept_first ) if refused: - raise OSError("store refuses writes") + raise refusals.error("store refuses writes") self._database.add_record(*args, **kwargs) def __getattr__(self, name: str) -> Any: return getattr(self._database, name) -def _database(accept_first: int | None = 0) -> Any: +def _database(accept_first: int | None = 0, *, error: type[OSError] = OSError) -> Any: """A database refusing every write after the first ``accept_first``.""" - return _RefusingDatabase(InMemoryArrowDatabase(), _Refusals(accept_first)) + return _RefusingDatabase(InMemoryArrowDatabase(), _Refusals(accept_first, error)) def _job(arrangement: Arrangement, store: Any = None) -> PipelineJob: @@ -429,7 +436,7 @@ def test_the_warning_can_be_turned_into_an_error_after_the_run_is_kept( def test_a_recontextualized_status_observer_keeps_its_run() -> None: """A copy contextualized twice writes its run's id and reports under it.""" from orcapod.core.datagrams import Tag - from orcapod.pipeline.observer_losses import collecting_lost_events + from orcapod.pipeline.observer_losses import RunLosses stored = StatusObserver(InMemoryArrowDatabase()) stored.on_run_start("run-1", pipeline_uri="p@1") @@ -440,10 +447,224 @@ def test_a_recontextualized_status_observer_keeps_its_run() -> None: assert table.column("_status_run_id").to_pylist() == ["run-1"] assert table.column("_status_pipeline_uri").to_pylist() == ["p@1"] - refusing = StatusObserver(_database()) + losses = RunLosses() + refusing = StatusObserver(_database()).with_run_losses(losses) refusing.on_run_start("run-2") - with collecting_lost_events("run-2") as losses: - refusing.contextualize("a").contextualize("b").on_data_start("n", tag, None) # pyright: ignore[reportArgumentType] # as above + refusing.contextualize("a").contextualize("b").on_data_start("n", tag, None) # pyright: ignore[reportArgumentType] # as above assert losses.by_kind() == { "status": LostObserverEvents("status", 1, "OSError: store refuses writes") } + + +def test_overlapping_async_jobs_can_share_observers() -> None: + """Both jobs count the events lost by their own execution.""" + observer = CompositeObserver( + StatusObserver(_database()), LoggingObserver(_database()) + ) + first, second = (_job(arrangement) for arrangement in ARRANGEMENTS) + + async def run_both() -> tuple[RunSummary, RunSummary]: + return await asyncio.gather( + first.run_async(observer=observer), second.run_async(observer=observer) + ) + + with pytest.warns(ObserverEventsLostWarning) as caught: + summaries = asyncio.run(run_both()) + + assert len(caught) == 2 + for summary in summaries: + assert { + kind: lost.count for kind, lost in summary.lost_observer_events.items() + } == { + "status": 2 * N_ROWS, + "logging": N_ROWS, + } + assert _rows(first) == _rows(second) == EXPECTED_ROWS + + +class _RunStart(NoOpObserver): + """Remember the ID delivered to the observer at the start of the run.""" + + run_id: str = "" + + @override + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + self.run_id = run_id + + +class _GateRunStart(_RunStart): + """Hold a run in its start hook while a second run finishes.""" + + def __init__(self) -> None: + self.started: threading.Event = threading.Event() + self.release: threading.Event = threading.Event() + + @override + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + super().on_run_start(run_id, pipeline_uri) + self.started.set() + assert self.release.wait(timeout=10) + + +@pytest.mark.parametrize("same_id", [False, True], ids=["shared-observer", "same-id"]) +def test_overlapping_sync_jobs_keep_separate_losses( + same_id: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """Sharing the observer or reusing the public ID cannot connect two runs.""" + if same_id: + original = PipelineJob._prepare_run # pyright: ignore[reportPrivateUsage] + + def prepare_run(job: PipelineJob, *args: Any, **kwargs: Any) -> Any: + return replace(original(job, *args, **kwargs), run_id="12345678abcd4eee") + + monkeypatch.setattr(PipelineJob, "_prepare_run", prepare_run) + + gate = _GateRunStart() + second_start = _RunStart() + first, second = (_job(arrangement) for arrangement in ARRANGEMENTS) + status = StatusObserver(_database()) + second_status = StatusObserver(_database()) if same_id else status + first_observer: Any = CompositeObserver(status, gate) + second_observer: Any = CompositeObserver(second_status, second_start) + with ( + pytest.warns(ObserverEventsLostWarning) as caught, + ThreadPoolExecutor(2) as pool, + ): + pending = pool.submit(first.run, observer=first_observer) + try: + assert gate.started.wait(timeout=10) + second_summary = pool.submit(second.run, observer=second_observer).result( + timeout=10 + ) + finally: + gate.release.set() + first_summary = pending.result(timeout=10) + + assert len(caught) == 2 + assert (gate.run_id == second_start.run_id) is same_id + for summary in (first_summary, second_summary): + assert summary.lost_observer_events["status"].count == 2 * N_ROWS + + +@pytest.mark.parametrize( + "shared_observer", [False, True], ids=["direct-only", "shared"] +) +def test_direct_orchestrator_with_the_jobs_id_cannot_report_losses_for_it( + shared_observer: bool, +) -> None: + """A nested direct execution shares neither the job's report nor its warning.""" + direct_store = _database() + direct_job = _job(ARRANGEMENTS[1]) + status = StatusObserver(direct_store) + + class RunDirectly(NoOpObserver): + @override + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + _ = SyncPipelineOrchestrator().run( + direct_job.dag, observer=status, run_id=run_id + ) + + nested_run = RunDirectly() + observer = CompositeObserver(status, nested_run) if shared_observer else nested_run + summary, messages = _run_losing(_job(ARRANGEMENTS[0]), observer=observer) + + assert direct_store.refusals.writes == (4 if shared_observer else 2) * N_ROWS + if shared_observer: + assert summary.lost_observer_events["status"].count == 2 * N_ROWS + assert len(messages) == 1 + else: + assert summary.lost_observer_events == {} + assert messages == [] + + +class _UnprintableWriteError(OSError): + @override + def __str__(self) -> str: + raise RuntimeError("could not format the failed write") + + +@pytest.mark.parametrize("kind", ["status", "logging"]) +def test_unprintable_write_error_preserves_rows( + kind: str, orchestrator: Any, arrangement: Arrangement +) -> None: + """Summarizing either observer's error cannot damage the run.""" + database = _database(error=_UnprintableWriteError) + observer = ( + StatusObserver(database) if kind == "status" else LoggingObserver(database) + ) + count = 2 * N_ROWS if kind == "status" else N_ROWS + job = _job(arrangement) + summary, messages = _run_losing(job, orchestrator=orchestrator, observer=observer) + + assert summary.lost_observer_events == { + kind: LostObserverEvents( + kind, count, "_UnprintableWriteError: " + ) + } + assert len(messages) == 1 + assert summary.ok and _rows(job) == EXPECTED_ROWS + + +def test_a_failing_log_handler_cannot_interrupt_loss_reporting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A log sink failure cannot prevent either built-in from recording a loss.""" + + class RefusingHandler(logging.Handler): + @override + def emit(self, record: logging.LogRecord) -> None: + raise OSError("log sink unavailable") + + log = logging.getLogger("orcapod.pipeline") + monkeypatch.setattr(log, "handlers", [RefusingHandler()]) + observer = CompositeObserver( + StatusObserver(_database()), LoggingObserver(_database()) + ) + job = _job(ARRANGEMENTS[0]) + summary, messages = _run_losing(job, observer=observer) + + assert { + kind: loss.count for kind, loss in summary.lost_observer_events.items() + } == { + "status": 2 * N_ROWS, + "logging": N_ROWS, + } + assert len(messages) == 1 + assert summary.ok and _rows(job) == EXPECTED_ROWS + + +def test_precontextualized_logging_observer_uses_the_current_run( + orchestrator: Any, arrangement: Arrangement +) -> None: + """A twice scoped observer replaces stale metadata and counts failed writes.""" + observer = LoggingObserver(_database(accept_first=1)) + observer.on_run_start("earlier-run") + scoped = observer.contextualize("tenant").contextualize("project") + started = _RunStart() + job = _job(arrangement) + summary, messages = _run_losing( + job, orchestrator=orchestrator, observer=CompositeObserver(scoped, started) + ) + + assert summary.lost_observer_events["logging"].count == N_ROWS - 1 + assert len(messages) == 1 + logs = observer.get_logs() + assert logs is not None + assert logs["_log_run_id"].to_pylist() == [started.run_id] + assert _rows(job) == EXPECTED_ROWS + + +def test_async_orchestrator_on_its_own_thread_keeps_the_jobs_losses() -> None: + """A blocking async run in a running event loop reports from its new thread.""" + + async def run() -> tuple[RunSummary, list[str]]: + return _run_losing( + _job(ARRANGEMENTS[0]), + orchestrator=AsyncPipelineOrchestrator(), + observer=LoggingObserver(_database()).contextualize("tenant"), + ) + + summary, messages = asyncio.run(run()) + + assert summary.lost_observer_events["logging"].count == N_ROWS + assert len(messages) == 1 From 02b3575f60870ec8ec0378036ef0367a26641b04 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:21:20 -0800 Subject: [PATCH 04/16] fix(observers): preserve lifecycle and report encoding losses (ITL-1556) --- changelog.d/ITL-1556.md | 5 +- docs/concepts/pipeline-job.md | 6 +- docs/dev/design_issues/ITL-1556-OBS1.md | 11 +- docs/troubleshooting.md | 19 +- src/orcapod/pipeline/composite_observer.py | 42 ++-- src/orcapod/pipeline/job.py | 72 +++++-- src/orcapod/pipeline/logging_observer.py | 52 ++--- src/orcapod/pipeline/run_summary.py | 9 +- src/orcapod/pipeline/status_observer.py | 118 ++++++------ src/orcapod/utils/warning_utils.py | 39 +++- .../test_observer_event_losses.py | 180 +++++++++++++++++- 11 files changed, 405 insertions(+), 148 deletions(-) diff --git a/changelog.d/ITL-1556.md b/changelog.d/ITL-1556.md index 3064544d3..30f8e935a 100644 --- a/changelog.d/ITL-1556.md +++ b/changelog.d/ITL-1556.md @@ -20,5 +20,6 @@ with its traceback; the loss is now counted in `RunSummary.lost_observer_events` and reported by one `ObserverEventsLostWarning` per run, on the sync and the async orchestrator, for `job.run()`, `job.run_async()` and load-only runs, and for the - observers inside a `CompositeObserver`. A job node's own `run()` takes no observer, so - its summary lists none. (ITL-1556) + built-in observers inside a `CompositeObserver`. Event rows that cannot be encoded + are reported the same way. A job node's own `run()` takes no observer, so its summary + lists none. (ITL-1556) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 1afd5a439..0e5baf81a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -64,9 +64,9 @@ Among `job.run()`'s optional arguments, the tutorial default policy skips failed rows and continues) and `observer=` (`StatusObserver`, `LoggingObserver`) to record what happened during the run. Both observers raise `SpiralDBObserverNotSupportedError` at setup if given a SpiralDB store, so give them -another database such as Delta (ITL-1540). An observer that cannot write an event to its -database does not stop the run: the failure is logged, the run summary counts the lost -events per observer kind in `lost_observer_events`, and one `ObserverEventsLostWarning` is +another database such as Delta (ITL-1540). If a built-in observer cannot encode or write +an event, the failure is logged, the run continues, the summary counts the lost events +per observer kind in `lost_observer_events`, and one `ObserverEventsLostWarning` is issued at the end of the run (ITL-1556). An observer only watches: one that changes the job, its nodes or its bound sources during a run is unsupported, and what the run then does is undefined (ITL-1369). `load_only=True` fills the nodes diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md index 5dca7664a..679257dd2 100644 --- a/docs/dev/design_issues/ITL-1556-OBS1.md +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -16,14 +16,17 @@ one case only (a SQLite-backed store is accepted at setup and refuses every even reported. A job creates a counter for its execution (`pipeline/observer_losses.py`, `RunLosses`) and gives it to copies of the built-in observers. Node-scoped observers and data loggers carry that counter, so overlapping executions remain independent even when -they share an observer or a run id. A failed write is counted and logged. The +they share an observer or a run id. A failed event encoding or write is counted and logged. +Custom observer subclasses receive lifecycle hooks on the supplied instance. The run puts the record in `RunSummary.lost_observer_events` (per observer kind: count and first error's text) and issues one `ObserverEventsLostWarning` at the end of the run, after the summary is kept, at the caller's line. The end and not the first loss: the counts are complete then, the warning turned into an error loses no result, and the first loss happens -inside a node, possibly on a worker thread. Additive: no existing field changed meaning, and -the run's result and exit are unchanged. A run that raises reports nothing beyond the log -lines. A job node's own `run()` takes no observer, so it has nothing to lose. An observer +inside a node, possibly on a worker thread. A completed run reports observer losses even +when the row-failure warning is promoted to an exception. Additive: no existing field +changed meaning, and the run's result and exit are unchanged. A run that raises before +the summary is kept reports nothing beyond the log lines. A job node's own `run()` takes +no observer, so it has nothing to lose. An observer handed directly to an orchestrator or to `node.execute` has no job run to report for it: its failed writes are logged only. A re-contextualized status observer now keeps its run id. Which stores observers work on (the SQLite case) stays open on the issue. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 80793b4fd..cc98b23e3 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -207,16 +207,15 @@ same (`Run of job '...': 1 row failed.`). ### `ObserverEventsLostWarning: Observer events were not recorded in this run: ...` -**Cause.** A `StatusObserver` or `LoggingObserver` could not write some of its rows to its -database (the store refused the write, or failed partway through the run). The run does -not stop for that: its results are complete and are not affected. Only the status and log -records of the run are incomplete. The warning is issued once, at the end of the run, and -gives, per observer kind, how many events were lost and the first error. - -**Fix.** Read the first error in the message; each failed write is also logged with its -traceback (logger `orcapod.pipeline`). The counts are in the run summary: -`job.last_run.lost_observer_events`. Give the observer a database that accepts its rows -(in-memory or Delta), then run again if you need the records. +**Cause.** A `StatusObserver` or `LoggingObserver` could not encode an event row or write +it to its database. The run continues with its usual results and incomplete status or +log records. The warning is issued once, at the end of the run, and gives, per observer +kind, how many events were lost and the first error. + +**Fix.** Check the first error in the message and the traceback in the +`orcapod.pipeline` logs. The counts are in `job.last_run.lost_observer_events`. For a +write error, use a database that accepts the observer's rows, such as in-memory or Delta. +For an encoding error, correct the reported value. Run again if you need the records. ### `TypeError: ...() got an unexpected keyword argument 'ctx'` from a `sink_pod` diff --git a/src/orcapod/pipeline/composite_observer.py b/src/orcapod/pipeline/composite_observer.py index dc683e682..971701026 100644 --- a/src/orcapod/pipeline/composite_observer.py +++ b/src/orcapod/pipeline/composite_observer.py @@ -22,11 +22,9 @@ from __future__ import annotations -from copy import copy -from typing import TYPE_CHECKING, Any, Self, cast +from typing import TYPE_CHECKING, Any, cast from orcapod.pipeline.observer import NoOpLogger -from orcapod.pipeline.observer_losses import RunLossObserver from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import SchemaLike @@ -57,18 +55,32 @@ def contextualize(self, *identity_path: str) -> "CompositeObserver": *[o.contextualize(*identity_path) for o in self._observers] ) - def _with_run_losses(self, losses: RunLosses) -> Self: - """Copy this composite and bind its built-in children to a job execution.""" - observer = copy(self) - observer._observers = [ - child._with_run_losses(losses) - if isinstance(child, CompositeObserver) - else child.with_run_losses(losses) - if isinstance(child, RunLossObserver) - else child - for child in self._observers - ] - return observer + def _with_run_losses(self, losses: RunLosses) -> CompositeObserver: + """Bind concrete built-in children while preserving custom observer instances.""" + from orcapod.pipeline.logging_observer import ( + LoggingObserver, + _ContextualizedLoggingObserver, # pyright: ignore[reportPrivateUsage] + ) + from orcapod.pipeline.status_observer import ( + StatusObserver, + _ContextualizedStatusObserver, # pyright: ignore[reportPrivateUsage] + ) + + built_ins = ( + LoggingObserver, + StatusObserver, + _ContextualizedLoggingObserver, + _ContextualizedStatusObserver, + ) + children: list[Any] = [] + for child in self._observers: + # Custom hooks must keep running on the observer the caller supplied. + if type(child) is CompositeObserver: + child = child._with_run_losses(losses) + elif type(child) in built_ins: + child = child.with_run_losses(losses) + children.append(child) + return CompositeObserver(*children) def on_run_start(self, run_id: str, **kwargs: Any) -> None: for o in self._observers: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index b448ce4ac..914536cf6 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -20,9 +20,11 @@ from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.errors import ( + ObserverEventsLostWarning, OrcapodDatabaseError, OrcapodDatabaseReadError, OrcapodDatabaseWriteError, + RowFailuresWarning, ) from orcapod.pipeline.base import AbstractPipelineBase from orcapod.pipeline.dag import OrcaDAG @@ -50,10 +52,12 @@ from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig from orcapod.utils.database_errors import database_write_path, flush_best_effort +from orcapod.utils.warning_utils import WarningLocation if TYPE_CHECKING: - from collections.abc import Mapping + from collections.abc import Coroutine, Mapping from pathlib import Path + from types import FrameType from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext @@ -129,6 +133,32 @@ def _with_counter( return CompositeObserver(observer, counter)._with_run_losses(losses) # pyright: ignore[reportPrivateUsage, reportReturnType] # forwards every hook; its **kwargs signatures do not match the protocol structurally +def _warn_run_completion( + summary: RunSummary, + caller: FrameType, + *, + observer_location: WarningLocation | None = None, +) -> None: + """Issue both completion warnings while preserving the row warning's precedence.""" + row_warning: RowFailuresWarning | None = None + if not summary.ok: + try: + warn_row_failures(summary, caller) + except RowFailuresWarning as error: + row_warning = error + if summary.lost_observer_events: + try: + warn_lost_observer_events( + summary, observer_location or WarningLocation.from_frame(caller) + ) + except ObserverEventsLostWarning as error: + if row_warning is None: + raise + raise row_warning from error + if row_warning is not None: + raise row_warning + + class PipelineJob(AbstractPipelineBase[JobNode]): """Pipeline + source bindings + execution context. @@ -1129,13 +1159,10 @@ def run( lost_observer_events=losses.by_kind(), ) caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warnings are shown - if not summary.ok: - warn_row_failures(summary, caller) - if summary.lost_observer_events: - warn_lost_observer_events(summary, caller) + _warn_run_completion(summary, caller) return summary - async def run_async( + def run_async( self, orchestrator: "AsyncPipelineOrchestrator | None" = None, observer: "ExecutionObserverProtocol | None" = None, @@ -1143,7 +1170,7 @@ async def run_async( commit_every_rows: int = 100, *, load_only: bool = False, - ) -> RunSummary: + ) -> Coroutine[Any, Any, RunSummary]: """Execute the job with the async orchestrator, from async code. The awaitable form of ``run``: ``await job.run_async()`` runs on the caller's @@ -1161,7 +1188,7 @@ async def run_async( load_only: As for ``run``. Returns: - The run's ``RunSummary``, as ``run`` returns. + A coroutine that returns the run's ``RunSummary``. Raises: TypeError: If ``orchestrator`` is not an ``AsyncPipelineOrchestrator``; @@ -1171,6 +1198,28 @@ async def run_async( OrcapodDatabaseWriteError: As for ``run``. OrcapodDatabaseReadError: As for ``run``. """ + # A scheduler may resume the coroutine after its caller has moved on. + caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] + return self._run_async( + orchestrator, + observer, + materialize_results, + commit_every_rows, + load_only=load_only, + observer_location=WarningLocation.from_frame(caller), + ) + + async def _run_async( + self, + orchestrator: AsyncPipelineOrchestrator | None, + observer: ExecutionObserverProtocol | None, + materialize_results: bool, + commit_every_rows: int, + *, + load_only: bool, + observer_location: WarningLocation, + ) -> RunSummary: + """Execute the job and warn on completion using the captured call site.""" from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator if orchestrator is None: @@ -1206,11 +1255,8 @@ async def run_async( asynchronous=True, lost_observer_events=losses.by_kind(), ) - caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warnings are shown - if not summary.ok: - warn_row_failures(summary, caller) - if summary.lost_observer_events: - warn_lost_observer_events(summary, caller) + caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] # keep the existing row warning location + _warn_run_completion(summary, caller, observer_location=observer_location) return summary def _prepare_run( diff --git a/src/orcapod/pipeline/logging_observer.py b/src/orcapod/pipeline/logging_observer.py index 5786c300c..08260c8a4 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -110,33 +110,33 @@ def record(self, **kwargs: Any) -> None: """ import pyarrow as pa - log_id = uuid7().bytes - timestamp = datetime.now(timezone.utc).isoformat() - - # Context columns — prefixed with "_log_" to follow system column conventions - columns: dict[str, pa.Array] = { - "_log_id": pa.array([log_id], type=pa.binary(16)), - "_log_run_id": pa.array([self._run_id], type=pa.large_utf8()), - "_log_timestamp": pa.array([timestamp], type=pa.large_utf8()), - } - - # Execution output columns from kwargs — prefixed with "_log_" - for key, value in kwargs.items(): - col_name = f"_log_{key}" - if isinstance(value, bool): - columns[col_name] = pa.array([value], type=pa.bool_()) - else: - columns[col_name] = pa.array( - [str(value) if value is not None else None], - type=pa.large_utf8(), - ) - - # Dynamic tag columns — each tag key becomes its own column (unprefixed) - for key, value in self._tag_data.items(): - columns[key] = pa.array([str(value)], type=pa.large_utf8()) - - row = pa.table(columns) try: + log_id = uuid7().bytes + timestamp = datetime.now(timezone.utc).isoformat() + + # Context columns — prefixed with "_log_" to follow system column conventions + columns: dict[str, pa.Array[Any]] = { + "_log_id": pa.array([log_id], type=pa.binary(16)), + "_log_run_id": pa.array([self._run_id], type=pa.large_utf8()), + "_log_timestamp": pa.array([timestamp], type=pa.large_utf8()), + } + + # Execution output columns from kwargs — prefixed with "_log_" + for key, value in kwargs.items(): + col_name = f"_log_{key}" + if isinstance(value, bool): + columns[col_name] = pa.array([value], type=pa.bool_()) + else: + columns[col_name] = pa.array( + [str(value) if value is not None else None], + type=pa.large_utf8(), + ) + + # Dynamic tag columns — each tag key becomes its own column (unprefixed) + for key, value in self._tag_data.items(): + columns[key] = pa.array([str(value)], type=pa.large_utf8()) + + row = pa.Table.from_pydict(columns) self._db.add_record(self._log_path, log_id, row, flush=True) except Exception as error: # The run goes on: its results do not depend on this row. The loss is diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 25df10088..b82b4360d 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -26,6 +26,7 @@ from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.pipeline.restrictions import RestrictedSource from orcapod.types import Condition, SchemaLike + from orcapod.utils.warning_utils import WarningLocation _NOOP_LOGGER = NoOpLogger() _ASYNC_ATTRIBUTION_NOTE = ( @@ -455,7 +456,7 @@ def warn_row_failures(summary: RunSummary, caller: FrameType) -> None: warn_at_frame(summary.failures_message(), RowFailuresWarning, caller) -def warn_lost_observer_events(summary: RunSummary, caller: FrameType) -> None: +def warn_lost_observer_events(summary: RunSummary, location: WarningLocation) -> None: """Issue the run's ``ObserverEventsLostWarning``, at the end of the run (ITL-1556). At the end and not at the first loss: the count and each kind's first error are @@ -466,19 +467,17 @@ def warn_lost_observer_events(summary: RunSummary, caller: FrameType) -> None: Args: summary: The run's summary, with lost observer events. - caller: The frame that called ``run``; the warning is shown at its line. + location: The line that called ``run`` or ``run_async``. """ from orcapod.errors import ObserverEventsLostWarning - from orcapod.utils.warning_utils import warn_at_frame - warn_at_frame( + location.warn( "Observer events were not recorded in this run: " + f"{summary.lost_observer_events_message()}. The run's results are not " + "affected, but its status and log records are incomplete. Each failed " + "write was logged with its traceback; the counts are in the run " + "summary's lost_observer_events.", ObserverEventsLostWarning, - caller, ) diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index 740be687d..e0ecd6172 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -277,43 +277,45 @@ def _write_event( """Build and write a single status event row.""" import pyarrow as pa - tag_schema = self._tag_schema_per_node.get(node_label, {}) - - status_id = uuid7().bytes - timestamp = datetime.now(timezone.utc).isoformat() - - columns: dict[str, pa.Array] = { - "_status_id": pa.array([status_id], type=pa.binary(16)), - "_status_run_id": pa.array([self._current_run_id], type=pa.large_utf8()), - "_status_pipeline_uri": pa.array( - [self._current_pipeline_uri], type=pa.large_utf8() - ), - "_status_state": pa.array([state], type=pa.large_utf8()), - "_status_timestamp": pa.array([timestamp], type=pa.large_utf8()), - "_status_error_summary": pa.array( - [str(error) if error is not None else None], - type=pa.large_utf8(), - ), - } - - # Tag columns — use statically-known schema from on_node_start - for key in tag_schema: - value = tag.get(key, None) - columns[key] = pa.array( - [str(value) if value is not None else None], - type=pa.large_utf8(), - ) - - row = pa.table(columns) try: + tag_schema = self._tag_schema_per_node.get(node_label, {}) + + status_id = uuid7().bytes + timestamp = datetime.now(timezone.utc).isoformat() + + columns: dict[str, pa.Array[Any]] = { + "_status_id": pa.array([status_id], type=pa.binary(16)), + "_status_run_id": pa.array( + [self._current_run_id], type=pa.large_utf8() + ), + "_status_pipeline_uri": pa.array( + [self._current_pipeline_uri], type=pa.large_utf8() + ), + "_status_state": pa.array([state], type=pa.large_utf8()), + "_status_timestamp": pa.array([timestamp], type=pa.large_utf8()), + "_status_error_summary": pa.array( + [str(error) if error is not None else None], + type=pa.large_utf8(), + ), + } + + # Tag columns — use statically-known schema from on_node_start + for key in tag_schema: + value = tag.get(key, None) + columns[key] = pa.array( + [str(value) if value is not None else None], + type=pa.large_utf8(), + ) + + row = pa.Table.from_pydict(columns) self._db.add_record(DEFAULT_STATUS_PATH, status_id, row, flush=True) - except Exception as error: + except Exception as event_error: # The run goes on: its results do not depend on this row. The loss is # logged here and reported by the run (ITL-1556). report_lost_event( self._run_losses, STATUS_EVENTS, - error, + event_error, logger, "StatusObserver: failed to write status event for node=%s state=%s", node_label, @@ -419,40 +421,42 @@ def _write_event( """Build and write a single status event row to the scoped database.""" import pyarrow as pa - status_id = uuid7().bytes - timestamp = datetime.now(timezone.utc).isoformat() - - columns: dict[str, pa.Array] = { - "_status_id": pa.array([status_id], type=pa.binary(16)), - "_status_run_id": pa.array([self._current_run_id], type=pa.large_utf8()), - "_status_pipeline_uri": pa.array( - [self._current_pipeline_uri], type=pa.large_utf8() - ), - "_status_state": pa.array([state], type=pa.large_utf8()), - "_status_timestamp": pa.array([timestamp], type=pa.large_utf8()), - "_status_error_summary": pa.array( - [str(error) if error is not None else None], - type=pa.large_utf8(), - ), - } - - for key in self._tag_schema: - value = tag.get(key, None) - columns[key] = pa.array( - [str(value) if value is not None else None], - type=pa.large_utf8(), - ) - - row = pa.table(columns) try: + status_id = uuid7().bytes + timestamp = datetime.now(timezone.utc).isoformat() + + columns: dict[str, pa.Array[Any]] = { + "_status_id": pa.array([status_id], type=pa.binary(16)), + "_status_run_id": pa.array( + [self._current_run_id], type=pa.large_utf8() + ), + "_status_pipeline_uri": pa.array( + [self._current_pipeline_uri], type=pa.large_utf8() + ), + "_status_state": pa.array([state], type=pa.large_utf8()), + "_status_timestamp": pa.array([timestamp], type=pa.large_utf8()), + "_status_error_summary": pa.array( + [str(error) if error is not None else None], + type=pa.large_utf8(), + ), + } + + for key in self._tag_schema: + value = tag.get(key, None) + columns[key] = pa.array( + [str(value) if value is not None else None], + type=pa.large_utf8(), + ) + + row = pa.Table.from_pydict(columns) self._db.add_record(DEFAULT_STATUS_PATH, status_id, row, flush=True) - except Exception as error: + except Exception as event_error: # The run goes on; the loss is logged here and reported by the run # (ITL-1556). report_lost_event( self._run_losses, STATUS_EVENTS, - error, + event_error, logger, "_ContextualizedStatusObserver: failed to write status event " "for node=%s state=%s", diff --git a/src/orcapod/utils/warning_utils.py b/src/orcapod/utils/warning_utils.py index 3d83f5d41..508afcf96 100644 --- a/src/orcapod/utils/warning_utils.py +++ b/src/orcapod/utils/warning_utils.py @@ -5,7 +5,9 @@ import linecache import sys import warnings +from dataclasses import dataclass from types import FrameType +from typing import Any def outside_orcapod_stacklevel() -> int: @@ -29,6 +31,32 @@ def outside_orcapod_stacklevel() -> int: return 2 +@dataclass(frozen=True) +class WarningLocation: + """Capture a warning's location without retaining the caller's frame.""" + + filename: str + lineno: int + module_globals: dict[str, Any] + + @classmethod + def from_frame(cls, frame: FrameType) -> WarningLocation: + """Capture the frame's current line and module.""" + return cls(frame.f_code.co_filename, frame.f_lineno, frame.f_globals) + + def warn(self, message: str, category: type[Warning]) -> None: + """Issue a warning at this location, respecting the active filters.""" + _ = linecache.lazycache(self.filename, self.module_globals) + warnings.warn_explicit( + message, + category, + self.filename, + self.lineno, + module=self.module_globals.get("__name__"), + registry=None, + ) + + def warn_at_frame(message: str, category: type[Warning], frame: FrameType) -> None: """Issue a warning shown at ``frame``'s line, at every call. @@ -65,13 +93,4 @@ def warn_at_frame(message: str, category: type[Warning], frame: FrameType) -> No category: The warning's class. frame: The frame whose file, line and module name the warning is shown at. """ - filename = frame.f_code.co_filename - _ = linecache.lazycache(filename, frame.f_globals) - warnings.warn_explicit( - message, - category, - filename, - frame.f_lineno, - module=frame.f_globals.get("__name__"), - registry=None, - ) + WarningLocation.from_frame(frame).warn(message, category) diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index 63c814762..b780d24f1 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -9,6 +9,7 @@ from __future__ import annotations import asyncio +import inspect import logging import threading import warnings @@ -22,7 +23,7 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import InMemoryArrowDatabase -from orcapod.errors import ObserverEventsLostWarning +from orcapod.errors import ObserverEventsLostWarning, RowFailuresWarning from orcapod.pipeline import ( AsyncPipelineOrchestrator, CompositeObserver, @@ -63,6 +64,29 @@ def describe(d1: int, d3: str) -> tuple[int, str]: return d1 + 1, d3 + d3 +@function_pod(output_keys=("n", "s")) +def describe_and_log(d1: int, d3: str) -> tuple[int, str]: + """Log a filename before returning the row's result.""" + logging.getLogger(__name__).warning("filename: bad\udcff") + return d1 + 1, d3 + d3 + + +@function_pod(output_keys=("n", "s")) +def describe_except_first(d1: int, d3: str) -> tuple[int, str]: + """Raise for one of the six input rows.""" + if d1 == 10: + raise ValueError("bad row") + return d1 + 1, d3 + d3 + + +@function_pod(output_keys=("n", "s")) +def describe_except_unencodable_error(d1: int, d3: str) -> tuple[int, str]: + """Raise with a filesystem-decoded filename for the first row.""" + if d1 == 10: + raise ValueError("filename: bad\udcff") + return d1 + 1, d3 + d3 + + class _Refusals: """Which writes a ``_RefusingDatabase`` and its scoped views refuse. @@ -119,11 +143,13 @@ def _database(accept_first: int | None = 0, *, error: type[OSError] = OSError) - return _RefusingDatabase(InMemoryArrowDatabase(), _Refusals(accept_first, error)) -def _job(arrangement: Arrangement, store: Any = None) -> PipelineJob: +def _job( + arrangement: Arrangement, store: Any = None, *, pod: Any = describe +) -> PipelineJob: """``MAIN`` in ``arrangement`` feeding ``describe`` under ``LABEL``.""" job = PipelineJob(name="losses", database=store or InMemoryArrowDatabase()) with job: - describe.pod(make_source(MAIN, arrangement), label=LABEL) + pod.pod(make_source(MAIN, arrangement), label=LABEL) return job @@ -312,6 +338,154 @@ def test_run_async_reports_lost_events(arrangement: Arrangement) -> None: assert _rows(job) == EXPECTED_ROWS +class _CompletionCounter: + """An observer subclass must receive its own lifecycle events.""" + + finished: int = 0 + + def __copy__(self) -> Any: + """Require lifecycle hooks to use the original instance.""" + raise AssertionError("custom observers cannot be copied") + + +class _CustomComposite(_CompletionCounter, CompositeObserver): + """A composite with a stateful lifecycle hook.""" + + @override + def on_run_end(self, run_id: str) -> None: + self.finished += 1 + super().on_run_end(run_id) + + +class _CustomStatus(_CompletionCounter, StatusObserver): + """A status observer with a stateful lifecycle hook.""" + + @override + def on_run_end(self, run_id: str) -> None: + self.finished += 1 + super().on_run_end(run_id) + + +class _CustomLogging(_CompletionCounter, LoggingObserver): + """A logging observer with a stateful lifecycle hook.""" + + @override + def on_run_end(self, run_id: str) -> None: + self.finished += 1 + super().on_run_end(run_id) + + +@pytest.fixture(params=["sync", "async", "run_async"]) +def run_job(request: pytest.FixtureRequest) -> Callable[[PipelineJob, Any], RunSummary]: + """Run a job through each public run path.""" + if request.param == "run_async": + return lambda job, observer: asyncio.run(job.run_async(observer=observer)) + return lambda job, observer: job.run( + orchestrator=ORCHESTRATORS[request.param](), observer=observer + ) + + +@pytest.mark.parametrize("kind", ["composite", "status", "logging"]) +def test_custom_observers_keep_their_lifecycle( + kind: str, + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], +) -> None: + """Job accounting leaves the caller's custom observer in place.""" + observers = { + "composite": _CustomComposite(StatusObserver(InMemoryArrowDatabase())), + "status": _CustomStatus(InMemoryArrowDatabase()), + "logging": _CustomLogging(InMemoryArrowDatabase()), + } + observer = observers[kind] + job = _job(arrangement) + + assert run_job(job, observer).ok + assert observer.finished == 1 + assert _rows(job) == EXPECTED_ROWS + + +def test_unencodable_log_event_preserves_rows( + arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] +) -> None: + """A filename containing a surrogate can lose a log row but not a result.""" + observer = LoggingObserver(InMemoryArrowDatabase()) + job = _job(arrangement, pod=describe_and_log) + + with pytest.warns(ObserverEventsLostWarning, match="UnicodeEncodeError") as caught: + summary = run_job(job, observer) + + assert len(caught) == 1 + assert summary.nodes[LABEL].computed == N_ROWS + assert summary.ok + assert summary.lost_observer_events["logging"].count == N_ROWS + assert _rows(job) == EXPECTED_ROWS + + +def test_promoted_row_warning_still_reports_observer_losses( + arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] +) -> None: + """A completed run reports losses even when the row warning raises.""" + job = _job(arrangement, pod=describe_except_first) + observer = StatusObserver(_database()) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", ObserverEventsLostWarning) + warnings.simplefilter("error", RowFailuresWarning) + with pytest.raises(RowFailuresWarning): + _ = run_job(job, observer) + + summary = job.last_run + assert summary is not None + assert summary.nodes[LABEL].computed == N_ROWS - 1 + assert summary.nodes[LABEL].failed == 1 + assert summary.lost_observer_events["status"].count == 2 * N_ROWS + assert [warning.category for warning in caught] == [ObserverEventsLostWarning] + + +def test_unencodable_status_event_preserves_other_rows( + arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] +) -> None: + """A status row with an unencodable error is lost and the job still finishes.""" + job = _job(arrangement, pod=describe_except_unencodable_error) + observer = StatusObserver(InMemoryArrowDatabase()) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", RowFailuresWarning) + warnings.simplefilter("always", ObserverEventsLostWarning) + summary = run_job(job, observer) + + assert summary.nodes[LABEL].computed == N_ROWS - 1 + assert summary.nodes[LABEL].failed == 1 + assert summary.lost_observer_events["status"].count == 1 + assert summary.lost_observer_events["status"].first_error.startswith( + "UnicodeEncodeError:" + ) + assert [warning.category for warning in caught] == [ + RowFailuresWarning, + ObserverEventsLostWarning, + ] + assert _rows(job) == [row for row in EXPECTED_ROWS if row[3] != 11] + + +def test_scheduled_run_async_warning_points_to_the_call( + arrangement: Arrangement, +) -> None: + """Scheduling the coroutine later still attributes the loss warning to its call.""" + job = _job(arrangement) + observer = StatusObserver(_database()) + frame = inspect.currentframe() + assert frame is not None + + with pytest.warns(ObserverEventsLostWarning) as caught: + call_line = frame.f_lineno + 1 + pending = job.run_async(observer=observer) + _ = asyncio.run(pending) + + assert len(caught) == 1 + assert (caught[0].filename, caught[0].lineno) == (__file__, call_line) + + def test_a_load_only_run_reports_lost_events( orchestrator: Any, arrangement: Arrangement ) -> None: From 3e3830b1234b96f4ed5aecc98eccbf7326ac18e1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:59:32 -0800 Subject: [PATCH 05/16] fix(observers): preserve lifecycle and run metadata (ITL-1556) --- changelog.d/ITL-1556.md | 5 +- docs/dev/design_issues/ITL-1556-OBS1.md | 32 ++-- src/orcapod/pipeline/composite_observer.py | 43 +++-- src/orcapod/pipeline/job.py | 68 ++----- src/orcapod/pipeline/logging_observer.py | 10 +- src/orcapod/pipeline/observer_losses.py | 18 +- src/orcapod/pipeline/run_summary.py | 14 +- src/orcapod/pipeline/status_observer.py | 13 +- src/orcapod/utils/warning_utils.py | 39 ++-- .../test_observer_event_losses.py | 166 ++++++++++++++---- 10 files changed, 227 insertions(+), 181 deletions(-) diff --git a/changelog.d/ITL-1556.md b/changelog.d/ITL-1556.md index 30f8e935a..790e74faf 100644 --- a/changelog.d/ITL-1556.md +++ b/changelog.d/ITL-1556.md @@ -6,8 +6,9 @@ `orcapod.pipeline`) with the number of events that were not written and the first error's text; it is empty when every event was recorded. The summary's text and notebook display show it as one line. A run with lost events issues one new warning, - `ObserverEventsLostWarning` (`orcapod.errors`), at the end of the run, at the line that - started it. (ITL-1556) + `ObserverEventsLostWarning` (`orcapod.errors`), at the end of the run. It points to the + `run()` call or the line awaiting `run_async()`. For a separately scheduled coroutine, + it points to the event loop's resumption site. (ITL-1556) ### Fixed diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md index 679257dd2..e52874ded 100644 --- a/docs/dev/design_issues/ITL-1556-OBS1.md +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -14,19 +14,19 @@ one case only (a SQLite-backed store is accepted at setup and refuses every even **Fix:** Developer decision (November 28, 2026): the observers continue, and the loss is reported. A job creates a counter for its execution (`pipeline/observer_losses.py`, -`RunLosses`) and gives it to copies of the built-in observers. Node-scoped observers and -data loggers carry that counter, so overlapping executions remain independent even when -they share an observer or a run id. A failed event encoding or write is counted and logged. -Custom observer subclasses receive lifecycle hooks on the supplied instance. The -run puts the record in `RunSummary.lost_observer_events` (per observer kind: count and first -error's text) and issues one `ObserverEventsLostWarning` at the end of the run, after the -summary is kept, at the caller's line. The end and not the first loss: the counts are -complete then, the warning turned into an error loses no result, and the first loss happens -inside a node, possibly on a worker thread. A completed run reports observer losses even -when the row-failure warning is promoted to an exception. Additive: no existing field -changed meaning, and the run's result and exit are unchanged. A run that raises before -the summary is kept reports nothing beyond the log lines. A job node's own `run()` takes -no observer, so it has nothing to lose. An observer -handed directly to an orchestrator or to `node.execute` has no job run to report for it: its -failed writes are logged only. A re-contextualized status observer now keeps its run id. -Which stores observers work on (the SQLite case) stays open on the issue. +`RunLosses`). Node-scoped built-in observers and their data loggers carry that counter, +so overlapping executions count their own losses even when they share an observer or +a run ID. A failed event encoding or write is counted and logged. Lifecycle hooks run +on the caller's original observers, and the built-ins derive event metadata as before. + +The run puts the count and first error for each observer kind in +`RunSummary.lost_observer_events`. It issues one `ObserverEventsLostWarning` after +keeping the completed summary. The warning points to the `run()` call, the +`run_async()` await, or the event loop's resumption site for a separately scheduled +coroutine. A completed run reports observer losses even when preparing or issuing the +row-failure warning raises. The earlier error still propagates. + +A run that raises before keeping a summary reports the losses in the logs. A job +node's own `run()` takes no observer. Observers passed directly to an orchestrator or +`node.execute` report failed writes in the logs. Which stores support observer event +rows remains open on the issue. diff --git a/src/orcapod/pipeline/composite_observer.py b/src/orcapod/pipeline/composite_observer.py index 971701026..4c70ae61e 100644 --- a/src/orcapod/pipeline/composite_observer.py +++ b/src/orcapod/pipeline/composite_observer.py @@ -30,6 +30,7 @@ if TYPE_CHECKING: from orcapod.pipeline.observer_losses import RunLosses + from orcapod.protocols.observability_protocols import ExecutionObserverProtocol _NOOP_LOGGER = NoOpLogger() @@ -42,21 +43,40 @@ class CompositeObserver: ``ExecutionObserverProtocol``. """ + _run_losses: RunLosses | None = None + def __init__(self, *observers: Any) -> None: self._observers = list(observers) def contextualize(self, *identity_path: str) -> "CompositeObserver": """Return a new CompositeObserver wrapping each child's contextualized version.""" + return self._contextualize(identity_path, self._run_losses) + + @classmethod + def _for_run( + cls, + observer: ExecutionObserverProtocol, + counter: ExecutionObserverProtocol, + losses: RunLosses, + ) -> CompositeObserver: + """Keep the original observers for lifecycle calls and count node event losses.""" + composite = cls(observer, counter) + composite._run_losses = losses + return composite + + def _contextualize( + self, identity_path: tuple[str, ...], losses: RunLosses | None + ) -> CompositeObserver: + """Scope the children and attach the job's counter to the built-in results.""" if not identity_path: raise ValueError( "CompositeObserver.contextualize() requires a non-empty identity_path." ) - return CompositeObserver( - *[o.contextualize(*identity_path) for o in self._observers] - ) + if losses is None: + return CompositeObserver( + *[o.contextualize(*identity_path) for o in self._observers] + ) - def _with_run_losses(self, losses: RunLosses) -> CompositeObserver: - """Bind concrete built-in children while preserving custom observer instances.""" from orcapod.pipeline.logging_observer import ( LoggingObserver, _ContextualizedLoggingObserver, # pyright: ignore[reportPrivateUsage] @@ -74,12 +94,15 @@ def _with_run_losses(self, losses: RunLosses) -> CompositeObserver: ) children: list[Any] = [] for child in self._observers: - # Custom hooks must keep running on the observer the caller supplied. + # Only factory results from concrete built-ins belong to this run. + # A custom contextualize() can return a shared or delegated observer. if type(child) is CompositeObserver: - child = child._with_run_losses(losses) - elif type(child) in built_ins: - child = child.with_run_losses(losses) - children.append(child) + scoped = child._contextualize(identity_path, losses) + else: + scoped = child.contextualize(*identity_path) + if type(child) in built_ins: + scoped._run_losses = losses + children.append(scoped) return CompositeObserver(*children) def on_run_start(self, run_id: str, **kwargs: Any) -> None: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 914536cf6..c3ddfc4d7 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -20,11 +20,9 @@ from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.errors import ( - ObserverEventsLostWarning, OrcapodDatabaseError, OrcapodDatabaseReadError, OrcapodDatabaseWriteError, - RowFailuresWarning, ) from orcapod.pipeline.base import AbstractPipelineBase from orcapod.pipeline.dag import OrcaDAG @@ -52,10 +50,9 @@ from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig from orcapod.utils.database_errors import database_write_path, flush_best_effort -from orcapod.utils.warning_utils import WarningLocation if TYPE_CHECKING: - from collections.abc import Coroutine, Mapping + from collections.abc import Mapping from pathlib import Path from types import FrameType @@ -130,33 +127,26 @@ def _with_counter( return counter from orcapod.pipeline.composite_observer import CompositeObserver - return CompositeObserver(observer, counter)._with_run_losses(losses) # pyright: ignore[reportPrivateUsage, reportReturnType] # forwards every hook; its **kwargs signatures do not match the protocol structurally + return CompositeObserver._for_run(observer, counter, losses) # pyright: ignore[reportPrivateUsage, reportReturnType] # forwards every hook; its **kwargs signatures do not match the protocol structurally -def _warn_run_completion( - summary: RunSummary, - caller: FrameType, - *, - observer_location: WarningLocation | None = None, -) -> None: - """Issue both completion warnings while preserving the row warning's precedence.""" - row_warning: RowFailuresWarning | None = None +def _warn_run_completion(summary: RunSummary, caller: FrameType) -> None: + """Issue both completion warnings, giving any row-reporting error precedence.""" + row_error: Exception | None = None if not summary.ok: try: warn_row_failures(summary, caller) - except RowFailuresWarning as error: - row_warning = error + except Exception as error: + row_error = error if summary.lost_observer_events: try: - warn_lost_observer_events( - summary, observer_location or WarningLocation.from_frame(caller) - ) - except ObserverEventsLostWarning as error: - if row_warning is None: + warn_lost_observer_events(summary, caller) + except Exception as error: + if row_error is None: raise - raise row_warning from error - if row_warning is not None: - raise row_warning + raise row_error from error + if row_error is not None: + raise row_error class PipelineJob(AbstractPipelineBase[JobNode]): @@ -1162,7 +1152,7 @@ def run( _warn_run_completion(summary, caller) return summary - def run_async( + async def run_async( self, orchestrator: "AsyncPipelineOrchestrator | None" = None, observer: "ExecutionObserverProtocol | None" = None, @@ -1170,7 +1160,7 @@ def run_async( commit_every_rows: int = 100, *, load_only: bool = False, - ) -> Coroutine[Any, Any, RunSummary]: + ) -> RunSummary: """Execute the job with the async orchestrator, from async code. The awaitable form of ``run``: ``await job.run_async()`` runs on the caller's @@ -1188,7 +1178,7 @@ def run_async( load_only: As for ``run``. Returns: - A coroutine that returns the run's ``RunSummary``. + The run's ``RunSummary``, as ``run`` returns. Raises: TypeError: If ``orchestrator`` is not an ``AsyncPipelineOrchestrator``; @@ -1198,28 +1188,6 @@ def run_async( OrcapodDatabaseWriteError: As for ``run``. OrcapodDatabaseReadError: As for ``run``. """ - # A scheduler may resume the coroutine after its caller has moved on. - caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] - return self._run_async( - orchestrator, - observer, - materialize_results, - commit_every_rows, - load_only=load_only, - observer_location=WarningLocation.from_frame(caller), - ) - - async def _run_async( - self, - orchestrator: AsyncPipelineOrchestrator | None, - observer: ExecutionObserverProtocol | None, - materialize_results: bool, - commit_every_rows: int, - *, - load_only: bool, - observer_location: WarningLocation, - ) -> RunSummary: - """Execute the job and warn on completion using the captured call site.""" from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator if orchestrator is None: @@ -1255,8 +1223,8 @@ async def _run_async( asynchronous=True, lost_observer_events=losses.by_kind(), ) - caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] # keep the existing row warning location - _warn_run_completion(summary, caller, observer_location=observer_location) + caller = sys._getframe(1) # pyright: ignore[reportPrivateUsage] # the coroutine's awaiting or resuming frame + _warn_run_completion(summary, caller) return summary def _prepare_run( diff --git a/src/orcapod/pipeline/logging_observer.py b/src/orcapod/pipeline/logging_observer.py index 08260c8a4..b68a5a885 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -56,7 +56,6 @@ from orcapod.pipeline.observer_losses import ( LOGGING_EVENTS, RunLosses, - RunLossObserver, report_lost_event, ) from orcapod.protocols.core_protocols import DataProtocol, TagProtocol @@ -150,7 +149,7 @@ def record(self, **kwargs: Any) -> None: ) -class LoggingObserver(RunLossObserver): +class LoggingObserver: """Writes data-level logs to a pre-scoped log database. Instantiate once, outside the pipeline, and pass to the orchestrator:: @@ -196,7 +195,7 @@ def contextualize(self, *identity_path: str) -> "_ContextualizedLoggingObserver" "LoggingObserver.contextualize() requires a non-empty identity_path." ) return _ContextualizedLoggingObserver( - self._db.at(*identity_path), self._current_run_id, self._run_losses + self._db.at(*identity_path), self._current_run_id ) # -- lifecycle hooks -- @@ -248,7 +247,6 @@ def create_data_logger( log_path=DEFAULT_LOG_PATH, run_id=self._current_run_id, tag_data=dict(tag), - losses=self._run_losses, ) # -- convenience -- @@ -323,7 +321,7 @@ def from_config( return cls(db) -class _ContextualizedLoggingObserver(RunLossObserver): +class _ContextualizedLoggingObserver: """ExecutionObserverProtocol implementation bound to a specific node identity path. One instance per node per run, created via LoggingObserver.contextualize(). @@ -350,7 +348,7 @@ def contextualize(self, *identity_path: str) -> "_ContextualizedLoggingObserver" ) def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: - self._run_id = run_id + pass def on_run_end(self, run_id: str) -> None: pass diff --git a/src/orcapod/pipeline/observer_losses.py b/src/orcapod/pipeline/observer_losses.py index 557567cb6..54b55e1de 100644 --- a/src/orcapod/pipeline/observer_losses.py +++ b/src/orcapod/pipeline/observer_losses.py @@ -1,20 +1,18 @@ """Observer events a run could not record (ITL-1556). -Each job execution gives its built-in observers a shared counter. Their contextualized -copies and data loggers carry the counter with them, including onto worker threads. +Each job execution gives its node-scoped built-in observers a shared counter. +Those observers and their data loggers carry it onto worker threads. An observer used directly by an orchestrator or node only logs failed writes. """ from __future__ import annotations import threading -from copy import copy from dataclasses import dataclass from typing import TYPE_CHECKING if TYPE_CHECKING: import logging - from typing import Self STATUS_EVENTS = "status" """The kind of the events a ``StatusObserver`` records.""" @@ -81,18 +79,6 @@ def by_kind(self) -> dict[str, LostObserverEvents]: } -class RunLossObserver: - """A built-in observer whose copy can collect losses for one job execution.""" - - _run_losses: RunLosses | None = None - - def with_run_losses(self, losses: RunLosses) -> Self: - """Copy the observer with a counter for this job's execution.""" - observer = copy(self) - observer._run_losses = losses - return observer - - def report_lost_event( losses: RunLosses | None, kind: str, diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index b82b4360d..c90deff47 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -26,7 +26,6 @@ from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.pipeline.restrictions import RestrictedSource from orcapod.types import Condition, SchemaLike - from orcapod.utils.warning_utils import WarningLocation _NOOP_LOGGER = NoOpLogger() _ASYNC_ATTRIBUTION_NOTE = ( @@ -456,28 +455,29 @@ def warn_row_failures(summary: RunSummary, caller: FrameType) -> None: warn_at_frame(summary.failures_message(), RowFailuresWarning, caller) -def warn_lost_observer_events(summary: RunSummary, location: WarningLocation) -> None: +def warn_lost_observer_events(summary: RunSummary, caller: FrameType) -> None: """Issue the run's ``ObserverEventsLostWarning``, at the end of the run (ITL-1556). At the end and not at the first loss: the count and each kind's first error are complete then, the run's rows and summary are already kept (the warning turned into - an error loses nothing), and it is shown at the line that started the run, where - the first loss happens inside a node, possibly on a worker thread. Each failed - write is still logged by its observer when it happens. + an error loses nothing). The first loss happens inside a node, possibly on a + worker thread. Each failed write is still logged by its observer when it happens. Args: summary: The run's summary, with lost observer events. - location: The line that called ``run`` or ``run_async``. + caller: The frame that called ``run`` or awaited or resumed ``run_async``. """ from orcapod.errors import ObserverEventsLostWarning + from orcapod.utils.warning_utils import warn_at_frame - location.warn( + warn_at_frame( "Observer events were not recorded in this run: " + f"{summary.lost_observer_events_message()}. The run's results are not " + "affected, but its status and log records are incomplete. Each failed " + "write was logged with its traceback; the counts are in the run " + "summary's lost_observer_events.", ObserverEventsLostWarning, + caller, ) diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index e0ecd6172..2c5bea7bc 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -62,7 +62,6 @@ from orcapod.pipeline.observer import NoOpLogger from orcapod.pipeline.observer_losses import ( STATUS_EVENTS, - RunLossObserver, report_lost_event, ) from orcapod.protocols.core_protocols import DataProtocol, TagProtocol @@ -71,6 +70,7 @@ if TYPE_CHECKING: import pyarrow as pa + from orcapod.pipeline.observer_losses import RunLosses from orcapod.protocols.database_protocols import ArrowDatabaseProtocol logger = logging.getLogger(__name__) @@ -81,7 +81,7 @@ _NOOP_LOGGER = NoOpLogger() -class StatusObserver(RunLossObserver): +class StatusObserver: """Writes node execution status to a pre-scoped status database. Instantiate once, outside the pipeline, and pass to the orchestrator:: @@ -128,7 +128,6 @@ def contextualize(self, *identity_path: str) -> "_ContextualizedStatusObserver": ctx = _ContextualizedStatusObserver(self._db.at(*identity_path)) ctx._current_run_id = self._current_run_id ctx._current_pipeline_uri = self._current_pipeline_uri - ctx._run_losses = self._run_losses return ctx # -- lifecycle hooks -- @@ -313,7 +312,7 @@ def _write_event( # The run goes on: its results do not depend on this row. The loss is # logged here and reported by the run (ITL-1556). report_lost_event( - self._run_losses, + None, STATUS_EVENTS, event_error, logger, @@ -323,7 +322,7 @@ def _write_event( ) -class _ContextualizedStatusObserver(RunLossObserver): +class _ContextualizedStatusObserver: """ExecutionObserverProtocol implementation bound to a specific node identity path. One instance is created per node per run via StatusObserver.contextualize(). @@ -342,13 +341,11 @@ def __init__( self._current_run_id: str = "" self._current_pipeline_uri: str = "" self._tag_schema: SchemaLike = {} + self._run_losses: RunLosses | None = None def contextualize(self, *identity_path: str) -> "_ContextualizedStatusObserver": """Re-contextualize with a new identity path (scopes the DB).""" ctx = _ContextualizedStatusObserver(self._db.at(*identity_path)) - # The copy belongs to the same execution and keeps its metadata and counter. - ctx._current_run_id = self._current_run_id - ctx._current_pipeline_uri = self._current_pipeline_uri ctx._run_losses = self._run_losses return ctx diff --git a/src/orcapod/utils/warning_utils.py b/src/orcapod/utils/warning_utils.py index 508afcf96..3d83f5d41 100644 --- a/src/orcapod/utils/warning_utils.py +++ b/src/orcapod/utils/warning_utils.py @@ -5,9 +5,7 @@ import linecache import sys import warnings -from dataclasses import dataclass from types import FrameType -from typing import Any def outside_orcapod_stacklevel() -> int: @@ -31,32 +29,6 @@ def outside_orcapod_stacklevel() -> int: return 2 -@dataclass(frozen=True) -class WarningLocation: - """Capture a warning's location without retaining the caller's frame.""" - - filename: str - lineno: int - module_globals: dict[str, Any] - - @classmethod - def from_frame(cls, frame: FrameType) -> WarningLocation: - """Capture the frame's current line and module.""" - return cls(frame.f_code.co_filename, frame.f_lineno, frame.f_globals) - - def warn(self, message: str, category: type[Warning]) -> None: - """Issue a warning at this location, respecting the active filters.""" - _ = linecache.lazycache(self.filename, self.module_globals) - warnings.warn_explicit( - message, - category, - self.filename, - self.lineno, - module=self.module_globals.get("__name__"), - registry=None, - ) - - def warn_at_frame(message: str, category: type[Warning], frame: FrameType) -> None: """Issue a warning shown at ``frame``'s line, at every call. @@ -93,4 +65,13 @@ def warn_at_frame(message: str, category: type[Warning], frame: FrameType) -> No category: The warning's class. frame: The frame whose file, line and module name the warning is shown at. """ - WarningLocation.from_frame(frame).warn(message, category) + filename = frame.f_code.co_filename + _ = linecache.lazycache(filename, frame.f_globals) + warnings.warn_explicit( + message, + category, + filename, + frame.f_lineno, + module=frame.f_globals.get("__name__"), + registry=None, + ) diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index b780d24f1..ef8b28268 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -22,6 +22,7 @@ from typing_extensions import override from orcapod import PipelineJob, function_pod +from orcapod.core.datagrams import Data, Tag from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import ObserverEventsLostWarning, RowFailuresWarning from orcapod.pipeline import ( @@ -87,6 +88,20 @@ def describe_except_unencodable_error(d1: int, d3: str) -> tuple[int, str]: return d1 + 1, d3 + d3 +class _UnprintableRowError(ValueError): + @override + def __str__(self) -> str: + raise RuntimeError("cannot format row error") + + +@function_pod(output_keys=("n", "s")) +def describe_except_unprintable_error(d1: int, d3: str) -> tuple[int, str]: + """Raise an error whose message cannot be formatted for the first row.""" + if d1 == 10: + raise _UnprintableRowError() + return d1 + 1, d3 + d3 + + class _Refusals: """Which writes a ``_RefusingDatabase`` and its scoped views refuse. @@ -405,6 +420,37 @@ def test_custom_observers_keep_their_lifecycle( assert _rows(job) == EXPECTED_ROWS +def test_custom_completion_observer_sees_the_current_logging_run( + arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] +) -> None: + """A custom hook sees the caller's built-in logger updated by the run.""" + db = InMemoryArrowDatabase() + logging_observer = LoggingObserver(db) + + class LogCompletion(NoOpObserver): + run_id: str = "" + + @override + def on_run_end(self, run_id: str) -> None: + self.run_id = run_id + logger = logging_observer.create_data_logger( + Tag({"t1": "completion", "t2": 0, "t3": True}), Data({}) + ) + logger.record(success=True) + + completion = LogCompletion() + job = _job(arrangement) + observer = CompositeObserver(CompositeObserver(logging_observer), completion) + + assert run_job(job, observer).ok + root_logs = db.get_all_records(("execution_logs",)) + assert root_logs is not None + assert root_logs["_log_run_id"].to_pylist() == [completion.run_id] + all_logs = logging_observer.get_logs() + assert all_logs is not None + assert all_logs["_log_run_id"].to_pylist() == [completion.run_id] * (N_ROWS + 1) + + def test_unencodable_log_event_preserves_rows( arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] ) -> None: @@ -443,6 +489,34 @@ def test_promoted_row_warning_still_reports_observer_losses( assert [warning.category for warning in caught] == [ObserverEventsLostWarning] +@pytest.mark.parametrize("promote_observer_warning", [False, True]) +def test_unprintable_row_error_still_reports_observer_losses( + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], + promote_observer_warning: bool, +) -> None: + """A row's broken formatter remains the primary error after completion.""" + job = _job(arrangement, pod=describe_except_unprintable_error) + observer = StatusObserver(InMemoryArrowDatabase()) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter( + "error" if promote_observer_warning else "always", ObserverEventsLostWarning + ) + with pytest.raises(RuntimeError, match="cannot format row error") as error: + _ = run_job(job, observer) + + summary = job.last_run + assert summary is not None + assert summary.nodes[LABEL].computed == N_ROWS - 1 + assert summary.nodes[LABEL].failed == 1 + assert summary.lost_observer_events["status"].count == 1 + if promote_observer_warning: + assert isinstance(error.value.__cause__, ObserverEventsLostWarning) + else: + assert [warning.category for warning in caught] == [ObserverEventsLostWarning] + + def test_unencodable_status_event_preserves_other_rows( arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] ) -> None: @@ -468,22 +542,33 @@ def test_unencodable_status_event_preserves_other_rows( assert _rows(job) == [row for row in EXPECTED_ROWS if row[3] != 11] -def test_scheduled_run_async_warning_points_to_the_call( +def test_run_async_is_a_coroutine_function() -> None: + """Both standard coroutine-function checks recognize the public method.""" + run_async = _job(ARRANGEMENTS[0]).run_async + assert inspect.iscoroutinefunction(run_async) + assert asyncio.iscoroutinefunction(run_async) # pyright: ignore[reportDeprecated] # verifies existing asyncio callers + + +def test_run_async_warning_points_to_the_await( arrangement: Arrangement, ) -> None: - """Scheduling the coroutine later still attributes the loss warning to its call.""" + """The completion warning points to the line awaiting the coroutine.""" job = _job(arrangement) observer = StatusObserver(_database()) - frame = inspect.currentframe() - assert frame is not None - with pytest.warns(ObserverEventsLostWarning) as caught: - call_line = frame.f_lineno + 1 + async def run() -> int: pending = job.run_async(observer=observer) - _ = asyncio.run(pending) + frame = inspect.currentframe() + assert frame is not None + await_line = frame.f_lineno + 1 + _ = await pending + return await_line + + with pytest.warns(ObserverEventsLostWarning) as caught: + await_line = asyncio.run(run()) assert len(caught) == 1 - assert (caught[0].filename, caught[0].lineno) == (__file__, call_line) + assert (caught[0].filename, caught[0].lineno) == (__file__, await_line) def test_a_load_only_run_reports_lost_events( @@ -607,27 +692,20 @@ def test_the_warning_can_be_turned_into_an_error_after_the_run_is_kept( assert _rows(job) == EXPECTED_ROWS -def test_a_recontextualized_status_observer_keeps_its_run() -> None: - """A copy contextualized twice writes its run's id and reports under it.""" - from orcapod.core.datagrams import Tag - from orcapod.pipeline.observer_losses import RunLosses - - stored = StatusObserver(InMemoryArrowDatabase()) - stored.on_run_start("run-1", pipeline_uri="p@1") - tag: Any = Tag({"t1": "a", "t2": 1}) - stored.contextualize("a").contextualize("b").on_data_start("n", tag, None) # pyright: ignore[reportArgumentType] # the status observer does not read the data - table = stored.get_status() +def test_precontextualized_status_observer_preserves_empty_metadata( + arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] +) -> None: + """Re-contextualized status rows retain main's empty metadata and report losses.""" + observer = StatusObserver(_database(accept_first=1)) + scoped = observer.contextualize("tenant") + with pytest.warns(ObserverEventsLostWarning): + summary = run_job(_job(arrangement), scoped) + + assert summary.lost_observer_events["status"].count == 2 * N_ROWS - 1 + table = observer.get_status() assert table is not None - assert table.column("_status_run_id").to_pylist() == ["run-1"] - assert table.column("_status_pipeline_uri").to_pylist() == ["p@1"] - - losses = RunLosses() - refusing = StatusObserver(_database()).with_run_losses(losses) - refusing.on_run_start("run-2") - refusing.contextualize("a").contextualize("b").on_data_start("n", tag, None) # pyright: ignore[reportArgumentType] # as above - assert losses.by_kind() == { - "status": LostObserverEvents("status", 1, "OSError: store refuses writes") - } + assert table["_status_run_id"].to_pylist() == [""] + assert table["_status_pipeline_uri"].to_pylist() == [""] def test_overlapping_async_jobs_can_share_observers() -> None: @@ -807,27 +885,41 @@ def emit(self, record: logging.LogRecord) -> None: assert summary.ok and _rows(job) == EXPECTED_ROWS -def test_precontextualized_logging_observer_uses_the_current_run( - orchestrator: Any, arrangement: Arrangement +def test_precontextualized_logging_observer_keeps_its_existing_run_id( + arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] ) -> None: - """A twice scoped observer replaces stale metadata and counts failed writes.""" + """A twice scoped observer keeps its stored run ID and counts failed writes.""" observer = LoggingObserver(_database(accept_first=1)) observer.on_run_start("earlier-run") scoped = observer.contextualize("tenant").contextualize("project") - started = _RunStart() job = _job(arrangement) - summary, messages = _run_losing( - job, orchestrator=orchestrator, observer=CompositeObserver(scoped, started) - ) + with pytest.warns(ObserverEventsLostWarning) as caught: + summary = run_job(job, scoped) assert summary.lost_observer_events["logging"].count == N_ROWS - 1 - assert len(messages) == 1 + assert len(caught) == 1 logs = observer.get_logs() assert logs is not None - assert logs["_log_run_id"].to_pylist() == [started.run_id] + assert logs["_log_run_id"].to_pylist() == ["earlier-run"] assert _rows(job) == EXPECTED_ROWS +def test_direct_precontextualized_logging_observer_keeps_its_existing_run_id( + orchestrator: Any, +) -> None: + """A direct orchestrator leaves the contextualized logger's run ID alone.""" + observer = LoggingObserver(InMemoryArrowDatabase()) + observer.on_run_start("earlier-run") + scoped = observer.contextualize("tenant") + _ = orchestrator.run( + _job(ARRANGEMENTS[0]).dag, observer=scoped, run_id="direct-run" + ) + + logs = observer.get_logs() + assert logs is not None + assert logs["_log_run_id"].to_pylist() == ["earlier-run"] * N_ROWS + + def test_async_orchestrator_on_its_own_thread_keeps_the_jobs_losses() -> None: """A blocking async run in a running event loop reports from its new thread.""" From af58840c8146ffc96bce4d9ae11f29e4826f14d9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:10:57 -0800 Subject: [PATCH 06/16] fix(observers): preserve first loss and tolerate error formatting (ITL-1556) --- docs/dev/design_issues/ITL-1556-OBS1.md | 5 +- src/orcapod/pipeline/observer_losses.py | 34 +++++++--- .../test_observer_event_losses.py | 65 +++++++++++++++++-- 3 files changed, 88 insertions(+), 16 deletions(-) diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md index e52874ded..0c25a9603 100644 --- a/docs/dev/design_issues/ITL-1556-OBS1.md +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -19,8 +19,9 @@ so overlapping executions count their own losses even when they share an observe a run ID. A failed event encoding or write is counted and logged. Lifecycle hooks run on the caller's original observers, and the built-ins derive event metadata as before. -The run puts the count and first error for each observer kind in -`RunSummary.lost_observer_events`. It issues one `ObserverEventsLostWarning` after +The run puts the count and first reported error for each observer kind in +`RunSummary.lost_observer_events`. If the error's message cannot be rendered, +the summary shows its type name. The run issues one `ObserverEventsLostWarning` after keeping the completed summary. The warning points to the `run()` call, the `run_async()` await, or the event loop's resumption site for a separately scheduled coroutine. A completed run reports observer losses even when preparing or issuing the diff --git a/src/orcapod/pipeline/observer_losses.py b/src/orcapod/pipeline/observer_losses.py index 54b55e1de..8800ccfef 100644 --- a/src/orcapod/pipeline/observer_losses.py +++ b/src/orcapod/pipeline/observer_losses.py @@ -29,7 +29,8 @@ class LostObserverEvents: kind: The observer kind: ``"status"`` (a ``StatusObserver``'s state transitions) or ``"logging"`` (a ``LoggingObserver``'s log rows). count: How many events of that kind were not recorded. - first_error: The first failed write's error, as ``Type: message``. + first_error: The first reported error as ``Type: message``, or its type + name if its message could not be rendered. """ kind: str @@ -57,24 +58,39 @@ def record(self, kind: str, error: BaseException) -> None: kind: The observer kind. error: What the failed write raised. """ + with self._lock: + count = self._counts.get(kind, 0) + 1 + self._counts[kind] = count + if count != 1: + return + + # The first report has claimed this kind. Formatting can invoke user code, + # so let other reports proceed while it runs. + try: + name = str.__str__(type(error).__name__) + except BaseException: + name = "Exception" try: - message = str(error) - except Exception: - message = "" - text = f"{type(error).__name__}: {message}" + # An exception's __str__ can return a subclass with a custom __format__. + message = str.__str__(str(error)) + text = f"{name}: {message}" + except BaseException: + text = name with self._lock: - self._counts[kind] = self._counts.get(kind, 0) + 1 - _ = self._first_errors.setdefault(kind, text) + self._first_errors[kind] = text def by_kind(self) -> dict[str, LostObserverEvents]: """The lost events so far, by observer kind, in kind order. Returns: - One entry per kind that lost an event; empty when none was lost. + One entry per kind that lost an event; empty when none was lost. A + report still formatting its first error shows ``Exception`` until ready. """ with self._lock: return { - kind: LostObserverEvents(kind, count, self._first_errors[kind]) + kind: LostObserverEvents( + kind, count, self._first_errors.get(kind, "Exception") + ) for kind, count in sorted(self._counts.items()) } diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index ef8b28268..3aeff9b1d 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -35,6 +35,7 @@ SyncPipelineOrchestrator, ) from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.observer_losses import RunLosses from tests.test_core.operators.several_items import ( DATA_FIRST_REVERSED, MAIN, @@ -835,12 +836,39 @@ def __str__(self) -> str: raise RuntimeError("could not format the failed write") +class _UnformattableMessage(str): + @override + def __format__(self, format_spec: str, /) -> str: + raise RuntimeError("could not format the write error's message") + + +class _WriteErrorWithStringSubclass(OSError): + @override + def __str__(self) -> str: + return _UnformattableMessage("failed to write") + + @pytest.mark.parametrize("kind", ["status", "logging"]) +@pytest.mark.parametrize( + ("error", "first_error"), + [ + (_UnprintableWriteError, "_UnprintableWriteError"), + ( + _WriteErrorWithStringSubclass, + "_WriteErrorWithStringSubclass: failed to write", + ), + ], + ids=["broken-str", "string-subclass"], +) def test_unprintable_write_error_preserves_rows( - kind: str, orchestrator: Any, arrangement: Arrangement + kind: str, + orchestrator: Any, + arrangement: Arrangement, + error: type[OSError], + first_error: str, ) -> None: """Summarizing either observer's error cannot damage the run.""" - database = _database(error=_UnprintableWriteError) + database = _database(error=error) observer = ( StatusObserver(database) if kind == "status" else LoggingObserver(database) ) @@ -849,14 +877,41 @@ def test_unprintable_write_error_preserves_rows( summary, messages = _run_losing(job, orchestrator=orchestrator, observer=observer) assert summary.lost_observer_events == { - kind: LostObserverEvents( - kind, count, "_UnprintableWriteError: " - ) + kind: LostObserverEvents(kind, count, first_error) } assert len(messages) == 1 assert summary.ok and _rows(job) == EXPECTED_ROWS +def test_concurrent_losses_keep_the_first_reported_error() -> None: + """A later report cannot claim first place while the first formats its error.""" + formatting = threading.Event() + release = threading.Event() + losses = RunLosses() + + class FirstWriteError(OSError): + @override + def __str__(self) -> str: + formatting.set() + if not release.wait(timeout=10): + raise RuntimeError("timed out waiting for the second report") + return "failed first" + + with ThreadPoolExecutor(2) as pool: + first = pool.submit(losses.record, "status", FirstWriteError()) + try: + assert formatting.wait(timeout=10) + second = pool.submit(losses.record, "status", OSError("failed second")) + second.result(timeout=10) + finally: + release.set() + first.result(timeout=10) + + assert losses.by_kind() == { + "status": LostObserverEvents("status", 2, "FirstWriteError: failed first") + } + + def test_a_failing_log_handler_cannot_interrupt_loss_reporting( monkeypatch: pytest.MonkeyPatch, ) -> None: From 1399afab0200caeb801a48eafbbcdced469ec992 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:59:03 -0800 Subject: [PATCH 07/16] fix(observers): scope built-in observers by class identity (ITL-1556) --- docs/dev/design_issues/ITL-1556-OBS1.md | 5 +- src/orcapod/pipeline/composite_observer.py | 5 +- .../test_observer_event_losses.py | 77 ++++++++++++++++++- 3 files changed, 80 insertions(+), 7 deletions(-) diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md index 0c25a9603..769b91539 100644 --- a/docs/dev/design_issues/ITL-1556-OBS1.md +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -16,8 +16,9 @@ one case only (a SQLite-backed store is accepted at setup and refuses every even reported. A job creates a counter for its execution (`pipeline/observer_losses.py`, `RunLosses`). Node-scoped built-in observers and their data loggers carry that counter, so overlapping executions count their own losses even when they share an observer or -a run ID. A failed event encoding or write is counted and logged. Lifecycle hooks run -on the caller's original observers, and the built-ins derive event metadata as before. +a run ID. The job selects concrete built-in observers by class identity. A failed event +encoding or write is counted and logged. Lifecycle hooks run on the caller's original +observers, and the built-ins derive event metadata as before. The run puts the count and first reported error for each observer kind in `RunSummary.lost_observer_events`. If the error's message cannot be rendered, diff --git a/src/orcapod/pipeline/composite_observer.py b/src/orcapod/pipeline/composite_observer.py index 4c70ae61e..940b75099 100644 --- a/src/orcapod/pipeline/composite_observer.py +++ b/src/orcapod/pipeline/composite_observer.py @@ -96,11 +96,12 @@ def _contextualize( for child in self._observers: # Only factory results from concrete built-ins belong to this run. # A custom contextualize() can return a shared or delegated observer. - if type(child) is CompositeObserver: + child_type = type(child) + if child_type is CompositeObserver: scoped = child._contextualize(identity_path, losses) else: scoped = child.contextualize(*identity_path) - if type(child) in built_ins: + if any(child_type is built_in for built_in in built_ins): scoped._run_losses = losses children.append(scoped) return CompositeObserver(*children) diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index 3aeff9b1d..30fc92fb6 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -16,7 +16,7 @@ from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from dataclasses import replace -from typing import Any +from typing import TYPE_CHECKING, Any, cast import pytest from typing_extensions import override @@ -46,6 +46,9 @@ make_source, ) +if TYPE_CHECKING: + from orcapod.protocols.database_protocols import ArrowDatabaseProtocol + ORCHESTRATORS: dict[str, Callable[[], Any]] = { "sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator, @@ -421,6 +424,38 @@ def test_custom_observers_keep_their_lifecycle( assert _rows(job) == EXPECTED_ROWS +@pytest.mark.parametrize("comparison_raises", [True, False], ids=["raises", "matches"]) +def test_custom_observer_class_is_never_compared( + arrangement: Arrangement, + run_job: Callable[[PipelineJob, StatusObserver], RunSummary], + comparison_raises: bool, +) -> None: + """Only concrete built-in observers have their losses counted by the job.""" + + class ObserverMeta(type): + @override + def __eq__(cls, other: object) -> bool: + if comparison_raises: + raise TypeError("this application does not compare observer classes") + return True + + class CustomObserver(StatusObserver, metaclass=ObserverMeta): + """Scope to a built-in status writer through the inherited hook.""" + + database = _RefusingDatabase(InMemoryArrowDatabase(), _Refusals(0)) + # The test double delegates the rest of the database protocol via __getattr__. + observer = CustomObserver(cast("ArrowDatabaseProtocol", cast("object", database))) + job = _job(arrangement) + with warnings.catch_warnings(): + warnings.simplefilter("error", ObserverEventsLostWarning) + summary = run_job(job, observer) + + assert summary.ok + assert database.refusals.writes == 2 * N_ROWS + assert summary.lost_observer_events == {} + assert _rows(job) == EXPECTED_ROWS + + def test_custom_completion_observer_sees_the_current_logging_run( arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] ) -> None: @@ -452,8 +487,40 @@ def on_run_end(self, run_id: str) -> None: assert all_logs["_log_run_id"].to_pylist() == [completion.run_id] * (N_ROWS + 1) +class _Utf8CaptureFormatter(logging.Formatter): + """Escape lone surrogates after pytest formats the message and traceback.""" + + def __init__(self, formatter: logging.Formatter | None) -> None: + super().__init__() + self._formatter: logging.Formatter = formatter or logging.Formatter() + + @override + def format(self, record: logging.LogRecord) -> str: + return ( + self._formatter.format(record) + .encode("utf-8", "backslashreplace") + .decode("utf-8") + ) + + +@pytest.fixture +def utf8_log_capture( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> pytest.LogCaptureFixture: + """Keep the original records and make both pytest log captures safe for xdist.""" + # Pytest captures logs for caplog and for its test report with separate handlers. + for handler in logging.getLogger().handlers: + if isinstance(handler, type(caplog.handler)): + monkeypatch.setattr( + handler, "formatter", _Utf8CaptureFormatter(handler.formatter) + ) + return caplog + + def test_unencodable_log_event_preserves_rows( - arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], + utf8_log_capture: pytest.LogCaptureFixture, ) -> None: """A filename containing a surrogate can lose a log row but not a result.""" observer = LoggingObserver(InMemoryArrowDatabase()) @@ -467,6 +534,7 @@ def test_unencodable_log_event_preserves_rows( assert summary.ok assert summary.lost_observer_events["logging"].count == N_ROWS assert _rows(job) == EXPECTED_ROWS + assert rb"filename: bad\udcff" in utf8_log_capture.text.encode("utf-8") def test_promoted_row_warning_still_reports_observer_losses( @@ -519,7 +587,9 @@ def test_unprintable_row_error_still_reports_observer_losses( def test_unencodable_status_event_preserves_other_rows( - arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary] + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], + utf8_log_capture: pytest.LogCaptureFixture, ) -> None: """A status row with an unencodable error is lost and the job still finishes.""" job = _job(arrangement, pod=describe_except_unencodable_error) @@ -541,6 +611,7 @@ def test_unencodable_status_event_preserves_other_rows( ObserverEventsLostWarning, ] assert _rows(job) == [row for row in EXPECTED_ROWS if row[3] != 11] + assert rb"filename: bad\udcff" in utf8_log_capture.text.encode("utf-8") def test_run_async_is_a_coroutine_function() -> None: From b587b5119b358b551b56be17b168448045a242e7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:26:32 -0800 Subject: [PATCH 08/16] fix(observers): preserve custom scoping and safely render loss warnings --- docs/dev/design_issues/ITL-1556-OBS1.md | 6 +- src/orcapod/pipeline/composite_observer.py | 63 ++++++++----- src/orcapod/pipeline/run_summary.py | 9 +- src/orcapod/pipeline/status_observer.py | 2 +- .../test_observer_event_losses.py | 91 +++++++++++++++++++ 5 files changed, 142 insertions(+), 29 deletions(-) diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md index 769b91539..71a40f085 100644 --- a/docs/dev/design_issues/ITL-1556-OBS1.md +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -16,13 +16,15 @@ one case only (a SQLite-backed store is accepted at setup and refuses every even reported. A job creates a counter for its execution (`pipeline/observer_losses.py`, `RunLosses`). Node-scoped built-in observers and their data loggers carry that counter, so overlapping executions count their own losses even when they share an observer or -a run ID. The job selects concrete built-in observers by class identity. A failed event +a run ID. The job selects concrete built-in observers that use the original scope +factory. Custom scope hooks keep control of the observers they return. A failed event encoding or write is counted and logged. Lifecycle hooks run on the caller's original observers, and the built-ins derive event metadata as before. The run puts the count and first reported error for each observer kind in `RunSummary.lost_observer_events`. If the error's message cannot be rendered, -the summary shows its type name. The run issues one `ObserverEventsLostWarning` after +the summary shows its type name. The warning escapes text for strict output encodings. +The run issues one `ObserverEventsLostWarning` after keeping the completed summary. The warning points to the `run()` call, the `run_async()` await, or the event loop's resumption site for a separately scheduled coroutine. A completed run reports observer losses even when preparing or issuing the diff --git a/src/orcapod/pipeline/composite_observer.py b/src/orcapod/pipeline/composite_observer.py index 940b75099..512ae8823 100644 --- a/src/orcapod/pipeline/composite_observer.py +++ b/src/orcapod/pipeline/composite_observer.py @@ -22,9 +22,18 @@ from __future__ import annotations +from types import MethodType from typing import TYPE_CHECKING, Any, cast +from orcapod.pipeline.logging_observer import ( + LoggingObserver, + _ContextualizedLoggingObserver, # pyright: ignore[reportPrivateUsage] +) from orcapod.pipeline.observer import NoOpLogger +from orcapod.pipeline.status_observer import ( + StatusObserver, + _ContextualizedStatusObserver, # pyright: ignore[reportPrivateUsage] +) from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import SchemaLike @@ -43,14 +52,14 @@ class CompositeObserver: ``ExecutionObserverProtocol``. """ - _run_losses: RunLosses | None = None + __run_losses: RunLosses | None = None def __init__(self, *observers: Any) -> None: self._observers = list(observers) def contextualize(self, *identity_path: str) -> "CompositeObserver": """Return a new CompositeObserver wrapping each child's contextualized version.""" - return self._contextualize(identity_path, self._run_losses) + return self.__contextualize(identity_path, self.__run_losses) @classmethod def _for_run( @@ -61,10 +70,10 @@ def _for_run( ) -> CompositeObserver: """Keep the original observers for lifecycle calls and count node event losses.""" composite = cls(observer, counter) - composite._run_losses = losses + composite.__run_losses = losses return composite - def _contextualize( + def __contextualize( self, identity_path: tuple[str, ...], losses: RunLosses | None ) -> CompositeObserver: """Scope the children and attach the job's counter to the built-in results.""" @@ -77,31 +86,25 @@ def _contextualize( *[o.contextualize(*identity_path) for o in self._observers] ) - from orcapod.pipeline.logging_observer import ( - LoggingObserver, - _ContextualizedLoggingObserver, # pyright: ignore[reportPrivateUsage] - ) - from orcapod.pipeline.status_observer import ( - StatusObserver, - _ContextualizedStatusObserver, # pyright: ignore[reportPrivateUsage] - ) - - built_ins = ( - LoggingObserver, - StatusObserver, - _ContextualizedLoggingObserver, - _ContextualizedStatusObserver, - ) children: list[Any] = [] for child in self._observers: - # Only factory results from concrete built-ins belong to this run. - # A custom contextualize() can return a shared or delegated observer. + contextualize = child.contextualize child_type = type(child) - if child_type is CompositeObserver: - scoped = child._contextualize(identity_path, losses) + # Custom hooks can return a shared or delegated observer. Only + # the default factories on concrete built-ins give us owned scopes. + uses_default_scope = ( + type(contextualize) is MethodType + and contextualize.__self__ is child + and any( + child_type is kind and contextualize.__func__ is factory + for kind, factory in _BUILT_IN_SCOPES + ) + ) + if uses_default_scope and child_type is CompositeObserver: + scoped = child.__contextualize(identity_path, losses) else: - scoped = child.contextualize(*identity_path) - if any(child_type is built_in for built_in in built_ins): + scoped = contextualize(*identity_path) + if uses_default_scope: scoped._run_losses = losses children.append(scoped) return CompositeObserver(*children) @@ -204,3 +207,13 @@ def from_config( cast("dict[str, object] | None", db_registry), ) return cls(*(build() for build in children)) + + +# Keep the original functions so hooks replaced on a class are custom too. +_BUILT_IN_SCOPES = ( + (CompositeObserver, CompositeObserver.contextualize), + (LoggingObserver, LoggingObserver.contextualize), + (StatusObserver, StatusObserver.contextualize), + (_ContextualizedLoggingObserver, _ContextualizedLoggingObserver.contextualize), + (_ContextualizedStatusObserver, _ContextualizedStatusObserver.contextualize), +) diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index c90deff47..1721ed89c 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -470,9 +470,16 @@ def warn_lost_observer_events(summary: RunSummary, caller: FrameType) -> None: from orcapod.errors import ObserverEventsLostWarning from orcapod.utils.warning_utils import warn_at_frame + # Warning sinks can use a strict encoding, including across worker processes. + # Keep the original error text on the summary. + details = ( + summary.lost_observer_events_message() + .encode("ascii", "backslashreplace") + .decode("ascii") + ) warn_at_frame( "Observer events were not recorded in this run: " - + f"{summary.lost_observer_events_message()}. The run's results are not " + + f"{details}. The run's results are not " + "affected, but its status and log records are incomplete. Each failed " + "write was logged with its traceback; the counts are in the run " + "summary's lost_observer_events.", diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index 2c5bea7bc..1b2cbbb41 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -139,7 +139,7 @@ def on_run_start( ) -> None: self._current_run_id = run_id self._current_pipeline_uri = pipeline_uri - self._tag_schema_per_node = {} + self._tag_schema_per_node.clear() def on_run_end(self, run_id: str) -> None: self._tag_schema_per_node.clear() diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index 30fc92fb6..3a7d1f0e5 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -10,6 +10,7 @@ import asyncio import inspect +import io import logging import threading import warnings @@ -370,6 +371,10 @@ def __copy__(self) -> Any: class _CustomComposite(_CompletionCounter, CompositeObserver): """A composite with a stateful lifecycle hook.""" + def _contextualize(self) -> str: + """Return an application-specific context label.""" + return "custom" + @override def on_run_end(self, run_id: str) -> None: self.finished += 1 @@ -517,6 +522,92 @@ def utf8_log_capture( return caplog +class _WriteErrorWithSurrogate(OSError): + @override + def __str__(self) -> str: + return "unreadable filename: café\udcff" + + +@pytest.mark.usefixtures("utf8_log_capture") +@pytest.mark.parametrize("encoding", ["utf-8", "ascii"]) +def test_observer_warning_displays_on_strict_stderr( + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], + monkeypatch: pytest.MonkeyPatch, + encoding: str, +) -> None: + """The ordinary warning path can display any failed write's error text.""" + observer = StatusObserver(_database(error=_WriteErrorWithSurrogate)) + job = _job(arrangement) + with ( + io.TextIOWrapper(io.BytesIO(), encoding=encoding) as stderr, + warnings.catch_warnings(), + ): + + def show_on_stderr( + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: Any = None, + line: str | None = None, + ) -> None: + _ = stderr.write( + warnings.formatwarning(message, category, filename, lineno, line) + ) + + # Format and write the warning even inside pytest's recorder. + monkeypatch.setattr(warnings, "showwarning", show_on_stderr) + warnings.simplefilter("default", ObserverEventsLostWarning) + summary = run_job(job, observer) + _ = stderr.seek(0) + message = stderr.read() + + assert message.count("ObserverEventsLostWarning:") == 1 + assert "unreadable filename:" in message + assert r"\udcff" in message + assert summary.lost_observer_events["status"].first_error.endswith("café\udcff") + assert summary is job.last_run and summary.ok + assert _rows(job) == EXPECTED_ROWS + + +@pytest.mark.parametrize("nested", [False, True], ids=["direct", "nested"]) +@pytest.mark.parametrize("kind", ["composite", "logging", "status"]) +def test_concrete_observer_uses_its_custom_contextualize( + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], + monkeypatch: pytest.MonkeyPatch, + kind: str, + nested: bool, +) -> None: + """An instance's hook controls node scoping and owns its delegated observer.""" + originals = { + "composite": CompositeObserver(), + "logging": LoggingObserver(InMemoryArrowDatabase()), + "status": StatusObserver(InMemoryArrowDatabase()), + } + original = originals[kind] + database = _database() + delegate = StatusObserver(database) + paths: list[tuple[str, ...]] = [] + + def scope(*path: str) -> Any: + paths.append(path) + return delegate.contextualize(*path) + + monkeypatch.setattr(original, "contextualize", scope) + observer = CompositeObserver(original) if nested else original + job = _job(arrangement) + with warnings.catch_warnings(): + warnings.simplefilter("error", ObserverEventsLostWarning) + summary = run_job(job, observer) + + assert paths.count(job.nodes[LABEL].node_identity_path) == 1 + assert database.refusals.writes == 2 * N_ROWS + assert summary.lost_observer_events == {} + assert summary.ok and _rows(job) == EXPECTED_ROWS + + def test_unencodable_log_event_preserves_rows( arrangement: Arrangement, run_job: Callable[[PipelineJob, Any], RunSummary], From 5e6d8c482943acf1a68ed1a63b08f044f4bac5a3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:41:33 -0800 Subject: [PATCH 09/16] fix(observers): keep loss reporting safe across warning renderers (ITL-1556) --- changelog.d/ITL-1556.md | 4 +- docs/dev/design_issues/ITL-1556-OBS1.md | 4 +- src/orcapod/pipeline/observer_losses.py | 10 +- src/orcapod/pipeline/run_summary.py | 34 ++-- src/orcapod/utils/warning_utils.py | 6 +- .../test_observer_event_losses.py | 148 +++++++++++++++++- 6 files changed, 188 insertions(+), 18 deletions(-) diff --git a/changelog.d/ITL-1556.md b/changelog.d/ITL-1556.md index 790e74faf..7d837e674 100644 --- a/changelog.d/ITL-1556.md +++ b/changelog.d/ITL-1556.md @@ -8,7 +8,9 @@ show it as one line. A run with lost events issues one new warning, `ObserverEventsLostWarning` (`orcapod.errors`), at the end of the run. It points to the `run()` call or the line awaiting `run_async()`. For a separately scheduled coroutine, - it points to the event loop's resumption site. (ITL-1556) + it points to the event loop's resumption site. The summary and warning escape non-ASCII + error text. If the warning renderer raises, the totals are logged. An explicit warnings + filter can still promote the warning to an error. (ITL-1556) ### Fixed diff --git a/docs/dev/design_issues/ITL-1556-OBS1.md b/docs/dev/design_issues/ITL-1556-OBS1.md index 71a40f085..ba745cf68 100644 --- a/docs/dev/design_issues/ITL-1556-OBS1.md +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -23,7 +23,9 @@ observers, and the built-ins derive event metadata as before. The run puts the count and first reported error for each observer kind in `RunSummary.lost_observer_events`. If the error's message cannot be rendered, -the summary shows its type name. The warning escapes text for strict output encodings. +the summary shows its type name. The summary and warning escape non-ASCII text for +strict output encodings. If warning delivery raises, the totals are logged. A filter +that promotes `ObserverEventsLostWarning` to an error still raises it. The run issues one `ObserverEventsLostWarning` after keeping the completed summary. The warning points to the `run()` call, the `run_async()` await, or the event loop's resumption site for a separately scheduled diff --git a/src/orcapod/pipeline/observer_losses.py b/src/orcapod/pipeline/observer_losses.py index 8800ccfef..04037f30a 100644 --- a/src/orcapod/pipeline/observer_losses.py +++ b/src/orcapod/pipeline/observer_losses.py @@ -21,6 +21,11 @@ """The kind of the events a ``LoggingObserver`` records.""" +def ascii_loss_text(text: str) -> str: + """Escape observer-loss text for strict output encodings, including surrogates.""" + return str.encode(text, "ascii", "backslashreplace").decode("ascii") + + @dataclass(frozen=True) class LostObserverEvents: """The events of one observer kind that a run could not record. @@ -30,7 +35,7 @@ class LostObserverEvents: transitions) or ``"logging"`` (a ``LoggingObserver``'s log rows). count: How many events of that kind were not recorded. first_error: The first reported error as ``Type: message``, or its type - name if its message could not be rendered. + name if its message could not be rendered. Non-ASCII text is escaped. """ kind: str @@ -76,8 +81,9 @@ def record(self, kind: str, error: BaseException) -> None: text = f"{name}: {message}" except BaseException: text = name + safe_text = ascii_loss_text(text) with self._lock: - self._first_errors[kind] = text + self._first_errors[kind] = safe_text def by_kind(self) -> dict[str, LostObserverEvents]: """The lost events so far, by observer kind, in kind order. diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 1721ed89c..11beb3ff9 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -9,6 +9,7 @@ import html import json +import logging import threading import traceback from dataclasses import dataclass @@ -16,6 +17,7 @@ from orcapod.core.result_cache import ResultCache from orcapod.pipeline.observer import NoOpLogger +from orcapod.pipeline.observer_losses import ascii_loss_text from orcapod.pipeline.restrictions import restriction_text if TYPE_CHECKING: @@ -27,6 +29,8 @@ from orcapod.pipeline.restrictions import RestrictedSource from orcapod.types import Condition, SchemaLike +logger = logging.getLogger(__name__) + _NOOP_LOGGER = NoOpLogger() _ASYNC_ATTRIBUTION_NOTE = ( "Computed and from-store counts reflect this run. Equal inputs may arrive in a " @@ -462,6 +466,7 @@ def warn_lost_observer_events(summary: RunSummary, caller: FrameType) -> None: complete then, the run's rows and summary are already kept (the warning turned into an error loses nothing). The first loss happens inside a node, possibly on a worker thread. Each failed write is still logged by its observer when it happens. + If the warning machinery fails, report the totals through the module logger. Args: summary: The run's summary, with lost observer events. @@ -470,22 +475,29 @@ def warn_lost_observer_events(summary: RunSummary, caller: FrameType) -> None: from orcapod.errors import ObserverEventsLostWarning from orcapod.utils.warning_utils import warn_at_frame - # Warning sinks can use a strict encoding, including across worker processes. - # Keep the original error text on the summary. - details = ( - summary.lost_observer_events_message() - .encode("ascii", "backslashreplace") - .decode("ascii") - ) - warn_at_frame( + details = ascii_loss_text(summary.lost_observer_events_message()) + message = ( "Observer events were not recorded in this run: " + f"{details}. The run's results are not " + "affected, but its status and log records are incomplete. Each failed " + "write was logged with its traceback; the counts are in the run " - + "summary's lost_observer_events.", - ObserverEventsLostWarning, - caller, + + "summary's lost_observer_events." ) + warning = ObserverEventsLostWarning(message) + try: + warn_at_frame(warning, ObserverEventsLostWarning, caller) + except BaseException as error: + # A filter promoting this warning raises it directly in warn_at_frame. + # Python rendering adds frames, even if a renderer raises the same instance. + if error is warning and warning.__traceback__ is not None: + issuing_frame = warning.__traceback__.tb_next + if issuing_frame is not None and issuing_frame.tb_next is None: + raise + try: + logger.warning("%s", message) + except BaseException: + # Application log handlers can also raise. The summary is already kept. + pass class RunCountingObserver: diff --git a/src/orcapod/utils/warning_utils.py b/src/orcapod/utils/warning_utils.py index 3d83f5d41..199007268 100644 --- a/src/orcapod/utils/warning_utils.py +++ b/src/orcapod/utils/warning_utils.py @@ -29,7 +29,9 @@ def outside_orcapod_stacklevel() -> int: return 2 -def warn_at_frame(message: str, category: type[Warning], frame: FrameType) -> None: +def warn_at_frame( + message: str | Warning, category: type[Warning], frame: FrameType +) -> None: """Issue a warning shown at ``frame``'s line, at every call. The one place Orcapod issues a warning at a frame it names (ITL-1344), for the @@ -61,7 +63,7 @@ def warn_at_frame(message: str, category: type[Warning], frame: FrameType) -> No a module with no file on disk (a zip import) is shown on every version. Args: - message: The warning's text. + message: The warning's text or an existing warning instance. category: The warning's class. frame: The frame whose file, line and module name the warning is shown at. """ diff --git a/tests/test_pipeline/test_observer_event_losses.py b/tests/test_pipeline/test_observer_event_losses.py index 3a7d1f0e5..83e25730d 100644 --- a/tests/test_pipeline/test_observer_event_losses.py +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -20,6 +20,7 @@ from typing import TYPE_CHECKING, Any, cast import pytest +from hypothesis import HealthCheck, example, given, settings, strategies as st from typing_extensions import override from orcapod import PipelineJob, function_pod @@ -566,7 +567,7 @@ def show_on_stderr( assert message.count("ObserverEventsLostWarning:") == 1 assert "unreadable filename:" in message assert r"\udcff" in message - assert summary.lost_observer_events["status"].first_error.endswith("café\udcff") + assert summary.lost_observer_events["status"].first_error.endswith(r"caf\xe9\udcff") assert summary is job.last_run and summary.ok assert _rows(job) == EXPECTED_ROWS @@ -1010,6 +1011,151 @@ def __str__(self) -> str: return _UnformattableMessage("failed to write") +def _run_with_non_ascii_caller( + job: PipelineJob, observer: StatusObserver, path: str +) -> RunSummary: + async def run() -> RunSummary: + return await job.run_async(observer=observer) # café + + if path == "run_async": + return asyncio.run(run()) + orchestrator = ORCHESTRATORS[path]() + return job.run(orchestrator=orchestrator, observer=observer) # café + + +@pytest.mark.parametrize("path", ["sync", "async", "run_async"]) +@pytest.mark.parametrize("mode", ["default", "error", "strict-ascii"]) +@settings( + max_examples=12, + deadline=None, + suppress_health_check=[HealthCheck.function_scoped_fixture], +) +@given(message=st.none() | st.text(alphabet=st.characters(), max_size=256)) +@example(message="caf\xe9 😀\ud800\udfff