diff --git a/changelog.d/ITL-1776.md b/changelog.d/ITL-1776.md new file mode 100644 index 000000000..642e4af08 --- /dev/null +++ b/changelog.d/ITL-1776.md @@ -0,0 +1,10 @@ +### Changed + +- A column selection placed directly on a `SpiralDBTableSource` and read outside a + job (`select_data_columns`, `drop_data_columns`, `select_columns`, `drop_columns`, + and the automatic selection before a function pod) now scans only the columns + 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. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 46c83a745..175544fe1 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -647,6 +647,15 @@ print(first.row_count_estimate) # rows in the whole table; reads every key to c metadata lookup; it reads no row and moves nothing). `check_for_new_data()`, which every run calls first, moves the pin. `head()` and the preview never ask. +**Reading only the columns a selection keeps.** A column selection placed directly on the +source (`select_data_columns`, `drop_data_columns`, `select_columns`, `drop_columns`, or the +selection a function pod adds before itself for columns it does not take) asks SpiralDB for +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. + **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: `limit=`, `where=`, or a larger `max_rows` (`max_rows=None` removes the cap). When nothing diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 8a3b5434c..266bd4551 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -3,13 +3,20 @@ from collections.abc import Collection, Sequence from typing import Any, ClassVar +import pyarrow as pa + from orcapod.channels import ReadableChannel, WritableChannel 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.errors import InputValidationError -from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol +from orcapod.protocols.core_protocols import ( + DataProtocol, + SourceProtocol, + StreamProtocol, + TagProtocol, +) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils.schema_utils import column_names @@ -30,6 +37,25 @@ def _canonical_columns(columns: str | Collection[str]) -> tuple[str, ...]: return tuple(sorted(set(column_names(columns)))) +def _input_table( + stream: StreamProtocol, kept_data: Collection[str], columns: dict[str, Any] +) -> pa.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 + 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): + projected = stream.projected_table(kept_data, columns=columns) + if projected is not None: + return projected + return stream.as_table(columns=columns) + + def require_a_data_column(remaining: Collection[str]) -> None: """Refuse a column operation whose result would have no data column. @@ -229,8 +255,10 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All data columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( - columns={ + table = _input_table( + stream, + new_data_columns, + { "source": True, "system_tags": True, "context": True, @@ -244,9 +272,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # A data-tag whose data column is removed keeps its column as a plain # tag with the same values (specification section 7.2). data_tags = stream_data_tags(stream) + dropped = { + *(c for c in data_columns_to_drop if c not in data_tags), + *associated_source_fields, + } + # A source that scanned fewer columns has left some out already. modified_table = table.drop_columns( - [c for c in data_columns_to_drop if c not in data_tags] - + associated_source_fields + [c for c in table.column_names if c in dropped] ) return ArrowTableStream._from_derived_table( @@ -534,20 +566,26 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: associated_source_columns = [ f"{constants.SOURCE_PREFIX}{c}" for c in columns_to_drop ] - table = stream.as_table( - columns={ + table = _input_table( + stream, + [c for c in data_columns if c not in columns_to_drop], + { "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A data-tag whose data column is removed keeps its column as a plain # tag with the same values (specification section 7.2). data_tags = stream_data_tags(stream) + dropped = { + *(c for c in columns_to_drop if c not in data_tags), + *associated_source_columns, + } + # A source that scanned fewer columns has left some out already. modified_table = table.drop_columns( - [c for c in columns_to_drop if c not in data_tags] - + associated_source_columns + [c for c in table.column_names if c in dropped] ) return ArrowTableStream._from_derived_table( @@ -774,13 +812,15 @@ def validate_unary_input(self, stream: StreamProtocol) -> None: def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_columns, data_columns = self._user_columns(stream) tags_removed, data_removed = self._removals(tag_columns, data_columns) - table = stream.as_table( - columns={ + table = _input_table( + stream, + [c for c in data_columns if c not in data_removed], + { "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) removed = { *tags_removed, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 9869fa2d0..27801241e 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -1,7 +1,7 @@ from __future__ import annotations import warnings -from collections.abc import Callable +from collections.abc import Callable, Collection from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast from orcapod import contexts @@ -400,6 +400,29 @@ def row_limit(self) -> int | None: its kind can be limited (``SpiralDBTableSource(limit=...)``).""" return None + def projected_table( + self, + data_columns: Collection[str], + *, + columns: ColumnConfig | dict[str, Any] | None = None, + ) -> "pa.Table | None": + """Read only the columns needed for ``data_columns``, when this kind can. + + Asked by a column selection placed directly on the source (ITL-1776): + ``SelectDataColumns``, ``DropDataColumns``, ``SelectColumns`` and + ``DropColumns``. A kind that can scan fewer columns returns + ``as_table(columns=columns)`` without the data columns not in + ``data_columns`` (never a tag column, also a data-tag) and their + source-info columns; everything else in it is what the whole read gives. + It is an execution detail: no identity, schema, record id or stored path + depends on it. + + Returns: + ``None``: the source is read whole. ``SpiralDBTableSource`` scans fewer + columns. + """ + 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 1a48e88a5..09742bbee 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -48,11 +48,18 @@ import copy import dataclasses import os -from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping +from collections.abc import ( + AsyncIterator, + Collection, + Generator, + Iterator, + Mapping, + Sequence, +) from concurrent.futures import ThreadPoolExecutor from threading import Lock from types import TracebackType -from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, cast import pyarrow as pa from typing_extensions import override @@ -83,6 +90,7 @@ require_same_process, ) from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError +from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ColumnRef, Condition from orcapod.types.condition import check_float_equalities, check_restriction from orcapod.utils import arrow_utils @@ -981,7 +989,11 @@ def _key_tokens(self, table: "pa.Table") -> list[str]: ) from exc def _batch_streams( - self, *, with_source_info: bool = True, count_first: bool = True + self, + *, + with_source_info: bool = True, + table_columns: Sequence[str] | None = None, + count_first: bool = True, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once and yield its rows as streams of at most ``batch_rows`` rows. @@ -989,6 +1001,7 @@ def _batch_streams( Args: with_source_info: As for ``_read_batches``. + table_columns: As for ``_read_batches``. count_first: As for ``_read_batches``. Raises: @@ -1005,6 +1018,7 @@ def _batch_streams( limit=self._limit, max_rows=self._max_rows, with_source_info=with_source_info, + table_columns=table_columns, count_first=count_first, ) @@ -1016,6 +1030,7 @@ def _read_batches( limit: int | None, max_rows: int | None, with_source_info: bool = True, + table_columns: Sequence[str] | None = None, count_first: bool = True, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``. @@ -1030,11 +1045,14 @@ def _read_batches( with_source_info: Whether each stream holds its rows' source-info tokens. ``False`` only where the caller returns no source-info column and hashes no row (``_whole_table``): the streams then hold null tokens. + table_columns: The table columns to scan, in the table's order; ``None`` + scans every column. Only ``projected_table`` passes them, and they + always hold every tag and key column (ITL-1776). count_first: Whether an unrestricted read that ``limit`` does not keep under ``max_rows`` counts the table's rows before it hands any row on. A - caller that hands no row on before the read ends (``as_table``) passes - ``False``: the scan then stops one row past ``max_rows`` and raises the - same error, with no separate count (ITL-1457). + caller that hands no row on before the read ends (``as_table`` or + ``projected_table``) passes ``False``: the scan then stops one row past + ``max_rows`` and raises the same error, with no separate count (ITL-1457). Raises: SourceTooLargeError: If the read would return, or returns, more than @@ -1063,10 +1081,21 @@ def _read_batches( seen = 0 # Keys must be unique across the whole read, not only within a slice. identifiers: set[str] = set() + expected_schema = self._table_schema + if table_columns is not None: + scanned = set(table_columns) + expected_schema = pa.schema( + [f for f in self._table_schema if f.name in scanned], + metadata=cast( + "dict[bytes | str, bytes | str] | None", + self._table_schema.metadata, + ), + ) for batch in table.scan_batches( where=None if self._condition.is_empty else self._condition, limit=scan_limit, asof=asof, + columns=None if table_columns is None else expected_schema.names, ): for start in range(0, max(batch.num_rows, 1), self._batch_rows): raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)]) @@ -1076,10 +1105,10 @@ def _read_batches( rows = arrow_utils.drop_system_columns(raw) # Metadata too: field metadata is how a column's logical type is # recorded, and the schema hash was computed at construction. - if not rows.schema.equals(self._table_schema, check_metadata=True): + if not rows.schema.equals(expected_schema, check_metadata=True): raise ValueError( f"SpiralDB table {self._qualified!r}: " - f"{_schema_difference(rows.schema, self._table_schema)}. " + f"{_schema_difference(rows.schema, expected_schema)}. " "The table changed after the source was built; build the " "source again to read it as it is now." ) @@ -1158,6 +1187,53 @@ def as_table( all_info=all_info, ) + @override + def projected_table( + self, + data_columns: Collection[str], + *, + columns: ColumnConfig | dict[str, Any] | None = None, + ) -> "pa.Table | None": + """Scan only the columns needed for ``data_columns`` (ITL-1776). + + The table is ``as_table(columns=columns)`` without the data columns not in + ``data_columns`` and their source-info columns: the other columns, rows, + values, types, record ids, system tags (named with the whole source's + schema hash) and source-info tokens are those of the whole read. The scan + reads every tag column, every key column (the record ids are built from + them), the key column behind each ``tags_as_data`` copy, and the columns of + the ``where`` condition (dropped after the comparison); of the other + columns, only those in ``data_columns``. With no rows, the whole source's + zero-row table without the same columns: never computed from a read. + + Returns: + The table, or ``None`` when there are no data columns to omit or the + column configuration requests a hash of each whole row. + """ + config = ColumnConfig.handle_config(columns) + if config.content_hash: + 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: + 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 = self._whole_table( + self._batch_streams( + with_source_info=_reads_source_info(config), + table_columns=table_columns, + count_first=False, + ), + columns=columns, + all_info=False, + ) + 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]) + def _whole_table( self, streams: Iterator["ArrowTableStream"], diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 7b53c6a47..61e695bd9 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -25,7 +25,7 @@ import urllib.parse import urllib.request import warnings -from collections.abc import Iterator, Mapping +from collections.abc import Iterator, Mapping, Sequence from contextlib import contextmanager from copy import copy from threading import Lock, local @@ -670,6 +670,7 @@ def scan_batches( where: Condition | None = None, limit: int | None = None, asof: int | None = None, + columns: Sequence[str] | None = None, ) -> Iterator[pa.RecordBatch]: """Yield prepared Arrow batches from this resolved table in key order. @@ -678,6 +679,9 @@ def scan_batches( (``SpiralDBConnector.scan_batches``). limit: Read at most this many matching rows. asof: Read this version. + columns: The columns to read; ``None`` reads every column. Each batch + holds them in the snapshot's order. The columns of ``where`` are + scanned too, and removed after any comparison made here (ITL-1776). Raises: ValueError: If ``where`` holds anything else, or a range of a column whose @@ -686,6 +690,13 @@ def scan_batches( connector = self._connector table = self._at(asof) reading = self._reading(table) + wanted: list[str] | None = None + scanned: list[str] | None = None + if columns is not None: + needed = set(columns) | {t.path.column for t in _scan_terms(where)} + wanted = [n for n in reading.found.names if n in set(columns)] + scanned = [n for n in reading.found.names if n in needed] + reading = reading.projected(scanned) predicate = None # Every equality compared here, in the order given: two of one column both hold. local: list[tuple[str, object]] = [] @@ -708,6 +719,7 @@ def scan_batches( predicate = equals if predicate is None else sp.and_(predicate, equals) with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle reader = table.scan( + scanned, filter=predicate, # The limit counts rows that match every condition. limit=None if local else limit, @@ -726,6 +738,8 @@ def scan_batches( if local and left is not None: batch = batch.slice(0, left) left -= batch.num_rows + if wanted is not None and wanted != scanned: + batch = batch.select(wanted) if batch.num_rows or not local: yield batch finally: @@ -807,6 +821,28 @@ def __init__( # The batch schema last found to have the snapshot's columns. self._accepted = found + def projected(self, names: Sequence[str]) -> _Reading: + """Return this reading restricted to the columns ``names`` (ITL-1776). + + The schemas keep the snapshot's column order and metadata; the non-null + checks keep only the paths under a kept column. + """ + duplicate = copy(self) + kept = set(names) + duplicate.found = pa.schema( + [f for f in self.found if f.name in kept], + metadata=cast("dict[bytes | str, bytes | str] | None", self.found.metadata), + ) + duplicate.schema = pa.schema( + [f for f in self.schema if f.name in kept], + metadata=cast( + "dict[bytes | str, bytes | str] | None", self.schema.metadata + ), + ) + duplicate._paths = frozenset(p for p in self._paths if p[0] in kept) + duplicate._accepted = duplicate.found + return duplicate + def prepare(self, batch: pa.RecordBatch) -> pa.RecordBatch: """Return a scanned batch under ``schema``, its non-null columns checked. diff --git a/src/orcapod/protocols/core_protocols/sources.py b/src/orcapod/protocols/core_protocols/sources.py index dd01741a9..d99a566c4 100644 --- a/src/orcapod/protocols/core_protocols/sources.py +++ b/src/orcapod/protocols/core_protocols/sources.py @@ -1,9 +1,10 @@ from __future__ import annotations +from collections.abc import Collection from typing import TYPE_CHECKING, Any, Protocol, TypeVar, runtime_checkable from orcapod.protocols.core_protocols.streams import StreamProtocol -from orcapod.types import Condition, Cursor +from orcapod.types import ColumnConfig, Condition, Cursor T = TypeVar("T") @@ -47,6 +48,21 @@ def row_limit(self) -> int | None: """The most rows the source reads, or ``None`` for no limit.""" ... + def projected_table( + self, + data_columns: Collection[str], + *, + columns: ColumnConfig | dict[str, Any] | None = None, + ) -> pa.Table | None: + """The source's table read with only the columns ``data_columns`` needs. + + ``as_table(columns=columns)`` without the data columns (other than tags) + not in ``data_columns`` and their source-info columns, or ``None`` when the + source is read whole. An execution detail asked by a column selection on + the source (ITL-1776): it changes no identity, schema or record id. + """ + ... + def to_config( self, db_registry: DatabaseRegistryProtocol | None = None ) -> dict[str, Any]: diff --git a/tests/test_databases/test_spiraldb_projection.py b/tests/test_databases/test_spiraldb_projection.py new file mode 100644 index 000000000..a883c523a --- /dev/null +++ b/tests/test_databases/test_spiraldb_projection.py @@ -0,0 +1,347 @@ +"""A column selection directly on a SpiralDB source scans only the columns it keeps +(ITL-1776), and gives exactly the rows, types and hashes of the whole read followed by +the same selection. + +The projection is an execution detail: every test compares the projected result with +the whole read (``projected_table`` disabled), on the table and on the identity. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +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.sources import SpiralDBTableSource +from orcapod.types import ColumnConfig, Condition +from tests.test_databases import fake_spiral_sdk as fake + +_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 = ["unit", "t", "x", "y", "blob"] + + +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, + ) + + +def _clear_logs() -> None: + fake.scan_log.clear() + fake.count_log.clear() + + +def _row_scans() -> list[list[str]]: + """The columns each row scan requested (``None``, every column, spelled out). + + The fake logs a scan of some columns as a count; a count reads one key column, + and every projected read here reads at least three. + """ + 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 scans + + +def _counts() -> list[list[str]]: + """The columns each count requested.""" + return [ + list(r.columns) for r in fake.count_log if r.columns and len(r.columns) == 1 + ] + + +def _assert_same_table(got: pa.Table, expected: pa.Table) -> None: + assert got.schema.equals(expected.schema, check_metadata=True) + assert got.equals(expected) + + +# (id, source arguments, selection, the columns every row scan must request) +SHAPES: list[tuple[str, dict[str, Any], Callable[[Any], Any], list[str]]] = [ + ( + "select_data_two", + {}, + lambda s: s.select_data_columns(["y", "x"]), + ["t", "unit", "x", "y"], + ), + ( + "select_data_two_reordered", + {}, + lambda s: s.select_data_columns(["x", "y"]), + ["t", "unit", "x", "y"], + ), + ("select_data_one", {}, lambda s: s.select_data_columns("x"), ["t", "unit", "x"]), + ( + "drop_data", + {}, + lambda s: s.drop_data_columns(["blob", "y"]), + ["t", "unit", "x"], + ), + ( + "select_columns_drops_a_tag", + {}, + lambda s: s.select_columns(["t", "x", "y"]), + ["t", "unit", "x", "y"], + ), + ( + "drop_columns_tag_and_data", + {}, + lambda s: s.drop_columns("unit", "blob"), + ["t", "unit", "x", "y"], + ), + ( + "data_tags", + {"tag_only_columns": ["unit"]}, + lambda s: s.select_data_columns(["x"]), + ["t", "unit", "x"], + ), + ( + "data_tag_selected_away", + {"tag_only_columns": False}, + lambda s: s.select_data_columns(["unit", "x"]), + ["t", "unit", "x"], + ), + ( + "where_and_limit", + {"where": Condition.of(unit="u1"), "limit": 2}, + lambda s: s.select_data_columns(["x"]), + ["t", "unit", "x"], + ), + ( + "where_on_an_unselected_column", + {"where": Condition.of(y=2)}, + lambda s: s.select_data_columns(["x"]), + ["t", "unit", "x", "y"], + ), + ( + "where_matching_no_row", + {"where": Condition.of(y=99)}, + lambda s: s.select_data_columns(["x"]), + ["t", "unit", "x", "y"], + ), + ( + "key_column_is_data", + {"tag_columns": ["unit"]}, + lambda s: s.select_data_columns(["x"]), + ["t", "unit", "x"], + ), + ( + "tags_as_data_kept", + {"tags_as_data": {"t": "t_copy"}}, + lambda s: s.select_data_columns(["t_copy", "x"]), + ["t", "unit", "x"], + ), + ( + "tags_as_data_dropped", + {"tags_as_data": {"t": "t_copy"}}, + lambda s: s.select_data_columns(["y"]), + ["t", "unit", "y"], + ), +] + + +@pytest.mark.parametrize("shape", SHAPES, ids=[s[0] for s in SHAPES]) +def test_a_selection_on_the_source_scans_only_what_it_keeps( + project: Any, monkeypatch: pytest.MonkeyPatch, shape: Any +) -> None: + _, given, apply, scanned = shape + kwargs: dict[str, Any] = {"tag_only_columns": True, **given} + _clear_logs() + projected = apply(SpiralDBTableSource("p", "wide", **kwargs)) + got = projected.as_table(all_info=True) + got_sorted = projected.as_table(columns={"sort_by_tags": True, "source": True}) + assert _row_scans() == [scanned] + # The cap check counts the rows by one key column, as before. + counted = _counts() + with monkeypatch.context() as m: + _read_whole(m) + _clear_logs() + whole = apply(SpiralDBTableSource("p", "wide", **kwargs)) + expected = whole.as_table(all_info=True) + assert _row_scans() == [_ALL] + assert _counts() == counted + _assert_same_table(got, expected) + _assert_same_table( + got_sorted, whole.as_table(columns={"sort_by_tags": True, "source": True}) + ) + assert projected.content_hash() == whole.content_hash() + assert projected.pipeline_hash() == whole.pipeline_hash() + assert projected.keys() == whole.keys() + assert projected.output_schema() == whole.output_schema() + expected_rows = [(t.as_dict(), d.as_dict()) for t, d in whole.iter_data()] + assert [ + (t.as_dict(), d.as_dict()) for t, d in projected.iter_data() + ] == expected_rows + + async def collect() -> list[Any]: + stream = apply(SpiralDBTableSource("p", "wide", **kwargs)) + return [(t.as_dict(), d.as_dict()) async for t, d in stream.async_iter_data()] + + _clear_logs() + assert asyncio.run(collect()) == expected_rows + assert _row_scans() == [scanned] + + +def test_a_selection_of_every_data_column_reads_the_whole_table(project: Any) -> None: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + assert source.projected_table(["x", "y", "blob"]) is None + _clear_logs() + source.select_data_columns(["blob", "x", "y"]).as_table() + assert _row_scans() + assert all(scan == _ALL for scan in _row_scans()) + + +def test_the_projected_table_leaves_out_only_unread_data_columns( + project: Any, +) -> None: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + config = {"source": True, "system_tags": True, "meta": True, "context": True} + projected = source.projected_table(["x"], columns=config) + assert projected is not None + whole = source.as_table(columns=config) + _assert_same_table( + projected, whole.drop_columns(["y", "blob", "_source_y", "_source_blob"]) + ) + + +@pytest.mark.parametrize( + ("columns", "hash_name"), + [ + ({"content_hash": True}, "_content_hash"), + (ColumnConfig(content_hash="row_hash"), "row_hash"), + ({"all_info": True}, "_content_hash"), + (ColumnConfig(all_info=True), "_content_hash"), + ], + ids=["default_name", "custom_name", "all_info_dict", "all_info_config"], +) +def test_projected_read_preserves_whole_row_content_hashes( + project: Any, columns: ColumnConfig | dict[str, Any], hash_name: str +) -> None: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + whole = source.as_table(columns=columns) + _clear_logs() + + projected = source.projected_table(["x"], columns=columns) + result = source.as_table(columns=columns) if projected is None else projected + + assert whole.num_rows == 6 + assert result[hash_name].equals(whole[hash_name]) + assert projected is None + assert _row_scans() == [_ALL] + + +def test_a_function_pod_reads_only_its_parameters( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + @function_pod(output_keys="z") + def double(x: float) -> float: + return 2 * x + + def without_result_ids(table: pa.Table) -> pa.Table: + # Meta columns and the output's token hold a random result id or a time. + return table.drop_columns( + [c for c in table.column_names if c.startswith("__") or c == "_source_z"] + ) + + _clear_logs() + got = double.pod(SpiralDBTableSource("p", "wide", tag_only_columns=True)) + table = without_result_ids(got.as_table(all_info=True)) + assert _row_scans() == [["t", "unit", "x"]] + with monkeypatch.context() as m: + _read_whole(m) + whole = double.pod(SpiralDBTableSource("p", "wide", tag_only_columns=True)) + _assert_same_table(without_result_ids(whole.as_table(all_info=True)), table) + assert whole.content_hash() == got.content_hash() + assert whole.pipeline_hash() == got.pipeline_hash() + + +def test_head_reads_what_it_read_before( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + def heads() -> tuple[str, str, list[Any], list[Any]]: + _clear_logs() + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + selected = source.select_data_columns(["x"]) + shown = (repr(source.head()), repr(selected.head())) + return (*shown, list(fake.scan_log), list(fake.count_log)) + + got = heads() + with monkeypatch.context() as m: + _read_whole(m) + expected = heads() + assert got[:2] == expected[:2] + assert [r.columns for r in got[2]] == [r.columns for r in expected[2]] + assert [r.columns for r in got[3]] == [r.columns for r in expected[3]] + + +@pytest.mark.parametrize("route", ["sync", "async"]) +def test_a_job_reads_the_whole_table_and_gives_the_same_rows( + project: Any, route: str +) -> None: + # The job route is unchanged by ITL-1776: the source node reads every column. + def config() -> dict[str, bool]: + return {"source": True, "system_tags": True, "sort_by_tags": True} + + standalone = ( + SpiralDBTableSource("p", "wide", tag_only_columns=True) + .select_data_columns(["x"]) + .as_table(columns=config()) + ) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + SpiralDBTableSource("p", "wide", tag_only_columns=True).select_data_columns( + ["x"], label="selected" + ) + _clear_logs() + if route == "sync": + job.run() + else: + asyncio.run(job.run_async()) + assert _row_scans() == [_ALL] + # 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 f44ef4c9b..ac7ede727 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -5,10 +5,11 @@ import asyncio import json import re -from collections.abc import Iterable +from collections.abc import Collection, Iterable from pathlib import Path from typing import Any, cast +import pyarrow as pa import pytest from orcapod import Pipeline, PipelineJob, function_pod, side_effect_pod @@ -18,6 +19,7 @@ from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.side_effects import SideEffectPod from orcapod.sources import CSVSource, DictSource +from orcapod.types import ColumnConfig Orchestrator = type[AsyncPipelineOrchestrator] | type[SyncPipelineOrchestrator] ORCHESTRATORS = [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] @@ -1571,6 +1573,14 @@ def condition(self) -> Condition: def row_limit(self) -> int | None: return None + def projected_table( + self, + data_columns: Collection[str], + *, + columns: ColumnConfig | dict[str, Any] | None = None, + ) -> pa.Table | None: + return None + def to_config( self, db_registry: DatabaseRegistryProtocol | None = None ) -> dict[str, Any]: