diff --git a/changelog.d/ITL-1556.md b/changelog.d/ITL-1556.md new file mode 100644 index 000000000..9401675cd --- /dev/null +++ b/changelog.d/ITL-1556.md @@ -0,0 +1,30 @@ +### 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. 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. The summary display and warning escape + non-ASCII text and ASCII control characters. If the warning renderer raises, the totals + are logged. Interrupts still propagate, and an explicit warnings filter can still + promote the warning to an error. + (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 + 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/api/errors.md b/docs/api/errors.md index 2008bf91b..16a8fcd8a 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 25871086b..f5831dfb2 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). 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 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..2085937ad --- /dev/null +++ b/docs/dev/design_issues/ITL-1556-OBS1.md @@ -0,0 +1,45 @@ +## `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 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 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`. The observer logs the original exception before +rendering it for the summary. If the error's message cannot be rendered, +the summary shows its type name. An interrupt while formatting the error propagates. +The summary display and warning escape non-ASCII +text and ASCII control characters within the first LF- or CRLF-delimited line. +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 +coroutine. If caller frame access is denied, the run issues the observer warning +from Orcapod. A completed run reports observer losses even when preparing or +issuing the row-failure warning raises. When both warnings raise ordinary +exceptions, the row-warning error propagates. An interrupt or cancellation during +delivery of the observer warning logs the totals and propagates, with an earlier +ordinary row-warning error as its cause. + +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/docs/troubleshooting.md b/docs/troubleshooting.md index 5e2b218ae..627abad60 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -207,6 +207,20 @@ 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 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 before it is used in another event. +These changes apply to future writes. A later `job.run()` can reuse work from the +completed run and may never emit replacement events for the missing 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 a748add05..0ca1e6a0c 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -796,6 +796,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/composite_observer.py b/src/orcapod/pipeline/composite_observer.py index 655866c64..512ae8823 100644 --- a/src/orcapod/pipeline/composite_observer.py +++ b/src/orcapod/pipeline/composite_observer.py @@ -22,12 +22,25 @@ from __future__ import annotations -from typing import Any, cast +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 +if TYPE_CHECKING: + from orcapod.pipeline.observer_losses import RunLosses + from orcapod.protocols.observability_protocols import ExecutionObserverProtocol + _NOOP_LOGGER = NoOpLogger() @@ -39,18 +52,62 @@ 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] + ) + + children: list[Any] = [] + for child in self._observers: + contextualize = child.contextualize + child_type = type(child) + # 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 = contextualize(*identity_path) + if uses_default_scope: + scoped._run_losses = losses + children.append(scoped) + return CompositeObserver(*children) def on_run_start(self, run_id: str, **kwargs: Any) -> None: for o in self._observers: @@ -150,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/job.py b/src/orcapod/pipeline/job.py index 5b9dbc7ef..63c332a4e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -37,6 +37,7 @@ clear_run_rows, plan_run, ) +from orcapod.pipeline.observer_losses import RunLosses from orcapod.pipeline.restrictions import ( refuse_restricted_operator_caches, refuse_restriction_conflicts, @@ -48,6 +49,7 @@ RunCountingObserver, RunSummary, run_node_summaries, + warn_lost_observer_events, warn_row_failures, ) from orcapod.pipeline.source_consistency import ( @@ -63,13 +65,16 @@ 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 types import FrameType from orcapod.core.nodes.source_node import _DeclaredForm # pyright: ignore[reportPrivateUsage] # shared binding transaction 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.pod_invocation import PodInvocation from orcapod.pipeline.restrictions import Rebinding from orcapod.pipeline.source_consistency import SourceUse @@ -122,13 +127,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``. @@ -137,7 +145,38 @@ 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._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) -> None: + """Issue both completion warnings, preserving interrupts and reporting errors.""" + row_error: BaseException | None = None + caller: FrameType | None + try: + caller = sys._getframe(2) # pyright: ignore[reportPrivateUsage] # the frame that called, awaited or resumed the run + except Exception as error: + if not summary.ok: + if not summary.lost_observer_events: + raise + row_error = error + caller = None + + if not summary.ok and caller is not None: + try: + warn_row_failures(summary, caller) + except BaseException as error: + row_error = error + if summary.lost_observer_events: + try: + warn_lost_observer_events(summary, caller) + except BaseException as error: + if row_error is None: + raise + if not isinstance(error, Exception) and isinstance(row_error, Exception): + raise error from row_error + raise row_error from error + if row_error is not None: + raise row_error class PipelineJob(AbstractPipelineBase[JobNode]): @@ -398,7 +437,9 @@ def last_run(self) -> RunSummary | None: The same object ``run`` and ``run_async`` returned: per function node, the rows computed, read from the database and failed, and each node's first error. Use ``job.last_run.print_traceback("")`` to see a failed row's full - traceback. A run that raised leaves it unchanged. A loaded job has none. + traceback. If execution fails before completion, this property keeps the + previous summary. If a completion warning is promoted to an error, the + new summary is already available here. A loaded job has none. """ return self._last_run @@ -1201,7 +1242,10 @@ def run( Rows whose function raised (with the default ``error_policy="continue"``) are skipped, and the run goes on. At the end, if any row failed, a single ``RowFailuresWarning`` names each node with failed rows, how many failed, the - first error, and how to print its traceback. A run without failures is quiet. + first error, and how to print its traceback. If an observer could not record + events, a single ``ObserverEventsLostWarning`` reports the loss even when every + row succeeded. A warnings-as-errors filter can raise either warning after + the summary is kept in ``job.last_run``. Returns: The run's ``RunSummary``: per function node, the rows computed, read from @@ -1238,12 +1282,16 @@ def run( counter = RunCountingObserver() 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 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, @@ -1254,7 +1302,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, @@ -1268,9 +1316,10 @@ def run( load_only=load_only, unchecked_sources=prepared.unchecked_sources, asynchronous=not is_sync, + lost_observer_events=losses.by_kind(), ) - if not summary.ok: - warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown + if not summary.ok or summary.lost_observer_events: + _warn_run_completion(summary) return summary async def run_async( @@ -1324,10 +1373,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() + 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, @@ -1341,9 +1392,10 @@ async def run_async( load_only=load_only, unchecked_sources=prepared.unchecked_sources, asynchronous=True, + lost_observer_events=losses.by_kind(), ) - if not summary.ok: - warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown + if not summary.ok or summary.lost_observer_events: + _warn_run_completion(summary) return summary def _prepare_run( @@ -1652,6 +1704,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. @@ -1665,6 +1718,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``. @@ -1729,6 +1784,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..b68a5a885 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -53,6 +53,11 @@ 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, + RunLosses, + report_lost_event, +) from orcapod.protocols.core_protocols import DataProtocol, TagProtocol if TYPE_CHECKING: @@ -85,11 +90,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. @@ -101,36 +109,42 @@ 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: - logger.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). + report_lost_event( + self._run_losses, + LOGGING_EVENTS, + error, + logger, "LoggingObserver: failed to write log row", ) @@ -321,13 +335,17 @@ 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 @@ -378,4 +396,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 new file mode 100644 index 000000000..5ec155055 --- /dev/null +++ b/src/orcapod/pipeline/observer_losses.py @@ -0,0 +1,129 @@ +"""Observer events a run could not record (ITL-1556). + +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 dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import logging + +STATUS_EVENTS = "status" +"""The kind of the events a ``StatusObserver`` records.""" + +LOGGING_EVENTS = "logging" +"""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. + + 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 reported error as ``Type: message``, or its type + name if its message could not be rendered. Non-ASCII text is escaped. + """ + + 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 count(self, kind: str) -> bool: + """Count one lost event of ``kind`` and claim the first error if needed. + + Args: + kind: The observer kind. + + Returns: + Whether this event is the first loss of its kind. + """ + with self._lock: + count = self._counts.get(kind, 0) + 1 + self._counts[kind] = count + return count == 1 + + def keep_first_error(self, kind: str, error: Exception) -> None: + """Format and keep the error from the event that first claimed ``kind``. + + Formatting can invoke user code, so do it outside the counter's lock. + + Args: + kind: The observer kind. + error: What the first failed write raised. + """ + try: + name = str.__str__(type(error).__name__) + except Exception: + name = "Exception" + try: + # An exception's __str__ can return a subclass with a custom __format__. + message = str.__str__(str(error)) + text = f"{name}: {message}" + except Exception: + text = name + safe_text = ascii_loss_text(text) + with self._lock: + self._first_errors[kind] = safe_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. A + report still formatting its first error shows ``Exception`` until ready. + """ + with self._lock: + return { + kind: LostObserverEvents( + kind, count, self._first_errors.get(kind, "Exception") + ) + for kind, count in sorted(self._counts.items()) + } + + +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.""" + first_loss = losses is not None and losses.count(kind) + try: + logger.exception(message, *args, stacklevel=2) + except Exception: + # An application log handler can raise. The observer write remains nonfatal. + pass + # Give the existing traceback the first opportunity to render the exception. + if first_loss and losses is not None: + losses.keep_first_error(kind, error) diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 3d2a52fbc..619ef0457 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -9,24 +9,31 @@ import html import json +import logging import threading import traceback +import warnings from dataclasses import dataclass from typing import TYPE_CHECKING, Any 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: 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 +logger = logging.getLogger(__name__) + _NOOP_LOGGER = NoOpLogger() +_ASCII_CONTROL_ESCAPES = {code: f"\\x{code:02x}" for code in (*range(0x20), 0x7F)} _ASYNC_ATTRIBUTION_NOTE = ( "Computed and from-store counts reflect this run. Scheduling can affect which " "node computes a shared result." @@ -104,6 +111,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 +131,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 +147,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 +156,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 +270,33 @@ 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. + """ + details = "; ".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() + ) + return ascii_loss_text(details).translate(_ASCII_CONTROL_ESCAPES) + + 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 +313,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,6 +419,14 @@ def _rows(n: int) -> str: return f"{n} row" if n == 1 else f"{n} rows" +def _first_line(text: str) -> str: + """The first LF- or CRLF-delimited line, marked if more text follows.""" + first, newline, rest = text.partition("\n") + if newline: + first = first.removesuffix("\r") + return f"{first} ..." if rest else first + + def _error_line(error: BaseException | None) -> str: """``Type: first line of the message``.""" if error is None: @@ -414,6 +467,52 @@ 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) -> 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). 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. + An interrupt still propagates. + + Args: + summary: The run's summary, with lost observer events. + caller: The frame that called ``run`` or awaited or resumed ``run_async``, + or ``None`` when caller attribution is unavailable. + """ + from orcapod.errors import ObserverEventsLostWarning + from orcapod.utils.warning_utils import warn_at_frame + + details = 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." + ) + warning = ObserverEventsLostWarning(message) + try: + warn_at_frame(warning, ObserverEventsLostWarning, caller) + except BaseException as error: + # Python dispatches accepted warnings through _showwarnmsg. An error filter + # raises the instance before that dispatch, even through forwarding wrappers. + if error is warning and not any( + frame.f_globals is vars(warnings) and frame.f_code.co_name == "_showwarnmsg" + for frame, _ in traceback.walk_tb(error.__traceback__) + ): + raise + try: + logger.warning("%s", message) + except Exception: + # Application log handlers can also raise. The summary is already kept. + pass + if not isinstance(error, Exception): + raise + + 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..1b2cbbb41 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -60,12 +60,17 @@ from orcapod.pipeline._observer_database import require_observer_database from orcapod.pipeline.observer import NoOpLogger +from orcapod.pipeline.observer_losses import ( + STATUS_EVENTS, + report_lost_event, +) from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import SchemaLike 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__) @@ -271,38 +276,46 @@ 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: - logger.exception( + 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( + None, + STATUS_EVENTS, + event_error, + logger, "StatusObserver: failed to write status event for node=%s state=%s", node_label, state, @@ -328,10 +341,13 @@ 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).""" - return _ContextualizedStatusObserver(self._db.at(*identity_path)) + ctx = _ContextualizedStatusObserver(self._db.at(*identity_path)) + ctx._run_losses = self._run_losses + return ctx def on_run_start( self, @@ -402,37 +418,43 @@ 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) - # 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: + 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: - logger.exception( + 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, + event_error, + logger, "_ContextualizedStatusObserver: failed to write status event " "for node=%s state=%s", node_label, diff --git a/src/orcapod/utils/warning_utils.py b/src/orcapod/utils/warning_utils.py index 3d83f5d41..768583846 100644 --- a/src/orcapod/utils/warning_utils.py +++ b/src/orcapod/utils/warning_utils.py @@ -29,8 +29,10 @@ def outside_orcapod_stacklevel() -> int: return 2 -def warn_at_frame(message: str, category: type[Warning], frame: FrameType) -> None: - """Issue a warning shown at ``frame``'s line, at every call. +def warn_at_frame( + message: str | Warning, category: type[Warning], frame: FrameType | None +) -> None: + """Issue a warning at every call, using ``frame``'s line when available. The one place Orcapod issues a warning at a frame it names (ITL-1344), for the warnings of a run, which are shown at the user's line that started it. Each call @@ -61,17 +63,23 @@ 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. + frame: The frame whose file, line and module name the warning is shown at, + or ``None`` to report from this module when the caller frame is unavailable. """ - filename = frame.f_code.co_filename - _ = linecache.lazycache(filename, frame.f_globals) + if frame is None: + filename, lineno, module = __file__, 1, __name__ + else: + filename = frame.f_code.co_filename + lineno = frame.f_lineno + module = frame.f_globals.get("__name__") + _ = linecache.lazycache(filename, frame.f_globals) warnings.warn_explicit( message, category, filename, - frame.f_lineno, - module=frame.f_globals.get("__name__"), + lineno, + module=module, registry=None, ) 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..d97adbfa1 --- /dev/null +++ b/tests/test_pipeline/test_observer_event_losses.py @@ -0,0 +1,1508 @@ +"""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 inspect +import io +import logging +import signal +import threading +import warnings +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from functools import wraps +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 +from orcapod.core.datagrams import Data, Tag +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ObserverEventsLostWarning, RowFailuresWarning +from orcapod.pipeline import ( + AsyncPipelineOrchestrator, + CompositeObserver, + LoggingObserver, + LostObserverEvents, + RunSummary, + StatusObserver, + SyncPipelineOrchestrator, +) +from orcapod.pipeline.observer import NoOpObserver +from orcapod.pipeline.observer_losses import RunLosses, report_lost_event +from tests.test_core.operators.several_items import ( + DATA_FIRST_REVERSED, + MAIN, + MIXED, + PLAIN, + TAGS_FIRST, + Arrangement, + make_source, +) + +if TYPE_CHECKING: + from orcapod.protocols.database_protocols import ArrowDatabaseProtocol + +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 + + +@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 _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. + + 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, 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() + + +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 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, *, error: type[OSError] = OSError) -> Any: + """A database refusing every write after the first ``accept_first``.""" + return _RefusingDatabase(InMemoryArrowDatabase(), _Refusals(accept_first, error)) + + +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: + pod.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 + + +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.""" + + 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 + 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 + + +@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: + """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) + + +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 + + +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(r"caf\xe9\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], + utf8_log_capture: pytest.LogCaptureFixture, +) -> 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 + assert rb"filename: bad\udcff" in utf8_log_capture.text.encode("utf-8") + + +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] + + +@pytest.mark.parametrize("category", [RowFailuresWarning, ObserverEventsLostWarning]) +def test_completion_warning_interrupt_propagates_after_report( + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], + category: type[Warning], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """An interrupt propagates after the completed run reports its observer losses.""" + interrupts_row_warning = category is RowFailuresWarning + pod = describe_except_first if interrupts_row_warning else describe + job = _job(arrangement, pod=pod) + observer = StatusObserver(_database()) + interrupt = KeyboardInterrupt("warning interrupted") + shown: list[type[Warning]] = [] + + def show_warning( + _message: Warning, emitted_category: type[Warning], *args: object + ) -> None: + shown.append(emitted_category) + if emitted_category is category: + raise interrupt + + with warnings.catch_warnings(): + warnings.simplefilter("always") + monkeypatch.setattr(warnings, "showwarning", show_warning) + with pytest.raises(KeyboardInterrupt) as raised: + _ = run_job(job, observer) + + assert raised.value is interrupt + summary = job.last_run + assert summary is not None + assert summary.lost_observer_events["status"].count == 2 * N_ROWS + if interrupts_row_warning: + assert shown == [RowFailuresWarning, ObserverEventsLostWarning] + else: + assert shown == [ObserverEventsLostWarning] + assert caplog.text.count("Observer events were not recorded in this run:") == 1 + + +@pytest.mark.parametrize( + "interrupt_type", [KeyboardInterrupt, SystemExit, asyncio.CancelledError] +) +def test_observer_warning_interrupt_takes_precedence_over_promoted_row_warning( + arrangement: Arrangement, + run_job: Callable[[PipelineJob, Any], RunSummary], + interrupt_type: type[BaseException], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """A completion interrupt keeps the promoted row warning as its cause.""" + job = _job(arrangement, pod=describe_except_first) + observer = StatusObserver(_database()) + interrupt = interrupt_type("observer warning interrupted") + + def interrupt_observer_warning( + _message: Warning, category: type[Warning], *args: object + ) -> None: + assert category is ObserverEventsLostWarning + raise interrupt + + with warnings.catch_warnings(): + warnings.simplefilter("always", ObserverEventsLostWarning) + warnings.simplefilter("error", RowFailuresWarning) + monkeypatch.setattr(warnings, "showwarning", interrupt_observer_warning) + with pytest.raises(interrupt_type) as raised: + _ = run_job(job, observer) + + assert raised.value is interrupt + assert isinstance(interrupt.__cause__, RowFailuresWarning) + summary = job.last_run + assert summary is not None + assert summary.nodes[LABEL].failed == 1 + assert summary.lost_observer_events["status"].count == 2 * N_ROWS + assert caplog.text.count("Observer events were not recorded in this run:") == 1 + + +@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], + 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) + 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] + assert rb"filename: bad\udcff" in utf8_log_capture.text.encode("utf-8") + + +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: + """The completion warning points to the line awaiting the coroutine.""" + job = _job(arrangement) + observer = StatusObserver(_database()) + + async def run() -> int: + pending = job.run_async(observer=observer) + 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__, await_line) + + +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_job = _job(arrangement, store) + + first, first_messages = _run_losing( + first_job, orchestrator=orchestrator, observer=observer + ) + status_database.refusals.accept_first = None + second_job = _job(arrangement, store) + with warnings.catch_warnings(): + warnings.simplefilter("error") + attempted = status_database.refusals.writes + held = first_job.run(orchestrator=orchestrator, observer=observer) + assert status_database.refusals.writes == attempted + second = 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 + + +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["_status_run_id"].to_pylist() == [""] + assert table["_status_pipeline_uri"].to_pylist() == [""] + + +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") + + +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("forward_warning", [False, True], ids=["direct", "forwarded"]) +def test_observer_warning_filter_raises_through_forwarding_call( + forward_warning: bool, + arrangement: Arrangement, + run_job: Callable[[PipelineJob, StatusObserver], RunSummary], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A forwarding warning call preserves promotion of the loss warning.""" + warn_explicit = warnings.warn_explicit + + @wraps(warn_explicit) + def forward(*args: Any, **kwargs: Any) -> None: + warn_explicit(*args, **kwargs) + + if forward_warning: + monkeypatch.setattr(warnings, "warn_explicit", forward) + job = _job(arrangement) + with warnings.catch_warnings(): + warnings.simplefilter("error", ObserverEventsLostWarning) + with pytest.raises(ObserverEventsLostWarning): + _ = run_job(job, StatusObserver(_database())) + + assert job.last_run is not None and job.last_run.ok + assert _rows(job) == EXPECTED_ROWS + + +@pytest.mark.parametrize("line_ending", ["\n", "\r\n"]) +def test_observer_loss_displays_escape_control_bytes( + arrangement: Arrangement, + run_job: Callable[[PipelineJob, StatusObserver], RunSummary], + line_ending: str, +) -> None: + """NUL, terminal escape sequences and other controls are shown as text.""" + + class WriteError(OSError): + @override + def __str__(self) -> str: + return f"bad bytes: \x00\x1b[2K\t\x7f\x1edetail{line_ending}second line" + + job = _job(arrangement) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", ObserverEventsLostWarning) + summary = run_job(job, StatusObserver(_database(error=WriteError))) + + (warning,) = [item for item in caught if item.category is ObserverEventsLostWarning] + notebook = summary._repr_html_() # pyright: ignore[reportPrivateUsage] # notebook display protocol + assert notebook is not None + for display in (repr(summary), notebook, str(warning.message)): + assert r"bad bytes: \x00\x1b[2K\x09\x7f\x1edetail ..." in display + assert all(control not in display for control in "\x00\x1b\t\x7f\x1e") + + +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