From 02e6f0a56971841bc1a2b8a8fc875c3f614bdae1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:41:22 -0800 Subject: [PATCH 1/3] wip(streams): preview(n) (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/cached_function_pod.py | 17 ++- src/orcapod/core/function_pod.py | 121 +++++++++++++++- src/orcapod/core/nodes/source_node.py | 9 ++ .../core/operators/static_output_pod.py | 54 +++++++ src/orcapod/core/sources/base.py | 19 ++- src/orcapod/core/sources/cached_source.py | 9 +- src/orcapod/core/sources/polling_source.py | 9 +- src/orcapod/core/sources/source_proxy.py | 8 + .../core/sources/spiraldb_table_source.py | 29 +++- .../core/streams/arrow_table_stream.py | 9 +- src/orcapod/core/streams/base.py | 75 ++++++++++ src/orcapod/core/streams/preview.py | 137 ++++++++++++++++++ src/orcapod/errors.py | 7 + .../protocols/core_protocols/streams.py | 13 ++ 14 files changed, 508 insertions(+), 8 deletions(-) create mode 100644 src/orcapod/core/streams/preview.py diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 5fa41bfdb..50a330356 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -6,7 +6,7 @@ import logging from datetime import datetime, timezone from collections.abc import Iterator -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram @@ -300,6 +300,21 @@ async def async_process_data( output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) return tag, output + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``: the inner pod's answer.""" + cast("_FunctionPodBase", self._function_pod).require_preview() + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """The stored result, else the inner pod's, which is not stored.""" + self.require_preview() + stored = self.lookup_cached_data(data) + if stored is not None: + return stored + output = cast("_FunctionPodBase", self._function_pod).preview_data(data) + if output is None: + return None + return output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) + def _invoke_with_hooks( self, tag: TagProtocol, diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8a24c3b49..bcc559265 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -5,7 +5,15 @@ import dataclasses import logging from abc import abstractmethod -from collections.abc import Callable, Collection, Iterable, Iterator, Sequence +from collections.abc import ( + Callable, + Collection, + Generator, + Iterable, + Iterator, + Sequence, +) +from contextlib import closing from functools import update_wrapper, wraps from typing import TYPE_CHECKING, Any, Literal, Protocol, cast @@ -29,6 +37,13 @@ schema_requires_io, typed_zero_row_input, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + refused, + slices_of, +) from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, STALE_NOTE, @@ -36,7 +51,7 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.errors import OrcapodDatabaseError, TypeIdentityError +from orcapod.errors import OrcapodDatabaseError, PreviewRefusedError, TypeIdentityError from orcapod.utils.database_errors import keep_database_error, note_callback_failure from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -370,6 +385,28 @@ def process_data( ) return tag, self.data_function.call(data, logger=logger, **extra) + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """Call the function on one row for a preview: no effect, nothing stored. + + Stored results are read; no hook fires. + + Args: + data: The row's data. + + Raises: + PreviewRefusedError: If this kind of pod has no preview, or its function + takes the invocation context (it performs an external action). + """ + raise PreviewRefusedError(f"{type(self).__name__} has no preview") + + def require_preview(self) -> None: + """Refuse a preview of this pod before any function is called. + + Raises: + PreviewRefusedError: As ``preview_data`` would. + """ + raise PreviewRefusedError(f"{type(self).__name__} has no preview") + async def async_process_data( self, tag: TagProtocol, @@ -949,6 +986,21 @@ def from_fn( **kwargs, ) + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``.""" + if self._ctx_arg_name is not None: + raise PreviewRefusedError( + "its function takes the invocation context: it performs an action" + ) + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """See ``_FunctionPodBase.preview_data``.""" + self.require_preview() + function = self.data_function + if isinstance(function, CachedDataFunction): + return function.call(data, skip_cache_insert=True) + return function.call(data) + @property def pod_config(self) -> PodConfig: """Per-pod executor configuration.""" @@ -1770,6 +1822,61 @@ def _computed_prefix( total += 1 return shown, total + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The function's rows, one per batch, each computed only when asked for. + + Results this stream already holds are used, and nothing is kept of the others. + """ + pod = self._pod_base() + try: + pod.require_preview() + except PreviewRefusedError as error: + raise refused(self, f"cannot be previewed: {error}") from error + current = not self.is_stale + if current and self._cached_output_table is not None: + yield from slices_of(self, request) + return + known = dict(self._cached_output_datas) if current else {} + function = pod.data_function + # An inactive function gives no row; any other gives one per input row. + one_per_row = type(function) is PythonDataFunction and function.is_active() + wanted = request if one_per_row else request.without_limit() + given = False + index = 0 + with closing(preview_batches(self._input_stream, wanted)) as batches: + for batch in batches: + for tag, data in batch.iter_data(): + if index in known: + tag, output = known[index] + else: + output = pod.preview_data(data) + index += 1 + if output is not None: + given = True + yield self._preview_batch([(tag, output)]) + if not given: + yield self._preview_batch([]) + + def _preview_batch( + self, pairs: list[tuple[TagProtocol, DataProtocol]] + ) -> StreamProtocol: + """``pairs`` as a stream, laid out as ``as_table`` lays out this stream's rows.""" + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + tag_keys, data_keys = self.keys() + return ArrowTableStream( + self._shape_table( + self._table_from_pairs(pairs), + ColumnConfig(**PREVIEW_COLUMNS), + _no_content_hashes, + ), + tag_columns=tag_keys, + data_tags=data_tag_names(tag_keys, data_keys), + data_context=self.data_context_key, + ) + def _shape_table( self, table: pa.Table, @@ -2134,6 +2241,16 @@ def with_fall_through( input_data, self._in_input_order(input_data.keys()) ) + def require_preview(self) -> None: + """See ``_FunctionPodBase.require_preview``.""" + self._plain_pod.require_preview() + + def preview_data(self, data: DataProtocol) -> DataProtocol | None: + """The plain pod's, then the fall-through columns, as ``process_data``.""" + return self.with_fall_through( + data, self._plain_pod.preview_data(self.function_input(data)) + ) + def function_input_schema(self, input_schema: Schema) -> Schema: """The part of an input data schema the function takes (see ``function_input``).""" parameters = self.input_data_schema diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..287096875 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -41,6 +41,7 @@ typed_zero_row_table, ) from orcapod.core.streams.record_batch_input import InputChannel +from orcapod.core.streams.preview import refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -1271,6 +1272,14 @@ def run(self) -> StreamView: display_all_rows=False, ) + def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: + """Refused: a node of a pipeline or job has no preview (``StreamBase.preview``). + + Raises: + PreviewRefusedError: Always. + """ + raise refused(self, "is a node of a pipeline or job") + def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 5149cf697..5d50e2de4 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -56,6 +56,12 @@ typed_zero_row_table, row_built_columns, ) +from orcapod.core.streams.preview import ( + PREVIEW_COLUMNS, + PreviewRequest, + preview_batches, + refuse_without_compute_all, +) from orcapod.core.streams.view import ( RUN_VIEW_COMPLETE_ROWS, BoundedStreamView, @@ -2108,6 +2114,54 @@ def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: self._kept_states = kept_states self._run_window = None + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The operator over its input's batches, or over its whole inputs. + + A kept current result is read as it is; nothing is computed, and nothing is + kept of what is computed here. + """ + self._pod._note_provisional_identity_use() + self._update_cache_status() + if self._cached_stream is not None and self._cached_time is not None: + yield from preview_batches(self._cached_stream, request) + return + pod = cast(StaticOutputOperatorPod, self._pod) + if ( + len(self._upstreams) == 1 + and type(pod).__dict__.get("BATCHES_GIVE_THE_WHOLE") is True + ): + keeps_every_row = pod.rows_dropped_text(0, (), self._upstreams) is None + wanted = request if keeps_every_row else request.without_limit() + with closing(preview_batches(self._upstreams[0], wanted)) as batches: + for batch in batches: + yield pod.static_process(batch) + return + refuse_without_compute_all(self, request, "needs every row of its input") + result = pod.static_process( + *( + self._whole_input(upstream, request.of_every_row()) + for upstream in self._upstreams + ) + ) + yield from preview_batches(result, request) + + @staticmethod + def _whole_input( + upstream: StreamProtocol, request: PreviewRequest + ) -> StreamProtocol: + """Every row of ``upstream``, computed for a preview, with its pipeline hash.""" + rows = joined_batches(list(preview_batches(upstream, request))) + return _RowsOfStream( + rows.as_table(columns=PREVIEW_COLUMNS), + tag_columns=rows.keys()[0], + pipeline_hash=upstream.pipeline_hash(), + data_tags=stream_data_tags(rows), + upstreams=upstream.upstreams, + data_context=StaticOutputOperatorPod._upstream_context(upstream), # pyright: ignore[reportPrivateUsage] # the one place that resolves an upstream's context + ) + def run(self) -> StreamView: """Compute every row and return a ``StreamView`` (``StreamBase.run``). diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..2048e7b06 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,7 +1,7 @@ from __future__ import annotations import warnings -from collections.abc import Callable +from collections.abc import Callable, Generator from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from orcapod import contexts @@ -13,6 +13,11 @@ typed_zero_row_table, ) from orcapod.errors import SourceNameWarning, SourceVersionWarning +from orcapod.core.streams.preview import ( + PreviewRequest, + refuse_without_compute_all, + slices_of, +) from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Condition, ContentHash, Schema @@ -587,6 +592,18 @@ def _display_name(self) -> str: # The header names the class already; the name is the part that is the user's. return self.source_name + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the rows a source holds (``preview_batches``). + + A source of the library that holds its table (``_stream``) reads nothing. Any + other read of a whole source is refused unless ``compute_all`` was given. + """ + if not isinstance(getattr(self, "_stream", None), ArrowTableStream): + refuse_without_compute_all(self, request, "reads its rows whole") + yield from slices_of(self, request) + def head( self, n: int = 10, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..0d4ba8c0e 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -3,7 +3,7 @@ import logging from datetime import datetime -from collections.abc import Iterator +from collections.abc import Generator, Iterator from typing import Any, ClassVar, TYPE_CHECKING import pyarrow as pa @@ -26,6 +26,7 @@ schema_requires_io, typed_zero_row_table, ) +from orcapod.core.streams.preview import PreviewRequest, refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -701,6 +702,12 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: assert self._cached_stream is not None return self._cached_stream.iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Refused: reading the source writes its cache.""" + raise refused(self, "writes its cache when it is read") + def as_table( self, *, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index de4cd3e1e..12912a975 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -14,7 +14,7 @@ import functools import logging import threading -from collections.abc import Collection +from collections.abc import Generator, Collection from math import floor from typing import Any, ClassVar, Generic, TYPE_CHECKING, TypeVar, cast @@ -29,6 +29,7 @@ SourceStreamBuilder, normalize_record_id_columns, ) +from orcapod.core.streams.preview import PreviewRequest, refused from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -652,6 +653,12 @@ def iter_data(self): _ = self._sync_poll_and_commit() return self._get_combined_stream().iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Refused: reading the source polls.""" + raise refused(self, "polls when it is read") + def as_table( self, *, diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..8dfdcf4cf 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -11,12 +11,14 @@ from __future__ import annotations from datetime import datetime +from collections.abc import Generator from typing import TYPE_CHECKING, Any from typing_extensions import override from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id +from orcapod.core.streams.preview import PreviewRequest, preview_batches from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -264,6 +266,12 @@ def _typed_zero_row_table(self) -> pa.Table | None: def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: return self._require_delegate().iter_data() + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """The bound source's (``preview_batches``).""" + yield from preview_batches(self._require_delegate(), request) + def as_table( self, *, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index d67578527..a0b48c9d8 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -64,6 +64,7 @@ ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import check_head_size, reads_as_its_class +from orcapod.core.streams.preview import PreviewRequest from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -1135,9 +1136,35 @@ def _reads_in_batches(self) -> bool: def _batch_streams_of_rows(self) -> Generator[StreamProtocol, None, None]: """One scan of the table, each batch shaped as ``as_table()`` shapes the whole (``run()``, ITL-1464).""" + yield from self._shaped_batches(self._batch_streams()) + + @override + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """One scan, limited by SpiralDB when the rows wanted are known, else closed when + enough were read. ``max_rows`` holds only when every row is asked for.""" + if not reads_as_its_class(self, SpiralDBTableSource): + yield from super()._preview_batches(request) + return + limits = [n for n in (self._limit, request.limit) if n is not None] + yield from self._shaped_batches( + self._read_batches( + self._lookup_table(), + asof=self._asof, + limit=min(limits, default=None), + max_rows=self._max_rows if request.whole else None, + ) + ) + + def _shaped_batches( + self, batches: Generator[ArrowTableStream, None, None] + ) -> Generator[StreamProtocol, None, None]: + """``batches`` of one read, each shaped as ``as_table()`` shapes the whole; at + least one.""" columns = {"source": True, "system_tags": True, "context": True} read = False - with closing(self._batch_streams()) as streams: + with closing(batches) as streams: for stream in streams: read = True yield ArrowTableStream( diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..7b44b77c3 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -2,7 +2,7 @@ import itertools import logging -from collections.abc import Collection, Iterator +from collections.abc import Collection, Generator, Iterator from typing import Any import pyarrow as pa @@ -15,6 +15,7 @@ StreamBase, check_head_size, ) +from orcapod.core.streams.preview import PreviewRequest, slices_of from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol from orcapod.protocols.hashing_protocols import PipelineElementProtocol @@ -379,6 +380,12 @@ def head( total_rows=self._table.num_rows, ) + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """Slices of the rows this stream holds (``preview_batches``).""" + yield from slices_of(self, request) + def _typed_zero_row_table(self) -> "pa.Table": """This stream's table cut to no rows: its own Arrow types, no row assembled.""" return self._assemble_table(ZERO_ROW_INPUT_COLUMNS, limit=0) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 79d23ca7f..afbd8ecd1 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -26,6 +26,7 @@ from orcapod.core.base import TraceableBase from orcapod.core.data_tags import data_tag_names +from orcapod.core.streams.preview import PreviewRequest, preview_batches, refused from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -1667,6 +1668,80 @@ def _view_of_rows(self, table: "pa.Table", origin: str) -> StreamView: display_all_rows=False, ) + def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: + """Compute the first ``n`` rows, and only what they need; keep nothing (ITL-1464). + + ``head()`` never computes; ``preview()`` does. The rows are the first ``n`` of + ``as_table()``. A source reads no more than is needed (a limit, or batches until + enough rows have passed), an operator applied batch by batch takes batches, and a + function is called on one row after another until ``n`` rows have come out, so + **your functions run**, once per row they are needed for. Nothing is kept on any + stream and nothing is written: a pod with stored results reads them and stores + none, no post-run hook fires, and a second ``preview()`` computes again. Results + a stream already holds are used. + + A join, ``group_by``, ``batch``, ``polars_filter``, ``tag_by``, ``pick``, + ``index`` or an operator of your own needs its whole input. It is refused unless + ``compute_all`` is ``True``, which computes that step, and everything beneath it, + in full (and calls functions beneath it on every row), and keeps none of it. + + Refused always: a side-effect pod or a function that takes the invocation + context (it would act), a source whose read polls or writes a cache, and a node + of a pipeline or job (``run()`` it, or ``head()`` it after a run). + + Args: + n: The most rows to compute; at least 1. + compute_all: Allow steps that need their whole input. + + Returns: + A ``StreamView``: ``ROWS`` when these are all the rows of the stream, else + ``PARTIAL``. + + Raises: + TypeError: If ``n`` is not an ``int``. + ValueError: If ``n`` is less than 1. + PreviewRefusedError: If a step is refused, as said above; the message names + it. Without ``compute_all`` it is raised before any function is called. + """ + if isinstance(n, bool) or not isinstance(n, int): + raise TypeError( + f"preview() takes an int number of rows, got {type(n).__name__}" + ) + if n < 1: + raise ValueError(f"preview() takes at least 1 row, got {n}") + request = PreviewRequest(limit=n, compute_all=compute_all) + tables: list[pa.Table] = [] + rows = 0 + with closing(preview_batches(self, request)) as batches: + for batch in batches: + tables.append(batch.as_table()) + rows += tables[-1].num_rows + if rows >= n: + break + table = pa.concat_tables(tables).slice(0, n) + complete = rows < n + shown = table.num_rows + noun = "row" if shown == 1 else "rows" + return StreamView.of_rows( + self, + table, + tag_columns=self.keys()[0], + total_rows=shown if complete else None, + status=ViewStatus.ROWS if complete else ViewStatus.PARTIAL, + origin="computed", + description=( + f"preview: all {shown:,} {noun}" + if complete + else f"preview: first {shown:,} {noun} (run() computes every row)" + ), + ) + + def _preview_batches( + self, request: PreviewRequest + ) -> Generator[StreamProtocol, None, None]: + """This stream's rows for a preview (``preview_batches``): not given by default.""" + raise refused(self, "has no preview") + def head( self, n: int = 10, diff --git a/src/orcapod/core/streams/preview.py b/src/orcapod/core/streams/preview.py new file mode 100644 index 000000000..f4cf4f2d0 --- /dev/null +++ b/src/orcapod/core/streams/preview.py @@ -0,0 +1,137 @@ +"""``stream.preview(n)``: the first rows of a stream, computing only what they need (ITL-1464). + +A preview reads a stream's rows as ``_preview_batches`` yields them, in the order of the +sync path, and stops at ``n``. Each kind of stream says how it gives its rows in batches +(a source reads a limit, an operator applied batch by batch takes its input's batches, a +function pod takes one row at a time); a stream that needs a whole input is refused unless +``compute_all`` was given. Nothing is kept on a stream, written to a database or +delivered. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Generator +from contextlib import closing +from typing import TYPE_CHECKING, Any + +import pyarrow as pa + +from orcapod.errors import PreviewRefusedError + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol + +FIRST_BATCH_ROWS = 1_024 +"""The rows of the first batch read when a step may drop rows; each next one doubles.""" + +PREVIEW_COLUMNS = {"source": True, "system_tags": True, "context": True} +"""The column groups a batch carries from step to step: every one but the hashes.""" + + +@dataclasses.dataclass(frozen=True) +class PreviewRequest: + """What a preview asks of a stream. + + Attributes: + limit: The most rows that can be used, or ``None`` when that is not known (a + step above may drop rows). A source reads no more. + compute_all: Whether a step that needs its whole input may be computed. + whole: Whether every row is asked for, by such a step. + kept: The batches of the streams read in full by such steps, by identity: a + stream two branches share is computed once. Discarded with the preview. + """ + + limit: int | None + compute_all: bool = False + whole: bool = False + kept: dict[int, list[StreamProtocol]] = dataclasses.field(default_factory=dict) + + def without_limit(self) -> PreviewRequest: + """The request to the input of a step that may drop rows.""" + return dataclasses.replace(self, limit=None) + + def of_every_row(self) -> PreviewRequest: + """The request to the inputs of a step that needs them whole.""" + return dataclasses.replace(self, limit=None, whole=True) + + +def preview_batches( + stream: Any, request: PreviewRequest +) -> Generator[StreamProtocol, None, None]: + """The rows of ``stream``, in order, as one stream per batch; at least one batch. + + Args: + stream: The stream, or anything else a step read as its input. + request: What is asked of it. + + Raises: + PreviewRefusedError: If the stream, or one beneath it, cannot be previewed. + """ + give = getattr(stream, "_preview_batches", None) + if give is None: + raise refused(stream, "has no preview") + if not request.whole: + with closing(give(request)) as batches: + yield from batches + return + if id(stream) not in request.kept: + with closing(give(request)) as batches: + request.kept[id(stream)] = list(batches) + yield from request.kept[id(stream)] + + +def slices_of( + stream: Any, request: PreviewRequest +) -> Generator[StreamProtocol, None, None]: + """The rows of a stream that holds them (or reads them without effect), in slices. + + Args: + stream: A stream whose ``as_table`` computes nothing. + request: What is asked of it. + """ + from orcapod.core.data_tags import stream_data_tags + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + table: pa.Table = stream.as_table(columns=PREVIEW_COLUMNS) + size = table.num_rows if request.whole else request.limit or FIRST_BATCH_ROWS + end = table.num_rows if request.limit is None else request.limit + start = 0 + while True: + yield ArrowTableStream( + table.slice(start, min(size, end - start)), + tag_columns=stream.keys()[0], + data_tags=stream_data_tags(stream), + data_context=stream.data_context_key, + ) + start += size + size *= 2 + if start >= min(end, table.num_rows): + return + + +def refused(stream: Any, why: str) -> PreviewRefusedError: + """Return the error for a stream that cannot be previewed, naming it and the remedy.""" + return PreviewRefusedError( + f"preview() stopped at {type(stream).__name__}[{getattr(stream, 'label', '')}], " + f"which {why}. run() computes every row." + ) + + +def refuse_without_compute_all(stream: Any, request: PreviewRequest, why: str) -> None: + """Refuse a step that needs its whole input, unless ``compute_all`` was given. + + Args: + stream: The step's stream. + request: What is asked of it. + why: What the step needs, after the stream's name. + + Raises: + PreviewRefusedError: Unless ``request.compute_all``. + """ + if not request.compute_all: + raise PreviewRefusedError( + f"preview() stopped at {type(stream).__name__}[{stream.label}], which {why}. " + "preview(n, compute_all=True) computes that step in full, and keeps nothing; " + "run() computes every row and keeps what it computes." + ) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 492f411ad..2c6652663 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1267,6 +1267,13 @@ def __str__(self) -> str: ) +class PreviewRefusedError(ValueError): + """A ``preview()`` would need more than the rows it shows, or would have an effect. + + The message names the stream it stopped at (ITL-1464). + """ + + class BoundedViewError(ValueError): """What was asked of a view needs rows the view does not hold (ITL-1464). diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index ad079e67e..af1b67bce 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -292,6 +292,19 @@ def run(self) -> "StreamViewProtocol": """ ... + def preview( + self, n: int = 10, *, compute_all: bool = False + ) -> "StreamViewProtocol": + """Compute the first ``n`` rows and only what they need, keeping nothing. + + User functions are called; nothing is stored and nothing has an effect. A step + that needs its whole input is refused unless ``compute_all`` (ITL-1464). + + Returns: + StreamView: The first ``n`` rows of ``as_table()``. + """ + ... + def head( self, n: int = 10, From a44cf433535c3fa7da6f564fe02bd999a60c3988 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:10:37 -0800 Subject: [PATCH 2/3] feat(streams): preview(n) computes the first rows and only what they need (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 7 + docs/concepts/streams.md | 26 + docs/dev/specs/itl-1464-views.md | 19 +- src/orcapod/core/cached_function_pod.py | 7 +- src/orcapod/core/function_pod.py | 18 +- src/orcapod/core/sources/base.py | 2 + src/orcapod/core/sources/cached_source.py | 7 +- src/orcapod/core/sources/polling_source.py | 1 + src/orcapod/core/sources/source_proxy.py | 6 +- src/orcapod/core/streams/base.py | 2 +- tests/test_core/streams/test_preview.py | 554 +++++++++++++++++++++ 11 files changed, 637 insertions(+), 12 deletions(-) create mode 100644 tests/test_core/streams/test_preview.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md index 996ee7dd7..c50666eda 100644 --- a/changelog.d/ITL-1464.md +++ b/changelog.d/ITL-1464.md @@ -1,3 +1,10 @@ +### Added + +- `stream.preview(n)`: the first `n` rows of a stream that is not computed, computing only what + they need (ITL-1464). Functions are called on as few rows as that takes; nothing is kept, + stored or delivered. A step that needs its whole input (a join, `group_by`, ...) is refused + unless `compute_all=True`. + ### Changed - `run()` of a `SpiralDBTableSource`, and of column selections, renames, `add_tags`, diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 63f89939f..9e3e3ad6f 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -237,6 +237,32 @@ a polling source polls again and a `SpiralDBTableSource` reads its whole table a an operator's stream whose `run()` gave a bounded view). A view never asks its stream for more columns, because for those streams asking again is not a read. +### The first rows of a stream not computed yet: `preview(n)` + +`head()` never computes, so it has nothing to show of a derived stream nobody ran. +`preview(n)` computes the first `n` rows of `as_table()`, and only what they need: + +```python +first = months.preview(2) +print(first.header()) +# FunctionPodStream[months] — preview: first 2 rows (run() computes every row) +print(first.as_table().column("age_months").to_pylist()) +# [108, 120] +``` + +A source reads no more than is needed, an operator takes batches until enough rows have +passed, and **your functions are called**, on one row after another until `n` rows have come +out. Nothing is kept on a stream, nothing is stored (a pod with stored results reads them and +adds none), and no hook fires; calling `preview` again computes again. Results a stream +already holds are used. A view of fewer rows than asked for says it shows all of them. + +A join, `group_by`, `batch`, `polars_filter`, `tag_by`, `pick`, `index` or an operator of your +own needs every row of its input, so `preview` refuses it (`PreviewRefusedError`, naming the +step). `preview(n, compute_all=True)` computes that step and everything beneath it in full, +functions included, and keeps none of it. A side-effect pod, a function that takes the +invocation context, a `CachedSource`, a `PollingSource` and a node of a pipeline or job are +refused always: a preview never acts. + What `run()` does on each kind of object: | Object | `run()` | diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index e7a6a7050..0e6f9bc66 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -1,7 +1,7 @@ # `run()`, its view and `preview(n)` without a full table (ITL-1464, track VIEWS) Status: V1 to V12 approved by the coordinator, November 25, 2026 (V2, V3 and V8 flagged for -the developer); the bounded view is implemented, `preview(n)` is not. Written, against `origin/main` 0d1e017c. Companion of +the developer); the bounded view and `preview(n)` are implemented. Written, against `origin/main` 0d1e017c. Companion of `itl-1464-streaming-design.md` (sections 1, 3 and 4 of it). Nothing here changes a hash, identity, stored layout, stored byte or golden value. @@ -156,3 +156,20 @@ none, so its run scans once. One outermost question (`_upstream_states`) asks each stream once, so the walk is linear in the graph: settling a stream asks for the states beneath it, and so does its own state. + +## `preview(n)` as built + +- `StreamBase.preview` pulls `_preview_batches` (`core/streams/preview.py`) and stops at `n`. A + function pod gives one row per batch, computed when asked for, so no function is called past + the last row needed, also under a filter; an operator's batch upstream of a function may be + larger, since it calls nothing. +- The limit is passed down through operators that drop no row (`rows_dropped_text`) and + through an active Python function; anything else takes batches and the scan is closed. +- `Pick` and `Index` are refused with the whole-input steps, for the reason they are not + batched by `run()`. +- `compute_all` memoizes each stream it reads in full for the one call, so a stream two + branches share is computed once. With it, functions beneath one input may have run when + another input is refused. +- No meta column is shown: a stored row and a computed one have different ones. +- A `DerivedSource` is a whole read (its origin may compute). A filter nothing passes reads the + whole table, in batches: `max_rows` does not stop it, as it does not stop `head`. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 50a330356..83684d608 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -11,6 +11,7 @@ from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram from orcapod.core.function_pod import ( + _FunctionPodBase, # pyright: ignore[reportPrivateUsage] # one pod family FunctionPodStream, WrappedFunctionPod, function_zero_row_table, @@ -302,7 +303,7 @@ async def async_process_data( def require_preview(self) -> None: """See ``_FunctionPodBase.require_preview``: the inner pod's answer.""" - cast("_FunctionPodBase", self._function_pod).require_preview() + cast(_FunctionPodBase, cast(object, self._function_pod)).require_preview() def preview_data(self, data: DataProtocol) -> DataProtocol | None: """The stored result, else the inner pod's, which is not stored.""" @@ -310,7 +311,9 @@ def preview_data(self, data: DataProtocol) -> DataProtocol | None: stored = self.lookup_cached_data(data) if stored is not None: return stored - output = cast("_FunctionPodBase", self._function_pod).preview_data(data) + output = cast(_FunctionPodBase, cast(object, self._function_pod)).preview_data( + data + ) if output is None: return None return output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index bcc559265..3f4e6c24e 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -1862,16 +1862,22 @@ def _preview_batches( def _preview_batch( self, pairs: list[tuple[TagProtocol, DataProtocol]] ) -> StreamProtocol: - """``pairs`` as a stream, laid out as ``as_table`` lays out this stream's rows.""" + """``pairs`` as a stream, laid out as ``as_table`` lays out this stream's rows. + + Without the meta columns: a stored row of a cached pod has other ones than a row + computed here, and a preview shows none. + """ + from orcapod.core.operators.meta_columns import without_meta_columns from orcapod.core.streams.arrow_table_stream import ArrowTableStream tag_keys, data_keys = self.keys() + table = self._shape_table( + self._table_from_pairs(pairs), + ColumnConfig(**PREVIEW_COLUMNS), + _no_content_hashes, + ) return ArrowTableStream( - self._shape_table( - self._table_from_pairs(pairs), - ColumnConfig(**PREVIEW_COLUMNS), - _no_content_hashes, - ), + without_meta_columns(table, tag_keys), tag_columns=tag_keys, data_tags=data_tag_names(tag_keys, data_keys), data_context=self.data_context_key, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 2048e7b06..1d7450f5d 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -600,6 +600,8 @@ def _preview_batches( A source of the library that holds its table (``_stream``) reads nothing. Any other read of a whole source is refused unless ``compute_all`` was given. """ + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + if not isinstance(getattr(self, "_stream", None), ArrowTableStream): refuse_without_compute_all(self, request, "reads its rows whole") yield from slices_of(self, request) diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 0d4ba8c0e..694c8b54d 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -42,7 +42,12 @@ report_rows_of_other_data_contexts, with_data_context, ) -from orcapod.protocols.core_protocols import DataProtocol, SourceProtocol, TagProtocol +from orcapod.protocols.core_protocols import ( + DataProtocol, + SourceProtocol, + StreamProtocol, + TagProtocol, +) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 12912a975..a45a344b6 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -58,6 +58,7 @@ from polars._typing import FrameInitTypes from orcapod.core.streams.arrow_table_stream import ArrowTableStream + from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.types import Schema diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 8dfdcf4cf..374050ad5 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -37,7 +37,11 @@ import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) class SourceProxy(RootSource): diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 99ec4cc0b..b334ab607 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1672,7 +1672,7 @@ def preview(self, n: int = 10, *, compute_all: bool = False) -> StreamView: """Compute the first ``n`` rows, and only what they need; keep nothing (ITL-1464). ``head()`` never computes; ``preview()`` does. The rows are the first ``n`` of - ``as_table()``. A source reads no more than is needed (a limit, or batches until + ``as_table()``, without a cached pod's meta columns. A source reads no more than is needed (a limit, or batches until enough rows have passed), an operator applied batch by batch takes batches, and a function is called on one row after another until ``n`` rows have come out, so **your functions run**, once per row they are needed for. Nothing is kept on any diff --git a/tests/test_core/streams/test_preview.py b/tests/test_core/streams/test_preview.py new file mode 100644 index 000000000..1e8d422f8 --- /dev/null +++ b/tests/test_core/streams/test_preview.py @@ -0,0 +1,554 @@ +"""``stream.preview(n)``: the first rows of the sync result, and no more work (ITL-1464).""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, col, function_pod +from orcapod.core.cached_function_pod import CachedFunctionPod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.operators import MapData +from orcapod.core.sources import ArrowTableSource, CachedSource, DerivedSource +from orcapod.core.sources.polling_source import PollingSource +from orcapod.core.streams import preview as preview_module +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import PreviewRefusedError, RowIdentifierError +from orcapod.side_effects import SideEffectPod +from orcapod.sources import SpiralDBTableSource +from orcapod.streams import StreamView, ViewStatus +from tests.test_core.streams.test_head_and_preview import _FakeDynamicSource +from tests.test_databases import fake_spiral_sdk + +ROWS = 40 +_PROJECT = "sample" +_KEYS = pa.schema( + [pa.field("subject", pa.string()), pa.field("timestamp", pa.uint64())] +) + + +def _rows(n: int = ROWS) -> pa.Table: + return pa.table( + { + "subject": [f"m{i * 3 // n}" for i in range(n)], + "timestamp": pa.array(range(n), pa.uint64()), + "x": pa.array([None if i % 7 == 3 else i for i in range(n)], pa.int64()), + "note": [f"n{i}" for i in range(n)], + } + ) + + +@pytest.fixture(params=["spiral", "held"]) +def source( + request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """Make a source of 40 rows, read on demand (6 per SDK batch) or held.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 6) + with fake_spiral_sdk.install(tmp_path / "spiral"): + fake_spiral_sdk.ExternalProject(_PROJECT).create_table( + "default.event", key_schema=_KEYS + ).write(_rows()) + + def make(**kwargs: Any) -> Any: + kwargs.setdefault("tag_only_columns", True) + if request.param == "spiral": + kwargs.setdefault("batch_rows", 4) + return SpiralDBTableSource(_PROJECT, "event", **kwargs) + kwargs.pop("batch_rows", None) + return ArrowTableSource( + _rows(), tag_columns=["subject", "timestamp"], source_id="e", **kwargs + ) + + yield make + + +@pytest.fixture() +def spiral(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """A SpiralDB source of 40 rows, scanned 6 rows per SDK batch, and its scan log.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 6) + with fake_spiral_sdk.install(tmp_path / "spiral"): + fake_spiral_sdk.ExternalProject(_PROJECT).create_table( + "default.event", key_schema=_KEYS + ).write(_rows()) + + def make(**kwargs: Any) -> SpiralDBTableSource: + options: dict[str, Any] = {"tag_only_columns": True, "batch_rows": 4} + options.update(kwargs) + made = SpiralDBTableSource( + _PROJECT, + "event", + **options, + ) + fake_spiral_sdk.scan_log.clear() + return made + + yield make + + +class _Calls: + """A function pod that records the rows it was called on.""" + + def __init__(self, fail_at: int | None = None) -> None: + self.seen: list[int] = [] + seen = self.seen + + @function_pod(output_keys="y") + def triple(timestamp: int | None, x: int | None) -> int: + seen.append(timestamp or 0) + if timestamp == fail_at: + raise RuntimeError(f"failed at {timestamp}") + return 3 * (x or 0) + + self.function: Any = triple + + @property + def pod(self) -> FunctionPod: + return self.function.pod + + +def _with_time(source: Any) -> Any: + """``source`` with its ``timestamp`` as data: a pod takes it.""" + return source(tag_only_columns=["subject"]) + + +def _same(left: pa.Table, right: pa.Table) -> None: + assert left.schema.equals(right.schema, check_metadata=True) + assert left.equals(right) + + +# --------------------------------------------------------------------------- +# The first n rows of the sync order +# --------------------------------------------------------------------------- + + +CHAINS: dict[str, Callable[[Any], Any]] = { + "source": lambda s: s(), + "data_tags": lambda s: s(tag_only_columns=False), + "drop_nulls": lambda s: s().drop_nulls(), + "filter": lambda s: s().filter(col("x") >= 9, subject="m2"), + "nothing_left": lambda s: s().filter(col("x") >= 1000), + "columns": lambda s: ( + s() + .map_data({"note": "text"}) + .map_tags({"timestamp": "t"}) + .add_tags(cohort="A") + .drop_tag_columns("subject") + ), + "pass_through": lambda s: s().select_data_columns(["x", "note"]), + "function": lambda s: _Calls().pod(_with_time(s)), + "function_then_filter": lambda s: ( + _Calls().pod(_with_time(s)).filter(col("y") >= 30).map_data({"y": "z"}) + ), + "filter_then_function": lambda s: _Calls().pod(_with_time(s).filter(subject="m1")), + "nothing_to_compute": lambda s: _Calls().pod( + _with_time(s).filter(subject="absent") + ), + "two_functions": lambda s: _on_y(_Calls().pod(_with_time(s)).drop_nulls()), +} + + +def _on_y(stream: Any) -> Any: + @function_pod(output_keys=("half", "label")) + def second(y: int) -> tuple[float, str]: + return y / 2, str(y) + + return second.pod(stream) + + +@pytest.mark.parametrize("n", [1, 3, 12, 39, 40, 41, 500]) +@pytest.mark.parametrize("name", list(CHAINS)) +def test_a_preview_is_the_first_rows_of_the_sync_result( + source: Any, name: str, n: int +) -> None: + """Values, types, nullability, columns and order; and what the view says.""" + stream = CHAINS[name](source) + view = stream.preview(n) + whole = CHAINS[name](source).as_table() + _same(view.as_table(), whole.slice(0, n)) + assert type(view) is StreamView + if whole.num_rows < n: + assert view.status is ViewStatus.ROWS + assert view.total_rows == whole.num_rows + assert f"preview: all {whole.num_rows} row" in view.header() + else: + assert view.status is ViewStatus.PARTIAL + assert view.total_rows is None + assert f"preview: first {n} row" in view.header() + assert "run() computes every row" in str(view) + # Nothing was kept: head() shows what it did before. + assert stream.head(3).header() == CHAINS[name](source).head(3).header() + _ = view._repr_html_() + + +@pytest.mark.parametrize("first", [1, 2, 1024]) +def test_the_batch_sizes_do_not_show( + source: Any, monkeypatch: pytest.MonkeyPatch, first: int +) -> None: + """The size of the first slice is not part of the result.""" + monkeypatch.setattr(preview_module, "FIRST_BATCH_ROWS", first) + stream = source().drop_nulls().filter(subject="m2") + _same(stream.preview(7).as_table(), stream.as_table().slice(0, 7)) + + +WHOLE: dict[str, Callable[[Any], Any]] = { + "join": lambda s: s().join(s().select_data_columns(["x"]).map_data({"x": "x2"})), + "semi_join": lambda s: s().semi_join(s().filter(subject="m1")), + "group_by": lambda s: s().group_by("subject"), + "batch": lambda s: s().batch(3), + "polars_filter": lambda s: s().polars_filter(pl.col("x") > 5), + "tag_by": lambda s: s().drop_nulls().tag_by("note"), + "over_a_group": lambda s: s().group_by("subject").map_data({"x": "xs"}), + "rejoin": lambda s: ( + lambda t: t.select_data_columns(["x"]).rejoin( + t.select_data_columns(["note"]).filter(subject="m2") + ) + )(s()), + "join_after_function": lambda s: ( + lambda t: t.join(s().select_data_columns(["note"])) + )(_Calls().pod(_with_time(s))), + "several": lambda s: ( + s() + .drop_nulls() + .join(s().filter(col("x") >= 9).map_data({"x": "a", "note": "b"})) + .group_by("subject") + ), +} + + +@pytest.mark.parametrize("n", [1, 2, 30, 500]) +@pytest.mark.parametrize("name", list(WHOLE)) +def test_a_step_over_its_whole_input(source: Any, name: str, n: int) -> None: + """Refused; with ``compute_all`` the first rows of the sync result, nothing kept.""" + stream = WHOLE[name](source) + with pytest.raises(PreviewRefusedError, match="compute_all=True"): + stream.preview(n) + view = stream.preview(n, compute_all=True) + whole = WHOLE[name](source).as_table() + _same(view.as_table(), whole.slice(0, n)) + assert stream.head(3).header() == WHOLE[name](source).head(3).header() + + +# --------------------------------------------------------------------------- +# How often a function is called +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("n", [1, 5, 40, 100]) +def test_a_function_is_called_once_per_row_shown(source: Any, n: int) -> None: + """Never on a row past the last one needed; in order; again on the next preview.""" + calls = _Calls() + stream = calls.pod(_with_time(source)) + _ = stream.preview(n) + expected = list(range(min(n, ROWS))) + assert calls.seen == expected + _ = stream.preview(n) + assert calls.seen == expected * 2 + + +def test_a_filter_after_a_function_calls_it_until_enough_rows_pass(source: Any) -> None: + """Rows 10, 11 and 12 pass (``x`` of row 10 is null); the next is not asked for.""" + calls = _Calls() + stream = calls.pod(_with_time(source)).filter(col("y") >= 30).map_data({"y": "z"}) + view = stream.preview(2) + assert view.table.column("z").to_pylist() == [33, 36] + assert calls.seen == list(range(13)) + + +def test_a_filter_before_a_function_spares_the_calls(source: Any) -> None: + """Only rows that pass it reach the function.""" + calls = _Calls() + stream = calls.pod(_with_time(source).filter(subject="m1")) + _ = stream.preview(3) + assert calls.seen == [14, 15, 16] + + +def test_each_function_of_a_chain_is_called_once_per_row(source: Any) -> None: + """The inner one no more often than the outer one needs.""" + inner = _Calls() + outer: list[int] = [] + + @function_pod(output_keys="z") + def second(y: int) -> int: + outer.append(y) + return y + 1 + + _ = second.pod(inner.pod(_with_time(source))).preview(4) + assert inner.seen == [0, 1, 2, 3] + assert len(outer) == 4 + + +def test_a_shared_stream_is_computed_once_by_compute_all(source: Any) -> None: + """Two branches of one function joined: one call per row, not two.""" + calls = _Calls() + shared = calls.pod(_with_time(source)) + joined = shared.join(shared.map_data({"y": "z"})) + view = joined.preview(3, compute_all=True) + assert len(view) == 3 + assert calls.seen == list(range(ROWS)) + + +def test_a_function_over_a_whole_step_is_called_for_the_rows_shown(source: Any) -> None: + """``compute_all`` computes the step beneath in full, not the function above it.""" + seen: list[int] = [] + + @function_pod(output_keys="size") + def count(x: list[int | None]) -> int: + seen.append(len(x)) + return len(x) + + stream = count.pod(source().group_by("subject")) + assert len(stream.preview(2, compute_all=True)) == 2 + assert len(seen) == 2 + + +def test_results_a_stream_holds_are_used(source: Any) -> None: + """After a run nothing is called; after a partial read only the rest is.""" + calls = _Calls() + stream = calls.pod(_with_time(source)) + rows = iter(stream) + _ = [next(rows) for _ in range(3)] + assert calls.seen == [0, 1, 2] + _ = stream.preview(5) + assert calls.seen == [0, 1, 2, 3, 4] + _ = stream.run() + calls.seen.clear() + _same(stream.preview(5).as_table(), stream.as_table().slice(0, 5)) + _ = stream.map_data({"y": "z"}).preview(5) + assert calls.seen == [] + + +def test_no_hook_fires(source: Any) -> None: + """A post-run hook is an effect.""" + fired: list[Any] = [] + calls = _Calls() + pod = calls.pod + pod._post_run_hooks.append(fired.append) # pyright: ignore[reportPrivateUsage] # a registered hook + _ = pod(_with_time(source)).preview(3) + assert calls.seen == [0, 1, 2] + assert fired == [] + + +# --------------------------------------------------------------------------- +# Nothing stored +# --------------------------------------------------------------------------- + + +def _cached_pod(calls: _Calls, store: InMemoryArrowDatabase) -> Any: + return CachedFunctionPod(calls.pod, result_database=store) + + +def _cached_function(calls: _Calls, store: InMemoryArrowDatabase) -> Any: + inner = calls.pod.data_function + return FunctionPod(CachedDataFunction(inner, result_database=store)) # pyright: ignore[reportArgumentType] # conforms at runtime + + +@pytest.mark.parametrize("kind", [_cached_pod, _cached_function]) +def test_a_cached_pod_reads_its_results_and_stores_none( + source: Any, kind: Callable[..., Any] +) -> None: + """Stored results are used, missing ones computed and left out of the store.""" + calls = _Calls() + store = InMemoryArrowDatabase() + stream = kind(calls, store).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + _ = stream.preview(3) + assert calls.seen == [0, 1, 2] + assert store.list_table_paths() == [] + # Rows 0 and 1 stored by an iteration of another stream over the same pod. + other = kind(calls, store).process( + _with_time(source).select_data_columns(["timestamp", "x"]) + ) + rows = iter(other) + _ = [next(rows) for _ in range(2)] + calls.seen.clear() + view = stream.preview(4) + assert calls.seen == [2, 3] + assert view.table.column("y").to_pylist() == [0, 3, 6, 0] + (path,) = store.list_table_paths() + table = store.get_all_records(path) + assert table is not None and table.num_rows == 2 + + +# --------------------------------------------------------------------------- +# The read of a source +# --------------------------------------------------------------------------- + + +def test_the_limit_reaches_the_scan(spiral: Any) -> None: + """Pushed down when every row read is shown; else the scan is closed early.""" + cases: list[tuple[Callable[[Any], Any], int | None, int]] = [ + (lambda s: s, 5, 1), + (lambda s: s.map_data({"note": "text"}).add_tags(a=1), 5, 1), + (lambda s: s.drop_nulls(["x"]), None, 2), + (lambda s: s.filter(subject="m0"), None, 1), + ] + for chain, limit, batches in cases: + stream = chain(spiral()) + assert len(stream.preview(5)) == 5 + (scan,) = fake_spiral_sdk.scan_log + assert scan.limit == limit + assert scan.batches_read <= batches + 1 + assert scan.closed + stream = _Calls().pod(spiral(tag_only_columns=["subject"])) + _ = stream.preview(5) + assert fake_spiral_sdk.scan_log[0].limit == 5 + + +def test_a_source_limit_and_where_hold(spiral: Any) -> None: + """The smaller of the two limits; ``where`` in the scan.""" + view = spiral(limit=3, where={"subject": "m1"}).preview(10) + assert view.status is ViewStatus.ROWS + assert view.table.column("timestamp").to_pylist() == [14, 15, 16] + + +def test_max_rows_holds_only_when_every_row_is_read(spiral: Any) -> None: + """As for ``head``: a table of any size can be looked at.""" + assert len(spiral(max_rows=10).preview(20)) == 20 + with pytest.raises(ValueError, match="max_rows"): + spiral(max_rows=10).group_by("subject").preview(1, compute_all=True) + + +def test_a_refreshed_source_is_read_as_it_is_now(spiral: Any) -> None: + """A result kept before a change is not shown after it.""" + root = spiral(tag_only_columns=["subject"]) + calls = _Calls() + stream = calls.pod(root.filter(subject="m0")).map_data({"y": "z"}) + _ = stream.run() + calls.seen.clear() + changed = _rows().slice(1, 1).set_column(2, "x", pa.array([100], pa.int64())) + fake_spiral_sdk.ExternalProject(_PROJECT).table("default.event").write(changed) + assert stream.preview(2).table.column("z").to_pylist() == [0, 3] # still pinned + assert calls.seen == [] + assert root.check_for_new_data() + assert stream.preview(2).table.column("z").to_pylist() == [0, 300] + assert calls.seen == [0, 1] + + +# --------------------------------------------------------------------------- +# Errors and refusals +# --------------------------------------------------------------------------- + + +def test_an_error_is_raised_only_for_a_row_that_is_needed(source: Any) -> None: + """The function's own error, and nothing is kept; a later row is never reached.""" + calls = _Calls(fail_at=5) + stream = calls.pod(_with_time(source)).map_data({"y": "z"}) + assert len(stream.preview(5)) == 5 + with pytest.raises(RuntimeError, match="failed at 5"): + stream.preview(6) + assert calls.seen == [*range(5), *range(6)] + assert stream.head().status is ViewStatus.NOT_COMPUTED + + +def test_a_source_error_is_raised_only_when_reached( + spiral: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """The scan is closed after an error, too.""" + original = SpiralDBTableSource._key_tokens # pyright: ignore[reportPrivateUsage] # a failing row + + def failing(self: Any, table: pa.Table) -> list[str]: + if 20 in table.column("timestamp").to_pylist(): + raise RowIdentifierError("bad key") + return original(self, table) + + monkeypatch.setattr(SpiralDBTableSource, "_key_tokens", failing) + stream = spiral().drop_nulls(["x"]) + assert len(stream.preview(5)) == 5 + with pytest.raises(RowIdentifierError, match="bad key"): + stream.preview(30) + assert all(scan.closed for scan in fake_spiral_sdk.scan_log) + + +def test_what_would_act_is_refused_before_any_call(source: Any) -> None: + """Side effects, the invocation context, polls and cache writes; compute_all or not.""" + calls = _Calls() + delivered: list[int] = [] + + def deliver(y: int, ctx: Any) -> None: + delivered.append(y) + + @function_pod(output_keys="w", ctx_arg="ctx") + def act(y: int, ctx: Any) -> int: + delivered.append(y) + return y + + computed = calls.pod(_with_time(source)) + store = InMemoryArrowDatabase() + fake = _FakeDynamicSource() + refused = [ + SideEffectPod(deliver)(computed), + act.pod(computed), + MapData({"w": "v"})(act.pod(computed)), + CachedSource(source(), cache_database=store), + PollingSource(fake, tag_columns="id", record_id_columns="id"), + ] + for stream in refused: + for compute_all in (False, True): + with pytest.raises( + PreviewRefusedError, match=r"run\(\) computes every row" + ): + stream.preview(2, compute_all=compute_all) + assert (calls.seen, delivered) == ([], []) + assert store.list_table_paths() == [] + assert (fake.polls, fake.fetches) == (0, 0) + + +def test_a_derived_source_is_read_whole(source: Any) -> None: + """Refused, since its origin may compute; allowed by ``compute_all``.""" + derived = DerivedSource( + source(), tags_as_data={"timestamp": "time"}, source_id="derived" + ) + with pytest.raises(PreviewRefusedError, match="compute_all"): + derived.preview(3) + _same( + derived.preview(3, compute_all=True).as_table(), derived.as_table().slice(0, 3) + ) + + +def test_nodes_are_refused(source: Any) -> None: + """Every node of a job, run or not, and a stream over one.""" + calls = _Calls() + job = PipelineJob(name="itl1464", database=InMemoryArrowDatabase()) + with job: + _ = calls.pod(_with_time(source), label="triple").map_data( + {"y": "z"}, label="renamed" + ) + nodes = list(job.nodes.values()) + for node in nodes: + with pytest.raises(PreviewRefusedError): + node.preview(1) + _ = job.run() + calls.seen.clear() + for node in nodes: + with pytest.raises(PreviewRefusedError): + node.preview(1, compute_all=True) + with pytest.raises(PreviewRefusedError): + job.nodes["triple"].map_data({"y": "q"}).preview(1) + assert calls.seen == [] + + +@pytest.mark.parametrize( + ("n", "error"), + [(0, ValueError), (-1, ValueError), (2.0, TypeError), (True, TypeError)], +) +def test_the_number_of_rows_is_checked(source: Any, n: Any, error: Any) -> None: + """Before anything is read.""" + with pytest.raises(error): + source().preview(n) + + +def test_an_inactive_function_gives_no_row(source: Any) -> None: + """No limit is pushed down, every row is looked at, and the view says so.""" + calls = _Calls() + function = calls.pod.data_function + assert isinstance(function, PythonDataFunction) + function.set_active(False) + view = calls.pod(_with_time(source)).preview(3) + assert (len(view), view.status, calls.seen) == (0, ViewStatus.ROWS, []) From 5a86f45a4a2a828307f94c61552ceea888b6da15 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 03:22:08 -0800 Subject: [PATCH 3/3] perf(streams): a view's display reads only the rows it shows; a job node's view over its kept run (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-views.md | 9 +++ src/orcapod/core/streams/view.py | 61 +++++++------- tests/test_core/operators/test_row_chunks.py | 45 +++++++++++ .../streams/test_view_display_frame.py | 79 +++++++++++++++++++ 4 files changed, 167 insertions(+), 27 deletions(-) create mode 100644 tests/test_core/streams/test_view_display_frame.py diff --git a/docs/dev/specs/itl-1464-views.md b/docs/dev/specs/itl-1464-views.md index 0e6f9bc66..3480e936a 100644 --- a/docs/dev/specs/itl-1464-views.md +++ b/docs/dev/specs/itl-1464-views.md @@ -173,3 +173,12 @@ the graph: settling a stream asks for the states beneath it, and so does its own - 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`. + +## Job nodes, as built + +An operator job node's `run()` view is the table its current run is kept in (memory-mapped +when large), so it holds every row, refuses nothing, and equals +`read_current_run(0, current_run_row_count())`. Cutting it touches only the pages of the rows +cut; it stays valid after the node is cleared, which paging through the node would not. The +display of any long view now gives Polars the eleven rows it needs, not the whole table. A +function job node and a source job node still hold their rows in memory. diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index ce5c333ec..9b92cc4ee 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -575,32 +575,30 @@ def _display_frame(self, text: bool = False) -> pl.DataFrame: never changed.""" columns_shown = self._display_columns() table = self.table.select([name for name, _ in columns_shown]) - rows = table.num_rows half = _DISPLAY_ROWS // 2 - # Only the rows the display shows are summarised; the others are left null, - # because Polars shows the first and last ``half`` of a long frame only. - shown = ( - table - if self._displays_every_row() - else pa.concat_tables([table.slice(0, half), table.slice(rows - half)]) - ) + # Only the rows the display shows are read: of a long view the first and the last + # ``half``, and one more between them, where Polars renders its ellipsis. The + # view of a job node may be a memory-mapped file (ITL-1464). + ends: list[pa.Table] = [] + if not self._displays_every_row(): + ends = [ + table.slice(0, half), + table.slice(half, 1), + table.slice(table.num_rows - half), + ] + table = pa.concat_tables(ends) + shown = pa.concat_tables([ends[0], ends[2]]) if ends else table columns = [] for name in table.column_names: summary = _summarise(shown.column(name)) if summary is None: columns.append(table.column(name)) - elif shown is table: - columns.append(pa.chunked_array([summary], type=pa.large_string())) - else: - columns.append( - pa.chunked_array( - [ - pa.array(summary[:half], type=pa.large_string()), - pa.nulls(rows - 2 * half, type=pa.large_string()), - pa.array(summary[half:], type=pa.large_string()), - ] - ) - ) + continue + if ends: + summary = [*summary[:half], None, *summary[half:]] + columns.append( + pa.chunked_array([pa.array(summary, type=pa.large_string())]) + ) names = list(table.column_names) if text: marked = [ @@ -616,8 +614,20 @@ def _display_frame(self, text: bool = False) -> pl.DataFrame: return pl.DataFrame(pa.table(columns, names=names)) def _with_row_count(self, rendered: str) -> str: - """Return Polars' rendering of the display frame, which names its row count.""" - return rendered + """Return Polars' rendering of the display frame, naming the view's row count. + + The frame of a long view has one row more than the display shows. Polars names + the frame's shape before anything else it renders. + """ + if self._displays_every_row(): + return rendered + return rendered.replace( + f"shape: ({_DISPLAY_ROWS + 1:_}, ", f"shape: ({self._row_count():_}, ", 1 + ) + + def _row_count(self) -> int: + """The rows of the view, as its display names them.""" + return self.table.num_rows def _displays_every_row(self) -> bool: """Whether the display shows every row: a view cut to ``n`` rows, or a short one.""" @@ -708,11 +718,8 @@ class _EndsView(StreamView): shown_total: int = 0 @override - def _with_row_count(self, rendered: str) -> str: - # Polars names the frame's shape before anything else it renders. - return rendered.replace( - f"shape: ({self.table.num_rows:_}, ", f"shape: ({self.shown_total:_}, ", 1 - ) + def _row_count(self) -> int: + return self.shown_total class BoundedStreamView(StreamView): diff --git a/tests/test_core/operators/test_row_chunks.py b/tests/test_core/operators/test_row_chunks.py index 762e032c0..2720fd525 100644 --- a/tests/test_core/operators/test_row_chunks.py +++ b/tests/test_core/operators/test_row_chunks.py @@ -30,6 +30,7 @@ from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.sources import ArrowTableSource +from orcapod.streams import StreamView from orcapod.utils import arrow_utils _ROWS = 11 @@ -929,3 +930,47 @@ def test_a_finished_async_run_leaves_no_file_either( _ = job.run(orchestrator=AsyncPipelineOrchestrator()) assert not _spool_files(spilled) assert job.nodes["out"].as_table().num_rows == 3 + + +@pytest.mark.parametrize("orchestrator", ["sync", "async", "node"]) +@pytest.mark.parametrize("on_disk", [False, True], ids=["in_memory", "on_disk"]) +def test_a_job_nodes_run_view_is_its_current_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, orchestrator: str, on_disk: bool +) -> None: + """The view pages through the rows the node keeps; nothing is refused, whatever the + size, and it stays valid once the node lets its rows go (ITL-1464).""" + monkeypatch.setattr(static_output_pod, "ROW_CHUNK_ROWS", 3) + monkeypatch.setattr("orcapod.core.streams.view.RUN_VIEW_COMPLETE_ROWS", 1) + monkeypatch.setattr("orcapod.core.streams.view.RUN_VIEW_WINDOW_ROWS", 0) + if on_disk: + monkeypatch.setattr(static_output_pod, "KEPT_ROWS_MEMORY_BYTES", 0) + monkeypatch.setattr("tempfile.tempdir", str(tmp_path)) + job = _job(tmp_path, "viewed", "map", False) + node = job.nodes["out"] + if orchestrator == "sync": + _ = job.run() + elif orchestrator == "async": + _ = job.run(orchestrator=AsyncPipelineOrchestrator()) + view = node.run() + + assert type(view) is StreamView + assert view.total_rows == len(view) == node.current_run_row_count() == _ROWS + whole = node.as_table() + page = node.read_current_run(0, _ROWS) + assert page is not None + assert view.as_table().equals(whole) + assert view.as_table().equals(page) + assert view.head(4).table.equals(node.read_current_run(0, 4)) + assert view.tail(4).table.equals(node.read_current_run(_ROWS - 4, 4)) + assert view.sort_by_tags().table.equals( + node.as_table(columns={"sort_by_tags": True}) + ) + assert node.head(3).header() == view.head(3).header() + + shown, html = str(view), view._repr_html_() + expected = whole.to_pylist() + node.clear_cache() + assert view.as_table().to_pylist() == expected + assert (str(view), view._repr_html_()) == (shown, html) + # A cleared node pages no row; the view is a snapshot of the run it was given. + assert node.read_current_run(0, 4) is None diff --git a/tests/test_core/streams/test_view_display_frame.py b/tests/test_core/streams/test_view_display_frame.py new file mode 100644 index 000000000..1c847647e --- /dev/null +++ b/tests/test_core/streams/test_view_display_frame.py @@ -0,0 +1,79 @@ +"""The display of a long view reads the rows it shows only, and renders as Polars renders +the whole table (ITL-1464).""" + +from __future__ import annotations + +import datetime as dt +import uuid +from typing import Any +from unittest import mock + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams import view as view_module + + +def _table(rows: int, wide: bool) -> pa.Table: + """Values whose width differs along the rows, a middle row the widest.""" + columns: dict[str, Any] = { + "i": [10**9 if i == rows // 2 else i for i in range(rows)], + "f": [i / 7 if i % 3 else float(i) for i in range(rows)], + "t": ["x" * (70 if i == rows // 2 else i % 9) for i in range(rows)], + "n": [None if i % 4 else i for i in range(rows)], + "b": [i % 2 == 0 for i in range(rows)], + "d": [dt.datetime(2026, 1, 1) + dt.timedelta(hours=i) for i in range(rows)], + "l": [[i] * (i % 3) for i in range(rows)], + "s": [{"a": i} for i in range(rows)], + } + if wide: + columns |= {f"c{k}": list(range(rows)) for k in range(12)} + return pa.table(columns) + + +@pytest.mark.parametrize("wide", [False, True]) +@pytest.mark.parametrize("rows", [1, 10, 11, 12, 25, 1_000, 1_234]) +def test_a_view_renders_as_polars_renders_the_whole(rows: int, wide: bool) -> None: + """Text and HTML: the shape line, the widths, the ellipsis and every shown cell.""" + stream = ArrowTableStream(_table(rows, wide), tag_columns=[]) + table = stream.as_table() + limit = 10 if rows > 10 else -1 + with pl.Config(fmt_str_lengths=80, tbl_rows=limit): + whole = pl.DataFrame(table) + text, html = str(whole), whole._repr_html_() + assert str(stream.run()).endswith(text) + with mock.patch.object(view_module, "_mark_columns", lambda frame, *_: frame): + assert stream.run()._repr_html_().endswith(html) + + +def test_a_summarised_column_renders_its_shown_cells() -> None: + """Long text, bytes, lists and a logical type, at the ends; the middle is not read.""" + rows = 200 + table = pa.table( + { + "text": [f"{i:03d}" + "a" * 200 for i in range(rows)], + "raw": [bytes(i % 9) for i in range(rows)], + "many": [list(range(20)) for _ in range(rows)], + "id": pa.ExtensionArray.from_storage( + pa.uuid(), + pa.array([uuid.UUID(int=i).bytes for i in range(rows)], pa.binary(16)), + ), + } + ) + view = ArrowTableStream(table, tag_columns=[]).run() + text = str(view) + assert "shape: (200, 4)" in text + for shown in (0, 4, 195, 199): + assert f"{shown:03d}aaa" in text + for left_out in (5, 100, 194): + assert f"{left_out:03d}aaa" not in text + assert "(200, 4)" in view._repr_html_() + + +def test_a_long_view_gives_polars_the_rows_it_shows() -> None: + """One row more than the display: never the table.""" + view = ArrowTableStream(_table(5_000, False), tag_columns=[]).run() + assert view._display_frame().height == 11 + assert view.head(25)._display_frame().height == 25