diff --git a/changelog.d/ITL-1341.md b/changelog.d/ITL-1341.md new file mode 100644 index 000000000..15148164c --- /dev/null +++ b/changelog.d/ITL-1341.md @@ -0,0 +1,3 @@ +### Breaking changes and migration + +- `ArrowTableStream` raises `InputValidationError` at construction for a non-string system tag, a null system-tag value, or a raw source-id or record-id column without its matching column. Supply string values without nulls and include both ID columns for each provenance path. diff --git a/docs/dev/design_issues/ITL-1341-AS4.md b/docs/dev/design_issues/ITL-1341-AS4.md new file mode 100644 index 000000000..a3e477a7e --- /dev/null +++ b/docs/dev/design_issues/ITL-1341-AS4.md @@ -0,0 +1,17 @@ +## `src/orcapod/core/streams/` + +### AS4 — Arrow streams accepted invalid system tags +**Status:** resolved +**Severity:** medium +**Issue:** ITL-1341 + +A raw `ArrowTableStream` accepted non-string system tags, null system-tag values, +and incomplete source-id/record-id pairs. These columns could propagate through +operators even though they could not represent a complete provenance ID. + +**Fix:** Validate system tags at construction, including columns nominated +through `system_tag_columns`. Require string values without nulls and check raw +tables for a counterpart at the same provenance path. Source builders nominate +custom tags and add their provenance pair explicitly. Operators and their stores +carry forward system tags from streams whose roles are already established. +Keep the declared field nullability and support custom string system tags. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 6bc905919..4e640cee3 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -53,7 +53,10 @@ from orcapod.core.cached_function_pod import CachedFunctionPod from orcapod.core.data_function import PYTHON_FUNCTION, declaration_for from orcapod.core.result_cache import with_recorded_output_keys -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -4078,7 +4081,7 @@ def _stored_rows_stream( # A fall-through column is the stored tag column in its data role (ITL-1023): # the table states which (ITL-1019). In the stream the binding is the shared # name, so the marker stays with the stored table. - stream = ArrowTableStream( + stream = stream_from_derived_table( without_tag_kind_marks(joined.drop(drop_cols)), tag_columns=self._stored_tag_keys(fetched), data_tags=fetched.data_tags, diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 1bec000ab..b9e3809b4 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -46,7 +46,10 @@ produced_stream, rows_on_read, ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -474,7 +477,7 @@ def _zero_row_table(self, config: ColumnConfig) -> "pa.Table | None": saved = self._saved_zero_row_table() if saved is None: return None - return ArrowTableStream( + return stream_from_derived_table( saved, tag_columns=self.keys()[0], data_tags=stream_data_tags(self), @@ -1316,7 +1319,7 @@ def _stream_over_stored(self, records: "pa.Table") -> ArrowTableStream: pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), pa.array([self.data_context_key] * rows.num_rows, pa.large_string()), ) - return ArrowTableStream( + return stream_from_derived_table( rows, tag_columns=self.keys()[0], data_tags=self.declared_data_tags(), @@ -2217,7 +2220,7 @@ def as_table( return current.as_table(columns=columns, all_info=all_info) # Every node, one with an operator or one rebuilt without it, from the one # builder of its zero-row table (``_make_empty_table``). - empty_stream = ArrowTableStream( + empty_stream = stream_from_derived_table( self._make_empty_table(), tag_columns=self.keys()[0], data_tags=stream_data_tags(self), diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 903dd3fd0..a73b258a7 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -33,7 +33,10 @@ ) from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.sources.base import RootSource, table_is_rows -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, CompleteStreamFeed, @@ -1935,7 +1938,7 @@ def _declared_stream( *table* must hold the system-tag, source-info and context columns, so the stream selects, sorts and hashes the declared rows as any stream does. """ - return ArrowTableStream( + return stream_from_derived_table( form.apply(table), tag_columns=tuple(self._tag_schema.keys()), data_context=source.data_context, # pyright: ignore[reportAttributeAccessIssue] # StreamProtocol omits data_context, which every concrete stream provides (ITL-844) diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 9af218e81..925891d76 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -15,7 +15,7 @@ from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.column_selection import is_meta_column from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -330,7 +330,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: "sort_by_tags": False, } ) - return ArrowTableStream( + return stream_from_derived_table( self._with_constants(table, tag_keys, data_context.type_converter), tag_columns=[*tag_keys, *self._tags], data_tags=stream_data_tags(stream), diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 7a653251a..710b19106 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -22,7 +22,7 @@ finish_operator, ) from orcapod.core.data_tags import stream_data_tags -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash @@ -202,7 +202,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ) # A data-tag stays a data-tag: the same list in both roles. - return ArrowTableStream( + return stream_from_derived_table( batched_table, tag_columns=tag_columns, data_context=stream.data_context, diff --git a/src/orcapod/core/operators/column_selection.py b/src/orcapod/core/operators/column_selection.py index cbc6570b8..87c35c107 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -7,7 +7,7 @@ from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import stream_data_tags, warn_materialized -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -106,7 +106,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: [c for c in tags_to_drop if c not in data_tags] ) - return ArrowTableStream( + return stream_from_derived_table( modified_table, tag_columns=new_tag_columns, data_tags=[c for c in data_tags if c in new_tag_columns], @@ -249,7 +249,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: + associated_source_fields ) - return ArrowTableStream( + return stream_from_derived_table( modified_table, tag_columns=tag_columns, data_tags=[c for c in data_tags if c not in data_columns_to_drop], @@ -404,7 +404,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: [c for c in columns_to_drop if c not in data_tags] ) - return ArrowTableStream( + return stream_from_derived_table( modified_table, tag_columns=new_tag_columns, data_tags=[c for c in data_tags if c in new_tag_columns], @@ -550,7 +550,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: + associated_source_columns ) - return ArrowTableStream( + return stream_from_derived_table( modified_table, tag_columns=tag_columns, data_tags=[c for c in data_tags if c not in columns_to_drop], @@ -787,7 +787,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: *data_removed, *(f"{constants.SOURCE_PREFIX}{c}" for c in data_removed), } - return ArrowTableStream( + return stream_from_derived_table( table.drop_columns( [ c diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 1e7840935..46d82a6a3 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -15,7 +15,7 @@ from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.datagrams import Data, Tag from orcapod.core.operators.base import UnaryOperator -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -325,7 +325,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: } ) tag_columns, data_columns = stream.keys() - return ArrowTableStream( + return stream_from_derived_table( self._narrow_table(table, self._target_columns(tag_columns, data_columns)), tag_columns=tag_columns, data_tags=stream_data_tags(stream), diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index e5a4fa1a8..17e97ee11 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -21,7 +21,7 @@ filter_table, ) from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -253,7 +253,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ) tag_columns, data_columns = stream.keys() self._check_arrow(table.schema, _user_columns(tag_columns, data_columns)) - return ArrowTableStream( + return stream_from_derived_table( filter_table(table, self._condition), tag_columns=tag_columns, data_tags=stream_data_tags(stream), diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 0b48a08dd..2e7e42788 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -8,7 +8,7 @@ from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import PolarsFilterWarning from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema @@ -128,7 +128,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: filtered_table, pa.schema(input_fields) ) - return ArrowTableStream( + return stream_from_derived_table( filtered_table, tag_columns=stream.keys()[0], data_tags=stream_data_tags(stream), diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index c544fee70..c0080d639 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -18,7 +18,7 @@ ) from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import stream_data_tags -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.core.streams.base import typed_zero_row_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol @@ -568,7 +568,7 @@ def folded(c: str) -> pa.Array[Any]: grouped_table = grouped_table.select( [*keys, *(c for c in grouped_table.column_names if c not in keys)] ) - return ArrowTableStream( + return stream_from_derived_table( grouped_table, tag_columns=keys, data_context=stream.data_context, diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index c5d133f33..94f6b11cc 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -15,7 +15,7 @@ from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.base import ProjectionType, UnaryOperator from orcapod.system_constants import constants -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.types import ColumnConfig, ContentHash, DataType, Schema, SourceInfoValue @@ -471,7 +471,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: else: output_schema = input_schema.append(element_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized output_schema = output_schema.append(token_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized - return ArrowTableStream( + return stream_from_derived_table( self._in_row_order(output_schema.empty_table(), tag_columns), tag_columns=tag_columns, data_context=stream.data_context, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 2dc5bfe51..870b75784 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -38,7 +38,10 @@ reconcile_key_nullability, ) from orcapod.core.datagrams import Tag -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -798,7 +801,7 @@ def _join_result_stream( data_tags=data_tags, inferred_system_tags=inferred, ) - return ArrowTableStream( + return stream_from_derived_table( result_table, tag_columns=tag_columns, data_tags=data_tags ) @@ -1860,7 +1863,12 @@ def __init__( data_tags: Collection[str], inferred_system_tags: frozenset[str], ) -> None: - super().__init__(table, tag_columns=tag_columns, data_tags=data_tags) + super().__init__( + table, + tag_columns=tag_columns, + data_tags=data_tags, + _system_tags_are_derived=True, + ) self._inferred_system_tags = inferred_system_tags def _iter_tags(self, table: pa.Table) -> Iterator[Tag]: diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index fa89ec4a5..d4d4186ec 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -9,7 +9,7 @@ require_a_data_column, ) from orcapod.core.data_tags import stream_data_tags -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -228,7 +228,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ] ) - return ArrowTableStream( + return stream_from_derived_table( renamed_table, tag_columns=tag_columns, data_tags=[ @@ -511,7 +511,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: new_data_tags = [self.name_map.get(c, c) for c in data_tags] if self.drop_unmapped: new_data_tags = [c for c in new_data_tags if c in new_tag_columns] - return ArrowTableStream( + return stream_from_derived_table( renamed_table, tag_columns=new_tag_columns, data_tags=new_data_tags, @@ -828,7 +828,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: for c, t in data_renames.items() }, } - return ArrowTableStream( + return stream_from_derived_table( table.rename_columns([renames.get(c, c) for c in table.column_names]), tag_columns=[ tag_renames.get(c, c) for c in tag_columns if c not in tags_dropped diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index e84ed0300..479e17c67 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -30,7 +30,7 @@ data_tag_names, stream_data_tags, ) -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants @@ -604,7 +604,7 @@ def binary_static_process( ], schema=result_schema, ) - return ArrowTableStream( + return stream_from_derived_table( joined, tag_columns=tuple(tag_cols), data_tags=data_tag_names(tag_schema, data_schema), diff --git a/src/orcapod/core/operators/meta_columns.py b/src/orcapod/core/operators/meta_columns.py index 674d55e46..dafc5e059 100644 --- a/src/orcapod/core/operators/meta_columns.py +++ b/src/orcapod/core/operators/meta_columns.py @@ -19,7 +19,7 @@ from orcapod.channels import WritableChannel from orcapod.core.data_tags import stream_data_tags, with_data_tags_first -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import Schema @@ -116,7 +116,7 @@ def without_input_meta( columns={"source": True, "system_tags": True, "context": True} ) tag_columns = stream.keys()[0] - return ArrowTableStream( + return stream_from_derived_table( without_meta_columns(table, tag_columns), tag_columns=tag_columns, # A data-tag (ITL-1023) keeps its data role. diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 5752ec88e..9ec499169 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -14,7 +14,7 @@ from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel from orcapod.core.operators.base import ProjectionType, UnaryOperator -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol @@ -428,7 +428,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: else: output_schema = input_schema.append(value_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized output_schema = output_schema.append(token_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized - return ArrowTableStream( + return stream_from_derived_table( self._in_row_order(output_schema.empty_table(), tag_columns), tag_columns=tag_columns, data_context=stream.data_context, diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index d760f5865..87a0fb13f 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -39,7 +39,7 @@ without_meta_columns, ) from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError, RejoinDifferingColumnWarning from orcapod.protocols.core_protocols import ( DataProtocol, @@ -467,7 +467,7 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: + data_order + [name for name in table.column_names if name not in listed] ) - return ArrowTableStream( + return stream_from_derived_table( result_table, tag_columns=tuple(tag_order), data_tags=data_tag_names(tag_schema, data_schema), diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index d19971bc4..a91c0e624 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -21,7 +21,7 @@ ) from orcapod.core.operators.key_nullability import reconcile_key_nullability from orcapod.core.operators.match_keys import frozen_scalar -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError, SemiJoinIgnoredColumnWarning from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.protocols.core_protocols.trackers import TrackerManagerProtocol @@ -270,7 +270,7 @@ def binary_static_process( ) semi_joined_table = left_table.take(kept.get_column(_LEFT_ROW).to_arrow()) - return ArrowTableStream( + return stream_from_derived_table( semi_joined_table, tag_columns=tuple(left_tag_schema.keys()), data_tags=stream_data_tags(left_stream), diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 15e109357..da34ea071 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -44,7 +44,10 @@ warn_provisional_operator, ) from orcapod.utils.provisional import note_provisional_use, provisional_class_name -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -473,7 +476,7 @@ def _zero_rows_in_row_order(result: StreamProtocol) -> StreamProtocol: table = StaticOutputOperatorPod._in_row_order( result.as_table(columns=ZERO_ROW_INPUT_COLUMNS), tag_keys ) - return ArrowTableStream( + return stream_from_derived_table( table, tag_columns=tag_keys, data_tags=stream_data_tags(result), @@ -496,7 +499,7 @@ def _kept_output( def _keep_output_table(table: pa.Table, result: StreamProtocol) -> ArrowTableStream: """Put the result table in row order using its declared fields.""" tag_keys = result.keys()[0] - return ArrowTableStream( + return stream_from_derived_table( StaticOutputOperatorPod._in_row_order(table, tag_keys), tag_columns=tag_keys, data_tags=stream_data_tags(result), @@ -695,7 +698,7 @@ def zero_row_result(self, *inputs: StreamProtocol) -> StreamProtocol: for field in schema ] ) - return ArrowTableStream( + return stream_from_derived_table( normalized.empty_table(), tag_columns=only.keys()[0], data_tags=stream_data_tags(only), @@ -744,7 +747,9 @@ def _stream_over_row_table( table, tag_keys, data_tags = row_table # No ``source_info`` argument: the table's own ``_source_*`` columns # pass through, one value per row. - return ArrowTableStream(table, tag_columns=tag_keys, data_tags=data_tags) + return stream_from_derived_table( + table, tag_columns=tag_keys, data_tags=data_tags + ) @staticmethod def _materialize_upstream( @@ -859,7 +864,7 @@ def _as_upstream_stream( else: # No ``source_info`` argument: the table's own ``_source_*`` columns # pass through, one value per row. - stream = ArrowTableStream( + stream = stream_from_derived_table( table, tag_columns=tag_keys, data_tags=data_tags, @@ -1643,6 +1648,7 @@ def __init__( data_tags=data_tags, upstreams=upstreams, data_context=data_context, + _system_tags_are_derived=True, ) self._input_pipeline_hash: ContentHash = pipeline_hash @@ -1808,7 +1814,7 @@ def _typed_zero_row_table(self) -> pa.Table | None: inputs.append(rows) continue inputs.append( - ArrowTableStream( + stream_from_derived_table( table, tag_columns=upstream.keys()[0], data_tags=stream_data_tags(upstream), diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 911fefc36..2e6b431b6 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -9,7 +9,7 @@ from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import require_taggable_type, stream_data_tags -from orcapod.core.streams import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants @@ -217,7 +217,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: "sort_by_tags": False, } ) - return ArrowTableStream( + return stream_from_derived_table( table, tag_columns=[*tag_columns, *self.columns], data_tags=[*stream_data_tags(stream), *self.columns], diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 84512e567..5c00d1641 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -24,7 +24,10 @@ InputValidationError, UnstorableColumnError, ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.core.streams.base import ( typed_arrow_schemas, check_head_size, @@ -701,7 +704,7 @@ def _build_merged_stream(self) -> ArrowTableStream: tag_keys = self._source.keys()[0] # Cached rows are this source's: give them its data context, not the default. - return ArrowTableStream( + return stream_from_derived_table( all_records, tag_columns=tag_keys, data_context=self.data_context, diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index b92d03ffe..8e270cbeb 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -25,7 +25,10 @@ SourceStreamBuilder, normalize_record_id_columns, ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -864,7 +867,7 @@ def _stream_over(self, table: "pa.Table") -> ArrowTableStream: """Return this source's stream over the origin rows ``table``.""" if self._tags_as_data is not None: return self._derive_from(table, self._tags_as_data) - return ArrowTableStream( + return stream_from_derived_table( validate_source_table(table), tag_columns=self._origin.keys()[0], data_tags=self._data_tags(), diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index a2f154dec..25d83dab6 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -32,6 +32,7 @@ require_supported_nullable_types, validate_source_table, ) +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -576,8 +577,6 @@ def _typed_zero_row_table(self) -> pa.Table | None: knows only the Python schema ``impl.schema()`` declares, which cannot say an Arrow type such as ``int8`` (a known limitation, ITL-912). """ - from orcapod.core.streams.arrow_table_stream import ArrowTableStream - batches = list(self._batches) # snapshot, as in ``_get_combined_stream`` if not batches: return None @@ -588,7 +587,7 @@ def _typed_zero_row_table(self) -> pa.Table | None: table = typed_zero_row_table(batch) if table is None: return None - zero_rows = ArrowTableStream( + zero_rows = stream_from_derived_table( table=validate_source_table(table), tag_columns=self._tag_columns ) result = zero_rows if result is None else self._combine(result, zero_rows) @@ -1102,8 +1101,6 @@ def _combine( SchemaInconsistencyError: If the schemas are incompatible (see ``_validate_combining_schemas``). """ - from orcapod.core.streams.arrow_table_stream import ArrowTableStream - self._validate_combining_schemas(existing, new_stream) combined = pa.concat_tables( @@ -1113,7 +1110,7 @@ def _combine( ], promote_options="default", ) - return ArrowTableStream( + return stream_from_derived_table( table=validate_source_table(combined), tag_columns=self._tag_columns ) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dcdd309c5..a82066160 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -68,7 +68,10 @@ normalize_record_id_columns, row_identifiers, ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import ( + ArrowTableStream, + stream_from_derived_table, +) from orcapod.core.streams.base import check_head_size from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( @@ -1030,7 +1033,7 @@ def _whole_table( tables = [stream.as_table(columns=enriched) for stream in streams] if not tables: return self._stream.as_table(columns=columns, all_info=all_info) - whole = ArrowTableStream( + whole = stream_from_derived_table( table=pa.concat_tables(tables), tag_columns=self._tag_columns, system_tag_columns=self._system_tag_columns, diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 743de64aa..fa562cc15 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -22,7 +22,7 @@ parse_kind_part, require_source_name, ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.streams.arrow_table_stream import stream_from_derived_table from orcapod.errors import InputValidationError, RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.system_constants import constants @@ -32,6 +32,7 @@ if TYPE_CHECKING: from orcapod.contexts import DataContext + from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.hashing_protocols import ArrowHasherProtocol @@ -816,7 +817,7 @@ def attach_provenance( row_identifiers, ) # Nullable flags are already correct — the caller set them. - return ArrowTableStream( + return stream_from_derived_table( table=table, tag_columns=tag_columns, system_tag_columns=system_tag_columns, diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 5181ba3e0..5e8cb46c2 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -9,6 +9,7 @@ from orcapod.hashing.orcapod_table import OrcapodTable from orcapod import contexts +from orcapod.errors import InputValidationError from orcapod.core.datagrams import Data, Tag from orcapod.core.identity_chains import refuse_identity_io from orcapod.core.streams.base import ( @@ -47,6 +48,10 @@ class ArrowTableStream(StreamBase): stream, so every source (each builds its stream here, from a user's Arrow table too) and every operator result presents large types. Width, nullability, field metadata and logical types are kept; large and non-large variants hash identically. + + System tags contain only non-null strings. In a raw table a source-id or + record-id column must be paired with its counterpart at the same provenance + path. """ # The table's rows are held, not computed: a run() view says "all N rows", as @@ -62,6 +67,8 @@ def __init__( producer: PodProtocol | None = None, upstreams: tuple[StreamProtocol, ...] = (), data_tags: Collection[str] = (), + *, + _system_tags_are_derived: bool = False, **kwargs: Any, ) -> None: """Wrap ``table`` as a stream. @@ -76,6 +83,9 @@ def __init__( data_tags: The tag columns that are data-tags: each is also a data column of the same name, stored once (specification "Referential Tags", section 4). Must be a subset of ``tag_columns``. + _system_tags_are_derived: The library built the table and established + the system-tag roles. Custom tags can have names indistinguishable + from provenance IDs. **kwargs: Passed to ``StreamBase``. Raises: @@ -87,14 +97,14 @@ def __init__( Also if a source-info token column does not have the shape of its data column, or a token with a list layer is null (``schema_utils.token_layers_fit``, ITL-1491). + Also if a system-tag column is not a string, contains + null values, or lacks its matching source-id or record-id column. """ super().__init__(**kwargs) self._producer = producer self._upstreams = upstreams - # Every table Orcapod presents is in its large variants (ITL-1122). - table = arrow_utils.normalize_table_to_large_types(table, keep_null=True) # Dictionary-encoded columns are not currently supported (ITL-1264, # ITL-1277): every source and operator result becomes a stream here, so this # refuses them all, tags and data alike. @@ -110,6 +120,17 @@ def __init__( found, tag_columns, data_tags, system_tag_columns ) + system_tag_renames = { + name: f"{constants.SYSTEM_TAG_PREFIX}{name}" for name in system_tag_columns + } + # Check validity before a large-variant cast can reject a null under a + # non-nullable field with an Arrow error that omits the column name. + self._require_valid_system_tags( + table, system_tag_renames, require_pairs=not _system_tags_are_derived + ) + # Every table Orcapod presents is in its large variants (ITL-1122). + table = arrow_utils.normalize_table_to_large_types(table, keep_null=True) + data_table, data_context_table = arrow_utils.split_by_column_groups( table, [constants.CONTEXT_KEY] ) @@ -142,13 +163,9 @@ def __init__( self._system_tag_columns = tuple( c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) ) - if len(system_tag_columns) > 0: - # rename system_tag_columns - column_name_map = { - c: f"{constants.SYSTEM_TAG_PREFIX}{c}" for c in system_tag_columns - } + if system_tag_renames: table = table.rename_columns( - [column_name_map.get(c, c) for c in table.column_names] + [system_tag_renames.get(c, c) for c in table.column_names] ) self._system_tag_columns += tuple( @@ -236,6 +253,68 @@ def __init__( self._cached_elements: list[tuple[TagProtocol, Data]] | None = None self._update_modified_time() # set modified time to now + @staticmethod + def _require_valid_system_tags( + table: pa.Table, renames: dict[str, str], *, require_pairs: bool + ) -> None: + """Require non-null string values and complete provenance pairs. + + Args: + table: The input table, before normalization. + renames: The final names of nominated system-tag columns. + require_pairs: Infer provenance IDs from their names in a raw table. + + Raises: + InputValidationError: Naming a non-string, null or unpaired system tag. + """ + system_tags = { + index: name + for index, original in enumerate(table.column_names) + if original != constants.CONTEXT_KEY + and (name := renames.get(original, original)).startswith( + constants.SYSTEM_TAG_PREFIX + ) + } + if not system_tags: + return + names = set(system_tags.values()) + schema = table.schema + source_prefix = ( + constants.SYSTEM_TAG_SOURCE_ID_PREFIX + constants.BLOCK_SEPARATOR + ) + record_prefix = ( + constants.SYSTEM_TAG_RECORD_ID_PREFIX + constants.BLOCK_SEPARATOR + ) + for index, name in system_tags.items(): + field = schema.field(index) + if not ( + pa.types.is_string(field.type) + or pa.types.is_large_string(field.type) + or pa.types.is_string_view(field.type) + ): + raise InputValidationError( + f"System-tag column {name!r} must be a string, got {field.type}." + ) + if table.column(index).null_count: + raise InputValidationError( + f"System-tag column {name!r} contains null values." + ) + + if not require_pairs: + continue + kind, sep, path = name.partition(constants.BLOCK_SEPARATOR) + prefix = kind + sep + if prefix == source_prefix: + partner = record_prefix + path + elif prefix == record_prefix: + partner = source_prefix + path + else: + continue + if partner not in names: + raise InputValidationError( + f"System-tag column {name!r} requires matching column {partner!r}." + ) + @property def _content_hash_depends_on_bindings(self) -> bool: """Raw tables have no producer or upstream bindings in their legacy hash.""" @@ -530,3 +609,32 @@ def __repr__(self) -> str: f"{self.__class__.__name__}(table={self._table.column_names}, " f"tag_columns={self._tag_columns}{refs})" ) + + +def stream_from_derived_table( + table: pa.Table, + *, + tag_columns: Collection[str] = (), + system_tag_columns: Collection[str] = (), + data_tags: Collection[str] = (), + producer: PodProtocol | None = None, + upstreams: tuple[StreamProtocol, ...] = (), + data_context: str | contexts.DataContext | None = None, +) -> ArrowTableStream: + """Wrap a source, operator, row transport or store table built by the library. + + A source nominates its custom tags and adds its own provenance pair. A + derived table carries existing system tags, possibly with added suffixes. + In both cases a custom tag may have the same prefix and path as an ID. + Validate the text while retaining the roles established by the caller. + """ + return ArrowTableStream( + table, + tag_columns=tag_columns, + system_tag_columns=system_tag_columns, + data_tags=data_tags, + producer=producer, + upstreams=upstreams, + data_context=data_context, + _system_tags_are_derived=True, + ) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 25ceb9793..c83ea043f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1781,12 +1781,12 @@ def _zero_row_table(self, config: ColumnConfig) -> pa.Table | None: The table, or ``None`` when the stream cannot type it without rows. """ from orcapod.core.data_tags import stream_data_tags - from orcapod.core.streams.arrow_table_stream import ArrowTableStream + from orcapod.core.streams.arrow_table_stream import stream_from_derived_table typed = typed_zero_row_table(self) if typed is None: return None - return ArrowTableStream( + return stream_from_derived_table( typed, tag_columns=self.keys()[0], data_tags=stream_data_tags(self), diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index df37f0765..2be341b87 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -76,7 +76,9 @@ def test_raw_system_tag_fields_survive_a_record_batch_channel() -> None: """A channel carries a stream's system-tag Arrow fields through to its rows.""" system = pa.schema( [ - pa.field("_tag_rank", pa.int8(), False, metadata={b"purpose": b"rank"}), + pa.field( + "_tag_rank", pa.large_string(), False, metadata={b"purpose": b"rank"} + ), pa.field("_tag_label", pa.large_string(), True), ] ) @@ -93,7 +95,7 @@ def test_raw_system_tag_fields_survive_a_record_batch_channel() -> None: [ pa.array(values, field.type) for values, field in zip( - (["a", "b"], [1, 2], [3, 4], [5, 6], [7, 8], ["a", None]), + (["a", "b"], [1, 2], [3, 4], [5, 6], ["7", "8"], ["a", "b"]), schema, strict=True, ) @@ -2394,13 +2396,13 @@ async def read() -> Any: def test_channel_keeps_first_system_tag_declaration_and_entry_id() -> None: - """A later batch containing a null cannot change an earlier row's entry ID.""" + """A later batch cannot change an earlier row's entry ID.""" from orcapod.core import row_ids name = "_tag_custom" field = pa.field(name, pa.large_string(), metadata={b"owner": b"test"}) table = pa.Table.from_arrays( - [pa.array([1, 2]), pa.array([7, 8]), pa.array(["kept", None], field.type)], + [pa.array([1, 2]), pa.array([7, 8]), pa.array(["kept", "later"], field.type)], schema=pa.schema([pa.field("k", pa.int64()), pa.field("x", pa.int64()), field]), ) stream = _UntypedStream(table, tag_columns=["k"]) diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py index a170a75e3..ba224bce7 100644 --- a/tests/test_channels/test_record_batch_review_findings.py +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -941,8 +941,8 @@ async def write() -> None: asyncio.run(write()) -def test_a_system_tag_cannot_hold_a_null_in_a_required_struct_child() -> None: - name = "_tag_extra" +def test_a_user_tag_cannot_hold_a_null_in_a_required_struct_child() -> None: + name = "extra" kind = pa.struct( [pa.field("required", pa.int64(), nullable=False, metadata={b"unit": b"m"})] ) @@ -954,7 +954,7 @@ def test_a_system_tag_cannot_hold_a_null_in_a_required_struct_child() -> None: name: pa.array([{"required": 1}, None], type=kind), } ), - tag_columns=["k"], + tag_columns=["k", name], ) (good,) = pa.Table.from_batches(batches_of(stream)).combine_chunks().to_batches() index = good.schema.get_field_index(name) @@ -966,7 +966,7 @@ def test_a_system_tag_cannot_hold_a_null_in_a_required_struct_child() -> None: async def write() -> None: output = OutputChannel(stream) - with pytest.raises(ValueError, match=r"_tag_extra.*required.*not nullable"): + with pytest.raises(ValueError, match=r"extra.*required.*not nullable"): await output.send(bad) await output.send(good) await output.close() diff --git a/tests/test_core/data_tags/test_operator_node_storage.py b/tests/test_core/data_tags/test_operator_node_storage.py index e76755f53..65f3f073c 100644 --- a/tests/test_core/data_tags/test_operator_node_storage.py +++ b/tests/test_core/data_tags/test_operator_node_storage.py @@ -565,7 +565,7 @@ def test_merge_join_cache_keeps_declared_system_tag_fields( from orcapod.streams import ArrowTableStream left = ArrowTableStream( - pa.table({"k": [1, 2], "x": [3, 4], "_tag_custom": ["one", None]}), + pa.table({"k": [1, 2], "x": [3, 4], "_tag_custom": ["one", "two"]}), tag_columns=["k"], ) right = ArrowTableStream(pa.table({"k": [1, 2], "y": [5, 6]}), tag_columns=["k"]) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index b915bc59e..9448adfd2 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -514,10 +514,7 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: CASES = [ # Rejoin leaves out rows of one origin row that differ in a shared column; equal - # floats of different bits match (ITL-1355). A null system tag is not here: rows - # holding one cannot be rebuilt into a table by the barrier of any operator (their - # system-tag field is nullable, the other rows' is not), before Rejoin sees them; - # the sync path is tested in test_rejoin. + # floats of different bits match (ITL-1355). Case( "rejoin_differing_tag", Rejoin, @@ -1098,7 +1095,7 @@ def test_tied_join_table_keeps_declared_identifier_fields( ) inputs = [] empty_inputs = [] - for source, records in (("a", [None, "q"]), ("b", ["r", "t"]), ("c", ["s", "u"])): + for source, records in (("a", ["p", "q"]), ("b", ["r", "t"]), ("c", ["s", "u"])): field_metadata: dict[bytes | str, bytes | str] | None = ( None if metadata == "none" @@ -1490,20 +1487,21 @@ async def run() -> list[Row]: def test_tied_join_with_asymmetric_empty_input_matches_main( arity: int, mode: str ) -> None: - """Keep main's zero-row layout when a tied input omits a record ID.""" + """Keep the zero-row layout when a tied input omits its identifier pair.""" inputs = _tied_join_inputs(arity) columns = {"system_tags": True} empty_table = ( - inputs[-1].as_table(columns=columns).drop(["_tag_record_id"]).slice(0, 0) + inputs[-1] + .as_table(columns=columns) + .drop(["_tag_source_id", "_tag_record_id"]) + .slice(0, 0) ) inputs[-1] = ArrowTableStream(empty_table, tag_columns=["k"], data_tags=["k"]) for order in itertools.permutations(inputs): join = Join() tags, _ = join.output_schema(*order, columns=columns) - assert ( - len([name for name in tags if name.startswith("_tag_record_id")]) - == arity - 1 - ) + for prefix in ("_tag_source_id", "_tag_record_id"): + assert sum(name.startswith(prefix) for name in tags) == arity - 1 table, rows = _tied_join_outputs(mode, join, order) assert not rows and not table.num_rows if mode != "rows": @@ -1566,7 +1564,7 @@ def test_join_suffixes_distinguish_hashes_with_the_same_prefix(reverse: bool) -> @pytest.mark.parametrize("reverse_columns", [False, True]) -def test_raw_stream_rows_keep_system_tag_width_flags_and_metadata( +def test_raw_stream_rows_keep_system_tag_flags_and_metadata( reverse_columns: bool, ) -> None: """Keep both system tags and their Arrow fields through a cache-free copy.""" @@ -1576,14 +1574,16 @@ def test_raw_stream_rows_keep_system_tag_width_flags_and_metadata( pa.field("g", pa.large_string(), False), pa.field("x", pa.int16(), False), pa.field("y", pa.large_string(), True), - pa.field("_tag_rank", pa.int8(), False, metadata={b"purpose": b"rank"}), + pa.field( + "_tag_rank", pa.large_string(), False, metadata={b"purpose": b"rank"} + ), pa.field("_tag_label", pa.large_string(), True), ] ) table = pa.Table.from_pylist( [ - {"k": 1, "g": "a", "x": 4, "y": "x", "_tag_rank": 7, "_tag_label": "a"}, - {"k": 2, "g": "b", "x": 5, "y": None, "_tag_rank": 8, "_tag_label": None}, + {"k": 1, "g": "a", "x": 4, "y": "x", "_tag_rank": "7", "_tag_label": "a"}, + {"k": 2, "g": "b", "x": 5, "y": None, "_tag_rank": "8", "_tag_label": "b"}, ], schema=schema, ) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 95a1ce7f1..12d67d9e9 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -508,6 +508,7 @@ async def go() -> tuple[StreamProtocol, set[bool]]: # --- The row-built form, F (stage 2, ITL-1360) --------------------------------------------- SYSTEM_TAG = "_tag_source_id::abc" +RECORD_ID_TAG = "_tag_record_id::abc" def test_the_provenance_columns_have_the_row_built_schema() -> None: @@ -518,6 +519,7 @@ def test_the_provenance_columns_have_the_row_built_schema() -> None: [ pa.field("k", pa.int64()), pa.field(SYSTEM_TAG, pa.large_string(), metadata={"m": "1"}), + pa.field(RECORD_ID_TAG, pa.large_string(), nullable=False), # A list token needs list data (the token-shape rule, ITL-1491). pa.field("x", pa.large_list(pa.int64())), pa.field("z", pa.int64()), @@ -533,6 +535,7 @@ def test_the_provenance_columns_have_the_row_built_schema() -> None: [ pa.array([1, 2], pa.int64()), pa.array(["s", "s"], pa.large_string()), + pa.array(["r1", "r2"], pa.large_string()), pa.array([[1], [2]], pa.large_list(pa.int64())), pa.array([3, 4], pa.int64()), pa.array([5, 6], pa.int64()), @@ -672,12 +675,13 @@ def test_empty_source_info_lists_keep_their_columns_type(layout: str) -> None: def test_a_raw_nullable_system_tag_keeps_its_field_in_a_job_and_channel() -> None: - """The stream's nullable string field applies to rows with and without a value.""" + """The stream keeps its nullable string field when both rows have a value.""" raw = ArrowTableStream( pa.table( { "k": pa.array([1, 2], pa.int64()), - SYSTEM_TAG: pa.array(["s", None], pa.large_string()), + SYSTEM_TAG: pa.array(["s", "t"], pa.large_string()), + RECORD_ID_TAG: pa.array(["r1", "r2"], pa.large_string()), "x": pa.array([1, 2], pa.int64()), "z": pa.array([3, 4], pa.int64()), } diff --git a/tests/test_core/operators/test_rejoin.py b/tests/test_core/operators/test_rejoin.py index 44251bf5d..0a4200690 100644 --- a/tests/test_core/operators/test_rejoin.py +++ b/tests/test_core/operators/test_rejoin.py @@ -45,6 +45,7 @@ from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.system_constants import constants +from orcapod.utils import arrow_utils pytestmark = [ pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), @@ -438,16 +439,19 @@ def test_stated_system_tags_are_compared_even_beside_an_input_that_states_none() _ = Rejoin()(a, b, c) -def _float_provenance(origin: list[float], data: str) -> ArrowTableStream: - """A raw stream whose one system tag is a float, with data column ``data``.""" +def _float_tag_branch(level: list[float], data: str) -> ArrowTableStream: + """A branch with a float user tag and data column ``data``.""" table = pa.table( { "g": pa.array([1, 2], pa.int64()), - "origin": pa.array(origin, pa.float64()), + "level": pa.array(level, pa.float64()), data: pa.array([0.5, 0.25], pa.float64()), } ) - return ArrowTableStream(table, tag_columns=["g"], system_tag_columns=["origin"]) + return ArrowTableStream( + arrow_utils.add_system_tag_columns(table, "origin", "source", ["r1", "r2"]), + tag_columns=["g", "level"], + ) OTHER_CONTEXT = "std:v1:test-other" @@ -764,18 +768,19 @@ def test_several_shared_tags_several_inputs_in_every_order() -> None: assert _units(_rejoined(*order)[0]) == kept -def test_a_null_in_a_system_tag_matches_nothing() -> None: - """Provenance is never null: rows with a null in a system-tag column match nothing - and are left out, in both inputs; the other rows are put together. Nothing is - refused and nothing warns (no shared column differs).""" +def test_different_source_ids_match_nothing() -> None: + """Rows from different sources do not match, even with matching record IDs.""" origin = _origin() source_id = next(name for name in _system_tags(_source()) if "source_id" in name) values = origin.column(source_id).to_pylist() - nulled: dict[str, Any] = { - source_id: pa.array([None, None, *values[2:]], pa.large_string()) + left: dict[str, Any] = { + source_id: pa.array(["a", "a", *values[2:]], pa.large_string()) } - a = _branch(origin, ["rate"], **nulled) - b = _branch(origin, ["depth"], **nulled) + right: dict[str, Any] = { + source_id: pa.array(["b", "b", *values[2:]], pa.large_string()) + } + a = _branch(origin, ["rate"], **left) + b = _branch(origin, ["depth"], **right) whole = _branch(origin, ["area"]) for inputs in ((a, b), (b, a), (a, whole), (whole, a), (a, whole, b)): result, warned = _rejoined(*inputs) @@ -784,8 +789,8 @@ def test_a_null_in_a_system_tag_matches_nothing() -> None: def test_a_null_in_another_shared_column_equals_a_null() -> None: - """Only a system tag's null matches nothing. Rows of one origin row that both hold - no value in a shared tag, or in a shared data-tag's source info, are put together.""" + """Rows of one origin row that both hold no value in a shared tag or source-info + column are put together.""" origin = _origin() holes = pa.array( ["s0", None, "s2", None, "s1", "s2", "s0", "s1"], pa.large_string() @@ -1023,22 +1028,18 @@ def test_the_first_input_is_the_first_by_pipeline_hash_whatever_the_argument_ord ): """Inputs of different pipeline hashes are taken in the order of those hashes: the shared column keeps the same input's bits in both argument orders. Here the shared - column is a float system tag, ``-0.0`` in one input and ``0.0`` in the other.""" - a = _float_provenance([0.0, 1.0], "x") - b = _float_provenance([-0.0, 1.0], "y") + column is a float user tag, ``-0.0`` in one input and ``0.0`` in the other.""" + a = _float_tag_branch([0.0, 1.0], "x") + b = _float_tag_branch([-0.0, 1.0], "y") assert a.pipeline_hash() != b.pipeline_hash() first = _first(a, b) - wanted = _bits( - first.as_table(columns={"system_tags": True}) - .column("_tag_origin") - .to_pylist()[0] - ) + wanted = _bits(first.as_table().column("level").to_pylist()[0]) for inputs in ((a, b), (b, a)): result, warned = _rejoined(*inputs) table = result.as_table(columns={"system_tags": True}) assert table.num_rows == 2 and not warned by_g = dict( - zip(table.column("g").to_pylist(), table.column("_tag_origin").to_pylist()) + zip(table.column("g").to_pylist(), table.column("level").to_pylist()) ) assert _bits(by_g[1]) == wanted diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 243263761..22566c853 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -149,12 +149,14 @@ def _raw_stream() -> ArrowTableStream: its own source info. """ system_tag = f"{constants.SYSTEM_TAG_PREFIX}source_id::abc" + record_id = f"{constants.SYSTEM_TAG_PREFIX}record_id::abc" member = pa.field("member", pa.large_string(), nullable=False) table = pa.table( { "k": pa.array([1, 2], pa.int64()), "j": pa.array(["a", "b"], pa.large_string()), system_tag: pa.array(["s1", "s2"], pa.large_string()), + record_id: pa.array(["r1", "r2"], pa.large_string()), # A list token needs list data (the token-shape rule, ITL-1491). "x": pa.array([[1.0, float("nan")], [2.0]], pa.large_list(pa.float64())), "z": pa.array([3, None], pa.int8()), @@ -466,11 +468,7 @@ def test_a_job_over_tokens_no_value_could_type_alike_completes( def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: - """A system-tag field with a null never reaches a job: a slot refuses the source. - - So F never meets one; ``_rows_to_table`` could not build its rows (two rows would - give the field two nullability flags). - """ + """A slot rejects a nullable ID declaration even when all values are present.""" from orcapod import PipelineJob from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import SourceSpecMismatchError @@ -495,7 +493,7 @@ def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: with_null = table.set_column( position, pa.field(record_id, pa.large_string(), nullable=True), - pa.array(["row_0", None], pa.large_string()), + pa.array(["row_0", "row_1"], pa.large_string()), ) slot = next(label for label in job.nodes if label != "selected") with pytest.raises(SourceSpecMismatchError, match="record_id"): diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 9d4088743..55954dd55 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -917,7 +917,7 @@ def test_join_keeps_nullable_tied_raw_system_tag_fields() -> None: tag_columns=["k"], data_tags=["k"], ) - for source, record in (("a", None), ("b", "r"), ("c", "s")) + for source, record in (("a", "q"), ("b", "r"), ("c", "s")) ) assert len({stream.pipeline_hash() for stream in inputs}) == 1 columns = {"system_tags": True} @@ -1535,7 +1535,7 @@ def test_merge_join_preserves_system_tag_declarations(matched: list[int]) -> Non [ pa.array([1, 2]), pa.array([3, 4]), - pa.array(["one", None], fields[0].type), + pa.array(["one", "two"], fields[0].type), pa.array(["a", "b"], fields[1].type), ], schema=pa.schema( @@ -1619,7 +1619,7 @@ def test_filtering_join_kernels_preserve_system_tag_fields( field = pa.field( name, pa.large_string(), nullable=nullable, metadata={b"owner": b"raw"} ) - values = pa.array(["selected", None if nullable else "another"], field.type) + values = pa.array(["selected", "another"], field.type) left = ArrowTableStream( pa.Table.from_arrays( [pa.array([1, 2]), pa.array([10, 20]), values], diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py index c517d3e50..1a477858a 100644 --- a/tests/test_core/operators/test_streaming_rejoin.py +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -130,7 +130,7 @@ def test_a_shared_tag_that_differs_on_some_rows_matches_only_where_equal() -> No def _hand_branch( - data: str, *, origin: list[str | None], tag: list[int | None] + data: str, *, origin: list[str], tag: list[int | None] ) -> ArrowTableStream: """A hand-built branch: tag ``k``, one system tag, data column ``data``.""" n = len(origin) @@ -147,12 +147,13 @@ def _hand_branch( ) -def test_a_null_system_tag_matches_nothing_and_a_null_tag_equals_a_null() -> None: - # Rows rebuilt from datagrams cannot hold a null system tag (provenance is never - # null), so the oracle here is the sync path over the raw streams, and the - # kernel is fed their tables. - left = _hand_branch("a", origin=["r1", None, "r3", "r4"], tag=[1, 2, None, 4]) - right = _hand_branch("b", origin=["r1", None, "r3", "r4"], tag=[1, 2, None, 5]) +def test_different_origin_rows_do_not_match_and_a_null_tag_equals_a_null() -> None: + left = _hand_branch( + "a", origin=["r1", "left-only", "r3", "r4"], tag=[1, 2, None, 4] + ) + right = _hand_branch( + "b", origin=["r1", "right-only", "r3", "r4"], tag=[1, 2, None, 5] + ) for inputs in ((left, right), (right, left)): expected = _transport(Rejoin().static_process(*inputs)) assert sorted(expected.column("k").to_pylist(), key=str) == [1, None] diff --git a/tests/test_core/streams/test_system_tag_validation.py b/tests/test_core/streams/test_system_tag_validation.py new file mode 100644 index 000000000..251114853 --- /dev/null +++ b/tests/test_core/streams/test_system_tag_validation.py @@ -0,0 +1,229 @@ +"""System-tag validation on raw Arrow streams (ITL-1341).""" + +from __future__ import annotations + +import re +from typing import cast + +import pyarrow as pa +import pytest + +from orcapod.core.operators import Join +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError +from orcapod.sources import ArrowTableSource, DataFrameSource, DictSource +from orcapod.system_constants import constants +from orcapod.utils.arrow_utils import add_system_tag_columns, system_tag_column_names + +SOURCE_ID, RECORD_ID = system_tag_column_names("origin") + + +@pytest.mark.parametrize( + ("dtype", "values", "nullable", "message"), + [ + (pa.float64(), [1.5], False, "string"), + (pa.string(), [None], False, "null values"), + (pa.string(), [None], True, "null values"), + ], +) +@pytest.mark.parametrize("nominated", [False, True]) +def test_invalid_system_tags_are_refused_at_construction( + dtype: pa.DataType, + values: list[object], + nullable: bool, + message: str, + nominated: bool, +) -> None: + """Both ways of defining a system tag validate its field and values.""" + name = "st" if nominated else f"{constants.SYSTEM_TAG_PREFIX}st" + table = add_system_tag_columns(pa.table({"x": [1]}), "origin", "source", ["row"]) + table = table.append_column( + pa.field(name, dtype, nullable=nullable), pa.array(values, type=dtype) + ) + with pytest.raises(InputValidationError, match=rf"_tag_st.*{message}"): + ArrowTableStream(table, system_tag_columns=[name] if nominated else ()) + + +@pytest.mark.parametrize("name", [SOURCE_ID, RECORD_ID]) +def test_a_system_tag_id_requires_its_partner(name: str) -> None: + """Report the present column when either partner is missing.""" + table = pa.table({"x": [1]}).append_column( + pa.field(name, pa.string(), nullable=False), pa.array(["id"]) + ) + with pytest.raises(InputValidationError, match=re.escape(name)): + ArrowTableStream(table) + + +def test_pairing_uses_the_full_provenance_path() -> None: + """A second source ID cannot be paired with a record ID of another path.""" + table = add_system_tag_columns(pa.table({"x": [1]}), "origin", "source", ["row"]) + unpaired, _ = system_tag_column_names("origin::branch:1") + table = table.append_column( + pa.field(unpaired, pa.string(), nullable=False), pa.array(["id"]) + ) + with pytest.raises(InputValidationError, match=re.escape(unpaired)): + ArrowTableStream(table) + + +def test_nullable_string_field_is_preserved_when_values_are_present() -> None: + """Wrapping a raw stream preserves the declaration of a valid string tag.""" + name = f"{constants.SYSTEM_TAG_PREFIX}label" + table = pa.table({"x": [1], name: ["custom"]}) + stream = ArrowTableStream(table) + result = stream.as_table(columns={"system_tags": True}) + assert result.schema.field(name).equals(pa.field(name, pa.large_string())) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("source_type", [ArrowTableSource, DataFrameSource, DictSource]) +@pytest.mark.parametrize("name", ["source_id::external", "record_id::external"]) +async def test_source_preserves_nominated_custom_id_tag( + source_type: type[ArrowTableSource] | type[DataFrameSource] | type[DictSource], + name: str, +) -> None: + """Sources nominate custom tags separately from the pair they generate.""" + table = pa.table({"k": [1, 2], "x": [3, 4]}).append_column( + pa.field(name, pa.string(), nullable=False), pa.array(["a", "b"]) + ) + if issubclass(source_type, DictSource): + source = source_type( + table.to_pylist(), tag_columns=["k"], system_tag_columns=[name] + ) + else: + source = source_type(table, tag_columns=["k"], system_tag_columns=[name]) + + expected_name = f"{constants.SYSTEM_TAG_PREFIX}{name}" + sync = source.as_table(columns={"system_tags": True}) + asynchronous = pa.Table.from_batches(await source.open_channel().collect()) + for result in (sync, asynchronous): + assert result[expected_name].to_pylist() == ["a", "b"] + assert result.schema.field(expected_name).equals( + pa.field(expected_name, pa.large_string(), nullable=False) + ) + + +def test_join_extends_complete_pairs_and_custom_system_tags() -> None: + """Joined output can carry multiple valid pairs and preserve custom tags.""" + left_table = add_system_tag_columns(pa.table({"x": [1]}), "left", "l", ["row"]) + left_table = left_table.append_column( + pa.field("label", pa.string_view(), nullable=False), + pa.array(["custom"], type=pa.string_view()), + ) + right_table = add_system_tag_columns(pa.table({"y": [2]}), "right", "r", ["row"]) + left = ArrowTableStream(left_table, system_tag_columns=["label"]) + right = ArrowTableStream(right_table) + joined = Join()(left, right).as_table(columns={"system_tags": True}) + system_names = [ + name + for name in joined.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + assert len(system_names) == 5 + custom = next(name for name in system_names if name.startswith("_tag_label::")) + assert joined.column(custom).to_pylist() == ["custom"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("custom_name", ["source_id", "record_id"]) +@pytest.mark.parametrize("operation", ["join", "merge_join", "batch", "group_by"]) +@pytest.mark.parametrize("execution", ["sync", "async"]) +@pytest.mark.parametrize("raw", [False, True], ids=["source", "raw"]) +async def test_extended_custom_id_tags_survive_operator_log( + custom_name: str, operation: str, execution: str, raw: bool +) -> None: + """An ordinary custom string tag survives extension, LOG and further operators.""" + from orcapod.channels import Channel, ReadableChannel + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.databases import InMemoryArrowDatabase + from orcapod.operators import Batch, GroupBy, MergeJoin, SelectDataColumns + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) + from orcapod.types import CacheMode + + table = pa.table({"k": [1, 2], "x": [3, 4]}).append_column( + pa.field(custom_name, pa.string(), nullable=False), pa.array(["a", "b"]) + ) + left: StreamProtocol = ( + ArrowTableStream(table, tag_columns=["k"], system_tag_columns=[custom_name]) + if raw + else ArrowTableSource( + table, + tag_columns=["k"], + tag_only_columns=True, + system_tag_columns=[custom_name], + ) + ) + right: StreamProtocol = ArrowTableSource( + pa.table({"k": [1, 2], "y": [5, 6]}), + tag_columns=["k"], + tag_only_columns=True, + ) + if operation == "join": + operator, inputs = Join(), (left, right) + elif operation == "merge_join": + operator, inputs = MergeJoin(), (left, right) + elif operation == "batch": + operator, inputs = Batch(batch_size=1), (left,) + else: + operator, inputs = GroupBy(by=["k"]), (left,) + + config = {"system_tags": True} + expected = operator(*inputs).as_table(columns=config) + suffix = left.pipeline_hash().to_hex() + prefix = f"{constants.SYSTEM_TAG_PREFIX}{custom_name}{constants.BLOCK_SEPARATOR}" + [extended_name] = [ + name + for name in expected.column_names + if name == prefix + suffix + or name.startswith(prefix + suffix + constants.FIELD_SEPARATOR) + and constants.BLOCK_SEPARATOR not in name[len(prefix) :] + ] + assert expected[extended_name].null_count == 0 + projected = SelectDataColumns(["x"])(operator(*inputs)).as_table(columns=config) + assert projected[extended_name].equals(expected[extended_name]) + + store = InMemoryArrowDatabase() + node = OperatorJobNode( + operator, inputs, pipeline_database=store, cache_mode=CacheMode.LOG + ) + if execution == "sync": + output = node.execute(*inputs).as_table(columns=config) + else: + readers: list[ReadableChannel[tuple[TagProtocol, DataProtocol]]] = [] + for stream in inputs: + incoming = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=4) + for row in stream.iter_data(): + await incoming.writer.send(row) + await incoming.writer.close() + readers.append(incoming.reader) + outgoing = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=4) + await node.async_execute(readers, outgoing.writer) + assert len(await outgoing.reader.collect()) == expected.num_rows + output = node.as_table(columns=config) + store.flush() + [path] = store.list_table_paths() + stored = store.get_all_records(path, record_id_column="_record_hash") + assert stored is not None + for actual in (output, stored): + assert actual.schema.field(extended_name).equals( + expected.schema.field(extended_name), check_metadata=True + ) + assert sorted(cast("list[str]", actual[extended_name].to_pylist())) == sorted( + cast("list[str]", expected[extended_name].to_pylist()) + ) + + +def test_detached_custom_id_tag_read_as_raw_requires_its_partner() -> None: + """A detached table can no longer distinguish a custom tag from a raw ID.""" + from orcapod.operators import Batch + + table = pa.table({"x": [1], "source_id": ["custom"]}) + source = ArrowTableStream(table, system_tag_columns=["source_id"]) + detached = Batch(batch_size=1)(source).as_table(columns={"system_tags": True}) + _, partner = system_tag_column_names(source.pipeline_hash().to_hex()) + + with pytest.raises(InputValidationError, match=re.escape(partner)): + _ = ArrowTableStream(detached) diff --git a/tests/test_core/test_row_ids.py b/tests/test_core/test_row_ids.py index 25299b7ca..6beafe11f 100644 --- a/tests/test_core/test_row_ids.py +++ b/tests/test_core/test_row_ids.py @@ -22,7 +22,6 @@ from orcapod.core.data_function import output_source_info from orcapod.core.datagrams import Data, Tag from orcapod.core.datagrams.tag_data import EmptyData -from orcapod.core.streams import ArrowTableStream from orcapod.system_constants import constants from orcapod.types import SourceInfoValue from orcapod.utils import arrow_utils @@ -115,28 +114,22 @@ def test_with_source_info_keeps_a_scalar_type_its_value_cannot_show() -> None: ("arrow_type", "values"), [(pa.null(), [None, None]), (pa.large_list(pa.null()), [[None], [None, None]])], ) -def test_entry_id_explains_how_to_replace_a_raw_null_system_tag( +def test_entry_id_explains_an_unsupported_system_tag_type_on_a_tag( arrow_type: pa.DataType, values: list[Any], ) -> None: name = "_tag_record_id::seed" - stream = ArrowTableStream( - pa.table( - { - "subject": pa.array(["m1", "m2"], pa.large_string()), - "session": [1, 2], - "_tag_source_id::seed": pa.array( - ["source", "source"], pa.large_string() - ), - name: pa.array(values, type=arrow_type), - "weight": [25, 30], - } - ), - tag_columns=["subject", "session"], + tags = pa.table( + { + "subject": pa.array(["m1", "m2"], pa.large_string()), + "session": [1, 2], + "_tag_source_id::seed": pa.array(["source", "source"], pa.large_string()), + name: pa.array(values, type=arrow_type), + } ) - for tag, data in stream.iter_data(): + for row in tags.to_batches(max_chunksize=1): with pytest.raises(ValueError, match=rf"{name}.*supported nullable type"): - row_ids.entry_id(HASHER, tag, data) + row_ids.entry_id(HASHER, Tag(row), _data()) class TestEntryId: diff --git a/tests/test_hashing/test_wrong_hash_findings.py b/tests/test_hashing/test_wrong_hash_findings.py index 19dbe7bc5..645dda42b 100644 --- a/tests/test_hashing/test_wrong_hash_findings.py +++ b/tests/test_hashing/test_wrong_hash_findings.py @@ -19,6 +19,7 @@ from orcapod import FunctionPod, function_pod, side_effect_function_pod from orcapod.contexts import resolve_context +from orcapod.errors import InputValidationError from orcapod.operators import ( Batch, DropDataColumns, @@ -73,8 +74,8 @@ def _stream_with_source_ids(source_ids: list[str | None]) -> ArrowTableStream: "x": pa.array(list(range(len(source_ids))), type=pa.int64()), SOURCE_ID_COL: pa.array(source_ids, type=pa.large_string()), RECORD_ID_COL: pa.array( - [uuid.UUID(int=i + 1).bytes for i in range(len(source_ids))], - type=pa.large_binary(), + [f"record-{i}" for i in range(len(source_ids))], + type=pa.large_string(), ), } ) @@ -101,15 +102,12 @@ def test_member_boundaries_are_identity(self, make_op: Any) -> None: right = _folded_source_id(make_op()(_stream_with_source_ids(["a", "bc"]))) assert left != right - def test_null_member_differs_from_empty_member(self) -> None: - """A null member folds unlike an empty-string member.""" - left = _folded_source_id( - Batch(batch_size=2)(_stream_with_source_ids([None, "x"])) - ) - right = _folded_source_id( - Batch(batch_size=2)(_stream_with_source_ids(["", "x"])) - ) - assert left != right + def test_null_source_id_is_refused_before_folding(self) -> None: + """Refuse a null source ID at the stream boundary.""" + with pytest.raises( + InputValidationError, match=rf"{SOURCE_ID_COL}.*null values" + ): + _ = _stream_with_source_ids([None, "x"]) def test_source_info_stays_the_list_of_member_tokens(self) -> None: """Only the scalar system-tag fold changed, not source info.""" diff --git a/tests/test_pipeline/test_bind_narrower_source.py b/tests/test_pipeline/test_bind_narrower_source.py index 37733fb65..9fe55a257 100644 --- a/tests/test_pipeline/test_bind_narrower_source.py +++ b/tests/test_pipeline/test_bind_narrower_source.py @@ -34,7 +34,11 @@ typed_zero_row_table, ) from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import SourceSpecMismatchError, UnboundSourceError +from orcapod.errors import ( + InputValidationError, + SourceSpecMismatchError, + UnboundSourceError, +) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.sources import ArrowTableSource, CSVSource, DictSource from orcapod.types import Schema @@ -1064,20 +1068,12 @@ def test_an_extra_system_tag_column_is_refused( bind(job, stream) -@pytest.mark.parametrize("x_type", [int, int | None], ids=["declared", "narrower"]) -@pytest.mark.parametrize("bind", ALL_BINDS.values(), ids=ALL_BINDS.keys()) -def test_a_system_tag_pair_of_other_types_is_refused( - bind: Callable[[PipelineJob, Any], None], x_type: Any -) -> None: - """The source id and the record id must be ``str``, as the slot predicts (ITL-1154).""" - stream = _stream_with_system_tags( - { - SOURCE_ID: pa.array(["s"], pa.large_string()), - RECORD_ID: pa.array([b"r"], pa.large_binary()), - } - ) - job = PipelineJob(name="j", database=InMemoryArrowDatabase()) - with job: - _ = MapData({"x": "y"})(_slot(x_type), label="renamed") - with pytest.raises(SourceSpecMismatchError, match=r"declared str but the source"): - bind(job, stream) +def test_a_non_string_record_id_is_refused_before_binding() -> None: + """A raw stream reports its invalid ID type at construction.""" + with pytest.raises(InputValidationError, match=RECORD_ID): + _stream_with_system_tags( + { + SOURCE_ID: pa.array(["s"], pa.large_string()), + RECORD_ID: pa.array([b"r"], pa.large_binary()), + } + ) diff --git a/tests/test_pipeline/test_review_findings_510.py b/tests/test_pipeline/test_review_findings_510.py index b41697476..19cd7e3ac 100644 --- a/tests/test_pipeline/test_review_findings_510.py +++ b/tests/test_pipeline/test_review_findings_510.py @@ -191,11 +191,10 @@ def _with_system_tag(column: pa.Array[Any]) -> ArrowTableStream: @pytest.mark.parametrize( "column", [ - pa.array([1, 2], pa.int16()), - pa.array([1, 2], pa.int32()), pa.array(["a", "b"], pa.string()), + pa.array(["a", "b"], pa.large_string()), ], - ids=["int16", "int32", "string"], + ids=["string", "large_string"], ) def test_a_channel_on_a_raw_stream_keeps_the_declared_system_tag_field( column: pa.Array[Any], @@ -216,14 +215,6 @@ def test_a_channel_on_a_raw_stream_keeps_the_declared_system_tag_field( assert delivered[name].to_pylist() == built[name].to_pylist() -def test_a_channel_keeps_null_values_in_a_nullable_raw_system_tag() -> None: - """A single nullable field can hold the rows with and without a value.""" - stream = _with_system_tag(pa.array(["a", None], pa.large_string())) - table = pa.Table.from_batches(asyncio.run(stream.open_channel().collect())) - assert table.schema.field("_tag_e").equals(pa.field("_tag_e", pa.large_string())) - assert table.column("_tag_e").to_pylist() == ["a", None] - - def _arrow_table_source() -> ArrowTableSource: return ArrowTableSource( pa.table({"k": [1, 2], "j": ["a", "b"], "x": [10, 20], "y": [0.5, 1.5]}), diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index fb0d97b46..c98c8f62f 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -901,10 +901,10 @@ def test_a_source_in_another_data_context_hands_on_its_own_rows() -> None: class _AddSystemTag: - """``SelectDataColumns`` whose result carries one more system tag, ``int16``.""" + """``SelectDataColumns`` whose result carries one more string system tag.""" @staticmethod - def operator(values: list[int | None], exact: bool) -> Any: + def operator(values: list[str], exact: bool) -> Any: from orcapod.operators import SelectDataColumns from orcapod.system_constants import constants @@ -919,14 +919,14 @@ def unary_static_process(self, stream: Any) -> Any: table = out.as_table(columns={"source": True, "system_tags": True}) table = table.append_column( f"{constants.SYSTEM_TAG_PREFIX}region", - pa.array(values[: table.num_rows], pa.int16()), + pa.array(values[: table.num_rows], pa.large_string()), ) return kind(table, tag_columns=["k"]) return AddSystemTag(["x"]) -def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: +def _system_tag_job(values: list[str], exact: bool) -> tuple[Any, Any]: database = InMemoryArrowDatabase() job = PipelineJob(name="system_tag", database=database) with job: @@ -943,43 +943,31 @@ def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: return job, database -def test_a_narrow_raw_system_tag_is_stored_with_its_declared_field() -> None: +def test_a_nullable_raw_system_tag_is_stored_with_its_declared_field() -> None: """Both the exact stream and the fallback row path keep the declared field.""" from orcapod.system_constants import constants name = f"{constants.SYSTEM_TAG_PREFIX}region" stored: dict[bool, Any] = {} for exact in (True, False): - job, database = _system_tag_job([1, 2], exact) + job, database = _system_tag_job(["a", "b"], exact) job.run() node: Any = job.nodes["marked"] kept = node.as_table(columns={"system_tags": True}).schema.field(name) - assert kept.equals(pa.field(name, pa.int16()), check_metadata=True) + assert kept.equals(pa.field(name, pa.large_string()), check_metadata=True) stored[exact] = database.at("log").get_all_records( node._stored_table_path, # pyright: ignore[reportPrivateUsage] # the raw LOG table record_id_column="_record_hash", ) for table in stored.values(): field = table.schema.field(name) - assert field.equals(pa.field(name, pa.int16()), check_metadata=True) + assert field.equals(pa.field(name, pa.large_string()), check_metadata=True) assert ( stored[True]["_record_hash"].to_pylist() == stored[False]["_record_hash"].to_pylist() ) -def test_an_operator_keeps_null_values_in_a_nullable_raw_system_tag() -> None: - """A nullable declared field lets rows with and without a value share a table.""" - job, _ = _system_tag_job([None, 2], exact=True) - observer = _NodeEvents() - job.run(observer=observer) - assert ("start", "marked") in observer.events - assert ("end", "marked") in observer.events - table = job.nodes["marked"].as_table(columns={"system_tags": True}) - assert table.schema.field("_tag_region").equals(pa.field("_tag_region", pa.int16())) - assert table.column("_tag_region").to_pylist() == [None, 2] - - def test_a_source_refuses_a_non_text_custom_system_tag() -> None: """Source-built system tags must be non-nullable text.""" from orcapod.core.streams.base import system_tags_as_rows_give