Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog.d/ITL-1464.md
Original file line number Diff line number Diff line change
@@ -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`,
Expand Down
34 changes: 34 additions & 0 deletions docs/concepts/streams.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()` |
Expand Down
27 changes: 25 additions & 2 deletions 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 @@ -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.
Expand Down Expand Up @@ -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`.
40 changes: 40 additions & 0 deletions src/orcapod/core/cached_function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand Down
76 changes: 76 additions & 0 deletions src/orcapod/core/data_function.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations


import inspect
import io
import logging
Expand Down Expand Up @@ -30,6 +31,7 @@
from orcapod.core.result_cache import ResultCache
from orcapod.errors import (
NoOutputsDeclaredError,
PreviewRefusedError,
OutputTypeError,
UnstorableDatetimeError,
)
Expand Down Expand Up @@ -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``)."""
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
54 changes: 54 additions & 0 deletions src/orcapod/core/data_function_preview.py
Original file line number Diff line number Diff line change
@@ -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
31 changes: 31 additions & 0 deletions src/orcapod/core/data_function_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
Loading
Loading