From b6796d15d08c87bf6e821851fd5467e9fc5f5832 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:24:09 -0800 Subject: [PATCH 1/3] perf(core): carry source-info tokens as a recipe until their text is needed (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/operators/add_tags.py | 2 +- .../core/operators/column_selection.py | 10 +- src/orcapod/core/operators/drop_nulls.py | 2 +- src/orcapod/core/operators/filter.py | 2 +- src/orcapod/core/operators/filters.py | 37 ++- src/orcapod/core/operators/mappers.py | 6 +- src/orcapod/core/operators/meta_columns.py | 2 +- .../core/operators/static_output_pod.py | 10 + src/orcapod/core/operators/tag_by.py | 2 +- src/orcapod/core/sources/base.py | 12 + src/orcapod/core/sources/derived_source.py | 6 + .../core/sources/spiraldb_table_source.py | 37 ++- src/orcapod/core/sources/stream_builder.py | 15 +- .../core/streams/arrow_table_stream.py | 59 +++-- src/orcapod/core/streams/base.py | 12 + .../protocols/core_protocols/streams.py | 11 + src/orcapod/utils/arrow_utils.py | 72 +++--- src/orcapod/utils/source_tokens.py | 234 ++++++++++++++++++ .../unit/test_arrow_data_utils.py | 24 -- tests/test_utils/test_arrow_utils.py | 94 +++---- 20 files changed, 472 insertions(+), 177 deletions(-) create mode 100644 src/orcapod/utils/source_tokens.py diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..efedd2592 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -322,7 +322,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_keys, _ = stream.keys() data_context = stream.data_context # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..9cfd73cbd 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -90,7 +90,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All tag columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -229,7 +229,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All data columns are selected. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -388,7 +388,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("No tag columns to drop. Returning stream unaltered.") return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -534,7 +534,7 @@ 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( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -774,7 +774,7 @@ 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( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..028bcfa8c 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -316,7 +316,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: A stream over the surviving rows, in input order, with the named columns non-nullable. A result with no rows has the same schema. """ - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..b8e3621e1 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -243,7 +243,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ # Every system column passes through: source info, system tags and each row's # data context (a raw stream may hold several). - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index ce01c02b5..2a84592f5 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -10,7 +10,7 @@ from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: import numpy as np @@ -71,9 +71,17 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: return stream # TODO: improve efficiency here... - table = stream.as_table( + whole = stream.as_carried_table( columns={"source": True, "system_tags": True, "sort_by_tags": False} ) + # Polars reads no derived token column: one is left out, and put back for the + # rows kept (its recipe reads the system tags kept with them, ITL-1464), unless + # a predicate could read it. + derived = source_tokens.derived_columns(whole.schema) + others = {c for c in whole.column_names if c not in derived} + if derived and not self._reads_only(others): + whole, derived = source_tokens.materialize(whole), () + table = whole.drop_columns(list(derived)) df = pl.DataFrame(table) filtered_table = df.filter(*self.predicates, **self.constraints).to_arrow() # A filter passes every column through, so each one takes the @@ -96,6 +104,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: filtered_table = arrow_utils.restore_schema_nullability( filtered_table, pa.schema(input_fields) ) + for name in derived: + field = whole.schema.field(name) + recipe = source_tokens.derived_recipe(field.type) + assert recipe is not None + filtered_table = filtered_table.append_column( + field, source_tokens.derived_array(recipe, filtered_table.num_rows) + ) + filtered_table = filtered_table.select(whole.column_names) return ArrowTableStream( filtered_table, @@ -103,6 +119,23 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: data_tags=stream_data_tags(stream), ) + def _reads_only(self, columns: Collection[str]) -> bool: + """Whether every predicate certainly reads columns of ``columns`` only. + + Certain only for expressions that name each column they read: a selector + (``pl.all()``, a regular expression, a type) can read any column, and a predicate + that is not an expression is not looked into. A name that is no column is not + certain either: Polars' error then lists the columns there are. + """ + if not set(self.constraints) <= set(columns): + return False + return all( + isinstance(predicate, pl.Expr) + and not predicate.meta.has_multiple_outputs() + and set(predicate.meta.root_names()) <= set(columns) + for predicate in self.predicates + ) + def validate_unary_input(self, stream: StreamProtocol) -> None: """ This method should be implemented by subclasses to validate the inputs to the operator. diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..184f66252 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -179,7 +179,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename in the data, return stream as is return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -457,7 +457,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename or drop in the tags, return stream as is return stream - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, @@ -799,7 +799,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_renames, data_renames, tags_dropped, data_dropped = self._plan( tag_columns, data_columns ) - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index 674d55e46..a2312b830 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -112,7 +112,7 @@ def without_input_meta( """ if not _carries_meta(stream, inputs): return stream - table = stream.as_table( + table = stream.as_carried_table( columns={"source": True, "system_tags": True, "context": True} ) tag_columns = stream.keys()[0] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..c8f45d059 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -2045,6 +2045,16 @@ def as_table( ) return self._cached_stream.as_table(columns=columns, all_info=all_info) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The operator's result, derived token columns as they are (ITL-1464).""" + self._refresh() + assert self._cached_stream is not None, ( + "StreamProtocol has not been updated or is empty." + ) + return self._cached_stream.as_carried_table(columns=columns) + def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 911fefc36..a7cbe5f7a 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -209,7 +209,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_columns, _ = stream.keys() # The context column too, so each row keeps its own data context key. - table = stream.as_table( + table = stream.as_carried_table( columns={ "source": True, "system_tags": True, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..780e1c63a 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -537,6 +537,18 @@ def as_table( """Delegate to the underlying stream's as_table.""" return self._stream.as_table(columns=columns, all_info=all_info) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The underlying stream's table, derived token columns as they are (ITL-1464). + + A source that reads its rows its own way (a subclass, or an object, with its own + ``as_table``) gives that table. + """ + if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): + return self._stream.as_carried_table(columns=columns) + return super().as_carried_table(columns=columns) + # ------------------------------------------------------------------------- # The start-of-run check (ITL-1102) # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..ab1a585b1 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -812,3 +812,9 @@ def as_table( all_info: bool = False, ) -> "pa.Table": return self._get_stream().as_table(columns=columns, all_info=all_info) + + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The source's table, derived token columns as they are (ITL-1464).""" + return self._get_stream().as_carried_table(columns=columns) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..b1dba51bb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -62,7 +62,7 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.core.streams.base import check_head_size +from orcapod.core.streams.base import StreamBase, check_head_size from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, @@ -959,31 +959,32 @@ def as_table( all_info: bool = False, ) -> "pa.Table": """Scan the table and return its rows as one PyArrow table (all held in memory).""" - return self._whole_table( - self._batch_streams(), columns=columns, all_info=all_info + return self._whole_stream(self._batch_streams()).as_table( + columns=columns, all_info=all_info ) - def _whole_table( - self, - streams: Iterator["ArrowTableStream"], - *, - columns: ColumnConfig | dict[str, Any] | None, - all_info: bool, + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None ) -> "pa.Table": - """Return the rows of ``streams`` (batches of one read) as one table.""" + """Scan the table as ``as_table`` does, building no source-info text (ITL-1464).""" + return self._whole_stream(self._batch_streams()).as_carried_table( + columns=columns + ) + + def _whole_stream(self, streams: Iterator["ArrowTableStream"]) -> StreamBase: + """Return the rows of ``streams`` (batches of one read) as one stream.""" # One stream over all the rows, so that a whole-table option (sorting by # tags) applies across batches. enriched = {"source": True, "system_tags": True} - tables = [stream.as_table(columns=enriched) for stream in streams] + tables = [stream.as_carried_table(columns=enriched) for stream in streams] if not tables: - return self._stream.as_table(columns=columns, all_info=all_info) - whole = ArrowTableStream( + return self._stream + return ArrowTableStream( table=pa.concat_tables(tables), tag_columns=self._tag_columns, system_tag_columns=self._system_tag_columns, data_tags=self._data_tags, ) - return whole.as_table(columns=columns, all_info=all_info) def _head( self, @@ -1013,11 +1014,9 @@ def _head( head_limit = n if limit is None else min(n, limit) asof = self._asof table = self._lookup_table() - rows = self._whole_table( - self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), - columns=columns, - all_info=all_info, - ) + rows = self._whole_stream( + self._read_batches(table, asof=asof, limit=head_limit, max_rows=None) + ).as_table(columns=columns, all_info=all_info) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) bound, total = self._bounded_count(n, table) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..67eeb2114 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -25,7 +25,6 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.schema_utils import compute_source_schema_hash @@ -597,7 +596,8 @@ def attach_provenance( key's canonical JSON), and its source id is the source's name: the two system-tag columns. Each source-info value is ``::::`` (for example ``_source_amplitude`` - holds ``::row_3::amplitude``). A row keeps its record id wherever + holds ``::row_3::amplitude``), carried as a recipe over the two system + tags until its text is needed (``source_tokens``). A row keeps its record id wherever and however often it is read, as long as its identifier is the same (ITL-1154). @@ -615,13 +615,12 @@ def attach_provenance( Returns: The stream over the enriched table. """ - source_info = [ - f"{source_id}{constants.BLOCK_SEPARATOR}{identifier}" - for identifier in row_identifiers - ] - table = arrow_utils.add_source_info( + # The tokens say nothing the two system tags below and the column names do not: + # each is carried as that recipe, and its text is built when it is needed + # (``source_tokens``, ITL-1464). + table = arrow_utils.add_source_tokens( table, - source_info, + schema_hash, exclude_columns=[c for c in tag_columns if c not in data_tags], ) table = arrow_utils.add_system_tag_columns( diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..09f1b1d4e 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -20,10 +20,13 @@ from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue -from orcapod.utils import arrow_utils, schema_utils +from orcapod.utils import arrow_utils, schema_utils, source_tokens logger = logging.getLogger(__name__) +ROWS_PER_PART = 8192 +"""The rows whose source-info text ``iter_data`` builds at once (ITL-1464).""" + class ArrowTableStream(StreamBase): """ @@ -351,6 +354,13 @@ def as_table( columns_config = ColumnConfig.handle_config(columns, all_info=all_info) return self._assemble_table(columns_config, limit=None) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table with its derived token columns as they are (ITL-1464).""" + config = ColumnConfig.handle_config(columns) + return self._assemble_table(config, limit=None, carried=config.system_tags) + def head( self, n: int = 10, @@ -384,13 +394,19 @@ def _typed_zero_row_table(self) -> "pa.Table": return self._assemble_table(ZERO_ROW_INPUT_COLUMNS, limit=0) def _assemble_table( - self, columns_config: ColumnConfig, limit: int | None + self, + columns_config: ColumnConfig, + limit: int | None, + *, + carried: bool = False, ) -> "pa.Table": """Return the stream's rows with the column groups of ``columns_config``. Args: columns_config: The column groups to include, and whether to sort by tags. limit: Assemble only the first ``limit`` rows; ``None`` for all of them. + carried: Leave a derived token column derived (``as_carried_table``), which + needs the system tags in the table; ``False`` gives its text. """ output_table = self._table data_context_table = self._data_context_table @@ -408,8 +424,8 @@ def hashes() -> pa.Array[Any]: [str(data.content_hash()) for _, data in rows], type=pa.large_string() ) - def shape(carried: "pa.Table") -> "pa.Table": - table_stack = (carried,) + def shape(rows: "pa.Table") -> "pa.Table": + table_stack = (rows,) if columns_config.context: table_stack += (data_context_table,) if columns_config.source: @@ -423,6 +439,8 @@ def shape(carried: "pa.Table") -> "pa.Table": # the system tags are asked for. The system tags stay in the table # through the sort: they break ties between equal tags. table = arrow_utils.sort_by_tag_columns(table, tuple(self._tag_columns)) + if not carried: + table = source_tokens.materialize(table) if not columns_config.system_tags: table = table.drop_columns(list(self._system_tag_columns)) return table @@ -471,21 +489,30 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, Data]]: self._source_info_table.schema.field(name), self._source_info_table.column(name), ) - # The table is prepared once for all of its rows (ITL-1348): building - # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every row - # three times and split its columns again. - tags = ( - Tag.rows_of(rows.select(tag_columns), self.data_context) - if tag_columns - else None + # Derived tokens become text a part of the rows at a time (ITL-1464); a + # table with none is one part. + size = ( + ROWS_PER_PART + if source_tokens.derived_columns(rows.schema) + else max(rows.num_rows, 1) ) - for data in Data.rows_of(rows.select(data_columns), self.data_context): - # A fresh empty tag per row, so rows never share one object. - tag = next(tags) if tags is not None else Tag({}) + for start in range(0, rows.num_rows, size): + part = source_tokens.materialize(rows.slice(start, size)) + # The part is prepared once for all of its rows (ITL-1348): building + # ``Tag(row)`` and ``Data(row)`` from one-row slices normalized every + # row three times and split its columns again. + tags = ( + Tag.rows_of(part.select(tag_columns), self.data_context) + if tag_columns + else None + ) + for data in Data.rows_of(part.select(data_columns), self.data_context): + # A fresh empty tag per row, so rows never share one object. + tag = next(tags) if tags is not None else Tag({}) - yield tag, data + yield tag, data - cached_elements.append((tag, data)) + cached_elements.append((tag, data)) self._cached_elements = cached_elements else: yield from self._cached_elements diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..26fa6713d 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1509,6 +1509,18 @@ def as_table( all_info: bool = False, ) -> "pa.Table": ... + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``, as operators pass it on. + + A source-info column may be derived (``utils/source_tokens.py``): a recipe over + the table's system tags in place of its text, which ``source_tokens.materialize`` + builds. Internal: never stored, hashed or shown (ITL-1464). A stream that holds + none gives ``as_table``. + """ + return self.as_table(columns=columns) + def as_polars_df( self, *, diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..b35e38beb 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -255,6 +255,17 @@ def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ ... + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``, as operators pass it on. + + A source-info column may be derived (``utils/source_tokens.py``): a recipe over + the table's system tags in place of its text. Internal: never stored, hashed or + shown (ITL-1464). + """ + ... + def as_table( self, *, diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 86ac58283..e51519cbd 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -10,6 +10,7 @@ from orcapod.system_constants import constants from orcapod.types import ColumnConfig, SourceInfoValue +from orcapod.utils import source_tokens if TYPE_CHECKING: from orcapod.logical_types.identifier import LogicalTypeIdentifier @@ -1464,7 +1465,10 @@ def append_to_system_tags(table: "pa.Table", value: str) -> "pa.Table": else c for c in table.column_names } - return table.rename_columns(column_name_map) + # A derived token column keeps reading the columns it read (ITL-1464). + return source_tokens.rename_read_columns( + table.rename_columns(column_name_map), column_name_map + ) def fold_system_tag_values(values: Sequence[Any], *, label: str) -> str: @@ -1712,6 +1716,12 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": if len(positions) <= 1: continue + # The values move between these columns, so a token derived from them is built + # first: it names the row it always named (ITL-1464). + table = source_tokens.materialize_reading( + table, {name for pair in positions.values() for name in pair.values()} + ) + # Sort positions numerically sorted_positions = sorted(positions.keys(), key=int) @@ -1777,50 +1787,38 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": return table -def add_source_info( +def add_source_tokens( table: "pa.Table", - source_info: str | Collection[str] | None, - exclude_prefixes: Collection[str] = ( - constants.META_PREFIX, - constants.DATAGRAM_PREFIX, - ), + schema_hash: str, exclude_columns: Collection[str] = (), ) -> "pa.Table": - """Add source information to an Arrow table.""" - # Create a base list of per-row source tokens; one entry per row. - if source_info is None or isinstance(source_info, str): - base_source = [source_info] * table.num_rows - elif isinstance(source_info, Collection): - if len(source_info) != table.num_rows: - raise ValueError( - "Length of source_info collection must match number of rows in the table." - ) - base_source = list(source_info) - else: - raise TypeError( - f"source_info must be a str, a sized Collection[str], or None; " - f"got {type(source_info).__name__}" - ) + """Add the source-info token column of each data column, as a recipe (ITL-1464). + + Each ``_source_`` column holds no bytes: its type says the token is the row's + source id, its record id and ``col`` (``source_tokens.TokenRecipe``), read from the + two system-tag columns ``add_system_tag_columns`` adds under ``schema_hash``. + + Args: + table: The rows. + schema_hash: The source's schema hash, which names the system-tag columns. + exclude_columns: Columns with no token (the plain tags). Meta and datagram + columns have none either. - # For each data column, build an independent _source_ column from the - # base tokens. We must NOT re-use the array produced for a previous column - # as input for the next one — doing so would accumulate column names - # (e.g. "src::col1::col2" instead of "src::col2"). - for col in table.column_names: - if col.startswith(tuple(exclude_prefixes)) or col in exclude_columns: + Returns: + The table with its token columns, non-nullable: a token is never null. + """ + source_id, record_id = system_tag_column_names(schema_hash) + prefixes = (constants.META_PREFIX, constants.DATAGRAM_PREFIX) + for name in table.column_names: + if name.startswith(prefixes) or name in exclude_columns: continue - col_source = pa.array( - [f"{source_val}::{col}" for source_val in base_source], - type=pa.large_string(), + tokens = source_tokens.derived_array( + source_tokens.TokenRecipe(source_id, record_id, name), table.num_rows ) - # Source info columns are always computed strings, never null. table = table.append_column( - pa.field( - f"{constants.SOURCE_PREFIX}{col}", pa.large_string(), nullable=False - ), - col_source, + pa.field(f"{constants.SOURCE_PREFIX}{name}", tokens.type, nullable=False), + tokens, ) - return table diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py new file mode 100644 index 000000000..9602c5b9f --- /dev/null +++ b/src/orcapod/utils/source_tokens.py @@ -0,0 +1,234 @@ +"""Source-info tokens that are carried as a recipe, not as text (ITL-1464). + +A source row's token is ``::::``: the values of the row's +two system tags and the name the column had at the source. As text it repeats them for +every row and data column, about 35 times the data of a typical table. Inside the library +a token column can instead be **derived**: a column of ``DerivedTokenType`` holds no +bytes, and its type holds the recipe that gives the text from the table's own system-tag +columns. Filtering, taking, slicing, concatenating, selecting and renaming carry such a +column as any other; nothing is computed until the text is needed (``materialize``). + +A derived column is an internal form of a table that operators pass on +(``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, +stored tables and everything hashed hold the text. A place that forgets fails loudly: no +value of a derived column can be read, cast to text, hashed, or written to Parquet (its +storage is a struct with no field, which Parquet refuses). +""" + +from __future__ import annotations + +import json +from collections.abc import Collection, Mapping +from dataclasses import dataclass +from typing import Any, NoReturn + +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.system_constants import constants + +_TEXT = pa.large_string() + +ROWS_PER_CHUNK = 65_536 +"""The most rows whose token text is built in one step.""" + + +@dataclass(frozen=True) +class TokenRecipe: + """How the token of each row is made from the row's system tags. + + Attributes: + source_id: The system-tag column holding the row's source id. + record_id: The system-tag column holding the row's record id. + column: The column name the token ends with: the column's name at the source, + whatever it is called now. + """ + + source_id: str + record_id: str + column: str + + def to_json(self) -> str: + """The recipe as text: what two equal recipes share.""" + return json.dumps([self.source_id, self.record_id, self.column]) + + @classmethod + def from_json(cls, text: str) -> TokenRecipe: + """The recipe ``to_json`` wrote.""" + return cls(*json.loads(text)) + + def renamed(self, names: Mapping[str, str]) -> TokenRecipe: + """The recipe over system-tag columns renamed by ``names``.""" + return TokenRecipe( + names.get(self.source_id, self.source_id), + names.get(self.record_id, self.record_id), + self.column, + ) + + def reads(self, columns: Collection[str]) -> bool: + """Whether the recipe reads one of ``columns``.""" + return self.source_id in columns or self.record_id in columns + + def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """The tokens of ``batch``'s rows, as ``large_string``.""" + return pc.binary_join_element_wise( + batch.column(self.source_id).cast(_TEXT), + batch.column(self.record_id).cast(_TEXT), + pa.scalar(self.column, _TEXT), + pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), + ) + + +class _DerivedTokenScalar(pa.ExtensionScalar): + """A value of a derived column: it has none to read.""" + + def as_py(self, *args: Any, **kwargs: Any) -> NoReturn: # pyright: ignore[reportExplicitAny, reportIncompatibleMethodOverride] # pyarrow's own signature varies by version + """Refuse to give a value. + + Raises: + TypeError: Always; the text must be built first (``materialize``). + """ + raise TypeError( + "a derived source-info token has no value: build its text first " + "(source_tokens.materialize)" + ) + + +class DerivedTokenType(pa.ExtensionType): + """The Arrow type of a derived token column: no bytes, and the recipe. + + Internal and never registered, so it is in no stored table and no schema Orcapod + presents or hashes. Two derived columns have one type only with one recipe. + """ + + def __init__(self, recipe: TokenRecipe) -> None: + self.recipe = recipe + super().__init__(pa.struct([]), "orcapod.internal.derived_token") + + def __arrow_ext_serialize__(self) -> bytes: + return self.recipe.to_json().encode() + + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> DerivedTokenType: + return cls(TokenRecipe.from_json(serialized.decode())) + + def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: + return _DerivedTokenScalar + + # pyarrow compares extension types by name and storage only; Arrow asks this. + def __eq__(self, other: object) -> bool: + return isinstance(other, DerivedTokenType) and self.recipe == other.recipe + + def __hash__(self) -> int: + return hash(self.recipe) + + +def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array + """A derived token column of ``rows`` rows: no row has a byte.""" + storage = pa.Array.from_buffers(pa.struct([]), rows, [None], 0, 0) + return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) + + +def derived_recipe(kind: pa.DataType) -> TokenRecipe | None: + """The recipe of a column of type ``kind``; ``None`` when it is not derived.""" + return kind.recipe if isinstance(kind, DerivedTokenType) else None + + +def derived_columns(schema: pa.Schema) -> tuple[str, ...]: + """The names of the derived token columns of ``schema``.""" + return tuple(f.name for f in schema if derived_recipe(f.type) is not None) + + +def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Table: + """Return ``table`` with its derived token columns as text. + + Args: + table: A table holding the system-tag columns its derived columns read. + names: The derived columns to build; ``None`` for all of them. + + Returns: + The table, each such column ``large_string`` with the field's own name and + nullability; ``table`` itself when there is none. + """ + wanted = [ + name for name in derived_columns(table.schema) if names is None or name in names + ] + if not wanted: + return table + schema = table.schema + recipes: dict[str, TokenRecipe] = {} + for name in wanted: + recipe = derived_recipe(schema.field(name).type) + assert recipe is not None + recipes[name] = recipe + read = {c for r in recipes.values() for c in (r.source_id, r.record_id)} + tags = table.select([c for c in table.column_names if c in read]) + chunks: dict[str, list[pa.Array[Any]]] = {name: [] for name in wanted} # pyright: ignore[reportExplicitAny] # Arrow arrays + for batch in tags.to_batches(max_chunksize=ROWS_PER_CHUNK): + for name, recipe in recipes.items(): + chunks[name].append(recipe.text(batch)) + for name in wanted: + index = schema.get_field_index(name) + table = table.set_column( + index, + schema.field(name).with_type(_TEXT), + pa.chunked_array(chunks[name], type=_TEXT), + ) + return table + + +def materialize_reading(table: pa.Table, columns: Collection[str]) -> pa.Table: + """Build the text of the derived columns that read one of ``columns``. + + Called before the values of system-tag columns change, so every token keeps naming + the row it named. + """ + return materialize( + table, + [ + name + for name in derived_columns(table.schema) + if (recipe := derived_recipe(table.schema.field(name).type)) is not None + and recipe.reads(columns) + ], + ) + + +def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: + """Point the derived columns of ``table`` at system-tag columns renamed by ``names``. + + Args: + table: The table, its system-tag columns already renamed. + names: Old to new column name. + + Returns: + The table with each derived column's recipe reading the new names. + """ + for name in derived_columns(table.schema): + field = table.schema.field(name) + recipe = derived_recipe(field.type) + assert recipe is not None + renamed = recipe.renamed(names) + if renamed == recipe: + continue + table = table.set_column( + table.schema.get_field_index(name), + field.with_type(DerivedTokenType(renamed)), + derived_array(renamed, table.num_rows), + ) + return table + + +def text_schema(schema: pa.Schema) -> pa.Schema: + """``schema`` with each derived token column as the text it stands for.""" + if not derived_columns(schema): + return schema + return pa.schema( + [ + field.with_type(_TEXT) if derived_recipe(field.type) else field + for field in schema + ], + metadata=schema.metadata, + ) diff --git a/test-specification/unit/test_arrow_data_utils.py b/test-specification/unit/test_arrow_data_utils.py index dfc17c7a2..100adcabe 100644 --- a/test-specification/unit/test_arrow_data_utils.py +++ b/test-specification/unit/test_arrow_data_utils.py @@ -13,7 +13,6 @@ from orcapod.system_constants import constants from orcapod.utils.arrow_utils import ( - add_source_info, add_system_tag_columns, append_to_system_tags, drop_columns_with_prefix, @@ -144,29 +143,6 @@ def test_sorts_system_tag_values(self): assert result.num_rows == table_with_tags.num_rows -# --------------------------------------------------------------------------- -# add_source_info -# --------------------------------------------------------------------------- - - -class TestAddSourceInfo: - """Per design, source info columns are prefixed with _source_ and track - provenance tokens per data column.""" - - def test_adds_source_info_columns(self): - table = pa.table({"id": [1, 2], "value": [10, 20]}) - result = add_source_info(table, source_info="src_token") - source_cols = [ - c for c in result.column_names if c.startswith(constants.SOURCE_PREFIX) - ] - assert len(source_cols) > 0 - - def test_source_info_length_mismatch_raises(self): - table = pa.table({"id": [1, 2], "value": [10, 20]}) - with pytest.raises(ValueError): - add_source_info(table, source_info=["a", "b", "c"]) # Wrong count - - # --------------------------------------------------------------------------- # drop_columns_with_prefix # --------------------------------------------------------------------------- diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 26bbddda1..234b86c34 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -4,8 +4,10 @@ import pytest from orcapod.types import ColumnConfig, SourceInfoValue +from orcapod.utils import source_tokens from orcapod.utils.arrow_utils import ( - add_source_info, + add_source_tokens, + add_system_tag_columns, apply_column_config, column_arrow_type, concat_tables_by_name, @@ -243,65 +245,41 @@ def test_none_schema_metadata_stays_none(self): assert not result.metadata -# --------------------------------------------------------------------------- -# add_source_info -# --------------------------------------------------------------------------- - - -class TestAddSourceInfo: - """add_source_info must produce one _source_ column per data column - whose values are exactly '::' for every row.""" - - def test_single_column_produces_correct_source_token(self): - """_source_ value is '::' for every row.""" - table = pa.table({"x": pa.array([10, 20], type=pa.int64())}) - result = add_source_info(table, "mysrc") - - assert result.column("_source_x").to_pylist() == ["mysrc::x", "mysrc::x"] - - def test_multi_column_each_source_column_uses_its_own_name(self): - """Each _source_ value is '::' — columns are independent.""" - table = pa.table( - { - "x": pa.array([1, 2], type=pa.int64()), - "y": pa.array([3, 4], type=pa.int64()), - "z": pa.array([5, 6], type=pa.int64()), - } - ) - result = add_source_info(table, "base") +class TestAddSourceTokens: + """One ``_source_`` column per data column, whose text is + ``::::`` of the row's own system tags.""" - assert result.column("_source_x").to_pylist() == ["base::x", "base::x"] - assert result.column("_source_y").to_pylist() == ["base::y", "base::y"] - assert result.column("_source_z").to_pylist() == ["base::z", "base::z"] - - def test_per_row_source_tokens_combined_with_column_name(self): - """With a per-row source list, each row's token is '::'.""" - table = pa.table( - { - "a": pa.array([10, 20], type=pa.int64()), - "b": pa.array([30, 40], type=pa.int64()), - } + def test_each_column_gets_its_own_token_of_every_row(self): + table = pa.table({"k": [1, 2], "y": ["p", "q"], "x": [3.0, 4.0]}) + carried = add_system_tag_columns( + add_source_tokens(table, "hash", exclude_columns=["k"]), + "hash", + "src", + ["row_0", "row_1"], ) - result = add_source_info(table, ["src0", "src1"]) - - assert result.column("_source_a").to_pylist() == ["src0::a", "src1::a"] - assert result.column("_source_b").to_pylist() == ["src0::b", "src1::b"] - - def test_correct_number_of_source_columns_added(self): - """Exactly one _source_ column is added per non-excluded data column.""" - table = pa.table( - { - "p": pa.array([1], type=pa.int64()), - "q": pa.array([2], type=pa.int64()), - "r": pa.array([3], type=pa.int64()), - } - ) - result = add_source_info(table, "s") - - assert result.num_columns == 6 # 3 data + 3 source - assert "_source_p" in result.column_names - assert "_source_q" in result.column_names - assert "_source_r" in result.column_names + result = source_tokens.materialize(carried) + assert [c for c in result.column_names if c.startswith("_source_")] == [ + "_source_y", + "_source_x", + ] + assert result.column("_source_y").to_pylist() == [ + "src::row_0::y", + "src::row_1::y", + ] + assert result.column("_source_x").to_pylist() == [ + "src::row_0::x", + "src::row_1::x", + ] + field = result.schema.field("_source_x") + assert (field.type, field.nullable) == (pa.large_string(), False) + + def test_meta_columns_get_none(self): + table = pa.table({"x": [1], "__m": [2]}) + assert add_source_tokens(table, "hash").column_names == [ + "x", + "__m", + "_source_x", + ] class TestSystemTagColumnNames: From b03a944e7b5edcaae39df36c9f2cbb0b614ce93b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 01:37:57 -0800 Subject: [PATCH 2/3] perf(core): recipes through F, predicates and spills; design and tests (ITL-1464) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1464.md | 7 + docs/dev/specs/itl-1464-tokens.md | 111 +++++ src/orcapod/core/nodes/source_node.py | 6 + src/orcapod/core/operators/filters.py | 5 +- .../core/operators/static_output_pod.py | 4 + src/orcapod/core/sources/base.py | 3 +- src/orcapod/core/streams/base.py | 9 +- src/orcapod/utils/source_tokens.py | 44 +- tests/test_core/streams/test_source_tokens.py | 449 ++++++++++++++++++ 9 files changed, 612 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1464.md create mode 100644 docs/dev/specs/itl-1464-tokens.md create mode 100644 tests/test_core/streams/test_source_tokens.py diff --git a/changelog.d/ITL-1464.md b/changelog.d/ITL-1464.md new file mode 100644 index 000000000..c9b7b4402 --- /dev/null +++ b/changelog.d/ITL-1464.md @@ -0,0 +1,7 @@ +### Changed + +- Reading a source and applying an operator that selects, renames, filters or tags rows + no longer builds the source-info text of every row and column. The text is built when + it is shown, stored or handed to a function, a part of the rows at a time, so these + steps take a few times the memory of their data instead of tens of times (ITL-1464). + Values, hashes and stored tables are unchanged. diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md new file mode 100644 index 000000000..7473d3954 --- /dev/null +++ b/docs/dev/specs/itl-1464-tokens.md @@ -0,0 +1,111 @@ +# Source-info tokens carried as a recipe (ITL-1464, track TOKENS) + +Status: direction approved November 25, 2026. Step 1 (sources and row-wise operators) +implemented with this document; step 2 (joins) is a separate pull request. + +## The cost + +A source row's token is `::::`, one per row and data +column: about 300 bytes each on the measured synthetic tables, 35 times the data +(`itl-1464-memory-diagnosis.md`). Everything in it is in the row's two system tags and +the column's name at the source. + +## The representation + +A `_source_x` column is **derived** while no one needs its text: a column of +`DerivedTokenType` (`src/orcapod/utils/source_tokens.py`), an internal Arrow extension +type. Its storage is a struct with no field, so a row has no byte, whatever the number of +rows. Its parameter is a recipe, `TokenRecipe(source_id, record_id, column)`: two +system-tag column names of the same table, and the column's name at the source. + +- `filter`, `take`, `slice`, `concat_tables`, `select` and `rename_columns` carry the + column with no special code, since it is one column like any other. The rows of the + table and their system tags move together, so the recipe stays right. +- Two columns have one Arrow type only with one recipe (`__eq__`), so Arrow itself refuses + to concatenate two that would read different columns. +- The system-tag names of a join change (`append_to_system_tags`): the recipes follow + there (`rename_read_columns`). The values of the system tags move between columns only + in `sort_system_tag_values` (inputs of one pipeline hash): the tokens that read them + become text first (`materialize_reading`). +- Text is made in one function, `materialize`, at most 65,536 rows at a time. + +A derived column is loud where it does not belong: reading a value, casting to text, +hashing, pickling and writing Parquet (so Delta) each raise. + +## Where a derived table can go + +`StreamProtocol.as_carried_table(columns=)` is the internal read: the table of `as_table` +with derived columns left as they are. Only library operators call it. The default is +`as_table` (text), so a user's operator, source or stream, and every job node today, is +given and gives text. `ArrowTableStream`, `DynamicPodStream`, and the sources over a held +or scanned table answer it without text. `as_table` with any columns, `iter_data`, `head`, +`run`, the data frame methods and the identity table give text, as before. A read without +the system tags gives text (the recipe would have nothing to read). + +## Producers of `_source_` columns + +| Producer | Form | +|---|---| +| `SourceStreamBuilder.attach_provenance` (every source's rows) | derived | +| `ArrowTableStream(source_info=...)` and a raw table's own `_source_` columns | as given (text) | +| `prepare_prefixed_columns` for a data column with no token | null text | +| `CachedSource`, `DerivedSource` over stored records | text, read from storage | +| `DerivedSource(tags_as_data=)` | derived (a new root, through the builder) | +| `PollingSource` | derived per batch; its combined stream is text (its batches are combined through `as_table`) | +| A function pod's outputs (`data_function.py`) | text: an output's token names the computation, not a source row | +| `Pick` (`with_source_info`) | text: the token is extended | +| `Index` | per row, text (the element's token) | +| `Batch`, `GroupBy` | text lists, one element per member | +| `Join`, `MergeJoin` merged or colliding columns | text | + +## Consumers + +| Consumer | What it needs | Step 1 | +|---|---|---| +| Column selections, `MapData`, `MapTags`, `MapColumns`, `TagBy`, `AddTags`, `DropNulls`, `Filter` | none of the values | derived in, derived out | +| `PolarsFilter` | none, unless a predicate reads a token | the columns stay out of the Polars frame and are put back for the kept rows; a predicate that could read one (a selector, a regular expression, a non-expression, a name that is no column) gets text, as before | +| `without_input_meta` | names only | derived | +| `SemiJoin` (left input) | none | step 2 | +| `Join`, `Rejoin`, `MergeJoin`: columns of one input | none | step 2 | +| `Join`: a shared data-tag | both tokens, folded (`join_v1`) | step 2: a fold recipe; until then text | +| `MergeJoin`: a colliding column | both tokens, in a list | text of that column | +| `GroupBy`, `Batch` | the members' tokens, in a list | text (below) | +| `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time | +| `F` (`_row_built_form`, `row_built_provenance`) | types and null flags | passes a derived column through (a token is one string and never null) | +| Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `as_carried_table` | +| Function node pipeline table, result table, operator and source caches | stored text | unchanged: they read rows or `as_table` | +| Record-batch channels, streaming joins | types, values | unchanged (text) | +| Provenance trace (`pipeline/provenance.py`) | text | unchanged | +| Identity of a raw stream (`_identity_table`), record hashes | text | unchanged | + +## After each operator + +| Operator | Derivable after it? | +|---|---| +| filter, drop nulls, select, drop, rename, add tags, tag by | yes, all columns | +| semi join | yes, all left columns | +| join, rejoin | yes: each input's columns through its renamed system tags; a shared data-tag through a fold of two recipes. Not for inputs of one pipeline hash in `Join`, whose system-tag values are sorted per row | +| merge join | yes for columns only one input has; a colliding column is a list of two tokens | +| group by, batch | no: the system tags are folded to one digest, the members' ids are gone. The lists must be text (or carry the members' ids, a later step) | +| function pod | an output: no. Inputs' tokens are not in its output | + +## Aggregations + +`GroupBy` and `Batch` keep one token per member and column, so their output needs the +members' record ids: text lists are about 300 bytes per member and column. A derived list +(the members' record ids once, in one hidden list column, and recipes over it) is possible +but adds a column operators would have to carry; it is not done here. + +## Measured + +A synthetic time series table, about 2.2 million rows, 13 columns, about 250 MiB of Arrow data, read through +`SpiralDBTableSource` (`measure.py` of the diagnosis, one process per step). + +| Step | Peak RSS before | after | Arrow pool peak before | after | +|---|---|---|---|---| +| `as_table()`, `run()` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | +| `map_data` | 10.8 GiB | 2.0 GiB | 9.3 GiB | 0.75 GiB | +| `drop_nulls` | 19.7 GiB | 2.4 GiB | 18.6 GiB | 1.7 GiB | +| `polars_filter` | 16.6 GiB | 2.5 GiB | 9.3 GiB | 0.75 GiB | +| `join` (8 and 14 columns) | above 24 GiB | above 24 GiB (step 2) | | | +| `group_by` | 20.9 GiB | 20.7 GiB (its lists are text) | 15.9 GiB | 15.9 GiB | diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..2fc8678fd 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1271,6 +1271,12 @@ def run(self) -> StreamView: display_all_rows=False, ) + def as_carried_table( + self, *, columns: ColumnConfig | dict[str, Any] | None = None + ) -> "pa.Table": + """The table of ``as_table(columns=columns)``; see ``StreamProtocol`` (ITL-1464).""" + return self.as_table(columns=columns) + def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 2a84592f5..491fa79b9 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -133,7 +133,10 @@ def _reads_only(self, columns: Collection[str]) -> bool: isinstance(predicate, pl.Expr) and not predicate.meta.has_multiple_outputs() and set(predicate.meta.root_names()) <= set(columns) - for predicate in self.predicates + for predicate in ( + *self.predicates, + *(v for v in self.constraints.values() if isinstance(v, pl.Expr)), + ) ) def validate_unary_input(self, stream: StreamProtocol) -> None: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index c8f45d059..845a7d6a7 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -40,6 +40,7 @@ provisional_operator_name, warn_provisional_operator, ) +from orcapod.utils import source_tokens from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( @@ -579,6 +580,9 @@ def _type_source_info_by_values(table: pa.Table) -> pa.Table: continue if pa.types.is_large_string(field.type): continue + if source_tokens.derived_recipe(field.type) is not None: + # Every token of a derived column is one string. + continue values = table.column(index).to_pylist() kinds = {arrow_utils.source_info_arrow_type(value) for value in values} if len(kinds) != 1: diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 780e1c63a..100d67285 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -546,7 +546,8 @@ def as_carried_table( ``as_table``) gives that table. """ if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): - return self._stream.as_carried_table(columns=columns) + stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass + return stream.as_carried_table(columns=columns) return super().as_carried_table(columns=columns) # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 26fa6713d..833a17347 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -42,7 +42,7 @@ from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Condition, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens if TYPE_CHECKING: from orcapod.types.explanation import Explanation @@ -340,7 +340,12 @@ def row_built_provenance(table: pa.Table) -> pa.Table: changed = False for field, column in zip(table.schema, table.columns, strict=True): if field.name.startswith(constants.SOURCE_PREFIX): - kind = _source_info_value_type(field.type) + # A derived token column stays derived: its text is what the rows give. + kind = ( + field.type + if source_tokens.derived_recipe(field.type) is not None + else _source_info_value_type(field.type) + ) if kind != field.type: column = column.cast(kind) new_field = pa.field(field.name, kind, nullable=field.nullable) diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 9602c5b9f..0fd59bcfc 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -11,8 +11,8 @@ A derived column is an internal form of a table that operators pass on (``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, stored tables and everything hashed hold the text. A place that forgets fails loudly: no -value of a derived column can be read, cast to text, hashed, or written to Parquet (its -storage is a struct with no field, which Parquet refuses). +value of a derived column can be read, cast to text, hashed, pickled, or written to +Parquet (its storage is a struct with no field, which Parquet refuses). """ from __future__ import annotations @@ -20,7 +20,7 @@ import json from collections.abc import Collection, Mapping from dataclasses import dataclass -from typing import Any, NoReturn +from typing import Any, NoReturn, cast import pyarrow as pa import pyarrow.compute as pc @@ -71,11 +71,11 @@ def reads(self, columns: Collection[str]) -> bool: def text(self, batch: pa.RecordBatch) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """The tokens of ``batch``'s rows, as ``large_string``.""" - return pc.binary_join_element_wise( + return pc.binary_join_element_wise( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the stubs leave out scalar arguments batch.column(self.source_id).cast(_TEXT), batch.column(self.record_id).cast(_TEXT), - pa.scalar(self.column, _TEXT), - pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), + pa.scalar(self.column, _TEXT), # pyright: ignore[reportArgumentType] # as above + pa.scalar(constants.BLOCK_SEPARATOR, _TEXT), # pyright: ignore[reportArgumentType] # as above ) @@ -97,8 +97,9 @@ def as_py(self, *args: Any, **kwargs: Any) -> NoReturn: # pyright: ignore[repor class DerivedTokenType(pa.ExtensionType): """The Arrow type of a derived token column: no bytes, and the recipe. - Internal and never registered, so it is in no stored table and no schema Orcapod - presents or hashes. Two derived columns have one type only with one recipe. + Internal: in no stored table and no schema Orcapod presents or hashes. Not + registered with Arrow: a spilled table is written as its storage (no bytes) and + wrapped in its type again. Two derived columns have one type only with one recipe. """ def __init__(self, recipe: TokenRecipe) -> None: @@ -117,17 +118,29 @@ def __arrow_ext_deserialize__( def __arrow_ext_scalar_class__(self) -> type[pa.ExtensionScalar]: return _DerivedTokenScalar + def __reduce__(self) -> NoReturn: + """Refuse to be pickled: a table another process reads holds the text. + + Raises: + TypeError: Always. + """ + raise TypeError("a derived source-info token column is not pickled") + # pyarrow compares extension types by name and storage only; Arrow asks this. def __eq__(self, other: object) -> bool: return isinstance(other, DerivedTokenType) and self.recipe == other.recipe + def __ne__(self, other: object) -> bool: + return not self == other + def __hash__(self) -> int: return hash(self.recipe) def derived_array(recipe: TokenRecipe, rows: int) -> pa.Array[Any]: # pyright: ignore[reportExplicitAny] # an Arrow array """A derived token column of ``rows`` rows: no row has a byte.""" - storage = pa.Array.from_buffers(pa.struct([]), rows, [None], 0, 0) + # No validity bitmap: no row is null. (The stubs do not allow the absent buffer.) + storage = pa.Array.from_buffers(pa.struct([]), rows, cast(Any, [None]), 0, 0) return pa.ExtensionArray.from_storage(DerivedTokenType(recipe), storage) @@ -219,16 +232,3 @@ def rename_read_columns(table: pa.Table, names: Mapping[str, str]) -> pa.Table: derived_array(renamed, table.num_rows), ) return table - - -def text_schema(schema: pa.Schema) -> pa.Schema: - """``schema`` with each derived token column as the text it stands for.""" - if not derived_columns(schema): - return schema - return pa.schema( - [ - field.with_type(_TEXT) if derived_recipe(field.type) else field - for field in schema - ], - metadata=schema.metadata, - ) diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py new file mode 100644 index 000000000..40eb740ea --- /dev/null +++ b/tests/test_core/streams/test_source_tokens.py @@ -0,0 +1,449 @@ +"""Source-info tokens carried as a recipe until their text is needed (ITL-1464). + +The oracle is the same operation with every source's tokens built as text at once, as +sources did before: values, types, nullability, row order and hashes are equal, and no +derived column reaches a user, a user's operator, a stored table, a hash or a pickle. +""" + +from __future__ import annotations + +import pickle +from collections.abc import Callable +from typing import Any + +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq +import pytest + +from orcapod import contexts +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import ( + AddTags, + DropColumns, + DropNulls, + DropTagColumns, + MapColumns, + MapData, + MapTags, + PolarsFilter, + SelectDataColumns, + TagBy, +) +from orcapod.sources import ArrowTableSource, CachedSource +from orcapod.system_constants import constants +from orcapod.utils import arrow_utils, source_tokens +from tests.test_core.operators.test_async_sync_equivalence import ( + AFTER_OPERATOR_CASES, + CASES, + Case, +) +from tests.test_core.operators.test_row_built_form import assert_same_values + +CARRIED = {"source": True, "system_tags": True, "context": True} + + +@pytest.fixture +def text_sources(monkeypatch: pytest.MonkeyPatch) -> Callable[[], None]: + """Make every source built from now on hold its tokens as text.""" + add = arrow_utils.add_system_tag_columns + + def switch() -> None: + monkeypatch.setattr( + arrow_utils, + "add_system_tag_columns", + lambda *args: source_tokens.materialize(add(*args)), + ) + + return switch + + +def _table() -> pa.Table: + """Chunked, two tags (one a data-tag), two data columns, nulls.""" + whole = pa.table( + { + "k": pa.array(range(10), pa.int32()), + "j": pa.array([f"j{i % 3}" for i in range(10)]), + "x": pa.array([None if i % 4 == 0 else float(i) for i in range(10)]), + "y": pa.array([f"y{i}" for i in range(10)]), + } + ) + return pa.concat_tables([whole.slice(0, 3), whole.slice(3, 4), whole.slice(7)]) + + +def _source(**kwargs: Any) -> ArrowTableSource: + return ArrowTableSource( + _table(), + tag_columns=["k", "j"], + tag_only_columns=["j"], + record_id_columns=["k"], + **kwargs, + ) + + +def _plain_source() -> ArrowTableSource: + return ArrowTableSource( + _table(), tag_columns=["k", "j"], tag_only_columns=True, record_id_columns=["k"] + ) + + +def _derived(table: pa.Table) -> tuple[str, ...]: + return source_tokens.derived_columns(table.schema) + + +ROW_WISE: dict[str, Callable[[], Any]] = { + "drop_nulls": lambda: DropNulls(["x"])(_source()), + "drop_nulls_all": lambda: DropNulls()(_source()), + "polars_filter": lambda: PolarsFilter([pl.col("x") > 2, pl.col("j") == "j1"])( + _source() + ), + "polars_constraint": lambda: PolarsFilter([], {"j": "j1", "y": "y4"})(_source()), + "filter": lambda: _source().filter({"j": "j1", "y": "y4"}), + "map_data": lambda: MapData({"x": "y", "y": "x"})(_source()), + "map_data_tag": lambda: MapData({"k": "kk", "x": "z"})(_source()), + "map_tags": lambda: MapTags({"k": "kk", "j": "jj"})(_source()), + "map_tags_only": lambda: MapTags({"k": "kk", "j": "jj"}, tag_only=True)(_source()), + "map_columns": lambda: MapColumns({"j": "jj", "x": "z", "k": "kk"})( + _plain_source() + ), + "select_data": lambda: SelectDataColumns(["y"])(_source()), + "drop_tags": lambda: DropTagColumns(["k"])(_source()), + "drop_columns": lambda: DropColumns(["k", "x"])(_source()), + "add_tags": lambda: AddTags({"b": 1, "a": "q"})(_source()), + "tag_by": lambda: TagBy(["x"])(DropNulls(["x"])(_plain_source())), + "chain": lambda: ( + _source() + .drop_nulls(["x"]) + .map_data({"x": "y", "y": "x"}) + .polars_filter(pl.col("y") > 2) + .add_tags(c=1) + ), +} + + +@pytest.mark.parametrize("name", ROW_WISE) +def test_a_row_wise_operator_carries_the_tokens_and_gives_the_same_rows( + name: str, text_sources: Callable[[], None] +) -> None: + result = ROW_WISE[name]() + carried = result.as_carried_table(columns=CARRIED) + tokens = [c for c in carried.column_names if c.startswith(constants.SOURCE_PREFIX)] + assert tokens and set(_derived(carried)) == set(tokens) + table = result.as_table(all_info=True) + rows = [(t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in result] + digest = result.content_hash() + text_sources() + oracle = ROW_WISE[name]() + expected = oracle.as_table(all_info=True) + assert not _derived(oracle.as_carried_table(columns=CARRIED)) + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + assert rows == [ + (t.as_dict(all_info=True), d.as_dict(all_info=True)) for t, d in oracle + ] + assert digest == oracle.content_hash() + + +@pytest.mark.parametrize( + "case", [*[pytest.param(c, id=c.label) for c in CASES], *AFTER_OPERATOR_CASES] +) +def test_every_operator_gives_what_text_sources_give( + case: Case, text_sources: Callable[[], None] +) -> None: + """Every operator of the equivalence corpus: the whole table, its carried form, and + F (the table a job node hands on) of the carried form.""" + result = case.make_op()(*case.make_sources()) + table = result.as_table(all_info=True) + carried = result.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS) + plain = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + built = source_tokens.materialize(carried) + assert built.schema.equals(plain.schema, check_metadata=True) + assert_same_values(built, plain) + if plain.num_rows: + formed = StaticOutputOperatorPod._row_built_form(carried, result.keys()) + from_text = StaticOutputOperatorPod._row_built_form(plain, result.keys()) + assert _derived(formed) or not _derived(carried) + formed = source_tokens.materialize(formed) + assert formed.schema.equals(from_text.schema, check_metadata=True) + assert_same_values(formed, from_text) + text_sources() + expected = case.make_op()(*case.make_sources()).as_table(all_info=True) + assert table.schema.equals(expected.schema, check_metadata=True) + assert_same_values(table, expected) + + +def _column_configs() -> list[dict[str, bool]]: + groups = ("source", "system_tags", "context", "content_hash", "sort_by_tags") + return [ + {g: bool(bits >> i & 1) for i, g in enumerate(groups)} + for bits in range(2 ** len(groups)) + ] + + +@pytest.mark.parametrize("make", [_source, ROW_WISE["chain"]], ids=["source", "chain"]) +def test_no_public_read_gives_a_derived_column(make: Callable[[], Any]) -> None: + stream = make() + tables: list[pa.Table] = [stream.as_table(columns=c) for c in _column_configs()] + tables += [stream.head(3, columns=c).table for c in _column_configs()] + tables += [stream.as_table(all_info=True), stream.head(3, all_info=True).table] + tables += [stream.run().table] + for tag, data in stream.flow(): + tables += [tag.as_table(all_info=True), data.as_table(all_info=True)] + assert all(isinstance(t, str) for t in data.source_info().values()) + tables.append(stream.as_polars_df(columns=CARRIED).to_arrow()) + tables.append(pa.Table.from_pandas(stream.as_pandas_df(columns=CARRIED))) + assert not stream.as_lazy_frame(columns=CARRIED).collect().is_empty() + for table in tables: + assert not _derived(table) + assert pa.struct([]) not in table.schema.types + _ = table.to_pylist() + for schema in (stream.arrow_schema(), *stream.output_schema(all_info=True)): + assert "derived" not in str(schema) + assert "derived_token" not in stream.run()._repr_html_() + repr(stream.run()) + + +def test_a_table_without_its_system_tags_holds_text() -> None: + """The recipe reads the system tags, so a table without them is never carried.""" + for config in ({"source": True}, {"source": True, "context": True}): + table = _source().as_carried_table(columns=config) + assert not _derived(table) + assert table.column("_source_x").type == pa.large_string() + + +class _ReadsEverything(UnaryOperator): + """A user's operator: reads every column of its input table.""" + + DATA_TAGS_ISSUE = None + seen: list[pa.Table] = [] + + def validate_unary_input(self, stream: Any) -> None: + pass + + def unary_output_schema(self, stream: Any, **kwargs: Any) -> Any: + return stream.output_schema(**kwargs) + + def identity_structure(self) -> Any: + return "ReadsEverything" + + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns={"source": True, "system_tags": True}) + self.seen.append(table) + assert all(len(v) == len(table) for v in table.to_pydict().values()) + return ArrowTableStream( + table, tag_columns=stream.keys()[0], data_tags=stream_data_tags(stream) + ) + + +def test_a_users_operator_reads_text() -> None: + _ReadsEverything.seen = [] + result = _ReadsEverything()(_source()) + after = result.drop_nulls(["x"]) + table = after.as_table(columns=CARRIED) + (seen,) = _ReadsEverything.seen + assert not _derived(seen) + assert str(seen.column("_source_x")[1]).endswith('::{"k":1}::x') + assert table.column("_source_x").to_pylist() == [ + t for i, t in enumerate(seen.column("_source_x").to_pylist()) if i % 4 + ] + + +@pytest.mark.parametrize( + "predicate", + [ + pl.col("_source_x").str.ends_with("::x"), + pl.any_horizontal(pl.all().is_not_null()), + pl.any_horizontal(pl.col("^_source_.*$").str.contains("::")), + pl.concat_str(["_source_x", "_source_y"]).str.contains("::x"), + "x_is_big", + [True] * 5 + [False] * 5, + ], + ids=["named", "all", "regex", "concat", "name", "mask"], +) +def test_a_predicate_that_may_read_tokens_reads_text( + predicate: Any, text_sources: Callable[[], None] +) -> None: + def make() -> Any: + table = _table().append_column("x_is_big", pa.array([True, False] * 5)) + return PolarsFilter([predicate])(ArrowTableSource(table, tag_columns=["k"])) + + table = make().as_table(all_info=True) + text_sources() + expected = make().as_table(all_info=True) + assert table.num_rows > 0 + assert table.equals(expected) + + +def test_an_unknown_column_is_reported_as_with_text( + text_sources: Callable[[], None], +) -> None: + def message() -> str: + with pytest.raises(pl.exceptions.ColumnNotFoundError) as error: + _ = PolarsFilter([pl.col("nope") > 1])(_source()).as_table() + return str(error.value) + + got = message() + text_sources() + assert got == message() + + +def test_a_constraint_expression_may_read_tokens() -> None: + """``filter(x=)``: the value is looked into as a predicate is.""" + kept = PolarsFilter([], {"y": pl.col("_source_y").str.slice(0, 2)})(_source()) + assert kept.as_table().num_rows == 0 + + +def test_stored_rows_hold_text(text_sources: Callable[[], None]) -> None: + """A cached source stores every column, tokens and record hashes included.""" + + def stored() -> pa.Table: + database = InMemoryArrowDatabase() + cached = CachedSource(_source(), cache_database=database) + _ = cached.as_table() + table = cached.get_all_records() + assert table is not None + return table.drop_columns( + [c for c in table.column_names if "time" in c or c.endswith("_ts")] + ) + + table = stored() + assert not _derived(table) + text_sources() + expected = stored() + assert table.schema.equals(expected.schema, check_metadata=True) + assert table.equals(expected) + + +def test_a_derived_column_that_leaks_is_an_error() -> None: + carried = _source().as_carried_table(columns=CARRIED) + tokens = carried.column("_source_x") + with pytest.raises(TypeError, match="no value"): + _ = tokens.to_pylist() + with pytest.raises(pa.ArrowNotImplementedError): + _ = tokens.cast(pa.large_string()) + with pytest.raises(TypeError, match="not pickled"): + _ = pickle.dumps(carried) + with pytest.raises(pa.ArrowNotImplementedError): + pq.write_table(carried, pa.BufferOutputStream()) + with pytest.raises(Exception, match="no value|derived"): + _ = contexts.get_default_context().arrow_hasher.hash_table(carried) + + +def test_a_spilled_table_keeps_its_recipes() -> None: + """As the row spool writes it: an extension column's storage, wrapped when read.""" + carried: Any = _source().as_carried_table(columns=CARRIED).combine_chunks() + arrow: Any = pa + batch: Any = carried.to_batches()[0] + storage = arrow.RecordBatch.from_arrays( + [getattr(c, "storage", c) for c in batch.columns], names=batch.schema.names + ) + sink = pa.BufferOutputStream() + with pa.ipc.new_file(sink, storage.schema) as writer: + writer.write_batch(storage) + read = pa.ipc.open_file(sink.getvalue()).get_batch(0) + wrapped = arrow.Table.from_arrays( + [ + arrow.ExtensionArray.from_storage(f.type, c) + if isinstance(f.type, pa.BaseExtensionType) + else c + for f, c in zip(carried.schema, read.columns, strict=True) + ], + schema=carried.schema, + ) + order = pa.array([7, 2, 2, 9]) + assert _derived(wrapped) == _derived(carried) + assert source_tokens.materialize(wrapped.take(order)).equals( + source_tokens.materialize(carried).take(order) + ) + + +def test_a_carried_column_has_no_bytes_and_is_not_null() -> None: + carried = _source().as_carried_table(columns=CARRIED) + taken = carried.take(pa.array([1, 5])).filter(pc.field("k") > 1) + for table in (carried, taken, pa.concat_tables([carried, taken]).combine_chunks()): + for name in _derived(table): + assert table.column(name).nbytes == 0 + assert table.column(name).null_count == 0 + assert not table.schema.field(name).nullable + + +def test_recipes_tell_types_apart() -> None: + one, two = ( + source_tokens.derived_array(source_tokens.TokenRecipe("s", "r", c), 2) + for c in ("a", "b") + ) + assert one.type != two.type + assert pa.schema([("c", one.type)]) != pa.schema([("c", two.type)]) + with pytest.raises(pa.ArrowInvalid): + _ = pa.concat_tables([pa.table({"c": one}), pa.table({"c": two})]) + + +def test_extended_system_tag_names_are_followed_and_sorting_builds_the_text() -> None: + """A join's system-tag rename keeps the tokens derived; sorting the values of two + inputs with one pipeline hash builds them first, so each names its own row.""" + left, right = ( + _source(source_id=name).map_data( + {"x": f"x{name}", "y": f"y{name}", "k": f"k{name}"} + ) + for name in ("b", "a") + ) + tables = [ + arrow_utils.append_to_system_tags( + s.as_carried_table(columns={"source": True, "system_tags": True}), f"h:{i}" + ) + for i, s in enumerate((left, right)) + ] + plain = [source_tokens.materialize(t) for t in tables] + assert plain[0].column("_source_xb")[1].as_py().startswith("arrow_table_v1:b::") + joined = arrow_utils.hstack_tables(tables[0], tables[1].drop_columns(["k", "j"])) + assert _derived(joined) + done = arrow_utils.sort_system_tag_values(joined) + assert not _derived(done) + for table in plain: + for name in table.column_names: + if name.startswith(constants.SOURCE_PREFIX): + assert done.column(name).equals(table.column(name)) + + +def test_rows_are_built_a_part_at_a_time(monkeypatch: pytest.MonkeyPatch) -> None: + """Iteration builds text per part of the rows, whatever their chunks.""" + from orcapod.core.streams import arrow_table_stream + + expected = _source().as_table(columns=CARRIED) + sizes: list[int] = [] + build = source_tokens.materialize + + def record(table: pa.Table, names: Any = None) -> pa.Table: + sizes.append(table.num_rows) + return build(table, names) + + monkeypatch.setattr(arrow_table_stream, "ROWS_PER_PART", 4) + monkeypatch.setattr(source_tokens, "materialize", record) + rows = list(_source()) + assert sizes == [4, 4, 2] + assert [d.source_info()["x"] for _, d in rows] == expected.column( + "_source_x" + ).to_pylist() + + +def test_no_rows_hold_text_types() -> None: + table = _source().polars_filter(pl.col("k") > 100).as_table(all_info=True) + assert table.num_rows == 0 + assert table.schema.field("_source_x").type == pa.large_string() + assert table.schema.equals(_source().as_table(all_info=True).schema) + + +def test_a_source_with_its_own_read_gives_its_own_table() -> None: + """A subclass, or an object, with its own ``as_table`` is read through it.""" + + class Own(ArrowTableSource): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + own = Own(_table(), tag_columns=["k"]) + assert own.drop_columns(["x"]).as_table().num_rows == 2 From 7062127c1d3ebb05fb3acd3a171ece0063e0914e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 25 Nov 2026 02:16:53 -0800 Subject: [PATCH 3/3] fix(core): the carried read is private and exact; hashes and stores refuse recipes (ITL-1464) Review of PRs 563 and 564. Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1464-tokens.md | 27 ++- src/orcapod/core/nodes/source_node.py | 6 - src/orcapod/core/operators/add_tags.py | 7 +- .../core/operators/column_selection.py | 35 +++- src/orcapod/core/operators/drop_nulls.py | 7 +- src/orcapod/core/operators/filter.py | 7 +- src/orcapod/core/operators/filters.py | 6 +- src/orcapod/core/operators/mappers.py | 21 +- src/orcapod/core/operators/meta_columns.py | 5 +- .../core/operators/static_output_pod.py | 35 +++- src/orcapod/core/operators/tag_by.py | 7 +- .../core/sources/arrow_table_source.py | 1 + src/orcapod/core/sources/base.py | 17 +- src/orcapod/core/sources/csv_source.py | 1 + src/orcapod/core/sources/data_frame_source.py | 1 + src/orcapod/core/sources/db_table_source.py | 1 + .../core/sources/delta_table_source.py | 1 + src/orcapod/core/sources/derived_source.py | 7 +- src/orcapod/core/sources/dict_source.py | 1 + src/orcapod/core/sources/list_source.py | 1 + .../core/sources/postgresql_table_source.py | 1 + .../core/sources/spiraldb_table_source.py | 11 +- .../core/sources/sqlite_table_source.py | 1 + .../core/streams/arrow_table_stream.py | 9 +- src/orcapod/core/streams/base.py | 12 -- src/orcapod/core/streams/carried.py | 46 +++++ .../databases/connector_arrow_database.py | 2 + src/orcapod/databases/delta_lake_databases.py | 3 +- src/orcapod/databases/in_memory_databases.py | 2 + src/orcapod/hashing/arrow_hashers.py | 3 + .../protocols/core_protocols/streams.py | 11 -- src/orcapod/utils/source_tokens.py | 15 +- tests/test_core/streams/test_source_tokens.py | 186 ++++++++++++++++-- 33 files changed, 379 insertions(+), 117 deletions(-) create mode 100644 src/orcapod/core/streams/carried.py diff --git a/docs/dev/specs/itl-1464-tokens.md b/docs/dev/specs/itl-1464-tokens.md index 7473d3954..c15c94a0d 100644 --- a/docs/dev/specs/itl-1464-tokens.md +++ b/docs/dev/specs/itl-1464-tokens.md @@ -30,17 +30,26 @@ system-tag column names of the same table, and the column's name at the source. - Text is made in one function, `materialize`, at most 65,536 rows at a time. A derived column is loud where it does not belong: reading a value, casting to text, -hashing, pickling and writing Parquet (so Delta) each raise. +hashing, pickling, storing and writing Parquet each raise. ## Where a derived table can go -`StreamProtocol.as_carried_table(columns=)` is the internal read: the table of `as_table` -with derived columns left as they are. Only library operators call it. The default is -`as_table` (text), so a user's operator, source or stream, and every job node today, is -given and gives text. `ArrowTableStream`, `DynamicPodStream`, and the sources over a held -or scanned table answer it without text. `as_table` with any columns, `iter_data`, `head`, -`run`, the data frame methods and the identity table give text, as before. A read without -the system tags gives text (the recipe would have nothing to read). +`core/streams/carried.py` holds the internal read, `carried_table(stream, columns)`: the +table of `as_table` with derived columns left as they are. It is a private library function, +no part of a stream's interface. Both ends are exact: + +- the stream: its own class declares `_carried_table` (the library's `ArrowTableStream`, + `DynamicPodStream` and source kinds), and the object reads as that class + (`reads_as_its_class`). A subclass, a replaced `as_table` and a user's stream are read + through `as_table`, and give text; +- the reader: an operator whose own class declares `CARRIES_TOKENS`, through + `StaticOutputOperatorPod._input_table`. A user's operator, also a subclass of a library + one, reads text. + +`as_table` with any columns, `iter_data`, `head`, `run`, the data frame methods and the +identity table give text, as before, and so does a read without the system tags (the recipe +would have nothing to read). The Arrow hashers (schemas, and tables without rows too) and +every database's `add_records` refuse a derived column by name (`refuse_derived`). ## Producers of `_source_` columns @@ -72,7 +81,7 @@ the system tags gives text (the recipe would have nothing to read). | `GroupBy`, `Batch` | the members' tokens, in a list | text (below) | | `iter_data` (rows: function pods, side effects, async rows) | one string per column of each row | built for 8,192 rows at a time | | `F` (`_row_built_form`, `row_built_provenance`) | types and null flags | passes a derived column through (a token is one string and never null) | -| Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `as_carried_table` | +| Job nodes (`core/nodes/*`) | the stored text; the kept table | text until the transport calls `carried_table` | | Function node pipeline table, result table, operator and source caches | stored text | unchanged: they read rows or `as_table` | | Record-batch channels, streaming joins | types, values | unchanged (text) | | Provenance trace (`pipeline/provenance.py`) | text | unchanged | diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 2fc8678fd..b6b8bc0f6 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1271,12 +1271,6 @@ def run(self) -> StreamView: display_all_rows=False, ) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table of ``as_table(columns=columns)``; see ``StreamProtocol`` (ITL-1464).""" - return self.as_table(columns=columns) - def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index efedd2592..812fcdf1a 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -116,6 +116,8 @@ class AddTags(UnaryOperator): ``::`` separator). """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -322,13 +324,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_keys, _ = stream.keys() data_context = stream.data_context # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844) - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) return ArrowTableStream( self._with_constants(table, tag_keys, data_context.type_converter), diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index 9cfd73cbd..964f5f838 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -57,6 +57,8 @@ class SelectTagColumns(UnaryOperator): Operator that selects specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -90,13 +92,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All tag columns are selected. Returning stream unaltered.") return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A dropped data-tag leaves its column as plain data (specification @@ -196,6 +199,8 @@ class SelectDataColumns(UnaryOperator): Operator that selects specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -229,7 +234,8 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("All data columns are selected. Returning stream unaltered.") return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, @@ -352,6 +358,8 @@ class DropTagColumns(UnaryOperator): Operator that drops specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -388,13 +396,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: logger.info("No tag columns to drop. Returning stream unaltered.") return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A dropped data-tag leaves its column as plain data (specification @@ -496,6 +505,8 @@ class DropDataColumns(UnaryOperator): Operator that drops specified columns from a stream. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -534,13 +545,14 @@ 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_carried_table( + table = self._input_table( + stream, columns={ "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). @@ -774,13 +786,14 @@ 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_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) removed = { *tags_removed, @@ -881,6 +894,8 @@ class DropColumns(_TagAndDataColumnsOperator): be dropped: a stream needs at least one data column. """ + CARRIES_TOKENS: ClassVar[bool] = True + _verb: ClassVar[str] = "drop" def _removed(self, columns: Collection[str]) -> list[str]: @@ -905,6 +920,8 @@ class SelectColumns(_TagAndDataColumnsOperator): named: a stream needs at least one data column. """ + CARRIES_TOKENS: ClassVar[bool] = True + _verb: ClassVar[str] = "select" def _removed(self, columns: Collection[str]) -> list[str]: diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 028bcfa8c..03780ede0 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -90,6 +90,8 @@ class DropNulls(UnaryOperator): ValueError: If ``columns`` is an empty collection. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -316,13 +318,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: A stream over the surviving rows, in input order, with the named columns non-nullable. A result with no rows has the same schema. """ - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) tag_columns, data_columns = stream.keys() return ArrowTableStream( diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index b8e3621e1..7f80fe975 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -74,6 +74,8 @@ class Filter(UnaryOperator): TypeError: If ``condition`` is neither a condition nor a mapping. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): a data-tag is one column, named alike as tag or data. DATA_TAGS_ISSUE: ClassVar[str | None] = None @@ -243,13 +245,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ # Every system column passes through: source info, system tags and each row's # data context (a raw stream may hold several). - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) tag_columns, data_columns = stream.keys() self._check_arrow(table.schema, _user_columns(tag_columns, data_columns)) diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 491fa79b9..e0de9aad8 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -40,6 +40,8 @@ class PolarsFilter(UnaryOperator): Operator that applies Polars filtering to a stream """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. DATA_TAGS_ISSUE: ClassVar[str | None] = None @@ -71,8 +73,8 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: return stream # TODO: improve efficiency here... - whole = stream.as_carried_table( - columns={"source": True, "system_tags": True, "sort_by_tags": False} + whole = self._input_table( + stream, columns={"source": True, "system_tags": True, "sort_by_tags": False} ) # Polars reads no derived token column: one is left out, and put back for the # rows kept (its recipe reads the system tags kept with them, ITL-1464), unless diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index 184f66252..47cbde20b 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -91,6 +91,8 @@ class MapData(UnaryOperator): ``SelectTagColumns`` and the other column operators. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Data-tags (ITL-1023): handled. # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -179,13 +181,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename in the data, return stream as is return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) # A data-tag column keeps its tag under its own name, now plain; the @@ -365,6 +368,8 @@ class MapTags(UnaryOperator): tag_only: Rename data-tags in the tag role only. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -457,13 +462,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # nothing to rename or drop in the tags, return stream as is return stream - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) name_map = { @@ -664,6 +670,8 @@ class MapColumns(UnaryOperator): or (with ``drop_unmapped``) no data column would remain. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). # Each output row comes from one input row (ITL-1347). ROW_BY_ROW: ClassVar[bool] = True @@ -799,13 +807,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: tag_renames, data_renames, tags_dropped, data_dropped = self._plan( tag_columns, data_columns ) - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) dropped = { *tags_dropped, diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index a2312b830..fd6a7b00f 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -19,6 +19,7 @@ from orcapod.channels import WritableChannel from orcapod.core.data_tags import stream_data_tags, with_data_tags_first +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -112,8 +113,8 @@ def without_input_meta( """ if not _carries_meta(stream, inputs): return stream - table = stream.as_carried_table( - columns={"source": True, "system_tags": True, "context": True} + table = carried_table( + stream, {"source": True, "system_tags": True, "context": True} ) tag_columns = stream.keys()[0] return ArrowTableStream( diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 845a7d6a7..c17ec38ad 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -43,6 +43,7 @@ from orcapod.utils import source_tokens from orcapod.utils.provisional import note_provisional_use, provisional_class_name from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -118,6 +119,14 @@ class StaticOutputOperatorPod(TraceableBase): (``async_execute_batches``); every other operator needs all of an input first. """ + CARRIES_TOKENS: ClassVar[bool] = False + """Whether the operator passes derived token columns on (ITL-1464). + + Declared by a library operator that never reads the values of a source-info column + it passes on, or builds their text itself. It holds for exactly the class that + declares it, never for a subclass (``_input_table``). + """ + OUTPUT_SCHEMA_IS_INPUT_SCHEMA: ClassVar[bool] = False """Whether the output has exactly its single input's columns and Arrow types. @@ -221,6 +230,24 @@ def check_data_tag_support(self, *streams: StreamProtocol) -> None: if any(stream_data_tags(stream) for stream in streams): raise not_supported_yet(type(self).__name__, self.DATA_TAGS_ISSUE) + def _input_table( + self, stream: StreamProtocol, columns: dict[str, Any] + ) -> "pa.Table": + """The table of ``stream`` as this operator reads it. + + Derived token columns as they are (``carried_table``) for an operator whose class + declares ``CARRIES_TOKENS`` itself and is used as that class; text for any other, + so a user's operator, also one that subclasses a library operator, reads text. + + Args: + stream: An input stream. + columns: The column groups, as for ``as_table``. + """ + kind = type(self) + if vars(kind).get("CARRIES_TOKENS") is True and reads_as_its_class(self, kind): + return carried_table(stream, columns) + return stream.as_table(columns=columns) + def pipeline_identity_structure(self) -> Any: """Return the pipeline identity, which defaults to content identity for operators.""" return self.identity_structure() @@ -1751,6 +1778,8 @@ class _RowsOfStream(ArrowTableStream): data_context: The rows' data context; ``None`` for the default. """ + _carried_table = ArrowTableStream._carried_table # pyright: ignore[reportPrivateUsage] # read as its base is + def __init__( self, table: pa.Table, @@ -2049,15 +2078,13 @@ def as_table( ) return self._cached_stream.as_table(columns=columns, all_info=all_info) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": + def _carried_table(self, config: ColumnConfig) -> "pa.Table": """The operator's result, derived token columns as they are (ITL-1464).""" self._refresh() assert self._cached_stream is not None, ( "StreamProtocol has not been updated or is empty." ) - return self._cached_stream.as_carried_table(columns=columns) + return carried_table(self._cached_stream, config) def iter_data( self, diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index a7cbe5f7a..7a9dfffae 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -73,6 +73,8 @@ class TagBy(UnaryOperator): column name, or one holding ``::``. """ + CARRIES_TOKENS: ClassVar[bool] = True + # Provisional: its identity is not frozen with data context v1 (ITL-1279). PROVISIONAL: ClassVar[bool] = True @@ -209,13 +211,14 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """ tag_columns, _ = stream.keys() # The context column too, so each row keeps its own data context key. - table = stream.as_carried_table( + table = self._input_table( + stream, columns={ "source": True, "system_tags": True, "context": True, "sort_by_tags": False, - } + }, ) return ArrowTableStream( table, diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f05485472..d70b3f1f9 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -92,6 +92,7 @@ class ArrowTableSource(RootSource): # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 100d67285..2fad18ee3 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -6,6 +6,7 @@ from orcapod import contexts from orcapod.config import OrcapodConfig +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ( StreamBase, reads_as_its_class, @@ -537,18 +538,14 @@ def as_table( """Delegate to the underlying stream's as_table.""" return self._stream.as_table(columns=columns, all_info=all_info) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The underlying stream's table, derived token columns as they are (ITL-1464). + def _carried_from_stream(self, config: ColumnConfig) -> "pa.Table": + """``as_table`` above, derived token columns as they are (ITL-1464). - A source that reads its rows its own way (a subclass, or an object, with its own - ``as_table``) gives that table. + What a source kind that reads through ``_stream`` declares as its + ``_carried_table`` (``core/streams/carried.py``). """ - if type(self).as_table is RootSource.as_table and "as_table" not in vars(self): - stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass - return stream.as_carried_table(columns=columns) - return super().as_carried_table(columns=columns) + stream: StreamBase = getattr(self, "_stream") # noqa: B009 # set by each subclass + return carried_table(stream, config) # ------------------------------------------------------------------------- # The start-of-run check (ITL-1102) diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index f39681d9e..095fcce76 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -280,6 +280,7 @@ class CSVSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6c65bf64d..0f41f442f 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -47,6 +47,7 @@ class DataFrameSource(RootSource): # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 86ea349d5..b50ad5e6a 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -84,6 +84,7 @@ class DBTableSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..608c783ae 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -53,6 +53,7 @@ class DeltaTableSource(RootSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True def __init__( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index ab1a585b1..6ae376410 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -23,6 +23,7 @@ normalize_record_id_columns, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -813,8 +814,6 @@ def as_table( ) -> "pa.Table": return self._get_stream().as_table(columns=columns, all_info=all_info) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": + def _carried_table(self, config: ColumnConfig) -> "pa.Table": """The source's table, derived token columns as they are (ITL-1464).""" - return self._get_stream().as_carried_table(columns=columns) + return carried_table(self._get_stream(), config) diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index fdf7c1f34..0cbdbcf1a 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -43,6 +43,7 @@ class DictSource(RootSource): # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..2902262cb 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -42,6 +42,7 @@ def _default_tag(element: Any, idx: int) -> dict[str, Any]: # The version of this kind's implementation, in the kind part (ITL-1425). SOURCE_VERSION: ClassVar[int] = 1 TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = RootSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 58acc1f17..e7585811e 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -176,6 +176,7 @@ class PostgreSQLTableSource(DBTableSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = DBTableSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index b1dba51bb..f3b1241fb 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -62,6 +62,7 @@ row_identifiers, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import StreamBase, check_head_size from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( @@ -963,20 +964,16 @@ def as_table( columns=columns, all_info=all_info ) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": + def _carried_table(self, config: ColumnConfig) -> "pa.Table": """Scan the table as ``as_table`` does, building no source-info text (ITL-1464).""" - return self._whole_stream(self._batch_streams()).as_carried_table( - columns=columns - ) + return carried_table(self._whole_stream(self._batch_streams()), config) def _whole_stream(self, streams: Iterator["ArrowTableStream"]) -> StreamBase: """Return the rows of ``streams`` (batches of one read) as one stream.""" # One stream over all the rows, so that a whole-table option (sorting by # tags) applies across batches. enriched = {"source": True, "system_tags": True} - tables = [stream.as_carried_table(columns=enriched) for stream in streams] + tables = [carried_table(stream, enriched) for stream in streams] if not tables: return self._stream return ArrowTableStream( diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eab59a821..b197e8c2a 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -105,6 +105,7 @@ class SQLiteTableSource(DBTableSource): SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True + _carried_table = DBTableSource._carried_from_stream def __init__( self, diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 09f1b1d4e..4860839f1 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -354,11 +354,8 @@ def as_table( columns_config = ColumnConfig.handle_config(columns, all_info=all_info) return self._assemble_table(columns_config, limit=None) - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table with its derived token columns as they are (ITL-1464).""" - config = ColumnConfig.handle_config(columns) + def _carried_table(self, config: ColumnConfig) -> "pa.Table": + """The table with its derived token columns as they are (``carried_table``).""" return self._assemble_table(config, limit=None, carried=config.system_tags) def head( @@ -405,7 +402,7 @@ def _assemble_table( Args: columns_config: The column groups to include, and whether to sort by tags. limit: Assemble only the first ``limit`` rows; ``None`` for all of them. - carried: Leave a derived token column derived (``as_carried_table``), which + carried: Leave a derived token column derived (``carried_table``), which needs the system tags in the table; ``False`` gives its text. """ output_table = self._table diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 833a17347..eeaa7a16f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1514,18 +1514,6 @@ def as_table( all_info: bool = False, ) -> "pa.Table": ... - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table of ``as_table(columns=columns)``, as operators pass it on. - - A source-info column may be derived (``utils/source_tokens.py``): a recipe over - the table's system tags in place of its text, which ``source_tokens.materialize`` - builds. Internal: never stored, hashed or shown (ITL-1464). A stream that holds - none gives ``as_table``. - """ - return self.as_table(columns=columns) - def as_polars_df( self, *, diff --git a/src/orcapod/core/streams/carried.py b/src/orcapod/core/streams/carried.py new file mode 100644 index 000000000..5fca2f948 --- /dev/null +++ b/src/orcapod/core/streams/carried.py @@ -0,0 +1,46 @@ +"""Reading a stream's table with its derived token columns as they are (ITL-1464). + +``carried_table`` is how the library's own operators read their inputs: the table of +``as_table``, where a source-info column may be a recipe in place of its text +(``utils/source_tokens.py``). It is no part of a stream's interface. Only a stream whose +class is a library class that declares ``_carried_table`` itself, read as that class +(``reads_as_its_class``: no subclass, nothing replaced on the object), is read this way; +every other stream, a subclass with its own ``as_table`` or a user's stream, is read +through ``as_table`` and gives text. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from orcapod.core.streams.base import reads_as_its_class +from orcapod.types import ColumnConfig + +if TYPE_CHECKING: + import pyarrow as pa + + from orcapod.protocols.core_protocols import StreamProtocol + +CARRIED_TABLE = "_carried_table" +"""The method a library class declares when its table may hold derived columns.""" + + +def carried_table( + stream: StreamProtocol, + columns: ColumnConfig | dict[str, Any], # pyright: ignore[reportExplicitAny] # as as_table +) -> pa.Table: + """``stream.as_table(columns=columns)``, derived token columns as they are. + + Args: + stream: The stream. + columns: The column groups, as for ``as_table``. + + Returns: + The table, for library code that passes it on; never for a user, a user's + operator or function, a store or a hash. + """ + kind = type(stream) + read: Any = vars(kind).get(CARRIED_TABLE) # pyright: ignore[reportExplicitAny] # a method + if read is None or not reads_as_its_class(stream, kind): + return stream.as_table(columns=columns) + return read(stream, ColumnConfig.handle_config(columns)) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..20b4421b1 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -27,6 +27,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.utils import source_tokens from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases.utils import ( coerce_record_id, @@ -438,6 +439,7 @@ def add_records( ) -> None: """Add multiple records to the pending batch.""" self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..e369b1735 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -63,7 +63,7 @@ TypeIdentityError, UnstorableColumnError, ) -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, source_tokens from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -2747,6 +2747,7 @@ def add_records( ValueError: If any record IDs already exist and skip_duplicates=False """ self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2ccb4d696..92b270874 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -9,6 +9,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.utils import source_tokens from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows from orcapod.databases.utils import ( @@ -242,6 +243,7 @@ def add_records( flush: bool = False, ) -> None: self._validate_record_path(record_path) + source_tokens.refuse_derived(records.schema) if records.num_rows == 0: return diff --git a/src/orcapod/hashing/arrow_hashers.py b/src/orcapod/hashing/arrow_hashers.py index cf520d9f8..800086a68 100644 --- a/src/orcapod/hashing/arrow_hashers.py +++ b/src/orcapod/hashing/arrow_hashers.py @@ -18,6 +18,7 @@ from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.hashing.visitors import SemanticHashingVisitor from orcapod.logical_types.canonical_form import storage_form_schema +from orcapod.utils import source_tokens from orcapod.utils.arrow_utils import normalize_extension_columns from orcapod.types import ContentHash @@ -231,6 +232,7 @@ def hash_schema(self, schema: "pa.Schema") -> ContentHash: column that keeps the identifier, so ``hash_schema(table.schema)`` is not the schema inside ``hash_table(table)``, and nothing may rely on it. """ + source_tokens.refuse_derived(schema) schema = storage_form_schema(schema) include_meta = has_extension_metadata(schema) or has_extension_type(schema) if include_meta: @@ -329,6 +331,7 @@ def _digest( Returns: The starfix digest (version prefix included). """ + source_tokens.refuse_derived(table.schema) if isinstance(table, pa.RecordBatch): table = pa.Table.from_batches([table]) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index b35e38beb..c8c72abd6 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -255,17 +255,6 @@ def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ ... - def as_carried_table( - self, *, columns: ColumnConfig | dict[str, Any] | None = None - ) -> "pa.Table": - """The table of ``as_table(columns=columns)``, as operators pass it on. - - A source-info column may be derived (``utils/source_tokens.py``): a recipe over - the table's system tags in place of its text. Internal: never stored, hashed or - shown (ITL-1464). - """ - ... - def as_table( self, *, diff --git a/src/orcapod/utils/source_tokens.py b/src/orcapod/utils/source_tokens.py index 0fd59bcfc..915586db3 100644 --- a/src/orcapod/utils/source_tokens.py +++ b/src/orcapod/utils/source_tokens.py @@ -9,7 +9,7 @@ column as any other; nothing is computed until the text is needed (``materialize``). A derived column is an internal form of a table that operators pass on -(``StreamProtocol.as_carried_table``). It never leaves the library: ``as_table``, rows, +(``core/streams/carried.py``). It never leaves the library: ``as_table``, rows, stored tables and everything hashed hold the text. A place that forgets fails loudly: no value of a derived column can be read, cast to text, hashed, pickled, or written to Parquet (its storage is a struct with no field, which Parquet refuses). @@ -154,6 +154,19 @@ def derived_columns(schema: pa.Schema) -> tuple[str, ...]: return tuple(f.name for f in schema if derived_recipe(f.type) is not None) +def refuse_derived(schema: pa.Schema) -> None: + """Raise if a column of ``schema`` is derived: hashes and stores take text only. + + Raises: + TypeError: Naming the derived columns. + """ + if derived := derived_columns(schema): + raise TypeError( + f"columns {list(derived)} are derived source-info tokens: their text must " + + "be built first (source_tokens.materialize)" + ) + + def materialize(table: pa.Table, names: Collection[str] | None = None) -> pa.Table: """Return ``table`` with its derived token columns as text. diff --git a/tests/test_core/streams/test_source_tokens.py b/tests/test_core/streams/test_source_tokens.py index 40eb740ea..c87163199 100644 --- a/tests/test_core/streams/test_source_tokens.py +++ b/tests/test_core/streams/test_source_tokens.py @@ -9,6 +9,7 @@ import pickle from collections.abc import Callable +from pathlib import Path from typing import Any import polars as pl @@ -22,8 +23,14 @@ from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.carried import carried_table from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS -from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SQLiteConnector, +) from orcapod.operators import ( AddTags, DropColumns, @@ -36,7 +43,8 @@ SelectDataColumns, TagBy, ) -from orcapod.sources import ArrowTableSource, CachedSource +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.sources import ArrowTableSource, CachedSource, SpiralDBTableSource from orcapod.system_constants import constants from orcapod.utils import arrow_utils, source_tokens from tests.test_core.operators.test_async_sync_equivalence import ( @@ -45,6 +53,7 @@ Case, ) from tests.test_core.operators.test_row_built_form import assert_same_values +from tests.test_databases import fake_spiral_sdk as fake CARRIED = {"source": True, "system_tags": True, "context": True} @@ -115,6 +124,9 @@ def _derived(table: pa.Table) -> tuple[str, ...]: "select_data": lambda: SelectDataColumns(["y"])(_source()), "drop_tags": lambda: DropTagColumns(["k"])(_source()), "drop_columns": lambda: DropColumns(["k", "x"])(_source()), + "select_columns": lambda: _source().select_columns(["k", "y"]), + "select_tags": lambda: _source().select_tag_columns(["k"]), + "drop_data": lambda: _source().drop_data_columns(["y"]), "add_tags": lambda: AddTags({"b": 1, "a": "q"})(_source()), "tag_by": lambda: TagBy(["x"])(DropNulls(["x"])(_plain_source())), "chain": lambda: ( @@ -132,7 +144,7 @@ def test_a_row_wise_operator_carries_the_tokens_and_gives_the_same_rows( name: str, text_sources: Callable[[], None] ) -> None: result = ROW_WISE[name]() - carried = result.as_carried_table(columns=CARRIED) + carried = carried_table(result, CARRIED) tokens = [c for c in carried.column_names if c.startswith(constants.SOURCE_PREFIX)] assert tokens and set(_derived(carried)) == set(tokens) table = result.as_table(all_info=True) @@ -141,7 +153,7 @@ def test_a_row_wise_operator_carries_the_tokens_and_gives_the_same_rows( text_sources() oracle = ROW_WISE[name]() expected = oracle.as_table(all_info=True) - assert not _derived(oracle.as_carried_table(columns=CARRIED)) + assert not _derived(carried_table(oracle, CARRIED)) assert table.schema.equals(expected.schema, check_metadata=True) assert_same_values(table, expected) assert rows == [ @@ -160,7 +172,7 @@ def test_every_operator_gives_what_text_sources_give( F (the table a job node hands on) of the carried form.""" result = case.make_op()(*case.make_sources()) table = result.as_table(all_info=True) - carried = result.as_carried_table(columns=ZERO_ROW_INPUT_COLUMNS) + carried = carried_table(result, ZERO_ROW_INPUT_COLUMNS) plain = result.as_table(columns=ZERO_ROW_INPUT_COLUMNS) built = source_tokens.materialize(carried) assert built.schema.equals(plain.schema, check_metadata=True) @@ -211,7 +223,7 @@ def test_no_public_read_gives_a_derived_column(make: Callable[[], Any]) -> None: def test_a_table_without_its_system_tags_holds_text() -> None: """The recipe reads the system tags, so a table without them is never carried.""" for config in ({"source": True}, {"source": True, "context": True}): - table = _source().as_carried_table(columns=config) + table = carried_table(_source(), config) assert not _derived(table) assert table.column("_source_x").type == pa.large_string() @@ -320,7 +332,7 @@ def stored() -> pa.Table: def test_a_derived_column_that_leaks_is_an_error() -> None: - carried = _source().as_carried_table(columns=CARRIED) + carried = carried_table(_source(), CARRIED) tokens = carried.column("_source_x") with pytest.raises(TypeError, match="no value"): _ = tokens.to_pylist() @@ -330,13 +342,47 @@ def test_a_derived_column_that_leaks_is_an_error() -> None: _ = pickle.dumps(carried) with pytest.raises(pa.ArrowNotImplementedError): pq.write_table(carried, pa.BufferOutputStream()) - with pytest.raises(Exception, match="no value|derived"): - _ = contexts.get_default_context().arrow_hasher.hash_table(carried) + hasher = contexts.get_default_context().arrow_hasher + for hash_it in ( + lambda: hasher.hash_table(carried), + lambda: hasher.hash_table(carried.slice(0, 0)), + lambda: hasher.hash_schema(carried.schema), + lambda: hasher.hash_table_strict(carried), + lambda: hasher.hash_table_ordered(carried), + ): + with pytest.raises(TypeError, match="derived"): + _ = hash_it() + + +@pytest.mark.parametrize("rows", [0, 3]) +@pytest.mark.parametrize("kind", ["memory", "delta", "connector"]) +def test_a_store_refuses_a_derived_column(kind: str, rows: int, tmp_path: Path) -> None: + carried = carried_table(_source(), CARRIED).slice(0, rows) + records = carried.append_column( + "rid", pa.array([str(i).encode() for i in range(rows)], pa.large_binary()) + ) + databases: dict[str, Callable[[], Any]] = { + "memory": InMemoryArrowDatabase, + "delta": lambda: DeltaTableDatabase(str(tmp_path / "delta")), + "connector": lambda: ConnectorArrowDatabase( + SQLiteConnector(str(tmp_path / "store.db")) + ), + } + database = databases[kind]() + with pytest.raises(TypeError, match="derived"): + database.add_records(("t",), records, record_id_column="rid", flush=True) + + +def test_the_carried_read_is_no_part_of_a_stream() -> None: + """Review of PR 563: no public name gives a derived column.""" + for stream in (_source(), ROW_WISE["chain"]()): + assert not [n for n in dir(stream) if "carried" in n and not n.startswith("_")] + assert "carried" not in " ".join(dir(StreamProtocol)) def test_a_spilled_table_keeps_its_recipes() -> None: """As the row spool writes it: an extension column's storage, wrapped when read.""" - carried: Any = _source().as_carried_table(columns=CARRIED).combine_chunks() + carried: Any = carried_table(_source(), CARRIED).combine_chunks() arrow: Any = pa batch: Any = carried.to_batches()[0] storage = arrow.RecordBatch.from_arrays( @@ -363,7 +409,7 @@ def test_a_spilled_table_keeps_its_recipes() -> None: def test_a_carried_column_has_no_bytes_and_is_not_null() -> None: - carried = _source().as_carried_table(columns=CARRIED) + carried = carried_table(_source(), CARRIED) taken = carried.take(pa.array([1, 5])).filter(pc.field("k") > 1) for table in (carried, taken, pa.concat_tables([carried, taken]).combine_chunks()): for name in _derived(table): @@ -394,7 +440,7 @@ def test_extended_system_tag_names_are_followed_and_sorting_builds_the_text() -> ) tables = [ arrow_utils.append_to_system_tags( - s.as_carried_table(columns={"source": True, "system_tags": True}), f"h:{i}" + carried_table(s, {"source": True, "system_tags": True}), f"h:{i}" ) for i, s in enumerate((left, right)) ] @@ -438,12 +484,114 @@ def test_no_rows_hold_text_types() -> None: assert table.schema.equals(_source().as_table(all_info=True).schema) -def test_a_source_with_its_own_read_gives_its_own_table() -> None: - """A subclass, or an object, with its own ``as_table`` is read through it.""" +class _OwnSource(ArrowTableSource): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + +class _OwnStream(ArrowTableStream): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + +class _OwnSpiral(SpiralDBTableSource): + def as_table(self, **kwargs: Any) -> pa.Table: + return super().as_table(**kwargs).slice(0, 2) + + +class _Forwarding: + """A stream of the read interface as it is, forwarding to another.""" + + def __init__(self, inner: Any) -> None: + self.inner = inner + + def __getattr__(self, name: str) -> Any: + if name.startswith("_"): + raise AttributeError(name) + return getattr(self.inner, name) + + +def _raw(kind: type[ArrowTableStream]) -> ArrowTableStream: + return kind( + carried_table(_source(), {"source": True, "system_tags": True}), + tag_columns=["k", "j"], + data_tags=["k"], + ) + + +def _replaced() -> Any: + source = _source() + read = source.as_table + setattr(source, "as_table", lambda **kwargs: read(**kwargs).slice(0, 2)) # noqa: B010 # the point + return source + + +@pytest.mark.parametrize("kind", ["source", "stream", "spiral", "replaced"]) +def test_a_stream_with_its_own_read_is_read_through_it( + kind: str, tmp_path: Path +) -> None: + """Review of PRs 563 and 564: a subclass, or an object, with its own ``as_table``.""" + with fake.install(tmp_path): + if kind == "spiral": + table = fake.ExternalProject("example").create_table( + "default.demo", key_schema=pa.schema([("k", pa.uint64())]) + ) + table.write( + pa.table({"k": pa.array([1, 2, 3], pa.uint64()), "x": [3.0, 4.0, 5.0]}) + ) + own: Any = { + "source": lambda: _OwnSource(_table(), tag_columns=["k"]), + "stream": lambda: _raw(_OwnStream), + "spiral": lambda: _OwnSpiral("example", "demo"), + "replaced": _replaced, + }[kind]() + assert not _derived(carried_table(own, CARRIED)) + assert own.map_data({"x": "z"}).as_table().num_rows == 2 + assert own.polars_filter(pl.col("k") > -1).as_table().num_rows == 2 + + +def test_a_stream_without_the_internal_read_is_read_as_before() -> None: + forwarding: Any = _Forwarding(_source()) + assert not _derived(carried_table(forwarding, CARRIED)) + result = DropNulls(["x"]).static_process(forwarding) + assert result.as_table(all_info=True).equals( + DropNulls(["x"]).static_process(_source()).as_table(all_info=True) + ) + + +class _OwnDropNulls(DropNulls): + """A user's operator over a library one.""" + + seen: list[pa.Table] = [] + + def unary_static_process(self, stream: Any) -> Any: + self.seen.append(self._input_table(stream, CARRIED)) + return super().unary_static_process(stream) + + +def test_a_subclass_of_a_library_operator_reads_text() -> None: + _OwnDropNulls.seen = [] + result = _OwnDropNulls(["x"])(_source()) + assert not _derived(carried_table(result, CARRIED)) + (seen,) = _OwnDropNulls.seen + assert not _derived(seen) - class Own(ArrowTableSource): - def as_table(self, **kwargs: Any) -> pa.Table: - return super().as_table(**kwargs).slice(0, 2) - own = Own(_table(), tag_columns=["k"]) - assert own.drop_columns(["x"]).as_table().num_rows == 2 +def test_every_library_source_is_read_without_text() -> None: + """Each kind declares the read itself; the ones with rows of their own do not.""" + from orcapod import sources + + declared = { + name + for name in dir(sources) + if isinstance(cls := getattr(sources, name), type) + and "_carried_table" in vars(cls) + } + kinds = { + name + for name in dir(sources) + if isinstance(cls := getattr(sources, name), type) + and vars(cls).get("TABLE_IS_ROWS") is True + } + assert kinds - declared == {"CachedSource"} + assert declared <= kinds