diff --git a/changelog.d/ITL-1776.md b/changelog.d/ITL-1776.md index 642e4af08..80414f6db 100644 --- a/changelog.d/ITL-1776.md +++ b/changelog.d/ITL-1776.md @@ -6,5 +6,4 @@ it keeps. Every tag column, every key column and the columns of a `where` condition are still read. The result, its hashes, schema, record ids and stored paths are those of the whole read followed by the selection. On a table with a - wide column the read is several times faster. A job still reads each SpiralDB - source whole. + wide column the read is several times faster. diff --git a/changelog.d/ITL-1798.md b/changelog.d/ITL-1798.md new file mode 100644 index 000000000..e8f45a12c --- /dev/null +++ b/changelog.d/ITL-1798.md @@ -0,0 +1,21 @@ +### Changed + +- In a pipeline job, a `SpiralDBTableSource` node read only by column selections + (`select_data_columns` or `select_columns` directly on the source, including the + automatic selection before a function pod) now scans only the columns those + selections keep: the union, when several selections read it. Every tag column, every + key column and the columns of a `where` condition are still read. This holds for + `job.run()`, `job.run_async()`, load-only runs and a node's own `run()`; on + `job.run_async()` the narrowed rows are read and sent batch by batch, as a whole + read's are, so the first row reaches the next step before the scan ends and one + batch is held at a time. Any other + step directly on the source (a drop, a join, a function pod taking every column) + means the whole table is read, as before. The job's rows, stored rows, hashes, + schemas, record ids and stored paths are those of the whole read, and an + orchestrator's collected output for the source node (`node_outputs`) is the whole + node's. Reading that collected output whole (its table, its rows, or any column the + selections left out) reads the source again, whole, on first use, and so transfers + the columns the selections omit; that read is of the version the run used, as + before, also after a later check or run has pinned a newer one. Describing the + collected output (its keys, schemas, hashes, `explain()`, a `head(0)` that asks for no row hash) reads nothing, + and a step built on it reads only when its own rows are read. On a table with a wide column, a narrow job is several times faster. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 175544fe1..82926a1d4 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -653,8 +653,21 @@ selection a function pod adds before itself for columns it does not take) asks S the columns it keeps, so a wide column it drops (images, long arrays) is never transferred. Every tag column, every key column and the columns of a `where` condition are still read. This is only how the rows are read: the result, its hashes, schema and record ids are those -of the whole read followed by the selection. For now it applies to a stream read outside a -job; a pipeline job reads each SpiralDB source whole. +of the whole read followed by the selection. In a pipeline job, a source node reads only +the columns its steps keep when every step that reads it directly is a `select_data_columns` +or `select_columns` (several such steps read the union of their columns); any other step on +the source (a drop, a join, a function pod given the source's every column) means the whole +table is read. With `run_async()`, the narrowed rows are read and sent batch by batch, as a +whole read's are: the first row reaches the next step before the scan ends, and one batch +is held at a time. The job's rows, stored rows, hashes and stored paths are the same either way. +The source node's own output, as an orchestrator collects it (`node_outputs`), still stands +for every column: reading it whole (its `as_table()`, its rows, or any read that needs the +columns the selections left out) reads the source again, whole, the first time, and so +transfers those columns after all. That read is of the version the run used, also after +a later check or run has pinned a newer version, so it gives the rows a whole read gave +when the run made the output. Describing that output reads nothing: its keys, schemas, +hashes, `explain()` and a `head(0)` that asks for no row hash, and a step built on it reads only when its own rows +are read. **The row cap.** One read returns at most `max_rows` rows (default 100,000). A read that would return more raises `SourceTooLargeError`, which says so and gives the ways out: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index c15a541d6..7c0c1db3c 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -8,6 +8,7 @@ from __future__ import annotations +import asyncio import contextlib import dataclasses import functools @@ -15,7 +16,15 @@ import logging import weakref from abc import ABC, abstractmethod -from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence +from collections.abc import ( + AsyncIterator, + Callable, + Collection, + Iterator, + Mapping, + Sequence, +) +from concurrent.futures import ThreadPoolExecutor from datetime import datetime from typing import TYPE_CHECKING, Any @@ -76,8 +85,10 @@ if TYPE_CHECKING: from orcapod.channels import WritableChannel + from orcapod.core.output_bindings import OutputBindings + from orcapod.core.streams.arrow_table_stream import WholeRead from orcapod.pipeline.job import PipelineJob - from orcapod.protocols.core_protocols import StreamProtocol + from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, ) @@ -1407,6 +1418,7 @@ def execute( self, *, observer: ExecutionObserverProtocol | None = None, + read_columns: Collection[str] | None = None, ) -> StreamProtocol: """Execute this source node: read its source once and return its output stream. @@ -1417,6 +1429,13 @@ def execute( Args: observer: Optional execution observer. + read_columns: The data columns every successor reads, when the + orchestrator knows them (``pipeline.column_demand``, ITL-1798); ``None`` + reads every column. A source that can scan fewer columns reads only + these (and every tag and key column), and the output is the whole + read's own stream, its rows read whole when first read + (``whole_on_read``). An execution detail: no hash, schema, record id + or stored row depends on it. Returns: The node's output stream. @@ -1424,11 +1443,6 @@ def execute( Raises: UnboundSourceError: When no concrete data is available. """ - from orcapod.core.operators.static_output_pod import ( - RowBuiltFormUnavailable, - StaticOutputOperatorPod, - rows_on_read, - ) from orcapod.core.output_bindings import capture_output_bindings bindings = capture_output_bindings(self) @@ -1436,31 +1450,100 @@ def execute( node_hash = graph_hash(self).to_string() if observer is not None: observer.on_node_start(node_label, node_hash) + result = None + if read_columns is not None: + result = self._projected_output(read_columns, bindings) + if result is None: + result = self._whole_output(bindings) + if observer is not None: + observer.on_node_end(node_label, node_hash) + return result + + def _whole_output(self, bindings: OutputBindings) -> StreamProtocol: + """This node's output, its source read whole (``execute``). + + Args: + bindings: The bindings at production. + """ + from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + rows_on_read, + ) + # The table and keys of this node's rows, when F of the table is provably the # rows' own table; otherwise (a narrower bind) the rows, built when read. rows_table = self._rows_table() - result: StreamProtocol if rows_table is None: - result = rows_on_read(self.iter_data(), self, bindings=bindings) - else: - table, keys = rows_table - try: - result = StaticOutputOperatorPod._output_stream( - table, keys, self, bindings=bindings - ) - except RowBuiltFormUnavailable: - # The rows decide (read once, here), built when read, as on main. - result = rows_on_read(self.iter_data(), self, bindings=bindings) - if observer is not None: - observer.on_node_end(node_label, node_hash) - return result + return rows_on_read(self.iter_data(), self, bindings=bindings) + table, keys = rows_table + try: + return StaticOutputOperatorPod._output_stream( + table, keys, self, bindings=bindings + ) + except RowBuiltFormUnavailable: + # The rows decide (read once, here), built when read, as on main. + return rows_on_read(self.iter_data(), self, bindings=bindings) + + def _projected_output( + self, read_columns: Collection[str], bindings: OutputBindings + ) -> StreamProtocol | None: + """This node's output read with only ``read_columns`` of its data, or ``None``. + + The output is main's own (``_output_stream``), its rows read whole when first + read (``whole_on_read``), or, with no row, the narrowed read's zero-row output. + + Args: + read_columns: The data columns the node's successors read. + bindings: The bindings at production. + """ + from orcapod.core.operators.static_output_pod import whole_on_read + + projected = self._projected_read(read_columns, bindings) + if projected is None: + return None + narrow, loader = projected + if loader is None: + return narrow + return whole_on_read(self, loader, bindings=bindings) + + def _projected_read( + self, read_columns: Collection[str], bindings: OutputBindings + ) -> tuple[StreamProtocol, WholeRead | None] | None: + """The narrowed read and the node's whole read, or ``None``: read whole. + + ``None`` here: a node that carries no data of its own is read whole. A bound + job node whose source can scan fewer columns reads only those (ITL-1798). + + Args: + read_columns: The data columns the node's successors read. + bindings: The bindings at production. + """ + return None + + def _projected_batches( + self, read_columns: Collection[str], bindings: OutputBindings + ) -> tuple[Iterator[StreamProtocol], Callable[[int], WholeRead]] | None: + """The narrowed read in batches and the way to the node's whole read, or ``None``. + + The async route's form of ``_projected_read``: the streams are read as they + are asked for, one batch held at a time; the second member makes the node's + whole read (``WholeRead``) from the row count sent. ``None`` here: a node that + carries no data of its own is read whole. + + Args: + read_columns: The data columns the node's successors read. + bindings: The bindings at production. + """ + return None async def async_execute( self, output: "WritableChannel[tuple[TagProtocol, DataProtocol]]", *, observer: ExecutionObserverProtocol | None = None, - ) -> None: + read_columns: Collection[str] | None = None, + ) -> StreamProtocol | None: """Push all (tag, data) pairs to the output channel. Delegates to ``async_iter_data`` so that dynamic sources @@ -1470,19 +1553,53 @@ async def async_execute( Args: output: Channel to write results to. observer: Optional execution observer. + read_columns: As for ``execute`` (ITL-1798): a source that can scan fewer + columns reads only these and sends the rows of that read, each + without the unread data columns, which every successor drops. They + are read and sent batch by batch, off the event loop, as the whole + read's are (``async_iter_data``). + + Returns: + The node's whole output when the rows sent are a narrowed read's (main's + ``RowsOnRead``, its rows read whole when first read: ``rows_on_read_of``): + the node's output is that, never the narrowed rows sent, so a caller that + collects the node's output takes it in their place. ``None`` when the + rows sent are the node's whole output. Raises: UnboundSourceError: When no concrete data is available. """ + from orcapod.core.operators.static_output_pod import rows_on_read_of + from orcapod.core.output_bindings import capture_output_bindings + node_label = self.label try: node_hash = graph_hash(self).to_string() if observer is not None: observer.on_node_start(node_label, node_hash) - async for tag, data in self.async_iter_data(): - await output.send((tag, data)) + projected = None + whole: StreamProtocol | None = None + if read_columns is not None: + bindings = capture_output_bindings(self) + projected = await asyncio.to_thread( + self._projected_batches, read_columns, bindings + ) + if projected is not None: + streams, whole_read = projected + sent = await _send_batches(streams, output) + if sent: + # Collected as this route collects a node's output: its rows, + # read whole when first read. With no row, the rows sent + # (none) are the node's output, as for the whole read. + whole = rows_on_read_of( + self, whole_read(sent), bindings=bindings + ) + if projected is None: + async for tag, data in self.async_iter_data(): + await output.send((tag, data)) if observer is not None: observer.on_node_end(node_label, node_hash) + return whole finally: await output.close() @@ -2093,6 +2210,182 @@ def _rows_table( return None return table, keys_of_rows(table, source.keys()) + def _projected_read( + self, read_columns: Collection[str], bindings: OutputBindings + ) -> tuple[StreamProtocol, WholeRead | None] | None: + """The bound source read with only ``read_columns`` of its data (ITL-1798). + + Only where the whole read takes the table route (``_rows_table``) and the + source can scan fewer columns (``SourceProtocol.projected_table``): the + narrowed table goes through the same F as the whole one. The whole read + (``WholeRead``) is made when the output's rows are first read; a column + selection on the output takes the narrowed table in its place. With no row, + the narrowed read's output is the node's zero-row output, as for the whole + read, and there is no whole read to make. + + Only over a snapshot of the source at its pinned version + (``SourceProtocol.pinned_snapshot``): the narrowed rows are read from it now + and the whole rows, when read, from the same snapshot, so they are always of + the version the run used, as the whole output held when produced is, also + after a later check or run pins a newer version on the source. A kind that + keeps no version is read whole. + + Args: + read_columns: The data columns the node's successors read. + bindings: The bindings at production. + + Returns: + The narrowed read's output and the whole read (``None`` with no row), or + ``None``: the node is read whole. + """ + from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + at_edge, + ) + from orcapod.core.streams.arrow_table_stream import ArrowTableStream, WholeRead + + found = self._projection_snapshot() + if found is None: + return None + source, snapshot, zero_rows = found + table = snapshot.projected_table(read_columns, columns=ZERO_ROW_INPUT_COLUMNS) + if table is None: + return None + if not system_tags_as_rows_give(table): + return None + source_keys = source.keys() + names = set(table.column_names) + narrow_keys = keys_of_rows( + table, + (source_keys[0], tuple(c for c in source_keys[1] if c in names)), + ) + try: + narrow = StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, as the whole read + table, narrow_keys, self, bindings=bindings + ) + except RowBuiltFormUnavailable: + return None + if table.num_rows == 0: + # The node's zero-row output: what the whole read hands on with no row. + return narrow, None + assert isinstance(narrow, ArrowTableStream) + + def whole() -> ArrowTableStream: + # The whole read, of the snapshot the narrowed rows were read from, as a + # table (rows the row-built form refuses are built here, as at an edge). + stream = at_edge(self._whole_output_of(snapshot, bindings)) + assert isinstance(stream, ArrowTableStream) + return stream + + return narrow, WholeRead( + whole, narrow, keys_of_rows(zero_rows, source_keys), table.num_rows + ) + + def _projected_batches( + self, read_columns: Collection[str], bindings: OutputBindings + ) -> tuple[Iterator[StreamProtocol], Callable[[int], WholeRead]] | None: + """The bound source read with only ``read_columns``, in batches (ITL-1798). + + The async route's projected read: the snapshot's batches + (``SourceProtocol.projected_batch_streams``), each the rows the whole read's + batch gives (``async_iter_data``) without the unread data columns, read as + they are asked for. The node's whole read (``WholeRead``) is of the same + snapshot, as for ``_projected_read``; it keeps no narrowed read. + + Args: + read_columns: The data columns the node's successors read. + bindings: The bindings at production. + + Returns: + The batches and the way to the whole read (from the row count sent), or + ``None``: the node is read whole. + """ + from orcapod.core.operators.static_output_pod import at_edge + from orcapod.core.streams.arrow_table_stream import ArrowTableStream, WholeRead + + found = self._projection_snapshot() + if found is None: + return None + source, snapshot, zero_rows = found + streams = snapshot.projected_batch_streams(read_columns) + if streams is None: + return None + keys = keys_of_rows(zero_rows, source.keys()) + + def whole() -> ArrowTableStream: + # As ``_projected_read``'s: the snapshot read whole, as a table. + stream = at_edge(self._whole_output_of(snapshot, bindings)) + assert isinstance(stream, ArrowTableStream) + return stream + + return streams, lambda num_rows: WholeRead(whole, None, keys, num_rows) + + def _projection_snapshot( + self, + ) -> tuple[SourceProtocol, SourceProtocol, pa.Table] | None: + """The bound source, its snapshot at its pinned version and its zero-row + table, when a projected read may be made of it; ``None``: read whole. + + Only where the whole read takes the table route (``_rows_table``) and the + source keeps a version (``SourceProtocol.pinned_snapshot``): both reads, the + narrowed one now and the whole one when asked, are of the version the run + uses, whatever a later check pins on the source. A kind that cannot keep a + version is read whole now, as on main. + """ + from orcapod.protocols.core_protocols import SourceProtocol + + if not reads_as_its_class(self, SourceJobNode): + return None + source = self._bound_stream() + if ( + source is None + or self._declared_form is not None + or not isinstance(source, SourceProtocol) + or not table_is_rows(source) + or source.data_context_key != self.data_context_key + ): + # As ``_rows_table``: the whole read decides (and raises when unbound). + return None + zero_rows = typed_zero_row_table(source) + if zero_rows is None: + return None + snapshot = source.pinned_snapshot() + if snapshot is None: + return None + return source, snapshot, zero_rows + + def _whole_output_of( + self, snapshot: SourceProtocol, bindings: OutputBindings + ) -> StreamProtocol: + """This node's whole output read from ``snapshot`` (a projected output's). + + ``_whole_output`` over the snapshot in place of the bound source: the same + table route, and the same rows when the row-built form decides, read at the + snapshot's version. ``_projected_read`` has checked what ``_rows_table`` + checks of the source (class, declared form, kind, data context). + + Args: + snapshot: The source at the version the narrowed rows were read at. + bindings: The bindings at production. + """ + from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + rows_on_read, + ) + + table = snapshot.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + if system_tags_as_rows_give(table): + try: + return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, as the whole read + table, keys_of_rows(table, snapshot.keys()), self, bindings=bindings + ) + except RowBuiltFormUnavailable: + pass + # The rows decide, as on main. + return rows_on_read(snapshot.iter_data(), self, bindings=bindings) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. @@ -2419,3 +2712,36 @@ def as_node(self) -> SourceNode: ) node._take_saved_state_of(self) return node + + +async def _send_batches( + streams: Iterator[StreamProtocol], + output: "WritableChannel[tuple[TagProtocol, DataProtocol]]", +) -> int: + """Send the rows of ``streams`` to ``output``, each batch read off the event loop. + + As ``SpiralDBTableSource.async_iter_data`` reads a whole source: one thread owns + the reader for its whole life, a batch is read only when the previous one's rows + were sent, and when the sending stops or is cancelled that thread closes the + reader, after a read in progress has ended (ITL-1798). + + Returns: + The number of rows sent. + """ + owner = ThreadPoolExecutor(max_workers=1, thread_name_prefix="source-read") + loop = asyncio.get_running_loop() + sent = 0 + try: + while True: + stream = await loop.run_in_executor(owner, next, streams, None) + if stream is None: + break + for pair in stream.iter_data(): + await output.send(pair) + sent += 1 + finally: + close = getattr(streams, "close", None) + if close is not None: + _ = owner.submit(close) + owner.shutdown(wait=False) + return sent diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 266bd4551..79b594304 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -9,7 +9,10 @@ from orcapod.core.data_tags import stream_data_tags, warn_materialized from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + pending_whole_read, +) from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( DataProtocol, @@ -43,13 +46,19 @@ def _input_table( """Return the input's table for a column selection that keeps ``kept_data``. A source that can scan fewer columns (``SourceProtocol.projected_table``) - reads only those the selection keeps (ITL-1776); any other input is read - whole. The selection keeps its own rule: it decides what to keep from the - whole input's keys and drops the removed columns that are present, so its + reads only those the selection keeps (ITL-1776), and so does a source node's + output in a job read with fewer columns, until its rows are read + (``pending_whole_read``, ITL-1798); any other input is read whole. The + selection keeps its own rule: it decides what to keep from the whole input's keys and drops the removed columns that are present, so its result, identity and route are those of the whole read (a narrowed input stream would instead meet the "nothing to drop" shortcut). """ - if isinstance(stream, SourceProtocol): + whole_read = pending_whole_read(stream) + if whole_read is not None: + projected = whole_read.projected_table(kept_data, columns=columns) + if projected is not None: + return projected + elif isinstance(stream, SourceProtocol): projected = stream.projected_table(kept_data, columns=columns) if projected is not None: return projected diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f673b7447..f41272d4f 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -57,6 +57,7 @@ ) from orcapod.core.streams.arrow_table_stream import ( ArrowTableStream, + WholeRead, ) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -1449,6 +1450,10 @@ class RowsOnRead(MaterializedOutput): # Not a stream the row-built form already made: a channel opened on it reads it. _orcapod_row_built_output = False + # A projected source node's output (ITL-1798): its rows are this whole read's, + # made when they are first read (``rows_on_read_of``). + _row_loader: WholeRead | None = None + def __init__( self, rows: Iterable[tuple[TagProtocol, DataProtocol]], @@ -1475,9 +1480,17 @@ def built(self) -> StreamProtocol: self._require_current_output() if self._stream is None: refuse_identity_io("this stream requires materializing rows") - stream = StaticOutputOperatorPod._materialize_upstream( - self._rows, self._node - ) + # Read once: a concurrent ``iter_data`` clears it after taking the rows. + loader = self._row_loader + if loader is not None: + # Rows not read yet: the stream reads them on its first row access. + stream = whole_on_read( + self._node, loader, bindings=self._output_bindings + ) + else: + stream = StaticOutputOperatorPod._materialize_upstream( + self._rows, self._node + ) assert isinstance(stream, ArrowTableStream) stream._output_bindings = self._output_bindings # pyright: ignore[reportPrivateUsage] # The view represents these same rows. self._stream = stream @@ -1495,6 +1508,12 @@ def release_built(self) -> None: def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """The rows it holds, unchanged (their meta columns included), as ``main``.""" self._require_current_output() + # Read once: a concurrent reader clears it after taking the rows (the rows + # are set first, so a reader that finds no loader finds them). + loader = self._row_loader + if loader is not None: + self._rows = list(loader().iter_data()) + self._row_loader = None if not self._output_bindings: return iter(self._rows) return self._iter_current_rows() @@ -1679,6 +1698,54 @@ def rows_on_read( return cast(StreamProtocol, cast(object, RowsOnRead(rows, node, bindings=bindings))) +def whole_on_read( + node: StreamProtocol, loader: WholeRead, *, bindings: OutputBindings +) -> StreamProtocol: + """A projected source node's output: main's stream, its rows read when first read. + + The stream the whole read gives (``_output_stream``: the node's table as the + node's stream), built now from the node's zero-row table, so that every member + that describes it reads nothing; its first row access takes ``loader``'s whole + read (ITL-1798). + + Args: + node: The source node. + loader: The node's whole read. + bindings: The bindings at production. + """ + table = typed_zero_row_table(node) + if table is None: # pragma: no cover - a projected node types its rows + raise RuntimeError("A projected source node types its rows.") + tag_keys, data_keys = loader.keys + stream = StaticOutputOperatorPod._as_upstream_stream( + StaticOutputOperatorPod._in_row_order(table, tag_keys), + tag_keys, + data_tag_names(tag_keys, data_keys), + node, + bindings=bindings, + ) + stream._row_loader = loader # pyright: ignore[reportPrivateUsage] # its rows, read when first read + return stream + + +def rows_on_read_of( + node: StreamProtocol, loader: WholeRead, *, bindings: OutputBindings +) -> StreamProtocol: + """A projected source node's output as the async route collects it (``RowsOnRead``). + + It holds no row: its rows are ``loader``'s whole read, made when they are first + read, and its stream, until then, ``whole_on_read`` (ITL-1798). + + Args: + node: The source node. + loader: The node's whole read. + bindings: The bindings at production. + """ + output = RowsOnRead([], node, bindings=bindings) + output._row_loader = loader # pyright: ignore[reportPrivateUsage] # its rows, read when first read + return cast(StreamProtocol, cast(object, output)) + + def at_edge(stream: StreamProtocol) -> StreamProtocol: """``stream`` as a node's input: a ``RowsOnRead`` output is built here. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 27801241e..cc06e210b 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, Collection +from collections.abc import Callable, Collection, Iterator from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast from orcapod import contexts @@ -32,6 +32,7 @@ import pyarrow as pa from orcapod.core.sources.cached_source import CachedSource + from orcapod.protocols.core_protocols import SourceProtocol from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import SemanticHasherProtocol @@ -400,6 +401,11 @@ def row_limit(self) -> int | None: its kind can be limited (``SpiralDBTableSource(limit=...)``).""" return None + PROJECTS_COLUMNS: ClassVar[bool] = False + """Whether ``projected_table`` can read fewer columns (ITL-1798). A job asks a + source node's source for a narrower read only when its class says so, so a + source that cannot changes nothing in how a job runs.""" + def projected_table( self, data_columns: Collection[str], @@ -423,6 +429,38 @@ def projected_table( """ return None + def projected_batch_streams( + self, data_columns: Collection[str] + ) -> "Iterator[StreamProtocol] | None": + """This source's rows in batches, read with only ``data_columns``, or ``None``. + + A kind that can scan fewer columns hands on, as its ``async_iter_data`` reads + them, streams of the rows it gives without the data columns not in + ``data_columns`` (and their source-info columns). A job's async route sends a + source node's rows from them (ITL-1798), one batch held at a time, as it + sends a whole read's. + + Returns: + ``None``: this kind reads every column. ``SpiralDBTableSource`` returns its + batches. + """ + return None + + def pinned_snapshot(self) -> "SourceProtocol | None": + """A source that reads this source's current version, or ``None``. + + A kind whose reads scan a pinned version returns a copy that keeps reading + that version after a check pins a newer one on this source. A job projects a + source node's read (ITL-1798) only over such a snapshot, so a run's output + always reads the version the run used, as a whole read held when produced + does. + + Returns: + ``None``: this kind keeps no version. ``SpiralDBTableSource`` returns a + copy at its pinned version. + """ + return None + # ------------------------------------------------------------------------- # Content identity # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 09742bbee..fe4c37a41 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1187,6 +1187,19 @@ def as_table( all_info=all_info, ) + PROJECTS_COLUMNS: ClassVar[bool] = True + + @override + def pinned_snapshot(self) -> "SpiralDBTableSource": + """A copy of this source that reads its pinned version (``_copy``). + + Every read scans the pinned table handle, an immutable snapshot of one + version; a later ``check_for_new_data`` on this source replaces this source's + handle and pin, never the copy's. The copy has this source's identity, keys, + restriction and modified time. + """ + return self._copy() + @override def projected_table( self, @@ -1212,16 +1225,12 @@ def projected_table( """ config = ColumnConfig.handle_config(columns) if config.content_hash: + # A row hash covers every data column, not only those read. return None - tag_columns, data_keys = self._stream.keys() - wanted = set(data_columns) - unread = {c for c in data_keys if c not in wanted and c not in tag_columns} - if not unread: + scan = self._projected_scan(data_columns) + if scan is None: return None - keys = set(self._key_columns) - table_columns = [ - c for c in self._table_schema.names if c not in unread or c in keys - ] + table_columns, unread = scan table = self._whole_table( self._batch_streams( with_source_info=_reads_source_info(config), @@ -1234,6 +1243,61 @@ def projected_table( dropped = unread | {f"{constants.SOURCE_PREFIX}{c}" for c in unread} return table.drop_columns([c for c in table.column_names if c in dropped]) + @override + def projected_batch_streams( + self, data_columns: Collection[str] + ) -> "Iterator[ArrowTableStream] | None": + """Scan only the columns needed for ``data_columns``, in batches (ITL-1798). + + As ``iter_data`` reads the table, one SpiralDB batch held at a time, the + count first, in streams of at most ``batch_rows`` rows: each stream holds the + rows ``iter_data`` gives for its batch, without the data columns not in + ``data_columns`` and their source-info columns. The columns scanned are + those of ``projected_table``. + + Returns: + The streams, read as they are asked for, or ``None`` when there are no + data columns to omit. + """ + scan = self._projected_scan(data_columns) + if scan is None: + return None + table_columns, unread = scan + return self._narrowed_streams(table_columns, unread) + + def _projected_scan( + self, data_columns: Collection[str] + ) -> tuple[list[str], set[str]] | None: + """The table columns a read of ``data_columns`` scans, and the data columns it + leaves out; ``None`` when it leaves none out (see ``projected_table``).""" + tag_columns, data_keys = self._stream.keys() + wanted = set(data_columns) + unread = {c for c in data_keys if c not in wanted and c not in tag_columns} + if not unread: + return None + keys = set(self._key_columns) + table_columns = [ + c for c in self._table_schema.names if c not in unread or c in keys + ] + return table_columns, unread + + def _narrowed_streams( + self, table_columns: list[str], unread: set[str] + ) -> Generator["ArrowTableStream", None, None]: + """``_batch_streams`` over ``table_columns``, each without ``unread``.""" + dropped = unread | {f"{constants.SOURCE_PREFIX}{c}" for c in unread} + enriched = {"source": True, "system_tags": True} + for stream in self._batch_streams(table_columns=table_columns): + table = stream.as_table(columns=enriched) + yield ArrowTableStream._from_derived_table( + table=table.drop_columns( + [c for c in table.column_names if c in dropped] + ), + tag_columns=self._tag_columns, + data_tags=self._data_tags, + data_context=stream.data_context, + ) + def _whole_table( self, streams: Iterator["ArrowTableStream"], diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 02e92d1cd..7f3c7dfbc 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -2,7 +2,8 @@ import itertools import logging -from collections.abc import Collection, Iterator +import threading +from collections.abc import Callable, Collection, Iterator from datetime import datetime from typing import Any, Self @@ -35,6 +36,92 @@ logger = logging.getLogger(__name__) +class WholeRead: + """A projected source node's whole read, made once, when its rows are first read. + + A job reads a source node with only the data columns its successors keep + (ITL-1798). The node's output is still main's own class (``ArrowTableStream``, or + ``RowsOnRead`` on the async route), holding its zero-row table, and this object: + the first access to its rows reads the source whole, from the snapshot pinned at + production, and every later one (also by a shallow copy, which holds this same + object) takes that read. It also holds the narrowed read, which a column + selection on the output takes in place of the whole table (``projected_table``). + An execution detail: no hash, schema, record id or stored row depends on it. + """ + + def __init__( + self, + read: Callable[[], ArrowTableStream], + narrow: ArrowTableStream | None, + keys: tuple[tuple[str, ...], tuple[str, ...]], + num_rows: int, + ) -> None: + """Hold the narrowed read and the way to the whole one. + + Args: + read: Returns the node's whole output, built from its table, reading the + source whole at the version the narrowed rows were read at. + narrow: The node's output over the narrowed read, or ``None`` when it was + not kept (the async route sends it batch by batch): a column + selection on the output then reads the whole output. + keys: The tag and data keys of the whole output. + num_rows: The whole output's row count: the narrowed read's, which holds + the same rows. + """ + self._read = read + self._narrow = narrow + self._keys = keys + self._whole: ArrowTableStream | None = None + self._lock = threading.Lock() + self.num_rows: int = num_rows + """The whole output's row count: the narrowed read's, which holds the same rows.""" + + @property + def keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The tag and data keys of the whole output.""" + return self._keys + + def __call__(self) -> ArrowTableStream: + """The whole output, read on the first call only.""" + with self._lock: + if self._whole is None: + self._whole = self._read() + return self._whole + + def projected_table( + self, + data_columns: Collection[str], + *, + columns: ColumnConfig | dict[str, Any] | None = None, + ) -> pa.Table | None: + """The whole output's table without the data columns not in ``data_columns``. + + As ``SourceProtocol.projected_table`` (ITL-1776): the data columns not in + ``data_columns`` (never a tag, also a data-tag) and their source-info columns + are left out; every other column is the whole output's. + + Returns: + The table, or ``None`` when it would not be the whole output's table + without those columns (a row hash, meta columns, a column not read), or + the narrowed read was not kept: the caller then reads the whole output. + """ + config = ColumnConfig.handle_config(columns) + tag_keys, data_keys = self._keys + wanted = set(data_columns) + narrow = self._narrow + if ( + narrow is None + or config.content_hash + or config.meta + or not wanted <= set(narrow.keys()[1]) + ): + return None + table = narrow.as_table(columns=config) + unread = {c for c in data_keys if c not in wanted and c not in tag_keys} + dropped = unread | {f"{constants.SOURCE_PREFIX}{c}" for c in unread} + return table.drop_columns([c for c in table.column_names if c in dropped]) + + class ArrowTableStream(MaterializedOutput, StreamBase): """ An immutable stream based on a PyArrow Table. @@ -60,6 +147,10 @@ class ArrowTableStream(MaterializedOutput, StreamBase): # head() does. _RUN_ORIGIN: str = "held" + # A projected source node's output in a job (ITL-1798): it holds its zero-row + # table until its rows are first read, then the whole read's (``WholeRead``). + _row_loader: WholeRead | None = None + def __init__( self, table: "pa.Table", @@ -261,6 +352,18 @@ def _initialize( self._cached_elements: list[tuple[TagProtocol, Data]] | None = None self._update_modified_time() # set modified time to now + def _load_rows(self) -> None: + """Take the whole read's rows, when this stream holds only its zero-row table.""" + loader = self._row_loader + if loader is None: + return + whole = loader() + self._table = whole._table + self._source_info_table = whole._source_info_table + self._data_context_table = whole._data_context_table + # Cleared last: a reader that finds no loader finds the whole rows. + self._row_loader = None + @staticmethod def _require_valid_system_tags(table: pa.Table) -> None: """Require non-null string values in every system-tag column.""" @@ -480,7 +583,16 @@ def head( """ check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) - if config.sort_by_tags: + # Read once: a concurrent full read of this stream clears it after taking the + # whole rows (``_load_rows``), and its count is then the table's. + loader = self._row_loader + if config.sort_by_tags and (n or loader is None or config.content_hash): + # A stream that holds its rows always sorts them all, as main does. Only a + # projected output with its whole read pending (ITL-1798) asked for no row + # and no row hash reads no row: its zero-row table is sorted instead, which + # refuses exactly what sorting its rows would (the refusal is the tag + # type's). A row hash is computed from the rows, so asking for one reads + # them whole and hashes them all, raising what main raises. table = self._assemble_table(config, limit=None).slice(0, n) else: table = self._assemble_table(config, limit=n) @@ -488,7 +600,7 @@ def head( self, table, tag_columns=self.keys(columns=config)[0], - total_rows=self._table.num_rows, + total_rows=self._table.num_rows if loader is None else loader.num_rows, ) def _typed_zero_row_table(self) -> "pa.Table": @@ -505,6 +617,8 @@ def _assemble_table( limit: Assemble only the first ``limit`` rows; ``None`` for all of them. """ self._require_current_output() + if limit != 0: + self._load_rows() output_table = self._table data_context_table = self._data_context_table source_info_table = self._source_info_table @@ -569,6 +683,7 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: A ``(Tag, Data)`` tuple for each row. """ self._require_current_output() + self._load_rows() # TODO: make it work with table batch stream if self._cached_elements is None: cached_elements = [] @@ -618,3 +733,14 @@ def __repr__(self) -> str: f"{self.__class__.__name__}(table={self._table.column_names}, " f"tag_columns={self._tag_columns}{refs})" ) + + +def pending_whole_read(stream: object) -> WholeRead | None: + """The whole read ``stream`` has yet to make, or ``None`` (ITL-1798). + + Only a projected source node's output whose rows were not read yet has one: a + column selection on it then takes the narrowed read (``WholeRead.projected_table``). + """ + if isinstance(stream, ArrowTableStream): + return stream._row_loader # pyright: ignore[reportPrivateUsage] # this module's class + return None diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index a83d789be..6d35331fe 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -215,6 +215,7 @@ async def _run_async( from orcapod.core.operators.static_output_pod import ( rows_on_read, ) + from orcapod.pipeline.column_demand import read_columns from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -273,9 +274,16 @@ async def _run_async( collectors[node] = [] bindings_at_collection[id(node)] = capture_output_bindings(node) + # A source node that sent a narrowed read's rows (ITL-1798): its output is + # the whole one it returned, never the narrowed rows collected. + whole_outputs: dict[int, StreamProtocol] = {} + def collected_output( rows: list[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: + whole = whole_outputs.get(id(node)) + if whole is not None: + return whole return rows_on_read( rows, node, bindings=bindings_at_collection[id(node)] ) @@ -307,7 +315,14 @@ def collected_output( tg, failed_nodes, node, - node.async_execute(writer, observer=effective_observer), + _source_execution( + node, + writer, + effective_observer, + graph, + read_columns, + whole_outputs, + ), ) elif is_function_node(node) or is_side_effect_function_node(node): predecessors = in_edges.get(node, []) @@ -407,6 +422,32 @@ def collected_output( effective_observer.on_run_end(run_id) +async def _source_execution( + node: Any, + writer: Any, + observer: Any, + graph: Any, + read_columns: Callable[[Any, Any], frozenset[str] | None], + whole_outputs: dict[int, Any], +) -> None: + """A source node's ``async_execute``, given its successors' columns when known + (ITL-1798); without them, called exactly as before. + + When the node sends a narrowed read's rows, it returns its whole output, recorded + in ``whole_outputs`` (by the node's id): the run's collected output for the node + is that, never the narrowed rows its successors received. + """ + demand = read_columns(node, graph) + if demand is None: + await node.async_execute(writer, observer=observer) + return + whole = await node.async_execute(writer, observer=observer, read_columns=demand) + if whole is not None: + whole_outputs[id(node)] = whole + if isinstance(writer, _CollectingWriter): + writer.discard_collected() + + def _run_on_own_thread( make_run: Callable[[], Coroutine[Any, Any, _T]], rows_in_flight: _RowsInFlight ) -> _T: @@ -836,5 +877,9 @@ async def send(self, item: Any) -> None: async def close(self) -> None: await self._writer.close() + def discard_collected(self) -> None: + """Forget the items collected: the node's output is held elsewhere.""" + self._collector.clear() + def __getattr__(self, name: str) -> Any: return getattr(self._writer, name) diff --git a/src/orcapod/pipeline/column_demand.py b/src/orcapod/pipeline/column_demand.py new file mode 100644 index 000000000..776563c6e --- /dev/null +++ b/src/orcapod/pipeline/column_demand.py @@ -0,0 +1,83 @@ +"""The data columns a source node's successors read, for a narrower read (ITL-1798). + +A job reads each source node before any successor runs, so a column selection on the +source (ITL-1776) never reaches the source. The orchestrators compute here, from the +run's graph, which data columns a source node's successors read, and give them to the +node (``execute(read_columns=...)``), which reads only those when its source can. + +The rule is deliberately narrow: the node must be a ``SourceJobNode`` whose bound +source's class reads fewer columns (``PROJECTS_COLUMNS``), and every successor in the run's graph must be a job +operator node over this one source node whose operator is exactly a +``SelectDataColumns`` or ``SelectColumns``; the node then reads the union of the data +columns they keep. Any other successor (a drop, a function node, a join, a side +effect, a subclass), or none at all, means a whole read. The projection is an +execution detail: no hash, stored path, schema, record id or stored row depends on it. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.core.operators.column_selection import SelectColumns, SelectDataColumns +from orcapod.core.streams.base import reads_as_its_class + +if TYPE_CHECKING: + from orcapod.pipeline.dag import GraphProtocol + + +def _kept_data_columns(successor: Any, node: Any) -> frozenset[str] | None: # pyright: ignore[reportExplicitAny] # any graph node + """The data columns of ``node`` that ``successor`` keeps, or ``None`` if unknown. + + Args: + successor: A successor of ``node`` in the run's graph. + node: The source node. + + Returns: + The kept data columns of a column selection directly on ``node``; ``None`` + for any other successor. + """ + if not reads_as_its_class(successor, OperatorJobNode): + return None + upstreams = tuple(successor.upstreams) + # By identity: a stream's ``==`` compares hashes, which a plan never computes. + if len(upstreams) != 1 or upstreams[0] is not node: + return None + operator = successor.producer + if type(operator) not in (SelectDataColumns, SelectColumns): + return None + _, data_keys = node.keys() + return frozenset(c for c in data_keys if c in operator.columns) + + +def read_columns(node: Any, graph: GraphProtocol[Any]) -> frozenset[str] | None: # pyright: ignore[reportExplicitAny] # any graph node + """The data columns ``node``'s successors read, or ``None``: read every column. + + Args: + node: A source node of ``graph``. + graph: The run's graph. + + Returns: + The union of the data columns its successors keep, when every successor is a + column selection directly on it; otherwise ``None``. + """ + if not reads_as_its_class(node, SourceJobNode): + return None + source = node.bound_source + if not getattr(type(source), "PROJECTS_COLUMNS", False): + # A source that cannot read fewer columns: the run is exactly as before. + return None + successors = list(graph.successors(node)) + if not successors: + return None + demand: set[str] = set() + for successor in successors: + kept = _kept_data_columns(successor, node) + if kept is None: + return None + demand |= kept + tag_keys, data_keys = node.keys() + if all(c in demand or c in tag_keys for c in data_keys): + return None # every data column is read + return frozenset(demand) diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index 5167ea901..5d526f08d 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -85,6 +85,7 @@ def run( Returns: OrchestratorResult with each node's output stream. """ + from orcapod.pipeline.column_demand import read_columns from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -114,7 +115,14 @@ def run( if node in held_streams: outputs[node] = held_streams[node] elif is_source_node(node): - outputs[node] = node.execute(observer=effective_observer) + # The data columns its successors read, when known (ITL-1798). + demand = read_columns(node, graph) + if demand is None: + outputs[node] = node.execute(observer=effective_observer) + else: + outputs[node] = node.execute( + observer=effective_observer, read_columns=demand + ) elif is_function_node(node) or is_side_effect_function_node(node): input_stream = self._single_input(node, graph, outputs) outputs[node] = node.execute( diff --git a/src/orcapod/protocols/core_protocols/sources.py b/src/orcapod/protocols/core_protocols/sources.py index d99a566c4..ed6f01a1a 100644 --- a/src/orcapod/protocols/core_protocols/sources.py +++ b/src/orcapod/protocols/core_protocols/sources.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Collection +from collections.abc import Collection, Iterator from typing import TYPE_CHECKING, Any, Protocol, TypeVar, runtime_checkable from orcapod.protocols.core_protocols.streams import StreamProtocol @@ -63,6 +63,27 @@ def projected_table( """ ... + def projected_batch_streams( + self, data_columns: Collection[str] + ) -> Iterator[StreamProtocol] | None: + """This source's rows in batches without the data columns not in + ``data_columns``, or ``None`` when this kind reads every column. + + A job's async route sends a source node's rows from them, one batch held at a + time, as it sends a whole read's (ITL-1798). + """ + ... + + def pinned_snapshot(self) -> SourceProtocol | None: + """A source that reads this source's current version, whatever a later check + pins, or ``None`` when this kind cannot keep a version. + + A job reads a source node's source with fewer columns (``projected_table``) + only from such a snapshot, and reads its whole rows, when asked, from the same + snapshot: both are of the version the run used (ITL-1798). + """ + ... + def to_config( self, db_registry: DatabaseRegistryProtocol | None = None ) -> dict[str, Any]: diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index a07d00f68..33e8196a2 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -11,7 +11,7 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Collection, Sequence from typing import TYPE_CHECKING, Literal, Protocol, TypeGuard, runtime_checkable if TYPE_CHECKING: @@ -67,6 +67,7 @@ def execute( self, *, observer: ExecutionObserverProtocol | None = None, + read_columns: Collection[str] | None = None, ) -> StreamProtocol: ... async def async_execute( @@ -74,7 +75,8 @@ async def async_execute( output: WritableChannel[tuple[TagProtocol, DataProtocol]], *, observer: ExecutionObserverProtocol | None = None, - ) -> None: ... + read_columns: Collection[str] | None = None, + ) -> StreamProtocol | None: ... @runtime_checkable diff --git a/tests/test_core/sources/test_source_protocol_conformance.py b/tests/test_core/sources/test_source_protocol_conformance.py index ad73668e4..049f0a36c 100644 --- a/tests/test_core/sources/test_source_protocol_conformance.py +++ b/tests/test_core/sources/test_source_protocol_conformance.py @@ -14,6 +14,11 @@ from __future__ import annotations +import importlib +import inspect +import pkgutil +import typing + import pyarrow as pa import pytest @@ -131,6 +136,65 @@ def test_is_source_protocol(self, src_fixture, request): ) +def _protocol_members(protocol: type) -> set[str]: + """The public members a runtime protocol declares, its protocol bases' included.""" + members: set[str] = set() + for klass in protocol.__mro__: + if klass in (object, typing.Protocol, typing.Generic): + continue + if not getattr(klass, "_is_protocol", False): + continue + members |= {n for n in vars(klass) if not n.startswith("_")} + members |= { + n for n in getattr(klass, "__annotations__", {}) if not n.startswith("_") + } + return members + + +def _library_source_classes() -> list[type]: + """Every concrete source class the library defines: the subclasses of the abstract + ``RootSource``.""" + package = importlib.import_module("orcapod.core.sources") + for module in pkgutil.iter_modules(package.__path__): + _ = importlib.import_module(f"orcapod.core.sources.{module.name}") + found: list[type] = [] + pending: list[type] = [RootSource] + while pending: + klass = pending.pop() + concrete = klass is not RootSource and not inspect.isabstract(klass) + if concrete and klass.__module__.startswith("orcapod.") and klass not in found: + found.append(klass) + pending.extend(klass.__subclasses__()) + return sorted(found, key=lambda k: f"{k.__module__}.{k.__qualname__}") + + +def test_every_library_source_class_answers_every_source_protocol_member() -> None: + """``SourceProtocol`` is internal: every member it declares, ``pinned_snapshot`` + included (ITL-1798), is answered by every library source class, so adding a + member changes no library source's ``isinstance`` (review of PR 687 at 267a5edc, + finding 1, declined).""" + members = _protocol_members(SourceProtocol) + assert {"pinned_snapshot", "projected_table", "source_id"} <= members + classes = _library_source_classes() + assert len(classes) >= 14 + for klass in classes: + missing = sorted( + m for m in members if inspect.getattr_static(klass, m, _ABSENT) is _ABSENT + ) + assert missing == [], f"{klass.__qualname__} lacks {missing}" + + +def test_a_library_source_answers_pinned_snapshot_without_a_version( + arrow_src: ArrowTableSource, +) -> None: + """A source that keeps no version answers ``None`` (the ``RootSource`` default).""" + assert arrow_src.pinned_snapshot() is None + assert isinstance(arrow_src, SourceProtocol) + + +_ABSENT = object() + + # --------------------------------------------------------------------------- # 2. output_schema # --------------------------------------------------------------------------- diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 1aac79b95..31f80cd9e 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -490,12 +490,17 @@ def test_two_async_job_readers_use_the_restricted_sources_endpoint( with job: SelectColumns(["subject", "x"])(restricted, label="left") SelectColumns(["k", "x"])(restricted, label="right") - start = len(fake_spiral_sdk.scan_log) + start = len(fake_spiral_sdk.scan_log) + len(fake_spiral_sdk.count_log) job.run(orchestrator=AsyncPipelineOrchestrator()) assert job.nodes["left"].as_table()["x"].to_pylist() == [14] assert job.nodes["right"].as_table()["x"].to_pylist() == [14] - # The async job fans one scan out to both readers of this source. - assert len(fake_spiral_sdk.scan_log) - start == 1 + # The async job fans one scan out to both readers of this source. Both read + # only selected columns, so it is a scan of some columns (ITL-1798), which + # the fake logs beside its counts. + scans = len(fake_spiral_sdk.scan_log) + len(fake_spiral_sdk.count_log) + assert scans - start == 1 + assert fake_spiral_sdk.count_log[-1].columns is not None + assert "y" not in fake_spiral_sdk.count_log[-1].columns @pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) diff --git a/tests/test_core/streams/test_head_sorting.py b/tests/test_core/streams/test_head_sorting.py index 4a5029f0b..138680c42 100644 --- a/tests/test_core/streams/test_head_sorting.py +++ b/tests/test_core/streams/test_head_sorting.py @@ -451,3 +451,31 @@ def test_a_hash_column_named_like_a_system_tag_does_not_reorder_tied_rows() -> N assert shown.column("x").to_pylist() == [3, 1, 2] assert shown.column_names[-1] == ("_content_hash" if name is True else name) assert stream.head(2, columns=config).table.equals(shown.slice(0, 2)) + + +_MAP_TYPE = pa.map_(pa.int32(), pa.int32()) + + +@pytest.mark.parametrize("n", [0, 1]) +def test_sorted_head_with_a_row_hash_hashes_the_rows_of_a_held_stream(n: int) -> None: + """A stream holding its rows hashes every row for a sorted head, ``head(0)`` too. + + A map value cannot be hashed, so ``as_table`` and the sorted head refuse it with + ``ValueError``, whatever ``n`` is; an unsorted ``head(0)`` assembles no row and + hashes none (review of PR 687 at 267a5edc, finding 2). + """ + from orcapod.core.streams import ArrowTableStream + + table = pa.table( + {"id": [2, 1], "x": pa.array([[(1, 2)], [(1, 2)]], type=_MAP_TYPE)} + ) + stream = ArrowTableStream(table, tag_columns=["id"]) + config = {"sort_by_tags": True, "content_hash": True} + with pytest.raises(ValueError, match="map"): + stream.as_table(columns=config) + with pytest.raises(ValueError, match="map"): + stream.head(n, columns=config) + shown = stream.head(0, columns={"sort_by_tags": True}) + assert shown.table.num_rows == 0 + assert shown.total_rows == 2 + assert stream.head(0, columns={"content_hash": True}).table.num_rows == 0 diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py new file mode 100644 index 000000000..197c8597a --- /dev/null +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -0,0 +1,1425 @@ +"""In a job, a SpiralDB source node read only by column selections scans only the +columns they keep (ITL-1798), and the job gives exactly the rows, stored rows and +hashes of the whole read. + +The projection is an execution detail: every test runs the same job twice, once as it +is and once with the projection turned off (``projected_table`` disabled, the read +before ITL-1776), and compares every node's rows, every stored table, the node hashes +and stored paths, and which columns were scanned. +""" + +from __future__ import annotations + +import asyncio +import copy +import dataclasses +import datetime +from collections.abc import Callable +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.static_output_pod import ( + RowsOnRead, + _RowsOfStream, # pyright: ignore[reportPrivateUsage] # main's sync output class +) +from orcapod.core.streams.arrow_table_stream import pending_whole_read +from orcapod.core.sources import spiraldb_table_source as source_module +from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases import spiraldb_connector as connector_module +from orcapod.pipeline import ( + AsyncPipelineOrchestrator, + SyncPipelineOrchestrator, + column_demand, +) +from orcapod.core.streams.base import schema_requires_io, typed_zero_row_table +from orcapod.core.streams.view import display_name +from orcapod.pipeline.dag import OrcaDAG +from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol +from orcapod.sources import SpiralDBTableSource +from orcapod.types import CacheMode, ColumnConfig, Condition +from tests.test_databases import fake_spiral_sdk as fake + +if TYPE_CHECKING: + from orcapod.pipeline.dag import GraphProtocol + +_WRITTEN = pa.schema( + [ + pa.field("unit", pa.large_string(), False), + pa.field("t", pa.int64(), False), + pa.field("x", pa.float64(), False), + pa.field("y", pa.int32()), + pa.field("blob", pa.large_binary()), + ] +) +_ALL = ["blob", "t", "unit", "x", "y"] + + +def _rows() -> pa.Table: + return pa.Table.from_pylist( + [ + {"unit": u, "t": t, "x": t * 0.5, "y": t, "blob": bytes(50) + bytes([t])} + for u in ("u2", "u1") + for t in (3, 1, 2) + ], + schema=_WRITTEN, + ) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(connector_module, "_warned_unrecorded", set()) + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p") + made.create_table( + "default.wide", key_schema=[_WRITTEN.field("unit"), _WRITTEN.field("t")] + ).write(_rows()) + fake.migrate("p", {"wide": _WRITTEN}) + yield made + + +def _read_whole(monkeypatch: pytest.MonkeyPatch) -> None: + """Turn the projection off: every source is read whole, as before ITL-1776.""" + monkeypatch.setattr( + source_module.SpiralDBTableSource, + "projected_table", + lambda self, data_columns, *, columns=None: None, + ) + monkeypatch.setattr( + source_module.SpiralDBTableSource, + "projected_batch_streams", + lambda self, data_columns: None, + ) + + +def _pair(tag: Any, data: Any) -> tuple[Any, Any, Any]: + """A row as two runs' rows compare: its tags with its system tags (the source + id and record id), its data with each column's source-info token, and the data's + row hash.""" + return ( + tag.as_dict(columns={"system_tags": True}), + data.as_dict(columns={"source": True}), + data.content_hash(), + ) + + +def _row_scans() -> list[list[str]]: + """The sorted columns each row scan requested (a count reads one column).""" + scans: list[list[str]] = [] + for record in fake.scan_log + fake.count_log: + if record.columns is None: + scans.append(_ALL) + elif len(record.columns) > 1: + scans.append(sorted(record.columns)) + return sorted(scans) + + +# Columns that hold a time or a random result id: equal in kind, never in value. +_UNREPEATABLE = { + "__recorded_at", + "__pod_ts", + "__data_id", + "__pipeline_record_id", + "__pipeline_run_id", +} + + +def _repeatable(table: pa.Table, outputs: tuple[str, ...] = ()) -> pa.Table: + """``table`` without the columns two runs never repeat (a time, a result id, and + the source-info token of a function output, which holds the result id).""" + drop = _UNREPEATABLE | {f"_source_{name}" for name in outputs} + return table.drop_columns([c for c in table.column_names if c in drop]) + + +def _as_set(table: pa.Table) -> pa.Table: + """``table`` in a canonical row order: a stored table is a set of rows, and the + async route writes them in the order its tasks finish.""" + keys: list[tuple[str, Literal["ascending", "descending"]]] = [ + (name, "ascending") + for name, column in zip(table.column_names, table.columns, strict=True) + if pa.types.is_string(column.type) + or pa.types.is_large_string(column.type) + or pa.types.is_integer(column.type) + or pa.types.is_floating(column.type) + or pa.types.is_boolean(column.type) + or pa.types.is_large_binary(column.type) + or pa.types.is_binary(column.type) + ] + return table.sort_by(keys) if keys else table + + +def _same(got: pa.Table, expected: pa.Table) -> None: + assert got.schema.equals(expected.schema, check_metadata=True) + assert got.equals(expected) + + +Build = Callable[[], tuple[PipelineJob, InMemoryArrowDatabase]] + + +def _stored( + database: InMemoryArrowDatabase, outputs: tuple[str, ...] +) -> dict[tuple[str, ...], pa.Table]: + tables = {} + for path in sorted(database.list_table_paths()): + table = database.get_all_records(path) + assert table is not None + tables[path] = _as_set(_repeatable(table, outputs)) + return tables + + +def _run( + build: Build, + route: str, + labels: list[str], + outputs: tuple[str, ...] = (), +) -> dict[str, Any]: + """Run the job built by ``build`` on ``route`` and return what the run gives.""" + job, log = build() + fake.scan_log.clear() + fake.count_log.clear() + if route == "sync": + job.run() + elif route == "async": + asyncio.run(job.run_async()) + elif route == "load_only": + job.run(load_only=True) + else: # one node's own run: the nodes it depends on run first + for label in labels: + job.nodes[label].run() + scans = _row_scans() + nodes = { + label: _repeatable(job.nodes[label].as_table(all_info=True), outputs) + for label in labels + } + hashes = { + label: ( + job.nodes[label].content_hash(), + job.nodes[label].pipeline_hash(), + job.nodes[label].keys(), + job.nodes[label].output_schema(all_info=True), + ) + for label in labels + } + return { + "scans": scans, + "nodes": nodes, + "hashes": hashes, + "stored": _stored(job.database, outputs), # pyright: ignore[reportArgumentType] + "log": _stored(log, outputs), + } + + +def _compare( + monkeypatch: pytest.MonkeyPatch, + build: Build, + route: str, + labels: list[str], + outputs: tuple[str, ...] = (), +) -> tuple[dict[str, Any], dict[str, Any]]: + got = _run(build, route, labels, outputs) + with monkeypatch.context() as m: + _read_whole(m) + expected = _run(build, route, labels, outputs) + # One whole read per run (a node's own run reads the source again). + runs = len(labels) if route == "node_run" else 1 + assert expected["scans"] == [_ALL] * runs + for label in labels: + _same(got["nodes"][label], expected["nodes"][label]) + assert got["hashes"] == expected["hashes"] + for key in ("stored", "log"): + assert list(got[key]) == list(expected[key]) + for path, table in got[key].items(): + _same(table, expected[key][path]) + return got, expected + + +ROUTES = ["sync", "async", "load_only", "node_run"] + + +def _job( + steps: Callable[[SpiralDBTableSource], object], + log_labels: tuple[str, ...] = (), + **source_args: Any, +) -> Build: + """A builder of a job over the wide table; ``log_labels`` store their rows.""" + + def build() -> tuple[PipelineJob, InMemoryArrowDatabase]: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + arguments: dict[str, Any] = {"tag_only_columns": True, **source_args} + steps(SpiralDBTableSource("p", "wide", **arguments)) + log = InMemoryArrowDatabase() + for label in log_labels: + job.nodes[label].attach_databases( + pipeline_database=log, cache_mode=CacheMode.LOG + ) + return job, log + + return build + + +@pytest.mark.parametrize("route", ROUTES) +def test_a_selection_in_a_job_scans_only_what_it_keeps( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str +) -> None: + build = _job(lambda s: s.select_data_columns(["x"], label="sx"), log_labels=("sx",)) + got, _ = _compare(monkeypatch, build, route, ["sx"]) + assert got["scans"] == [["t", "unit", "x"]] + if route != "load_only": + assert got["log"], "the LOG node stores its rows" + + +@pytest.mark.parametrize("route", ROUTES) +def test_two_selections_read_the_union_of_their_columns( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str +) -> None: + def steps(s: SpiralDBTableSource) -> None: + s.select_data_columns(["y", "x"], label="sxy") + s.select_columns(["t", "y"], label="sty") + + build = _job(steps, log_labels=("sxy", "sty")) + got, _ = _compare(monkeypatch, build, route, ["sxy", "sty"]) + if route == "node_run": + # Each node's own run plans its own dependencies: one read per run. + assert got["scans"] == [["t", "unit", "x", "y"], ["t", "unit", "y"]] + else: + assert got["scans"] == [["t", "unit", "x", "y"]] + + +@function_pod(output_keys="size") +def every_column(x: float, y: int | None, blob: bytes | None) -> int: + return len(blob or b"") + int(x) + (y or 0) + + +@pytest.mark.parametrize("route", ["sync", "async"]) +@pytest.mark.parametrize( + "other", + ["drop", "function", "plain"], +) +def test_a_consumer_that_is_not_a_selection_reads_the_whole_table( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str, other: str +) -> None: + def steps(s: SpiralDBTableSource) -> None: + s.select_data_columns(["x"], label="sx") + if other == "drop": + s.drop_data_columns(["blob"], label="other") + elif other == "function": + # A function node directly on the source reads every data column. + every_column.pod(s, label="other") + else: + s.select_tag_columns(["unit"], label="other") + + build = _job(steps) + outputs = ("size",) if other == "function" else () + got, _ = _compare(monkeypatch, build, route, ["sx", "other"], outputs=outputs) + assert got["scans"] == [_ALL] + + +@pytest.mark.parametrize("route", ROUTES) +def test_a_function_pod_on_the_source_reads_only_its_parameters( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str +) -> None: + @function_pod(output_keys="z") + def double(x: float) -> float: + return 2 * x + + # The automatic selection before the pod is the source node's one successor. + build = _job(lambda s: double.pod(s, label="doubled")) + got, _ = _compare(monkeypatch, build, route, ["doubled"], outputs=("z",)) + assert got["scans"] == [["t", "unit", "x"]] + + +SHAPES: list[tuple[str, dict[str, Any], list[str], list[str] | None]] = [ + # (id, source arguments, selected data columns, the scan) + ("data_tags", {"tag_only_columns": False}, ["x"], ["t", "unit", "x"]), + ( + "data_tag_selected_away", + {"tag_only_columns": False}, + ["unit", "x"], + ["t", "unit", "x"], + ), + ( + "where_and_limit", + {"where": Condition.of(unit="u1"), "limit": 2}, + ["x"], + ["t", "unit", "x"], + ), + ( + "where_on_an_unselected_column", + {"where": Condition.of(y=2)}, + ["x"], + ["t", "unit", "x", "y"], + ), + ("where_matching_no_row", {"where": Condition.of(y=99)}, ["x"], None), + ("key_column_is_data", {"tag_columns": ["unit"]}, ["x"], ["t", "unit", "x"]), + ( + "tags_as_data_kept", + {"tags_as_data": {"t": "t_copy"}}, + ["t_copy", "x"], + ["t", "unit", "x"], + ), +] + + +@pytest.mark.parametrize("route", ["sync", "async"]) +@pytest.mark.parametrize("shape", SHAPES, ids=[s[0] for s in SHAPES]) +def test_source_shapes_give_the_rows_of_the_whole_read( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str, shape: Any +) -> None: + _, source_args, selected, scanned = shape + # A restricted read is never kept in an operator cache (ITL-1218). + restricted = "where" in source_args or "limit" in source_args + build = _job( + lambda s: s.select_data_columns(selected, label="sel"), + log_labels=() if restricted else ("sel",), + **source_args, + ) + got, _ = _compare(monkeypatch, build, route, ["sel"]) + if scanned is not None: + assert got["scans"] == [scanned] + else: + # No row: one narrow scan; the empty result is the whole node's zero-row form. + assert len(got["scans"]) == 1 and _ALL not in got["scans"] + + +def test_the_projected_output_describes_the_whole_node(project: Any) -> None: + """Keys and identity are the whole node's; a whole read is made only on demand.""" + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + SpiralDBTableSource("p", "wide", tag_only_columns=True).select_data_columns( + ["x"], label="sx" + ) + node = next(n for n in job.nodes.values() if n.node_type == "source") + whole = node.execute() + fake.scan_log.clear() + fake.count_log.clear() + output = node.execute(read_columns=["x"]) + assert type(output) is type(whole) + assert _row_scans() == [["t", "unit", "x"]] + assert output.keys() == whole.keys() + assert output.content_hash() == whole.content_hash() + assert output.pipeline_hash() == whole.pipeline_hash() + config = {"source": True, "system_tags": True, "context": True} + whole_read = pending_whole_read(output) + assert whole_read is not None + narrowed = whole_read.projected_table(["x"], columns=config) + assert narrowed is not None + _same( + narrowed, + whole.as_table(columns=config).drop_columns( + ["y", "blob", "_source_y", "_source_blob"] + ), + ) + # A request beyond the read, or a row hash, is answered from the whole read. + assert whole_read.projected_table(["y"], columns=config) is None + assert whole_read.projected_table(["x"], columns={"content_hash": True}) is None + assert _row_scans() == [["t", "unit", "x"]] + # Any other read is the whole output's, read whole once. + _same(output.as_table(all_info=True), whole.as_table(all_info=True)) + assert _row_scans() == [_ALL, ["t", "unit", "x"]] + # Once read, the output holds the whole rows: no narrowed read is offered. + assert pending_whole_read(output) is None + + +class _Graph: + """The one member ``read_columns`` reads of a run's graph.""" + + def __init__(self, successors: dict[Any, list[Any]]) -> None: + self._successors = successors + + def successors(self, node: Any) -> list[Any]: + return self._successors.get(node, []) + + +def test_demand_is_known_only_for_selections_directly_on_the_source( + project: Any, +) -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + source.select_data_columns(["x"], label="sx") + source.select_columns(["unit", "y"], label="suy") + source.drop_data_columns(["blob"], label="drop") + every_column.pod(source, label="f") + source.select_data_columns(["x"]).select_data_columns(["x"], label="deeper") + node = next(n for n in job.nodes.values() if n.node_type == "source") + sx, suy, drop, f = (job.nodes[k] for k in ("sx", "suy", "drop", "f")) + + def demand(*successors: Any) -> Any: + graph = cast( + "GraphProtocol[Any]", cast(object, _Graph({node: list(successors)})) + ) + return column_demand.read_columns(node, graph) + + assert demand(sx) == {"x"} + # Two selections: the union; a tag named by a selection is read anyway. + assert demand(sx, suy) == {"x", "y"} + # No successor, a drop, a function node, or a node not directly on the source: + # every column. + assert demand() is None + assert demand(sx, drop) is None + assert demand(sx, f) is None + assert demand(job.nodes["deeper"]) is None + + +@pytest.mark.parametrize("route", ["sync", "async"]) +def test_the_orchestrator_result_holds_the_whole_source_output( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str +) -> None: + """A projected source node's collected output is the whole node's, as without the + projection: its keys, rows, row hashes and table (review of PR 687, F1).""" + + def collected(*, whole: bool) -> tuple[Any, Any]: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + source.select_data_columns(["x"], label="sx") + source.select_data_columns(["y", "x"], label="sxy") + node = next(n for n in job.nodes.values() if n.node_type == "source") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(node, job.nodes["sx"]) + dag.add_edge(node, job.nodes["sxy"]) + orchestrator = ( + SyncPipelineOrchestrator() + if route == "sync" + else AsyncPipelineOrchestrator() + ) + fake.scan_log.clear() + fake.count_log.clear() + with monkeypatch.context() as m: + if whole: + _read_whole(m) + result = orchestrator.run(dag) + scans = _row_scans() + outputs = result.node_outputs + source_output = outputs[node] + rows = [_pair(tag, data) for tag, data in source_output.iter_data()] + return ( + scans, + ( + source_output.keys(), + rows, + source_output.as_table(all_info=True), + source_output.content_hash(), + outputs[job.nodes["sx"]].as_table(all_info=True), + outputs[job.nodes["sxy"]].as_table(all_info=True), + ), + ) + + got_scans, got = collected(whole=False) + expected_scans, expected = collected(whole=True) + assert got_scans == [["t", "unit", "x", "y"]] + assert expected_scans == [_ALL] + assert got[0] == expected[0] == (("unit", "t"), ("blob", "x", "y")) + assert got[1] == expected[1] + for g, e in zip(got[2:], expected[2:], strict=True): + if isinstance(g, pa.Table): + _same(g, e) + else: + assert g == e + + +def test_a_direct_projected_read_with_a_row_hash_is_refused(project: Any) -> None: + """``projected_table`` asked for a row hash returns ``None``: a row hash covers + every data column, so the caller reads the whole table (PR #679's contract).""" + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + assert source.projected_table(["x"], columns={"content_hash": True}) is None + narrowed = source.projected_table(["x"]) + assert narrowed is not None + + +def _projected(project: Any) -> tuple[Any, Any, SpiralDBTableSource]: + """A source node's projected output (``x`` read), its whole output, and the source.""" + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="sx") + node = next(n for n in job.nodes.values() if n.node_type == "source") + whole = node.execute() + output = node.execute(read_columns=["x"]) + assert type(output) is type(whole) + assert pending_whole_read(output) is not None + return output, whole, source + + +def test_probing_the_projected_output_reads_nothing(project: Any) -> None: + """A protocol check, ``hasattr`` and the private members library helpers ask for + read no row: on Python 3.11 ``isinstance`` against a runtime protocol looks each + member up on the instance, which used to read the source whole (review of PR 687, + thread 1).""" + output, whole, _ = _projected(project) + fake.scan_log.clear() + fake.count_log.clear() + assert not isinstance(output, SourceProtocol) + for name in ("source_id", "condition", "row_limit", "to_config", "_no_such"): + assert not hasattr(output, name) + assert isinstance(output, StreamProtocol) + zero_rows = typed_zero_row_table(output) + expected = typed_zero_row_table(whole) + assert zero_rows is not None and expected is not None + assert zero_rows.schema.equals(expected.schema, check_metadata=True) + assert schema_requires_io(output, ColumnConfig()) is False + assert display_name(output) == display_name(whole) + assert _row_scans() == [] + + +@pytest.mark.parametrize("route", ["sync", "async"]) +def test_a_select_only_job_makes_no_whole_read( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str +) -> None: + """The column selection's input check never reads the source whole, on every + supported Python (review of PR 687, thread 1).""" + whole_reads = 0 + original = source_module.SpiralDBTableSource.as_table + + def counted(self: Any, *args: Any, **kwargs: Any) -> pa.Table: + nonlocal whole_reads + whole_reads += 1 + return original(self, *args, **kwargs) + + monkeypatch.setattr(source_module.SpiralDBTableSource, "as_table", counted) + build = _job(lambda s: s.select_data_columns(["x"], label="sx")) + job, _ = build() + fake.scan_log.clear() + fake.count_log.clear() + if route == "sync": + job.run() + else: + asyncio.run(job.run_async()) + assert whole_reads == 0 + assert _row_scans() == [["t", "unit", "x"]] + + +def _write_newer_version(project: Any) -> None: + """Write a newer version of the wide table: two rows with other ``x`` values.""" + newer = _rows().slice(0, 2) + project.table("default.wide").write( + newer.set_column(2, "x", pa.array([9.0, 9.0], pa.float64())) + ) + + +@pytest.mark.parametrize("move", ["check", "job_run"]) +@pytest.mark.parametrize("route", ["sync", "async"]) +def test_a_kept_run_output_reads_the_version_its_run_used( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str, move: str +) -> None: + """A run's source output read whole after the source moved to a newer version + gives the rows of the version the run used, as without the projection (on main a + source node's output is materialized when produced; review of PR 687, thread 2). + """ + + def first_run(*, whole: bool) -> tuple[Callable[[], None], Callable[[], Any]]: + """Run a select-only job; return how to move its source and how to read the + run's kept outputs.""" + with monkeypatch.context() as m: + if whole: + _read_whole(m) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + source.select_data_columns(["x"], label="sx") + node = next(n for n in job.nodes.values() if n.node_type == "source") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(node, job.nodes["sx"]) + orchestrator = ( + SyncPipelineOrchestrator() + if route == "sync" + else AsyncPipelineOrchestrator() + ) + outputs = orchestrator.run(dag).node_outputs + + def move_source() -> None: + if move == "check": + assert source.check_for_new_data() is True + else: + job.run() + assert ( + source.pinned_version + == project.table("default.wide").last_modified_at() + ) + + def read() -> tuple[Any, ...]: + source_output = outputs[node] + return ( + source_output.as_table(all_info=True), + [_pair(tag, data) for tag, data in source_output.iter_data()], + outputs[job.nodes["sx"]].as_table(all_info=True), + ) + + return move_source, read + + move_expected, read_expected = first_run(whole=True) + move_got, read_got = first_run(whole=False) + _write_newer_version(project) + move_expected() + move_got() + expected = read_expected() + got = read_got() + _same(got[0], expected[0]) + assert got[1] == expected[1] + _same(got[2], expected[2]) + # The version the run used: six rows, none with the newer values. + assert got[0].num_rows == 6 + assert 9.0 not in got[0].column("x").to_pylist() + + +def test_a_whole_read_after_the_pin_moved_reads_the_pinned_version( + project: Any, +) -> None: + """The whole rows of a projected output are of the version its narrowed rows + were read at, also after a check pinned a newer one (review of PR 687, thread 2).""" + output, whole, source = _projected(project) + whole_read = pending_whole_read(output) + assert whole_read is not None + narrowed = whole_read.projected_table(["x"]) + assert narrowed is not None + expected = whole.as_table(all_info=True) + _write_newer_version(project) + assert source.check_for_new_data() is True + _same(output.as_table(all_info=True), expected) + # The narrowed rows are still those read at production. + again = whole_read.projected_table(["x"]) + assert again is not None + _same(again, narrowed) + + +def test_a_whole_read_at_the_pin_of_production_is_allowed(project: Any) -> None: + """Without a pin move the whole read is made, once, of the same version.""" + output, whole, source = _projected(project) + assert source.check_for_new_data() is False + _same(output.as_table(all_info=True), whole.as_table(all_info=True)) + + +@pytest.mark.parametrize("route", ["sync", "async"]) +def test_a_source_without_a_snapshot_is_read_whole( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str +) -> None: + """A source that cannot keep a version (``pinned_snapshot`` is ``None``) is read + whole, as on main, never projected and never refused (review of PR 687).""" + monkeypatch.setattr( + source_module.SpiralDBTableSource, "pinned_snapshot", lambda self: None + ) + _, expected = _compare( + monkeypatch, + _job(lambda s: s.select_data_columns(["x"], label="sx")), + route, + ["sx"], + ) + got = _run(_job(lambda s: s.select_data_columns(["x"], label="sx")), route, ["sx"]) + assert got["scans"] == expected["scans"] == [_ALL] + + +# -- Every member of the collected output answers as main's (review of PR 687). -- + +# Whether a member describes the stream (no row read), says when it was made (no row +# read), reads the rows (one whole read of the pinned snapshot, in total), or builds a +# step over the stream (nothing read until the step's rows are read, then at most one +# whole read). The collected output is main's own class, so every member is main's; +# these cases check that only its row access reads the source. + + +def _other() -> Any: + from orcapod.sources import ArrowTableSource + + table = pa.table( + { + "unit": pa.array(["u1", "u2"], pa.large_string()), + "z": pa.array([1, 2], pa.int64()), + } + ) + return ArrowTableSource( + table, tag_columns=["unit"], source_id="other", tag_only_columns=True + ) + + +def _identity_digest(s: Any) -> Any: + return s.data_context.semantic_hasher.hash_object(s.identity_structure()) + + +async def _async_rows(s: Any) -> list[Any]: + return [pair async for pair in s.async_iter_data()] + + +async def _channel_table(channel: Any) -> pa.Table: + return (await channel.to_stream()).as_table(all_info=True) + + +_DESCRIBE: dict[str, Callable[[Any], Any]] = { + "keys": lambda s: (s.keys(), s.keys(all_info=True)), + "output_schema": lambda s: (s.output_schema(), s.output_schema(all_info=True)), + "arrow_schema": lambda s: s.arrow_schema(), + "arrow_types_declared": lambda s: s.arrow_types_declared, + "data_tags": lambda s: s.data_tags, + "data_context": lambda s: s.data_context.context_key, + "data_context_key": lambda s: s.data_context_key, + "orcapod_config": lambda s: s.orcapod_config, + "label": lambda s: s.label, + "has_assigned_label": lambda s: s.has_assigned_label, + "computed_label": lambda s: s.computed_label(), + "producer": lambda s: s.producer, + "upstreams": lambda s: s.upstreams, + "explain": lambda s: s.explain().text(), + "content_hash_generation": lambda s: s.content_hash_generation() is not None, + "content_hash": lambda s: s.content_hash(), + "pipeline_hash": lambda s: s.pipeline_hash(), + "node_hash": lambda s: s.node_hash(), + "source_chain": lambda s: s.source_chain(), + "name_chain": lambda s: s.name_chain(), + "pipeline_identity_structure": lambda s: s.data_context.semantic_hasher.hash_object( + s.pipeline_identity_structure() + ), + # By content (the stream class) or by object (``RowsOnRead``), as main's. + "__hash__": lambda s: (hash(s) == hash(s), hash(s) == s.content_hash().to_int()), + "__str__": lambda s: str(s), + "__repr__": lambda s: repr(s), + "_display_name": lambda s: display_name(s), + "_typed_zero_row_table": lambda s: typed_zero_row_table(s), + "_schema_requires_io": lambda s: ( + schema_requires_io(s, ColumnConfig()), + schema_requires_io(s, ColumnConfig.handle_config(None, all_info=True)), + ), + "_identity_chains": lambda s: (s.content_hash(), s.pipeline_hash()), + "head(0)": lambda s: s.head(0), + # Sorted, without a row hash: the zero-row table is sorted, no row is read. + "head(0, sorted)": lambda s: s.head(0, columns={"sort_by_tags": True}), + "hasattr": lambda s: tuple( + hasattr(s, name) + for name in ("data_tags", "as_polars_df", "_repr_html_", "source_id", "_x") + ), + "clear_cache": lambda s: s.clear_cache(), + # When it was made: present, and the same staleness. + "last_modified": lambda s: s.last_modified is not None, + "is_stale": lambda s: s.is_stale, + "updated_since": lambda s: s.updated_since( + datetime.datetime(2000, 1, 1, tzinfo=datetime.timezone.utc) + ), +} + +_ROWS: dict[str, Callable[[Any], Any]] = { + "as_table": lambda s: s.as_table(all_info=True), + "iter_data": lambda s: list(s.iter_data()), + "__iter__": lambda s: list(s), + "flow": lambda s: s.flow(), + "run": lambda s: s.run(), + "head": lambda s: s.head(3, all_info=True), + # ``all_info`` asks for a row hash, sorted: every row is hashed, as on main + # (review of PR 687 at 267a5edc, finding 2). + "head(0, all_info)": lambda s: s.head(0, all_info=True), + "as_df": lambda s: s.as_df(all_info=True), + "as_polars_df": lambda s: s.as_polars_df(), + "as_lazy_frame": lambda s: s.as_lazy_frame().collect(), + "as_pandas_df": lambda s: s.as_pandas_df(index_by_tags=True), + "identity_structure": _identity_digest, + "__eq__": lambda s: s == s, + "_repr_html_": lambda s: s._repr_html_(), +} + +_STEPS: dict[str, Callable[[Any], Any]] = { + "join": lambda s: s.join(_other()), + "rejoin": lambda s: s.rejoin(), + "semi_join": lambda s: s.semi_join(_other()), + "map_tags": lambda s: s.map_tags(unit="u"), + "map_data": lambda s: s.map_data(x="x2"), + "map_columns": lambda s: s.map_columns(y="y2"), + "batch": lambda s: s.batch(4), + "group_by": lambda s: s.group_by("unit"), + "polars_filter": lambda s: s.polars_filter(unit="u1"), + "filter": lambda s: s.filter(unit="u1"), + "drop_nulls": lambda s: s.drop_nulls(), + "tag_by": lambda s: s.tag_by("x"), + "add_tags": lambda s: s.add_tags(cohort="A"), + "select_tag_columns": lambda s: s.select_tag_columns(["unit"]), + "select_data_columns": lambda s: s.select_data_columns(["x"]), + "drop_tag_columns": lambda s: s.drop_tag_columns(["t"]), + "drop_data_columns": lambda s: s.drop_data_columns(["blob"]), + "drop_columns": lambda s: s.drop_columns("blob"), + "select_columns": lambda s: s.select_columns("unit", "t", "x"), + "pick": lambda s: s.pick("blob", "k"), + "index": lambda s: s.index("blob", 0), + "open_channel": lambda s: s.open_channel(), + "async_iter_data": lambda s: s.async_iter_data(), +} + + +def _consume(name: str, step: Any) -> Any: + """Read a step's rows.""" + if name == "open_channel": + return asyncio.run(_channel_table(step)) + if name == "async_iter_data": + return asyncio.run(_rows_of_generator(step)) + return step.as_table(all_info=True) + + +async def _rows_of_generator(generator: Any) -> list[Any]: + return [pair async for pair in generator] + + +def _norm(value: Any) -> Any: + """``value`` in a form two runs' outputs compare by.""" + import pandas as pd + import polars as pl + + from orcapod.core.streams.view import StreamView + + if isinstance(value, pa.Table): + return ("table", value.schema.to_string(show_schema_metadata=True), value) + if isinstance(value, pl.DataFrame): + return ("polars", _norm(value.to_arrow())) + if isinstance(value, pd.DataFrame): + return ("pandas", value.to_dict(orient="split")) + if isinstance(value, StreamView): + fields = dataclasses.asdict(value) + fields["table"] = _norm(value.table) + return ("view", fields) + if isinstance(value, list): + return [_norm(v) for v in value] + if isinstance(value, tuple) and len(value) == 2 and hasattr(value[1], "as_dict"): + tag, data = value + return _pair(tag, data) + if isinstance(value, tuple): + return tuple(_norm(v) for v in value) + return value + + +def _same_value(got: Any, expected: Any) -> None: + if isinstance(got, pa.Table): + _same(got, expected) + return + if ( + isinstance(got, tuple) + and len(got) == 3 + and isinstance(got[0], str) + and got[0] == "table" + ): + assert got[1] == expected[1] + _same(got[2], expected[2]) + return + if isinstance(got, (tuple, list)) and not isinstance(got, str): + assert type(got) is type(expected) and len(got) == len(expected) + for g, e in zip(got, expected, strict=True): + _same_value(g, e) + return + if isinstance(got, dict): + assert got.keys() == expected.keys() + for key in got: + _same_value(got[key], expected[key]) + return + assert got == expected + + +def _outcome(call: Callable[[], Any]) -> tuple[str, Any]: + try: + return "value", call() + except Exception as error: # noqa: BLE001 - the same exception is the same answer + return "raises", (type(error).__name__, str(error)) + + +def _collected_output(route: str, *, whole: bool, monkeypatch: Any) -> Any: + """A select-only job's collected source output, run on ``route``; ``whole`` turns + the projection off (main's output).""" + with monkeypatch.context() as m: + if whole: + _read_whole(m) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + source.select_data_columns(["x"], label="sx") + node = next(n for n in job.nodes.values() if n.node_type == "source") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(node, job.nodes["sx"]) + orchestrator = ( + SyncPipelineOrchestrator() + if route == "sync" + else AsyncPipelineOrchestrator() + ) + output = orchestrator.run(dag).node_outputs[node] + # Main's own class on each route: the table-built stream, or the rows. + assert type(output) is (_RowsOfStream if route == "sync" else RowsOnRead) + return output + + +_MEMBER_CASES = ( + [pytest.param("describe", name, id=f"describe-{name}") for name in _DESCRIBE] + + [pytest.param("rows", name, id=f"rows-{name}") for name in _ROWS] + + [pytest.param("step", name, id=f"step-{name}") for name in _STEPS] +) + + +@pytest.mark.filterwarnings( + "ignore::orcapod.core.operators.filters.PolarsFilterWarning" +) +@pytest.mark.parametrize("route", ["sync", "async"]) +@pytest.mark.parametrize(("kind", "name"), _MEMBER_CASES) +def test_each_member_answers_as_main_and_reads_only_for_rows( + project: Any, monkeypatch: pytest.MonkeyPatch, route: str, kind: str, name: str +) -> None: + """Each member of the collected output gives main's value (or main's exception). + A member that describes the stream reads no row; a member that reads the rows + makes exactly one whole scan of the pinned snapshot; a step over the stream reads + nothing until its rows are read, then at most one whole scan (review of PR 687).""" + expected_output = _collected_output(route, whole=True, monkeypatch=monkeypatch) + got_output = _collected_output(route, whole=False, monkeypatch=monkeypatch) + calls = {"describe": _DESCRIBE, "rows": _ROWS, "step": _STEPS}[kind] + call = calls[name] + + def answer(output: Any) -> tuple[tuple[str, Any], list[list[str]]]: + fake.scan_log.clear() + fake.count_log.clear() + kind_of, value = _outcome(lambda: call(output)) + built_scans = _row_scans() + if kind == "step": + assert built_scans == [], "building a step reads nothing" + if kind_of == "value": + kind_of, value = _outcome(lambda: _consume(name, value)) + return (kind_of, _norm(value)), _row_scans() + + expected, _ = answer(expected_output) + got, scans = answer(got_output) + assert got[0] == expected[0], (got, expected) + _same_value(got[1], expected[1]) + if kind == "describe": + assert scans == [] + elif kind == "rows" and name == "__eq__" and route == "async": + # Main's output on this route (``RowsOnRead``) compares by object. + assert scans == [] + elif kind == "rows": + assert scans == [_ALL] + else: + assert scans in ([], [_ALL]) + + +# -- The review findings on the mirror class (review of PR 687, head b3d9eac7). -- + + +def test_outputs_of_two_routes_compare_and_hash_as_main( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Sync and async outputs, and two outputs of one route, compare and hash as + main's do (the mirror compared a sync and an async output equal with unequal + hashes).""" + + def answers(*, whole: bool) -> tuple[Any, ...]: + sync_a = _collected_output("sync", whole=whole, monkeypatch=monkeypatch) + sync_b = _collected_output("sync", whole=whole, monkeypatch=monkeypatch) + async_a = _collected_output("async", whole=whole, monkeypatch=monkeypatch) + async_b = _collected_output("async", whole=whole, monkeypatch=monkeypatch) + fake.scan_log.clear() + fake.count_log.clear() + cross = ( + sync_a == async_a, + async_a == sync_a, + sync_a != async_a, + hash(sync_a) == hash(async_a), + ) + cross_scans = _row_scans() + same_route = ( + sync_a == sync_b, + hash(sync_a) == hash(sync_b), + async_a == async_b, + async_a == async_a, + hash(async_a) == hash(async_b), + ) + return cross, cross_scans, same_route + + got = answers(whole=False) + expected = answers(whole=True) + assert got[0] == expected[0] + assert got[0][:3] == (False, False, True) + # Comparing two routes' outputs reads nothing, as on main. + assert got[1] == expected[1] == [] + assert got[2] == expected[2] + + +def test_a_shallow_copy_shares_the_one_whole_read( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """A shallow copy of a collected output, made before either is read, reads the + pinned snapshot at most once with its original: the whole read is held by an + object both reference (the mirror read it once per copy).""" + expected = _collected_output("sync", whole=True, monkeypatch=monkeypatch) + output = _collected_output("sync", whole=False, monkeypatch=monkeypatch) + fake.scan_log.clear() + fake.count_log.clear() + copied = copy.copy(output) + assert _row_scans() == [] + assert type(copied) is type(expected) + _same(copied.as_table(all_info=True), expected.as_table(all_info=True)) + _same(output.as_table(all_info=True), expected.as_table(all_info=True)) + assert _row_scans() == [_ALL] + # A copy of the async output fails as main's does (``RowsOnRead.__getattr__``). + async_expected = _collected_output("async", whole=True, monkeypatch=monkeypatch) + async_output = _collected_output("async", whole=False, monkeypatch=monkeypatch) + got = _outcome(lambda: copy.copy(async_output)) + want = _outcome(lambda: copy.copy(async_expected)) + assert got[0] == want[0] + if got[0] == "raises": + assert got[1][0] == want[1][0] + + +@pytest.mark.parametrize("read_first", [True, False]) +def test_the_async_output_keeps_release_built( + project: Any, monkeypatch: pytest.MonkeyPatch, read_first: bool +) -> None: + """The async collected output is main's ``RowsOnRead``, with ``release_built``: a + read after it builds the same table again, from the one whole read of the + pinned snapshot (the mirror had no ``release_built``).""" + expected = _collected_output("async", whole=True, monkeypatch=monkeypatch) + output = _collected_output("async", whole=False, monkeypatch=monkeypatch) + fake.scan_log.clear() + fake.count_log.clear() + if read_first: + _same(output.as_table(all_info=True), expected.as_table(all_info=True)) + output.release_built() + expected.release_built() + assert _row_scans() == ([_ALL] if read_first else []) + _same(output.as_table(all_info=True), expected.as_table(all_info=True)) + rows = [_pair(t, d) for t, d in output] + assert rows == [_pair(t, d) for t, d in expected] + output.release_built() + _same(output.as_table(all_info=True), expected.as_table(all_info=True)) + assert _row_scans() == [_ALL] + + +_WITH_MAP = pa.schema( + [ + pa.field("unit", pa.large_string(), False), + pa.field("t", pa.int64(), False), + pa.field("x", pa.float64(), False), + pa.field("m", pa.map_(pa.int32(), pa.int32())), + ] +) + + +def test_a_source_over_a_table_with_a_map_column_is_refused( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """No projected output holds a map: the source refuses the table when it is built, + as on main (a map cannot be hashed), so a sorted ``head(0)`` asking for a row hash + cannot meet one there (review of PR 687 at 267a5edc, finding 2).""" + monkeypatch.setattr(connector_module, "_warned_unrecorded", set()) + rows = pa.Table.from_pylist( + [{"unit": "u1", "t": 1, "x": 0.5, "m": [(1, 1)]}], schema=_WITH_MAP + ) + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p") + made.create_table( + "default.maps", key_schema=[_WITH_MAP.field("unit"), _WITH_MAP.field("t")] + ).write(rows) + fake.migrate("p", {"maps": _WITH_MAP}) + with pytest.raises(ValueError, match="map"): + SpiralDBTableSource("p", "maps", tag_only_columns=True) + + +@pytest.mark.parametrize( + "config", + [ + {"sort_by_tags": True, "content_hash": True}, + {"sort_by_tags": True, "content_hash": True, "source": True}, + ], + ids=["hash", "hash_and_source"], +) +def test_a_sorted_head_0_with_a_row_hash_takes_mains_path_on_a_projected_output( + project: Any, config: dict[str, Any] +) -> None: + """Asked for a row hash, a projected output's sorted ``head(0)`` reads its rows + whole and hashes them all, as main does on the populated table, so it raises what + main raises; without one it sorts its zero-row table and reads no row (review of + PR 687 at 267a5edc, finding 2).""" + output, whole, _ = _projected(project) + fake.scan_log.clear() + fake.count_log.clear() + sorted_only = output.head(0, columns={"sort_by_tags": True}) + assert _row_scans() == [] + expected_sorted = whole.head(0, columns={"sort_by_tags": True}) + assert sorted_only.table.equals(expected_sorted.table, check_metadata=True) + assert sorted_only.total_rows == expected_sorted.total_rows + shown = output.head(0, columns=config) + assert _row_scans() == [_ALL] + expected = whole.head(0, columns=config) + assert shown.table.equals(expected.table, check_metadata=True) + assert shown.total_rows == expected.total_rows + assert shown.header() == expected.header() + + +# -- The async route streams the narrowed read batch by batch, as main streams the +# -- whole one (review of PR 687, thread on ``SourceNodeBase.async_execute``). -- + + +class _RecordingWriter: + """An output channel that records each row sent, in the shared event log.""" + + def __init__(self, events: list[tuple[str, int]]) -> None: + self._events = events + self.rows: list[Any] = [] + + async def send(self, item: Any) -> None: + self.rows.append(item) + self._events.append(("send", 1)) + + async def close(self) -> None: + self._events.append(("close", 0)) + + +def _record_scanned_batches( + monkeypatch: pytest.MonkeyPatch, events: list[tuple[str, int]] +) -> None: + """Record each batch the source hands on and the end of its scan.""" + original = source_module.SpiralDBTableSource._read_batches # pyright: ignore[reportPrivateUsage] # the scan under test + + def recorded(self: Any, *args: Any, **kwargs: Any) -> Any: + for stream in original(self, *args, **kwargs): + events.append(("batch", stream.as_table().num_rows)) + yield stream + events.append(("scan_end", 0)) + + monkeypatch.setattr(source_module.SpiralDBTableSource, "_read_batches", recorded) + + +def _async_source_run( + monkeypatch: pytest.MonkeyPatch, *, projected: bool, **source_args: Any +) -> tuple[list[tuple[str, int]], list[Any]]: + """A source node's ``async_execute`` (``x`` read when ``projected``, else main's + whole route): the events of its scan and sends, and the rows sent.""" + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + SpiralDBTableSource( + "p", "wide", tag_only_columns=True, **source_args + ).select_data_columns(["x"], label="sx") + node = next(n for n in job.nodes.values() if n.node_type == "source") + events: list[tuple[str, int]] = [] + writer = _RecordingWriter(events) + with monkeypatch.context() as m: + _record_scanned_batches(m, events) + columns = ["x"] if projected else None + asyncio.run(node.async_execute(writer, read_columns=columns)) + return events, writer.rows + + +def _most_rows_held(events: list[tuple[str, int]]) -> int: + """The most rows read from the scan and not yet sent, at any point.""" + held = most = 0 + for kind, rows in events: + if kind == "batch": + held += rows + elif kind == "send": + held -= rows + most = max(most, held) + return most + + +@pytest.mark.parametrize("batch_rows", [1, 4]) +def test_the_async_projected_route_streams_as_mains_whole_route( + project: Any, monkeypatch: pytest.MonkeyPatch, batch_rows: int +) -> None: + """The first row reaches the output before the scan ends, and the scan and the + sends interleave exactly as on main's whole route: at most one batch is held.""" + got, got_rows = _async_source_run( + monkeypatch, projected=True, batch_rows=batch_rows + ) + main, main_rows = _async_source_run( + monkeypatch, projected=False, batch_rows=batch_rows + ) + assert got.index(("send", 1)) < got.index(("scan_end", 0)) + assert got == main + assert _most_rows_held(got) == _most_rows_held(main) <= batch_rows + assert len(got_rows) == len(main_rows) == 6 + # The rows sent are main's, without the data columns no successor reads. + for (tag, data), (main_tag, main_data) in zip(got_rows, main_rows, strict=True): + assert tag.as_dict(all_info=True) == main_tag.as_dict(all_info=True) + assert data.keys() == ("x",) + assert data.as_dict(all_info=True) == { + k: v + for k, v in main_data.as_dict(all_info=True).items() + if k not in ("y", "blob", "_source_y", "_source_blob") + } + + +def test_the_async_projected_route_holds_no_more_than_main( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Peak memory while sending a larger table's rows: the projected route's is + main's whole route's, one batch held (Python allocations, ``tracemalloc``).""" + import tracemalloc + + monkeypatch.setattr(fake, "scan_batch_rows", 64) + many = pa.Table.from_pylist( + [ + {"unit": f"u{i % 7}", "t": i, "x": i * 0.5, "y": i, "blob": bytes(256)} + for i in range(3000) + ], + schema=_WRITTEN, + ) + project.table("default.wide").write(many) + + def peak(*, projected: bool) -> int: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + SpiralDBTableSource( + "p", "wide", tag_only_columns=True, batch_rows=64 + ).select_data_columns(["x"], label="sx") + node = next(n for n in job.nodes.values() if n.node_type == "source") + + class _Dropping: + async def send(self, item: Any) -> None: + del item + + async def close(self) -> None: + pass + + tracemalloc.start() + try: + asyncio.run( + node.async_execute( + _Dropping(), read_columns=["x"] if projected else None + ) + ) + return tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + + # Each route once untraced first, so one-time costs (imports, caches, the first + # thread pool) count for neither; then the lowest of three traced runs, since a + # tracer or coverage adds noise to a single one. + peak(projected=False) + peak(projected=True) + main = min(peak(projected=False) for _ in range(3)) + got = min(peak(projected=True) for _ in range(3)) + # Both hold one batch: locally the peaks differ by about 2% (the narrowed batch's + # own stream). A route that kept the narrowed read whole held 14 times main's + # peak on this table, growing with its rows; the margin absorbs the noise of a + # traced run under coverage without letting that through. + assert got <= main * 1.5, (got, main) + + +# -- Several columns kept, in both orders, as plain tags and as data-tags (review of +# -- PR 687, thread on the selection cases). -- + +_SEVERAL: dict[str, Callable[[SpiralDBTableSource, list[str]], object]] = { + "select_data_columns": lambda s, names: s.select_data_columns(names, label="sel"), + "select_columns": lambda s, names: s.select_columns(*names, label="sel"), +} + + +@pytest.mark.filterwarnings( + "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" +) +@pytest.mark.parametrize("route", ["sync", "async"]) +@pytest.mark.parametrize("operator", sorted(_SEVERAL)) +@pytest.mark.parametrize("data_tags", [False, True], ids=["plain_tags", "data_tags"]) +def test_several_kept_columns_in_either_order_give_the_whole_reads_rows( + project: Any, + monkeypatch: pytest.MonkeyPatch, + route: str, + operator: str, + data_tags: bool, +) -> None: + """Two data columns kept and one left out, named in either order: the scan holds + exactly the kept columns, the rows, stored rows and hashes are the whole read's, + and the result keeps the source's column order whatever the order named. With + data-tags, ``select_data_columns`` names one data-tag (``unit``) and leaves the + other (``t``) a plain tag; ``select_columns`` names both.""" + names = ["x", "y"] + if operator == "select_columns": + names = ["t", "unit", *names] + if data_tags: + names = [*names, "unit"] if operator == "select_data_columns" else names + results = [] + for order in (names, list(reversed(names))): + build = _job( + lambda s, order=order: _SEVERAL[operator](s, order), + log_labels=("sel",), + tag_only_columns=not data_tags, + ) + got, _ = _compare(monkeypatch, build, route, ["sel"]) + assert got["scans"] == [["t", "unit", "x", "y"]] + results.append(got) + forward, backward = results + _same(backward["nodes"]["sel"], forward["nodes"]["sel"]) + assert backward["hashes"]["sel"][2] == forward["hashes"]["sel"][2] + tag_keys, data_keys = forward["hashes"]["sel"][2] + assert tag_keys == ("unit", "t") + expected_data = ("unit", "x", "y") if data_tags else ("x", "y") + if data_tags and operator == "select_columns": + expected_data = ("unit", "t", "x", "y") + assert data_keys == expected_data + + +# -- Two concurrent readers of one projected output (review of PR 687, threads on +# -- ``RowsOnRead.iter_data`` and ``head(0)``). -- + + +def _interleave(output: Any, other_reader: Callable[[], Any]) -> list[Any]: + """Make ``output``'s first read of its pending whole read wait while another + thread runs ``other_reader`` to its end (which takes the rows and clears the + pending read): the interleaving two concurrent readers can meet. Returns the + other thread's outcome, once it ran.""" + import threading + + pending = output.__dict__.pop("_row_loader") + outcome: list[Any] = [] + state = {"waited": False} + + class Interleaved: + def __get__(self, instance: Any, owner: Any) -> Any: + if instance is None: + return self + value = instance.__dict__["_interleaved_loader"] + if not state["waited"]: + # The first reader has read the attribute; the other one runs now. + state["waited"] = True + other = threading.Thread( + target=lambda: outcome.append(_outcome(other_reader)) + ) + other.start() + other.join() + return value + + def __set__(self, instance: Any, value: Any) -> None: + instance.__dict__["_interleaved_loader"] = value + + output.__dict__["_interleaved_loader"] = pending + output.__class__ = type( + type(output).__name__, (type(output),), {"_row_loader": Interleaved()} + ) + return outcome + + +def test_two_threads_reading_the_async_output_both_get_mains_rows( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """``iter_data`` reads the pending whole read once: a second thread that takes the + rows between the check and the call leaves the first one main's rows.""" + expected_output = _collected_output("async", whole=True, monkeypatch=monkeypatch) + expected = [_pair(t, d) for t, d in expected_output.iter_data()] + output = _collected_output("async", whole=False, monkeypatch=monkeypatch) + fake.scan_log.clear() + fake.count_log.clear() + other = _interleave(output, lambda: [_pair(t, d) for t, d in output.iter_data()]) + got = _outcome(lambda: [_pair(t, d) for t, d in output.iter_data()]) + assert other == [("value", expected)] + assert got == ("value", expected) + assert _row_scans() == [_ALL] + + +@pytest.mark.parametrize("sort", [False, True], ids=["unsorted", "sorted"]) +def test_two_threads_head_0_and_a_full_read_both_answer_as_main( + project: Any, sort: bool +) -> None: + """``head(0)`` reads the pending whole read once: a full read in another thread + that takes the rows between the check and the count leaves it main's head.""" + output, whole, _ = _projected(project) + columns = {"sort_by_tags": sort} + expected = whole.head(0, columns=columns) + fake.scan_log.clear() + fake.count_log.clear() + other = _interleave(output, lambda: output.as_table(all_info=True)) + shown = _outcome(lambda: output.head(0, columns=columns)) + assert _row_scans() == [_ALL] + assert len(other) == 1 and other[0][0] == "value" + _same(other[0][1], whole.as_table(all_info=True)) + assert shown[0] == "value", shown + assert shown[1].table.equals(expected.table, check_metadata=True) + assert shown[1].total_rows == expected.total_rows == 6 diff --git a/tests/test_databases/test_spiraldb_projection.py b/tests/test_databases/test_spiraldb_projection.py index a883c523a..65e148068 100644 --- a/tests/test_databases/test_spiraldb_projection.py +++ b/tests/test_databases/test_spiraldb_projection.py @@ -319,10 +319,11 @@ def heads() -> tuple[str, str, list[Any], list[Any]]: @pytest.mark.parametrize("route", ["sync", "async"]) -def test_a_job_reads_the_whole_table_and_gives_the_same_rows( +def test_a_job_scans_only_the_selected_columns_and_gives_the_same_rows( project: Any, route: str ) -> None: - # The job route is unchanged by ITL-1776: the source node reads every column. + # In a job the orchestrators give the source node its successors' columns + # (ITL-1798; tests/test_databases/test_spiraldb_job_projection.py). def config() -> dict[str, bool]: return {"source": True, "system_tags": True, "sort_by_tags": True} @@ -341,7 +342,7 @@ def config() -> dict[str, bool]: job.run() else: asyncio.run(job.run_async()) - assert _row_scans() == [_ALL] + assert _row_scans() == [["t", "unit", "x"]] # A job node lays out its columns in row order (presentation only). in_job = job.nodes["selected"].as_table(columns=config()) _assert_same_table(in_job.select(standalone.column_names), standalone) diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index ac7ede727..a2869934b 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -5,7 +5,7 @@ import asyncio import json import re -from collections.abc import Collection, Iterable +from collections.abc import Collection, Iterable, Iterator from pathlib import Path from typing import Any, cast @@ -1581,6 +1581,14 @@ def projected_table( ) -> pa.Table | None: return None + def projected_batch_streams( + self, data_columns: Collection[str] + ) -> Iterator[StreamProtocol] | None: + return None + + def pinned_snapshot(self) -> SourceProtocol | None: + return None + def to_config( self, db_registry: DatabaseRegistryProtocol | None = None ) -> dict[str, Any]: