Skip to content
7 changes: 7 additions & 0 deletions changelog.d/ITL-1464.md
Original file line number Diff line number Diff line change
@@ -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

- A `SpiralDBTableSource` read whose table holds no source-info column and no content hash
Expand Down
26 changes: 26 additions & 0 deletions docs/concepts/streams.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()` |
Expand Down
28 changes: 27 additions & 1 deletion docs/dev/specs/itl-1464-views.md
Original file line number Diff line number Diff line change
@@ -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.

Expand Down Expand Up @@ -156,3 +156,29 @@ 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`.

## 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.
20 changes: 19 additions & 1 deletion src/orcapod/core/cached_function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
import logging
from datetime import datetime, timezone
from collections.abc import Iterator
from typing import ClassVar, TYPE_CHECKING, Any
from typing import ClassVar, TYPE_CHECKING, Any, cast

from orcapod.core.unique_keys import UniqueKeys
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,
Expand Down Expand Up @@ -305,6 +306,23 @@ 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, 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."""
self.require_preview()
stored = self.lookup_cached_data(data)
if stored is not None:
return stored
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})

def _invoke_with_hooks(
self,
tag: TagProtocol,
Expand Down
127 changes: 125 additions & 2 deletions src/orcapod/core/function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ClassVar, TYPE_CHECKING, Any, Literal, Protocol, cast

Expand All @@ -30,14 +38,21 @@
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,
ViewStatus,
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,
Expand Down Expand Up @@ -371,6 +386,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,
Expand Down Expand Up @@ -954,6 +991,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."""
Expand Down Expand Up @@ -1782,6 +1834,67 @@ 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.

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,
Expand Down Expand Up @@ -2146,6 +2259,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
Expand Down
9 changes: 9 additions & 0 deletions src/orcapod/core/nodes/source_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,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,
Expand Down Expand Up @@ -1298,6 +1299,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).

Expand Down
54 changes: 54 additions & 0 deletions src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,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 (
BoundedStreamView,
RunSize,
Expand Down Expand Up @@ -2646,6 +2652,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``).

Expand Down
Loading
Loading