From a635799ef38d72a37c3f3676f3438fc7b18cf620 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 21:33:11 -0800 Subject: [PATCH 1/4] prototype(spiraldb): column projection for a select on the source (ITL-1776, local only) Co-Authored-By: Claude Opus 5.5 --- .../core/operators/column_selection.py | 39 ++++- .../core/sources/spiraldb_table_source.py | 54 ++++++- src/orcapod/databases/spiraldb_connector.py | 31 +++- .../test_spiraldb_projection_prototype.py | 139 ++++++++++++++++++ 4 files changed, 253 insertions(+), 10 deletions(-) create mode 100644 tests/test_databases/test_spiraldb_projection_prototype.py diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 8a3b5434c..dc34cf434 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -3,6 +3,8 @@ 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 @@ -30,6 +32,21 @@ 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": + """PROTOTYPE (ITL-1776): the input's table, read with only ``kept_data`` among its + data columns when the input can read narrower (a SpiralDB source), else whole. + + The rows of the kept columns are those of the whole read: the caller drops only + the columns present. + """ + narrower = getattr(stream, "read_data_columns", None) + reader = narrower(frozenset(kept_data)) if callable(narrower) else None + return (stream if reader is None else reader).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 +246,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, @@ -245,8 +264,12 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # tag with the same values (specification section 7.2). data_tags = stream_data_tags(stream) 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 [c for c in data_columns_to_drop if c not in data_tags] + + associated_source_fields + if c in table.column_names + ] ) return ArrowTableStream._from_derived_table( @@ -774,13 +797,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/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index ca1f243e2..16b1bb1f8 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -374,6 +374,8 @@ def __init__( self._pid = os.getpid() self._closed = False self._condition = Condition() + # PROTOTYPE (ITL-1776): the table columns a projected reader scans. + self._read_columns: frozenset[str] | None = None self._limit = limit self._max_rows = max_rows self._batch_rows = batch_rows @@ -666,6 +668,37 @@ def _copy(self) -> "SpiralDBTableSource": duplicate._pipeline_hash_cache = {} return duplicate + def read_data_columns(self, columns: Collection[str]) -> "SpiralDBTableSource | None": + """PROTOTYPE (ITL-1776): a reader of this source's rows with only ``columns`` + among the data columns, or ``None`` when that is every data column. + + Every tag column and every key column is read (record ids, system tags and + source-info tokens are those of the whole read); the system-tag column names + keep the whole source's schema hash. The returned object is a reader only: + its keys and zero-row table are the narrowed ones, its identity the source's. + """ + tag_columns, data_columns = self._stream.keys() + kept = [c for c in data_columns if c in columns or c in tag_columns] + if len(kept) == len(data_columns): + return None + reader = self._copy() + copies = set(self._tags_as_data.values()) + reader._read_columns = frozenset( + {*tag_columns, *self._key_columns, *(c for c in kept)} + | {k for k, v in self._tags_as_data.items() if v in kept} + ) - (copies - set(kept)) + # The narrowed zero-row template: the user columns the reader returns. + reader._stream = self._builder.build( + self._stream.as_table().select( + [*tag_columns, *(c for c in kept if c not in tag_columns)] + ), + tag_columns=self._tag_columns, + source_name=self._source_name, + kind_part=self.kind_part(), + data_tags=self._data_tags, + ).stream + return reader + def _apply_restriction(self, condition: Condition) -> None: """Add ``condition`` to the condition this source reads under, in place. @@ -1050,10 +1083,18 @@ def _read_batches( seen = 0 # Keys must be unique across the whole read, not only within a slice. identifiers: set[str] = set() + read_columns = self._read_columns + expected_schema = self._table_schema + if read_columns is not None: + expected_schema = pa.schema( + [f for f in self._table_schema if f.name in read_columns], + metadata=self._table_schema.metadata, + ) for batch in table.scan_batches( where=None if self._condition.is_empty else self._condition, limit=limit, asof=asof, + columns=None if read_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)]) @@ -1063,10 +1104,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." ) @@ -1084,6 +1125,15 @@ def _read_batches( "must be unique, so each row has its own identifier" ) rows = self._with_tag_copies(rows) + if read_columns is not None: + # Copies a projected read does not return. + rows = rows.select( + [ + c + for c in rows.column_names + if c in read_columns or c not in self._tags_as_data.values() + ] + ) if not rows.num_rows: continue identifiers.update(tokens) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index db3a0b45c..3a9e46b93 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -24,7 +24,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 local @@ -554,9 +554,14 @@ 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. + PROTOTYPE (ITL-1776): ``columns`` names the columns to read (in the + snapshot's order); ``None`` reads every column. A condition's columns are read + too and removed after any local filter. + Args: where: Equalities and ranges of columns, all of which must hold (``SpiralDBConnector.scan_batches``). @@ -570,6 +575,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]] = [] @@ -592,6 +604,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, @@ -610,6 +623,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: @@ -691,6 +706,20 @@ def __init__( # The batch schema last found to have the snapshot's columns. self._accepted = found + def projected(self, names: Sequence[str]) -> _Reading: + """PROTOTYPE (ITL-1776): this reading restricted to ``names``.""" + duplicate = copy(self) + kept = set(names) + duplicate.found = pa.schema( + [f for f in self.found if f.name in kept], metadata=self.found.metadata + ) + duplicate.schema = pa.schema( + [f for f in self.schema if f.name in kept], metadata=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/tests/test_databases/test_spiraldb_projection_prototype.py b/tests/test_databases/test_spiraldb_projection_prototype.py new file mode 100644 index 000000000..917f0eecf --- /dev/null +++ b/tests/test_databases/test_spiraldb_projection_prototype.py @@ -0,0 +1,139 @@ +"""PROTOTYPE (ITL-1776, local only): a select directly on a SpiralDB source reads only +the columns it keeps, and gives the rows and hashes of the whole read plus the select.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import function_pod +from orcapod.core.sources import spiraldb_table_source as source_module +from orcapod.databases import spiraldb_connector as connector_module +from orcapod.sources import SpiralDBTableSource +from orcapod.types import 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()), + ] +) + + +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 _whole(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + source_module.SpiralDBTableSource, "read_data_columns", lambda self, c: None + ) + + +def _without_meta(table: pa.Table) -> pa.Table: + # Meta columns and a function 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"] + ) + + +def _scanned() -> list[list[str] | None]: + return [r.columns for r in fake.scan_log + fake.count_log] + + +SHAPES: list[tuple[str, dict[str, Any], Any]] = [ + ("select_data", {}, lambda s: s.select_data_columns(["y", "x"])), + ("select_data_one", {}, lambda s: s.select_data_columns("x")), + ("select_columns", {}, lambda s: s.select_columns(["t", "x", "y"])), + ( + "data_tags", + {"tag_only_columns": ["unit"]}, + lambda s: s.select_data_columns(["x"]), + ), + ( + "where_limit", + {"where": Condition.of(unit="u1"), "limit": 2}, + lambda s: s.select_data_columns(["x"]), + ), + ( + "where_unselected", + {"where": Condition.of(y=2)}, + lambda s: s.select_data_columns(["x"]), + ), + ( + "tags_as_data", + {"tag_only_columns": True, "tags_as_data": {"t": "t_copy"}}, + lambda s: s.select_data_columns(["t_copy", "x"]), + ), +] + + +@pytest.mark.parametrize("shape", SHAPES, ids=[s[0] for s in SHAPES]) +def test_projected_select_equals_whole_read_then_select( + project: Any, monkeypatch: pytest.MonkeyPatch, shape: Any +) -> None: + _, kwargs, apply = shape + kwargs = {"tag_only_columns": True, **kwargs} + fake.scan_log.clear() + fake.count_log.clear() + projected = apply(SpiralDBTableSource("p", "wide", **kwargs)) + got = projected.as_table(all_info=True) + got_hashes = (projected.content_hash(), projected.pipeline_hash()) + got_keys = projected.keys() + assert all(c is None or "blob" not in c for c in _scanned()) + assert any(c is not None and len(c) < 5 for c in _scanned()) + with monkeypatch.context() as m: + _whole(m) + fake.scan_log.clear() + whole = apply(SpiralDBTableSource("p", "wide", **kwargs)) + expected = whole.as_table(all_info=True) + assert any(c is None for c in _scanned()) + assert (whole.content_hash(), whole.pipeline_hash()) == got_hashes + assert whole.keys() == got_keys + assert got.schema.equals(expected.schema, check_metadata=True) + assert got.equals(expected) + + +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 + + fake.scan_log.clear() + fake.count_log.clear() + got = double.pod(SpiralDBTableSource("p", "wide", tag_only_columns=True)) + table = _without_meta(got.as_table(all_info=True)) + assert [sorted(c) for c in _scanned() if c and len(c) > 1] == [["t", "unit", "x"]] + with monkeypatch.context() as m: + _whole(m) + whole = double.pod(SpiralDBTableSource("p", "wide", tag_only_columns=True)) + assert _without_meta(whole.as_table(all_info=True)).equals(table) + assert whole.content_hash() == got.content_hash() From fbcc065f9d7cc0f2fc5a434ca0f3d04a03c0c8b8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 21:59:50 -0800 Subject: [PATCH 2/4] feat(spiraldb): scan only the columns a selection on the source keeps (ITL-1776) A column selection placed directly on a SpiralDBTableSource and read outside a job asks the source for the columns it keeps (SourceProtocol.projected_table; RootSource reads whole). Tags, key columns and where-condition columns are always read; the result, hashes, schema, record ids and stored paths are those of the whole read followed by the selection. The job route is unchanged. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1776.md | 10 + docs/concepts/sources.md | 9 + .../core/operators/column_selection.py | 59 ++-- src/orcapod/core/sources/base.py | 25 +- .../core/sources/spiraldb_table_source.py | 122 ++++--- src/orcapod/databases/spiraldb_connector.py | 21 +- .../protocols/core_protocols/sources.py | 18 +- .../test_spiraldb_projection.py | 321 ++++++++++++++++++ .../test_spiraldb_projection_prototype.py | 139 -------- 9 files changed, 504 insertions(+), 220 deletions(-) create mode 100644 changelog.d/ITL-1776.md create mode 100644 tests/test_databases/test_spiraldb_projection.py delete mode 100644 tests/test_databases/test_spiraldb_projection_prototype.py 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 64012062f..b4c2ce355 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -640,6 +640,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 dc34cf434..266bd4551 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -11,7 +11,12 @@ 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 @@ -32,19 +37,23 @@ 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": - """PROTOTYPE (ITL-1776): the input's table, read with only ``kept_data`` among its - data columns when the input can read narrower (a SpiralDB source), else whole. - - The rows of the kept columns are those of the whole read: the caller drops only - the columns present. +) -> 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). """ - narrower = getattr(stream, "read_data_columns", None) - reader = narrower(frozenset(kept_data)) if callable(narrower) else None - return (stream if reader is None else reader).as_table(columns=columns) + 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: @@ -263,13 +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 [c for c in data_columns_to_drop if c not in data_tags] - + associated_source_fields - if c in table.column_names - ] + [c for c in table.column_names if c in dropped] ) return ArrowTableStream._from_derived_table( @@ -557,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( 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 16b1bb1f8..fc4d7bbb5 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -47,11 +47,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 @@ -82,6 +89,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 @@ -374,8 +382,6 @@ def __init__( self._pid = os.getpid() self._closed = False self._condition = Condition() - # PROTOTYPE (ITL-1776): the table columns a projected reader scans. - self._read_columns: frozenset[str] | None = None self._limit = limit self._max_rows = max_rows self._batch_rows = batch_rows @@ -668,37 +674,6 @@ def _copy(self) -> "SpiralDBTableSource": duplicate._pipeline_hash_cache = {} return duplicate - def read_data_columns(self, columns: Collection[str]) -> "SpiralDBTableSource | None": - """PROTOTYPE (ITL-1776): a reader of this source's rows with only ``columns`` - among the data columns, or ``None`` when that is every data column. - - Every tag column and every key column is read (record ids, system tags and - source-info tokens are those of the whole read); the system-tag column names - keep the whole source's schema hash. The returned object is a reader only: - its keys and zero-row table are the narrowed ones, its identity the source's. - """ - tag_columns, data_columns = self._stream.keys() - kept = [c for c in data_columns if c in columns or c in tag_columns] - if len(kept) == len(data_columns): - return None - reader = self._copy() - copies = set(self._tags_as_data.values()) - reader._read_columns = frozenset( - {*tag_columns, *self._key_columns, *(c for c in kept)} - | {k for k, v in self._tags_as_data.items() if v in kept} - ) - (copies - set(kept)) - # The narrowed zero-row template: the user columns the reader returns. - reader._stream = self._builder.build( - self._stream.as_table().select( - [*tag_columns, *(c for c in kept if c not in tag_columns)] - ), - tag_columns=self._tag_columns, - source_name=self._source_name, - kind_part=self.kind_part(), - data_tags=self._data_tags, - ).stream - return reader - def _apply_restriction(self, condition: Condition) -> None: """Add ``condition`` to the condition this source reads under, in place. @@ -1013,7 +988,10 @@ def _key_tokens(self, table: "pa.Table") -> list[str]: ) from exc def _batch_streams( - self, *, with_source_info: bool = True + self, + *, + with_source_info: bool = True, + table_columns: Sequence[str] | None = None, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once and yield its rows as streams of at most ``batch_rows`` rows. @@ -1021,6 +999,7 @@ def _batch_streams( Args: with_source_info: As for ``_read_batches``. + table_columns: As for ``_read_batches``. Raises: SourceTooLargeError: If the read would return, or returns, more than @@ -1036,6 +1015,7 @@ def _batch_streams( limit=self._limit, max_rows=self._max_rows, with_source_info=with_source_info, + table_columns=table_columns, ) def _read_batches( @@ -1046,6 +1026,7 @@ def _read_batches( limit: int | None, max_rows: int | None, with_source_info: bool = True, + table_columns: Sequence[str] | None = None, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``. @@ -1059,6 +1040,9 @@ 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). Raises: SourceTooLargeError: If the read would return, or returns, more than @@ -1083,18 +1067,21 @@ def _read_batches( seen = 0 # Keys must be unique across the whole read, not only within a slice. identifiers: set[str] = set() - read_columns = self._read_columns expected_schema = self._table_schema - if read_columns is not None: + 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 read_columns], - metadata=self._table_schema.metadata, + [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=limit, asof=asof, - columns=None if read_columns is None else expected_schema.names, + 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)]) @@ -1125,15 +1112,6 @@ def _read_batches( "must be unique, so each row has its own identifier" ) rows = self._with_tag_copies(rows) - if read_columns is not None: - # Copies a projected read does not return. - rows = rows.select( - [ - c - for c in rows.column_names - if c in read_columns or c not in self._tags_as_data.values() - ] - ) if not rows.num_rows: continue identifiers.update(tokens) @@ -1188,6 +1166,50 @@ 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 ``data_columns`` names every data column + that is not a tag (nothing would be left unread). + """ + 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 + ] + config = ColumnConfig.handle_config(columns) + table = self._whole_table( + self._batch_streams( + with_source_info=_reads_source_info(config), + table_columns=table_columns, + ), + 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 3a9e46b93..c659df3a8 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -558,15 +558,14 @@ def scan_batches( ) -> Iterator[pa.RecordBatch]: """Yield prepared Arrow batches from this resolved table in key order. - PROTOTYPE (ITL-1776): ``columns`` names the columns to read (in the - snapshot's order); ``None`` reads every column. A condition's columns are read - too and removed after any local filter. - Args: where: Equalities and ranges of columns, all of which must hold (``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 @@ -707,14 +706,22 @@ def __init__( self._accepted = found def projected(self, names: Sequence[str]) -> _Reading: - """PROTOTYPE (ITL-1776): this reading restricted to ``names``.""" + """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=self.found.metadata + [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=self.schema.metadata + [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 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..bc8309cd9 --- /dev/null +++ b/tests/test_databases/test_spiraldb_projection.py @@ -0,0 +1,321 @@ +"""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 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} + 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"]) + ) + + +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_databases/test_spiraldb_projection_prototype.py b/tests/test_databases/test_spiraldb_projection_prototype.py deleted file mode 100644 index 917f0eecf..000000000 --- a/tests/test_databases/test_spiraldb_projection_prototype.py +++ /dev/null @@ -1,139 +0,0 @@ -"""PROTOTYPE (ITL-1776, local only): a select directly on a SpiralDB source reads only -the columns it keeps, and gives the rows and hashes of the whole read plus the select.""" - -from __future__ import annotations - -from pathlib import Path -from typing import Any - -import pyarrow as pa -import pytest - -from orcapod import function_pod -from orcapod.core.sources import spiraldb_table_source as source_module -from orcapod.databases import spiraldb_connector as connector_module -from orcapod.sources import SpiralDBTableSource -from orcapod.types import 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()), - ] -) - - -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 _whole(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr( - source_module.SpiralDBTableSource, "read_data_columns", lambda self, c: None - ) - - -def _without_meta(table: pa.Table) -> pa.Table: - # Meta columns and a function 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"] - ) - - -def _scanned() -> list[list[str] | None]: - return [r.columns for r in fake.scan_log + fake.count_log] - - -SHAPES: list[tuple[str, dict[str, Any], Any]] = [ - ("select_data", {}, lambda s: s.select_data_columns(["y", "x"])), - ("select_data_one", {}, lambda s: s.select_data_columns("x")), - ("select_columns", {}, lambda s: s.select_columns(["t", "x", "y"])), - ( - "data_tags", - {"tag_only_columns": ["unit"]}, - lambda s: s.select_data_columns(["x"]), - ), - ( - "where_limit", - {"where": Condition.of(unit="u1"), "limit": 2}, - lambda s: s.select_data_columns(["x"]), - ), - ( - "where_unselected", - {"where": Condition.of(y=2)}, - lambda s: s.select_data_columns(["x"]), - ), - ( - "tags_as_data", - {"tag_only_columns": True, "tags_as_data": {"t": "t_copy"}}, - lambda s: s.select_data_columns(["t_copy", "x"]), - ), -] - - -@pytest.mark.parametrize("shape", SHAPES, ids=[s[0] for s in SHAPES]) -def test_projected_select_equals_whole_read_then_select( - project: Any, monkeypatch: pytest.MonkeyPatch, shape: Any -) -> None: - _, kwargs, apply = shape - kwargs = {"tag_only_columns": True, **kwargs} - fake.scan_log.clear() - fake.count_log.clear() - projected = apply(SpiralDBTableSource("p", "wide", **kwargs)) - got = projected.as_table(all_info=True) - got_hashes = (projected.content_hash(), projected.pipeline_hash()) - got_keys = projected.keys() - assert all(c is None or "blob" not in c for c in _scanned()) - assert any(c is not None and len(c) < 5 for c in _scanned()) - with monkeypatch.context() as m: - _whole(m) - fake.scan_log.clear() - whole = apply(SpiralDBTableSource("p", "wide", **kwargs)) - expected = whole.as_table(all_info=True) - assert any(c is None for c in _scanned()) - assert (whole.content_hash(), whole.pipeline_hash()) == got_hashes - assert whole.keys() == got_keys - assert got.schema.equals(expected.schema, check_metadata=True) - assert got.equals(expected) - - -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 - - fake.scan_log.clear() - fake.count_log.clear() - got = double.pod(SpiralDBTableSource("p", "wide", tag_only_columns=True)) - table = _without_meta(got.as_table(all_info=True)) - assert [sorted(c) for c in _scanned() if c and len(c) > 1] == [["t", "unit", "x"]] - with monkeypatch.context() as m: - _whole(m) - whole = double.pod(SpiralDBTableSource("p", "wide", tag_only_columns=True)) - assert _without_meta(whole.as_table(all_info=True)).equals(table) - assert whole.content_hash() == got.content_hash() From 1e3e050caa47b7a4e0d3c536c24bb7a40a687c3a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 22:39:58 -0800 Subject: [PATCH 3/4] test(pipeline): give the hand-written source slot the projected_table member (ITL-1776) Co-Authored-By: Claude Opus 5.5 --- .../test_pipeline/test_source_object_registration.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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]: From e116997cde3c81bd724731c64a88c30e38a3a5b4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 01:16:15 -0800 Subject: [PATCH 4/4] fix(projection): preserve whole-row content hashes --- .../core/sources/spiraldb_table_source.py | 8 +++-- .../test_spiraldb_projection.py | 30 +++++++++++++++++-- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 714343c91..09742bbee 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1207,9 +1207,12 @@ def projected_table( zero-row table without the same columns: never computed from a read. Returns: - The table, or ``None`` when ``data_columns`` names every data column - that is not a tag (nothing would be left unread). + 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} @@ -1219,7 +1222,6 @@ def projected_table( table_columns = [ c for c in self._table_schema.names if c not in unread or c in keys ] - config = ColumnConfig.handle_config(columns) table = self._whole_table( self._batch_streams( with_source_info=_reads_source_info(config), diff --git a/tests/test_databases/test_spiraldb_projection.py b/tests/test_databases/test_spiraldb_projection.py index bc8309cd9..a883c523a 100644 --- a/tests/test_databases/test_spiraldb_projection.py +++ b/tests/test_databases/test_spiraldb_projection.py @@ -21,7 +21,7 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.databases import spiraldb_connector as connector_module from orcapod.sources import SpiralDBTableSource -from orcapod.types import Condition +from orcapod.types import ColumnConfig, Condition from tests.test_databases import fake_spiral_sdk as fake _WRITTEN = pa.schema( @@ -239,7 +239,7 @@ 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} + 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) @@ -248,6 +248,32 @@ def test_the_projected_table_leaves_out_only_unread_data_columns( ) +@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: