diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index 996ee7dd7..dc9133274 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -1,3 +1,12 @@ +### 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`. 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 - `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..2a72f923a 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -237,6 +237,40 @@ 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 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 +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. 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 +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: | Object | `run()` | diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index e7a6a7050..7a9317423 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. @@ -92,7 +92,13 @@ 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 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. - A kept result (an already computed stream) is sliced and nothing is computed. @@ -156,3 +162,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 5fa41bfdb..646d76a3a 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -11,11 +11,15 @@ 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, + 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 from orcapod.contexts.stored import ( @@ -300,6 +304,42 @@ 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. + + 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() + 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) or not is_exact_library_instance( + inner, previewable_pods() + ): + 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.""" + self.require_preview() + stored = self.lookup_cached_data(data) + if stored is not None: + return stored + output = self._inner_for_preview().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/data_function.py b/src/orcapod/core/data_function.py index fc124c478..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 @@ -30,6 +31,7 @@ from orcapod.core.result_cache import ResultCache from orcapod.errors import ( NoOutputsDeclaredError, + PreviewRefusedError, OutputTypeError, UnstorableDatetimeError, ) @@ -418,6 +420,34 @@ async def direct_async_call( """Asynchronous counterpart of ``direct_call``.""" ... + # ==================== Preview ==================== + + def require_preview(self) -> None: + """Refuse a preview: this kind of data function has no read-only call. + + 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: Always, for a kind with 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. + + 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 +1335,14 @@ def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": version=inner.get("version", "v0.0"), ) + def require_preview(self) -> None: + """Nothing refused: calling the function stores nothing + (``DataFunctionProtocol.require_preview``).""" + + def preview_call(self, data: DataProtocol) -> DataProtocol | None: + """Call the function (``DataFunctionProtocol.preview_call``): it stores nothing.""" + return self.call(data) + class DataFunctionWrapper(DataFunctionBase[E]): """Wrapper around a DataFunctionProtocol to modify or extend its behavior. @@ -1459,6 +1497,25 @@ 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: + """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: + """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 +1624,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/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 90f3fd5fa..00e8e05b3 100644 --- a/src/orcapod/core/data_function_proxy.py +++ b/src/orcapod/core/data_function_proxy.py @@ -171,6 +171,37 @@ 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 the bound function has no read-only call. + """ + 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. + + 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 8a24c3b49..f8367b6e4 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1,11 +1,21 @@ from __future__ import annotations +import functools + import asyncio import itertools 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 @@ -16,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, @@ -29,6 +40,14 @@ schema_requires_io, typed_zero_row_input, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + refused, + slices_of, + is_exact_library_instance, +) from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, STALE_NOTE, @@ -36,7 +55,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 +389,33 @@ 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") + + def _require_own_processing(self) -> None: + """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, tag: TagProtocol, @@ -949,6 +995,22 @@ def from_fn( **kwargs, ) + def require_preview(self) -> None: + """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" + ) + require_previewable_function(self.data_function) + self.data_function.require_preview() + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """See ``_FunctionPodBase.preview_data``: the data function's read-only call.""" + self.require_preview() + return self.data_function.preview_call(data) + @property def pod_config(self) -> PodConfig: """Per-pod executor configuration.""" @@ -1770,6 +1832,99 @@ 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: + # 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 + current = not self.is_stale + if current and self._cached_output_table is not None: + 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. 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 + # 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([]) + + 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. + + 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( + 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, + ) + def _shape_table( self, table: pa.Table, @@ -2134,6 +2289,18 @@ def with_fall_through( input_data, self._in_input_order(input_data.keys()) ) + 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: + """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 @@ -2380,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/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/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 1851b1ce5..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 @@ -57,6 +59,13 @@ typed_zero_row_table, row_built_columns, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + is_exact_library_instance, + refuse_without_compute_all, +) from orcapod.core.streams.view import ( BoundedStreamView, RunSize, @@ -793,6 +802,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. @@ -1762,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__( @@ -1773,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, ) @@ -2058,7 +2084,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]) ) @@ -2109,6 +2135,76 @@ 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) + # 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_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() + with closing(preview_batches(self._upstreams[0], wanted)) as batches: + for batch in batches: + yield pod.static_process(batch) + return + given_back = ( + pod.input_given_back(self._upstreams) + if is_exact_library_instance(pod, operators_giving_back_an_input()) + 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. + 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( + *( + 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(), + # 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 + ) + def run(self) -> StreamView: """Compute every row and return a ``StreamView`` (``StreamBase.run``). @@ -2267,6 +2363,60 @@ 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()``). + + 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/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 07221924c..e858c7181 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,7 +1,8 @@ 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 +14,12 @@ typed_zero_row_table, ) from orcapod.errors import SourceNameWarning, SourceVersionWarning +from orcapod.core.streams.preview import ( + PreviewRequest, + is_exact_library_instance, + 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 +594,16 @@ 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]: + """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). + """ + refuse_without_compute_all(self, request, "reads its rows whole") + yield from slices_of(self, request) + def head( self, n: int = 10, @@ -637,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/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..694c8b54d 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, @@ -41,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 @@ -701,6 +707,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/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 1c4a57228..5bb21bf1a 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -1,7 +1,9 @@ from __future__ import annotations +import copy 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 @@ -15,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,6 +36,14 @@ typed_arrow_schemas, typed_zero_row_table, ) +from orcapod.core.streams.preview import ( + PreviewRequest, + preview_batches, + is_exact_library_instance, + refuse_without_compute_all, + refused, + slices_of, +) from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema @@ -40,6 +51,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 @@ -589,13 +601,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 @@ -611,6 +632,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 @@ -792,6 +815,79 @@ 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 + 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 an origin is refused. + """ + refuse_without_compute_all( + self, request, "is a subclass that reads its rows its own way" + ) + 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( + 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 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. + + 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 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: + 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) 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: + 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: """Return this source's stream over the origin rows ``table``.""" if self._tags_as_data is not None: @@ -812,3 +908,55 @@ 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`` 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 + 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 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 + origin._origin, # pyright: ignore[reportPrivateUsage] # as above + 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): + if is_exact_library_instance( + origin, HELD_LIBRARY_SOURCES | {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/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/polling_source.py b/src/orcapod/core/sources/polling_source.py index de4cd3e1e..a45a344b6 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, @@ -57,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 @@ -652,6 +654,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/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/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..374050ad5 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, @@ -35,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): @@ -264,6 +270,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 efcfb4acc..645a588c2 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -63,7 +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.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, @@ -1129,15 +1130,41 @@ 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]: """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 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] + 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/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/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/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..53902a1d9 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -1,8 +1,10 @@ from __future__ import annotations +import functools + 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 +17,12 @@ StreamBase, check_head_size, ) +from orcapod.core.streams.preview import ( + PreviewRequest, + is_exact_library_instance, + 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 @@ -379,6 +387,20 @@ 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``). + + 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_exact_library_instance(self, previewable_streams()): + 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": """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) @@ -496,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/base.py b/src/orcapod/core/streams/base.py index 747d61607..965623edd 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,88 @@ 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()``, 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 + 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). + + 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. + + 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..c9d16f2e9 --- /dev/null +++ b/src/orcapod/core/streams/preview.py @@ -0,0 +1,164 @@ +"""``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: 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, 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.""" + 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)] = (stream, list(batches)) + yield from request.kept[id(stream)][1] + + +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 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). + + 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, data function, source or stream. + classes: The library classes the path was written for. + + Returns: + Whether the path may be taken for ``obj``. + """ + from orcapod.core.streams.base import reads_as_its_class + + cls = type(obj) + return cls in classes and reads_as_its_class(obj, cls) + + +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/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/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, diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py new file mode 100644 index 000000000..73854f2b1 --- /dev/null +++ b/tests/test_core/streams/test_preview.py @@ -0,0 +1,1802 @@ +"""``stream.preview(n)``: the first rows of the sync result, and no more work (ITL-1464).""" + +from __future__ import annotations + +import asyncio +import gc +import weakref +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 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 +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 +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 + +ROWS = 40 +_PROJECT = "sample" +_KEYS = pa.schema( + [pa.field("subject", pa.string()), pa.field("timestamp", pa.uint64())] +) + + +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)], + "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 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) + + +# --------------------------------------------------------------------------- +# 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 _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] = [] + + @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.add_post_run_hook(fired.append) + _ = 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), + ( + lambda s: DerivedSource( + s, tags_as_data={"timestamp": "time"}, source_id="derived" + ), + 5, + 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 + + +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( + 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, + ) + + 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(7) + with pytest.raises(RowIdentifierError, match="unique"): + derived().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) + 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_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(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() + 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, []) + + +# --------------------------------------------------------------------------- +# 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 nothing was written to ``store``: it holds no table.""" + 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`` is read-only when what it wraps is.""" + from orcapod.core.data_function import DataFunctionWrapper + + calls = _Calls() + store = InMemoryArrowDatabase() + function = DataFunctionWrapper[Any]( + 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="not a pod of the library"): + 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="not a pod of the library"): + 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] + + +# --------------------------------------------------------------------------- +# 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] + + +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] + + +# --------------------------------------------------------------------------- +# 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="not a pod of the library"): + 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]) + + +# --------------------------------------------------------------------------- +# 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])