From 02e6f0a56971841bc1a2b8a8fc875c3f614bdae1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:41:22 -0800 Subject: [PATCH 01/11] wip(streams): preview(n) (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/cached_function_pod.py | 17 ++- src/orcapod/core/function_pod.py | 121 +++++++++++++++- src/orcapod/core/nodes/source_node.py | 9 ++ .../core/operators/static_output_pod.py | 54 +++++++ src/orcapod/core/sources/base.py | 19 ++- src/orcapod/core/sources/cached_source.py | 9 +- src/orcapod/core/sources/polling_source.py | 9 +- src/orcapod/core/sources/source_proxy.py | 8 + .../core/sources/spiraldb_table_source.py | 29 +++- .../core/streams/arrow_table_stream.py | 9 +- src/orcapod/core/streams/base.py | 75 ++++++++++ src/orcapod/core/streams/preview.py | 137 ++++++++++++++++++ src/orcapod/errors.py | 7 + .../protocols/core_protocols/streams.py | 13 ++ 14 files changed, 508 insertions(+), 8 deletions(-) create mode 100644 src/orcapod/core/streams/preview.py diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 5fa41bfdb..50a330356 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -6,7 +6,7 @@ import logging from datetime import datetime, timezone from collections.abc import Iterator -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram @@ -300,6 +300,21 @@ async def async_process_data( output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) return tag, output + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``: the inner pod's answer.""" + cast("_FunctionPodBase", self._function_pod).require_preview() + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """The stored result, else the inner pod's, which is not stored.""" + self.require_preview() + stored = self.lookup_cached_data(data) + if stored is not None: + return stored + output = cast("_FunctionPodBase", self._function_pod).preview_data(data) + if output is None: + return None + return output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) + def _invoke_with_hooks( self, tag: TagProtocol, diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8a24c3b49..bcc559265 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -5,7 +5,15 @@ import dataclasses import logging from abc import abstractmethod -from collections.abc import Callable, Collection, Iterable, Iterator, Sequence +from collections.abc import ( + Callable, + Collection, + Generator, + Iterable, + Iterator, + Sequence, +) +from contextlib import closing from functools import update_wrapper, wraps from typing import TYPE_CHECKING, Any, Literal, Protocol, cast @@ -29,6 +37,13 @@ schema_requires_io, typed_zero_row_input, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + refused, + slices_of, +) from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, STALE_NOTE, @@ -36,7 +51,7 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.errors import OrcapodDatabaseError, TypeIdentityError +from orcapod.errors import OrcapodDatabaseError, PreviewRefusedError, TypeIdentityError from orcapod.utils.database_errors import keep_database_error, note_callback_failure from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -370,6 +385,28 @@ def process_data( ) return tag, self.data_function.call(data, logger=logger, **extra) + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """Call the function on one row for a preview: no effect, nothing stored. + + Stored results are read; no hook fires. + + Args: + data: The row's data. + + Raises: + PreviewRefusedError: If this kind of pod has no preview, or its function + takes the invocation context (it performs an external action). + """ + raise PreviewRefusedError(f"{type(self).__name__} has no preview") + + def require_preview(self) -> None: + """Refuse a preview of this pod before any function is called. + + Raises: + PreviewRefusedError: As ``preview_data`` would. + """ + raise PreviewRefusedError(f"{type(self).__name__} has no preview") + async def async_process_data( self, tag: TagProtocol, @@ -949,6 +986,21 @@ def from_fn( **kwargs, ) + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``.""" + if self._ctx_arg_name is not None: + raise PreviewRefusedError( + "its function takes the invocation context: it performs an action" + ) + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """See ``_FunctionPodBase.preview_data``.""" + self.require_preview() + function = self.data_function + if isinstance(function, CachedDataFunction): + return function.call(data, skip_cache_insert=True) + return function.call(data) + @property def pod_config(self) -> PodConfig: """Per-pod executor configuration.""" @@ -1770,6 +1822,61 @@ def _computed_prefix( total += 1 return shown, total + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The function's rows, one per batch, each computed only when asked for. + + Results this stream already holds are used, and nothing is kept of the others. + """ + pod = self._pod_base() + try: + pod.require_preview() + except PreviewRefusedError as error: + raise refused(self, f"cannot be previewed: {error}") from error + current = not self.is_stale + if current and self._cached_output_table is not None: + yield from slices_of(self, request) + return + known = dict(self._cached_output_datas) if current else {} + function = pod.data_function + # An inactive function gives no row; any other gives one per input row. + one_per_row = type(function) is PythonDataFunction and function.is_active() + wanted = request if one_per_row else request.without_limit() + given = False + index = 0 + with closing(preview_batches(self._input_stream, wanted)) as batches: + for batch in batches: + for tag, data in batch.iter_data(): + if index in known: + tag, output = known[index] + else: + output = pod.preview_data(data) + index += 1 + if output is not None: + given = True + yield self._preview_batch([(tag, output)]) + if not given: + yield self._preview_batch([]) + + def _preview_batch( + self, pairs: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """``pairs`` as a stream, laid out as ``as_table`` lays out this stream's rows.""" + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + tag_keys, data_keys = self.keys() + return ArrowTableStream( + self._shape_table( + self._table_from_pairs(pairs), + ColumnConfig(**PREVIEW_COLUMNS), + _no_content_hashes, + ), + tag_columns=tag_keys, + data_tags=data_tag_names(tag_keys, data_keys), + data_context=self.data_context_key, + ) + def _shape_table( self, table: pa.Table, @@ -2134,6 +2241,16 @@ def with_fall_through( input_data, self._in_input_order(input_data.keys()) ) + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``.""" + self._plain_pod.require_preview() + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """The plain pod's, then the fall-through columns, as ``process_data``.""" + return self.with_fall_through( + data, self._plain_pod.preview_data(self.function_input(data)) + ) + def function_input_schema(self, input_schema: Schema) -> Schema: """The part of an input data schema the function takes (see ``function_input``).""" parameters = self.input_data_schema diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..287096875 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -41,6 +41,7 @@ typed_zero_row_table, ) from orcapod.core.streams.record_batch_input import InputChannel +from orcapod.core.streams.preview import refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -1271,6 +1272,14 @@ def run(self) -> StreamView: display_all_rows=False, ) + def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: + """Refused: a node of a pipeline or job has no preview (``StreamBase.preview``). + + Raises: + PreviewRefusedError: Always. + """ + raise refused(self, "is a node of a pipeline or job") + def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 5149cf697..5d50e2de4 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -56,6 +56,12 @@ typed_zero_row_table, row_built_columns, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + refuse_without_compute_all, +) from orcapod.core.streams.view import ( RUN_VIEW_COMPLETE_ROWS, BoundedStreamView, @@ -2108,6 +2114,54 @@ def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: self._kept_states = kept_states self._run_window = None + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The operator over its input's batches, or over its whole inputs. + + A kept current result is read as it is; nothing is computed, and nothing is + kept of what is computed here. + """ + self._pod._note_provisional_identity_use() + self._update_cache_status() + if self._cached_stream is not None and self._cached_time is not None: + yield from preview_batches(self._cached_stream, request) + return + pod = cast(StaticOutputOperatorPod, self._pod) + if ( + len(self._upstreams) == 1 + and type(pod).__dict__.get("BATCHES_GIVE_THE_WHOLE") is True + ): + keeps_every_row = pod.rows_dropped_text(0, (), self._upstreams) is None + wanted = request if keeps_every_row else request.without_limit() + with closing(preview_batches(self._upstreams[0], wanted)) as batches: + for batch in batches: + yield pod.static_process(batch) + return + refuse_without_compute_all(self, request, "needs every row of its input") + result = pod.static_process( + *( + self._whole_input(upstream, request.of_every_row()) + for upstream in self._upstreams + ) + ) + yield from preview_batches(result, request) + + @staticmethod + def _whole_input( + upstream: StreamProtocol, request: PreviewRequest + ) -> StreamProtocol: + """Every row of ``upstream``, computed for a preview, with its pipeline hash.""" + rows = joined_batches(list(preview_batches(upstream, request))) + return _RowsOfStream( + rows.as_table(columns=PREVIEW_COLUMNS), + tag_columns=rows.keys()[0], + pipeline_hash=upstream.pipeline_hash(), + data_tags=stream_data_tags(rows), + upstreams=upstream.upstreams, + data_context=StaticOutputOperatorPod._upstream_context(upstream), # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + ) + def run(self) -> StreamView: """Compute every row and return a ``StreamView`` (``StreamBase.run``). diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..2048e7b06 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,7 +1,7 @@ from __future__ import annotations import warnings -from collections.abc import Callable +from collections.abc import Callable, Generator from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from orcapod import contexts @@ -13,6 +13,11 @@ typed_zero_row_table, ) from orcapod.errors import SourceNameWarning, SourceVersionWarning +from orcapod.core.streams.preview import ( + PreviewRequest, + refuse_without_compute_all, + slices_of, +) from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Condition, ContentHash, Schema @@ -587,6 +592,18 @@ def _display_name(self) -> str: # The header names the class already; the name is the part that is the user's. return self.source_name + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the rows a source holds (``preview_batches``). + + A source of the library that holds its table (``_stream``) reads nothing. Any + other read of a whole source is refused unless ``compute_all`` was given. + """ + if not isinstance(getattr(self, "_stream", None), ArrowTableStream): + refuse_without_compute_all(self, request, "reads its rows whole") + yield from slices_of(self, request) + def head( self, n: int = 10, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..0d4ba8c0e 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -3,7 +3,7 @@ import logging from datetime import datetime -from collections.abc import Iterator +from collections.abc import Generator, Iterator from typing import Any, ClassVar, TYPE_CHECKING import pyarrow as pa @@ -26,6 +26,7 @@ schema_requires_io, typed_zero_row_table, ) +from orcapod.core.streams.preview import PreviewRequest, refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -701,6 +702,12 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: assert self._cached_stream is not None return self._cached_stream.iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Refused: reading the source writes its cache.""" + raise refused(self, "writes its cache when it is read") + def as_table( self, *, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index de4cd3e1e..12912a975 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -14,7 +14,7 @@ import functools import logging import threading -from collections.abc import Collection +from collections.abc import Generator, Collection from math import floor from typing import Any, ClassVar, Generic, TYPE_CHECKING, TypeVar, cast @@ -29,6 +29,7 @@ SourceStreamBuilder, normalize_record_id_columns, ) +from orcapod.core.streams.preview import PreviewRequest, refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -652,6 +653,12 @@ def iter_data(self): _ = self._sync_poll_and_commit() return self._get_combined_stream().iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Refused: reading the source polls.""" + raise refused(self, "polls when it is read") + def as_table( self, *, diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..8dfdcf4cf 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -11,12 +11,14 @@ from __future__ import annotations from datetime import datetime +from collections.abc import Generator from typing import TYPE_CHECKING, Any from typing_extensions import override from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id +from orcapod.core.streams.preview import PreviewRequest, preview_batches from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -264,6 +266,12 @@ def _typed_zero_row_table(self) -> pa.Table | None: def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: return self._require_delegate().iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The bound source's (``preview_batches``).""" + yield from preview_batches(self._require_delegate(), request) + def as_table( self, *, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index d67578527..a0b48c9d8 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -64,6 +64,7 @@ ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import check_head_size, reads_as_its_class +from orcapod.core.streams.preview import PreviewRequest from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -1135,9 +1136,35 @@ def _reads_in_batches(self) -> bool: def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: """One scan of the table, each batch shaped as ``as_table()`` shapes the whole (``run()``, ITL-1464).""" + yield from self._shaped_batches(self._batch_streams()) + + @override + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """One scan, limited by SpiralDB when the rows wanted are known, else closed when + enough were read. ``max_rows`` holds only when every row is asked for.""" + if not reads_as_its_class(self, SpiralDBTableSource): + yield from super()._preview_batches(request) + return + limits = [n for n in (self._limit, request.limit) if n is not None] + yield from self._shaped_batches( + self._read_batches( + self._lookup_table(), + asof=self._asof, + limit=min(limits, default=None), + max_rows=self._max_rows if request.whole else None, + ) + ) + + def _shaped_batches( + self, batches: Generator[ArrowTableStream, None, None] + ) -> Generator[StreamProtocol, None, None]: + """``batches`` of one read, each shaped as ``as_table()`` shapes the whole; at + least one.""" columns = {"source": True, "system_tags": True, "context": True} read = False - with closing(self._batch_streams()) as streams: + with closing(batches) as streams: for stream in streams: read = True yield ArrowTableStream( diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..7b44b77c3 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -2,7 +2,7 @@ import itertools import logging -from collections.abc import Collection, Iterator +from collections.abc import Collection, Generator, Iterator from typing import Any import pyarrow as pa @@ -15,6 +15,7 @@ StreamBase, check_head_size, ) +from orcapod.core.streams.preview import PreviewRequest, slices_of from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol from orcapod.protocols.hashing_protocols import PipelineElementProtocol @@ -379,6 +380,12 @@ def head( total_rows=self._table.num_rows, ) + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the rows this stream holds (``preview_batches``).""" + yield from slices_of(self, request) + def _typed_zero_row_table(self) -> "pa.Table": """This stream's table cut to no rows: its own Arrow types, no row assembled.""" return self._assemble_table(ZERO_ROW_INPUT_COLUMNS, limit=0) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 79d23ca7f..afbd8ecd1 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -26,6 +26,7 @@ from orcapod.core.base import TraceableBase from orcapod.core.data_tags import data_tag_names +from orcapod.core.streams.preview import PreviewRequest, preview_batches, refused from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -1667,6 +1668,80 @@ def _view_of_rows(self, table: "pa.Table", origin: str) -> StreamView: display_all_rows=False, ) + def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: + """Compute the first ``n`` rows, and only what they need; keep nothing (ITL-1464). + + ``head()`` never computes; ``preview()`` does. The rows are the first ``n`` of + ``as_table()``. A source reads no more than is needed (a limit, or batches until + enough rows have passed), an operator applied batch by batch takes batches, and a + function is called on one row after another until ``n`` rows have come out, so + **your functions run**, once per row they are needed for. Nothing is kept on any + stream and nothing is written: a pod with stored results reads them and stores + none, no post-run hook fires, and a second ``preview()`` computes again. Results + a stream already holds are used. + + A join, ``group_by``, ``batch``, ``polars_filter``, ``tag_by``, ``pick``, + ``index`` or an operator of your own needs its whole input. It is refused unless + ``compute_all`` is ``True``, which computes that step, and everything beneath it, + in full (and calls functions beneath it on every row), and keeps none of it. + + Refused always: a side-effect pod or a function that takes the invocation + context (it would act), a source whose read polls or writes a cache, and a node + of a pipeline or job (``run()`` it, or ``head()`` it after a run). + + Args: + n: The most rows to compute; at least 1. + compute_all: Allow steps that need their whole input. + + Returns: + A ``StreamView``: ``ROWS`` when these are all the rows of the stream, else + ``PARTIAL``. + + Raises: + TypeError: If ``n`` is not an ``int``. + ValueError: If ``n`` is less than 1. + PreviewRefusedError: If a step is refused, as said above; the message names + it. Without ``compute_all`` it is raised before any function is called. + """ + if isinstance(n, bool) or not isinstance(n, int): + raise TypeError( + f"preview() takes an int number of rows, got {type(n).__name__}" + ) + if n < 1: + raise ValueError(f"preview() takes at least 1 row, got {n}") + request = PreviewRequest(limit=n, compute_all=compute_all) + tables: list[pa.Table] = [] + rows = 0 + with closing(preview_batches(self, request)) as batches: + for batch in batches: + tables.append(batch.as_table()) + rows += tables[-1].num_rows + if rows >= n: + break + table = pa.concat_tables(tables).slice(0, n) + complete = rows < n + shown = table.num_rows + noun = "row" if shown == 1 else "rows" + return StreamView.of_rows( + self, + table, + tag_columns=self.keys()[0], + total_rows=shown if complete else None, + status=ViewStatus.ROWS if complete else ViewStatus.PARTIAL, + origin="computed", + description=( + f"preview: all {shown:,} {noun}" + if complete + else f"preview: first {shown:,} {noun} (run() computes every row)" + ), + ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """This stream's rows for a preview (``preview_batches``): not given by default.""" + raise refused(self, "has no preview") + def head( self, n: int = 10, diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py new file mode 100644 index 000000000..f4cf4f2d0 --- /dev/null +++ b/src/orcapod/core/streams/preview.py @@ -0,0 +1,137 @@ +"""``stream.preview(n)``: the first rows of a stream, computing only what they need (ITL-1464). + +A preview reads a stream's rows as ``_preview_batches`` yields them, in the order of the +sync path, and stops at ``n``. Each kind of stream says how it gives its rows in batches +(a source reads a limit, an operator applied batch by batch takes its input's batches, a +function pod takes one row at a time); a stream that needs a whole input is refused unless +``compute_all`` was given. Nothing is kept on a stream, written to a database or +delivered. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Generator +from contextlib import closing +from typing import TYPE_CHECKING, Any + +import pyarrow as pa + +from orcapod.errors import PreviewRefusedError + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol + +FIRST_BATCH_ROWS = 1_024 +"""The rows of the first batch read when a step may drop rows; each next one doubles.""" + +PREVIEW_COLUMNS = {"source": True, "system_tags": True, "context": True} +"""The column groups a batch carries from step to step: every one but the hashes.""" + + +@dataclasses.dataclass(frozen=True) +class PreviewRequest: + """What a preview asks of a stream. + + Attributes: + limit: The most rows that can be used, or ``None`` when that is not known (a + step above may drop rows). A source reads no more. + compute_all: Whether a step that needs its whole input may be computed. + whole: Whether every row is asked for, by such a step. + kept: The batches of the streams read in full by such steps, by identity: a + stream two branches share is computed once. Discarded with the preview. + """ + + limit: int | None + compute_all: bool = False + whole: bool = False + kept: dict[int, list[StreamProtocol]] = dataclasses.field(default_factory=dict) + + def without_limit(self) -> PreviewRequest: + """The request to the input of a step that may drop rows.""" + return dataclasses.replace(self, limit=None) + + def of_every_row(self) -> PreviewRequest: + """The request to the inputs of a step that needs them whole.""" + return dataclasses.replace(self, limit=None, whole=True) + + +def preview_batches( + stream: Any, request: PreviewRequest +) -> Generator[StreamProtocol, None, None]: + """The rows of ``stream``, in order, as one stream per batch; at least one batch. + + Args: + stream: The stream, or anything else a step read as its input. + request: What is asked of it. + + Raises: + PreviewRefusedError: If the stream, or one beneath it, cannot be previewed. + """ + give = getattr(stream, "_preview_batches", None) + if give is None: + raise refused(stream, "has no preview") + if not request.whole: + with closing(give(request)) as batches: + yield from batches + return + if id(stream) not in request.kept: + with closing(give(request)) as batches: + request.kept[id(stream)] = list(batches) + yield from request.kept[id(stream)] + + +def slices_of( + stream: Any, request: PreviewRequest +) -> Generator[StreamProtocol, None, None]: + """The rows of a stream that holds them (or reads them without effect), in slices. + + Args: + stream: A stream whose ``as_table`` computes nothing. + request: What is asked of it. + """ + from orcapod.core.data_tags import stream_data_tags + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + table: pa.Table = stream.as_table(columns=PREVIEW_COLUMNS) + size = table.num_rows if request.whole else request.limit or FIRST_BATCH_ROWS + end = table.num_rows if request.limit is None else request.limit + start = 0 + while True: + yield ArrowTableStream( + table.slice(start, min(size, end - start)), + tag_columns=stream.keys()[0], + data_tags=stream_data_tags(stream), + data_context=stream.data_context_key, + ) + start += size + size *= 2 + if start >= min(end, table.num_rows): + return + + +def refused(stream: Any, why: str) -> PreviewRefusedError: + """Return the error for a stream that cannot be previewed, naming it and the remedy.""" + return PreviewRefusedError( + f"preview() stopped at {type(stream).__name__}[{getattr(stream, 'label', '')}], " + f"which {why}. run() computes every row." + ) + + +def refuse_without_compute_all(stream: Any, request: PreviewRequest, why: str) -> None: + """Refuse a step that needs its whole input, unless ``compute_all`` was given. + + Args: + stream: The step's stream. + request: What is asked of it. + why: What the step needs, after the stream's name. + + Raises: + PreviewRefusedError: Unless ``request.compute_all``. + """ + if not request.compute_all: + raise PreviewRefusedError( + f"preview() stopped at {type(stream).__name__}[{stream.label}], which {why}. " + "preview(n, compute_all=True) computes that step in full, and keeps nothing; " + "run() computes every row and keeps what it computes." + ) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 492f411ad..2c6652663 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1267,6 +1267,13 @@ def __str__(self) -> str: ) +class PreviewRefusedError(ValueError): + """A ``preview()`` would need more than the rows it shows, or would have an effect. + + The message names the stream it stopped at (ITL-1464). + """ + + class BoundedViewError(ValueError): """What was asked of a view needs rows the view does not hold (ITL-1464). diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index ad079e67e..af1b67bce 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -292,6 +292,19 @@ def run(self) -> "StreamViewProtocol": """ ... + def preview( + self, n: int = 10, *, compute_all: bool = False + ) -> "StreamViewProtocol": + """Compute the first ``n`` rows and only what they need, keeping nothing. + + User functions are called; nothing is stored and nothing has an effect. A step + that needs its whole input is refused unless ``compute_all`` (ITL-1464). + + Returns: + StreamView: The first ``n`` rows of ``as_table()``. + """ + ... + def head( self, n: int = 10, From a44cf433535c3fa7da6f564fe02bd999a60c3988 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:10:37 -0800 Subject: [PATCH 02/11] feat(streams): preview(n) computes the first rows and only what they need (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 7 + docs/concepts/streams.md | 26 + docs/dev/specs/itl-1464-views.md | 19 +- src/orcapod/core/cached_function_pod.py | 7 +- src/orcapod/core/function_pod.py | 18 +- src/orcapod/core/sources/base.py | 2 + src/orcapod/core/sources/cached_source.py | 7 +- src/orcapod/core/sources/polling_source.py | 1 + src/orcapod/core/sources/source_proxy.py | 6 +- src/orcapod/core/streams/base.py | 2 +- tests/test_core/streams/test_preview.py | 554 +++++++++++++++++++++ 11 files changed, 637 insertions(+), 12 deletions(-) create mode 100644 tests/test_core/streams/test_preview.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index 996ee7dd7..c50666eda 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -1,3 +1,10 @@ +### Added + +- `stream.preview(n)`: the first `n` rows of a stream that is not computed, computing only what + they need (ITL-1464). Functions are called on as few rows as that takes; nothing is kept, + stored or delivered. A step that needs its whole input (a join, `group_by`, ...) is refused + unless `compute_all=True`. + ### Changed - `run()` of a `SpiralDBTableSource`, and of column selections, renames, `add_tags`, diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 63f89939f..9e3e3ad6f 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -237,6 +237,32 @@ a polling source polls again and a `SpiralDBTableSource` reads its whole table a an operator's stream whose `run()` gave a bounded view). A view never asks its stream for more columns, because for those streams asking again is not a read. +### The first rows of a stream not computed yet: `preview(n)` + +`head()` never computes, so it has nothing to show of a derived stream nobody ran. +`preview(n)` computes the first `n` rows of `as_table()`, and only what they need: + +```python +first = months.preview(2) +print(first.header()) +# FunctionPodStream[months] — preview: first 2 rows (run() computes every row) +print(first.as_table().column("age_months").to_pylist()) +# [108, 120] +``` + +A source reads no more than is needed, an operator takes batches until enough rows have +passed, and **your functions are called**, on one row after another until `n` rows have come +out. Nothing is kept on a stream, nothing is stored (a pod with stored results reads them and +adds none), and no hook fires; calling `preview` again computes again. Results a stream +already holds are used. A view of fewer rows than asked for says it shows all of them. + +A join, `group_by`, `batch`, `polars_filter`, `tag_by`, `pick`, `index` or an operator of your +own needs every row of its input, so `preview` refuses it (`PreviewRefusedError`, naming the +step). `preview(n, compute_all=True)` computes that step and everything beneath it in full, +functions included, and keeps none of it. A side-effect pod, a function that takes the +invocation context, a `CachedSource`, a `PollingSource` and a node of a pipeline or job are +refused always: a preview never acts. + What `run()` does on each kind of object: | Object | `run()` | diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index e7a6a7050..0e6f9bc66 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -1,7 +1,7 @@ # `run()`, its view and `preview(n)` without a full table (ITL-1464, track VIEWS) Status: V1 to V12 approved by the coordinator, November 25, 2026 (V2, V3 and V8 flagged for -the developer); the bounded view is implemented, `preview(n)` is not. Written, against `origin/main` 0d1e017c. Companion of +the developer); the bounded view and `preview(n)` are implemented. Written, against `origin/main` 0d1e017c. Companion of `itl-1464-streaming-design.md` (sections 1, 3 and 4 of it). Nothing here changes a hash, identity, stored layout, stored byte or golden value. @@ -156,3 +156,20 @@ none, so its run scans once. One outermost question (`_upstream_states`) asks each stream once, so the walk is linear in the graph: settling a stream asks for the states beneath it, and so does its own state. + +## `preview(n)` as built + +- `StreamBase.preview` pulls `_preview_batches` (`core/streams/preview.py`) and stops at `n`. A + function pod gives one row per batch, computed when asked for, so no function is called past + the last row needed, also under a filter; an operator's batch upstream of a function may be + larger, since it calls nothing. +- The limit is passed down through operators that drop no row (`rows_dropped_text`) and + through an active Python function; anything else takes batches and the scan is closed. +- `Pick` and `Index` are refused with the whole-input steps, for the reason they are not + batched by `run()`. +- `compute_all` memoizes each stream it reads in full for the one call, so a stream two + branches share is computed once. With it, functions beneath one input may have run when + another input is refused. +- No meta column is shown: a stored row and a computed one have different ones. +- A `DerivedSource` is a whole read (its origin may compute). A filter nothing passes reads the + whole table, in batches: `max_rows` does not stop it, as it does not stop `head`. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 50a330356..83684d608 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -11,6 +11,7 @@ from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram from orcapod.core.function_pod import ( + _FunctionPodBase, # pyright: ignore[reportPrivateUsage] # one pod family FunctionPodStream, WrappedFunctionPod, function_zero_row_table, @@ -302,7 +303,7 @@ async def async_process_data( def require_preview(self) -> None: """See ``_FunctionPodBase.require_preview``: the inner pod's answer.""" - cast("_FunctionPodBase", self._function_pod).require_preview() + cast(_FunctionPodBase, cast(object, self._function_pod)).require_preview() def preview_data(self, data: DataProtocol) -> DataProtocol | None: """The stored result, else the inner pod's, which is not stored.""" @@ -310,7 +311,9 @@ def preview_data(self, data: DataProtocol) -> DataProtocol | None: stored = self.lookup_cached_data(data) if stored is not None: return stored - output = cast("_FunctionPodBase", self._function_pod).preview_data(data) + output = cast(_FunctionPodBase, cast(object, self._function_pod)).preview_data( + data + ) if output is None: return None return output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index bcc559265..3f4e6c24e 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1862,16 +1862,22 @@ def _preview_batches( def _preview_batch( self, pairs: list[tuple[TagProtocol, DataProtocol]] ) -> StreamProtocol: - """``pairs`` as a stream, laid out as ``as_table`` lays out this stream's rows.""" + """``pairs`` as a stream, laid out as ``as_table`` lays out this stream's rows. + + Without the meta columns: a stored row of a cached pod has other ones than a row + computed here, and a preview shows none. + """ + from orcapod.core.operators.meta_columns import without_meta_columns from orcapod.core.streams.arrow_table_stream import ArrowTableStream tag_keys, data_keys = self.keys() + table = self._shape_table( + self._table_from_pairs(pairs), + ColumnConfig(**PREVIEW_COLUMNS), + _no_content_hashes, + ) return ArrowTableStream( - self._shape_table( - self._table_from_pairs(pairs), - ColumnConfig(**PREVIEW_COLUMNS), - _no_content_hashes, - ), + without_meta_columns(table, tag_keys), tag_columns=tag_keys, data_tags=data_tag_names(tag_keys, data_keys), data_context=self.data_context_key, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 2048e7b06..1d7450f5d 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -600,6 +600,8 @@ def _preview_batches( A source of the library that holds its table (``_stream``) reads nothing. Any other read of a whole source is refused unless ``compute_all`` was given. """ + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + if not isinstance(getattr(self, "_stream", None), ArrowTableStream): refuse_without_compute_all(self, request, "reads its rows whole") yield from slices_of(self, request) diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 0d4ba8c0e..694c8b54d 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -42,7 +42,12 @@ report_rows_of_other_data_contexts, with_data_context, ) -from orcapod.protocols.core_protocols import DataProtocol, SourceProtocol, TagProtocol +from orcapod.protocols.core_protocols import ( + DataProtocol, + SourceProtocol, + StreamProtocol, + TagProtocol, +) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 12912a975..a45a344b6 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -58,6 +58,7 @@ from polars._typing import FrameInitTypes from orcapod.core.streams.arrow_table_stream import ArrowTableStream + from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.types import Schema diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 8dfdcf4cf..374050ad5 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -37,7 +37,11 @@ import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) class SourceProxy(RootSource): diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 99ec4cc0b..b334ab607 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1672,7 +1672,7 @@ def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: """Compute the first ``n`` rows, and only what they need; keep nothing (ITL-1464). ``head()`` never computes; ``preview()`` does. The rows are the first ``n`` of - ``as_table()``. A source reads no more than is needed (a limit, or batches until + ``as_table()``, without a cached pod's meta columns. A source reads no more than is needed (a limit, or batches until enough rows have passed), an operator applied batch by batch takes batches, and a function is called on one row after another until ``n`` rows have come out, so **your functions run**, once per row they are needed for. Nothing is kept on any diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py new file mode 100644 index 000000000..1e8d422f8 --- /dev/null +++ b/tests/test_core/streams/test_preview.py @@ -0,0 +1,554 @@ +"""``stream.preview(n)``: the first rows of the sync result, and no more work (ITL-1464).""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, col, function_pod +from orcapod.core.cached_function_pod import CachedFunctionPod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.operators import MapData +from orcapod.core.sources import ArrowTableSource, CachedSource, DerivedSource +from orcapod.core.sources.polling_source import PollingSource +from orcapod.core.streams import preview as preview_module +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import PreviewRefusedError, RowIdentifierError +from orcapod.side_effects import SideEffectPod +from orcapod.sources import SpiralDBTableSource +from orcapod.streams import StreamView, ViewStatus +from tests.test_core.streams.test_head_and_preview import _FakeDynamicSource +from tests.test_databases import fake_spiral_sdk + +ROWS = 40 +_PROJECT = "sample" +_KEYS = pa.schema( + [pa.field("subject", pa.string()), pa.field("timestamp", pa.uint64())] +) + + +def _rows(n: int = ROWS) -> pa.Table: + return pa.table( + { + "subject": [f"m{i * 3 // n}" for i in range(n)], + "timestamp": pa.array(range(n), pa.uint64()), + "x": pa.array([None if i % 7 == 3 else i for i in range(n)], pa.int64()), + "note": [f"n{i}" for i in range(n)], + } + ) + + +@pytest.fixture(params=["spiral", "held"]) +def source( + request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """Make a source of 40 rows, read on demand (6 per SDK batch) or held.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 6) + with fake_spiral_sdk.install(tmp_path / "spiral"): + fake_spiral_sdk.ExternalProject(_PROJECT).create_table( + "default.event", key_schema=_KEYS + ).write(_rows()) + + def make(**kwargs: Any) -> Any: + kwargs.setdefault("tag_only_columns", True) + if request.param == "spiral": + kwargs.setdefault("batch_rows", 4) + return SpiralDBTableSource(_PROJECT, "event", **kwargs) + kwargs.pop("batch_rows", None) + return ArrowTableSource( + _rows(), tag_columns=["subject", "timestamp"], source_id="e", **kwargs + ) + + yield make + + +@pytest.fixture() +def spiral(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """A SpiralDB source of 40 rows, scanned 6 rows per SDK batch, and its scan log.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 6) + with fake_spiral_sdk.install(tmp_path / "spiral"): + fake_spiral_sdk.ExternalProject(_PROJECT).create_table( + "default.event", key_schema=_KEYS + ).write(_rows()) + + def make(**kwargs: Any) -> SpiralDBTableSource: + options: dict[str, Any] = {"tag_only_columns": True, "batch_rows": 4} + options.update(kwargs) + made = SpiralDBTableSource( + _PROJECT, + "event", + **options, + ) + fake_spiral_sdk.scan_log.clear() + return made + + yield make + + +class _Calls: + """A function pod that records the rows it was called on.""" + + def __init__(self, fail_at: int | None = None) -> None: + self.seen: list[int] = [] + seen = self.seen + + @function_pod(output_keys="y") + def triple(timestamp: int | None, x: int | None) -> int: + seen.append(timestamp or 0) + if timestamp == fail_at: + raise RuntimeError(f"failed at {timestamp}") + return 3 * (x or 0) + + self.function: Any = triple + + @property + def pod(self) -> FunctionPod: + return self.function.pod + + +def _with_time(source: Any) -> Any: + """``source`` with its ``timestamp`` as data: a pod takes it.""" + return source(tag_only_columns=["subject"]) + + +def _same(left: pa.Table, right: pa.Table) -> None: + assert left.schema.equals(right.schema, check_metadata=True) + assert left.equals(right) + + +# --------------------------------------------------------------------------- +# The first n rows of the sync order +# --------------------------------------------------------------------------- + + +CHAINS: dict[str, Callable[[Any], Any]] = { + "source": lambda s: s(), + "data_tags": lambda s: s(tag_only_columns=False), + "drop_nulls": lambda s: s().drop_nulls(), + "filter": lambda s: s().filter(col("x") >= 9, subject="m2"), + "nothing_left": lambda s: s().filter(col("x") >= 1000), + "columns": lambda s: ( + s() + .map_data({"note": "text"}) + .map_tags({"timestamp": "t"}) + .add_tags(cohort="A") + .drop_tag_columns("subject") + ), + "pass_through": lambda s: s().select_data_columns(["x", "note"]), + "function": lambda s: _Calls().pod(_with_time(s)), + "function_then_filter": lambda s: ( + _Calls().pod(_with_time(s)).filter(col("y") >= 30).map_data({"y": "z"}) + ), + "filter_then_function": lambda s: _Calls().pod(_with_time(s).filter(subject="m1")), + "nothing_to_compute": lambda s: _Calls().pod( + _with_time(s).filter(subject="absent") + ), + "two_functions": lambda s: _on_y(_Calls().pod(_with_time(s)).drop_nulls()), +} + + +def _on_y(stream: Any) -> Any: + @function_pod(output_keys=("half", "label")) + def second(y: int) -> tuple[float, str]: + return y / 2, str(y) + + return second.pod(stream) + + +@pytest.mark.parametrize("n", [1, 3, 12, 39, 40, 41, 500]) +@pytest.mark.parametrize("name", list(CHAINS)) +def test_a_preview_is_the_first_rows_of_the_sync_result( + source: Any, name: str, n: int +) -> None: + """Values, types, nullability, columns and order; and what the view says.""" + stream = CHAINS[name](source) + view = stream.preview(n) + whole = CHAINS[name](source).as_table() + _same(view.as_table(), whole.slice(0, n)) + assert type(view) is StreamView + if whole.num_rows < n: + assert view.status is ViewStatus.ROWS + assert view.total_rows == whole.num_rows + assert f"preview: all {whole.num_rows} row" in view.header() + else: + assert view.status is ViewStatus.PARTIAL + assert view.total_rows is None + assert f"preview: first {n} row" in view.header() + assert "run() computes every row" in str(view) + # Nothing was kept: head() shows what it did before. + assert stream.head(3).header() == CHAINS[name](source).head(3).header() + _ = view._repr_html_() + + +@pytest.mark.parametrize("first", [1, 2, 1024]) +def test_the_batch_sizes_do_not_show( + source: Any, monkeypatch: pytest.MonkeyPatch, first: int +) -> None: + """The size of the first slice is not part of the result.""" + monkeypatch.setattr(preview_module, "FIRST_BATCH_ROWS", first) + stream = source().drop_nulls().filter(subject="m2") + _same(stream.preview(7).as_table(), stream.as_table().slice(0, 7)) + + +WHOLE: dict[str, Callable[[Any], Any]] = { + "join": lambda s: s().join(s().select_data_columns(["x"]).map_data({"x": "x2"})), + "semi_join": lambda s: s().semi_join(s().filter(subject="m1")), + "group_by": lambda s: s().group_by("subject"), + "batch": lambda s: s().batch(3), + "polars_filter": lambda s: s().polars_filter(pl.col("x") > 5), + "tag_by": lambda s: s().drop_nulls().tag_by("note"), + "over_a_group": lambda s: s().group_by("subject").map_data({"x": "xs"}), + "rejoin": lambda s: ( + lambda t: t.select_data_columns(["x"]).rejoin( + t.select_data_columns(["note"]).filter(subject="m2") + ) + )(s()), + "join_after_function": lambda s: ( + lambda t: t.join(s().select_data_columns(["note"])) + )(_Calls().pod(_with_time(s))), + "several": lambda s: ( + s() + .drop_nulls() + .join(s().filter(col("x") >= 9).map_data({"x": "a", "note": "b"})) + .group_by("subject") + ), +} + + +@pytest.mark.parametrize("n", [1, 2, 30, 500]) +@pytest.mark.parametrize("name", list(WHOLE)) +def test_a_step_over_its_whole_input(source: Any, name: str, n: int) -> None: + """Refused; with ``compute_all`` the first rows of the sync result, nothing kept.""" + stream = WHOLE[name](source) + with pytest.raises(PreviewRefusedError, match="compute_all=True"): + stream.preview(n) + view = stream.preview(n, compute_all=True) + whole = WHOLE[name](source).as_table() + _same(view.as_table(), whole.slice(0, n)) + assert stream.head(3).header() == WHOLE[name](source).head(3).header() + + +# --------------------------------------------------------------------------- +# How often a function is called +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("n", [1, 5, 40, 100]) +def test_a_function_is_called_once_per_row_shown(source: Any, n: int) -> None: + """Never on a row past the last one needed; in order; again on the next preview.""" + calls = _Calls() + stream = calls.pod(_with_time(source)) + _ = stream.preview(n) + expected = list(range(min(n, ROWS))) + assert calls.seen == expected + _ = stream.preview(n) + assert calls.seen == expected * 2 + + +def test_a_filter_after_a_function_calls_it_until_enough_rows_pass(source: Any) -> None: + """Rows 10, 11 and 12 pass (``x`` of row 10 is null); the next is not asked for.""" + calls = _Calls() + stream = calls.pod(_with_time(source)).filter(col("y") >= 30).map_data({"y": "z"}) + view = stream.preview(2) + assert view.table.column("z").to_pylist() == [33, 36] + assert calls.seen == list(range(13)) + + +def test_a_filter_before_a_function_spares_the_calls(source: Any) -> None: + """Only rows that pass it reach the function.""" + calls = _Calls() + stream = calls.pod(_with_time(source).filter(subject="m1")) + _ = stream.preview(3) + assert calls.seen == [14, 15, 16] + + +def test_each_function_of_a_chain_is_called_once_per_row(source: Any) -> None: + """The inner one no more often than the outer one needs.""" + inner = _Calls() + outer: list[int] = [] + + @function_pod(output_keys="z") + def second(y: int) -> int: + outer.append(y) + return y + 1 + + _ = second.pod(inner.pod(_with_time(source))).preview(4) + assert inner.seen == [0, 1, 2, 3] + assert len(outer) == 4 + + +def test_a_shared_stream_is_computed_once_by_compute_all(source: Any) -> None: + """Two branches of one function joined: one call per row, not two.""" + calls = _Calls() + shared = calls.pod(_with_time(source)) + joined = shared.join(shared.map_data({"y": "z"})) + view = joined.preview(3, compute_all=True) + assert len(view) == 3 + assert calls.seen == list(range(ROWS)) + + +def test_a_function_over_a_whole_step_is_called_for_the_rows_shown(source: Any) -> None: + """``compute_all`` computes the step beneath in full, not the function above it.""" + seen: list[int] = [] + + @function_pod(output_keys="size") + def count(x: list[int | None]) -> int: + seen.append(len(x)) + return len(x) + + stream = count.pod(source().group_by("subject")) + assert len(stream.preview(2, compute_all=True)) == 2 + assert len(seen) == 2 + + +def test_results_a_stream_holds_are_used(source: Any) -> None: + """After a run nothing is called; after a partial read only the rest is.""" + calls = _Calls() + stream = calls.pod(_with_time(source)) + rows = iter(stream) + _ = [next(rows) for _ in range(3)] + assert calls.seen == [0, 1, 2] + _ = stream.preview(5) + assert calls.seen == [0, 1, 2, 3, 4] + _ = stream.run() + calls.seen.clear() + _same(stream.preview(5).as_table(), stream.as_table().slice(0, 5)) + _ = stream.map_data({"y": "z"}).preview(5) + assert calls.seen == [] + + +def test_no_hook_fires(source: Any) -> None: + """A post-run hook is an effect.""" + fired: list[Any] = [] + calls = _Calls() + pod = calls.pod + pod._post_run_hooks.append(fired.append) # pyright: ignore[reportPrivateUsage] # a registered hook + _ = pod(_with_time(source)).preview(3) + assert calls.seen == [0, 1, 2] + assert fired == [] + + +# --------------------------------------------------------------------------- +# Nothing stored +# --------------------------------------------------------------------------- + + +def _cached_pod(calls: _Calls, store: InMemoryArrowDatabase) -> Any: + return CachedFunctionPod(calls.pod, result_database=store) + + +def _cached_function(calls: _Calls, store: InMemoryArrowDatabase) -> Any: + inner = calls.pod.data_function + return FunctionPod(CachedDataFunction(inner, result_database=store)) # pyright: ignore[reportArgumentType] # conforms at runtime + + +@pytest.mark.parametrize("kind", [_cached_pod, _cached_function]) +def test_a_cached_pod_reads_its_results_and_stores_none( + source: Any, kind: Callable[..., Any] +) -> None: + """Stored results are used, missing ones computed and left out of the store.""" + calls = _Calls() + store = InMemoryArrowDatabase() + stream = kind(calls, store).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + _ = stream.preview(3) + assert calls.seen == [0, 1, 2] + assert store.list_table_paths() == [] + # Rows 0 and 1 stored by an iteration of another stream over the same pod. + other = kind(calls, store).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + rows = iter(other) + _ = [next(rows) for _ in range(2)] + calls.seen.clear() + view = stream.preview(4) + assert calls.seen == [2, 3] + assert view.table.column("y").to_pylist() == [0, 3, 6, 0] + (path,) = store.list_table_paths() + table = store.get_all_records(path) + assert table is not None and table.num_rows == 2 + + +# --------------------------------------------------------------------------- +# The read of a source +# --------------------------------------------------------------------------- + + +def test_the_limit_reaches_the_scan(spiral: Any) -> None: + """Pushed down when every row read is shown; else the scan is closed early.""" + cases: list[tuple[Callable[[Any], Any], int | None, int]] = [ + (lambda s: s, 5, 1), + (lambda s: s.map_data({"note": "text"}).add_tags(a=1), 5, 1), + (lambda s: s.drop_nulls(["x"]), None, 2), + (lambda s: s.filter(subject="m0"), None, 1), + ] + for chain, limit, batches in cases: + stream = chain(spiral()) + assert len(stream.preview(5)) == 5 + (scan,) = fake_spiral_sdk.scan_log + assert scan.limit == limit + assert scan.batches_read <= batches + 1 + assert scan.closed + stream = _Calls().pod(spiral(tag_only_columns=["subject"])) + _ = stream.preview(5) + assert fake_spiral_sdk.scan_log[0].limit == 5 + + +def test_a_source_limit_and_where_hold(spiral: Any) -> None: + """The smaller of the two limits; ``where`` in the scan.""" + view = spiral(limit=3, where={"subject": "m1"}).preview(10) + assert view.status is ViewStatus.ROWS + assert view.table.column("timestamp").to_pylist() == [14, 15, 16] + + +def test_max_rows_holds_only_when_every_row_is_read(spiral: Any) -> None: + """As for ``head``: a table of any size can be looked at.""" + assert len(spiral(max_rows=10).preview(20)) == 20 + with pytest.raises(ValueError, match="max_rows"): + spiral(max_rows=10).group_by("subject").preview(1, compute_all=True) + + +def test_a_refreshed_source_is_read_as_it_is_now(spiral: Any) -> None: + """A result kept before a change is not shown after it.""" + root = spiral(tag_only_columns=["subject"]) + calls = _Calls() + stream = calls.pod(root.filter(subject="m0")).map_data({"y": "z"}) + _ = stream.run() + calls.seen.clear() + changed = _rows().slice(1, 1).set_column(2, "x", pa.array([100], pa.int64())) + fake_spiral_sdk.ExternalProject(_PROJECT).table("default.event").write(changed) + assert stream.preview(2).table.column("z").to_pylist() == [0, 3] # still pinned + assert calls.seen == [] + assert root.check_for_new_data() + assert stream.preview(2).table.column("z").to_pylist() == [0, 300] + assert calls.seen == [0, 1] + + +# --------------------------------------------------------------------------- +# Errors and refusals +# --------------------------------------------------------------------------- + + +def test_an_error_is_raised_only_for_a_row_that_is_needed(source: Any) -> None: + """The function's own error, and nothing is kept; a later row is never reached.""" + calls = _Calls(fail_at=5) + stream = calls.pod(_with_time(source)).map_data({"y": "z"}) + assert len(stream.preview(5)) == 5 + with pytest.raises(RuntimeError, match="failed at 5"): + stream.preview(6) + assert calls.seen == [*range(5), *range(6)] + assert stream.head().status is ViewStatus.NOT_COMPUTED + + +def test_a_source_error_is_raised_only_when_reached( + spiral: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """The scan is closed after an error, too.""" + original = SpiralDBTableSource._key_tokens # pyright: ignore[reportPrivateUsage] # a failing row + + def failing(self: Any, table: pa.Table) -> list[str]: + if 20 in table.column("timestamp").to_pylist(): + raise RowIdentifierError("bad key") + return original(self, table) + + monkeypatch.setattr(SpiralDBTableSource, "_key_tokens", failing) + stream = spiral().drop_nulls(["x"]) + assert len(stream.preview(5)) == 5 + with pytest.raises(RowIdentifierError, match="bad key"): + stream.preview(30) + assert all(scan.closed for scan in fake_spiral_sdk.scan_log) + + +def test_what_would_act_is_refused_before_any_call(source: Any) -> None: + """Side effects, the invocation context, polls and cache writes; compute_all or not.""" + calls = _Calls() + delivered: list[int] = [] + + def deliver(y: int, ctx: Any) -> None: + delivered.append(y) + + @function_pod(output_keys="w", ctx_arg="ctx") + def act(y: int, ctx: Any) -> int: + delivered.append(y) + return y + + computed = calls.pod(_with_time(source)) + store = InMemoryArrowDatabase() + fake = _FakeDynamicSource() + refused = [ + SideEffectPod(deliver)(computed), + act.pod(computed), + MapData({"w": "v"})(act.pod(computed)), + CachedSource(source(), cache_database=store), + PollingSource(fake, tag_columns="id", record_id_columns="id"), + ] + for stream in refused: + for compute_all in (False, True): + with pytest.raises( + PreviewRefusedError, match=r"run\(\) computes every row" + ): + stream.preview(2, compute_all=compute_all) + assert (calls.seen, delivered) == ([], []) + assert store.list_table_paths() == [] + assert (fake.polls, fake.fetches) == (0, 0) + + +def test_a_derived_source_is_read_whole(source: Any) -> None: + """Refused, since its origin may compute; allowed by ``compute_all``.""" + derived = DerivedSource( + source(), tags_as_data={"timestamp": "time"}, source_id="derived" + ) + with pytest.raises(PreviewRefusedError, match="compute_all"): + derived.preview(3) + _same( + derived.preview(3, compute_all=True).as_table(), derived.as_table().slice(0, 3) + ) + + +def test_nodes_are_refused(source: Any) -> None: + """Every node of a job, run or not, and a stream over one.""" + calls = _Calls() + job = PipelineJob(name="itl1464", database=InMemoryArrowDatabase()) + with job: + _ = calls.pod(_with_time(source), label="triple").map_data( + {"y": "z"}, label="renamed" + ) + nodes = list(job.nodes.values()) + for node in nodes: + with pytest.raises(PreviewRefusedError): + node.preview(1) + _ = job.run() + calls.seen.clear() + for node in nodes: + with pytest.raises(PreviewRefusedError): + node.preview(1, compute_all=True) + with pytest.raises(PreviewRefusedError): + job.nodes["triple"].map_data({"y": "q"}).preview(1) + assert calls.seen == [] + + +@pytest.mark.parametrize( + ("n", "error"), + [(0, ValueError), (-1, ValueError), (2.0, TypeError), (True, TypeError)], +) +def test_the_number_of_rows_is_checked(source: Any, n: Any, error: Any) -> None: + """Before anything is read.""" + with pytest.raises(error): + source().preview(n) + + +def test_an_inactive_function_gives_no_row(source: Any) -> None: + """No limit is pushed down, every row is looked at, and the view says so.""" + calls = _Calls() + function = calls.pod.data_function + assert isinstance(function, PythonDataFunction) + function.set_active(False) + view = calls.pod(_with_time(source)).preview(3) + assert (len(view), view.status, calls.seen) == (0, ViewStatus.ROWS, []) From 2dda2d82890df0e13b7d08106754987e6b8b4e18 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 04:31:43 -0800 Subject: [PATCH 03/11] fix(streams): a preview holds the streams it remembers, so a freed one's id is never taken for another (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 18 +++- src/orcapod/core/streams/preview.py | 14 ++- tests/test_core/streams/test_preview.py | 99 ++++++++++++++++++- 3 files changed, 120 insertions(+), 11 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 1f699388d..eeca76e34 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -2064,7 +2064,7 @@ def _reads_in_batches(self) -> bool: """Whether the operator is applied batch by batch, over an input read so.""" return ( reads_as_its_class(self, DynamicPodStream) - and type(self._pod).__dict__.get("BATCHES_GIVE_THE_WHOLE") is True + and applied_by_batch(self._pod) and len(self._upstreams) == 1 and reads_in_batches(self._upstreams[0]) ) @@ -2129,10 +2129,7 @@ def _preview_batches( yield from preview_batches(self._cached_stream, request) return pod = cast(StaticOutputOperatorPod, self._pod) - if ( - len(self._upstreams) == 1 - and type(pod).__dict__.get("BATCHES_GIVE_THE_WHOLE") is True - ): + if len(self._upstreams) == 1 and applied_by_batch(pod): keeps_every_row = pod.rows_dropped_text(0, (), self._upstreams) is None wanted = request if keeps_every_row else request.without_limit() with closing(preview_batches(self._upstreams[0], wanted)) as batches: @@ -2321,6 +2318,17 @@ def __repr__(self) -> str: ) +def applied_by_batch(pod: object) -> bool: + """Whether an operator may be applied batch by batch (``run()``, ``preview()``). + + Its own class declares ``BATCHES_GIVE_THE_WHOLE``, and no member is replaced on the + instance: what the class declares says nothing of another ``static_process``. + """ + return type(pod).__dict__.get( + "BATCHES_GIVE_THE_WHOLE" + ) is True and reads_as_its_class(pod, type(pod)) + + def joined_batches(batches: Sequence[StreamProtocol]) -> StreamProtocol: """Put the batches of one operator's result together as the result itself. diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py index f4cf4f2d0..f022fec63 100644 --- a/src/orcapod/core/streams/preview.py +++ b/src/orcapod/core/streams/preview.py @@ -38,14 +38,18 @@ class PreviewRequest: step above may drop rows). A source reads no more. compute_all: Whether a step that needs its whole input may be computed. whole: Whether every row is asked for, by such a step. - kept: The batches of the streams read in full by such steps, by identity: a - stream two branches share is computed once. Discarded with the preview. + kept: Each stream read in full by such steps with its batches, by identity: a + stream two branches share is computed once. The stream is held with its + batches: many are temporary (a step's result), and the identity of one that + was freed is given to another. Discarded with the preview. """ limit: int | None compute_all: bool = False whole: bool = False - kept: dict[int, list[StreamProtocol]] = dataclasses.field(default_factory=dict) + kept: dict[int, tuple[Any, list[StreamProtocol]]] = dataclasses.field( + default_factory=dict + ) def without_limit(self) -> PreviewRequest: """The request to the input of a step that may drop rows.""" @@ -77,8 +81,8 @@ def preview_batches( return if id(stream) not in request.kept: with closing(give(request)) as batches: - request.kept[id(stream)] = list(batches) - yield from request.kept[id(stream)] + request.kept[id(stream)] = (stream, list(batches)) + yield from request.kept[id(stream)][1] def slices_of( diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index 1e8d422f8..1d5dc714f 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -2,6 +2,8 @@ from __future__ import annotations +import gc +import weakref from collections.abc import Callable from pathlib import Path from typing import Any @@ -14,10 +16,12 @@ from orcapod.core.cached_function_pod import CachedFunctionPod from orcapod.core.function_pod import FunctionPod from orcapod.core.data_function import CachedDataFunction, PythonDataFunction -from orcapod.core.operators import MapData +from orcapod.core.operators import Join, MapData, MergeJoin, PolarsFilter from orcapod.core.sources import ArrowTableSource, CachedSource, DerivedSource from orcapod.core.sources.polling_source import PollingSource +from orcapod.core.streams import ArrowTableStream from orcapod.core.streams import preview as preview_module +from orcapod.core.streams.base import reads_in_batches from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import PreviewRefusedError, RowIdentifierError from orcapod.side_effects import SideEffectPod @@ -293,6 +297,99 @@ def test_a_shared_stream_is_computed_once_by_compute_all(source: Any) -> None: assert calls.seen == list(range(ROWS)) +def _branches(s: Any, count: int) -> list[Any]: + """Branches over one source whose whole-input results differ in every value.""" + return [ + s() + .select_data_columns(["x"]) + .polars_filter(pl.col("x") >= k) + .map_data({"x": f"x{k}"}) + for k in range(count) + ] + + +def _joined(streams: list[Any]) -> Any: + first, *rest = streams + for other in rest: + first = first.join(other) + return first + + +# Each gives the memo several temporary results of one size, freed one after another. +TEMPORARIES: dict[str, Callable[[Any], Any]] = { + "joined_filters": lambda s: Join()(*_branches(s, 6)), + "nested_joins": lambda s: _joined(_branches(s, 6)), + "join_of_two_joins": lambda s: _joined(_branches(s, 4)[:2]).join( + _joined(_branches(s, 4)[2:]) + ), + "merge_of_two_filters": lambda s: MergeJoin()( + *( + s().select_data_columns(["x"]).map_data({"x": "a"}).polars_filter(p) + for p in (pl.col("a") >= 0, pl.col("a") >= 20) + ) + ), + "filters_of_tag_bys": lambda s: Join()( + *( + s() + .drop_nulls() + .tag_by("note") + .map_data({"x": f"x{k}"}) + .polars_filter(pl.col(f"x{k}") > k) + for k in range(4) + ) + ), +} + + +@pytest.mark.parametrize("name", list(TEMPORARIES)) +def test_a_temporary_result_is_never_taken_for_another(source: Any, name: str) -> None: + """Review of PR 571 (blocker): the memo was keyed by the identity of a freed stream, + so a branch was given another's rows. Repeated: the reuse depends on the allocator.""" + whole = TEMPORARIES[name](source).as_table() + assert whole.num_rows + for attempt in range(12): + stream = TEMPORARIES[name](source) + view = stream.preview(ROWS * ROWS, compute_all=True) + _same(view.as_table(), whole) + if attempt % 3 == 0: + gc.collect() + + +def test_a_stream_read_in_full_is_held_until_the_preview_ends() -> None: + """The rule itself, whatever the allocator does: the memo holds the stream.""" + stream: Any = ArrowTableStream(_rows(), tag_columns=["subject"]) + request = preview_module.PreviewRequest(limit=None, whole=True) + first = list(preview_module.preview_batches(stream, request)) + held = weakref.ref(stream) + del stream + _ = gc.collect() + assert held() is not None + assert list(preview_module.preview_batches(held(), request)) == first + del request, first + _ = gc.collect() + assert held() is None + + +def test_an_operator_changed_on_the_instance_is_not_applied_by_batch( + source: Any, +) -> None: + """Review of PR 571: what its class declares says nothing of another body.""" + pod = MapData({"note": "text"}) + original: Any = pod.static_process + pod.static_process = lambda *streams: original( # pyright: ignore[reportAttributeAccessIssue] # replaced on the instance: the test + *( + PolarsFilter(predicates=(pl.col("x") == pl.col("x").max(),))(s) + for s in streams + ) + ) + stream = pod(source()) + assert not reads_in_batches(stream) + with pytest.raises(PreviewRefusedError, match="compute_all=True"): + stream.preview(1) + assert stream.preview(1, compute_all=True).table.column("x").to_pylist() == [39] + assert stream.run().table.column("x").to_pylist() == [39] + + def test_a_function_over_a_whole_step_is_called_for_the_rows_shown(source: Any) -> None: """``compute_all`` computes the step beneath in full, not the function above it.""" seen: list[int] = [] From fdf70e94e6b73c1140f41b0a7d493cfa86910f5e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:20:00 -0800 Subject: [PATCH 04/11] fix(streams): a preview never reads a derived source's origin whole, nor a SemiJoin's unused input (ITL-1464) A DerivedSource previewed through its own as_table(), which read the origin whole: a CachedSource origin wrote its cache table, a PollingSource origin was polled, and the derived rows were kept. It now takes its origin's first rows through the origin's own preview (which refuses what would poll or write) or, with compute_all, a job node's stored rows, and keeps nothing. A SemiJoin whose inputs share no tag gives back its left input; preview computed both inputs first and so called a function the full read never calls. An operator now says which input it gives back unchanged, from the schemas (input_given_back), and preview reads only that input. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/streams.md | 6 +- docs/dev/specs/itl-1464-views.md | 7 +- src/orcapod/core/operators/semijoin.py | 5 + .../core/operators/static_output_pod.py | 19 +++ src/orcapod/core/sources/derived_source.py | 40 ++++- tests/test_core/streams/test_preview.py | 143 +++++++++++++++++- 6 files changed, 211 insertions(+), 9 deletions(-) diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 9e3e3ad6f..2374dc404 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -261,7 +261,11 @@ own needs every row of its input, so `preview` refuses it (`PreviewRefusedError` step). `preview(n, compute_all=True)` computes that step and everything beneath it in full, functions included, and keeps none of it. A side-effect pod, a function that takes the invocation context, a `CachedSource`, a `PollingSource` and a node of a pipeline or job are -refused always: a preview never acts. +refused always: a preview never acts. A `semi_join` whose inputs share no tag keeps every row +of its left input and never reads its right one, so `preview` reads only the left input, as +the full read does. A `DerivedSource` over a source shows its origin's first rows through +the origin's own `preview` (refused for a `CachedSource` or `PollingSource` origin); over a +job node it reads the stored rows, only with `compute_all=True`. It keeps none of them. What `run()` does on each kind of object: diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index 0e6f9bc66..06e287024 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -92,7 +92,12 @@ never computes. read in batches and closed at `n`. - `Join`, `MergeJoin`, `SemiJoin`, `Rejoin`, `GroupBy`, `Batch`, `TagBy`, `PolarsFilter` and user operators need a whole input. Refused, naming the step and `run()`; - `preview(n, compute_all=True)` computes that step in full. + `preview(n, compute_all=True)` computes that step in full. An operator that gives one + input back unchanged, decided from the schemas (`input_given_back`: `SemiJoin` without a + shared tag), is previewed as that input, and its other inputs are not read. +- A `DerivedSource` takes its origin's preview (a source origin; refused where the origin + would poll or write its cache) or, with `compute_all`, a job node's stored rows; it keeps + nothing. - A side-effect pod, or a function that takes the invocation context, is refused: a preview has no effects. - A kept result (an already computed stream) is sliced and nothing is computed. diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index d2a379f50..c16d7a8bc 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -190,6 +190,11 @@ def _warn_ignored(ignored: Sequence[tuple[str, str, str]]) -> None: stacklevel=outside_orcapod_stacklevel(), ) + def input_given_back(self, inputs: Sequence[StreamProtocol]) -> int | None: + """The left input, when the inputs share no tag column: every left row is + kept and the right input is never read (``binary_static_process``).""" + return None if self._checked_match_keys(*inputs) else 0 + def _checked_match_keys( self, left_stream: StreamProtocol, right_stream: StreamProtocol ) -> tuple[str, ...]: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index eeca76e34..4c19df0b7 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -799,6 +799,19 @@ def rows_dropped_text( """ return None + def input_given_back(self, inputs: Sequence[StreamProtocol]) -> int | None: + """The position of the input this operator gives back unchanged over + ``inputs``, or ``None`` (the default): it computes its result. + + Decided from the inputs' schemas only: nothing is computed or read. A preview + then reads only that input, as the full read does (``SemiJoin`` without a + shared tag gives back its left input and never reads its right one). + + Args: + inputs: The operator's inputs, in order. + """ + return None + def head_rows(self, stream: StreamProtocol, table: pa.Table) -> pa.Table | None: """The rows ``head`` may show of this operator over ``stream``, from the rows ``stream``'s own ``head`` shows (``table``), before the result is computed. @@ -2136,6 +2149,12 @@ def _preview_batches( for batch in batches: yield pod.static_process(batch) return + given_back = pod.input_given_back(self._upstreams) + if given_back is not None: + # The result is that input as it is: no other input is read, as in the + # full read. + yield from preview_batches(self._upstreams[given_back], request) + return refuse_without_compute_all(self, request, "needs every row of its input") result = pod.static_process( *( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..84d427417 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -1,7 +1,8 @@ from __future__ import annotations import dataclasses -from collections.abc import Collection, Mapping +from contextlib import closing +from collections.abc import Collection, Generator, Mapping from datetime import datetime from typing import TYPE_CHECKING, Any, ClassVar @@ -33,6 +34,12 @@ typed_arrow_schemas, typed_zero_row_table, ) +from orcapod.core.streams.preview import ( + PreviewRequest, + preview_batches, + refuse_without_compute_all, + slices_of, +) from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema @@ -40,6 +47,7 @@ from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode @@ -792,6 +800,36 @@ def head( head.for_stream(self, origin="stored"), total_rows=records.num_rows ) + @override + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """This source's first rows (``preview_batches``), read without keeping them. + + The rows it holds are sliced. Otherwise an origin source gives its first rows + through its own preview, which refuses a source that would poll or write its + cache when read, so nothing is polled or written. An origin job node's stored + rows are read whole, only with ``compute_all``. Nothing read here is kept by + this source. + """ + self._note_provisional_identity_use() + if self._tags_as_data is not None and self._cached_stream is not None: + yield from slices_of(self._cached_stream, request) + return + if self._tags_as_data is None and self._cached_table is not None: + yield from slices_of(self._stream_over(self._cached_table), request) + return + if isinstance(self._origin, RootSource): + # The derived rows are the origin's, one for one and in order: its first + # rows give this source's first rows. + with closing(preview_batches(self._origin, request)) as batches: + rows = pa.concat_tables([batch.as_table() for batch in batches]) + else: + refuse_without_compute_all(self, request, "reads its origin's rows whole") + records = self._origin_records() + rows = self._empty_origin_table() if records is None else records + yield from slices_of(self._stream_over(rows), request) + def _stream_over(self, table: "pa.Table") -> ArrowTableStream: """Return this source's stream over the origin rows ``table``.""" if self._tags_as_data is not None: diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index 1d5dc714f..eafc29a26 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import gc import weakref from collections.abc import Callable @@ -16,7 +17,7 @@ from orcapod.core.cached_function_pod import CachedFunctionPod from orcapod.core.function_pod import FunctionPod from orcapod.core.data_function import CachedDataFunction, PythonDataFunction -from orcapod.core.operators import Join, MapData, MergeJoin, PolarsFilter +from orcapod.core.operators import Join, MapData, MergeJoin, PolarsFilter, SemiJoin from orcapod.core.sources import ArrowTableSource, CachedSource, DerivedSource from orcapod.core.sources.polling_source import PollingSource from orcapod.core.streams import ArrowTableStream @@ -27,6 +28,7 @@ from orcapod.side_effects import SideEffectPod from orcapod.sources import SpiralDBTableSource from orcapod.streams import StreamView, ViewStatus +from orcapod.types import Schema from tests.test_core.streams.test_head_and_preview import _FakeDynamicSource from tests.test_databases import fake_spiral_sdk @@ -485,6 +487,13 @@ def test_the_limit_reaches_the_scan(spiral: Any) -> None: (lambda s: s.map_data({"note": "text"}).add_tags(a=1), 5, 1), (lambda s: s.drop_nulls(["x"]), None, 2), (lambda s: s.filter(subject="m0"), None, 1), + ( + lambda s: DerivedSource( + s, tags_as_data={"timestamp": "time"}, source_id="derived" + ), + 5, + 1, + ), ] for chain, limit, batches in cases: stream = chain(spiral()) @@ -597,18 +606,140 @@ def act(y: int, ctx: Any) -> int: assert (fake.polls, fake.fetches) == (0, 0) -def test_a_derived_source_is_read_whole(source: Any) -> None: - """Refused, since its origin may compute; allowed by ``compute_all``.""" +def test_a_derived_source_reads_only_the_rows_shown(source: Any) -> None: + """Its origin's first rows, as its origin previews them; nothing is kept.""" derived = DerivedSource( source(), tags_as_data={"timestamp": "time"}, source_id="derived" ) + shown = [derived.preview(3).as_table(), derived.preview(3, compute_all=True)] + assert derived._held_rows() is None # pyright: ignore[reportPrivateUsage] + whole = derived.as_table() + for view in shown: + _same(view if isinstance(view, pa.Table) else view.as_table(), whole[:3]) + _same(derived.preview(500).as_table(), whole) + + +@pytest.mark.parametrize("origin", ["cached", "polling"]) +def test_a_derived_source_never_writes_or_polls_its_origin( + source: Any, origin: str +) -> None: + """Refused by the origin, compute_all or not: no cache table, no poll, nothing kept. + + Review of 2dda2d82: the derived source read its origin whole through + ``as_table()``, which wrote a cache table, polled, and kept the rows. + """ + store = InMemoryArrowDatabase() + fake = _FakeDynamicSource(declared=Schema({"id": int, "val": int})) + made: Any = ( + CachedSource(source(), cache_database=store) + if origin == "cached" + else PollingSource(fake, tag_columns="id", record_id_columns="id") + ) + tag = "subject" if origin == "cached" else "id" + derived = DerivedSource(made, tags_as_data={tag: "copy"}, source_id="derived") + before = (fake.polls, fake.fetches) + for compute_all in (False, True): + with pytest.raises(PreviewRefusedError, match=r"run\(\) computes every row"): + derived.preview(1, compute_all=compute_all) + assert store.list_table_paths() == [] + assert (fake.polls, fake.fetches) == before + assert derived._held_rows() is None # pyright: ignore[reportPrivateUsage] + if origin == "cached": + assert made.head().status is ViewStatus.NOT_COMPUTED + + +@pytest.mark.parametrize("tags_as_data", [None, {"subject": "who"}]) +def test_a_derived_source_over_a_node_keeps_nothing( + source: Any, tags_as_data: dict[str, str] | None +) -> None: + """The node's stored rows, read whole only with compute_all and not kept.""" + job = PipelineJob(name="itl1464_derived", database=InMemoryArrowDatabase()) + with job: + _ = _Calls().pod(_with_time(source), label="triple") + _ = job.run() + node = job.nodes["triple"] + derived = ( + DerivedSource(node) + if tags_as_data is None + else DerivedSource(node, tags_as_data=tags_as_data, source_id="derived") + ) with pytest.raises(PreviewRefusedError, match="compute_all"): - derived.preview(3) - _same( - derived.preview(3, compute_all=True).as_table(), derived.as_table().slice(0, 3) + derived.preview(2) + shown = derived.preview(2, compute_all=True).as_table() + assert derived._held_rows() is None # pyright: ignore[reportPrivateUsage] + _same(shown, derived.as_table()[:2]) + + +def _unrelated() -> Any: + """A source tagged ``unrelated`` and ``batch``, whose data a ``_Calls`` pod takes.""" + return ArrowTableSource( + pa.table( + { + "unrelated": ["u0", "u1", "u2"], + "batch": ["b0", "b1", "b2"], + "timestamp": pa.array([0, 1, 2], pa.uint64()), + "x": pa.array([1, 2, 3], pa.int64()), + } + ), + tag_columns=["unrelated", "batch"], + source_id="other", + tag_only_columns=True, ) +@pytest.mark.parametrize("n", [1, 3, 40, 41]) +@pytest.mark.parametrize("form", ["method", "operator", "renamed_tag"]) +def test_a_semi_join_without_a_shared_tag_computes_no_right_input( + source: Any, n: int, form: str +) -> None: + """The left input's first rows, with no call of the right input's function. + + Review of 2dda2d82: preview computed both inputs before SemiJoin gave back its + left input, so it called (and raised in) a function the full read never calls. + """ + calls = _Calls(fail_at=0) + + def joined() -> Any: + """A fresh stream each time: a read keeps its result, which a preview uses.""" + right = calls.pod(_unrelated()) + left = source() + if form == "method": + return left.semi_join(right) + if form == "renamed_tag": + left = left.map_tags({"subject": "who"}) + return SemiJoin()(left, right) + + whole = joined().as_table() + assert calls.seen == [] + assert _row_set(asyncio.run(_async_rows(joined()))) == _row_set(whole.to_pylist()) + for compute_all in (False, True): + _same(joined().preview(n, compute_all=compute_all).as_table(), whole[:n]) + assert calls.seen == [] + + +def _row_set(rows: list[dict[str, Any]]) -> set[tuple[tuple[str, Any], ...]]: + """The rows as a set, for an order the async path does not promise.""" + return {tuple(sorted(row.items())) for row in rows} + + +async def _async_rows(stream: Any) -> list[dict[str, Any]]: + """Every row of the stream's async read, as dicts of its tags and data.""" + return [ + {**tag.as_dict(), **data.as_dict()} + async for tag, data in stream.async_iter_data() + ] + + +def test_a_semi_join_with_a_shared_tag_still_reads_both(source: Any) -> None: + """With a shared tag both inputs are needed, as in the full read.""" + left = source() + right = source().filter(subject="m1") + joined = left.semi_join(right) + with pytest.raises(PreviewRefusedError, match="compute_all"): + joined.preview(2) + _same(joined.preview(5, compute_all=True).as_table(), joined.as_table()[:5]) + + def test_nodes_are_refused(source: Any) -> None: """Every node of a job, run or not, and a stream over one.""" calls = _Calls() From 342d8bb0ca39e8c3bf5b4f452300aa0c9d14ee9b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 03:31:30 -0800 Subject: [PATCH 05/11] fix(streams): a derived source previews its origin batch by batch (ITL-1464) Below a step that may drop rows (a filter, drop_nulls, a function over them) no limit reaches the derived source, and it read and concatenated every batch of its origin before giving a row. Each origin batch is now derived as it comes, so the origin's scan is closed as soon as the step above has its rows. The builder takes the position of a batch's first row and the keys of the earlier batches, so positional record ids continue across batches and a key repeated in a later batch is refused when reached. Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-views.md | 5 +- src/orcapod/core/sources/derived_source.py | 48 ++++++++--- src/orcapod/core/sources/stream_builder.py | 41 ++++++++-- tests/test_core/streams/test_preview.py | 93 ++++++++++++++++++++++ 4 files changed, 166 insertions(+), 21 deletions(-) diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index 06e287024..7a9317423 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -95,8 +95,9 @@ never computes. `preview(n, compute_all=True)` computes that step in full. An operator that gives one input back unchanged, decided from the schemas (`input_given_back`: `SemiJoin` without a shared tag), is previewed as that input, and its other inputs are not read. -- A `DerivedSource` takes its origin's preview (a source origin; refused where the origin - would poll or write its cache) or, with `compute_all`, a job node's stored rows; it keeps +- A `DerivedSource` takes its origin's preview batch by batch (a source origin; refused + where the origin would poll or write its cache; positional record ids continue across + batches and a key repeated in a later batch is refused when reached) or, with `compute_all`, a job node's stored rows; it keeps nothing. - A side-effect pod, or a function that takes the invocation context, is refused: a preview has no effects. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 84d427417..54e24650e 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -597,13 +597,22 @@ def _build_derived_stream( return self._derive_from(table, tags_as_data), has_rows def _derive_from( - self, table: "pa.Table", tags_as_data: Mapping[str, str] + self, + table: "pa.Table", + tags_as_data: Mapping[str, str], + *, + first_row: int = 0, + seen_keys: dict[str, int] | None = None, ) -> ArrowTableStream: """Append the tag copies to the origin rows ``table`` and enrich it as a source. Args: table: Rows of the origin. tags_as_data: Maps a tag column of the origin to the name of its copy. + first_row: The position of the first row of ``table`` among the origin's + rows, when it is a later batch of them. + seen_keys: The keys of the earlier batches' rows + (``SourceStreamBuilder.build``); ``None`` for all the rows. """ for tag, name in tags_as_data.items(): # The copy is the tag's own Arrow column under a renamed field, so its @@ -619,6 +628,8 @@ def _derive_from( source_name=self.source_name, kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), + first_row=first_row, + seen_keys=seen_keys, ) return result.stream @@ -806,9 +817,10 @@ def _preview_batches( ) -> Generator[StreamProtocol, None, None]: """This source's first rows (``preview_batches``), read without keeping them. - The rows it holds are sliced. Otherwise an origin source gives its first rows - through its own preview, which refuses a source that would poll or write its - cache when read, so nothing is polled or written. An origin job node's stored + The rows it holds are sliced. Otherwise an origin source gives its rows through + its own preview, which refuses a source that would poll or write its cache + when read, so nothing is polled or written; each of its batches is derived as + it comes, so the origin reads no further than the rows a step above takes. An origin job node's stored rows are read whole, only with ``compute_all``. Nothing read here is kept by this source. """ @@ -819,15 +831,27 @@ def _preview_batches( if self._tags_as_data is None and self._cached_table is not None: yield from slices_of(self._stream_over(self._cached_table), request) return - if isinstance(self._origin, RootSource): - # The derived rows are the origin's, one for one and in order: its first - # rows give this source's first rows. + if isinstance(self._origin, RootSource) and self._tags_as_data is not None: + # The derived rows are the origin's, one for one and in order: each batch + # the origin gives is derived as it comes, its positional record ids + # continuing from the rows before it and its keys checked against + # theirs, so a step above that stops reading stops the origin too. + first_row = 0 + seen_keys: dict[str, int] = {} with closing(preview_batches(self._origin, request)) as batches: - rows = pa.concat_tables([batch.as_table() for batch in batches]) - else: - refuse_without_compute_all(self, request, "reads its origin's rows whole") - records = self._origin_records() - rows = self._empty_origin_table() if records is None else records + for batch in batches: + rows = batch.as_table() + yield self._derive_from( + rows, + self._tags_as_data, + first_row=first_row, + seen_keys=seen_keys, + ) + first_row += rows.num_rows + return + refuse_without_compute_all(self, request, "reads its origin's rows whole") + records = self._origin_records() + rows = self._empty_origin_table() if records is None else records yield from slices_of(self._stream_over(rows), request) def _stream_over(self, table: "pa.Table") -> ArrowTableStream: diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..0a291b7f9 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -200,12 +200,22 @@ def key_column_type_allowed(arrow_type: pa.DataType) -> bool: ) -def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[str]: +def row_identifiers( + table: pa.Table, + record_id_columns: Sequence[str], + *, + first_row: int = 0, + seen: dict[str, int] | None = None, +) -> list[str]: """Return each row's identifier: its key, or its position when no key is named. Args: - table: The source's rows. + table: The source's rows, or a part of them read in batches. record_id_columns: The key columns, in key order; empty for position. + first_row: The position of the table's first row among the source's rows: 0 + for the whole table, the rows before it for a later batch. + seen: The keys of the rows before ``table``, by position, when it is a later + batch; the keys of its rows are added. ``None`` for the whole table. Returns: One identifier per row, in row order. @@ -216,7 +226,7 @@ def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[s or two rows have the same key. The message names the column or the key. """ if not record_id_columns: - return [positional_row_identifier(i) for i in range(table.num_rows)] + return [positional_row_identifier(first_row + i) for i in range(table.num_rows)] missing = [c for c in record_id_columns if c not in table.column_names] if missing: raise RowIdentifierError( @@ -243,9 +253,10 @@ def row_identifiers(table: pa.Table, record_id_columns: Sequence[str]) -> list[s "value outside years 1 to 9999, which a row identifier cannot write" ) from exc identifiers: list[str] = [] - seen: dict[str, int] = {} - for i in range(table.num_rows): - key = [(c, columns[c][i]) for c in record_id_columns] + seen = {} if seen is None else seen + for row in range(table.num_rows): + i = first_row + row + key = [(c, columns[c][row]) for c in record_id_columns] nulls = [c for c, value in key if value is None] if nulls: raise RowIdentifierError( @@ -393,6 +404,8 @@ def build( data_tags: Collection[str] = (), *, hash_in_key_order: bool = False, + first_row: int = 0, + seen_keys: dict[str, int] | None = None, ) -> SourceStreamResult: """Run the full enrichment pipeline. @@ -431,6 +444,13 @@ def build( (ITL-1272). The stream keeps the rows in the order given. Off by default: the rows are hashed in the order given, which the user may have chosen on purpose. Needs key columns and no ``source_id``. + first_row: The position of the table's first row among the source's + rows, when the table is a later batch of them (a preview reads a + source in batches): positional record ids continue from it. Needs + a ``source_name``, since a default one is a hash of the whole table. + seen_keys: The keys of the rows of the earlier batches, by position; + the keys of this table's rows are added, and a repeat is refused as + within one table (``row_identifiers``). Returns: SourceStreamResult with enriched stream and metadata. @@ -506,7 +526,14 @@ def build( # 3. The row identifiers (validates the key columns: a missing, null or # repeated key is refused here, before anything is hashed). - identifiers = row_identifiers(table, key_columns) + if (first_row or seen_keys is not None) and source_name is None: + raise ValueError( + "a table read in batches needs a source_name: a default one is a " + "hash of the whole table" + ) + identifiers = row_identifiers( + table, key_columns, first_row=first_row, seen=seen_keys + ) # 4. Compute schema hash from the tag/data Arrow schemas (ITL-640). # Nullable flags in the incoming table are trusted as-is — callers must diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index eafc29a26..ed6ae2f5f 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -507,6 +507,99 @@ def test_the_limit_reaches_the_scan(spiral: Any) -> None: assert fake_spiral_sdk.scan_log[0].limit == 5 +DERIVED_CHAINS: dict[ + str, tuple[dict[str, Any], dict[str, str], Callable[[Any], Any]] +] = { + "filter": ({}, {"timestamp": "time"}, lambda d: d.filter(col("time") >= 0)), + "drop_nulls": ({}, {"timestamp": "time"}, lambda d: d.drop_nulls(["x"])), + "function": ( + {"tag_only_columns": ["subject"]}, + {"subject": "who"}, + lambda d: _Calls().pod(d.drop_nulls(["x"])), + ), +} + + +@pytest.mark.parametrize("keys", [(), ("subject",)]) +@pytest.mark.parametrize("name", list(DERIVED_CHAINS)) +def test_a_derived_source_below_a_step_that_drops_rows_reads_what_it_needs( + spiral: Any, name: str, keys: tuple[str, ...] +) -> None: + """The origin is read batch by batch, and its scan closed once enough rows passed. + + Review of fdf70e94: with no limit (a step above may drop rows), the derived + source read every batch of its origin before giving its first row. + """ + options, tags_as_data, chain = DERIVED_CHAINS[name] + key_columns = (*keys, "timestamp") if keys else () + + def derived() -> Any: + return DerivedSource( + spiral(**options), + tags_as_data=tags_as_data, + source_id="derived", + record_id_columns=key_columns or None, + ) + + stream = chain(derived()) + view = stream.preview(5) + (scan,) = fake_spiral_sdk.scan_log + assert scan.limit is None + assert scan.batches_read <= 2 + assert scan.closed + _same(view.as_table(), chain(derived()).as_table().slice(0, 5)) + + +@pytest.mark.parametrize("keys", [(), ("timestamp", "subject")]) +def test_a_derived_source_read_in_batches_names_its_rows_as_read_whole( + spiral: Any, keys: tuple[str, ...] +) -> None: + """Record ids, system tags and source info of every batch: as in one read. + + Positional record ids continue from one batch to the next. + """ + + def derived() -> Any: + return DerivedSource( + spiral(), + tags_as_data={"timestamp": "time"}, + source_id="derived", + record_id_columns=keys or None, + ) + + request = preview_module.PreviewRequest(limit=None) + batches = list(preview_module.preview_batches(derived(), request)) + assert len(batches) > 1 + read = pa.concat_tables( + b.as_table(columns=preview_module.PREVIEW_COLUMNS) for b in batches + ) + _same(read, derived().as_table(columns=preview_module.PREVIEW_COLUMNS)) + rows = asyncio.run(_async_rows(derived())) + assert _row_set(rows) == _row_set( + read.select(derived().keys()[0] + derived().keys()[1]).to_pylist() + ) + + +def test_a_repeated_key_across_batches_is_refused_when_reached(spiral: Any) -> None: + """A key repeated in a later batch raises when that row is reached, not before.""" + derived = DerivedSource( + spiral(), + tags_as_data={"timestamp": "time"}, + source_id="derived", + record_id_columns="subject", + ) + assert len(derived.preview(1)) == 1 + with pytest.raises(RowIdentifierError, match="unique"): + derived.preview(30) + with pytest.raises(RowIdentifierError, match="unique"): + DerivedSource( + spiral(), + tags_as_data={"timestamp": "time"}, + source_id="derived", + record_id_columns="subject", + ).as_table() + + def test_a_source_limit_and_where_hold(spiral: Any) -> None: """The smaller of the two limits; ``where`` in the scan.""" view = spiral(limit=3, where={"subject": "m1"}).preview(10) From 82a3a6e063259a2c528e22f15552bc82460d8402 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 07:49:12 -0800 Subject: [PATCH 06/11] fix(streams): a preview is read-only at every cached layer and takes no shortcut past a subclass (ITL-1464) Review of 342d8bb0: - Nested CachedDataFunction layers: preview read the outer layer and called the inner one with call(), which created and wrote its table. Data functions now have require_preview() and preview_call() (DataFunctionProtocol): each cached layer reads and hands a miss to the layer beneath, read-only; a layer with no read-only call refuses before any call. - SemiJoin's input_given_back shortcut skipped a subclass's own binary_static_process. A shortcut now holds only when the processing methods are those of the class that wrote it (written_for_its_processing); otherwise the full operation runs. Pods' preview_data and data functions' preview_call follow the same rule (a subclass with its own processing is refused). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 3 +- docs/concepts/streams.md | 8 +- src/orcapod/core/cached_function_pod.py | 1 + src/orcapod/core/data_function.py | 83 +++++++ src/orcapod/core/function_pod.py | 36 ++- .../core/operators/static_output_pod.py | 16 +- src/orcapod/core/streams/preview.py | 37 +++ .../protocols/core_protocols/data_function.py | 28 +++ tests/test_core/streams/test_preview.py | 229 ++++++++++++++++++ 9 files changed, 431 insertions(+), 10 deletions(-) diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index c50666eda..211a17901 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -3,7 +3,8 @@ - `stream.preview(n)`: the first `n` rows of a stream that is not computed, computing only what they need (ITL-1464). Functions are called on as few rows as that takes; nothing is kept, stored or delivered. A step that needs its whole input (a join, `group_by`, ...) is refused - unless `compute_all=True`. + unless `compute_all=True`. Every cached layer of a data function reads and none writes; a pod + or data function subclass with its own row processing is refused. ### Changed diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 2374dc404..731e53f53 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -253,7 +253,8 @@ print(first.as_table().column("age_months").to_pylist()) A source reads no more than is needed, an operator takes batches until enough rows have passed, and **your functions are called**, on one row after another until `n` rows have come out. Nothing is kept on a stream, nothing is stored (a pod with stored results reads them and -adds none), and no hook fires; calling `preview` again computes again. Results a stream +adds none, and so does every cached layer of a data function: none writes or creates a table), +and no hook fires; calling `preview` again computes again. Results a stream already holds are used. A view of fewer rows than asked for says it shows all of them. A join, `group_by`, `batch`, `polars_filter`, `tag_by`, `pick`, `index` or an operator of your @@ -261,7 +262,10 @@ own needs every row of its input, so `preview` refuses it (`PreviewRefusedError` step). `preview(n, compute_all=True)` computes that step and everything beneath it in full, functions included, and keeps none of it. A side-effect pod, a function that takes the invocation context, a `CachedSource`, a `PollingSource` and a node of a pipeline or job are -refused always: a preview never acts. A `semi_join` whose inputs share no tag keeps every row +refused always: a preview never acts. So is a function pod or data function of your own +class that overrides how its class computes a row (`process_data`, `call`): what it does is +not known. A subclass of an operator that overrides how it computes its result is treated as +an operator of your own. A `semi_join` whose inputs share no tag keeps every row of its left input and never reads its right one, so `preview` reads only the left input, as the full read does. A `DerivedSource` over a source shows its origin's first rows through the origin's own `preview` (refused for a `CachedSource` or `PollingSource` origin); over a diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 83684d608..e78831d90 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -303,6 +303,7 @@ async def async_process_data( def require_preview(self) -> None: """See ``_FunctionPodBase.require_preview``: the inner pod's answer.""" + self._require_own_processing() cast(_FunctionPodBase, cast(object, self._function_pod)).require_preview() def preview_data(self, data: DataProtocol) -> DataProtocol | None: diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index fc124c478..50eebe7ab 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -28,8 +28,10 @@ hash_default_value, ) from orcapod.core.result_cache import ResultCache +from orcapod.core.streams.preview import written_for_its_processing from orcapod.errors import ( NoOutputsDeclaredError, + PreviewRefusedError, OutputTypeError, UnstorableDatetimeError, ) @@ -126,6 +128,11 @@ def parse_function_outputs( E = TypeVar("E", bound=DataFunctionExecutorProtocol) +DATA_FUNCTION_PROCESSING = ("call", "direct_call") +"""The methods that compute a data function's output: a ``preview_call`` written for a +class holds for a subclass only when it overrides neither (``written_for_its_processing``).""" + + class DataFunctionBase(TraceableBase, Generic[E]): """Abstract base class for DataFunctionProtocol. @@ -418,6 +425,39 @@ async def direct_async_call( """Asynchronous counterpart of ``direct_call``.""" ... + # ==================== Preview ==================== + + def require_preview(self) -> None: + """Refuse a preview unless this function's ``preview_call`` is read-only. + + A kind with a read-only call (``PythonDataFunction``, ``DataFunctionWrapper``, + ``CachedDataFunction``) writes ``preview_call`` for its own ``call`` and + ``direct_call``: a subclass that overrides either without writing + ``preview_call`` again is refused, since what it does when called is not known + (review of PR 571). Any other kind has none. + + Raises: + PreviewRefusedError: If this function has no read-only call. + """ + definer = next(c for c in type(self).__mro__ if "preview_call" in vars(c)) + if definer is DataFunctionBase or not written_for_its_processing( + self, "preview_call", DATA_FUNCTION_PROCESSING + ): + raise PreviewRefusedError( + f"its data function {type(self).__name__} has no read-only call" + ) + + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """Refused: this kind of data function has no read-only call. + + Raises: + PreviewRefusedError: Always (``require_preview``). + """ + self.require_preview() + raise PreviewRefusedError( + f"its data function {type(self).__name__} has no read-only call" + ) + FUNCTION_SIGNATURE_HASH_LABEL = "function_signature_v1" """Label of the stored function signature hash (``function_signature_hash``).""" @@ -1305,6 +1345,16 @@ def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": version=inner.get("version", "v0.0"), ) + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """Call the function (``DataFunctionProtocol.preview_call``): it stores nothing. + + Raises: + PreviewRefusedError: If a subclass computes in its own way + (``require_preview``). + """ + self.require_preview() + return self.call(data) + class DataFunctionWrapper(DataFunctionBase[E]): """Wrapper around a DataFunctionProtocol to modify or extend its behavior. @@ -1459,6 +1509,20 @@ async def direct_async_call( ) -> DataProtocol | None: return await self._data_function.direct_async_call(data, **kwargs) + def require_preview(self) -> None: + """This wrapper's answer, then the wrapped function's (``DataFunctionBase``).""" + super().require_preview() + self._data_function.require_preview() + + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """The wrapped function's ``preview_call``. + + Raises: + PreviewRefusedError: As ``require_preview``. + """ + self.require_preview() + return self._data_function.preview_call(data) + class CachedDataFunction(DataFunctionWrapper): """Wrapper around a DataFunctionProtocol that caches results for identical input data. @@ -1567,6 +1631,25 @@ def call( ) return output_data + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """The stored result, else the wrapped function's ``preview_call``; nothing is + stored and no table created, at this layer or any beneath it (ITL-1464). + + Raises: + InputValidationError: If ``data`` is of another data context than this + function's. + PreviewRefusedError: As ``require_preview``. + """ + self.require_preview() + require_same_data_context(data.data_context_key, self.data_context_key) + stored = self._cache.lookup(data, data_context_key=self.data_context_key) + if stored is not None: + return stored + output = self._data_function.preview_call(data) + if output is None: + return None + return output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) + async def async_call( self, data: DataProtocol, diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 3f4e6c24e..daece9ec3 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -43,6 +43,7 @@ preview_batches, refused, slices_of, + written_for_its_processing, ) from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -102,6 +103,11 @@ def _executor_supports_concurrent( return executor is not None and executor.supports_concurrent_execution +POD_PROCESSING = ("process_data", "_invoke_with_hooks") +"""The methods that compute a function pod's rows: a ``preview_data`` written for a +class holds for a subclass only when it overrides neither (``written_for_its_processing``).""" + + class _FunctionPodBase(TraceableBase): """Base pod that applies a data function to each input data.""" @@ -407,6 +413,23 @@ def require_preview(self) -> None: """ raise PreviewRefusedError(f"{type(self).__name__} has no preview") + def _require_own_processing(self) -> None: + """Refuse a pod whose ``preview_data`` was not written for its processing. + + A kind's ``preview_data`` stands for its ``process_data`` and + ``_invoke_with_hooks``; a subclass that overrides either without writing + ``preview_data`` again computes in a way the preview does not know (review of + PR 571). + + Raises: + PreviewRefusedError: If so. + """ + if not written_for_its_processing(self, "preview_data", POD_PROCESSING): + raise PreviewRefusedError( + f"{type(self).__name__} computes its rows in its own way " + "(process_data): its preview is not known" + ) + async def async_process_data( self, tag: TagProtocol, @@ -987,19 +1010,19 @@ def from_fn( ) def require_preview(self) -> None: - """See ``_FunctionPodBase.require_preview``.""" + """See ``_FunctionPodBase.require_preview``; the data function must have a + read-only call at every layer (``DataFunctionProtocol.require_preview``).""" + self._require_own_processing() if self._ctx_arg_name is not None: raise PreviewRefusedError( "its function takes the invocation context: it performs an action" ) + self.data_function.require_preview() def preview_data(self, data: DataProtocol) -> DataProtocol | None: - """See ``_FunctionPodBase.preview_data``.""" + """See ``_FunctionPodBase.preview_data``: the data function's read-only call.""" self.require_preview() - function = self.data_function - if isinstance(function, CachedDataFunction): - return function.call(data, skip_cache_insert=True) - return function.call(data) + return self.data_function.preview_call(data) @property def pod_config(self) -> PodConfig: @@ -2249,6 +2272,7 @@ def with_fall_through( def require_preview(self) -> None: """See ``_FunctionPodBase.require_preview``.""" + self._require_own_processing() self._plain_pod.require_preview() def preview_data(self, data: DataProtocol) -> DataProtocol | None: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 4c19df0b7..5e18573f1 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -61,6 +61,7 @@ PREVIEW_COLUMNS, PreviewRequest, preview_batches, + written_for_its_processing, refuse_without_compute_all, ) from orcapod.core.streams.view import ( @@ -2149,7 +2150,11 @@ def _preview_batches( for batch in batches: yield pod.static_process(batch) return - given_back = pod.input_given_back(self._upstreams) + given_back = ( + pod.input_given_back(self._upstreams) + if written_for_its_processing(pod, "input_given_back", OPERATOR_PROCESSING) + else None + ) if given_back is not None: # The result is that input as it is: no other input is read, as in the # full read. @@ -2337,6 +2342,15 @@ def __repr__(self) -> str: ) +OPERATOR_PROCESSING = ( + "static_process", + "unary_static_process", + "binary_static_process", +) +"""The methods that compute an operator's result: a shortcut written for a class holds +for a subclass only when it overrides none of them (``written_for_its_processing``).""" + + def applied_by_batch(pod: object) -> bool: """Whether an operator may be applied batch by batch (``run()``, ``preview()``). diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py index f022fec63..0cc9c2acf 100644 --- a/src/orcapod/core/streams/preview.py +++ b/src/orcapod/core/streams/preview.py @@ -11,6 +11,7 @@ from __future__ import annotations import dataclasses +import inspect from collections.abc import Generator from contextlib import closing from typing import TYPE_CHECKING, Any @@ -114,6 +115,42 @@ def slices_of( return +def written_for_its_processing( + obj: object, shortcut: str, processing: tuple[str, ...] +) -> bool: + """Whether ``obj``'s ``shortcut`` was written for the processing ``obj`` does. + + A shortcut (an operator's ``input_given_back``, a pod's ``preview_data``, a data + function's ``preview_call``) is written for the processing methods of the class + that defines it. It holds for ``obj`` only when every one of ``processing`` + resolves on ``type(obj)`` to the very member it is on that class (no subclass + overrides one without also writing the shortcut again), and ``obj`` replaces + neither on the instance. Otherwise the shortcut says nothing of what ``obj`` + computes (review of PR 571). + + Args: + obj: The operator, pod or data function. + shortcut: The name of the shortcut method. + processing: The names of the methods that compute what the shortcut stands + for. + + Returns: + Whether the shortcut may be taken for ``obj``. + """ + cls = type(obj) + definer = next((c for c in cls.__mro__ if shortcut in vars(c)), None) + if definer is None: + return False + missing = object() + for name in processing: + if inspect.getattr_static(cls, name, missing) is not inspect.getattr_static( + definer, name, missing + ): + return False + own = getattr(obj, "__dict__", None) or {} + return not any(name in own for name in (shortcut, *processing)) + + def refused(stream: Any, why: str) -> PreviewRefusedError: """Return the error for a stream that cannot be previewed, naming it and the remedy.""" return PreviewRefusedError( diff --git a/src/orcapod/protocols/core_protocols/data_function.py b/src/orcapod/protocols/core_protocols/data_function.py index 140b289eb..51f7e3ecc 100644 --- a/src/orcapod/protocols/core_protocols/data_function.py +++ b/src/orcapod/protocols/core_protocols/data_function.py @@ -186,6 +186,34 @@ async def direct_async_call( """Asynchronous counterpart of ``direct_call``.""" ... + # ==================== Preview ==================== + + def require_preview(self) -> None: + """Refuse a preview of this function before it is called (ITL-1464). + + Raises: + PreviewRefusedError: If this function, or one it wraps, cannot be called + read-only (``preview_call``). + """ + ... + + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """Process a single data for a preview: read-only at every layer (ITL-1464). + + A layer that keeps results reads them and stores none, and creates no table; + it hands a miss to the function it wraps, read-only too. + + Args: + data: The data payload to process. + + Returns: + The output data, or ``None`` when the function filters the data out. + + Raises: + PreviewRefusedError: As ``require_preview``. + """ + ... + # ==================== Serialization ==================== def to_config(self) -> dict[str, Any]: diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index ed6ae2f5f..ac411af16 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -873,3 +873,232 @@ def test_an_inactive_function_gives_no_row(source: Any) -> None: function.set_active(False) view = calls.pod(_with_time(source)).preview(3) assert (len(view), view.status, calls.seen) == (0, ViewStatus.ROWS, []) + + +# --------------------------------------------------------------------------- +# Review of 342d8bb0: read-only at every layer; shortcuts only for their own class +# --------------------------------------------------------------------------- + + +def _nested_cached(calls: _Calls, stores: list[InMemoryArrowDatabase]) -> Any: + """``calls``' function wrapped in one ``CachedDataFunction`` per store, the first + store innermost.""" + function: Any = calls.pod.data_function + for store in stores: + function = CachedDataFunction(function, result_database=store) + return FunctionPod(function) + + +def _untouched(store: InMemoryArrowDatabase) -> None: + assert store.list_table_paths() == [] + + +@pytest.mark.parametrize("depth", [2, 3]) +def test_nested_cached_functions_write_at_no_layer(source: Any, depth: int) -> None: + """Review of 342d8bb0 (blocker): with two cached layers, preview created and wrote + the inner result table. Every layer reads; none writes or creates a table.""" + calls = _Calls() + stores = [InMemoryArrowDatabase() for _ in range(depth)] + stream = _nested_cached(calls, stores).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + shown = stream.preview(3).as_table() + assert calls.seen == [0, 1, 2] + for store in stores: + _untouched(store) + expected = ( + _nested_cached(_Calls(), [InMemoryArrowDatabase() for _ in range(depth)]) + .process(_with_time(source).select_data_columns(["timestamp", "x"])) + .as_table() + ) + _same(shown, expected.select(shown.column_names).slice(0, 3)) + + +@pytest.mark.parametrize("depth", [2, 3]) +def test_nested_cached_functions_read_every_layer(source: Any, depth: int) -> None: + """A result stored only by the innermost layer is read through the outer ones, + which add nothing.""" + calls = _Calls() + stores = [InMemoryArrowDatabase() for _ in range(depth)] + rows = iter( + _nested_cached(calls, stores[:1]).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + ) + _ = [next(rows) for _ in range(2)] + (inner_path,) = stores[0].list_table_paths() + calls.seen.clear() + view = ( + _nested_cached(calls, stores) + .process(_with_time(source).select_data_columns(["timestamp", "x"])) + .preview(4) + ) + assert calls.seen == [2, 3] + assert view.table.column("y").to_pylist() == [0, 3, 6, 0] + assert stores[0].list_table_paths() == [inner_path] + inner = stores[0].get_all_records(inner_path) + assert inner is not None and inner.num_rows == 2 + for store in stores[1:]: + _untouched(store) + + +def _python_function_calling_twice() -> Any: + class _CalledTwice(PythonDataFunction): + """A subclass whose ``call`` does more than its class's: it calls twice.""" + + def call(self, data: Any, **kwargs: Any) -> Any: + _ = super().call(data, **kwargs) + return super().call(data, **kwargs) + + calls = _Calls() + inner: Any = calls.pod.data_function + return calls, _CalledTwice(inner._function, output_keys="y") + + +def _wrapper_writing() -> Any: + from orcapod.core.data_function import DataFunctionWrapper + + written: list[Any] = [] + + class _Writing(DataFunctionWrapper[Any]): + """A wrapper whose ``call`` records every output: an effect.""" + + def call(self, data: Any, **kwargs: Any) -> Any: + output = super().call(data, **kwargs) + written.append(output) + return output + + calls = _Calls() + return calls, _Writing(calls.pod.data_function) + + +@pytest.mark.parametrize( + "make", [_python_function_calling_twice, _wrapper_writing], ids=["leaf", "wrapper"] +) +@pytest.mark.parametrize("cached", [False, True]) +def test_a_data_function_overriding_call_is_refused_before_any_call( + source: Any, make: Callable[[], Any], cached: bool +) -> None: + """A layer that cannot be made read-only makes preview refuse, never write: a + subclass whose ``call`` is its own, also beneath a cached layer.""" + calls, function = make() + store = InMemoryArrowDatabase() + if cached: + function = CachedDataFunction(function, result_database=store) + stream = FunctionPod(function).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + for compute_all in (False, True): + with pytest.raises(PreviewRefusedError, match="no read-only call"): + stream.preview(2, compute_all=compute_all) + assert calls.seen == [] + _untouched(store) + + +def test_a_plain_wrapper_is_previewed_through(source: Any) -> None: + """A ``DataFunctionWrapper`` subclass that keeps its class's ``call`` is read-only + when what it wraps is.""" + from orcapod.core.data_function import DataFunctionWrapper + + class _Plain(DataFunctionWrapper[Any]): + pass + + calls = _Calls() + store = InMemoryArrowDatabase() + function = _Plain( + CachedDataFunction(calls.pod.data_function, result_database=store) + ) + stream = FunctionPod(function).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + assert stream.preview(2).table.column("y").to_pylist() == [0, 3] + assert calls.seen == [0, 1] + _untouched(store) + + +class _DiscardingSemiJoin(SemiJoin): + """A SemiJoin that drops the first left row: its own ``binary_static_process``.""" + + def binary_static_process(self, left_stream: Any, right_stream: Any) -> Any: + result = super().binary_static_process(left_stream, right_stream) + table = result.as_table(columns={"source": True, "system_tags": True}) + return ArrowTableStream( + table.slice(1), + tag_columns=result.keys()[0], + data_context=result.data_context_key, + ) + + +def test_a_semi_join_subclass_is_not_given_back_its_left_input(source: Any) -> None: + """Review of 342d8bb0 (high): the shortcut gave back the left input past a + subclass's own processing. A subclass runs the full operation.""" + + def joined() -> Any: + return _DiscardingSemiJoin()(source(), _unrelated()) + + whole = joined().as_table() + with pytest.raises(PreviewRefusedError, match="compute_all"): + joined().preview(1) + for n in (1, 3): + _same(joined().preview(n, compute_all=True).as_table(), whole[:n]) + + +class _DiscardingMapData(MapData): + """A MapData that drops the first row: its own ``unary_static_process``.""" + + def unary_static_process(self, stream: Any) -> Any: + result = super().unary_static_process(stream) + table = result.as_table(columns={"source": True, "system_tags": True}) + return ArrowTableStream( + table.slice(1), + tag_columns=result.keys()[0], + data_context=result.data_context_key, + ) + + +def test_a_batch_operator_subclass_is_not_applied_by_batch(source: Any) -> None: + """The batch shortcut is its class's: a subclass with its own processing is + applied to its whole input.""" + stream = _DiscardingMapData({"note": "text"})(source()) + assert not reads_in_batches(stream) + with pytest.raises(PreviewRefusedError, match="compute_all"): + stream.preview(1) + whole = _DiscardingMapData({"note": "text"})(source()).as_table() + for n in (1, 3): + _same(stream.preview(n, compute_all=True).as_table(), whole[:n]) + + +class _FilteringPod(FunctionPod): + """A pod whose ``process_data`` is its own: it gives no row.""" + + def process_data(self, tag: Any, data: Any, **kwargs: Any) -> Any: + tag, _ = super().process_data(tag, data, **kwargs) + return tag, None + + +class _FilteringCachedPod(CachedFunctionPod): + """A cached pod whose ``process_data`` is its own: it gives no row.""" + + def process_data(self, tag: Any, data: Any, **kwargs: Any) -> Any: + tag, _ = super().process_data(tag, data, **kwargs) + return tag, None + + +@pytest.mark.parametrize("kind", ["plain", "cached"]) +def test_a_pod_subclass_with_its_own_processing_is_refused( + source: Any, kind: str +) -> None: + """A pod's preview stands for its class's ``process_data``; a subclass's own is + not known, so the preview is refused before any call.""" + calls = _Calls() + store = InMemoryArrowDatabase() + if kind == "plain": + pod: Any = _FilteringPod(calls.pod.data_function) + else: + pod = _FilteringCachedPod(calls.pod, result_database=store) + stream = pod.process(_with_time(source).select_data_columns(["timestamp", "x"])) + for compute_all in (False, True): + with pytest.raises(PreviewRefusedError, match="its own way"): + stream.preview(2, compute_all=compute_all) + assert calls.seen == [] + _untouched(store) From bae54b3cbd7b3dad468950945ed4498135df333d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 08:27:53 -0800 Subject: [PATCH 07/11] fix(streams): preview shortcuts apply only to exactly their library class (ITL-1464) Review of 82a3a6e0 (decision N55): a preview shortcut or read-only path applies only when the object is exactly the library class it was written for (exactly_its_class), replacing the method-by-method check. - A data function subclass (an output builder of its own) and a cached pod subclass (a lookup of its own) are refused before any call. - A SemiJoin subclass (dynamic dispatch included) runs the full operation. - A DerivedSource subclass is read in full through its own as_table, on a copy so nothing is kept, only with compute_all; an origin that would poll or write is refused first. - Regression fixed: a DataFunctionProxy bound to a function previews through that function's read-only call, as at 342d8bb0. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 5 +- docs/concepts/streams.md | 8 +- src/orcapod/core/data_function.py | 19 +- src/orcapod/core/data_function_proxy.py | 28 +++ src/orcapod/core/function_pod.py | 22 +-- .../core/operators/static_output_pod.py | 13 +- src/orcapod/core/sources/derived_source.py | 34 ++++ src/orcapod/core/streams/base.py | 8 + src/orcapod/core/streams/preview.py | 38 ++-- tests/test_core/streams/test_preview.py | 168 +++++++++++++++++- 10 files changed, 265 insertions(+), 78 deletions(-) diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index 211a17901..dc9133274 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -3,8 +3,9 @@ - `stream.preview(n)`: the first `n` rows of a stream that is not computed, computing only what they need (ITL-1464). Functions are called on as few rows as that takes; nothing is kept, stored or delivered. A step that needs its whole input (a join, `group_by`, ...) is refused - unless `compute_all=True`. Every cached layer of a data function reads and none writes; a pod - or data function subclass with its own row processing is refused. + unless `compute_all=True`. Every cached layer of a data function reads and none writes; a + subclass of an operator or source is computed in full, and one of a pod or data function + refused. ### Changed diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 731e53f53..2a72f923a 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -262,10 +262,10 @@ own needs every row of its input, so `preview` refuses it (`PreviewRefusedError` step). `preview(n, compute_all=True)` computes that step and everything beneath it in full, functions included, and keeps none of it. A side-effect pod, a function that takes the invocation context, a `CachedSource`, a `PollingSource` and a node of a pipeline or job are -refused always: a preview never acts. So is a function pod or data function of your own -class that overrides how its class computes a row (`process_data`, `call`): what it does is -not known. A subclass of an operator that overrides how it computes its result is treated as -an operator of your own. A `semi_join` whose inputs share no tag keeps every row +refused always: a preview never acts. Every shortcut is written for one class of the library +and applies only to an object of exactly that class: a subclass of an operator or a source is +computed in full (only with `compute_all=True`) and its first rows taken, and a subclass of a +function pod or data function, which could write or act, is refused before any call. A `semi_join` whose inputs share no tag keeps every row of its left input and never reads its right one, so `preview` reads only the left input, as the full read does. A `DerivedSource` over a source shows its origin's first rows through the origin's own `preview` (refused for a `CachedSource` or `PollingSource` origin); over a diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 50eebe7ab..3de1511d4 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -28,7 +28,7 @@ hash_default_value, ) from orcapod.core.result_cache import ResultCache -from orcapod.core.streams.preview import written_for_its_processing +from orcapod.core.streams.preview import exactly_its_class from orcapod.errors import ( NoOutputsDeclaredError, PreviewRefusedError, @@ -128,11 +128,6 @@ def parse_function_outputs( E = TypeVar("E", bound=DataFunctionExecutorProtocol) -DATA_FUNCTION_PROCESSING = ("call", "direct_call") -"""The methods that compute a data function's output: a ``preview_call`` written for a -class holds for a subclass only when it overrides neither (``written_for_its_processing``).""" - - class DataFunctionBase(TraceableBase, Generic[E]): """Abstract base class for DataFunctionProtocol. @@ -431,18 +426,16 @@ def require_preview(self) -> None: """Refuse a preview unless this function's ``preview_call`` is read-only. A kind with a read-only call (``PythonDataFunction``, ``DataFunctionWrapper``, - ``CachedDataFunction``) writes ``preview_call`` for its own ``call`` and - ``direct_call``: a subclass that overrides either without writing - ``preview_call`` again is refused, since what it does when called is not known - (review of PR 571). Any other kind has none. + ``CachedDataFunction``, a bound ``DataFunctionProxy``) has it for an object of + exactly that class (``exactly_its_class``): a subclass is refused, since what it + does when called (an output builder, a store) is not known (review of PR 571). + Any other kind has none. Raises: PreviewRefusedError: If this function has no read-only call. """ definer = next(c for c in type(self).__mro__ if "preview_call" in vars(c)) - if definer is DataFunctionBase or not written_for_its_processing( - self, "preview_call", DATA_FUNCTION_PROCESSING - ): + if definer is DataFunctionBase or not exactly_its_class(self, "preview_call"): raise PreviewRefusedError( f"its data function {type(self).__name__} has no read-only call" ) diff --git a/src/orcapod/core/data_function_proxy.py b/src/orcapod/core/data_function_proxy.py index 90f3fd5fa..690861cc5 100644 --- a/src/orcapod/core/data_function_proxy.py +++ b/src/orcapod/core/data_function_proxy.py @@ -171,6 +171,34 @@ async def direct_async_call(self, data: DataProtocol) -> DataProtocol | None: return await self._bound_function.direct_async_call(data) self._raise_unavailable() + # ==================== Preview ==================== + + def require_preview(self) -> None: + """The bound function's answer (``DataFunctionProtocol.require_preview``). + + Unbound, nothing is refused here: ``preview_call`` raises + ``DataFunctionUnavailableError``, as ``call`` does. + + Raises: + PreviewRefusedError: If this is a subclass, or the bound function has no + read-only call. + """ + super().require_preview() + if self._bound_function is not None: + self._bound_function.require_preview() + + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """The bound function's ``preview_call``; unbound, raises as ``call`` does. + + Raises: + DataFunctionUnavailableError: If no function is bound. + PreviewRefusedError: As ``require_preview``. + """ + self.require_preview() + if self._bound_function is not None: + return self._bound_function.preview_call(data) + self._raise_unavailable() + # ==================== Variation / execution data ==================== def get_function_variation_data(self) -> dict[str, Any]: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index daece9ec3..22eb33a43 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -43,7 +43,7 @@ preview_batches, refused, slices_of, - written_for_its_processing, + exactly_its_class, ) from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -103,11 +103,6 @@ def _executor_supports_concurrent( return executor is not None and executor.supports_concurrent_execution -POD_PROCESSING = ("process_data", "_invoke_with_hooks") -"""The methods that compute a function pod's rows: a ``preview_data`` written for a -class holds for a subclass only when it overrides neither (``written_for_its_processing``).""" - - class _FunctionPodBase(TraceableBase): """Base pod that applies a data function to each input data.""" @@ -414,20 +409,17 @@ def require_preview(self) -> None: raise PreviewRefusedError(f"{type(self).__name__} has no preview") def _require_own_processing(self) -> None: - """Refuse a pod whose ``preview_data`` was not written for its processing. - - A kind's ``preview_data`` stands for its ``process_data`` and - ``_invoke_with_hooks``; a subclass that overrides either without writing - ``preview_data`` again computes in a way the preview does not know (review of - PR 571). + """Refuse a pod that is not exactly the class its ``preview_data`` was written + for: a subclass may compute, look up or act in a way the preview does not know + (``exactly_its_class``; review of PR 571). Raises: PreviewRefusedError: If so. """ - if not written_for_its_processing(self, "preview_data", POD_PROCESSING): + if not exactly_its_class(self, "preview_data"): raise PreviewRefusedError( - f"{type(self).__name__} computes its rows in its own way " - "(process_data): its preview is not known" + f"{type(self).__name__} is a subclass of a pod of the library: " + "its preview is not known" ) async def async_process_data( diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 5e18573f1..7cf1d75e0 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -61,7 +61,7 @@ PREVIEW_COLUMNS, PreviewRequest, preview_batches, - written_for_its_processing, + exactly_its_class, refuse_without_compute_all, ) from orcapod.core.streams.view import ( @@ -2152,7 +2152,7 @@ def _preview_batches( return given_back = ( pod.input_given_back(self._upstreams) - if written_for_its_processing(pod, "input_given_back", OPERATOR_PROCESSING) + if exactly_its_class(pod, "input_given_back") else None ) if given_back is not None: @@ -2342,15 +2342,6 @@ def __repr__(self) -> str: ) -OPERATOR_PROCESSING = ( - "static_process", - "unary_static_process", - "binary_static_process", -) -"""The methods that compute an operator's result: a shortcut written for a class holds -for a subclass only when it overrides none of them (``written_for_its_processing``).""" - - def applied_by_batch(pod: object) -> bool: """Whether an operator may be applied batch by batch (``run()``, ``preview()``). diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 54e24650e..0e4e4d0df 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -1,5 +1,6 @@ from __future__ import annotations +import copy import dataclasses from contextlib import closing from collections.abc import Collection, Generator, Mapping @@ -32,6 +33,7 @@ check_head_size, schema_requires_io, typed_arrow_schemas, + reads_as_its_class, typed_zero_row_table, ) from orcapod.core.streams.preview import ( @@ -811,6 +813,32 @@ def head( head.for_stream(self, origin="stored"), total_rows=records.num_rows ) + def _preview_of_its_read( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """A subclass's preview: its own ``as_table()``, in full, then the first rows. + + The reading above is written for this class; a subclass may read or derive + its rows another way (developer decision N55, review of PR 571), so its rows + are its own full read, only with ``compute_all``. The read is made on a copy, + so this source keeps nothing; an origin source that would poll or write its + cache when read is refused first, as by this class's own preview. + + Raises: + PreviewRefusedError: Without ``compute_all``, or if the origin is refused. + """ + refuse_without_compute_all( + self, request, "is a subclass that reads its rows its own way" + ) + if isinstance(self._origin, RootSource): + # Its own preview refuses an origin that polls or writes its cache, and + # reads one row of any other. + with closing( + preview_batches(self._origin, PreviewRequest(limit=1)) + ) as batches: + _ = next(batches, None) + yield from slices_of(copy.copy(self), request) + @override def _preview_batches( self, request: PreviewRequest @@ -823,8 +851,14 @@ def _preview_batches( it comes, so the origin reads no further than the rows a step above takes. An origin job node's stored rows are read whole, only with ``compute_all``. Nothing read here is kept by this source. + + A subclass takes the general path (``_preview_of_its_read``): its own read in + full, then the first rows. """ self._note_provisional_identity_use() + if not reads_as_its_class(self, DerivedSource): + yield from self._preview_of_its_read(request) + return if self._tags_as_data is not None and self._cached_stream is not None: yield from slices_of(self._cached_stream, request) return diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index b334ab607..965623edd 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1689,6 +1689,14 @@ def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: context (it would act), a source whose read polls or writes a cache, and a node of a pipeline or job (``run()`` it, or ``head()`` it after a run). + Every shortcut and read-only path is written for one class of the library and + applies only to an object of exactly that class (an operator, a data function, + a cached pod, a ``DerivedSource``). A subclass of your own takes the general + path: an operator or source subclass is computed in full (only with + ``compute_all``) and its first ``n`` rows are taken, which is correct and may be + slower; a pod or data function subclass, which could write or act, is refused + before any function is called. + Args: n: The most rows to compute; at least 1. compute_all: Allow steps that need their whole input. diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py index 0cc9c2acf..9e21b49b1 100644 --- a/src/orcapod/core/streams/preview.py +++ b/src/orcapod/core/streams/preview.py @@ -11,7 +11,6 @@ from __future__ import annotations import dataclasses -import inspect from collections.abc import Generator from contextlib import closing from typing import TYPE_CHECKING, Any @@ -115,40 +114,27 @@ def slices_of( return -def written_for_its_processing( - obj: object, shortcut: str, processing: tuple[str, ...] -) -> bool: - """Whether ``obj``'s ``shortcut`` was written for the processing ``obj`` does. +def exactly_its_class(obj: object, shortcut: str) -> bool: + """Whether ``obj`` is exactly the library class its ``shortcut`` was written for. - A shortcut (an operator's ``input_given_back``, a pod's ``preview_data``, a data - function's ``preview_call``) is written for the processing methods of the class - that defines it. It holds for ``obj`` only when every one of ``processing`` - resolves on ``type(obj)`` to the very member it is on that class (no subclass - overrides one without also writing the shortcut again), and ``obj`` replaces - neither on the instance. Otherwise the shortcut says nothing of what ``obj`` - computes (review of PR 571). + A preview shortcut or read-only path (an operator's ``input_given_back``, a pod's + ``preview_data``, a data function's ``preview_call``) is written for one class of + the library. It holds only for an object of exactly that class, with no member + replaced on the instance (``reads_as_its_class``): a subclass, however small, can + compute or act in a way the shortcut does not know (developer decision N55, + review of PR 571). Args: obj: The operator, pod or data function. shortcut: The name of the shortcut method. - processing: The names of the methods that compute what the shortcut stands - for. Returns: Whether the shortcut may be taken for ``obj``. """ - cls = type(obj) - definer = next((c for c in cls.__mro__ if shortcut in vars(c)), None) - if definer is None: - return False - missing = object() - for name in processing: - if inspect.getattr_static(cls, name, missing) is not inspect.getattr_static( - definer, name, missing - ): - return False - own = getattr(obj, "__dict__", None) or {} - return not any(name in own for name in (shortcut, *processing)) + from orcapod.core.streams.base import reads_as_its_class + + definer = next((c for c in type(obj).__mro__ if shortcut in vars(c)), None) + return definer is not None and reads_as_its_class(obj, definer) def refused(stream: Any, why: str) -> PreviewRefusedError: diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index ac411af16..794ef6d1d 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -996,16 +996,12 @@ def test_a_data_function_overriding_call_is_refused_before_any_call( def test_a_plain_wrapper_is_previewed_through(source: Any) -> None: - """A ``DataFunctionWrapper`` subclass that keeps its class's ``call`` is read-only - when what it wraps is.""" + """A ``DataFunctionWrapper`` is read-only when what it wraps is.""" from orcapod.core.data_function import DataFunctionWrapper - class _Plain(DataFunctionWrapper[Any]): - pass - calls = _Calls() store = InMemoryArrowDatabase() - function = _Plain( + function = DataFunctionWrapper[Any]( CachedDataFunction(calls.pod.data_function, result_database=store) ) stream = FunctionPod(function).process( @@ -1098,7 +1094,165 @@ def test_a_pod_subclass_with_its_own_processing_is_refused( pod = _FilteringCachedPod(calls.pod, result_database=store) stream = pod.process(_with_time(source).select_data_columns(["timestamp", "x"])) for compute_all in (False, True): - with pytest.raises(PreviewRefusedError, match="its own way"): + with pytest.raises(PreviewRefusedError, match="subclass of a pod"): + stream.preview(2, compute_all=compute_all) + assert calls.seen == [] + _untouched(store) + + +# --------------------------------------------------------------------------- +# Review of 82a3a6e0: shortcuts for exactly their class (N55) +# --------------------------------------------------------------------------- + + +def test_a_data_function_with_its_own_output_builder_is_refused(source: Any) -> None: + """Review of 82a3a6e0, finding 1: a subclass's ``_build_output_data`` ran (an + effect) beneath a cached layer. A data function subclass is refused before any + call.""" + built: list[Any] = [] + + class _Recording(PythonDataFunction): + def _build_output_data(self, values: Any) -> Any: + output = super()._build_output_data(values) + built.append(output) + return output + + calls = _Calls() + inner: Any = calls.pod.data_function + store = InMemoryArrowDatabase() + leaf: Any = _Recording(inner._function, output_keys="y") + function = CachedDataFunction(leaf, result_database=store) + stream = FunctionPod(function).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + for compute_all in (False, True): + with pytest.raises(PreviewRefusedError, match="no read-only call"): stream.preview(2, compute_all=compute_all) assert calls.seen == [] + assert built == [] + _untouched(store) + + +def test_a_cached_pod_with_its_own_lookup_is_refused(source: Any) -> None: + """Review of 82a3a6e0, finding 2: a subclass's ``lookup_cached_data`` gave rows the + full read does not. A cached pod subclass is refused before any call.""" + + class _Synthetic(CachedFunctionPod): + def lookup_cached_data(self, data: Any) -> Any: + return None + + calls = _Calls() + store = InMemoryArrowDatabase() + stream = _Synthetic(calls.pod, result_database=store).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + with pytest.raises(PreviewRefusedError, match="subclass of a pod"): + stream.preview(2) + assert calls.seen == [] _untouched(store) + + +class _WrappedSemiJoin(SemiJoin): + """A SemiJoin whose ``static_process`` is wrapped by ``__getattribute__`` to drop + the first row: no member of the class is overridden.""" + + def __getattribute__(self, name: str) -> Any: + member = super().__getattribute__(name) + if name != "static_process": + return member + + def dropping(*streams: Any) -> Any: + result = member(*streams) + table = result.as_table(columns={"source": True, "system_tags": True}) + return ArrowTableStream( + table.slice(1), + tag_columns=result.keys()[0], + data_context=result.data_context_key, + ) + + return dropping + + +def test_a_semi_join_with_dynamic_dispatch_runs_the_full_operation( + source: Any, +) -> None: + """Review of 82a3a6e0, finding 3: the shortcut held for a subclass that wraps its + processing dynamically. A subclass runs the full operation.""" + + def joined() -> Any: + return _WrappedSemiJoin()(source(), _unrelated()) + + whole = joined().as_table() + assert whole.column("timestamp").to_pylist()[:2] == [1, 2] + with pytest.raises(PreviewRefusedError, match="compute_all"): + joined().preview(2) + _same(joined().preview(2, compute_all=True).as_table(), whole[:2]) + + +_PROXIED_CALLS: list[int] = [] + + +def _shifted(timestamp: int) -> int: + """A plain function, saved by name in a proxy's config.""" + _PROXIED_CALLS.append(timestamp) + return timestamp + 100 + + +def test_a_bound_proxy_previews_its_function(source: Any) -> None: + """Review of 82a3a6e0, finding 4 (a regression): a ``DataFunctionProxy`` bound to + a plain function previews as at 342d8bb0, through the bound function.""" + from orcapod.core.data_function_proxy import DataFunctionProxy + + function = PythonDataFunction(_shifted, output_keys="y", version="v1.0") + proxy = DataFunctionProxy( + config=function.to_config(), + content_hash_str=function.content_hash().to_string(), + pipeline_hash_str=function.pipeline_hash().to_string(), + ) + proxy.bind(function) # pyright: ignore[reportArgumentType] # conforms at runtime + + def stream() -> Any: + return FunctionPod(proxy).process( # pyright: ignore[reportArgumentType] # conforms at runtime + _with_time(source).select_data_columns(["timestamp"]).drop_nulls() + ) + + _PROXIED_CALLS.clear() + shown = stream().preview(2).as_table() + assert _PROXIED_CALLS == [0, 1] + whole = stream().as_table() + _same(shown, whole.select(shown.column_names).slice(0, 2)) + + +class _DroppingDerived(DerivedSource): + """A DerivedSource whose ``as_table`` drops the first row.""" + + def as_table(self, *args: Any, **kwargs: Any) -> Any: + return super().as_table(*args, **kwargs).slice(1) + + +class _DescendingDerived(DerivedSource): + """A DerivedSource that derives its rows in descending timestamp order.""" + + def _derive_from(self, table: Any, *args: Any, **kwargs: Any) -> Any: + return super()._derive_from( + table.sort_by([("timestamp", "descending")]), *args, **kwargs + ) + + +@pytest.mark.parametrize("kind", [_DroppingDerived, _DescendingDerived]) +def test_a_derived_source_subclass_previews_its_own_read( + source: Any, kind: type[DerivedSource] +) -> None: + """Review of 82a3a6e0, finding 5: a subclass's preview diverged from its read. + A subclass is read in full, only with ``compute_all``, and keeps nothing.""" + + def derived() -> Any: + return kind(source(), tags_as_data={"timestamp": "t"}, source_id="d") + + whole = derived().as_table() + previewed = derived() + with pytest.raises(PreviewRefusedError, match="compute_all"): + previewed.preview(2) + for n in (1, 2, 41): + _same(previewed.preview(n, compute_all=True).as_table(), whole[:n]) + assert previewed._held_rows() is None # pyright: ignore[reportPrivateUsage] From 963d492909048af11dab65bc2e5b01f253d07d8c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 09:03:12 -0800 Subject: [PATCH 08/11] fix(streams): a DerivedSource subclass's preview keeps nothing on its origins (ITL-1464) Review of bae54b3c: - The full read of a subclass ran on a shallow copy that shared its origin, so a cold DerivedSource origin kept every row. Each DerivedSource origin is now read through a copy of its own, recursively; a source of the library that holds its rows, or a SpiralDB table, is read as it is; a job node only by DerivedSource's own read; anything else is refused. - The one-row probe of the origin, made without compute_all, refused an exact DerivedSource over stored rows although the caller gave compute_all. The probe is gone: the origin rule above refuses what it refused. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/derived_source.py | 67 +++++++++++++++---- tests/test_core/streams/test_preview.py | 78 ++++++++++++++++++++++ 2 files changed, 133 insertions(+), 12 deletions(-) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 0e4e4d0df..aff44dfe2 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -40,6 +40,7 @@ PreviewRequest, preview_batches, refuse_without_compute_all, + refused, slices_of, ) from orcapod.errors import InputValidationError @@ -820,24 +821,22 @@ def _preview_of_its_read( The reading above is written for this class; a subclass may read or derive its rows another way (developer decision N55, review of PR 571), so its rows - are its own full read, only with ``compute_all``. The read is made on a copy, - so this source keeps nothing; an origin source that would poll or write its - cache when read is refused first, as by this class's own preview. + are its own full read, only with ``compute_all``. The read is made on a copy + whose origins are copies too (``_origin_read_keeping_nothing``), so neither + this source nor any origin keeps what it read; an origin that cannot be read + that way is refused. Raises: - PreviewRefusedError: Without ``compute_all``, or if the origin is refused. + PreviewRefusedError: Without ``compute_all``, or if an origin is refused. """ refuse_without_compute_all( self, request, "is a subclass that reads its rows its own way" ) - if isinstance(self._origin, RootSource): - # Its own preview refuses an origin that polls or writes its cache, and - # reads one row of any other. - with closing( - preview_batches(self._origin, PreviewRequest(limit=1)) - ) as batches: - _ = next(batches, None) - yield from slices_of(copy.copy(self), request) + twin = copy.copy(self) + twin._origin = _origin_read_keeping_nothing( + self._origin, read_by_this_class=False + ) + yield from slices_of(twin, request) @override def _preview_batches( @@ -908,3 +907,47 @@ def as_table( all_info: bool = False, ) -> "pa.Table": return self._get_stream().as_table(columns=columns, all_info=all_info) + + +def _origin_read_keeping_nothing(origin: Any, *, read_by_this_class: bool) -> Any: + """An origin that a full read of a ``DerivedSource`` subclass may read: nothing it + reads stays on ``origin`` or beneath it (review of PR 571, round 3). + + A ``DerivedSource`` is copied, with its own origin taken the same way, so the rows + it keeps stay on the copy. A source of the library that holds its rows + (``_stream``) or reads them on demand without keeping them (``SpiralDBTableSource``) + is read as it is. A job node is read as it is only by ``DerivedSource``'s own + code, which reads its stored rows (``get_all_records``) and keeps nothing; a + subclass reading one directly could do anything with it. Anything else (a + ``CachedSource``, a ``PollingSource``, a ``SourceProxy``, a source of your own) + is refused: when in doubt, refuse. + + Args: + origin: The origin to read. + read_by_this_class: Whether ``DerivedSource``'s own code reads it. + + Raises: + PreviewRefusedError: If the origin cannot be read without keeping rows. + """ + from orcapod.core.sources.spiraldb_table_source import SpiralDBTableSource + + if isinstance(origin, DerivedSource): + twin = copy.copy(origin) + twin._origin = _origin_read_keeping_nothing( # pyright: ignore[reportPrivateUsage] # the copy's own origin + origin._origin, # pyright: ignore[reportPrivateUsage] # as above + read_by_this_class=reads_as_its_class(origin, DerivedSource), + ) + return twin + if isinstance(origin, RootSource): + holds_its_rows = isinstance( + getattr(origin, "_stream", None), ArrowTableStream + ) and type(origin).__module__.startswith("orcapod.") + if holds_its_rows or reads_as_its_class(origin, SpiralDBTableSource): + return origin + elif read_by_this_class: + return origin + raise refused( + origin, + "a DerivedSource subclass above it would read in full, and it may keep or " + "write what is read", + ) diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index 794ef6d1d..bef944157 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -1256,3 +1256,81 @@ def derived() -> Any: for n in (1, 2, 41): _same(previewed.preview(n, compute_all=True).as_table(), whole[:n]) assert previewed._held_rows() is None # pyright: ignore[reportPrivateUsage] + + +# --------------------------------------------------------------------------- +# Review of bae54b3c: a DerivedSource subclass's full read keeps nothing anywhere +# --------------------------------------------------------------------------- + + +def test_a_derived_source_subclass_over_stored_rows_is_previewed_with_compute_all( + source: Any, +) -> None: + """Review of bae54b3c, finding 1: over an exact DerivedSource of a job node's + stored rows, the origin was probed without ``compute_all`` and refused although + the caller gave it.""" + job = PipelineJob(name="itl1464_derived_subclass", database=InMemoryArrowDatabase()) + with job: + _ = _Calls().pod(_with_time(source), label="triple") + _ = job.run() + + def derived() -> Any: + """Over a cold origin each time: a read keeps the origin's rows on it.""" + inner = DerivedSource(job.nodes["triple"]) + return _DroppingDerived(inner, tags_as_data={"subject": "who"}, source_id="d") + + whole = derived().as_table() + previewed = derived() + with pytest.raises(PreviewRefusedError, match="compute_all"): + previewed.preview(2) + for n in (1, 2): + _same(previewed.preview(n, compute_all=True).as_table(), whole[:n]) + assert previewed._held_rows() is None # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize("depth", [1, 2]) +def test_a_derived_source_subclass_leaves_its_origins_cold( + source: Any, depth: int +) -> None: + """Review of bae54b3c, finding 2: the full read of a copy kept every row on the + shared, cold origin. Each origin is read through a copy of its own.""" + origins: list[Any] = [source()] + for level in range(depth): + origins.append( + DerivedSource( + origins[-1], + tags_as_data={"subject": f"s{level}"}, + source_id=f"o{level}", + ) + ) + previewed = _DroppingDerived( + origins[-1], tags_as_data={"timestamp": "t"}, source_id="d" + ) + shown = previewed.preview(2, compute_all=True).as_table() + for origin in [previewed, *origins[1:]]: + assert origin._held_rows() is None # pyright: ignore[reportPrivateUsage] + _same(shown, previewed.as_table()[:2]) + + +@pytest.mark.parametrize("origin", ["cached", "subclass_over_node"]) +def test_a_derived_source_subclass_refuses_an_origin_that_could_keep_rows( + source: Any, origin: str +) -> None: + """When in doubt, refuse: an origin whose full read could write or keep rows (a + ``CachedSource``; a job node a subclass reads directly) is refused, compute_all or + not, and nothing is written or kept.""" + store = InMemoryArrowDatabase() + if origin == "cached": + made: Any = CachedSource(source(), cache_database=store) + else: + job = PipelineJob(name="itl1464_direct_node", database=InMemoryArrowDatabase()) + with job: + _ = _Calls().pod(_with_time(source), label="triple") + _ = job.run() + made = job.nodes["triple"] + derived = _DroppingDerived(made, tags_as_data={"subject": "who"}, source_id="d") + for compute_all in (False, True): + with pytest.raises(PreviewRefusedError): + derived.preview(1, compute_all=compute_all) + assert store.list_table_paths() == [] + assert derived._held_rows() is None # pyright: ignore[reportPrivateUsage] From 8987839d32917bb726a7a9cbaa549bad0cc6700e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 09:31:59 -0800 Subject: [PATCH 09/11] fix(streams): a DerivedSource subclass origin is refused, never copied (ITL-1464) Review of 963d4929: an origin that is a user's DerivedSource subclass was read through a shallow copy that shared its own state (a list), so it kept every row after a two-row preview. Per N55 only an origin of exactly DerivedSource is copied and read; a subclass origin is refused before it is read, compute_all or not. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/derived_source.py | 17 +++++++++--- tests/test_core/streams/test_preview.py | 30 ++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index aff44dfe2..312355047 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -913,8 +913,9 @@ def _origin_read_keeping_nothing(origin: Any, *, read_by_this_class: bool) -> An """An origin that a full read of a ``DerivedSource`` subclass may read: nothing it reads stays on ``origin`` or beneath it (review of PR 571, round 3). - A ``DerivedSource`` is copied, with its own origin taken the same way, so the rows - it keeps stay on the copy. A source of the library that holds its rows + A ``DerivedSource`` of exactly this class is copied, with its own origin taken the + same way, so the rows it keeps stay on the copy; a subclass of it may keep rows + where a copy shares them, and is refused. A source of the library that holds its rows (``_stream``) or reads them on demand without keeping them (``SpiralDBTableSource``) is read as it is. A job node is read as it is only by ``DerivedSource``'s own code, which reads its stored rows (``get_all_records``) and keeps nothing; a @@ -931,13 +932,21 @@ def _origin_read_keeping_nothing(origin: Any, *, read_by_this_class: bool) -> An """ from orcapod.core.sources.spiraldb_table_source import SpiralDBTableSource - if isinstance(origin, DerivedSource): + if reads_as_its_class(origin, DerivedSource): + # Exactly this class: its state is known, so a copy keeps what it reads. twin = copy.copy(origin) twin._origin = _origin_read_keeping_nothing( # pyright: ignore[reportPrivateUsage] # the copy's own origin origin._origin, # pyright: ignore[reportPrivateUsage] # as above - read_by_this_class=reads_as_its_class(origin, DerivedSource), + read_by_this_class=True, ) return twin + if isinstance(origin, DerivedSource): + # A subclass may hold what it reads where a copy shares it (N55). + raise refused( + origin, + "is a DerivedSource subclass: a DerivedSource subclass above it would " + "read it in full, and it may keep what is read", + ) if isinstance(origin, RootSource): holds_its_rows = isinstance( getattr(origin, "_stream", None), ArrowTableStream diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index bef944157..308122e01 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -1334,3 +1334,33 @@ def test_a_derived_source_subclass_refuses_an_origin_that_could_keep_rows( derived.preview(1, compute_all=compute_all) assert store.list_table_paths() == [] assert derived._held_rows() is None # pyright: ignore[reportPrivateUsage] + + +class _KeepingDerived(DerivedSource): + """A DerivedSource of your own that keeps every table it reads in a list.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kept: list[Any] = [] + + def as_table(self, *args: Any, **kwargs: Any) -> Any: + table = super().as_table(*args, **kwargs) + self.kept.append(table) + return table + + +def test_a_derived_source_subclass_refuses_an_origin_of_your_own_class( + source: Any, +) -> None: + """Review of 963d4929: a ``DerivedSource`` subclass as the origin was read through + a shallow copy sharing its list, so it kept all 40 rows. Only an origin of exactly + the library class is copied and read; a subclass origin is refused before it is + read, compute_all or not.""" + origin = _KeepingDerived(source(), tags_as_data={"subject": "who"}, source_id="o") + derived = _DroppingDerived(origin, tags_as_data={"timestamp": "t"}, source_id="d") + for compute_all in (False, True): + with pytest.raises(PreviewRefusedError): + derived.preview(2, compute_all=compute_all) + assert origin.kept == [] + assert origin._held_rows() is None # pyright: ignore[reportPrivateUsage] + assert derived._held_rows() is None # pyright: ignore[reportPrivateUsage] From 48f8533ec305b53868031c047aa22fd4e3008980 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 10:35:48 -0800 Subject: [PATCH 10/11] fix(streams): preview review fixes from CodeRabbit (ITL-1464) CodeRabbit review of 8987839d: - A shortcut written again by a subclass (preview_call, preview_data, input_given_back) is not the library's: exactly_its_class requires the defining class to be the library's (N55). - The batch shortcut in preview holds for library operators only; run() keeps the opt-in of an operator of your own. - A source or raw stream of your own is read in full only with compute_all; a DerivedSource subclass reads an origin as it is only when the origin is exactly a library class with nothing replaced on the instance. - A cached pod over an inner pod with no preview refuses with PreviewRefusedError. - A held function result and a SemiJoin's given-back input show no meta columns, as the cold preview and the full read. - A held result that gave no row stops the input limit pushdown. - Tests: helper docstrings, the public hook registration, a repeated key only across batches, several mapping entries in two orders. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/cached_function_pod.py | 29 +- src/orcapod/core/function_pod.py | 15 +- .../core/operators/static_output_pod.py | 18 +- src/orcapod/core/sources/base.py | 11 +- src/orcapod/core/sources/derived_source.py | 3 +- .../core/streams/arrow_table_stream.py | 17 +- src/orcapod/core/streams/preview.py | 26 +- tests/test_core/streams/test_preview.py | 277 +++++++++++++++++- 8 files changed, 360 insertions(+), 36 deletions(-) diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index e78831d90..287283ac4 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -6,7 +6,7 @@ import logging from datetime import datetime, timezone from collections.abc import Iterator -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram @@ -17,6 +17,7 @@ function_zero_row_table, ) from orcapod.core.streams.view import StreamView +from orcapod.errors import PreviewRefusedError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.contexts.stored import ( @@ -302,9 +303,27 @@ async def async_process_data( return tag, output def require_preview(self) -> None: - """See ``_FunctionPodBase.require_preview``: the inner pod's answer.""" + """See ``_FunctionPodBase.require_preview``: the inner pod's answer. + + Raises: + PreviewRefusedError: If this pod is a subclass, or the inner pod is not a + pod of the library (it has no preview), or refuses. + """ self._require_own_processing() - cast(_FunctionPodBase, cast(object, self._function_pod)).require_preview() + self._inner_for_preview().require_preview() + + def _inner_for_preview(self) -> _FunctionPodBase: + """The inner pod, which a preview reads through. + + Raises: + PreviewRefusedError: If it is not a pod of the library. + """ + inner: object = self._function_pod + if not isinstance(inner, _FunctionPodBase): + raise PreviewRefusedError( + f"its inner pod {type(inner).__name__} has no preview" + ) + return inner def preview_data(self, data: DataProtocol) -> DataProtocol | None: """The stored result, else the inner pod's, which is not stored.""" @@ -312,9 +331,7 @@ def preview_data(self, data: DataProtocol) -> DataProtocol | None: stored = self.lookup_cached_data(data) if stored is not None: return stored - output = cast(_FunctionPodBase, cast(object, self._function_pod)).preview_data( - data - ) + output = self._inner_for_preview().preview_data(data) if output is None: return None return output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 22eb33a43..2e704651f 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1851,12 +1851,21 @@ def _preview_batches( raise refused(self, f"cannot be previewed: {error}") from error current = not self.is_stale if current and self._cached_output_table is not None: - yield from slices_of(self, request) + from orcapod.core.operators.meta_columns import without_input_meta + + # Without the meta columns, as the rows computed below. + for batch in slices_of(self, request): + yield without_input_meta(batch, (batch,)) return known = dict(self._cached_output_datas) if current else {} function = pod.data_function - # An inactive function gives no row; any other gives one per input row. - one_per_row = type(function) is PythonDataFunction and function.is_active() + # An inactive function gives no row; any other gives one per input row. A + # held result that gave none (the function was inactive then) breaks that. + one_per_row = ( + type(function) is PythonDataFunction + and function.is_active() + and all(output is not None for _, output in known.values()) + ) wanted = request if one_per_row else request.without_limit() given = False index = 0 diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 7cf1d75e0..fe9489aaa 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -62,6 +62,7 @@ PreviewRequest, preview_batches, exactly_its_class, + is_library_class, refuse_without_compute_all, ) from orcapod.core.streams.view import ( @@ -2143,7 +2144,13 @@ def _preview_batches( yield from preview_batches(self._cached_stream, request) return pod = cast(StaticOutputOperatorPod, self._pod) - if len(self._upstreams) == 1 and applied_by_batch(pod): + # A shortcut of the library holds for its own classes only (N55); an operator + # of your own that declares it still takes it in run(). + if ( + len(self._upstreams) == 1 + and applied_by_batch(pod) + and is_library_class(type(pod)) + ): keeps_every_row = pod.rows_dropped_text(0, (), self._upstreams) is None wanted = request if keeps_every_row else request.without_limit() with closing(preview_batches(self._upstreams[0], wanted)) as batches: @@ -2158,7 +2165,14 @@ def _preview_batches( if given_back is not None: # The result is that input as it is: no other input is read, as in the # full read. - yield from preview_batches(self._upstreams[given_back], request) + from orcapod.core.operators.meta_columns import without_input_meta + + # Without the input's meta columns, as the full read (static_process). + with closing( + preview_batches(self._upstreams[given_back], request) + ) as batches: + for batch in batches: + yield without_input_meta(batch, (batch,)) return refuse_without_compute_all(self, request, "needs every row of its input") result = pod.static_process( diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1d7450f5d..0343355c7 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -15,6 +15,7 @@ from orcapod.errors import SourceNameWarning, SourceVersionWarning from orcapod.core.streams.preview import ( PreviewRequest, + is_library_object, refuse_without_compute_all, slices_of, ) @@ -597,12 +598,16 @@ def _preview_batches( ) -> Generator[StreamProtocol, None, None]: """Slices of the rows a source holds (``preview_batches``). - A source of the library that holds its table (``_stream``) reads nothing. Any - other read of a whole source is refused unless ``compute_all`` was given. + A source of exactly a library class that holds its table (``_stream``) reads + nothing. Any other read of a whole source (a subclass of your own included, + N55) is refused unless ``compute_all`` was given. """ from orcapod.core.streams.arrow_table_stream import ArrowTableStream - if not isinstance(getattr(self, "_stream", None), ArrowTableStream): + if not ( + isinstance(getattr(self, "_stream", None), ArrowTableStream) + and is_library_object(self) + ): refuse_without_compute_all(self, request, "reads its rows whole") yield from slices_of(self, request) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 312355047..c6391f150 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -39,6 +39,7 @@ from orcapod.core.streams.preview import ( PreviewRequest, preview_batches, + is_library_object, refuse_without_compute_all, refused, slices_of, @@ -950,7 +951,7 @@ def _origin_read_keeping_nothing(origin: Any, *, read_by_this_class: bool) -> An if isinstance(origin, RootSource): holds_its_rows = isinstance( getattr(origin, "_stream", None), ArrowTableStream - ) and type(origin).__module__.startswith("orcapod.") + ) and is_library_object(origin) if holds_its_rows or reads_as_its_class(origin, SpiralDBTableSource): return origin elif read_by_this_class: diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 7b44b77c3..0810091de 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -15,7 +15,12 @@ StreamBase, check_head_size, ) -from orcapod.core.streams.preview import PreviewRequest, slices_of +from orcapod.core.streams.preview import ( + PreviewRequest, + is_library_object, + refuse_without_compute_all, + slices_of, +) from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol from orcapod.protocols.hashing_protocols import PipelineElementProtocol @@ -383,7 +388,15 @@ def head( def _preview_batches( self, request: PreviewRequest ) -> Generator[StreamProtocol, None, None]: - """Slices of the rows this stream holds (``preview_batches``).""" + """Slices of the rows this stream holds (``preview_batches``). + + A subclass of your own may compute its rows in ``as_table``: it is read in + full, only with ``compute_all`` (N55). + """ + if not is_library_object(self): + refuse_without_compute_all( + self, request, "is a subclass that reads its rows its own way" + ) yield from slices_of(self, request) def _typed_zero_row_table(self) -> "pa.Table": diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py index 9e21b49b1..a1d59d857 100644 --- a/src/orcapod/core/streams/preview.py +++ b/src/orcapod/core/streams/preview.py @@ -120,8 +120,9 @@ def exactly_its_class(obj: object, shortcut: str) -> bool: A preview shortcut or read-only path (an operator's ``input_given_back``, a pod's ``preview_data``, a data function's ``preview_call``) is written for one class of the library. It holds only for an object of exactly that class, with no member - replaced on the instance (``reads_as_its_class``): a subclass, however small, can - compute or act in a way the shortcut does not know (developer decision N55, + replaced on the instance (``reads_as_its_class``), and only when that class is the + library's: a subclass, however small, can compute or act in a way the shortcut + does not know, also when it writes the shortcut again (developer decision N55, review of PR 571). Args: @@ -134,7 +135,26 @@ def exactly_its_class(obj: object, shortcut: str) -> bool: from orcapod.core.streams.base import reads_as_its_class definer = next((c for c in type(obj).__mro__ if shortcut in vars(c)), None) - return definer is not None and reads_as_its_class(obj, definer) + return ( + definer is not None + and is_library_class(definer) + and reads_as_its_class(obj, definer) + ) + + +def is_library_class(cls: type) -> bool: + """Whether ``cls`` is a class of the library (defined in ``orcapod``), not one of + your own: a shortcut a subclass writes again is not the library's (N55).""" + return cls.__module__ == "orcapod" or cls.__module__.startswith("orcapod.") + + +def is_library_object(obj: object) -> bool: + """Whether ``obj`` is exactly a class of the library, with no member replaced on + the instance (``reads_as_its_class``): what the library wrote for that class holds + for it (N55).""" + from orcapod.core.streams.base import reads_as_its_class + + return is_library_class(type(obj)) and reads_as_its_class(obj, type(obj)) def refused(stream: Any, why: str) -> PreviewRefusedError: diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index 308122e01..edfe65061 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -40,6 +40,7 @@ def _rows(n: int = ROWS) -> pa.Table: + """The test table: ``n`` rows over three subjects, ``x`` null on every seventh.""" return pa.table( { "subject": [f"m{i * 3 // n}" for i in range(n)], @@ -124,6 +125,8 @@ def _with_time(source: Any) -> Any: def _same(left: pa.Table, right: pa.Table) -> None: + """Assert two tables are equal in values and in schema, Arrow metadata included + (field metadata carries logical types and data-tags).""" assert left.schema.equals(right.schema, check_metadata=True) assert left.equals(right) @@ -427,7 +430,7 @@ def test_no_hook_fires(source: Any) -> None: fired: list[Any] = [] calls = _Calls() pod = calls.pod - pod._post_run_hooks.append(fired.append) # pyright: ignore[reportPrivateUsage] # a registered hook + pod.add_post_run_hook(fired.append) _ = pod(_with_time(source)).preview(3) assert calls.seen == [0, 1, 2] assert fired == [] @@ -580,24 +583,43 @@ def derived() -> Any: ) -def test_a_repeated_key_across_batches_is_refused_when_reached(spiral: Any) -> None: - """A key repeated in a later batch raises when that row is reached, not before.""" - derived = DerivedSource( - spiral(), - tags_as_data={"timestamp": "time"}, - source_id="derived", - record_id_columns="subject", +def test_a_repeated_key_across_batches_is_refused_when_reached( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A key repeated in a later batch raises when that row is reached, not before. + + Each batch holds unique keys; only the third repeats one of the first: preview + succeeds through the first two batches (CodeRabbit, PR 571). + """ + monkeypatch.setattr(preview_module, "FIRST_BATCH_ROWS", 2) + keys = ["a", "b", "c", "d", "e", "f", "a", "g"] + origin = ArrowTableSource( + pa.table( + { + "key": keys, + "time": pa.array(range(len(keys)), pa.int64()), + "x": pa.array(range(len(keys)), pa.int64()), + } + ), + tag_columns=["key", "time"], + source_id="keys", + tag_only_columns=True, ) - assert len(derived.preview(1)) == 1 + + def derived() -> Any: + """Read in batches of 2, 4, 8: a filter above takes the limit away.""" + return DerivedSource( + origin, + tags_as_data={"time": "t"}, + source_id="derived", + record_id_columns="key", + ).filter(col("x") >= 0) + + assert derived().preview(6).table.column("key").to_pylist() == keys[:6] with pytest.raises(RowIdentifierError, match="unique"): - derived.preview(30) + derived().preview(7) with pytest.raises(RowIdentifierError, match="unique"): - DerivedSource( - spiral(), - tags_as_data={"timestamp": "time"}, - source_id="derived", - record_id_columns="subject", - ).as_table() + derived().as_table() def test_a_source_limit_and_where_hold(spiral: Any) -> None: @@ -890,6 +912,7 @@ def _nested_cached(calls: _Calls, stores: list[InMemoryArrowDatabase]) -> Any: def _untouched(store: InMemoryArrowDatabase) -> None: + """Assert nothing was written to ``store``: it holds no table.""" assert store.list_table_paths() == [] @@ -1364,3 +1387,225 @@ def test_a_derived_source_subclass_refuses_an_origin_of_your_own_class( assert origin.kept == [] assert origin._held_rows() is None # pyright: ignore[reportPrivateUsage] assert derived._held_rows() is None # pyright: ignore[reportPrivateUsage] + + +# --------------------------------------------------------------------------- +# CodeRabbit review of 8987839d +# --------------------------------------------------------------------------- + + +def test_a_cached_pod_over_a_pod_without_a_preview_is_refused(source: Any) -> None: + """An inner pod that is not a pod of the library is refused with + ``PreviewRefusedError``, not an ``AttributeError``.""" + calls = _Calls() + + class _Bare: + """A function pod by protocol only: it delegates all but the preview.""" + + def __init__(self, pod: Any) -> None: + self._pod = pod + + def __getattr__(self, name: str) -> Any: + if name in ("require_preview", "preview_data"): + raise AttributeError(name) + return getattr(self._pod, name) + + store = InMemoryArrowDatabase() + pod = CachedFunctionPod(_Bare(calls.pod), result_database=store) # pyright: ignore[reportArgumentType] # conforms at runtime + stream = pod.process(_with_time(source).select_data_columns(["timestamp", "x"])) + with pytest.raises(PreviewRefusedError, match="inner pod _Bare"): + stream.preview(2) + assert calls.seen == [] + _untouched(store) + + +def test_a_data_function_writing_its_own_preview_call_is_refused(source: Any) -> None: + """A subclass that writes ``preview_call`` again is not the library's class.""" + effects: list[Any] = [] + + class _OwnPreview(PythonDataFunction): + def preview_call(self, data: Any) -> Any: + self.require_preview() + effects.append(data) + return self.call(data) + + calls = _Calls() + inner: Any = calls.pod.data_function + function: Any = _OwnPreview(inner._function, output_keys="y") + stream = FunctionPod(function).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + with pytest.raises(PreviewRefusedError, match="no read-only call"): + stream.preview(2) + assert calls.seen == [] + assert effects == [] + + +def test_a_pod_writing_its_own_preview_data_is_refused(source: Any) -> None: + """A pod subclass that writes ``preview_data`` again is not the library's.""" + + class _OwnPreview(FunctionPod): + def preview_data(self, data: Any) -> Any: + return None + + calls = _Calls() + stream = _OwnPreview(calls.pod.data_function).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + with pytest.raises(PreviewRefusedError, match="subclass of a pod"): + stream.preview(2) + assert calls.seen == [] + + +def test_a_held_result_shows_no_meta_columns(source: Any) -> None: + """A held result of a cached function shows the columns a cold preview shows.""" + store = InMemoryArrowDatabase() + calls = _Calls() + + def stream() -> Any: + return _cached_function(calls, store).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + + cold = stream().preview(3).table + held = stream() + _ = held.as_table() + shown = held.preview(3).table + assert not any(name.startswith("__") for name in shown.column_names) + assert shown.column_names == cold.column_names + assert shown.column("y").to_pylist() == cold.column("y").to_pylist() + + +def test_a_held_empty_result_does_not_limit_the_input(source: Any) -> None: + """A held input that gave no row (the function was inactive then) uses a row of + the input without giving one: the limit is not pushed down.""" + calls = _Calls() + function: Any = calls.pod.data_function + function.set_active(False) + pod = calls.pod + pod.add_post_run_hook(lambda *_: function.set_active(True)) + stream = pod(_with_time(source).select_data_columns(["timestamp", "x"])) + rows = iter(stream) + _ = next(rows) + shown = stream.preview(2).as_table() + _same(shown, stream.as_table().select(shown.column_names)[:2]) + + +class _BatchDeclaringMapData(MapData): + """A MapData of your own that declares batches and drops each batch's first row.""" + + BATCHES_GIVE_THE_WHOLE = True + + def unary_static_process(self, stream: Any) -> Any: + result = super().unary_static_process(stream) + table = result.as_table(columns={"source": True, "system_tags": True}) + return ArrowTableStream( + table.slice(1), + tag_columns=result.keys()[0], + data_context=result.data_context_key, + ) + + +def test_an_operator_of_your_own_declaring_batches_is_computed_in_full( + source: Any, +) -> None: + """The batch shortcut is the library's: an operator of your own that declares it + is computed in full by preview, only with compute_all.""" + + def stream() -> Any: + return _BatchDeclaringMapData({"note": "text"})(source()) + + whole = stream().as_table() + with pytest.raises(PreviewRefusedError, match="compute_all"): + stream().preview(2) + _same(stream().preview(2, compute_all=True).as_table(), whole[:2]) + + +def test_a_semi_join_given_back_input_shows_no_meta_columns() -> None: + """A left input with a meta column, given back by a SemiJoin with no shared tag: + the preview has the columns of the full read.""" + left = ArrowTableStream( + pa.table( + { + "k": ["a", "b", "c"], + "x": pa.array([1, 2, 3], pa.int64()), + "__debug": ["d1", "d2", "d3"], + } + ), + tag_columns=["k"], + ) + joined = SemiJoin()(left, _unrelated()) + shown = joined.preview(2).as_table() + _same(shown, joined.as_table()[:2]) + assert "__debug" not in shown.column_names + + +def test_a_source_subclass_is_read_in_full_only_with_compute_all( + spiral: Any, +) -> None: + """A SpiralDB source of your own reads its whole table: only with compute_all.""" + + class _Mine(SpiralDBTableSource): + pass + + mine = _Mine(_PROJECT, "event", tag_only_columns=True) + with pytest.raises(PreviewRefusedError, match="compute_all"): + mine.preview(1) + _same(mine.preview(2, compute_all=True).as_table(), mine.as_table()[:2]) + + +def test_a_derived_source_subclass_refuses_an_origin_read_replaced_on_it( + source: Any, +) -> None: + """An origin of a library class whose ``as_table`` is replaced on the instance + (it keeps what it reads) is refused, not read.""" + origin = source() + kept: list[Any] = [] + read = origin.as_table + + def keeping(*args: Any, **kwargs: Any) -> Any: + table = read(*args, **kwargs) + kept.append(table) + return table + + origin.as_table = keeping + derived = _DroppingDerived(origin, tags_as_data={"timestamp": "t"}, source_id="d") + with pytest.raises(PreviewRefusedError): + derived.preview(2, compute_all=True) + assert kept == [] + + +def test_a_stream_subclass_is_read_in_full_only_with_compute_all() -> None: + """A raw stream of your own may compute its rows in ``as_table``.""" + + class _Dropping(ArrowTableStream): + def as_table(self, *args: Any, **kwargs: Any) -> Any: + return super().as_table(*args, **kwargs).slice(1) + + stream = _Dropping(_rows(), tag_columns=["subject", "timestamp"]) + with pytest.raises(PreviewRefusedError, match="compute_all"): + stream.preview(2) + _same(stream.preview(2, compute_all=True).as_table(), stream.as_table()[:2]) + + +@pytest.mark.parametrize( + "mapping", + [ + {"note": "text", "x": "value"}, + {"x": "value", "note": "text"}, + ], + ids=["note_first", "x_first"], +) +def test_a_mapping_of_several_entries_is_previewed_as_read( + source: Any, mapping: dict[str, str] +) -> None: + """Several mapping entries, in two orders, on data and on tags (with data-tags): + the preview is the first rows of the sync read. ``preview`` is sync only.""" + tags = {"subject": "who", "timestamp": "t"} + for stream in ( + source().map_data(mapping), + source(tag_only_columns=False).map_tags(tags), + source().map_tags(dict(reversed(list(tags.items())))), + ): + for n in (1, 5, 41): + _same(stream.preview(n).as_table(), stream.as_table()[:n]) From 38d935c5fd82468e698313389e5801f0e87ee0eb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 11:28:47 -0800 Subject: [PATCH 11/11] fix(streams): every preview gate is one exact-set test (ITL-1464) Verification of 48f8533e: the gates tested which class defines a method, or a module name, not N55's rule. Every preview shortcut and read-only path now tests is_exact_library_instance(x, classes): type(x) in an explicit frozenset of the library classes the path was written for, nothing replaced on the instance. Anything else takes the general path or is refused. - Data functions: data_function_preview walks every layer (wrapper, cache, bound proxy) and checks each against PREVIEWABLE_DATA_FUNCTIONS before any of its methods is called: a subclass overriding require_preview and preview_call runs neither, and a function written to an older protocol is refused with PreviewRefusedError, not AttributeError. - Pods: the stream checks the pod against previewable_pods() before calling its require_preview; a cached pod checks its inner pod the same way. - Operators: the batch shortcut and SemiJoin's given-back input use explicit sets; a class named into the orcapod namespace is not admitted. - Sources: each library source that holds its table slices it for exactly its own class (held_table_batches); RootSource's default is the general path; HELD_LIBRARY_SOURCES is one explicit set for the DerivedSource origin rule. - A whole input computed by preview keeps its producer, so an operator reads it as the full read gives it. - Held results of the first inputs are shown before the input is opened, and the input is not opened at all when every input's result is held. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/cached_function_pod.py | 6 +- src/orcapod/core/data_function.py | 44 ++-- src/orcapod/core/data_function_preview.py | 54 +++++ src/orcapod/core/data_function_proxy.py | 9 +- src/orcapod/core/function_pod.py | 94 ++++++--- .../core/operators/static_output_pod.py | 58 +++++- .../core/sources/arrow_table_source.py | 11 + src/orcapod/core/sources/base.py | 36 ++-- src/orcapod/core/sources/csv_source.py | 11 + src/orcapod/core/sources/data_frame_source.py | 11 + src/orcapod/core/sources/db_table_source.py | 11 + .../core/sources/delta_table_source.py | 11 + src/orcapod/core/sources/derived_source.py | 15 +- src/orcapod/core/sources/dict_source.py | 11 + src/orcapod/core/sources/held_sources.py | 33 +++ src/orcapod/core/sources/list_source.py | 11 + .../core/sources/postgresql_table_source.py | 11 + .../core/sources/spiraldb_table_source.py | 8 +- .../core/sources/sqlite_table_source.py | 11 + .../core/streams/arrow_table_stream.py | 17 +- src/orcapod/core/streams/preview.py | 46 ++-- tests/test_core/streams/test_preview.py | 197 +++++++++++++++++- 22 files changed, 598 insertions(+), 118 deletions(-) create mode 100644 src/orcapod/core/data_function_preview.py create mode 100644 src/orcapod/core/sources/held_sources.py diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 287283ac4..646d76a3a 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -15,8 +15,10 @@ FunctionPodStream, WrappedFunctionPod, function_zero_row_table, + previewable_pods, ) from orcapod.core.streams.view import StreamView +from orcapod.core.streams.preview import is_exact_library_instance from orcapod.errors import PreviewRefusedError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema @@ -319,7 +321,9 @@ def _inner_for_preview(self) -> _FunctionPodBase: PreviewRefusedError: If it is not a pod of the library. """ inner: object = self._function_pod - if not isinstance(inner, _FunctionPodBase): + if not isinstance(inner, _FunctionPodBase) or not is_exact_library_instance( + inner, previewable_pods() + ): raise PreviewRefusedError( f"its inner pod {type(inner).__name__} has no preview" ) diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 3de1511d4..6d5c4e903 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1,5 +1,6 @@ from __future__ import annotations + import inspect import io import logging @@ -28,7 +29,6 @@ hash_default_value, ) from orcapod.core.result_cache import ResultCache -from orcapod.core.streams.preview import exactly_its_class from orcapod.errors import ( NoOutputsDeclaredError, PreviewRefusedError, @@ -423,22 +423,19 @@ async def direct_async_call( # ==================== Preview ==================== def require_preview(self) -> None: - """Refuse a preview unless this function's ``preview_call`` is read-only. + """Refuse a preview: this kind of data function has no read-only call. - A kind with a read-only call (``PythonDataFunction``, ``DataFunctionWrapper``, - ``CachedDataFunction``, a bound ``DataFunctionProxy``) has it for an object of - exactly that class (``exactly_its_class``): a subclass is refused, since what it - does when called (an output builder, a store) is not known (review of PR 571). - Any other kind has none. + Only the library's kinds with one (``data_function_preview``) answer otherwise; + a caller checks that every layer is exactly one of them + (``require_previewable_function``) before it calls this or ``preview_call``, + so a subclass's own methods are never called (N55). Raises: - PreviewRefusedError: If this function has no read-only call. + PreviewRefusedError: Always, for a kind with no read-only call. """ - definer = next(c for c in type(self).__mro__ if "preview_call" in vars(c)) - if definer is DataFunctionBase or not exactly_its_class(self, "preview_call"): - raise PreviewRefusedError( - f"its data function {type(self).__name__} has no read-only call" - ) + raise PreviewRefusedError( + f"its data function {type(self).__name__} has no read-only call" + ) def preview_call(self, data: DataProtocol) -> DataProtocol | None: """Refused: this kind of data function has no read-only call. @@ -1338,14 +1335,12 @@ def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": version=inner.get("version", "v0.0"), ) - def preview_call(self, data: DataProtocol) -> DataProtocol | None: - """Call the function (``DataFunctionProtocol.preview_call``): it stores nothing. + def require_preview(self) -> None: + """Nothing refused: calling the function stores nothing + (``DataFunctionProtocol.require_preview``).""" - Raises: - PreviewRefusedError: If a subclass computes in its own way - (``require_preview``). - """ - self.require_preview() + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """Call the function (``DataFunctionProtocol.preview_call``): it stores nothing.""" return self.call(data) @@ -1502,9 +1497,14 @@ async def direct_async_call( ) -> DataProtocol | None: return await self._data_function.direct_async_call(data, **kwargs) + @property + def wrapped(self) -> DataFunctionProtocol: + """The data function this wrapper wraps.""" + return self._data_function + def require_preview(self) -> None: - """This wrapper's answer, then the wrapped function's (``DataFunctionBase``).""" - super().require_preview() + """The wrapped function's answer: a wrapper adds nothing to a call that a + preview cannot do (``CachedDataFunction`` reads its store and writes none).""" self._data_function.require_preview() def preview_call(self, data: DataProtocol) -> DataProtocol | None: diff --git a/src/orcapod/core/data_function_preview.py b/src/orcapod/core/data_function_preview.py new file mode 100644 index 000000000..bb47ad2d0 --- /dev/null +++ b/src/orcapod/core/data_function_preview.py @@ -0,0 +1,54 @@ +"""Which data functions a preview may call, read-only, at every layer (ITL-1464). + +A preview calls a data function through ``require_preview`` and ``preview_call``. Those +are the library's own only for an instance of exactly one of the library's classes +that have a read-only call (developer decision N55), so every layer of a function is +checked to be one, before any of its methods is called. +""" + +from __future__ import annotations + +from orcapod.core.data_function import ( + CachedDataFunction, + DataFunctionWrapper, + PythonDataFunction, +) +from orcapod.core.data_function_proxy import DataFunctionProxy +from orcapod.core.streams.preview import is_exact_library_instance +from orcapod.errors import PreviewRefusedError + +PREVIEWABLE_DATA_FUNCTIONS: frozenset[type] = frozenset( + {PythonDataFunction, DataFunctionWrapper, CachedDataFunction, DataFunctionProxy} +) +"""The library's data function classes with a read-only call: a ``CachedDataFunction`` +reads its store and writes none; the others call what they wrap or bind.""" + + +def require_previewable_function(function: object) -> None: + """Refuse a data function any layer of which is not exactly one of + ``PREVIEWABLE_DATA_FUNCTIONS``. + + The layers are walked from the outermost in: what a wrapper wraps, what a proxy has + bound (an unbound proxy raises when it is called, as ``call`` does). No method of a + layer is called before the layer is checked, so a subclass's own ``require_preview`` + or ``preview_call`` never runs, and a function that has none (written to an older + protocol) is refused, not called. + + Args: + function: The pod's data function. + + Raises: + PreviewRefusedError: If a layer is not one of the library's previewable classes. + """ + layer: object | None = function + while layer is not None: + if not is_exact_library_instance(layer, PREVIEWABLE_DATA_FUNCTIONS): + raise PreviewRefusedError( + f"its data function {type(layer).__name__} has no read-only call" + ) + if isinstance(layer, DataFunctionProxy): + layer = layer.bound_function + elif isinstance(layer, DataFunctionWrapper): + layer = layer.wrapped + else: + layer = None diff --git a/src/orcapod/core/data_function_proxy.py b/src/orcapod/core/data_function_proxy.py index 690861cc5..00e8e05b3 100644 --- a/src/orcapod/core/data_function_proxy.py +++ b/src/orcapod/core/data_function_proxy.py @@ -180,13 +180,16 @@ def require_preview(self) -> None: ``DataFunctionUnavailableError``, as ``call`` does. Raises: - PreviewRefusedError: If this is a subclass, or the bound function has no - read-only call. + PreviewRefusedError: If the bound function has no read-only call. """ - super().require_preview() if self._bound_function is not None: self._bound_function.require_preview() + @property + def bound_function(self) -> DataFunctionProtocol | None: + """The function bound to this proxy, or ``None``.""" + return self._bound_function + def preview_call(self, data: DataProtocol) -> DataProtocol | None: """The bound function's ``preview_call``; unbound, raises as ``call`` does. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 2e704651f..f8367b6e4 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1,5 +1,7 @@ from __future__ import annotations +import functools + import asyncio import itertools import dataclasses @@ -24,6 +26,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.data_function_preview import require_previewable_function from orcapod.core.datagrams import Data from orcapod.core.data_tags import ( materialization_diagnostic_off, @@ -43,7 +46,7 @@ preview_batches, refused, slices_of, - exactly_its_class, + is_exact_library_instance, ) from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -409,18 +412,9 @@ def require_preview(self) -> None: raise PreviewRefusedError(f"{type(self).__name__} has no preview") def _require_own_processing(self) -> None: - """Refuse a pod that is not exactly the class its ``preview_data`` was written - for: a subclass may compute, look up or act in a way the preview does not know - (``exactly_its_class``; review of PR 571). - - Raises: - PreviewRefusedError: If so. - """ - if not exactly_its_class(self, "preview_data"): - raise PreviewRefusedError( - f"{type(self).__name__} is a subclass of a pod of the library: " - "its preview is not known" - ) + """Refuse a pod that is not exactly one of the library's previewable pods + (``require_previewable_pod``).""" + require_previewable_pod(self) async def async_process_data( self, @@ -1009,6 +1003,7 @@ def require_preview(self) -> None: raise PreviewRefusedError( "its function takes the invocation context: it performs an action" ) + require_previewable_function(self.data_function) self.data_function.require_preview() def preview_data(self, data: DataProtocol) -> DataProtocol | None: @@ -1846,6 +1841,9 @@ def _preview_batches( """ pod = self._pod_base() try: + # The pod's kind first: none of its methods is called unless it is exactly + # a library pod. + require_previewable_pod(pod) pod.require_preview() except PreviewRefusedError as error: raise refused(self, f"cannot be previewed: {error}") from error @@ -1868,18 +1866,38 @@ def _preview_batches( ) wanted = request if one_per_row else request.without_limit() given = False - index = 0 - with closing(preview_batches(self._input_stream, wanted)) as batches: - for batch in batches: - for tag, data in batch.iter_data(): - if index in known: - tag, output = known[index] - else: - output = pod.preview_data(data) - index += 1 - if output is not None: - given = True - yield self._preview_batch([(tag, output)]) + # The held results of the first inputs come first: the input is opened only + # when more rows are asked for than they give, and not at all when every + # input's result is held (an iteration ran to the end). + held = 0 + while held in known: + tag, output = known[held] + held += 1 + if output is not None: + given = True + yield self._preview_batch([(tag, output)]) + every_input_held = ( + current + and not self._needs_iterator + and not self._input_interrupted + and self._cached_input_iterator is None + ) + if not every_input_held: + index = 0 + with closing(preview_batches(self._input_stream, wanted)) as batches: + for batch in batches: + for tag, data in batch.iter_data(): + if index < held: + index += 1 + continue + if index in known: + tag, output = known[index] + else: + output = pod.preview_data(data) + index += 1 + if output is not None: + given = True + yield self._preview_batch([(tag, output)]) if not given: yield self._preview_batch([]) @@ -2274,6 +2292,7 @@ def with_fall_through( def require_preview(self) -> None: """See ``_FunctionPodBase.require_preview``.""" self._require_own_processing() + require_previewable_pod(self._plain_pod) self._plain_pod.require_preview() def preview_data(self, data: DataProtocol) -> DataProtocol | None: @@ -2528,3 +2547,28 @@ def decorator(func: Callable) -> FunctionPod: if fn is not None: return decorator(fn) return decorator + + +@functools.cache +def previewable_pods() -> frozenset[type]: + """The library's function pod classes with a preview (``preview_data``), written + for exactly these classes (N55).""" + from orcapod.core.cached_function_pod import CachedFunctionPod + + return frozenset({FunctionPod, FallThroughPod, CachedFunctionPod}) + + +def require_previewable_pod(pod: object) -> None: + """Refuse a pod that is not exactly one of ``previewable_pods``. + + Checked before any of the pod's preview methods is called, so none is ever a + subclass's own. + + Raises: + PreviewRefusedError: If so. + """ + if not is_exact_library_instance(pod, previewable_pods()): + raise PreviewRefusedError( + f"{type(pod).__name__} is not a pod of the library: its preview is not " + "known" + ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index fe9489aaa..2da882dfa 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1,5 +1,7 @@ from __future__ import annotations +import functools + import asyncio import dataclasses import logging @@ -61,8 +63,7 @@ PREVIEW_COLUMNS, PreviewRequest, preview_batches, - exactly_its_class, - is_library_class, + is_exact_library_instance, refuse_without_compute_all, ) from orcapod.core.streams.view import ( @@ -1783,6 +1784,8 @@ class _RowsOfStream(ArrowTableStream): pipeline_hash: The pipeline hash of the stream the rows came from. upstreams: The upstreams of the stream the rows came from, if any. data_context: The rows' data context; ``None`` for the default. + producer: The producer of the stream the rows came from, if any (a preview's + whole input, which an operator may read as the full read gives it). """ def __init__( @@ -1794,11 +1797,13 @@ def __init__( data_tags: Collection[str] = (), upstreams: tuple[StreamProtocol, ...] = (), data_context: DataContext | None = None, + producer: PodProtocol | None = None, ) -> None: super().__init__( table, tag_columns=tag_columns, data_tags=data_tags, + producer=producer, upstreams=upstreams, data_context=data_context, ) @@ -2149,7 +2154,7 @@ def _preview_batches( if ( len(self._upstreams) == 1 and applied_by_batch(pod) - and is_library_class(type(pod)) + and is_exact_library_instance(pod, library_batch_operators()) ): keeps_every_row = pod.rows_dropped_text(0, (), self._upstreams) is None wanted = request if keeps_every_row else request.without_limit() @@ -2159,7 +2164,7 @@ def _preview_batches( return given_back = ( pod.input_given_back(self._upstreams) - if exactly_its_class(pod, "input_given_back") + if is_exact_library_instance(pod, operators_giving_back_an_input()) else None ) if given_back is not None: @@ -2193,6 +2198,8 @@ def _whole_input( rows.as_table(columns=PREVIEW_COLUMNS), tag_columns=rows.keys()[0], pipeline_hash=upstream.pipeline_hash(), + # The upstream as the full read gives it to the operator: its producer too. + producer=upstream.producer, data_tags=stream_data_tags(rows), upstreams=upstream.upstreams, data_context=StaticOutputOperatorPod._upstream_context(upstream), # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context @@ -2356,6 +2363,49 @@ def __repr__(self) -> str: ) +@functools.cache +def library_batch_operators() -> frozenset[type]: + """The library's operators a preview applies batch by batch: each declares + ``BATCHES_GIVE_THE_WHOLE`` for exactly its own class (N55).""" + from orcapod.core.operators.add_tags import AddTags + from orcapod.core.operators.column_selection import ( + DropColumns, + DropDataColumns, + DropTagColumns, + SelectColumns, + SelectDataColumns, + SelectTagColumns, + ) + from orcapod.core.operators.drop_nulls import DropNulls + from orcapod.core.operators.filter import Filter + from orcapod.core.operators.mappers import MapColumns, MapData, MapTags + + return frozenset( + { + AddTags, + DropColumns, + DropDataColumns, + DropTagColumns, + DropNulls, + Filter, + MapColumns, + MapData, + MapTags, + SelectColumns, + SelectDataColumns, + SelectTagColumns, + } + ) + + +@functools.cache +def operators_giving_back_an_input() -> frozenset[type]: + """The library's operators whose ``input_given_back`` a preview follows (N55).""" + from orcapod.core.operators.semijoin import SemiJoin + + return frozenset({SemiJoin}) + + def applied_by_batch(pod: object) -> bool: """Whether an operator may be applied batch by batch (``run()``, ``preview()``). diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f05485472..f9a51d0d5 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -1,5 +1,10 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + import logging from collections.abc import Collection from typing import TYPE_CHECKING, Any, ClassVar @@ -171,3 +176,9 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> ArrowTableSour def table(self) -> "pa.Table": """Return the enriched table (with source-info and system tags).""" return self._stream.as_table(columns={"source": True, "system_tags": True}) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, ArrowTableSource, request) diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 0343355c7..e858c7181 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,5 +1,6 @@ from __future__ import annotations + import warnings from collections.abc import Callable, Generator from typing import TYPE_CHECKING, Any, ClassVar, TypeVar @@ -15,7 +16,7 @@ from orcapod.errors import SourceNameWarning, SourceVersionWarning from orcapod.core.streams.preview import ( PreviewRequest, - is_library_object, + is_exact_library_instance, refuse_without_compute_all, slices_of, ) @@ -596,19 +597,11 @@ def _display_name(self) -> str: def _preview_batches( self, request: PreviewRequest ) -> Generator[StreamProtocol, None, None]: - """Slices of the rows a source holds (``preview_batches``). - - A source of exactly a library class that holds its table (``_stream``) reads - nothing. Any other read of a whole source (a subclass of your own included, - N55) is refused unless ``compute_all`` was given. + """A source's whole read, sliced (``preview_batches``): the general path, + only with ``compute_all``. A library source that holds its table slices it + without asking, for exactly its own class (``held_table_batches``; N55). """ - from orcapod.core.streams.arrow_table_stream import ArrowTableStream - - if not ( - isinstance(getattr(self, "_stream", None), ArrowTableStream) - and is_library_object(self) - ): - refuse_without_compute_all(self, request, "reads its rows whole") + refuse_without_compute_all(self, request, "reads its rows whole") yield from slices_of(self, request) def head( @@ -661,3 +654,20 @@ def cached( cache_path_prefix=cache_path_prefix, **kwargs, ) + + +def held_table_batches( + source: RootSource, own_class: type, request: PreviewRequest +) -> Generator[StreamProtocol, None, None]: + """The preview of a library source that holds its whole table once built: slices + of it, which computes and keeps nothing, for exactly ``own_class`` (N55); a + subclass of it takes the general path (``RootSource._preview_batches``). + + Args: + source: The source. + own_class: The library class the source's override was written for. + request: What is asked of it. + """ + if not is_exact_library_instance(source, frozenset({own_class})): + refuse_without_compute_all(source, request, "reads its rows whole") + yield from slices_of(source, request) diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index f39681d9e..14120b12e 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -1,5 +1,10 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + import functools import math import os @@ -511,3 +516,9 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> CSVSource: schema=cls.saved_schema(config), ), ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, CSVSource, request) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6c65bf64d..675950dbc 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -1,5 +1,10 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + import logging from collections.abc import Collection from typing import TYPE_CHECKING, Any, ClassVar @@ -136,3 +141,9 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> DataFrameSourc "DataFrameSource cannot be reconstructed from config — " "the original DataFrame is not serializable." ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, DataFrameSource, request) diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 86ea349d5..7af641fe9 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -14,6 +14,11 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + from collections.abc import Collection, Iterator from contextlib import contextmanager from typing import Any, ClassVar, TYPE_CHECKING @@ -333,3 +338,9 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> DBTableSource: "DBTableSource.from_config requires a registered connector factory. " "Implement build_db_connector_from_config in PLT-1074/1075/1076." ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, DBTableSource, request) diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..9895efa51 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -1,5 +1,10 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + import os from collections.abc import Collection @@ -196,3 +201,9 @@ def from_config( source_id=name, ), ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, DeltaTableSource, request) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index c6391f150..5bb21bf1a 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -17,6 +17,7 @@ from typing_extensions import override from orcapod.core.sources.base import RootSource +from orcapod.core.sources.held_sources import HELD_LIBRARY_SOURCES from orcapod.core.sources.provisional import warn_provisional_source from orcapod.core.sources.reload import same_rows from orcapod.core.sources.source_ids import hash_source_name @@ -33,13 +34,12 @@ check_head_size, schema_requires_io, typed_arrow_schemas, - reads_as_its_class, typed_zero_row_table, ) from orcapod.core.streams.preview import ( PreviewRequest, preview_batches, - is_library_object, + is_exact_library_instance, refuse_without_compute_all, refused, slices_of, @@ -856,7 +856,7 @@ def _preview_batches( full, then the first rows. """ self._note_provisional_identity_use() - if not reads_as_its_class(self, DerivedSource): + if not is_exact_library_instance(self, frozenset({DerivedSource})): yield from self._preview_of_its_read(request) return if self._tags_as_data is not None and self._cached_stream is not None: @@ -933,7 +933,7 @@ def _origin_read_keeping_nothing(origin: Any, *, read_by_this_class: bool) -> An """ from orcapod.core.sources.spiraldb_table_source import SpiralDBTableSource - if reads_as_its_class(origin, DerivedSource): + if is_exact_library_instance(origin, frozenset({DerivedSource})): # Exactly this class: its state is known, so a copy keeps what it reads. twin = copy.copy(origin) twin._origin = _origin_read_keeping_nothing( # pyright: ignore[reportPrivateUsage] # the copy's own origin @@ -949,10 +949,9 @@ def _origin_read_keeping_nothing(origin: Any, *, read_by_this_class: bool) -> An "read it in full, and it may keep what is read", ) if isinstance(origin, RootSource): - holds_its_rows = isinstance( - getattr(origin, "_stream", None), ArrowTableStream - ) and is_library_object(origin) - if holds_its_rows or reads_as_its_class(origin, SpiralDBTableSource): + if is_exact_library_instance( + origin, HELD_LIBRARY_SOURCES | {SpiralDBTableSource} + ): return origin elif read_by_this_class: return origin diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index fdf7c1f34..3edb25d88 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -1,5 +1,10 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + from collections.abc import Collection, Mapping from typing import Any, ClassVar @@ -124,3 +129,9 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> DictSource: "DictSource cannot be reconstructed from config — " "original data is not serializable." ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, DictSource, request) diff --git a/src/orcapod/core/sources/held_sources.py b/src/orcapod/core/sources/held_sources.py new file mode 100644 index 000000000..f9360739b --- /dev/null +++ b/src/orcapod/core/sources/held_sources.py @@ -0,0 +1,33 @@ +"""The library's sources that hold their whole table once built (ITL-1464). + +Reading such a source's rows computes and keeps nothing, so a preview, or the full +read of a ``DerivedSource`` subclass over it, may read it as it is: for exactly these +classes only (developer decision N55). +""" + +from __future__ import annotations + +from orcapod.core.sources.arrow_table_source import ArrowTableSource +from orcapod.core.sources.csv_source import CSVSource +from orcapod.core.sources.data_frame_source import DataFrameSource +from orcapod.core.sources.db_table_source import DBTableSource +from orcapod.core.sources.delta_table_source import DeltaTableSource +from orcapod.core.sources.dict_source import DictSource +from orcapod.core.sources.list_source import ListSource +from orcapod.core.sources.postgresql_table_source import PostgreSQLTableSource +from orcapod.core.sources.sqlite_table_source import SQLiteTableSource + +HELD_LIBRARY_SOURCES: frozenset[type] = frozenset( + { + ArrowTableSource, + CSVSource, + DataFrameSource, + DBTableSource, + DeltaTableSource, + DictSource, + ListSource, + PostgreSQLTableSource, + SQLiteTableSource, + } +) +"""Every library source class that holds its table (``_stream``) once built.""" diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..75ccbd553 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -1,5 +1,10 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + from collections.abc import Callable, Collection from typing import TYPE_CHECKING, Any, ClassVar @@ -156,3 +161,9 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> "ListSource": "ListSource cannot be reconstructed from config — " "original list data is not serializable." ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, ListSource, request) diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 58acc1f17..cb134f683 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -12,6 +12,11 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + import ipaddress import re from collections.abc import Collection, Iterator @@ -307,3 +312,9 @@ def from_config( data_context=config.get("data_context"), ), ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, PostgreSQLTableSource, request) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dc31962b3..645a588c2 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -63,8 +63,8 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import check_head_size, reads_as_its_class -from orcapod.core.streams.preview import PreviewRequest +from orcapod.core.streams.base import check_head_size +from orcapod.core.streams.preview import PreviewRequest, is_exact_library_instance from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -1130,7 +1130,7 @@ def head( @override def _reads_in_batches(self) -> bool: - return reads_as_its_class(self, SpiralDBTableSource) + return is_exact_library_instance(self, frozenset({SpiralDBTableSource})) @override def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: @@ -1144,7 +1144,7 @@ def _preview_batches( ) -> Generator[StreamProtocol, None, None]: """One scan, limited by SpiralDB when the rows wanted are known, else closed when enough were read. ``max_rows`` holds only when every row is asked for.""" - if not reads_as_its_class(self, SpiralDBTableSource): + if not is_exact_library_instance(self, frozenset({SpiralDBTableSource})): yield from super()._preview_batches(request) return limits = [n for n in (self._limit, request.limit) if n is not None] diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eab59a821..e7f9e7295 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -23,6 +23,11 @@ from __future__ import annotations +from collections.abc import Generator +from orcapod.core.sources.base import held_table_batches +from orcapod.core.streams.preview import PreviewRequest +from orcapod.protocols.core_protocols import StreamProtocol + import os from collections.abc import Collection, Iterator from contextlib import contextmanager @@ -252,3 +257,9 @@ def from_config( data_context=config.get("data_context"), ), ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the table it holds, for exactly this class (``held_table_batches``).""" + yield from held_table_batches(self, SQLiteTableSource, request) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 0810091de..53902a1d9 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -1,5 +1,7 @@ from __future__ import annotations +import functools + import itertools import logging from collections.abc import Collection, Generator, Iterator @@ -17,7 +19,7 @@ ) from orcapod.core.streams.preview import ( PreviewRequest, - is_library_object, + is_exact_library_instance, refuse_without_compute_all, slices_of, ) @@ -393,7 +395,7 @@ def _preview_batches( A subclass of your own may compute its rows in ``as_table``: it is read in full, only with ``compute_all`` (N55). """ - if not is_library_object(self): + if not is_exact_library_instance(self, previewable_streams()): refuse_without_compute_all( self, request, "is a subclass that reads its rows its own way" ) @@ -516,3 +518,14 @@ def __repr__(self) -> str: f"{self.__class__.__name__}(table={self._table.column_names}, " f"tag_columns={self._tag_columns}{refs})" ) + + +@functools.cache +def previewable_streams() -> frozenset[type]: + """The library's raw stream classes whose ``as_table`` computes nothing: a preview + slices their rows (N55).""" + from orcapod.core.operators.static_output_pod import ( + _RowsOfStream, # pyright: ignore[reportPrivateUsage] # the library's stand-in + ) + + return frozenset({ArrowTableStream, _RowsOfStream}) diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py index a1d59d857..c9d16f2e9 100644 --- a/src/orcapod/core/streams/preview.py +++ b/src/orcapod/core/streams/preview.py @@ -114,47 +114,27 @@ def slices_of( return -def exactly_its_class(obj: object, shortcut: str) -> bool: - """Whether ``obj`` is exactly the library class its ``shortcut`` was written for. +def is_exact_library_instance(obj: object, classes: frozenset[type]) -> bool: + """Whether ``obj`` is an instance of exactly one of ``classes``, the library + classes a preview path was written for (developer decision N55). - A preview shortcut or read-only path (an operator's ``input_given_back``, a pod's - ``preview_data``, a data function's ``preview_call``) is written for one class of - the library. It holds only for an object of exactly that class, with no member - replaced on the instance (``reads_as_its_class``), and only when that class is the - library's: a subclass, however small, can compute or act in a way the shortcut - does not know, also when it writes the shortcut again (developer decision N55, - review of PR 571). + The one test of every preview shortcut and read-only path: ``type(obj)`` must be in + the explicit set, never a subclass, never decided by a module name or by which + class defines a method. Nothing of the class may be replaced on the instance + (``reads_as_its_class``: an ``as_table`` or ``static_process`` assigned to the + object). Anything else takes the general path or is refused. Args: - obj: The operator, pod or data function. - shortcut: The name of the shortcut method. + obj: The operator, pod, data function, source or stream. + classes: The library classes the path was written for. Returns: - Whether the shortcut may be taken for ``obj``. + Whether the path may be taken for ``obj``. """ from orcapod.core.streams.base import reads_as_its_class - definer = next((c for c in type(obj).__mro__ if shortcut in vars(c)), None) - return ( - definer is not None - and is_library_class(definer) - and reads_as_its_class(obj, definer) - ) - - -def is_library_class(cls: type) -> bool: - """Whether ``cls`` is a class of the library (defined in ``orcapod``), not one of - your own: a shortcut a subclass writes again is not the library's (N55).""" - return cls.__module__ == "orcapod" or cls.__module__.startswith("orcapod.") - - -def is_library_object(obj: object) -> bool: - """Whether ``obj`` is exactly a class of the library, with no member replaced on - the instance (``reads_as_its_class``): what the library wrote for that class holds - for it (N55).""" - from orcapod.core.streams.base import reads_as_its_class - - return is_library_class(type(obj)) and reads_as_its_class(obj, type(obj)) + cls = type(obj) + return cls in classes and reads_as_its_class(obj, cls) def refused(stream: Any, why: str) -> PreviewRefusedError: diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py index edfe65061..73854f2b1 100644 --- a/tests/test_core/streams/test_preview.py +++ b/tests/test_core/streams/test_preview.py @@ -1117,7 +1117,7 @@ def test_a_pod_subclass_with_its_own_processing_is_refused( pod = _FilteringCachedPod(calls.pod, result_database=store) stream = pod.process(_with_time(source).select_data_columns(["timestamp", "x"])) for compute_all in (False, True): - with pytest.raises(PreviewRefusedError, match="subclass of a pod"): + with pytest.raises(PreviewRefusedError, match="not a pod of the library"): stream.preview(2, compute_all=compute_all) assert calls.seen == [] _untouched(store) @@ -1169,7 +1169,7 @@ def lookup_cached_data(self, data: Any) -> Any: stream = _Synthetic(calls.pod, result_database=store).process( _with_time(source).select_data_columns(["timestamp", "x"]) ) - with pytest.raises(PreviewRefusedError, match="subclass of a pod"): + with pytest.raises(PreviewRefusedError, match="not a pod of the library"): stream.preview(2) assert calls.seen == [] _untouched(store) @@ -1452,7 +1452,7 @@ def preview_data(self, data: Any) -> Any: stream = _OwnPreview(calls.pod.data_function).process( _with_time(source).select_data_columns(["timestamp", "x"]) ) - with pytest.raises(PreviewRefusedError, match="subclass of a pod"): + with pytest.raises(PreviewRefusedError, match="not a pod of the library"): stream.preview(2) assert calls.seen == [] @@ -1609,3 +1609,194 @@ def test_a_mapping_of_several_entries_is_previewed_as_read( ): for n in (1, 5, 41): _same(stream.preview(n).as_table(), stream.as_table()[:n]) + + +# --------------------------------------------------------------------------- +# Verification of 48f8533e: one exact-set gate (N55) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("wrapped", [False, True]) +def test_a_data_function_overriding_both_preview_methods_is_refused( + source: Any, wrapped: bool +) -> None: + """A subclass writing ``require_preview`` and ``preview_call`` both: neither runs, + plain or beneath a cached layer.""" + effects: list[Any] = [] + + class _Both(PythonDataFunction): + def require_preview(self) -> None: + effects.append("checked") + + def preview_call(self, data: Any) -> Any: + effects.append(data) + return self.call(data) + + calls = _Calls() + inner: Any = calls.pod.data_function + function: Any = _Both(inner._function, output_keys="y") + store = InMemoryArrowDatabase() + if wrapped: + function = CachedDataFunction(function, result_database=store) + stream = FunctionPod(function).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + with pytest.raises(PreviewRefusedError, match="no read-only call"): + stream.preview(2) + assert effects == [] + assert calls.seen == [] + _untouched(store) + + +@pytest.mark.parametrize("wrapped", [False, True]) +def test_a_pod_overriding_both_preview_methods_is_refused( + source: Any, wrapped: bool +) -> None: + """A pod subclass writing ``require_preview`` and ``preview_data`` both: neither + runs, plain or beneath a cached pod.""" + effects: list[Any] = [] + + class _Both(FunctionPod): + def require_preview(self) -> None: + effects.append("checked") + + def preview_data(self, data: Any) -> Any: + effects.append(data) + return self.data_function.call(data) + + calls = _Calls() + pod: Any = _Both(calls.pod.data_function) + store = InMemoryArrowDatabase() + if wrapped: + pod = CachedFunctionPod(pod, result_database=store) + stream = pod.process(_with_time(source).select_data_columns(["timestamp", "x"])) + with pytest.raises(PreviewRefusedError): + stream.preview(2) + assert effects == [] + assert calls.seen == [] + _untouched(store) + + +class _DropsAfterAProducer(MapData): + """An operator of your own that drops the first row when its input has a + producer: it reads its input as the full read gives it.""" + + def unary_static_process(self, stream: Any) -> Any: + result = super().unary_static_process(stream) + if stream.producer is None: + return result + table = result.as_table(columns={"source": True, "system_tags": True}) + return ArrowTableStream( + table.slice(1), + tag_columns=result.keys()[0], + data_context=result.data_context_key, + ) + + +def test_a_whole_input_keeps_its_producer(source: Any) -> None: + """The whole input a preview computes is given with its producer, so the rows are + the first of the full read.""" + + def stream() -> Any: + return _DropsAfterAProducer({"y": "z"})(_Calls().pod(_with_time(source))) + + whole = stream().as_table() + _same(stream().preview(2, compute_all=True).as_table(), whole[:2]) + + +def test_a_data_function_without_preview_methods_is_refused(source: Any) -> None: + """A data function written to the protocol before ``preview_call``: refused with + ``PreviewRefusedError``, not ``AttributeError``.""" + calls = _Calls() + + class _Legacy: + """Delegates every method but the preview ones.""" + + def __init__(self, function: Any) -> None: + self._function = function + + def __getattr__(self, name: str) -> Any: + if name in ("require_preview", "preview_call"): + raise AttributeError(name) + return getattr(self._function, name) + + function: Any = _Legacy(calls.pod.data_function) + stream = FunctionPod(function).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + with pytest.raises(PreviewRefusedError, match="no read-only call"): + stream.preview(2) + assert calls.seen == [] + + +def _all_columns_pod(seen: list[int], store: InMemoryArrowDatabase | None) -> Any: + """A pod that takes every data column of the SpiralDB source, so it reads the + source directly (no selection step between them), cached or not.""" + + @function_pod(output_keys="y") + def triple_all(timestamp: int | None, x: int | None, note: str | None) -> int: + seen.append(timestamp or 0) + return 3 * (x or 0) + + pod: Any = triple_all.pod + if store is None: + return pod + return FunctionPod(CachedDataFunction(pod.data_function, result_database=store)) + + +@pytest.mark.parametrize("cached", [False, True]) +def test_held_results_are_shown_without_reading_the_input( + spiral: Any, cached: bool +) -> None: + """Rows held by an iteration are shown first; the source is scanned only when + more rows are asked for than they give, with or without a limit pushed down.""" + seen: list[int] = [] + store = InMemoryArrowDatabase() + stream = _all_columns_pod(seen, store if cached else None).process( + spiral(tag_only_columns=["subject"]) + ) + rows = iter(stream) + _ = [next(rows) for _ in range(2)] + fake_spiral_sdk.scan_log.clear() + seen.clear() + shown = stream.preview(2).table + assert fake_spiral_sdk.scan_log == [] + assert seen == [] + assert shown.column("timestamp").to_pylist() == [0, 1] + more = stream.preview(3).table + assert more.column("timestamp").to_pylist() == [0, 1, 2] + assert seen == [2] + _same(more, stream.as_table().select(more.column_names)[:3]) + + +def test_held_results_of_every_input_read_no_input(spiral: Any) -> None: + """After an iteration to the end, a preview past the last row reads nothing.""" + seen: list[int] = [] + stream = _all_columns_pod(seen, None).process(spiral(tag_only_columns=["subject"])) + _ = list(stream.iter_data()) + fake_spiral_sdk.scan_log.clear() + seen.clear() + view = stream.preview(41) + assert len(view) == 40 + assert fake_spiral_sdk.scan_log == [] + assert seen == [] + + +def test_an_operator_in_the_library_namespace_is_not_the_library( + source: Any, +) -> None: + """A batch-declaring operator of your own named into the ``orcapod`` namespace is + still not one of the library's classes.""" + + class _Named(_BatchDeclaringMapData): + BATCHES_GIVE_THE_WHOLE = True + + _Named.__module__ = "orcapod.local_extension" + + def stream() -> Any: + return _Named({"note": "text"})(source()) + + whole = stream().as_table() + with pytest.raises(PreviewRefusedError, match="compute_all"): + stream().preview(2) + _same(stream().preview(2, compute_all=True).as_table(), whole[:2])