From a635799ef38d72a37c3f3676f3438fc7b18cf620 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 21:33:11 -0800 Subject: [PATCH 01/12] 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 02/12] 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 03/12] 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 526b7717a86237ae0dc911df0516419fa9f13d06 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 01:22:23 -0800 Subject: [PATCH 04/12] perf(spiraldb): a job reads only the columns its selections keep (ITL-1798) The sync and async orchestrators compute each SpiralDB source node's column demand from the run's graph (pipeline/column_demand.py): when every successor is a SelectDataColumns or SelectColumns operator node directly on the source, the node reads the union of the data columns they keep, plus every tag, key and condition column. Any other successor means a whole read, as before. The node hands on a ProjectedOutput: it describes the whole node (the whole read's keys, the node's identity) and offers only the narrowed table to a column selection; any other read is answered from a whole read. Nothing in any hash, schema, record id, stored path or stored row changes. A source declares that it can read fewer columns with PROJECTS_COLUMNS (SpiralDB only), so every other source runs exactly as before. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1776.md | 3 +- changelog.d/ITL-1798.md | 12 + docs/concepts/sources.md | 7 +- src/orcapod/core/nodes/source_node.py | 168 ++++++- .../core/operators/column_selection.py | 7 +- .../core/operators/static_output_pod.py | 210 +++++++++ src/orcapod/core/sources/base.py | 5 + .../core/sources/spiraldb_table_source.py | 2 + src/orcapod/pipeline/async_orchestrator.py | 20 +- src/orcapod/pipeline/column_demand.py | 83 ++++ src/orcapod/pipeline/sync_orchestrator.py | 10 +- src/orcapod/protocols/node_protocols.py | 4 +- .../sources/test_spiraldb_lookups.py | 11 +- .../test_spiraldb_job_projection.py | 430 ++++++++++++++++++ .../test_spiraldb_projection.py | 7 +- 15 files changed, 943 insertions(+), 36 deletions(-) create mode 100644 changelog.d/ITL-1798.md create mode 100644 src/orcapod/pipeline/column_demand.py create mode 100644 tests/test_databases/test_spiraldb_job_projection.py 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..ff7ffe144 --- /dev/null +++ b/changelog.d/ITL-1798.md @@ -0,0 +1,12 @@ +### 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()`. 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. 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..c8ecfd0be 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -653,8 +653,11 @@ 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. The job's rows, stored rows, hashes and stored paths are the same either way. **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..213913d4a 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 @@ -76,6 +77,7 @@ if TYPE_CHECKING: from orcapod.channels import WritableChannel + from orcapod.core.output_bindings import OutputBindings from orcapod.pipeline.job import PipelineJob from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols.streams import ( @@ -1407,6 +1409,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 +1420,12 @@ 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 still describes + the whole node (``ProjectedOutput``). An execution detail: no hash, + schema, record id or stored row depends on it. Returns: The node's output stream. @@ -1424,11 +1433,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,30 +1440,61 @@ 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``. + + ``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 async def async_execute( self, output: "WritableChannel[tuple[TagProtocol, DataProtocol]]", *, observer: ExecutionObserverProtocol | None = None, + read_columns: Collection[str] | None = None, ) -> None: """Push all (tag, data) pairs to the output channel. @@ -1470,17 +1505,40 @@ 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 (off the event loop) and sends the rows of + that read, each without the unread data columns, which every + successor drops. Raises: UnboundSourceError: When no concrete data is available. """ + from orcapod.core.operators.static_output_pod import ProjectedOutput + 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 + if read_columns is not None: + bindings = capture_output_bindings(self) + projected = await asyncio.to_thread( + self._projected_output, read_columns, bindings + ) + if projected is not None: + # The narrowed read's rows (a projected output's, or no row at all). + rows = ( + projected.narrow + if isinstance(projected, ProjectedOutput) + else projected + ) + for tag, data in rows.iter_data(): + await output.send((tag, data)) + else: + 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) finally: @@ -2093,6 +2151,74 @@ def _rows_table( return None return table, keys_of_rows(table, source.keys()) + def _projected_output( + self, read_columns: Collection[str], bindings: OutputBindings + ) -> StreamProtocol | 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, and the output + describes the whole node (``ProjectedOutput``: the whole read's keys, the + node's identity), offering only the narrowed table to a column selection. + With no row, it is the node's zero-row output, as for the whole read. + + Args: + read_columns: The data columns the node's successors read. + bindings: The bindings at production. + + Returns: + The output, or ``None``: the node is read whole. + """ + from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + projected_output, + ) + 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 + table = source.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 + return projected_output( + narrow, + keys_of_rows(zero_rows, source_keys), + lambda: self._whole_output(bindings), + bindings=bindings, + ) + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 266bd4551..ba2164936 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -9,6 +9,7 @@ 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.operators.static_output_pod import ProjectedOutput from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( @@ -43,13 +44,15 @@ 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 + reads only those the selection keeps (ITL-1776), and so does a source node's + output in a job read with fewer columns (``ProjectedOutput``, 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): + if isinstance(stream, (SourceProtocol, ProjectedOutput)): 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..1cb1c3488 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -6,6 +6,7 @@ from abc import abstractmethod from collections.abc import ( AsyncIterator, + Callable, Collection, Iterable, Iterator, @@ -1679,6 +1680,215 @@ def rows_on_read( return cast(StreamProtocol, cast(object, RowsOnRead(rows, node, bindings=bindings))) +class ProjectedOutput(MaterializedOutput): + """A source node's output in a job, read with fewer data columns (ITL-1798). + + The orchestrators give a source node the data columns its successors read + (``pipeline.column_demand``) when every successor is a column selection. The node + then reads only those columns (``SourceProtocol.projected_table``) and hands on this + output. It describes the whole node: its keys are those of the whole read, and its + identity (content and pipeline hash, identity chains, producer, upstreams, data + context) is the node's, as the whole output's is. A column selection asks it for + its table with ``projected_table`` (``column_selection._input_table``), and gets the + narrowed table: the whole output's table without the unread data columns and their + source-info columns. + + Every other member is the whole output's, built on first use by reading the source + whole (``whole``), so a reader that needs the whole row gets exactly what it got + before. The projection is an execution detail: no hash, stored path, schema, record + id or stored row depends on it. + """ + + # Not a stream the row-built form already made: a channel opened on it reads it. + _orcapod_row_built_output = False + + def __init__( + self, + narrow: StreamProtocol, + keys: tuple[tuple[str, ...], tuple[str, ...]], + whole: Callable[[], StreamProtocol], + *, + bindings: OutputBindings, + ) -> None: + """Hold the narrowed output and the way to the whole one. + + Args: + narrow: The node's output over the narrowed read, with the node's identity + (``_output_stream`` of the narrowed table). + keys: The tag and data keys of the whole output. + whole: Returns the whole output, reading the source whole. + bindings: The bindings at production. + """ + self._output_bindings = bindings + self._narrow = narrow + self._keys = keys + self._make_whole = whole + self._whole: StreamProtocol | None = None + + @property + def narrow(self) -> StreamProtocol: + """The node's output over the narrowed read (fewer data columns).""" + self._require_current_output() + return self._narrow + + def built(self) -> StreamProtocol: + """The whole output, read on the first call.""" + self._require_current_output() + if self._whole is None: + self._whole = self._make_whole() + return self._whole + + def keys( + self, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The whole output's keys; with column groups asked for, read from it.""" + if columns is None and not all_info: + self._require_current_output() + return self._keys + return self.built().keys(columns=columns, all_info=all_info) + + 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. ``data_columns`` must be + among those read; any other request is answered from the whole output. + + Returns: + The table, or ``None`` when it would not be the whole output's table + without those columns: the caller then reads the whole output. + """ + self._require_current_output() + config = ColumnConfig.handle_config(columns) + tag_keys, data_keys = self._keys + read = set(self._narrow.keys()[1]) + wanted = set(data_columns) + if config.content_hash or config.meta or not wanted <= read: + # A row hash covers every data column; a request beyond the read. + return None + table = self._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]) + + # The node's identity, which the narrowed output holds as the whole one does + # (``_as_upstream_stream`` of the node): reading it reads no row. + @property + def producer(self) -> Any: + return self._narrow.producer + + @property + def upstreams(self) -> tuple[StreamProtocol, ...]: + self._require_current_output() + return self._narrow.upstreams + + @property + def data_context_key(self) -> str: + return self._narrow.data_context_key + + @property + def label(self) -> Any: + return getattr(self._narrow, "label", None) + + @property + def last_modified(self) -> Any: + """When the output was made: the narrowed output's, made where the whole one + would have been.""" + self._require_current_output() + return self._narrow.last_modified + + def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: + """The narrowed output's, which are the node's.""" + self._require_current_output() + return walk.visit(self._narrow) + + def source_chain(self) -> ContentHash: + with identity_lock: + self._require_current_output() + return self._narrow.source_chain() + + def name_chain(self) -> ContentHash: + with identity_lock: + self._require_current_output() + return self._narrow.name_chain() + + def content_hash(self, hasher=None) -> ContentHash: + with identity_lock: + self._require_current_output() + return self._narrow.content_hash(hasher) + + def pipeline_hash(self, hasher=None) -> ContentHash: + with identity_lock: + self._require_current_output() + return self._narrow.pipeline_hash(hasher) + + def __getattr__(self, name: str) -> Any: + # Every other member is the whole output's. + return getattr(self.built(), name) + + def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + return self.built().iter_data() + + def __repr__(self) -> str: + return f"ProjectedOutput({short_stream_repr(self._narrow)})" + + +def _delegated_to_whole(name: str) -> Any: + """A method of ``ProjectedOutput`` that is the whole output's.""" + + def delegate(self: ProjectedOutput, *args: Any, **kwargs: Any) -> Any: + return getattr(self.built(), name)(*args, **kwargs) + + delegate.__name__ = name + return delegate + + +for _name in _stream_protocol_members(): + if _name not in vars(ProjectedOutput): + member = getattr(StreamProtocol, _name, None) + if isinstance(member, property): + setattr( + ProjectedOutput, + _name, + property(lambda self, n=_name: getattr(self.built(), n)), + ) + else: + setattr(ProjectedOutput, _name, _delegated_to_whole(_name)) + + +def projected_output( + narrow: StreamProtocol, + keys: tuple[tuple[str, ...], tuple[str, ...]], + whole: Callable[[], StreamProtocol], + *, + bindings: OutputBindings, +) -> StreamProtocol: + """``ProjectedOutput`` as a stream (it delegates every other member to the whole one). + + Args: + narrow: The node's output over the narrowed read. + keys: The whole output's tag and data keys. + whole: Returns the whole output, reading the source whole. + bindings: The bindings at production. + + Returns: + The output. + """ + return cast( + StreamProtocol, + cast(object, ProjectedOutput(narrow, keys, whole, bindings=bindings)), + ) + + 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..cca266e2a 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -400,6 +400,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], diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 714343c91..c1cf314d4 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1187,6 +1187,8 @@ def as_table( all_info=all_info, ) + PROJECTS_COLUMNS: ClassVar[bool] = True + @override def projected_table( self, diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index a83d789be..f92caaaa8 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()) @@ -307,7 +308,9 @@ def collected_output( tg, failed_nodes, node, - node.async_execute(writer, observer=effective_observer), + _source_execution( + node, writer, effective_observer, graph, read_columns + ), ) elif is_function_node(node) or is_side_effect_function_node(node): predecessors = in_edges.get(node, []) @@ -407,6 +410,21 @@ def collected_output( effective_observer.on_run_end(run_id) +def _source_execution( + node: Any, + writer: Any, + observer: Any, + graph: Any, + read_columns: Callable[[Any, Any], frozenset[str] | None], +) -> Coroutine[Any, Any, None]: + """A source node's ``async_execute``, given its successors' columns when known + (ITL-1798); without them, called exactly as before.""" + demand = read_columns(node, graph) + if demand is None: + return node.async_execute(writer, observer=observer) + return node.async_execute(writer, observer=observer, read_columns=demand) + + def _run_on_own_thread( make_run: Callable[[], Coroutine[Any, Any, _T]], rows_in_flight: _RowsInFlight ) -> _T: 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/node_protocols.py b/src/orcapod/protocols/node_protocols.py index a07d00f68..1cc06d136 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,6 +75,7 @@ async def async_execute( output: WritableChannel[tuple[TagProtocol, DataProtocol]], *, observer: ExecutionObserverProtocol | None = None, + read_columns: Collection[str] | None = None, ) -> None: ... 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_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py new file mode 100644 index 000000000..cb8a43ca3 --- /dev/null +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -0,0 +1,430 @@ +"""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 +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 ProjectedOutput +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 column_demand +from orcapod.sources import SpiralDBTableSource +from orcapod.types import CacheMode, 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, + ) + + +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 isinstance(output, ProjectedOutput) + 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} + narrowed = output.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 output.projected_table(["y"], columns=config) is None + assert output.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"]] + + +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 diff --git a/tests/test_databases/test_spiraldb_projection.py b/tests/test_databases/test_spiraldb_projection.py index bc8309cd9..b9c7cdf16 100644 --- a/tests/test_databases/test_spiraldb_projection.py +++ b/tests/test_databases/test_spiraldb_projection.py @@ -293,10 +293,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} @@ -315,7 +316,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) From 6e37ae89421f421f801b9132c52a7da5842995fb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 02:33:07 -0800 Subject: [PATCH 05/12] fix(pipeline): collect a projected source node's whole output; restore the row-hash refusal (ITL-1798) The async orchestrator collected the narrowed rows a projected source node sent to its selections as the node's output. The node now returns its whole output (a ProjectedOutput, read whole only when read) and the run's node_outputs holds that, as the sync route does. SpiralDBTableSource projected_table again returns None when a row hash is requested. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1798.md | 4 +- src/orcapod/core/nodes/source_node.py | 20 +++-- .../core/sources/spiraldb_table_source.py | 9 ++- src/orcapod/pipeline/async_orchestrator.py | 39 ++++++++-- src/orcapod/protocols/node_protocols.py | 2 +- .../test_spiraldb_job_projection.py | 76 ++++++++++++++++++- 6 files changed, 133 insertions(+), 17 deletions(-) diff --git a/changelog.d/ITL-1798.md b/changelog.d/ITL-1798.md index ff7ffe144..dbf476afa 100644 --- a/changelog.d/ITL-1798.md +++ b/changelog.d/ITL-1798.md @@ -8,5 +8,7 @@ `job.run()`, `job.run_async()`, load-only runs and a node's own `run()`. 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. On a table with a + 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. On a table with a wide column, a narrow job is several times faster. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 213913d4a..7a48ff6ca 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1495,7 +1495,7 @@ async def async_execute( *, observer: ExecutionObserverProtocol | None = None, read_columns: Collection[str] | None = None, - ) -> None: + ) -> StreamProtocol | None: """Push all (tag, data) pairs to the output channel. Delegates to ``async_iter_data`` so that dynamic sources @@ -1510,6 +1510,13 @@ async def async_execute( that read, each without the unread data columns, which every successor drops. + Returns: + The node's whole output when the rows sent are a narrowed read's (a + ``ProjectedOutput``, which reads the source whole only when read): 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. """ @@ -1522,6 +1529,7 @@ async def async_execute( if observer is not None: observer.on_node_start(node_label, node_hash) projected = None + whole: StreamProtocol | None = None if read_columns is not None: bindings = capture_output_bindings(self) projected = await asyncio.to_thread( @@ -1529,11 +1537,10 @@ async def async_execute( ) if projected is not None: # The narrowed read's rows (a projected output's, or no row at all). - rows = ( - projected.narrow - if isinstance(projected, ProjectedOutput) - else projected - ) + rows = projected + if isinstance(projected, ProjectedOutput): + rows = projected.narrow + whole = projected # pyright: ignore[reportAssignmentType] # a stream by delegation for tag, data in rows.iter_data(): await output.send((tag, data)) else: @@ -1541,6 +1548,7 @@ async def async_execute( await output.send((tag, data)) if observer is not None: observer.on_node_end(node_label, node_hash) + return whole finally: await output.close() diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index c1cf314d4..2ccfc4ef9 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1210,8 +1210,14 @@ def projected_table( Returns: The table, or ``None`` when ``data_columns`` names every data column - that is not a tag (nothing would be left unread). + that is not a tag (nothing would be left unread) or the column + configuration requests a hash of each whole row (``content_hash``): the + caller then reads the whole 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} @@ -1221,7 +1227,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/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index f92caaaa8..6d35331fe 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -274,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)] ) @@ -309,7 +316,12 @@ def collected_output( failed_nodes, node, _source_execution( - node, writer, effective_observer, graph, read_columns + node, + writer, + effective_observer, + graph, + read_columns, + whole_outputs, ), ) elif is_function_node(node) or is_side_effect_function_node(node): @@ -410,19 +422,30 @@ def collected_output( effective_observer.on_run_end(run_id) -def _source_execution( +async def _source_execution( node: Any, writer: Any, observer: Any, graph: Any, read_columns: Callable[[Any, Any], frozenset[str] | None], -) -> Coroutine[Any, Any, 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.""" + (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: - return node.async_execute(writer, observer=observer) - return node.async_execute(writer, observer=observer, read_columns=demand) + 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( @@ -854,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/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index 1cc06d136..33e8196a2 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -76,7 +76,7 @@ async def async_execute( *, observer: ExecutionObserverProtocol | None = None, read_columns: Collection[str] | None = None, - ) -> None: ... + ) -> StreamProtocol | None: ... @runtime_checkable diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index cb8a43ca3..7044b65ec 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -23,7 +23,12 @@ 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 column_demand +from orcapod.pipeline import ( + AsyncPipelineOrchestrator, + SyncPipelineOrchestrator, + column_demand, +) +from orcapod.pipeline.dag import OrcaDAG from orcapod.sources import SpiralDBTableSource from orcapod.types import CacheMode, Condition from tests.test_databases import fake_spiral_sdk as fake @@ -428,3 +433,72 @@ def demand(*successors: Any) -> Any: 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 = [ + (tag.as_dict(), data.as_dict(), data.content_hash()) + 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 From 48c97e373a39736758945c70df676987adb6b6bf Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 07:57:29 -0800 Subject: [PATCH 06/12] fix(spiraldb): probes of a projected output read nothing; its whole read keeps the narrowed version (ITL-1798) - ProjectedOutput delegates to the whole output only the public members of the whole output's stream class; a private name or one that class lacks is absent, so hasattr and a runtime protocol check (Python 3.11 looks up every member) never read the source whole. The private members library helpers ask for (zero-row table, schema-needs-io, display name) and arrow_types_declared are answered without reading. The column selection checks ProjectedOutput first. - The whole read is of the version the narrowed rows were read at: it is refused with StaleOutputError once a check has moved the source's pin. - The changelog fragment and docs/concepts/sources.md say that reading the collected source output whole reads the source whole on first use. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1798.md | 7 +- docs/concepts/sources.md | 6 ++ src/orcapod/core/nodes/source_node.py | 39 +++++++- .../core/operators/column_selection.py | 3 +- .../core/operators/static_output_pod.py | 73 ++++++++++++-- .../test_spiraldb_job_projection.py | 97 ++++++++++++++++++- 6 files changed, 211 insertions(+), 14 deletions(-) diff --git a/changelog.d/ITL-1798.md b/changelog.d/ITL-1798.md index dbf476afa..f33bb6481 100644 --- a/changelog.d/ITL-1798.md +++ b/changelog.d/ITL-1798.md @@ -10,5 +10,8 @@ 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. On a table with a - wide column, a narrow job is several times faster. + 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 narrowed columns + were read at, and is refused (`StaleOutputError`) once a check has pinned a newer + one. 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 c8ecfd0be..00b301d60 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -658,6 +658,12 @@ the columns its steps keep when every step that reads it directly is a `select_d 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. 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 narrowed columns were +read at; once a check has pinned a newer version, it is refused (`StaleOutputError`): read +the node again. **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 7a48ff6ca..c83588cb2 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -60,7 +60,11 @@ from orcapod.core.streams.base import ( check_head_size, ) -from orcapod.errors import SourceSpecMismatchError, UnboundSourceError +from orcapod.errors import ( + SourceSpecMismatchError, + StaleOutputError, + UnboundSourceError, +) from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.system_constants import constants @@ -2200,6 +2204,9 @@ def _projected_output( zero_rows = typed_zero_row_table(source) if zero_rows is None: return None + # The source's version the narrowed rows are read at: a check that pins a newer + # one moves the modified time (``check_for_new_data``). + read_at = source.last_modified table = source.projected_table(read_columns, columns=ZERO_ROW_INPUT_COLUMNS) if table is None: return None @@ -2220,10 +2227,20 @@ def _projected_output( if table.num_rows == 0: # The node's zero-row output: what the whole read hands on with no row. return narrow + + def whole() -> StreamProtocol: + # The whole read is of the version the narrowed rows were read at, or + # refused: never whole rows of a newer version than the narrowed ones. + _require_same_version(source, read_at) + output = self._whole_output(bindings) + _require_same_version(source, read_at) + return output + return projected_output( narrow, keys_of_rows(zero_rows, source_keys), - lambda: self._whole_output(bindings), + whole, + node=self, bindings=bindings, ) @@ -2553,3 +2570,21 @@ def as_node(self) -> SourceNode: ) node._take_saved_state_of(self) return node + + +def _require_same_version(source: StreamProtocol, read_at: object) -> None: + """Refuse a whole read of ``source`` once it has moved past ``read_at``. + + A projected output's narrowed rows were read at ``read_at`` (the source's modified + time then); a check that pins a newer version moves it, and the source can no longer + read the version those rows came from (review of PR 687). + + Raises: + StaleOutputError: If the source's modified time is no longer ``read_at``. + """ + if source.last_modified != read_at: + raise StaleOutputError( + "This output's columns were read at an earlier version of its source, " + "which has since moved to a newer one: its other columns cannot be read " + "at that version. Please read the node again." + ) diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index ba2164936..aecfa4dff 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -52,7 +52,8 @@ def _input_table( 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, ProjectedOutput)): + # ``ProjectedOutput`` first: a plain class check looks up nothing on the instance. + if isinstance(stream, (ProjectedOutput, 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 1cb1c3488..e9dedf369 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -2,6 +2,7 @@ import asyncio import dataclasses +import inspect import logging from abc import abstractmethod from collections.abc import ( @@ -1693,10 +1694,17 @@ class ProjectedOutput(MaterializedOutput): narrowed table: the whole output's table without the unread data columns and their source-info columns. - Every other member is the whole output's, built on first use by reading the source - whole (``whole``), so a reader that needs the whole row gets exactly what it got - before. The projection is an execution detail: no hash, stored path, schema, record - id or stored row depends on it. + Every other member of the whole output's stream class is the whole output's, built + on first use by reading the source whole (``whole``), so a reader that needs the + whole row gets exactly what it got before. A probe never reads (review of PR 687): + a name the whole output's class does not have, and every private name, is not + there (``AttributeError``, so ``hasattr`` and a runtime protocol check on Python + 3.11 read nothing), and the private members a library helper asks for (the zero-row + table, whether the schema needs a read, the display name) are answered without + reading. The whole read is of the source version the narrowed rows were read at: + ``whole`` refuses once the source has moved on (``StaleOutputError``). The + projection is an execution detail: no hash, stored path, schema, record id or + stored row depends on it. """ # Not a stream the row-built form already made: a channel opened on it reads it. @@ -1708,6 +1716,7 @@ def __init__( keys: tuple[tuple[str, ...], tuple[str, ...]], whole: Callable[[], StreamProtocol], *, + node: StreamProtocol, bindings: OutputBindings, ) -> None: """Hold the narrowed output and the way to the whole one. @@ -1716,11 +1725,14 @@ def __init__( narrow: The node's output over the narrowed read, with the node's identity (``_output_stream`` of the narrowed table). keys: The tag and data keys of the whole output. - whole: Returns the whole output, reading the source whole. + whole: Returns the whole output, reading the source whole at the version + the narrowed rows were read at, or raises ``StaleOutputError``. + node: The node whose output this is: it types the zero-row table. bindings: The bindings at production. """ self._output_bindings = bindings self._narrow = narrow + self._node = node self._keys = keys self._make_whole = whole self._whole: StreamProtocol | None = None @@ -1806,6 +1818,15 @@ def last_modified(self) -> Any: self._require_current_output() return self._narrow.last_modified + @property + def arrow_types_declared(self) -> bool: + """The narrowed output's: the same kind of stream, built by the same F. + + A property, so it reads nothing: a runtime protocol check on Python 3.11 calls + every property getter of ``StreamProtocol``. + """ + return self._narrow.arrow_types_declared + def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: """The narrowed output's, which are the node's.""" self._require_current_output() @@ -1831,8 +1852,39 @@ def pipeline_hash(self, hasher=None) -> ContentHash: self._require_current_output() return self._narrow.pipeline_hash(hasher) + # What library helpers ask a stream for by private name, answered without reading. + def _typed_zero_row_table(self) -> pa.Table | None: + """The whole output's zero-row table: the node's, in row order; reads nothing.""" + from orcapod.core.streams.base import typed_zero_row_table + + self._require_current_output() + table = typed_zero_row_table(self._node) + if table is None: + return None + return StaticOutputOperatorPod._in_row_order(table, self._keys[0]) + + def _schema_requires_io(self, config: ColumnConfig) -> bool: + """The narrowed output's answer: the same node over the same upstreams.""" + from orcapod.core.streams.base import schema_requires_io + + return schema_requires_io(self._narrow, config) + + def _display_name(self) -> str | None: + """The node's label, as a preview header shows it; reads nothing.""" + return getattr(self._narrow, "label", None) + def __getattr__(self, name: str) -> Any: - # Every other member is the whole output's. + # Every other public member of the whole output's stream class is the whole + # output's, read on first use. A probe never reads: a private name, or one the + # class does not have (a source's ``source_id``, which a runtime protocol check + # looks up on Python 3.11), is not there. + missing = object() + if name.startswith("_") or ( + inspect.getattr_static(type(self._narrow), name, missing) is missing + ): + raise AttributeError( + f"{type(self).__name__!r} object has no attribute {name!r}" + ) return getattr(self.built(), name) def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: @@ -1870,6 +1922,7 @@ def projected_output( keys: tuple[tuple[str, ...], tuple[str, ...]], whole: Callable[[], StreamProtocol], *, + node: StreamProtocol, bindings: OutputBindings, ) -> StreamProtocol: """``ProjectedOutput`` as a stream (it delegates every other member to the whole one). @@ -1877,7 +1930,9 @@ def projected_output( Args: narrow: The node's output over the narrowed read. keys: The whole output's tag and data keys. - whole: Returns the whole output, reading the source whole. + whole: Returns the whole output, reading the source whole at the version the + narrowed rows were read at, or raises ``StaleOutputError``. + node: The node whose output this is. bindings: The bindings at production. Returns: @@ -1885,7 +1940,9 @@ def projected_output( """ return cast( StreamProtocol, - cast(object, ProjectedOutput(narrow, keys, whole, bindings=bindings)), + cast( + object, ProjectedOutput(narrow, keys, whole, node=node, bindings=bindings) + ), ) diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 7044b65ec..511ac1e92 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -28,9 +28,13 @@ 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.errors import StaleOutputError from orcapod.pipeline.dag import OrcaDAG +from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.sources import SpiralDBTableSource -from orcapod.types import CacheMode, Condition +from orcapod.types import CacheMode, ColumnConfig, Condition from tests.test_databases import fake_spiral_sdk as fake if TYPE_CHECKING: @@ -502,3 +506,94 @@ def test_a_direct_projected_read_with_a_row_hash_is_refused(project: Any) -> Non 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 isinstance(output, ProjectedOutput) + 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 test_a_whole_read_after_the_pin_moved_is_refused(project: Any) -> None: + """The whole rows of a projected output are of the version its narrowed rows were + read at: once a check pins a newer version, reading them whole is refused (review + of PR 687, thread 2).""" + output, _, source = _projected(project) + narrowed = output.projected_table(["x"]) + assert narrowed is not None + newer = _rows().slice(0, 2) + project.table("default.wide").write( + newer.set_column(2, "x", pa.array([9.0, 9.0], pa.float64())) + ) + assert source.check_for_new_data() is True + fake.scan_log.clear() + fake.count_log.clear() + with pytest.raises(StaleOutputError, match="earlier version of its source"): + output.as_table() + assert _row_scans() == [] + # The narrowed rows are still those read at production. + again = output.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)) From 917970c6ca15c3575e00bfe634d2328e78df1d11 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 09:15:42 -0800 Subject: [PATCH 07/12] fix(spiraldb): a projected output's whole read uses the snapshot pinned at production (ITL-1798) A kept run's source output read whole after a later check or run moved the source's pin used to be refused (StaleOutputError); without the projection the output was materialized when produced and gave the rows of the version the run used. The node now takes a snapshot of the source at its pinned version (SourceProtocol.pinned_snapshot; SpiralDB returns a copy over the pinned table handle), reads the narrowed rows from it, and reads the whole rows from the same snapshot when asked, so they always equal the whole read at production. A source kind without a snapshot is read whole, as on main. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1798.md | 5 +- docs/concepts/sources.md | 6 +- src/orcapod/core/nodes/source_node.py | 83 +++++++------ .../core/operators/static_output_pod.py | 8 +- src/orcapod/core/sources/base.py | 16 +++ .../core/sources/spiraldb_table_source.py | 11 ++ .../protocols/core_protocols/sources.py | 10 ++ .../test_spiraldb_job_projection.py | 115 ++++++++++++++++-- .../test_source_object_registration.py | 3 + 9 files changed, 201 insertions(+), 56 deletions(-) diff --git a/changelog.d/ITL-1798.md b/changelog.d/ITL-1798.md index f33bb6481..dad2ad6f5 100644 --- a/changelog.d/ITL-1798.md +++ b/changelog.d/ITL-1798.md @@ -12,6 +12,5 @@ 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 narrowed columns - were read at, and is refused (`StaleOutputError`) once a check has pinned a newer - one. On a table with a wide column, a narrow job is several times faster. + 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. 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 00b301d60..c6d88c3d8 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -661,9 +661,9 @@ table is read. The job's rows, stored rows, hashes and stored paths are the same 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 narrowed columns were -read at; once a check has pinned a newer version, it is refused (`StaleOutputError`): read -the node again. +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. **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 c83588cb2..33db925c9 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -60,11 +60,7 @@ from orcapod.core.streams.base import ( check_head_size, ) -from orcapod.errors import ( - SourceSpecMismatchError, - StaleOutputError, - UnboundSourceError, -) +from orcapod.errors import SourceSpecMismatchError, UnboundSourceError from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.logical_types.user_class_identity import equivalent_hints from orcapod.system_constants import constants @@ -83,7 +79,7 @@ from orcapod.channels import WritableChannel from orcapod.core.output_bindings import OutputBindings 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, ) @@ -2175,6 +2171,13 @@ def _projected_output( node's identity), offering only the narrowed table to a column selection. With no row, it is the node's zero-row output, as for the whole read. + 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. @@ -2204,10 +2207,13 @@ def _projected_output( zero_rows = typed_zero_row_table(source) if zero_rows is None: return None - # The source's version the narrowed rows are read at: a check that pins a newer - # one moves the modified time (``check_for_new_data``). - read_at = source.last_modified - table = source.projected_table(read_columns, columns=ZERO_ROW_INPUT_COLUMNS) + # 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. + snapshot = source.pinned_snapshot() + if snapshot is None: + return None + 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): @@ -2229,12 +2235,8 @@ def _projected_output( return narrow def whole() -> StreamProtocol: - # The whole read is of the version the narrowed rows were read at, or - # refused: never whole rows of a newer version than the narrowed ones. - _require_same_version(source, read_at) - output = self._whole_output(bindings) - _require_same_version(source, read_at) - return output + # The whole read, of the snapshot the narrowed rows were read from. + return self._whole_output_of(snapshot, bindings) return projected_output( narrow, @@ -2244,6 +2246,37 @@ def whole() -> StreamProtocol: bindings=bindings, ) + 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_output`` 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. @@ -2570,21 +2603,3 @@ def as_node(self) -> SourceNode: ) node._take_saved_state_of(self) return node - - -def _require_same_version(source: StreamProtocol, read_at: object) -> None: - """Refuse a whole read of ``source`` once it has moved past ``read_at``. - - A projected output's narrowed rows were read at ``read_at`` (the source's modified - time then); a check that pins a newer version moves it, and the source can no longer - read the version those rows came from (review of PR 687). - - Raises: - StaleOutputError: If the source's modified time is no longer ``read_at``. - """ - if source.last_modified != read_at: - raise StaleOutputError( - "This output's columns were read at an earlier version of its source, " - "which has since moved to a newer one: its other columns cannot be read " - "at that version. Please read the node again." - ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index e9dedf369..e458b1682 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1702,7 +1702,9 @@ class ProjectedOutput(MaterializedOutput): 3.11 read nothing), and the private members a library helper asks for (the zero-row table, whether the schema needs a read, the display name) are answered without reading. The whole read is of the source version the narrowed rows were read at: - ``whole`` refuses once the source has moved on (``StaleOutputError``). The + ``whole`` reads the snapshot of the source pinned at production + (``SourceProtocol.pinned_snapshot``), so the whole rows are those a whole read + at production gave, also after a later check pins a newer version. The projection is an execution detail: no hash, stored path, schema, record id or stored row depends on it. """ @@ -1726,7 +1728,7 @@ def __init__( (``_output_stream`` of the narrowed table). keys: The tag and data keys of the whole output. whole: Returns the whole output, reading the source whole at the version - the narrowed rows were read at, or raises ``StaleOutputError``. + the narrowed rows were read at (its snapshot pinned at production). node: The node whose output this is: it types the zero-row table. bindings: The bindings at production. """ @@ -1931,7 +1933,7 @@ def projected_output( narrow: The node's output over the narrowed read. keys: The whole output's tag and data keys. whole: Returns the whole output, reading the source whole at the version the - narrowed rows were read at, or raises ``StaleOutputError``. + narrowed rows were read at (its snapshot pinned at production). node: The node whose output this is. bindings: The bindings at production. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index cca266e2a..9ce76d002 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -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 @@ -428,6 +429,21 @@ def projected_table( """ 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 aca689356..9f75eebab 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1189,6 +1189,17 @@ def as_table( 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, diff --git a/src/orcapod/protocols/core_protocols/sources.py b/src/orcapod/protocols/core_protocols/sources.py index d99a566c4..5ff061f5f 100644 --- a/src/orcapod/protocols/core_protocols/sources.py +++ b/src/orcapod/protocols/core_protocols/sources.py @@ -63,6 +63,16 @@ def projected_table( """ ... + 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/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 511ac1e92..b939b4dc9 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -30,7 +30,6 @@ ) from orcapod.core.streams.base import schema_requires_io, typed_zero_row_table from orcapod.core.streams.view import display_name -from orcapod.errors import StaleOutputError from orcapod.pipeline.dag import OrcaDAG from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.sources import SpiralDBTableSource @@ -569,23 +568,94 @@ def counted(self: Any, *args: Any, **kwargs: Any) -> pa.Table: assert _row_scans() == [["t", "unit", "x"]] -def test_a_whole_read_after_the_pin_moved_is_refused(project: Any) -> None: - """The whole rows of a projected output are of the version its narrowed rows were - read at: once a check pins a newer version, reading them whole is refused (review - of PR 687, thread 2).""" - output, _, source = _projected(project) - narrowed = output.projected_table(["x"]) - assert narrowed is not None +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), + [ + (tag.as_dict(), data.as_dict(), data.content_hash()) + 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) + narrowed = output.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 - fake.scan_log.clear() - fake.count_log.clear() - with pytest.raises(StaleOutputError, match="earlier version of its source"): - output.as_table() - assert _row_scans() == [] + _same(output.as_table(all_info=True), expected) # The narrowed rows are still those read at production. again = output.projected_table(["x"]) assert again is not None @@ -597,3 +667,22 @@ def test_a_whole_read_at_the_pin_of_production_is_allowed(project: Any) -> None: 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] diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index ac7ede727..bf3ca65e8 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1581,6 +1581,9 @@ def projected_table( ) -> pa.Table | None: return None + def pinned_snapshot(self) -> SourceProtocol | None: + return None + def to_config( self, db_registry: DatabaseRegistryProtocol | None = None ) -> dict[str, Any]: From b3d9eac73bd8ecbcbb9016f5e6eeaeaa07a3d6d2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 10:01:17 -0800 Subject: [PATCH 08/12] fix(spiraldb): a projected output answers every member as main's and reads rows only for rows (ITL-1798) ProjectedOutput now defines every public member of the class main's collected source output has, and its notebook and dunder hooks, explicitly; no member is looked up at run time. Members that describe the stream (keys, schemas, data context, label, identity and hashes, explain, head(0)) are answered by the node's output with no row, of the class the route collects (the stream built from the table on the sync orchestrator, RowsOnRead on the async one), and read nothing. Row members (tables, rows, data frames, run, head, preview, identity structure) read the pinned snapshot whole once. Operator methods, open_channel and async_iter_data build over the output and read only when their rows are read. A parametrized test checks each member against main's output on both orchestrators, and fails for a member added to that class until it is classified. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1798.md | 4 +- docs/concepts/sources.md | 4 +- src/orcapod/core/nodes/source_node.py | 3 +- .../core/operators/static_output_pod.py | 393 ++++++++++++------ .../test_spiraldb_job_projection.py | 310 ++++++++++++++ 5 files changed, 594 insertions(+), 120 deletions(-) diff --git a/changelog.d/ITL-1798.md b/changelog.d/ITL-1798.md index dad2ad6f5..7fac6a99e 100644 --- a/changelog.d/ITL-1798.md +++ b/changelog.d/ITL-1798.md @@ -13,4 +13,6 @@ 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. On a table with a wide column, a narrow job is several times faster. + 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)`) 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 c6d88c3d8..41985726c 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -663,7 +663,9 @@ for every column: reading it whole (its `as_table()`, its rows, or any read that 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. +when the run made the output. Describing that output reads nothing: its keys, schemas, +hashes, `explain()` and a `head(0)`, 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 33db925c9..5058ea76b 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1540,7 +1540,8 @@ async def async_execute( rows = projected if isinstance(projected, ProjectedOutput): rows = projected.narrow - whole = projected # pyright: ignore[reportAssignmentType] # a stream by delegation + # Collected as this route collects a node's output: its rows. + whole = projected.held_as_rows() # pyright: ignore[reportAssignmentType] # a stream by its members for tag, data in rows.iter_data(): await output.send((tag, data)) else: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index e458b1682..161ac2c7e 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -2,7 +2,6 @@ import asyncio import dataclasses -import inspect import logging from abc import abstractmethod from collections.abc import ( @@ -30,7 +29,7 @@ from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext -from orcapod.core.base import TraceableBase +from orcapod.core.base import ContentIdentifiableBase, TraceableBase from orcapod.core.data_tags import ( not_supported_yet, data_tag_names, @@ -1687,26 +1686,34 @@ class ProjectedOutput(MaterializedOutput): The orchestrators give a source node the data columns its successors read (``pipeline.column_demand``) when every successor is a column selection. The node then reads only those columns (``SourceProtocol.projected_table``) and hands on this - output. It describes the whole node: its keys are those of the whole read, and its - identity (content and pipeline hash, identity chains, producer, upstreams, data - context) is the node's, as the whole output's is. A column selection asks it for - its table with ``projected_table`` (``column_selection._input_table``), and gets the - narrowed table: the whole output's table without the unread data columns and their - source-info columns. - - Every other member of the whole output's stream class is the whole output's, built - on first use by reading the source whole (``whole``), so a reader that needs the - whole row gets exactly what it got before. A probe never reads (review of PR 687): - a name the whole output's class does not have, and every private name, is not - there (``AttributeError``, so ``hasattr`` and a runtime protocol check on Python - 3.11 read nothing), and the private members a library helper asks for (the zero-row - table, whether the schema needs a read, the display name) are answered without - reading. The whole read is of the source version the narrowed rows were read at: - ``whole`` reads the snapshot of the source pinned at production - (``SourceProtocol.pinned_snapshot``), so the whole rows are those a whole read - at production gave, also after a later check pins a newer version. The - projection is an execution detail: no hash, stored path, schema, record id or - stored row depends on it. + output. It stands for the node's whole output, the stream the whole read gives + (``whole``), and answers every member of that stream's class as it does, each + member explicitly (review of PR 687): nothing is looked up by name at run time, so + ``hasattr`` and a runtime protocol check read nothing, and a member the class does + not have is not there. The members fall in four groups: + + - What describes the stream (keys, schemas, data-tags, data context, label, the + identity: content, pipeline and node hash, identity chains, producer, upstreams, + ``explain``): the answers of ``described``, the node's output with no row, built + as the whole output is, from the node's zero-row table and the node's identity. + Nothing is read (the Arrow schema is never computed). + - When it was made (``last_modified``, ``is_stale``, ``updated_since``): the + narrowed output's, made where the whole one would have been. + - The rows (``as_table``, ``iter_data``, the data frames, ``flow``, ``run``, + ``head`` of one row or more, the identity structure, which holds the rows, + equality, the notebook preview): the whole output's, read on first use, once. + - A step over the stream (an operator method, ``open_channel``, + ``async_iter_data``): built over this output, reading nothing until its rows are + read. A column selection then asks it for its table with ``projected_table`` + (``column_selection._input_table``) and gets the narrowed table: the whole + output's table without the unread data columns and their source-info columns. + + The whole read is of the source version the narrowed rows were read at: ``whole`` + reads the snapshot of the source pinned at production + (``SourceProtocol.pinned_snapshot``), so the whole rows are those a whole read at + production gave, also after a later check pins a newer version. The projection is + an execution detail: no hash, stored path, schema, record id or stored row depends + on it. """ # Not a stream the row-built form already made: a channel opened on it reads it. @@ -1720,6 +1727,7 @@ def __init__( *, node: StreamProtocol, bindings: OutputBindings, + held_as_rows: bool = False, ) -> None: """Hold the narrowed output and the way to the whole one. @@ -1731,13 +1739,18 @@ def __init__( the narrowed rows were read at (its snapshot pinned at production). node: The node whose output this is: it types the zero-row table. bindings: The bindings at production. + held_as_rows: Whether the route that collects it holds a node's output as + its rows (``RowsOnRead``, the async orchestrator's collected output) + rather than as the stream built from its table (the sync one's). """ self._output_bindings = bindings + self._held_as_rows = held_as_rows self._narrow = narrow self._node = node self._keys = keys self._make_whole = whole self._whole: StreamProtocol | None = None + self._described: StreamProtocol | None = None @property def narrow(self) -> StreamProtocol: @@ -1745,6 +1758,18 @@ def narrow(self) -> StreamProtocol: self._require_current_output() return self._narrow + def held_as_rows(self) -> ProjectedOutput: + """This output as the async orchestrator collects it: a node's output held as + its rows (``RowsOnRead``), so that ``described`` is of that class.""" + return ProjectedOutput( + self._narrow, + self._keys, + self._make_whole, + node=self._node, + bindings=self._output_bindings, + held_as_rows=True, + ) + def built(self) -> StreamProtocol: """The whole output, read on the first call.""" self._require_current_output() @@ -1752,17 +1777,32 @@ def built(self) -> StreamProtocol: self._whole = self._make_whole() return self._whole - def keys( - self, - *, - columns: ColumnConfig | dict[str, Any] | None = None, - all_info: bool = False, - ) -> tuple[tuple[str, ...], tuple[str, ...]]: - """The whole output's keys; with column groups asked for, read from it.""" - if columns is None and not all_info: - self._require_current_output() - return self._keys - return self.built().keys(columns=columns, all_info=all_info) + def described(self) -> StreamProtocol: + """The whole output with no row: its class, columns, types and identity. + + Of the class the route that collects the output gives a whole read's output, + built as that is: the stream of the node's zero-row table + (``typed_zero_row_table``) in row order (``_as_upstream_stream`` of the node), or, + held as rows, the node's output holding no row (``RowsOnRead``). Reads nothing. + Each of its members checks the bindings as the whole output's does. + """ + if self._described is None and self._held_as_rows: + self._described = rows_on_read( + [], self._node, bindings=self._output_bindings + ) + if self._described is None: + table = typed_zero_row_table(self._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 = self._keys + self._described = StaticOutputOperatorPod._as_upstream_stream( + StaticOutputOperatorPod._in_row_order(table, tag_keys), + tag_keys, + data_tag_names(tag_keys, data_keys), + self._node, + bindings=self._output_bindings, + ) + return self._described def projected_table( self, @@ -1794,129 +1834,248 @@ 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]) - # The node's identity, which the narrowed output holds as the whole one does - # (``_as_upstream_stream`` of the node): reading it reads no row. + # -- What describes the stream: ``described``'s answers; nothing is read. -- + + def keys( + self, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> tuple[tuple[str, ...], tuple[str, ...]]: + return self.described().keys(columns=columns, all_info=all_info) + + def output_schema( + self, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> tuple[Schema, Schema]: + return self.described().output_schema(columns=columns, all_info=all_info) + + def arrow_schema(self) -> pa.Schema: + return self.described().arrow_schema() + @property - def producer(self) -> Any: - return self._narrow.producer + def arrow_types_declared(self) -> bool: + return self.described().arrow_types_declared @property - def upstreams(self) -> tuple[StreamProtocol, ...]: - self._require_current_output() - return self._narrow.upstreams + def data_tags(self) -> tuple[str, ...]: + return cast(ArrowTableStream, self.described()).data_tags + + @property + def data_context(self) -> DataContext: + return cast(ArrowTableStream, self.described()).data_context @property def data_context_key(self) -> str: - return self._narrow.data_context_key + return self.described().data_context_key + + @property + def orcapod_config(self) -> OrcapodConfig: + return cast(ArrowTableStream, self.described()).orcapod_config @property def label(self) -> Any: - return getattr(self._narrow, "label", None) + return self.described().label @property - def last_modified(self) -> Any: - """When the output was made: the narrowed output's, made where the whole one - would have been.""" - self._require_current_output() - return self._narrow.last_modified + def has_assigned_label(self) -> bool: + return cast(ArrowTableStream, self.described()).has_assigned_label + + def computed_label(self) -> str | None: + return cast(ArrowTableStream, self.described()).computed_label() @property - def arrow_types_declared(self) -> bool: - """The narrowed output's: the same kind of stream, built by the same F. + def producer(self) -> Any: + return self.described().producer - A property, so it reads nothing: a runtime protocol check on Python 3.11 calls - every property getter of ``StreamProtocol``. - """ - return self._narrow.arrow_types_declared + @property + def upstreams(self) -> tuple[StreamProtocol, ...]: + return self.described().upstreams - def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: - """The narrowed output's, which are the node's.""" - self._require_current_output() - return walk.visit(self._narrow) + def explain(self) -> Any: + return cast(ArrowTableStream, self.described()).explain() + + @staticmethod + def content_hash_generation() -> object: + return ArrowTableStream.content_hash_generation() + + def content_hash(self, hasher=None) -> ContentHash: + return self.described().content_hash(hasher) + + def pipeline_hash(self, hasher=None) -> ContentHash: + return self.described().pipeline_hash(hasher) + + def node_hash(self) -> ContentHash: + return cast(ArrowTableStream, self.described()).node_hash() def source_chain(self) -> ContentHash: - with identity_lock: - self._require_current_output() - return self._narrow.source_chain() + return self.described().source_chain() def name_chain(self) -> ContentHash: - with identity_lock: - self._require_current_output() - return self._narrow.name_chain() + return self.described().name_chain() - def content_hash(self, hasher=None) -> ContentHash: - with identity_lock: - self._require_current_output() - return self._narrow.content_hash(hasher) + def pipeline_identity_structure(self) -> Any: + return self.described().pipeline_identity_structure() - def pipeline_hash(self, hasher=None) -> ContentHash: - with identity_lock: - self._require_current_output() - return self._narrow.pipeline_hash(hasher) + def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: + return walk.visit(self.described()) - # What library helpers ask a stream for by private name, answered without reading. def _typed_zero_row_table(self) -> pa.Table | None: - """The whole output's zero-row table: the node's, in row order; reads nothing.""" - from orcapod.core.streams.base import typed_zero_row_table - - self._require_current_output() - table = typed_zero_row_table(self._node) - if table is None: - return None - return StaticOutputOperatorPod._in_row_order(table, self._keys[0]) + return typed_zero_row_table(self.described()) def _schema_requires_io(self, config: ColumnConfig) -> bool: - """The narrowed output's answer: the same node over the same upstreams.""" from orcapod.core.streams.base import schema_requires_io - return schema_requires_io(self._narrow, config) + return schema_requires_io(self.described(), config) def _display_name(self) -> str | None: - """The node's label, as a preview header shows it; reads nothing.""" - return getattr(self._narrow, "label", None) + return cast(ArrowTableStream, self.described())._display_name() # pyright: ignore[reportPrivateUsage] # the preview header of the whole output - def __getattr__(self, name: str) -> Any: - # Every other public member of the whole output's stream class is the whole - # output's, read on first use. A probe never reads: a private name, or one the - # class does not have (a source's ``source_id``, which a runtime protocol check - # looks up on Python 3.11), is not there. - missing = object() - if name.startswith("_") or ( - inspect.getattr_static(type(self._narrow), name, missing) is missing - ): - raise AttributeError( - f"{type(self).__name__!r} object has no attribute {name!r}" - ) - return getattr(self.built(), name) + def __hash__(self) -> int: + return hash(self.described()) - def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - return self.built().iter_data() + def __str__(self) -> str: + return str(self.described()) def __repr__(self) -> str: - return f"ProjectedOutput({short_stream_repr(self._narrow)})" + return repr(self.described()) + # -- When it was made: the narrowed output's, made where the whole one would be. -- -def _delegated_to_whole(name: str) -> Any: - """A method of ``ProjectedOutput`` that is the whole output's.""" + @property + def last_modified(self) -> datetime | None: + self._require_current_output() + return self._narrow.last_modified - def delegate(self: ProjectedOutput, *args: Any, **kwargs: Any) -> Any: - return getattr(self.built(), name)(*args, **kwargs) + @property + def is_stale(self) -> bool: + self._require_current_output() + return cast(ArrowTableStream, self._narrow).is_stale - delegate.__name__ = name - return delegate + def updated_since(self, timestamp: datetime) -> bool: + self._require_current_output() + return cast(ArrowTableStream, self._narrow).updated_since(timestamp) + def clear_cache(self) -> None: + cast(ArrowTableStream, self._narrow).clear_cache() + if self._whole is not None: + cast(ArrowTableStream, self._whole).clear_cache() -for _name in _stream_protocol_members(): - if _name not in vars(ProjectedOutput): - member = getattr(StreamProtocol, _name, None) - if isinstance(member, property): - setattr( - ProjectedOutput, - _name, - property(lambda self, n=_name: getattr(self.built(), n)), + # -- The rows: the whole output's, read on first use. -- + + def as_table( + self, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> pa.Table: + return self.built().as_table(columns=columns, all_info=all_info) + + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + return self.built().iter_data() + + def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: + return iter(cast(ArrowTableStream, self.built())) + + def flow(self) -> list[tuple[TagProtocol, DataProtocol]]: + return cast(ArrowTableStream, self.built()).flow() + + def run(self) -> StreamView: + return cast(ArrowTableStream, self.built()).run() + + def as_polars_df(self, *args: Any, **kwargs: Any) -> Any: + return cast(ArrowTableStream, self.built()).as_polars_df(*args, **kwargs) + + def as_df(self, *args: Any, **kwargs: Any) -> Any: + return cast(ArrowTableStream, self.built()).as_df(*args, **kwargs) + + def as_lazy_frame(self, *args: Any, **kwargs: Any) -> Any: + return cast(ArrowTableStream, self.built()).as_lazy_frame(*args, **kwargs) + + def as_pandas_df(self, *args: Any, **kwargs: Any) -> Any: + return cast(ArrowTableStream, self.built()).as_pandas_df(*args, **kwargs) + + def identity_structure(self) -> Any: + return self.built().identity_structure() + + def __eq__(self, other: object) -> bool: + """As the whole output's class compares: by identity structure (the rows), or, + for a class that does not define it (``RowsOnRead``), by object.""" + if not isinstance(self.described(), ContentIdentifiableBase): + return True if other is self else NotImplemented + if not isinstance(other, (ContentIdentifiableBase, ProjectedOutput)): + return NotImplemented + return self.identity_structure() == other.identity_structure() + + def head( + self, + n: int = 10, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> StreamView: + """The whole output's head; with no row asked for, read from nothing. + + ``head(0)`` is the described output's head, with the whole output's row + count: the narrowed output's, which holds the same rows. + """ + check_head_size(n) + if n == 0: + view = cast( + StreamView, + self.described().head(0, columns=columns, all_info=all_info), ) - else: - setattr(ProjectedOutput, _name, _delegated_to_whole(_name)) + return dataclasses.replace( + view, total_rows=self._narrow.as_table().num_rows + ) + return cast( + StreamView, self.built().head(n, columns=columns, all_info=all_info) + ) + + def _repr_html_(self) -> str: + """The whole output's notebook preview; a stale output shows its error.""" + from orcapod.core.streams.view import preview_html + + try: + shown = self.built() + except Exception: # noqa: BLE001 - a display hook must not raise + # The narrowed output, of the whole output's class and label, raises the + # same error in its head, and the preview shows it. + shown = self._narrow + return preview_html(shown) + + # -- A step over the stream: built over this output, reading nothing. -- + + join = StreamBase.join + rejoin = StreamBase.rejoin + semi_join = StreamBase.semi_join + map_tags = StreamBase.map_tags + map_data = StreamBase.map_data + map_columns = StreamBase.map_columns + batch = StreamBase.batch + group_by = StreamBase.group_by + polars_filter = StreamBase.polars_filter + filter = StreamBase.filter + drop_nulls = StreamBase.drop_nulls + tag_by = StreamBase.tag_by + add_tags = StreamBase.add_tags + select_tag_columns = StreamBase.select_tag_columns + select_data_columns = StreamBase.select_data_columns + drop_tag_columns = StreamBase.drop_tag_columns + drop_data_columns = StreamBase.drop_data_columns + drop_columns = StreamBase.drop_columns + select_columns = StreamBase.select_columns + pick = StreamBase.pick + index = StreamBase.index + open_channel = StreamBase.open_channel + + async def async_iter_data( + self, + ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: + for item in self.iter_data(): + yield item def projected_output( @@ -1927,7 +2086,7 @@ def projected_output( node: StreamProtocol, bindings: OutputBindings, ) -> StreamProtocol: - """``ProjectedOutput`` as a stream (it delegates every other member to the whole one). + """``ProjectedOutput`` as a stream (it answers every member as the whole output does). Args: narrow: The node's output over the narrowed read. diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index b939b4dc9..4029e4fa4 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -11,6 +11,8 @@ from __future__ import annotations import asyncio +import dataclasses +import datetime from collections.abc import Callable from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast @@ -686,3 +688,311 @@ def test_a_source_without_a_snapshot_is_read_whole( ) 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). Every public member of the class of main's collected output, and the +# hooks below, must be classified here: a member added to that class later fails +# ``test_every_member_of_the_collected_output_is_classified`` until it is. +_HOOKS = ( + "__eq__", + "__hash__", + "__iter__", + "__repr__", + "__str__", + "_repr_html_", + "_display_name", + "_identity_chains", + "_schema_requires_io", + "_typed_zero_row_table", +) + + +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), + "head(0, all_info)": lambda s: s.head(0, all_info=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), + "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 (tag.as_dict(), data.as_dict(), data.content_hash()) + 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] + assert isinstance(output, ProjectedOutput) is not whole + return output + + +def test_every_member_of_the_collected_output_is_classified( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Each public member of main's collected output's class, and each hook, is + classified above and defined on ``ProjectedOutput`` itself, as is every member of + ``StreamProtocol``: nothing is answered by a lookup at run time.""" + main_output = _collected_output("sync", whole=True, monkeypatch=monkeypatch) + public = {n for n in dir(type(main_output)) if not n.startswith("_")} + classified = ( + {n for n in _DESCRIBE if n.isidentifier()} | set(_ROWS) | set(_STEPS) + ) - {"hasattr"} + assert public | set(_HOOKS) == classified + assert all(hasattr(type(main_output), name) for name in _HOOKS) + from orcapod.core.operators.static_output_pod import _stream_protocol_members + + defined = set(vars(ProjectedOutput)) + assert classified - defined == set() + assert set(_stream_protocol_members()) - defined == set() + assert "__getattr__" not in defined + + +_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]) From 267a5edc33556e9be2fd46afeb7378888f2532a1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 10:40:38 -0800 Subject: [PATCH 09/12] refactor(spiraldb): collect main's own output classes with a shared whole-row loader (ITL-1798) A projected source node's collected output is now main's own class on each route: the table-built stream (sync) and RowsOnRead (async), unchanged in every member. The class holds its zero-row table and a WholeRead: a memoized whole read of the snapshot pinned at production, made at the class's own row access and shared by shallow copies. A column selection on the output takes the narrowed read until the rows are read. The mirror class, which kept diverging from main, is removed. Fixes from the review of PR 687: sync and async outputs compare and hash as main's; a shallow copy shares the one whole read; the async output keeps release_built. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 96 ++-- .../core/operators/column_selection.py | 21 +- .../core/operators/static_output_pod.py | 476 ++---------------- .../core/streams/arrow_table_stream.py | 120 ++++- .../test_spiraldb_job_projection.py | 161 ++++-- 5 files changed, 361 insertions(+), 513 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5058ea76b..5172f336f 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -78,6 +78,7 @@ 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 SourceProtocol, StreamProtocol from orcapod.protocols.core_protocols.streams import ( @@ -1423,9 +1424,10 @@ def execute( 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 still describes - the whole node (``ProjectedOutput``). An execution detail: no hash, - schema, record id or stored row depends on it. + 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. @@ -1480,6 +1482,28 @@ def _projected_output( ) -> 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). @@ -1511,16 +1535,16 @@ async def async_execute( successor drops. Returns: - The node's whole output when the rows sent are a narrowed read's (a - ``ProjectedOutput``, which reads the source whole only when read): the - node's output is that, never the narrowed rows sent, so a caller that + 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 ProjectedOutput + 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 @@ -1533,16 +1557,15 @@ async def async_execute( if read_columns is not None: bindings = capture_output_bindings(self) projected = await asyncio.to_thread( - self._projected_output, read_columns, bindings + self._projected_read, read_columns, bindings ) + if projected is not None and projected[1] is not None: + # Collected as this route collects a node's output: its rows, + # read whole when first read. + whole = rows_on_read_of(self, projected[1], bindings=bindings) if projected is not None: - # The narrowed read's rows (a projected output's, or no row at all). - rows = projected - if isinstance(projected, ProjectedOutput): - rows = projected.narrow - # Collected as this route collects a node's output: its rows. - whole = projected.held_as_rows() # pyright: ignore[reportAssignmentType] # a stream by its members - for tag, data in rows.iter_data(): + # The narrowed read's rows (none, with no row at all). + for tag, data in projected[0].iter_data(): await output.send((tag, data)) else: async for tag, data in self.async_iter_data(): @@ -2160,17 +2183,18 @@ def _rows_table( return None return table, keys_of_rows(table, source.keys()) - def _projected_output( + def _projected_read( self, read_columns: Collection[str], bindings: OutputBindings - ) -> StreamProtocol | None: + ) -> 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, and the output - describes the whole node (``ProjectedOutput``: the whole read's keys, the - node's identity), offering only the narrowed table to a column selection. - With no row, it is the node's zero-row output, as for the whole read. + 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 @@ -2184,13 +2208,15 @@ def _projected_output( bindings: The bindings at production. Returns: - The output, or ``None``: the node is read whole. + 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, - projected_output, + at_edge, ) + from orcapod.core.streams.arrow_table_stream import ArrowTableStream, WholeRead from orcapod.protocols.core_protocols import SourceProtocol if not reads_as_its_class(self, SourceJobNode): @@ -2233,19 +2259,17 @@ def _projected_output( return None if table.num_rows == 0: # The node's zero-row output: what the whole read hands on with no row. - return narrow - - def whole() -> StreamProtocol: - # The whole read, of the snapshot the narrowed rows were read from. - return self._whole_output_of(snapshot, bindings) + 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 projected_output( - narrow, - keys_of_rows(zero_rows, source_keys), - whole, - node=self, - bindings=bindings, - ) + return narrow, WholeRead(whole, narrow, keys_of_rows(zero_rows, source_keys)) def _whole_output_of( self, snapshot: SourceProtocol, bindings: OutputBindings @@ -2254,7 +2278,7 @@ def _whole_output_of( ``_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_output`` has checked what ``_rows_table`` + snapshot's version. ``_projected_read`` has checked what ``_rows_table`` checks of the source (class, declared form, kind, data context). Args: diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index aecfa4dff..79b594304 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -9,8 +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.operators.static_output_pod import ProjectedOutput -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, @@ -45,15 +47,18 @@ def _input_table( A source that can scan fewer columns (``SourceProtocol.projected_table``) reads only those the selection keeps (ITL-1776), and so does a source node's - output in a job read with fewer columns (``ProjectedOutput``, 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 + 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). """ - # ``ProjectedOutput`` first: a plain class check looks up nothing on the instance. - if isinstance(stream, (ProjectedOutput, 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 161ac2c7e..aab7fca49 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -6,7 +6,6 @@ from abc import abstractmethod from collections.abc import ( AsyncIterator, - Callable, Collection, Iterable, Iterator, @@ -29,7 +28,7 @@ from orcapod import contexts from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext -from orcapod.core.base import ContentIdentifiableBase, TraceableBase +from orcapod.core.base import TraceableBase from orcapod.core.data_tags import ( not_supported_yet, data_tag_names, @@ -58,6 +57,7 @@ ) from orcapod.core.streams.arrow_table_stream import ( ArrowTableStream, + WholeRead, ) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -1450,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]], @@ -1476,9 +1480,15 @@ 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 - ) + if self._row_loader is not None: + # Rows not read yet: the stream reads them on its first row access. + stream = whole_on_read( + self._node, self._row_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 @@ -1496,6 +1506,9 @@ 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() + if self._row_loader is not None: + self._rows = list(self._row_loader().iter_data()) + self._row_loader = None if not self._output_bindings: return iter(self._rows) return self._iter_current_rows() @@ -1680,431 +1693,52 @@ def rows_on_read( return cast(StreamProtocol, cast(object, RowsOnRead(rows, node, bindings=bindings))) -class ProjectedOutput(MaterializedOutput): - """A source node's output in a job, read with fewer data columns (ITL-1798). - - The orchestrators give a source node the data columns its successors read - (``pipeline.column_demand``) when every successor is a column selection. The node - then reads only those columns (``SourceProtocol.projected_table``) and hands on this - output. It stands for the node's whole output, the stream the whole read gives - (``whole``), and answers every member of that stream's class as it does, each - member explicitly (review of PR 687): nothing is looked up by name at run time, so - ``hasattr`` and a runtime protocol check read nothing, and a member the class does - not have is not there. The members fall in four groups: - - - What describes the stream (keys, schemas, data-tags, data context, label, the - identity: content, pipeline and node hash, identity chains, producer, upstreams, - ``explain``): the answers of ``described``, the node's output with no row, built - as the whole output is, from the node's zero-row table and the node's identity. - Nothing is read (the Arrow schema is never computed). - - When it was made (``last_modified``, ``is_stale``, ``updated_since``): the - narrowed output's, made where the whole one would have been. - - The rows (``as_table``, ``iter_data``, the data frames, ``flow``, ``run``, - ``head`` of one row or more, the identity structure, which holds the rows, - equality, the notebook preview): the whole output's, read on first use, once. - - A step over the stream (an operator method, ``open_channel``, - ``async_iter_data``): built over this output, reading nothing until its rows are - read. A column selection then asks it for its table with ``projected_table`` - (``column_selection._input_table``) and gets the narrowed table: the whole - output's table without the unread data columns and their source-info columns. - - The whole read is of the source version the narrowed rows were read at: ``whole`` - reads the snapshot of the source pinned at production - (``SourceProtocol.pinned_snapshot``), so the whole rows are those a whole read at - production gave, also after a later check pins a newer version. The projection is - an execution detail: no hash, stored path, schema, record id or stored row depends - on it. - """ - - # Not a stream the row-built form already made: a channel opened on it reads it. - _orcapod_row_built_output = False - - def __init__( - self, - narrow: StreamProtocol, - keys: tuple[tuple[str, ...], tuple[str, ...]], - whole: Callable[[], StreamProtocol], - *, - node: StreamProtocol, - bindings: OutputBindings, - held_as_rows: bool = False, - ) -> None: - """Hold the narrowed output and the way to the whole one. - - Args: - narrow: The node's output over the narrowed read, with the node's identity - (``_output_stream`` of the narrowed table). - keys: The tag and data keys of the whole output. - whole: Returns the whole output, reading the source whole at the version - the narrowed rows were read at (its snapshot pinned at production). - node: The node whose output this is: it types the zero-row table. - bindings: The bindings at production. - held_as_rows: Whether the route that collects it holds a node's output as - its rows (``RowsOnRead``, the async orchestrator's collected output) - rather than as the stream built from its table (the sync one's). - """ - self._output_bindings = bindings - self._held_as_rows = held_as_rows - self._narrow = narrow - self._node = node - self._keys = keys - self._make_whole = whole - self._whole: StreamProtocol | None = None - self._described: StreamProtocol | None = None - - @property - def narrow(self) -> StreamProtocol: - """The node's output over the narrowed read (fewer data columns).""" - self._require_current_output() - return self._narrow - - def held_as_rows(self) -> ProjectedOutput: - """This output as the async orchestrator collects it: a node's output held as - its rows (``RowsOnRead``), so that ``described`` is of that class.""" - return ProjectedOutput( - self._narrow, - self._keys, - self._make_whole, - node=self._node, - bindings=self._output_bindings, - held_as_rows=True, - ) - - def built(self) -> StreamProtocol: - """The whole output, read on the first call.""" - self._require_current_output() - if self._whole is None: - self._whole = self._make_whole() - return self._whole - - def described(self) -> StreamProtocol: - """The whole output with no row: its class, columns, types and identity. - - Of the class the route that collects the output gives a whole read's output, - built as that is: the stream of the node's zero-row table - (``typed_zero_row_table``) in row order (``_as_upstream_stream`` of the node), or, - held as rows, the node's output holding no row (``RowsOnRead``). Reads nothing. - Each of its members checks the bindings as the whole output's does. - """ - if self._described is None and self._held_as_rows: - self._described = rows_on_read( - [], self._node, bindings=self._output_bindings - ) - if self._described is None: - table = typed_zero_row_table(self._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 = self._keys - self._described = StaticOutputOperatorPod._as_upstream_stream( - StaticOutputOperatorPod._in_row_order(table, tag_keys), - tag_keys, - data_tag_names(tag_keys, data_keys), - self._node, - bindings=self._output_bindings, - ) - return self._described - - 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. ``data_columns`` must be - among those read; any other request is answered from the whole output. - - Returns: - The table, or ``None`` when it would not be the whole output's table - without those columns: the caller then reads the whole output. - """ - self._require_current_output() - config = ColumnConfig.handle_config(columns) - tag_keys, data_keys = self._keys - read = set(self._narrow.keys()[1]) - wanted = set(data_columns) - if config.content_hash or config.meta or not wanted <= read: - # A row hash covers every data column; a request beyond the read. - return None - table = self._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]) - - # -- What describes the stream: ``described``'s answers; nothing is read. -- - - def keys( - self, - *, - columns: ColumnConfig | dict[str, Any] | None = None, - all_info: bool = False, - ) -> tuple[tuple[str, ...], tuple[str, ...]]: - return self.described().keys(columns=columns, all_info=all_info) - - def output_schema( - self, - *, - columns: ColumnConfig | dict[str, Any] | None = None, - all_info: bool = False, - ) -> tuple[Schema, Schema]: - return self.described().output_schema(columns=columns, all_info=all_info) - - def arrow_schema(self) -> pa.Schema: - return self.described().arrow_schema() - - @property - def arrow_types_declared(self) -> bool: - return self.described().arrow_types_declared - - @property - def data_tags(self) -> tuple[str, ...]: - return cast(ArrowTableStream, self.described()).data_tags - - @property - def data_context(self) -> DataContext: - return cast(ArrowTableStream, self.described()).data_context - - @property - def data_context_key(self) -> str: - return self.described().data_context_key - - @property - def orcapod_config(self) -> OrcapodConfig: - return cast(ArrowTableStream, self.described()).orcapod_config - - @property - def label(self) -> Any: - return self.described().label - - @property - def has_assigned_label(self) -> bool: - return cast(ArrowTableStream, self.described()).has_assigned_label - - def computed_label(self) -> str | None: - return cast(ArrowTableStream, self.described()).computed_label() - - @property - def producer(self) -> Any: - return self.described().producer - - @property - def upstreams(self) -> tuple[StreamProtocol, ...]: - return self.described().upstreams - - def explain(self) -> Any: - return cast(ArrowTableStream, self.described()).explain() - - @staticmethod - def content_hash_generation() -> object: - return ArrowTableStream.content_hash_generation() - - def content_hash(self, hasher=None) -> ContentHash: - return self.described().content_hash(hasher) - - def pipeline_hash(self, hasher=None) -> ContentHash: - return self.described().pipeline_hash(hasher) - - def node_hash(self) -> ContentHash: - return cast(ArrowTableStream, self.described()).node_hash() - - def source_chain(self) -> ContentHash: - return self.described().source_chain() - - def name_chain(self) -> ContentHash: - return self.described().name_chain() - - def pipeline_identity_structure(self) -> Any: - return self.described().pipeline_identity_structure() - - def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: - return walk.visit(self.described()) - - def _typed_zero_row_table(self) -> pa.Table | None: - return typed_zero_row_table(self.described()) - - def _schema_requires_io(self, config: ColumnConfig) -> bool: - from orcapod.core.streams.base import schema_requires_io - - return schema_requires_io(self.described(), config) - - def _display_name(self) -> str | None: - return cast(ArrowTableStream, self.described())._display_name() # pyright: ignore[reportPrivateUsage] # the preview header of the whole output - - def __hash__(self) -> int: - return hash(self.described()) - - def __str__(self) -> str: - return str(self.described()) - - def __repr__(self) -> str: - return repr(self.described()) - - # -- When it was made: the narrowed output's, made where the whole one would be. -- - - @property - def last_modified(self) -> datetime | None: - self._require_current_output() - return self._narrow.last_modified - - @property - def is_stale(self) -> bool: - self._require_current_output() - return cast(ArrowTableStream, self._narrow).is_stale - - def updated_since(self, timestamp: datetime) -> bool: - self._require_current_output() - return cast(ArrowTableStream, self._narrow).updated_since(timestamp) - - def clear_cache(self) -> None: - cast(ArrowTableStream, self._narrow).clear_cache() - if self._whole is not None: - cast(ArrowTableStream, self._whole).clear_cache() - - # -- The rows: the whole output's, read on first use. -- - - def as_table( - self, - *, - columns: ColumnConfig | dict[str, Any] | None = None, - all_info: bool = False, - ) -> pa.Table: - return self.built().as_table(columns=columns, all_info=all_info) - - def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - return self.built().iter_data() - - def __iter__(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - return iter(cast(ArrowTableStream, self.built())) - - def flow(self) -> list[tuple[TagProtocol, DataProtocol]]: - return cast(ArrowTableStream, self.built()).flow() - - def run(self) -> StreamView: - return cast(ArrowTableStream, self.built()).run() - - def as_polars_df(self, *args: Any, **kwargs: Any) -> Any: - return cast(ArrowTableStream, self.built()).as_polars_df(*args, **kwargs) - - def as_df(self, *args: Any, **kwargs: Any) -> Any: - return cast(ArrowTableStream, self.built()).as_df(*args, **kwargs) - - def as_lazy_frame(self, *args: Any, **kwargs: Any) -> Any: - return cast(ArrowTableStream, self.built()).as_lazy_frame(*args, **kwargs) - - def as_pandas_df(self, *args: Any, **kwargs: Any) -> Any: - return cast(ArrowTableStream, self.built()).as_pandas_df(*args, **kwargs) - - def identity_structure(self) -> Any: - return self.built().identity_structure() - - def __eq__(self, other: object) -> bool: - """As the whole output's class compares: by identity structure (the rows), or, - for a class that does not define it (``RowsOnRead``), by object.""" - if not isinstance(self.described(), ContentIdentifiableBase): - return True if other is self else NotImplemented - if not isinstance(other, (ContentIdentifiableBase, ProjectedOutput)): - return NotImplemented - return self.identity_structure() == other.identity_structure() - - def head( - self, - n: int = 10, - *, - columns: ColumnConfig | dict[str, Any] | None = None, - all_info: bool = False, - ) -> StreamView: - """The whole output's head; with no row asked for, read from nothing. - - ``head(0)`` is the described output's head, with the whole output's row - count: the narrowed output's, which holds the same rows. - """ - check_head_size(n) - if n == 0: - view = cast( - StreamView, - self.described().head(0, columns=columns, all_info=all_info), - ) - return dataclasses.replace( - view, total_rows=self._narrow.as_table().num_rows - ) - return cast( - StreamView, self.built().head(n, columns=columns, all_info=all_info) - ) +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. - def _repr_html_(self) -> str: - """The whole output's notebook preview; a stale output shows its error.""" - from orcapod.core.streams.view import preview_html + 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). - try: - shown = self.built() - except Exception: # noqa: BLE001 - a display hook must not raise - # The narrowed output, of the whole output's class and label, raises the - # same error in its head, and the preview shows it. - shown = self._narrow - return preview_html(shown) - - # -- A step over the stream: built over this output, reading nothing. -- - - join = StreamBase.join - rejoin = StreamBase.rejoin - semi_join = StreamBase.semi_join - map_tags = StreamBase.map_tags - map_data = StreamBase.map_data - map_columns = StreamBase.map_columns - batch = StreamBase.batch - group_by = StreamBase.group_by - polars_filter = StreamBase.polars_filter - filter = StreamBase.filter - drop_nulls = StreamBase.drop_nulls - tag_by = StreamBase.tag_by - add_tags = StreamBase.add_tags - select_tag_columns = StreamBase.select_tag_columns - select_data_columns = StreamBase.select_data_columns - drop_tag_columns = StreamBase.drop_tag_columns - drop_data_columns = StreamBase.drop_data_columns - drop_columns = StreamBase.drop_columns - select_columns = StreamBase.select_columns - pick = StreamBase.pick - index = StreamBase.index - open_channel = StreamBase.open_channel - - async def async_iter_data( - self, - ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: - for item in self.iter_data(): - yield item + 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 projected_output( - narrow: StreamProtocol, - keys: tuple[tuple[str, ...], tuple[str, ...]], - whole: Callable[[], StreamProtocol], - *, - node: StreamProtocol, - bindings: OutputBindings, +def rows_on_read_of( + node: StreamProtocol, loader: WholeRead, *, bindings: OutputBindings ) -> StreamProtocol: - """``ProjectedOutput`` as a stream (it answers every member as the whole output does). + """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: - narrow: The node's output over the narrowed read. - keys: The whole output's tag and data keys. - whole: Returns the whole output, reading the source whole at the version the - narrowed rows were read at (its snapshot pinned at production). - node: The node whose output this is. + node: The source node. + loader: The node's whole read. bindings: The bindings at production. - - Returns: - The output. """ - return cast( - StreamProtocol, - cast( - object, ProjectedOutput(narrow, keys, whole, node=node, bindings=bindings) - ), - ) + 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: diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 02e92d1cd..2459d0af2 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,85 @@ 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, + keys: tuple[tuple[str, ...], tuple[str, ...]], + ) -> 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. + keys: The tag and data keys of the whole output. + """ + self._read = read + self._narrow = narrow + self._keys = keys + self._whole: ArrowTableStream | None = None + self._lock = threading.Lock() + self.num_rows: int = narrow.as_table().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): the + caller then reads the whole output. + """ + config = ColumnConfig.handle_config(columns) + tag_keys, data_keys = self._keys + wanted = set(data_columns) + if ( + config.content_hash + or config.meta + or not wanted <= set(self._narrow.keys()[1]) + ): + return None + table = self._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 +140,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 +345,17 @@ 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 + 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 +575,8 @@ def head( """ check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) - if config.sort_by_tags: + if config.sort_by_tags and n: + # No row asked for: nothing to sort (a projected output reads no row). table = self._assemble_table(config, limit=None).slice(0, n) else: table = self._assemble_table(config, limit=n) @@ -488,7 +584,11 @@ def head( self, table, tag_columns=self.keys(columns=config)[0], - total_rows=self._table.num_rows, + total_rows=( + self._table.num_rows + if self._row_loader is None + else self._row_loader.num_rows + ), ) def _typed_zero_row_table(self) -> "pa.Table": @@ -505,6 +605,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 +671,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 +721,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/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 4029e4fa4..f0fde7d1e 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -11,6 +11,7 @@ from __future__ import annotations import asyncio +import copy import dataclasses import datetime from collections.abc import Callable @@ -21,7 +22,11 @@ import pytest from orcapod import PipelineJob, function_pod -from orcapod.core.operators.static_output_pod import ProjectedOutput +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 @@ -376,13 +381,15 @@ def test_the_projected_output_describes_the_whole_node(project: Any) -> None: fake.scan_log.clear() fake.count_log.clear() output = node.execute(read_columns=["x"]) - assert isinstance(output, ProjectedOutput) + 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} - narrowed = output.projected_table(["x"], columns=config) + 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, @@ -391,12 +398,14 @@ def test_the_projected_output_describes_the_whole_node(project: Any) -> None: ), ) # A request beyond the read, or a row hash, is answered from the whole read. - assert output.projected_table(["y"], columns=config) is None - assert output.projected_table(["x"], columns={"content_hash": True}) is None + 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: @@ -518,7 +527,8 @@ def _projected(project: Any) -> tuple[Any, Any, SpiralDBTableSource]: node = next(n for n in job.nodes.values() if n.node_type == "source") whole = node.execute() output = node.execute(read_columns=["x"]) - assert isinstance(output, ProjectedOutput) + assert type(output) is type(whole) + assert pending_whole_read(output) is not None return output, whole, source @@ -652,14 +662,16 @@ def test_a_whole_read_after_the_pin_moved_reads_the_pinned_version( """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) - narrowed = output.projected_table(["x"]) + 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 = output.projected_table(["x"]) + again = whole_read.projected_table(["x"]) assert again is not None _same(again, narrowed) @@ -695,21 +707,8 @@ def test_a_source_without_a_snapshot_is_read_whole( # 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). Every public member of the class of main's collected output, and the -# hooks below, must be classified here: a member added to that class later fails -# ``test_every_member_of_the_collected_output_is_classified`` until it is. -_HOOKS = ( - "__eq__", - "__hash__", - "__iter__", - "__repr__", - "__str__", - "_repr_html_", - "_display_name", - "_identity_chains", - "_schema_requires_io", - "_typed_zero_row_table", -) +# 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: @@ -923,31 +922,11 @@ def _collected_output(route: str, *, whole: bool, monkeypatch: Any) -> Any: else AsyncPipelineOrchestrator() ) output = orchestrator.run(dag).node_outputs[node] - assert isinstance(output, ProjectedOutput) is not whole + # 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 -def test_every_member_of_the_collected_output_is_classified( - project: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - """Each public member of main's collected output's class, and each hook, is - classified above and defined on ``ProjectedOutput`` itself, as is every member of - ``StreamProtocol``: nothing is answered by a lookup at run time.""" - main_output = _collected_output("sync", whole=True, monkeypatch=monkeypatch) - public = {n for n in dir(type(main_output)) if not n.startswith("_")} - classified = ( - {n for n in _DESCRIBE if n.isidentifier()} | set(_ROWS) | set(_STEPS) - ) - {"hasattr"} - assert public | set(_HOOKS) == classified - assert all(hasattr(type(main_output), name) for name in _HOOKS) - from orcapod.core.operators.static_output_pod import _stream_protocol_members - - defined = set(vars(ProjectedOutput)) - assert classified - defined == set() - assert set(_stream_protocol_members()) - defined == set() - assert "__getattr__" not in defined - - _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] @@ -996,3 +975,95 @@ def answer(output: Any) -> tuple[tuple[str, Any], list[list[str]]]: 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 = [(t.as_dict(), d.as_dict(), d.content_hash()) for t, d in output] + assert rows == [(t.as_dict(), d.as_dict(), d.content_hash()) 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] From 07579b8d9be03364fb1a98a48710965b3f425123 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 11:36:23 -0800 Subject: [PATCH 10/12] fix(streams): a sorted head(0) of a stream holding its rows takes main's path (ITL-1798) Only a projected output with its whole read pending, asked for no row hash, sorts its zero-row table and reads no row; a stream holding its rows, or a request for a row hash, sorts and hashes every row as main does, so a map value is refused with main's ValueError. Adds a test that every library source class answers every SourceProtocol member. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1798.md | 2 +- docs/concepts/sources.md | 2 +- .../core/streams/arrow_table_stream.py | 11 ++- .../test_source_protocol_conformance.py | 64 ++++++++++++++++++ tests/test_core/streams/test_head_sorting.py | 28 ++++++++ .../test_spiraldb_job_projection.py | 67 ++++++++++++++++++- 6 files changed, 169 insertions(+), 5 deletions(-) diff --git a/changelog.d/ITL-1798.md b/changelog.d/ITL-1798.md index 7fac6a99e..ed700289f 100644 --- a/changelog.d/ITL-1798.md +++ b/changelog.d/ITL-1798.md @@ -14,5 +14,5 @@ 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)`) reads nothing, + 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 41985726c..256f57b40 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -664,7 +664,7 @@ columns the selections left out) reads the source again, whole, the first time, 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)`, and a step built on it reads only when its own rows +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 diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 2459d0af2..5e2ed27e8 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -575,8 +575,15 @@ def head( """ check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) - if config.sort_by_tags and n: - # No row asked for: nothing to sort (a projected output reads no row). + if config.sort_by_tags and ( + n or self._row_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) 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/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 index f0fde7d1e..56dd2154c 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -773,7 +773,8 @@ async def _channel_table(channel: Any) -> pa.Table: ), "_identity_chains": lambda s: (s.content_hash(), s.pipeline_hash()), "head(0)": lambda s: s.head(0), - "head(0, all_info)": lambda s: s.head(0, all_info=True), + # 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") @@ -794,6 +795,9 @@ async def _channel_table(channel: Any) -> pa.Table: "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(), @@ -1067,3 +1071,64 @@ def test_the_async_output_keeps_release_built( 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() From a8aa07001dbdcb71c29a1c759a428e223dcdec9d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 12:33:12 -0800 Subject: [PATCH 11/12] fix(spiraldb): the async projected route streams its batches as main's whole read does (ITL-1798) A source node read with fewer columns on the async route now reads and sends the narrowed rows batch by batch (SourceProtocol.projected_batch_streams), one reader thread, the count first, as SpiralDBTableSource.async_iter_data sends the whole read's: the first row reaches the next step before the scan ends, and one batch is held at a time. It keeps no narrowed table: the collected output's whole read is made from the row count sent. RowsOnRead.iter_data, RowsOnRead.built and ArrowTableStream.head read the pending whole read once, so a concurrent reader that takes the rows between the check and the use leaves them main's answer. Tests: the async route's scan and sends interleave as main's (first row before the scan ends, at most one batch held) and its peak is main's; two threads reading one output; several kept columns in either order, plain tags and data-tags, on both routes; row comparisons include system tags and source-info tokens. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1798.md | 5 +- docs/concepts/sources.md | 4 +- src/orcapod/core/nodes/source_node.py | 189 +++++++++-- .../core/operators/static_output_pod.py | 13 +- src/orcapod/core/sources/base.py | 19 +- .../core/sources/spiraldb_table_source.py | 66 +++- .../core/streams/arrow_table_stream.py | 37 ++- .../protocols/core_protocols/sources.py | 13 +- .../test_spiraldb_job_projection.py | 307 +++++++++++++++++- .../test_source_object_registration.py | 7 +- 10 files changed, 580 insertions(+), 80 deletions(-) diff --git a/changelog.d/ITL-1798.md b/changelog.d/ITL-1798.md index ed700289f..e8f45a12c 100644 --- a/changelog.d/ITL-1798.md +++ b/changelog.d/ITL-1798.md @@ -5,7 +5,10 @@ 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()`. Any other + `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 diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 256f57b40..82926a1d4 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -657,7 +657,9 @@ of the whole read followed by the selection. In a pipeline job, a source node re 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. The job's rows, stored rows, hashes and stored paths are the same either way. +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 diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5172f336f..7c0c1db3c 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -16,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 @@ -1513,6 +1521,22 @@ def _projected_read( """ 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]]", @@ -1530,9 +1554,10 @@ async def async_execute( 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 (off the event loop) and sends the rows of - that read, each without the unread data columns, which every - successor drops. + 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 @@ -1557,17 +1582,19 @@ async def async_execute( if read_columns is not None: bindings = capture_output_bindings(self) projected = await asyncio.to_thread( - self._projected_read, read_columns, bindings + self._projected_batches, read_columns, bindings ) - if projected is not None and projected[1] is not None: - # Collected as this route collects a node's output: its rows, - # read whole when first read. - whole = rows_on_read_of(self, projected[1], bindings=bindings) - if projected is not None: - # The narrowed read's rows (none, with no row at all). - for tag, data in projected[0].iter_data(): - await output.send((tag, data)) - else: + 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: @@ -2217,29 +2244,11 @@ def _projected_read( at_edge, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream, WholeRead - 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 - # 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. - snapshot = source.pinned_snapshot() - if snapshot is None: + 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 @@ -2269,7 +2278,82 @@ def whole() -> ArrowTableStream: assert isinstance(stream, ArrowTableStream) return stream - return narrow, WholeRead(whole, narrow, keys_of_rows(zero_rows, source_keys)) + 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 @@ -2628,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/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index aab7fca49..f41272d4f 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1480,10 +1480,12 @@ def built(self) -> StreamProtocol: self._require_current_output() if self._stream is None: refuse_identity_io("this stream requires materializing rows") - if self._row_loader is not None: + # 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, self._row_loader, bindings=self._output_bindings + self._node, loader, bindings=self._output_bindings ) else: stream = StaticOutputOperatorPod._materialize_upstream( @@ -1506,8 +1508,11 @@ 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() - if self._row_loader is not None: - self._rows = list(self._row_loader().iter_data()) + # 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) diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 9ce76d002..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 @@ -429,6 +429,23 @@ 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``. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 9f75eebab..fe4c37a41 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1227,15 +1227,10 @@ def projected_table( 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), @@ -1248,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 5e2ed27e8..7f3c7dfbc 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -52,23 +52,28 @@ class WholeRead: def __init__( self, read: Callable[[], ArrowTableStream], - narrow: 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. + 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 = narrow.as_table().num_rows + self.num_rows: int = num_rows """The whole output's row count: the narrowed read's, which holds the same rows.""" @property @@ -97,19 +102,21 @@ def projected_table( 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): the - caller then reads the whole output. + 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 ( - config.content_hash + narrow is None + or config.content_hash or config.meta - or not wanted <= set(self._narrow.keys()[1]) + or not wanted <= set(narrow.keys()[1]) ): return None - table = self._narrow.as_table(columns=config) + 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]) @@ -354,6 +361,7 @@ def _load_rows(self) -> None: 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 @@ -575,9 +583,10 @@ def head( """ check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) - if config.sort_by_tags and ( - n or self._row_loader is None or config.content_hash - ): + # 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 @@ -591,11 +600,7 @@ def head( self, table, tag_columns=self.keys(columns=config)[0], - total_rows=( - self._table.num_rows - if self._row_loader is None - else self._row_loader.num_rows - ), + total_rows=self._table.num_rows if loader is None else loader.num_rows, ) def _typed_zero_row_table(self) -> "pa.Table": diff --git a/src/orcapod/protocols/core_protocols/sources.py b/src/orcapod/protocols/core_protocols/sources.py index 5ff061f5f..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,17 @@ 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. diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 56dd2154c..8f1aaa2ad 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -88,6 +88,22 @@ def _read_whole(monkeypatch: pytest.MonkeyPatch) -> None: "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]]: @@ -480,10 +496,7 @@ def collected(*, whole: bool) -> tuple[Any, Any]: scans = _row_scans() outputs = result.node_outputs source_output = outputs[node] - rows = [ - (tag.as_dict(), data.as_dict(), data.content_hash()) - for tag, data in source_output.iter_data() - ] + rows = [_pair(tag, data) for tag, data in source_output.iter_data()] return ( scans, ( @@ -632,10 +645,7 @@ def read() -> tuple[Any, ...]: source_output = outputs[node] return ( source_output.as_table(all_info=True), - [ - (tag.as_dict(), data.as_dict(), data.content_hash()) - for tag, data in source_output.iter_data() - ], + [_pair(tag, data) for tag, data in source_output.iter_data()], outputs[job.nodes["sx"]].as_table(all_info=True), ) @@ -868,7 +878,7 @@ def _norm(value: Any) -> Any: 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 (tag.as_dict(), data.as_dict(), data.content_hash()) + return _pair(tag, data) if isinstance(value, tuple): return tuple(_norm(v) for v in value) return value @@ -1066,8 +1076,8 @@ def test_the_async_output_keeps_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 = [(t.as_dict(), d.as_dict(), d.content_hash()) for t, d in output] - assert rows == [(t.as_dict(), d.as_dict(), d.content_hash()) for t, d in expected] + 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] @@ -1132,3 +1142,278 @@ def test_a_sorted_head_0_with_a_row_hash_takes_mains_path_on_a_projected_output( 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() + + main = peak(projected=False) + got = peak(projected=True) + # Both hold one batch: the peaks differ only by the narrowed batch's own stream + # (about 2% here). A route that kept the narrowed read whole held 14 times + # main's peak on this table, growing with its rows. + assert got <= main * 1.1, (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_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index bf3ca65e8..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,11 @@ 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 From 96975dec3a39122c60c327bc5b4661455d9c842c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 12:54:05 -0800 Subject: [PATCH 12/12] test(spiraldb): measure the async route's peak after a warm-up, lowest of three (ITL-1798) A single traced run under coverage on CI read 709 KB against main's 606 KB: one-time costs and tracer noise. Each route runs once untraced first, the lowest of three traced runs is compared, with a 1.5x margin (the route that kept the narrowed read whole held 14 times main's peak). Co-Authored-By: Claude Opus 5.5 --- .../test_spiraldb_job_projection.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 8f1aaa2ad..197c8597a 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -1280,12 +1280,18 @@ async def close(self) -> None: finally: tracemalloc.stop() - main = peak(projected=False) - got = peak(projected=True) - # Both hold one batch: the peaks differ only by the narrowed batch's own stream - # (about 2% here). A route that kept the narrowed read whole held 14 times - # main's peak on this table, growing with its rows. - assert got <= main * 1.1, (got, main) + # 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