diff --git a/.zed/rules b/.zed/rules index 994dc92f0..20696ba54 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1003,7 +1003,7 @@ of its identity (GroupBy's member_order), never the input's column order. _source_ prefix — Source info provenance (ColumnConfig source) _input_source_ prefix — Source-info provenance of an input data column as stored by a function node, e.g. _input_source_age (ColumnConfig(source=True)) - _tag:: prefix — System tag (ColumnConfig system_tags) + _tag_ prefix — System tag (ColumnConfig system_tags) _context_key — Data context (ColumnConfig context) Prefixes are computed from SystemConstant in system_constants.py. @@ -1521,19 +1521,17 @@ data. The rules: to large_list, recursively). Width, nullability and logical (extension) types are never changed, so `int8` stays `int8`. Sources refuse Arrow type `null` at any depth, including in reserved raw columns. Declare a supported nullable type for missing values. - A source's custom system-tag names must each identify an existing non-nullable text - column with no null values and no Arrow field metadata. Remove field metadata before - building the source. This restriction is a stopgap pending ITL-1561. System-tag fields on - a raw ArrowTableStream keep their metadata. DataFrameSource uses an explicit schema for - custom system-tag nullability and validates the raw values, types and metadata before casting. - Join's sync and batch sort pairs source and record IDs within each printed - provenance path. The rebuilt ID field can hold nulls when any corresponding - input field can hold nulls or an input lacks that field. Custom tags keep their - input positions in these tables. Standalone row channels sort the custom tags - of a tied path with its IDs at every link. Join rows infer tied system-tag - fields from values. Non-tied system-tag fields keep their Arrow declarations. - A raw `ArrowTableStream` preserves the system-tag fields in its table and - rows, including the Arrow Null type (ITL-1543). + Orcapod constructs system tags (ITL-1751). Public source and stream inputs refuse + columns in the system-tag namespace. Function pod outputs and operator rename targets + cannot use reserved system column names. Saved source configs that nominate system + tags are refused before loading a wrapped source or resolving its cache. + Tables built by operators, sources, row transport + and storage reads enter through the private Arrow stream factory. It preserves system-tag + field declarations and requires string values without nulls. Cached source rows also + require non-nullable fields without metadata, pending ITL-1561. + Join's sync and batch sort source and record ID pairs within each printed provenance + path. Join rows infer tied system-tag fields from values. Non-tied system-tag fields + keep their Arrow declarations. Streams, rows and record batches declare every `_source_*` token field nullable (ITL-1557). The top-level flag comes from `arrow_utils.source_info_field` and is independent of the token values and of any list item fields. CachedSource writes these fields diff --git a/CLAUDE.md b/CLAUDE.md index 568c4b3a0..610eb1866 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1027,7 +1027,7 @@ of its identity (GroupBy's `member_order`), never the input's column order. | `__` | System metadata | `__data_id`, `__pod_version` | `ColumnConfig(meta=True)` | | `_source_` | Source info provenance | `_source_age` | `ColumnConfig(source=True)` | | `_input_source_` | Source-info provenance of an input data column as stored by a function node | `_input_source_age` | `ColumnConfig(source=True)` | -| `_tag::` | System tag | `_tag::source:abc123` | `ColumnConfig(system_tags=True)` | +| `_tag_` | System tag | `_tag_source_id::abc123` | `ColumnConfig(system_tags=True)` | | `_context_key` | Data context | `_context_key` | `ColumnConfig(context=True)` | Prefixes are computed from `SystemConstant` in `system_constants.py`. The `constants` singleton @@ -1566,19 +1566,17 @@ data. The rules: to `large_list`, recursively). Width, nullability and logical (extension) types are never changed, so `int8` stays `int8`. Sources refuse Arrow type `null` at any depth, including in reserved raw columns. Declare a supported nullable type for missing values. - A source's custom system-tag names must each identify an existing non-nullable text - column with no null values and no Arrow field metadata. Remove field metadata before - building the source. This restriction is a stopgap pending ITL-1561. System-tag fields on - a raw ArrowTableStream keep their metadata. DataFrameSource uses an explicit schema for - custom system-tag nullability and validates the raw values, types and metadata before casting. - Join's sync and batch sort pairs source and record IDs within each printed - provenance path. The rebuilt ID field can hold nulls when any corresponding - input field can hold nulls or an input lacks that field. Custom tags keep their - input positions in these tables. Standalone row channels sort the custom tags - of a tied path with its IDs at every link. Join rows infer tied system-tag - fields from values. Non-tied system-tag fields keep their Arrow declarations. - A raw `ArrowTableStream` preserves the system-tag fields in its table and - rows, including the Arrow Null type (ITL-1543). + Orcapod constructs system tags (ITL-1751). Public source and stream inputs refuse + columns in the system-tag namespace. Function pod outputs and operator rename targets + cannot use reserved system column names. Saved source configs that nominate system + tags are refused before loading a wrapped source or resolving its cache. + Tables built by operators, sources, row transport + and storage reads enter through the private Arrow stream factory. It preserves system-tag + field declarations and requires string values without nulls. Cached source rows also + require non-nullable fields without metadata, pending ITL-1561. + Join's sync and batch sort source and record ID pairs within each printed provenance + path. Join rows infer tied system-tag fields from values. Non-tied system-tag fields + keep their Arrow declarations. Streams, rows and record batches declare every `_source_*` token field nullable (ITL-1557). The top-level flag comes from `arrow_utils.source_info_field` and is independent of the token values and of any list item fields. CachedSource writes these fields diff --git a/changelog.d/ITL-1751.md b/changelog.d/ITL-1751.md new file mode 100644 index 000000000..d233a6b90 --- /dev/null +++ b/changelog.d/ITL-1751.md @@ -0,0 +1,10 @@ +### Breaking changes and migration + +- Orcapod owns system tags. Source constructors and `ArrowTableStream` no longer accept + `system_tag_columns` and reject input columns in the reserved system-tag namespace. + Rename those fields and use ordinary tag columns for user-supplied tags. Saved source + configs with an empty setting still load. Remove non-empty settings and update the + source's tag columns before loading. +- Function pods reject output names reserved for system tags, source-info columns, + metadata, and the data context. `Index` and `Pick` also reject these names as output + targets. Rename affected outputs before defining the pod or operator. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 60b3771c2..2a54f0213 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1183,10 +1183,8 @@ and neither does a source's own `run()` outside a job (`source.run()` does what | `DerivedSource` | over a source, checks it; reads the origin's rows again when the origin's modified time moved since this source read them (a source that took in new data, a job node that ran again); holds the new rows if they changed; one that holds no rows (over a job node that had not run) moves when its origin's time moves | | `SourceProxy` | checks the source bound to it; its modified time follows that source's, and binding or unbinding moves it | -Rows read again are compared with the rows read before, as read from the table or file -(every column, a `system_tag_columns` column too), value by value, with a -NaN equal to a NaN (and -0.0 equal to 0.0), so a table holding a NaN is not a change at every -check. A check that raises part way changes nothing, so the next run checks again. +A check compares every column from the original table or file, value by value. NaN equals +NaN and -0.0 equals 0.0 for this comparison. A check that raises part way changes nothing, so the next run checks again. Row order follows the source's record id rule (developer, November 14, 2026). Without key columns a row's record id is its position: a change of row order is a change, so diff --git a/docs/dev/design_issues/ITL-1751-AS5.md b/docs/dev/design_issues/ITL-1751-AS5.md new file mode 100644 index 000000000..dc29b217a --- /dev/null +++ b/docs/dev/design_issues/ITL-1751-AS5.md @@ -0,0 +1,16 @@ +## `src/orcapod/core/streams/` + +### AS5 — User-defined system tags could be mistaken for provenance +**Status:** resolved +**Severity:** medium +**Issue:** ITL-1751 + +A source or stream could accept user-defined system tags with the same names as +Orcapod's own provenance columns. The same column could appear to have different +roles at different construction boundaries. + +**Fix:** Reserve the system-tag namespace at public construction boundaries. +Use a private stream factory for provenance produced by Orcapod. Function +pods, `Index`, and `Pick` refuse reserved output names at definition. +Source configs omit the removed setting and refuse a saved non-empty list, +including in wrapped source configs, before reconstructing sources or caches. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index c344d2646..1b784a7e2 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -136,6 +136,13 @@ def __init__( config: OrcapodConfig | None = None, ctx_arg_name: str | None = None, ) -> None: + output_names = data_function.output_data_schema.keys() + try: + schema_utils.require_names_not_meta(output_names) + schema_utils.require_names_not_system(output_names) + except InputValidationError as exc: + raise InputValidationError(f"Invalid function output: {exc}") from exc + super().__init__( label=label, data_context=data_context, diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 99585a62f..09b106439 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -58,10 +58,7 @@ 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, - stream_from_derived_table, -) +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -627,11 +624,11 @@ def output_schema( restored to a Python type (an unregistered logical type). """ if self._function_pod is None: + from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.pipeline.serialization import ( - deserialize_output_schema, SavedSchemaVersionError, + deserialize_output_schema, ) - from orcapod.logical_types.identifier import LogicalTypeIdentifierError try: return deserialize_output_schema( @@ -4163,7 +4160,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 = stream_from_derived_table( + stream = ArrowTableStream._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 007e1cd20..611e0c242 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -54,10 +54,7 @@ produced_stream, rows_on_read, ) -from orcapod.core.streams.arrow_table_stream import ( - ArrowTableStream, - stream_from_derived_table, -) +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, StreamBase, @@ -508,7 +505,7 @@ def _zero_row_table(self, config: ColumnConfig) -> "pa.Table | None": saved = self._saved_zero_row_table() if saved is None: return None - return stream_from_derived_table( + return ArrowTableStream._from_derived_table( saved, tag_columns=self.keys()[0], data_tags=stream_data_tags(self), @@ -541,11 +538,11 @@ def output_schema( restored to a Python type (an unregistered logical type). """ if self._operator is None: + from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.pipeline.serialization import ( - deserialize_output_schema, SavedSchemaVersionError, + deserialize_output_schema, ) - from orcapod.logical_types.identifier import LogicalTypeIdentifierError try: return deserialize_output_schema( @@ -1354,7 +1351,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 stream_from_derived_table( + return ArrowTableStream._from_derived_table( rows, tag_columns=self.keys()[0], data_tags=self.declared_data_tags(), @@ -1850,8 +1847,8 @@ def execute( feeding ``input_streams`` is restricted (ITL-1218); nothing is read, computed or written. """ - from orcapod.pipeline.restrictions import refuse_restricted_operator_cache from orcapod.pipeline.observer import NoOpObserver + from orcapod.pipeline.restrictions import refuse_restricted_operator_cache # A loaded node runs only in a load-only run, with its rebuilt operator. if self._loaded and (not load_only or self._operator is None): @@ -2250,7 +2247,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 = stream_from_derived_table( + empty_stream = ArrowTableStream._from_derived_table( self._make_empty_table(), tag_columns=self.keys()[0], data_tags=stream_data_tags(self), @@ -2451,8 +2448,8 @@ async def async_execute( feeding its ``upstreams`` (which the channels carry) is restricted (ITL-1218); the output is closed, nothing read or written. """ - from orcapod.pipeline.restrictions import refuse_restricted_operator_cache from orcapod.pipeline.observer import NoOpObserver + from orcapod.pipeline.restrictions import refuse_restricted_operator_cache # A loaded node runs only in a load-only run, with its rebuilt operator. if self._loaded and (not load_only or self._operator is None): diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7b0f8d9ac..b07f4ad06 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -36,10 +36,7 @@ ) 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, - stream_from_derived_table, -) +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, CompleteStreamFeed, @@ -1417,12 +1414,12 @@ def execute( Raises: UnboundSourceError: When no concrete data is available. """ - from orcapod.core.output_bindings import capture_output_bindings from orcapod.core.operators.static_output_pod import ( RowBuiltFormUnavailable, StaticOutputOperatorPod, rows_on_read, ) + from orcapod.core.output_bindings import capture_output_bindings bindings = capture_output_bindings(self) node_label = self.label @@ -1963,7 +1960,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 stream_from_derived_table( + return ArrowTableStream._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 4d49c51f8..aa2f350bd 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 stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -333,7 +333,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: "sort_by_tags": False, } ) - return stream_from_derived_table( + return ArrowTableStream._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 710b19106..0d854a1ae 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.arrow_table_stream import stream_from_derived_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 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 stream_from_derived_table( + return ArrowTableStream._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 87c35c107..8a3b5434c 100644 --- a/src/orcapod/core/operators/column_selection.py +++ b/src/orcapod/core/operators/column_selection.py @@ -3,11 +3,11 @@ from collections.abc import Collection, Sequence from typing import Any, ClassVar -from orcapod.core.operators.meta_columns import WithoutMetaWriter 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.arrow_table_stream import stream_from_derived_table +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.operators.meta_columns import WithoutMetaWriter +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.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 stream_from_derived_table( + return ArrowTableStream._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 stream_from_derived_table( + return ArrowTableStream._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 stream_from_derived_table( + return ArrowTableStream._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 stream_from_derived_table( + return ArrowTableStream._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 stream_from_derived_table( + return ArrowTableStream._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 46d82a6a3..ad1f0afdf 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -10,12 +10,12 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.core.data_tags import stream_data_tags -from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.core.data_tags import stream_data_tags from orcapod.core.datagrams import Data, Tag from orcapod.core.operators.base import UnaryOperator -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.operators.meta_columns import WithoutMetaWriter +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -325,7 +325,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: } ) tag_columns, data_columns = stream.keys() - return stream_from_derived_table( + return ArrowTableStream._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 17e97ee11..c6cf1e9ed 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 stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.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 stream_from_derived_table( + return ArrowTableStream._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 2e7e42788..043485e4b 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -1,14 +1,14 @@ import logging import sys from collections.abc import Callable, Collection, Iterable, Mapping, Sequence -from typing import Any, ClassVar, TYPE_CHECKING, TypeAlias +from typing import TYPE_CHECKING, Any, ClassVar, TypeAlias import polars as pl import pyarrow as pa from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream 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 stream_from_derived_table( + return ArrowTableStream._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 12e13985b..73abe3971 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -9,6 +9,7 @@ import polars as pl import pyarrow as pa +from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.arrow_keys import ( is_list_kind, part_without_rule, @@ -17,8 +18,7 @@ values_of, ) from orcapod.core.operators.base import UnaryOperator -from orcapod.core.data_tags import stream_data_tags -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import typed_zero_row_table from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import StreamProtocol @@ -573,7 +573,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 stream_from_derived_table( + return ArrowTableStream._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 94f6b11cc..6d38f4a63 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -9,16 +9,16 @@ import pyarrow as pa -from orcapod.types.explanation import plain_repr -from orcapod.core.data_tags import stream_data_tags -from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import ProjectionType, UnaryOperator -from orcapod.system_constants import constants -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.operators.meta_columns import WithoutMetaWriter +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol +from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataType, Schema, SourceInfoValue +from orcapod.types.explanation import plain_repr from orcapod.utils import arrow_utils, schema_utils logger = logging.getLogger(__name__) @@ -68,6 +68,7 @@ def __init__( # as ``MapData`` refuses it, so no path can produce one and drop it. if out is not None: schema_utils.require_names_not_meta([out]) + schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out self.fail_on_miss = fail_on_miss @@ -471,7 +472,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 stream_from_derived_table( + return ArrowTableStream._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 1fd6a554d..ff3c1fb35 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -38,10 +38,7 @@ reconcile_key_nullability, ) from orcapod.core.datagrams import Tag -from orcapod.core.streams.arrow_table_stream import ( - ArrowTableStream, - stream_from_derived_table, -) +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -800,13 +797,12 @@ def _join_result_stream( ) for field in result_table.schema ): - return _TiedJoinStream( - result_table, - tag_columns=tag_columns, - data_tags=data_tags, - inferred_system_tags=inferred, + tied = _TiedJoinStream._from_derived_table( + result_table, tag_columns=tag_columns, data_tags=data_tags ) - return stream_from_derived_table( + tied._inferred_system_tags = inferred + return tied + return ArrowTableStream._from_derived_table( result_table, tag_columns=tag_columns, data_tags=data_tags ) @@ -1860,21 +1856,7 @@ def __repr__(self) -> str: class _TiedJoinStream(ArrowTableStream): """A Join table whose tied system-tag fields are inferred on row reads.""" - def __init__( - self, - table: pa.Table, - *, - tag_columns: Collection[str], - data_tags: Collection[str], - inferred_system_tags: frozenset[str], - ) -> None: - super().__init__( - table, - tag_columns=tag_columns, - data_tags=data_tags, - _system_tags_are_derived=True, - ) - self._inferred_system_tags = inferred_system_tags + _inferred_system_tags: frozenset[str] def _iter_tags(self, table: pa.Table) -> Iterator[Tag]: return Tag.rows_of( diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index d4d4186ec..6b76fea6f 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -1,15 +1,15 @@ from collections.abc import Collection, Mapping, Sequence from typing import Any, ClassVar -from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator from orcapod.core.operators.column_selection import ( is_meta_column, require_a_data_column, ) -from orcapod.core.data_tags import stream_data_tags -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.operators.meta_columns import WithoutMetaWriter +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants @@ -228,7 +228,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: ] ) - return stream_from_derived_table( + return ArrowTableStream._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 stream_from_derived_table( + return ArrowTableStream._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 stream_from_derived_table( + return ArrowTableStream._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 479e17c67..e71bbd2cf 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.arrow_table_stream import stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream 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 stream_from_derived_table( + return ArrowTableStream._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 dafc5e059..40ea8c099 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 stream_from_derived_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 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 stream_from_derived_table( + return ArrowTableStream._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 9ec499169..f36c87c0b 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -9,16 +9,16 @@ import pyarrow as pa -from orcapod.types.explanation import plain_repr -from orcapod.core.data_tags import stream_data_tags -from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import ProjectionType, UnaryOperator -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.operators.meta_columns import WithoutMetaWriter +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError -from orcapod.system_constants import constants from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol +from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataType, Schema +from orcapod.types.explanation import plain_repr from orcapod.utils import arrow_utils, schema_utils logger = logging.getLogger(__name__) @@ -70,6 +70,7 @@ def __init__( # as ``MapData`` refuses it, so no path can produce one and drop it. if out is not None: schema_utils.require_names_not_meta([out]) + schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out self.fail_on_miss = fail_on_miss @@ -428,7 +429,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 stream_from_derived_table( + return ArrowTableStream._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 87a0fb13f..bb32a2ab8 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.arrow_table_stream import stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream 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 stream_from_derived_table( + return ArrowTableStream._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 a91c0e624..4d01dac7d 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -8,25 +8,25 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.types.explanation import plain_repr from orcapod.channels import ChannelClosed, ReadableChannel, WritableChannel -from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.arrow_keys import polars_key_frame from orcapod.core.operators.base import ( BinaryOperator, + explain_nested_join_conflict, require_matchable_key, require_shared_arrow_type, - explain_nested_join_conflict, ) from orcapod.core.operators.key_nullability import reconcile_key_nullability from orcapod.core.operators.match_keys import frozen_scalar -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.operators.meta_columns import WithoutMetaWriter +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError, SemiJoinIgnoredColumnWarning from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.protocols.core_protocols.trackers import TrackerManagerProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Schema +from orcapod.types.explanation import plain_repr from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.warning_utils import outside_orcapod_stacklevel @@ -270,7 +270,7 @@ def binary_static_process( ) semi_joined_table = left_table.take(kept.get_column(_LEFT_ROW).to_arrow()) - return stream_from_derived_table( + return ArrowTableStream._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 471f8e781..f673b7447 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -57,7 +57,6 @@ ) from orcapod.core.streams.arrow_table_stream import ( ArrowTableStream, - stream_from_derived_table, ) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -494,7 +493,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 stream_from_derived_table( + return ArrowTableStream._from_derived_table( table, tag_columns=tag_keys, data_tags=stream_data_tags(result), @@ -517,7 +516,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 stream_from_derived_table( + return ArrowTableStream._from_derived_table( StaticOutputOperatorPod._in_row_order(table, tag_keys), tag_columns=tag_keys, data_tags=stream_data_tags(result), @@ -720,7 +719,7 @@ def zero_row_result(self, *inputs: StreamProtocol) -> StreamProtocol: for field in schema ] ) - return stream_from_derived_table( + return ArrowTableStream._from_derived_table( normalized.empty_table(), tag_columns=only.keys()[0], data_tags=stream_data_tags(only), @@ -769,7 +768,7 @@ 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 stream_from_derived_table( + return ArrowTableStream._from_derived_table( table, tag_columns=tag_keys, data_tags=data_tags ) @@ -878,18 +877,18 @@ def _as_upstream_stream( # otherwise it would fall back to a root's schema-only hash and an # operator would name its system tags after that. A source's pipeline # hash is that schema-only hash already. - stream = _RowsOfStream( + stream = _RowsOfStream._from_derived_table( table, tag_columns=tag_keys, - pipeline_hash=upstream.pipeline_hash(), data_tags=data_tags, upstreams=upstream.upstreams, data_context=context, ) + stream._input_pipeline_hash = upstream.pipeline_hash() else: # No ``source_info`` argument: the table's own ``_source_*`` columns # pass through, one value per row. - stream = stream_from_derived_table( + stream = ArrowTableStream._from_derived_table( table, tag_columns=tag_keys, data_tags=data_tags, @@ -945,13 +944,13 @@ def _materialize_input_stream( pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), pa.array([data.data_context_key for _, data in rows], pa.large_string()), ) - stream = _RowsOfStream( + stream = _RowsOfStream._from_derived_table( table, tag_columns=tag_keys, - pipeline_hash=pipeline_hash, data_tags=data_tags, data_context=contexts.resolve_context(rows[0][1].data_context_key), ) + stream._input_pipeline_hash = pipeline_hash stream._identity_origin = job_input_stream(reader) # pyright: ignore[reportPrivateUsage] # This stream is a row representation. return stream @@ -1709,33 +1708,9 @@ class _RowsOfStream(ArrowTableStream): node's ``input_pipeline_hashes``, or the upstream's own). Its content hash is that of its table, as for any ``ArrowTableStream`` without a producer. - Args: - table: The rows. - tag_columns: The user tag columns. - pipeline_hash: The pipeline hash of the stream the rows came from. - upstreams: The upstreams of the stream the rows came from, if any. - data_context: The rows' data context; ``None`` for the default. """ - def __init__( - self, - table: pa.Table, - *, - tag_columns: Collection[str], - pipeline_hash: ContentHash, - data_tags: Collection[str] = (), - upstreams: tuple[StreamProtocol, ...] = (), - data_context: DataContext | None = None, - ) -> None: - super().__init__( - table, - tag_columns=tag_columns, - data_tags=data_tags, - upstreams=upstreams, - data_context=data_context, - _system_tags_are_derived=True, - ) - self._input_pipeline_hash: ContentHash = pipeline_hash + _input_pipeline_hash: ContentHash def _identity_inputs(self) -> tuple[StreamProtocol, ...]: """Preserve the restored node's lineage even without its pod.""" @@ -1886,19 +1861,19 @@ def _typed_zero_row_table(self) -> pa.Table | None: # not (a raw stream's meta columns enter its hash, and its zero-row # table has none): the system-tag names then follow the upstream's # hash, as on the sync path (``_as_upstream_stream``'s rule). - rows = _RowsOfStream( + rows = _RowsOfStream._from_derived_table( table, tag_columns=upstream.keys()[0], - pipeline_hash=upstream.pipeline_hash(), data_tags=stream_data_tags(upstream), upstreams=upstream.upstreams, data_context=context, ) + rows._input_pipeline_hash = upstream.pipeline_hash() rows._identity_origin = upstream # pyright: ignore[reportPrivateUsage] # This stream is a row representation. inputs.append(rows) continue inputs.append( - stream_from_derived_table( + ArrowTableStream._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 2e6b431b6..0481a133b 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -7,9 +7,9 @@ from typing_extensions import override -from orcapod.core.operators.base import UnaryOperator from orcapod.core.data_tags import require_taggable_type, stream_data_tags -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.streams.arrow_table_stream import ArrowTableStream 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 stream_from_derived_table( + return ArrowTableStream._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/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index 1b03e0509..d3703d5d5 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -4,15 +4,18 @@ from collections.abc import Collection from typing import TYPE_CHECKING, Any, ClassVar -from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.stream_builder import SourceStreamBuilder +from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( + SourceStreamBuilder, normalize_record_id_columns, require_supported_nullable_types, ) from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import ( + _normalize_column_list, + require_names_not_system_tags, +) if TYPE_CHECKING: import pyarrow as pa @@ -98,7 +101,6 @@ def __init__( self, table: "pa.Table", tag_columns: str | Collection[str] = (), - system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, infer_nullable: bool = False, *, @@ -109,6 +111,7 @@ def __init__( super().__init__(**kwargs) tag_columns = _normalize_column_list(tag_columns) + require_names_not_system_tags(table.column_names) if infer_nullable: require_supported_nullable_types(table.schema) logger.debug( @@ -126,7 +129,6 @@ def __init__( source_name=self._source_name, kind_part=self.kind_part(), record_id_columns=normalize_record_id_columns(record_id_columns) or (), - system_tag_columns=system_tag_columns, hash_in_key_order=hash_in_key_order, ) @@ -137,7 +139,6 @@ def __init__( self._tag_only_columns = tuple( c for c in result.tag_columns if c not in result.data_tags ) - self._system_tag_columns = result.system_tag_columns self._record_id_columns = normalize_record_id_columns(record_id_columns) self._key_columns = self._record_id_columns or () @@ -164,6 +165,7 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> ArrowTableSour Raises: NotImplementedError: Always. """ + cls._require_no_saved_system_tags(config) raise NotImplementedError( "ArrowTableSource cannot be reconstructed from config — " "the in-memory Arrow table is not serializable." diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 8d3c31d37..9869fa2d0 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -2,7 +2,7 @@ import warnings from collections.abc import Callable -from typing import TYPE_CHECKING, Any, ClassVar, TypeVar +from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast from orcapod import contexts from orcapod.config import OrcapodConfig @@ -274,6 +274,22 @@ def _source_id_config(self) -> dict[str, Any]: "source_version": self.SOURCE_VERSION, } + @classmethod + def _require_no_saved_system_tags(cls, config: dict[str, Any]) -> None: + """Refuse saved system tags before reconstructing any wrapped source.""" + from orcapod.pipeline.serialization import NESTED_SOURCE_CONFIG_KEYS + + if names := config.get("system_tag_columns"): + raise ValueError( + f"Saved source config contains system_tag_columns {names!r}. " + "Orcapod creates system tags itself. Remove this setting and use " + "ordinary tag columns for those fields." + ) + for key in NESTED_SOURCE_CONFIG_KEYS: + nested = config.get(key) + if isinstance(nested, dict): + cls._require_no_saved_system_tags(cast("dict[str, Any]", nested)) + @classmethod def _from_saved_name( cls, config: dict[str, Any], build: Callable[[str | None], _SourceT] @@ -306,7 +322,7 @@ def _from_saved_name( @classmethod def require_saved_name_fields(cls, config: dict[str, Any]) -> None: - """Refuse a saved config written before source ids named their kind (ITL-1425). + """Check reserved settings in a saved source config. Such a config holds a ``source_id`` and no ``source_name``. It is not read as anything else: ``from_config`` refuses it, and ``PipelineJob.load`` refuses a @@ -317,8 +333,10 @@ def require_saved_name_fields(cls, config: dict[str, Any]) -> None: config: A saved source config (``to_config``). Raises: - ValueError: If the config holds a ``source_id`` but no ``source_name``. + ValueError: If the config names custom system tags or holds a + ``source_id`` without a ``source_name``. """ + cls._require_no_saved_system_tags(config) if "source_id" in config and "source_name" not in config: raise ValueError( f"the saved {cls.SOURCE_KIND} source config holds a source_id but no " diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 156da6a7c..66edd6cd5 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -23,7 +23,7 @@ from orcapod.core.sources.source_ids import parse_source_id from orcapod.core.sources.stream_builder import ( require_supported_nullable_types, - source_stream, + _source_stream, validate_source_table, ) from orcapod.errors import ( @@ -266,6 +266,8 @@ def from_config( resolve_source_from_config, ) + # An invalid saved config cannot fall back to a proxy that replays its cache. + cls._require_no_saved_system_tags(config) cache_db_ref = config["cache_database"] if isinstance(cache_db_ref, str): if db_registry is None: @@ -778,7 +780,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 source_stream( + return _source_stream( all_records, self.data_context.type_converter, tag_columns=tag_keys, diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 270fc1b82..acbdfe788 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -10,20 +10,22 @@ import pyarrow as pa from typing_extensions import override -from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.source_ids import location_source_name +from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.sources.reload import keep_nullable_columns, same_rows +from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.stream_builder import ( - normalize_record_id_columns, SourceStreamBuilder, SourceStreamResult, - require_custom_system_tags, - require_supported_nullable_types, + normalize_record_id_columns, require_live_logical_types, + require_supported_nullable_types, ) from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import ( + _normalize_column_list, + require_names_not_system_tags, +) _INFINITY = re.compile(r"\s*[+-]?inf(inity)?\s*", re.IGNORECASE) """The texts pyarrow's CSV reader reads as an infinity: ``inf`` or ``infinity``, any @@ -122,9 +124,7 @@ def _refuse_overflow(values: pa.ChunkedArray[Any], texts: pa.ChunkedArray[Any]) ) -def _read_declared( - path: str, schema: pa.Schema, system_tag_columns: Collection[str] -) -> pa.Table: +def _read_declared(path: str, schema: pa.Schema) -> pa.Table: """Read a CSV file with every column parsed as ``schema`` declares it (ITL-1322). The text of each cell is parsed as its column's declared type; nothing is @@ -199,6 +199,7 @@ def as_text(columns: list[str], include: list[str]) -> pa_csv.ConvertOptions: table = parse(as_text(text_like, [])) # text-like columns only: one parse else: table = parse(pa_csv.ConvertOptions(column_types=reader_types)) + require_names_not_system_tags(table.column_names) if table.column_names != schema.names: raise ValueError( f"the file's columns {table.column_names} are not the schema's fields " @@ -251,8 +252,7 @@ def as_text(columns: list[str], include: list[str]) -> pa_csv.ConvertOptions: table = table.set_column( table.column_names.index(field.name), field.name, value ) - require_custom_system_tags(table, system_tag_columns, schema=schema) - # A null in an ordinary non-nullable field raises here, naming the field. + # A null in a non-nullable field raises here, naming the field. return table.cast(schema) @@ -292,7 +292,6 @@ def __init__( self, file_path: str, tag_columns: str | Collection[str] = (), - system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, source_id: str | None = None, schema: pa.Schema | None = None, @@ -312,7 +311,6 @@ def __init__( self._access_path = os.path.abspath(file_path) self._schema = schema self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) - self._system_tag_columns: Collection[str] = system_tag_columns self._record_id_columns = normalize_record_id_columns(record_id_columns) self._key_columns = self._record_id_columns or () self._file_state = _file_state(self._access_path) @@ -329,7 +327,6 @@ def __init__( result = self._build(table) self._stream = result.stream self._tag_columns = result.tag_columns - self._system_tag_columns = result.system_tag_columns if self._source_name is None: self._source_name = result.source_name @@ -349,14 +346,14 @@ def _read_table(self) -> pa.Table: if self._schema is None: table: pa.Table = pa_csv.read_csv(self._access_path) + require_names_not_system_tags(table.column_names) require_supported_nullable_types(table.schema) return table.cast(arrow_utils.infer_schema_nullable(table)) + require_names_not_system_tags(self._schema.names) require_supported_nullable_types(self._schema) - require_live_logical_types(self._schema, exclude=self._system_tag_columns) + require_live_logical_types(self._schema) try: - return _read_declared( - self._access_path, self._schema, self._system_tag_columns - ) + return _read_declared(self._access_path, self._schema) except ValueError as exc: # pyarrow's ArrowInvalid is a ValueError # The reader names a column by its position in the file, which is the # schema's field order (a schema names every column, in order). @@ -377,7 +374,6 @@ def _build(self, table: pa.Table) -> SourceStreamResult: source_name=self._source_name, kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), - system_tag_columns=self._system_tag_columns, ) @override @@ -388,7 +384,7 @@ def check_for_new_data(self) -> bool: file written again with the same rows (in another order too, given a ``record_id_columns``) leaves the held rows and the modified time as they are. The rows are compared as read from the file, - every column included (a ``system_tag_columns`` column too), in order unless a + every column included, in order unless a ``record_id_columns`` gives the record ids (``same_rows``). @@ -452,7 +448,6 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "file_path": self._file_path, "tag_columns": list(self._tag_columns), **self._tag_only_config(), - "system_tag_columns": list(self._system_tag_columns), "record_id_columns": None if self._record_id_columns is None else list(self._record_id_columns), @@ -516,7 +511,6 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> CSVSource: file_path=config["file_path"], tag_columns=config.get("tag_columns", ()), tag_only_columns=saved_tag_only_columns(config), - system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), source_id=name, schema=cls.saved_schema(config), diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 2953acc90..9e8fb9809 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -11,17 +11,16 @@ from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, - declare_native_custom_system_tags, normalize_record_id_columns, read_arrow_frame_input, - require_custom_system_tags, - require_custom_system_tags_values, require_live_logical_types, require_supported_nullable_types, ) -from orcapod.errors import InputValidationError from orcapod.utils import arrow_utils, polars_data_utils -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import ( + _normalize_column_list, + require_names_not_system_tags, +) from orcapod.semantic_types._schema_conversion import arrow_table_for_rows @@ -61,7 +60,6 @@ def __init__( self, data: FrameInitTypes, tag_columns: str | Collection[str] = (), - system_tag_columns: Collection[str] = (), source_id: str | None = None, schema: pa.Schema | None = None, *, @@ -73,19 +71,8 @@ def __init__( super().__init__(source_id=source_id, **kwargs) input_schema = arrow_input_schema = None - if ( - arrow_frame := read_arrow_frame_input( - data, system_tag_columns=system_tag_columns - ) - ) is not None: + if (arrow_frame := read_arrow_frame_input(data)) is not None: arrow_input, input_schema = arrow_frame - if schema is None: - require_custom_system_tags(arrow_input, system_tag_columns) - else: - require_custom_system_tags_values(arrow_input, system_tag_columns) - require_custom_system_tags( - arrow_input, system_tag_columns, schema=schema - ) arrow_input_schema = arrow_input.schema # Polars rechunks native tables but preserves chunks on exporter inputs. df = cast( @@ -95,15 +82,10 @@ def __init__( else: df = pl.DataFrame(data) + require_names_not_system_tags(df.columns) + # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] - for name in object_columns: - if name in system_tag_columns: - raise InputValidationError( - f"Custom system-tag column {name!r} has type {pl.Object}. " - "Declare a non-nullable string column with no null values " - "and convert its values to text first." - ) if object_columns: logger.info( f"Converting {len(object_columns)} object column(s) to Arrow format" @@ -127,14 +109,10 @@ def __init__( arrow_table = df.to_arrow() if input_schema is None: - require_live_logical_types(arrow_table.schema, exclude=system_tag_columns) + require_live_logical_types(arrow_table.schema) if schema is not None: require_supported_nullable_types(schema) - if arrow_input_schema is None: - require_custom_system_tags_values(arrow_table, system_tag_columns) - require_custom_system_tags( - arrow_table, system_tag_columns, schema=schema - ) + require_names_not_system_tags(schema.names) require_live_logical_types(schema) arrow_table = arrow_table.cast(schema) elif arrow_input_schema is not None: @@ -142,14 +120,9 @@ def __init__( arrow_table, arrow_input_schema ) else: - arrow_table = declare_native_custom_system_tags( - arrow_table, system_tag_columns - ) require_supported_nullable_types(arrow_table.schema) # Native frames carry no Arrow nullability declarations. - inferred = arrow_utils.infer_schema_nullable( - arrow_table.drop_columns(list(system_tag_columns)) - ) + inferred = arrow_utils.infer_schema_nullable(arrow_table) arrow_table = arrow_utils.restore_schema_nullability(arrow_table, inferred) self._key_columns = normalize_record_id_columns(record_id_columns) or () @@ -162,7 +135,6 @@ def __init__( kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, - system_tag_columns=system_tag_columns, input_schema=input_schema if schema is None else schema, ) @@ -191,6 +163,7 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> DataFrameSourc Raises: NotImplementedError: Always. """ + cls._require_no_saved_system_tags(config) raise NotImplementedError( "DataFrameSource cannot be reconstructed from config — " "the original DataFrame is not serializable." diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 9853975ef..20ec3123e 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -16,25 +16,27 @@ from collections.abc import Collection, Iterator from contextlib import contextmanager -from typing import Any, ClassVar, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, ClassVar import pyarrow as pa from typing_extensions import override -from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.source_ids import location_source_name +from orcapod.core.sources.base import RootSource from orcapod.core.sources.reload import keep_nullable_columns, same_rows +from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.stream_builder import ( - require_custom_system_tags, - require_supported_nullable_types, - require_live_logical_types, - normalize_record_id_columns, SourceStreamBuilder, SourceStreamResult, + normalize_record_id_columns, + require_live_logical_types, + require_supported_nullable_types, ) from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import ( + _normalize_column_list, + require_names_not_system_tags, +) if TYPE_CHECKING: from orcapod import contexts @@ -58,8 +60,6 @@ class DBTableSource(RootSource): accepted as a single column name. If ``None`` (default), the table's primary-key columns are used. Raises ``ValueError`` if the table has no primary key and no explicit columns are given. - system_tag_columns: Additional system-level tag columns (passed through - to ``SourceStreamBuilder``; mirrors ``DeltaTableSource`` API). record_id_columns: The key columns whose values identify a row (the record id), in key order. ``None`` (default): the table's primary key; a table without one is refused. ``()``: the row's position, ``row_``. @@ -94,7 +94,6 @@ def __init__( connector: DBConnectorProtocol, table_name: str, tag_columns: str | Collection[str] | None = None, - system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, source_id: str | None = None, label: str | None = None, @@ -168,7 +167,6 @@ def __init__( # _query allows subclasses (e.g. SQLiteTableSource) to inject a custom # SELECT (e.g. SELECT rowid, * FROM "t") without duplicating the rest of init. self._query = _query if _query is not None else f'SELECT * FROM "{table_name}"' - self._system_tag_columns: Collection[str] = system_tag_columns table = self._read_table(connector) # The rows as read, columns and types included: a check compares a new read # with them, and refuses a table whose columns changed. @@ -185,7 +183,6 @@ def __init__( result = self._build(table) self._stream = result.stream self._tag_columns = result.tag_columns - self._system_tag_columns = result.system_tag_columns if self._source_name is None: self._source_name = result.source_name @@ -230,7 +227,8 @@ def _read_table( if not batches: raise ValueError(f"Table {self._table_name!r} is empty.") table: pa.Table = pa.Table.from_batches(batches) - require_live_logical_types(table.schema, exclude=self._system_tag_columns) + require_names_not_system_tags(table.column_names) + require_live_logical_types(table.schema) # Apply database-defined nullability: the connector's get_column_info # returns the authoritative nullable flag per column from the DB schema. col_infos = connector.get_column_info(self._table_name) @@ -244,9 +242,6 @@ def _read_table( f.name, f.type, nullable=db_nullable.get(f.name, True), - metadata=f.metadata or None - if f.name in self._system_tag_columns - else None, ) for f in table.schema ] @@ -255,8 +250,6 @@ def _read_table( [table.column(i) for i in range(table.num_columns)], schema=db_schema, ) - # Validate nominated fields before fallback inference for ordinary columns. - require_custom_system_tags(table, self._system_tag_columns) require_supported_nullable_types(table.schema) inferred = table.cast(arrow_utils.infer_schema_nullable(table)) return inferred if held is None else keep_nullable_columns(inferred, held) @@ -271,7 +264,6 @@ def _build(self, table: pa.Table) -> SourceStreamResult: source_name=self._source_name, kind_part=self.kind_part(), record_id_columns=self._key_columns, - system_tag_columns=self._system_tag_columns, ) @contextmanager @@ -291,7 +283,7 @@ def check_for_new_data(self) -> bool: in any order when a ``record_id_columns`` gives the record ids: a table that returns the same rows in another order (an unordered ``SELECT``) is unchanged. The rows are compared as read, every column - included (a ``system_tag_columns`` column too; ``same_rows``). + included (``same_rows``). Returns: ``True`` if the source now holds new rows. @@ -325,7 +317,6 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "table_name": self._table_name, "tag_columns": list(self._tag_columns), **self._tag_only_config(), - "system_tag_columns": list(self._system_tag_columns), "record_id_columns": None if self._record_id_columns is None else list(self._record_id_columns), @@ -349,6 +340,7 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> DBTableSource: a registry helper (``build_db_connector_from_config``) in PLT-1074/1075/1076. """ + cls._require_no_saved_system_tags(config) raise NotImplementedError( "DBTableSource.from_config requires a registered connector factory. " "Implement build_db_connector_from_config in PLT-1074/1075/1076." diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index a0261b1be..590fc0a1e 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -1,28 +1,30 @@ from __future__ import annotations import os - from collections.abc import Collection from pathlib import Path -from typing import Any, ClassVar, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, ClassVar import pyarrow as pa from typing_extensions import override -from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.source_ids import location_source_name +from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.sources.reload import same_rows +from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.stream_builder import ( - normalize_record_id_columns, SourceStreamBuilder, - require_live_logical_types, SourceStreamResult, + normalize_record_id_columns, + require_live_logical_types, ) from orcapod.databases.storage_utils import delta_to_pyarrow_dataset from orcapod.types import PathLike from orcapod.utils.lazy_module import LazyModule -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import ( + _normalize_column_list, + require_names_not_system_tags, +) if TYPE_CHECKING: import deltalake @@ -60,7 +62,6 @@ def __init__( self, delta_table_path: PathLike, tag_columns: str | Collection[str] = (), - system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, source_id: str | None = None, *, @@ -84,7 +85,6 @@ def __init__( raise ValueError(f"Delta table not found at {self._delta_table_path}") self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) - self._system_tag_columns: Collection[str] = system_tag_columns self._record_id_columns = normalize_record_id_columns(record_id_columns) self._key_columns = self._record_id_columns or () self._version: int = self._delta_table.version() @@ -101,7 +101,6 @@ def __init__( result = self._build(table) self._stream = result.stream self._tag_columns = result.tag_columns - self._system_tag_columns = result.system_tag_columns if self._source_name is None: self._source_name = result.source_name @@ -109,9 +108,11 @@ def _read_table(self) -> "pa.Table": """Read the table at the Delta version ``self._delta_table`` is loaded at.""" # The Delta log stores field-level nullable flags; to_pyarrow_dataset() # preserves them exactly — no inference needed. - return delta_to_pyarrow_dataset( + table = delta_to_pyarrow_dataset( self._delta_table, as_large_types=True ).to_table() + require_names_not_system_tags(table.column_names) + return table def _build(self, table: "pa.Table") -> SourceStreamResult: """Enrich ``table`` as this source's stream (source info, system tags).""" @@ -123,7 +124,6 @@ def _build(self, table: "pa.Table") -> SourceStreamResult: source_name=self._source_name, kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), - system_tag_columns=self._system_tag_columns, ) @override @@ -133,7 +133,7 @@ def check_for_new_data(self) -> bool: Only the Delta log is read when the version did not move. A version that moved without changing the rows (``OPTIMIZE``, a metadata change) leaves the held rows and the modified time as they are. The rows are compared as read from the - table, every column included (a ``system_tag_columns`` column too), in any + table, every column included, in any order (``same_rows``). Returns: @@ -174,7 +174,6 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "delta_table_path": str(self._delta_table_path), "tag_columns": list(self._tag_columns), **self._tag_only_config(), - "system_tag_columns": list(self._system_tag_columns), "record_id_columns": None if self._record_id_columns is None else list(self._record_id_columns), @@ -193,7 +192,6 @@ def from_config( delta_table_path=config["delta_table_path"], tag_columns=config.get("tag_columns", ()), tag_only_columns=saved_tag_only_columns(config), - system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), source_id=name, ), diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 714eee8d0..614f4fd55 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -6,14 +6,13 @@ from typing import TYPE_CHECKING, Any, ClassVar, cast import pyarrow as pa +from typing_extensions import override from orcapod.core.data_tags import ( stored_data_tags, stream_data_tags, without_tag_kind_marks, ) -from typing_extensions import override - from orcapod.core.identity_chains import require_bound_identity_origin from orcapod.core.output_bindings import ( binding_checked_rows, @@ -33,21 +32,21 @@ from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, + _source_stream, normalize_record_id_columns, require_supported_nullable_types, - source_stream, validate_source_table, ) -from orcapod.core.streams.view import ( - ViewStatus, - StreamView, -) from orcapod.core.streams.base import ( check_head_size, schema_requires_io, typed_arrow_schemas, typed_zero_row_table, ) +from orcapod.core.streams.view import ( + StreamView, + ViewStatus, +) from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema @@ -55,9 +54,9 @@ from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: - from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from orcapod.types import ContentHash @@ -469,6 +468,7 @@ def from_config( """ from orcapod.pipeline.serialization import resolve_source_from_config + cls._require_no_saved_system_tags(config) # Reading a saved DerivedSource is a use of a provisional source, also when its # origin (a job node) cannot be rebuilt and the constructor is never reached: a # loaded job warns for it as for a rebuilt one (ITL-1331). @@ -772,6 +772,10 @@ def _derive_from( table: Rows of the origin. tags_as_data: Maps a tag column of the origin to the name of its copy. """ + require_supported_nullable_types(table.schema) + table = arrow_utils.drop_columns_with_prefix( + table, (constants.SYSTEM_TAG_PREFIX,) + ) for tag, name in tags_as_data.items(): # The copy is the tag's own Arrow column under a renamed field, so its # type, nullability and field metadata are the tag's exactly. @@ -988,7 +992,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 source_stream( + return _source_stream( validate_source_table(table), self.data_context.type_converter, tag_columns=self._origin.keys()[0], diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 3ddb1319f..6ff048353 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -14,13 +14,15 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, - declare_native_custom_system_tags, - require_supported_nullable_types, require_live_logical_types, + require_supported_nullable_types, ) from orcapod.types import DataValue, SchemaLike from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import ( + _normalize_column_list, + require_names_not_system_tags, +) from orcapod.utils.tensor_conversions import warn_source_tensor_conversions from orcapod.semantic_types.narrow_float_keys import ( @@ -60,7 +62,6 @@ def __init__( self, data: Collection[Mapping[str, DataValue]], tag_columns: str | Collection[str] = (), - system_tag_columns: Collection[str] = (), data_schema: SchemaLike | pa.Schema | None = None, source_id: str | None = None, *, @@ -93,11 +94,20 @@ def __init__( else: rows = [dict(row) for row in data] + for row in rows: + require_names_not_system_tags(row.keys()) + if data_schema is not None: + require_names_not_system_tags( + data_schema.names + if isinstance(data_schema, pa.Schema) + else tuple(data_schema) + ) + # Accept either a Python SchemaLike (Mapping[str, type]) or a # pa.Schema directly via data_schema; route to the converter accordingly. if isinstance(data_schema, pa.Schema): require_supported_nullable_types(data_schema) - require_live_logical_types(data_schema, exclude=system_tag_columns) + require_live_logical_types(data_schema) arrow_table = arrow_table_for_rows( self.data_context.type_converter, rows, @@ -110,9 +120,6 @@ def __init__( python_schema=data_schema, ) if data_schema is None: - arrow_table = declare_native_custom_system_tags( - arrow_table, system_tag_columns - ) # No explicit schema — infer nullable from actual values. # The type converter defaults all fields to nullable=True; derive # the correct flags here so the builder can trust the schema as-is. @@ -130,7 +137,6 @@ def __init__( kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, - system_tag_columns=system_tag_columns, ) self._stream = result.stream @@ -159,6 +165,7 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> DictSource: Raises: NotImplementedError: Always. """ + cls._require_no_saved_system_tags(config) raise NotImplementedError( "DictSource cannot be reconstructed from config — " "original data is not serializable." diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 8e00aa704..1d345bc84 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -187,8 +187,10 @@ def from_config(cls, config: dict[str, Any], db_registry=None) -> "ListSource": """Not supported — ListSource data cannot be reconstructed from config. Raises: - NotImplementedError: Always. + ValueError: If the config names custom system tags. + NotImplementedError: For all other configs. """ + cls._require_no_saved_system_tags(config) raise NotImplementedError( "ListSource cannot be reconstructed from config — " "original list data is not serializable." diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index f6d2ac7e4..81a84cb32 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -33,7 +33,7 @@ require_supported_nullable_types, validate_source_table, ) -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( check_head_size, typed_zero_row_table, @@ -51,7 +51,7 @@ from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, Cursor, PollingConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.semantic_types.narrow_float_keys import ( require_python_schema_without_narrow_float_keys, @@ -67,7 +67,6 @@ if TYPE_CHECKING: from polars._typing import FrameInitTypes - from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from orcapod.types import Schema @@ -340,6 +339,13 @@ def __init__( # schema of the declared Python types; it fixes the source's identity. self._declared_arrow: pa.Schema | None = None unified_schema = self._impl.schema() + if unified_schema is not None: + names = ( + unified_schema.names + if isinstance(unified_schema, pa.Schema) + else tuple(unified_schema.keys()) + ) + schema_utils.require_names_not_system_tags(names) if isinstance(unified_schema, pa.Schema): require_supported_nullable_types(unified_schema) require_live_logical_types(unified_schema) @@ -597,7 +603,7 @@ def _typed_zero_row_table(self) -> pa.Table | None: table = typed_zero_row_table(batch) if table is None: return None - zero_rows = stream_from_derived_table( + zero_rows = ArrowTableStream._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) @@ -761,6 +767,7 @@ def from_config( """ import importlib + cls._require_no_saved_system_tags(config) module = importlib.import_module(config["impl_module"]) # Walk dotted qualname to support nested classes (e.g. "Outer.Inner") impl_class: Any = module @@ -943,6 +950,7 @@ def _build_stream_from_df( ) df = df.with_columns([pl.from_arrow(c) for c in sub_table]) + schema_utils.require_names_not_system_tags(df.columns) raw = df.to_arrow() require_supported_nullable_types(raw.schema) # An Arrow input has already been checked against its authoritative schema. @@ -1132,7 +1140,7 @@ def _combine( ], promote_options="default", ) - return stream_from_derived_table( + return ArrowTableStream._from_derived_table( table=validate_source_table(combined), tag_columns=self._tag_columns ) diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index d0fd966d7..dabeffadb 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -18,12 +18,12 @@ from contextlib import contextmanager from typing import TYPE_CHECKING, Any, ClassVar, cast -from orcapod.core.data_tags import TagOnlyColumns from typing_extensions import override +from orcapod.core.data_tags import TagOnlyColumns +from orcapod.core.sources.base import saved_tag_only_columns from orcapod.core.sources.db_table_source import DBTableSource from orcapod.core.sources.source_ids import joined_location -from orcapod.core.sources.base import saved_tag_only_columns from orcapod.databases.postgresql_connector import PostgreSQLConnector from orcapod.protocols.db_connector_protocol import DBConnectorProtocol @@ -150,7 +150,6 @@ class PostgreSQLTableSource(DBTableSource): accepted as a single column name. If ``None`` (default), the table's primary-key columns are used. Raises ``ValueError`` if the table has no primary key and no explicit columns are given. - system_tag_columns: Additional system-level tag columns. record_id_columns: The key columns that identify a row; ``None``: the primary key (a table without one is refused); ``()``: the position. source_id: The source's name; its id is ``postgresql_table_v1:`` @@ -182,7 +181,6 @@ def __init__( dsn: str, table_name: str, tag_columns: str | Collection[str] | None = None, - system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, source_id: str | None = None, label: str | None = None, @@ -200,7 +198,6 @@ def __init__( connector, table_name, tag_columns=tag_columns, - system_tag_columns=system_tag_columns, record_id_columns=record_id_columns, source_id=source_id, label=label, @@ -302,7 +299,6 @@ def from_config( table_name=config["table_name"], tag_columns=config.get("tag_columns"), tag_only_columns=saved_tag_only_columns(config), - system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), source_id=name, label=config.get("label"), diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index db49e4690..50d30c183 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -363,6 +363,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: @classmethod def from_config(cls, config: dict[str, Any], db_registry=None) -> SourceProxy: """Not supported — SourceProxy is created by the deserialization pipeline.""" + cls._require_no_saved_system_tags(config) raise NotImplementedError( "SourceProxy cannot be reconstructed via from_config. " "It is created automatically when a source cannot be loaded." diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index eff376f2d..0f15fee7b 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -51,31 +51,29 @@ from concurrent.futures import ThreadPoolExecutor from threading import Lock from types import TracebackType -from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple import pyarrow as pa from typing_extensions import override -from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.source_ids import joined_location, location_source_name +from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.sources.derived_source import validate_tags_as_data from orcapod.core.sources.provisional import warn_provisional_tags_as_data +from orcapod.core.sources.source_ids import joined_location, location_source_name from orcapod.core.sources.stream_builder import ( - require_custom_system_tags, - require_supported_nullable_types, - require_live_logical_types, SourceStreamBuilder, key_column_type_allowed, normalize_record_id_columns, + require_live_logical_types, + require_supported_nullable_types, row_identifiers, ) 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.core.streams.view import StreamView, ViewStatus from orcapod.databases.spiraldb_connector import ( SpiralDBConnector, SpiralDBTable, @@ -86,7 +84,10 @@ from orcapod.types import ColumnConfig, Condition from orcapod.types.condition import check_float_equalities, check_restriction from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import ( + _normalize_column_list, + require_names_not_system_tags, +) if TYPE_CHECKING: from orcapod import contexts @@ -251,7 +252,6 @@ class SpiralDBTableSource(RootSource): tag_columns: Columns to use as tag columns. A bare string is accepted as a single column name. If ``None`` (default), the table's primary-key (key-schema) columns are used. - system_tag_columns: Additional system-level tag columns. where: Column name to value, or a ``Condition`` (``orcapod.types``) of equalities and ranges. Only the rows that meet it are read; SpiralDB applies it before any row is transferred. Values follow the same type @@ -321,7 +321,6 @@ def __init__( table_name: str, dataset: str = "default", tag_columns: str | Collection[str] | None = None, - system_tag_columns: Collection[str] = (), where: "Mapping[str, object] | Condition | None" = None, limit: int | None = None, asof: int | None = None, @@ -399,6 +398,7 @@ def __init__( ) self._table_id = table.table_id schema = table.arrow_schema() + require_names_not_system_tags(schema.names) require_supported_nullable_types(schema) # One version for every read of this source object. A given version is # used as it is; a table that was never written has no version to pin. @@ -442,11 +442,6 @@ def __init__( tag_columns=resolved_tags, source_name=self._source_name, kind_part=self.kind_part(), - system_tag_columns=tuple( - name - for name in system_tag_columns - if name not in self._tags_as_data.values() - ), data_tags=self._data_tags, ) except ValueError as exc: @@ -472,7 +467,6 @@ def __init__( tag_columns=template.tag_columns, source_name=self._source_name, kind_part=self.kind_part(), - system_tag_columns=system_tag_columns, data_tags=self._data_tags, ) self._stream = template.stream @@ -481,7 +475,6 @@ def __init__( self._tag_only_columns = tuple( c for c in self._tag_columns if c not in self._data_tags ) - self._system_tag_columns = template.system_tag_columns except BaseException: self.close() raise @@ -817,9 +810,9 @@ def check_for_new_data(self) -> bool: # One lookup per check (ITL-1350): a table dropped and created again since # is found by this lookup, and its schema and version come from it. table = self._lookup_table() - schema = arrow_utils.drop_system_columns( - table.arrow_schema().empty_table() - ).schema + raw_schema = table.arrow_schema() + require_names_not_system_tags(raw_schema.names) + schema = arrow_utils.drop_system_columns(raw_schema.empty_table()).schema if not schema.equals(self._table_schema, check_metadata=True): raise ValueError( f"SpiralDB table {self._qualified!r}: " @@ -946,6 +939,7 @@ def _read_batches( ): for start in range(0, max(batch.num_rows, 1), self._batch_rows): raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)]) + require_names_not_system_tags(raw.column_names) require_supported_nullable_types(raw.schema) require_live_logical_types(raw.schema) rows = arrow_utils.drop_system_columns(raw) @@ -972,14 +966,12 @@ def _read_batches( "must be unique, so each row has its own identifier" ) rows = self._with_tag_copies(rows) - require_custom_system_tags(rows, self._system_tag_columns) if not rows.num_rows: continue identifiers.update(tokens) - yield self._builder.attach_provenance( + yield self._builder._attach_provenance( rows, tag_columns=self._tag_columns, - system_tag_columns=self._system_tag_columns, schema_hash=self._schema_hash, source_id=self.source_id, row_identifiers=tokens, @@ -1044,10 +1036,9 @@ 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 = stream_from_derived_table( + whole = ArrowTableStream._from_derived_table( 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) @@ -1225,7 +1216,6 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "table_id": self._table_id, "tag_columns": list(self._tag_columns), **self._tag_only_config(), - "system_tag_columns": list(self._system_tag_columns), "where": self._condition.to_config(), "limit": self._limit, "asof": self._given_asof, @@ -1264,7 +1254,6 @@ def from_config( dataset=config.get("dataset", "default"), tag_columns=config.get("tag_columns"), tag_only_columns=saved_tag_only_columns(config), - system_tag_columns=config.get("system_tag_columns", ()), where=Condition.from_config(config.get("where") or {}), limit=config.get("limit"), asof=config.get("asof"), diff --git a/src/orcapod/core/sources/sqlite_table_source.py b/src/orcapod/core/sources/sqlite_table_source.py index eab59a821..56ef7be27 100644 --- a/src/orcapod/core/sources/sqlite_table_source.py +++ b/src/orcapod/core/sources/sqlite_table_source.py @@ -26,15 +26,15 @@ import os from collections.abc import Collection, Iterator from contextlib import contextmanager -from typing import Any, ClassVar, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, ClassVar -from orcapod.core.data_tags import TagOnlyColumns from typing_extensions import override +from orcapod.core.data_tags import TagOnlyColumns +from orcapod.core.sources.base import saved_tag_only_columns from orcapod.core.sources.db_table_source import DBTableSource from orcapod.core.sources.source_ids import joined_location from orcapod.core.sources.stream_builder import normalize_record_id_columns -from orcapod.core.sources.base import saved_tag_only_columns from orcapod.databases.sqlite_connector import SQLiteConnector from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.utils.schema_utils import _normalize_column_list @@ -82,7 +82,6 @@ class SQLiteTableSource(DBTableSource): accepted as a single column name. If ``None`` (default), the table's primary-key columns are used; ROWID-only tables fall back to ``["rowid"]``. - system_tag_columns: Additional system-level tag columns. record_id_columns: The key columns that identify a row; ``None``: the primary key (a table without one is refused); ``()``: the position. source_id: The source's name; its id is ``sqlite_table_v1:`` @@ -111,7 +110,6 @@ def __init__( db_path: str | os.PathLike, table_name: str, tag_columns: str | Collection[str] | None = None, - system_tag_columns: Collection[str] = (), record_id_columns: str | Collection[str] | None = None, source_id: str | None = None, label: str | None = None, @@ -162,7 +160,6 @@ def __init__( connector, table_name, tag_columns=resolved_tags, - system_tag_columns=system_tag_columns, record_id_columns=record_id_columns, source_id=source_id, label=label, @@ -245,7 +242,6 @@ def from_config( table_name=config["table_name"], tag_columns=config.get("tag_columns"), tag_only_columns=saved_tag_only_columns(config), - system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), source_id=name, label=config.get("label"), diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 80902cda4..7fc19f16b 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -23,7 +23,7 @@ parse_kind_part, require_source_name, ) -from orcapod.core.streams.arrow_table_stream import stream_from_derived_table +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import ( InputValidationError, RepeatedDictKeyError, @@ -74,18 +74,11 @@ def _stored_logical_fields(field: pa.Field[Any]) -> Iterator[tuple[str, str]]: yield f"{field.name!r}.{path}", identifier -def require_live_logical_types( - schema: pa.Schema, *, exclude: Collection[str] = () -) -> None: - """Refuse stored logical fields in external Arrow inputs, at any depth. - - Early checks before a lossy conversion may exclude custom system tags, - which already have their own metadata validation. - """ +def require_live_logical_types(schema: pa.Schema) -> None: + """Refuse stored logical fields in external Arrow inputs, at any depth.""" columns = sorted( f"{path} ({identifier})" for field in schema - if field.name not in exclude for path, identifier in _stored_logical_fields(field) ) if columns: @@ -96,14 +89,13 @@ def require_live_logical_types( ) -def read_arrow_frame_input( - data: FrameInitTypes, *, system_tag_columns: Collection[str] = () -) -> tuple[pa.Table, pa.Schema] | None: +def read_arrow_frame_input(data: FrameInitTypes) -> tuple[pa.Table, pa.Schema] | None: """Read Arrow frame inputs and validate annotations before Polars can drop them.""" import pandas as pd import polars as pl if isinstance(data, pd.DataFrame): + schema_utils.require_names_not_system_tags([str(name) for name in data.columns]) # Arrow-backed dtypes retain nested field metadata. Check them before # Polars reads the frame, while keeping its normal conversion for pandas. require_live_logical_types( @@ -127,7 +119,8 @@ def read_arrow_frame_input( # Passing the StructType directly to pa.schema would also use C import. input_schema = pa.schema(list(data.type)) if input_schema is not None: - require_live_logical_types(input_schema, exclude=system_tag_columns) + schema_utils.require_names_not_system_tags(input_schema.names) + require_live_logical_types(input_schema) # Like Polars, prefer the array export when both are available. if hasattr(data, "__arrow_c_array__"): batch = pa.record_batch(cast("ArrowArrayExportable", data)) @@ -140,7 +133,8 @@ def read_arrow_frame_input( # C exporters describe live and stored extensions the same way. Validate # the imported field types and any annotations that remain on storage. input_schema = table.schema - require_live_logical_types(input_schema, exclude=system_tag_columns) + schema_utils.require_names_not_system_tags(input_schema.names) + require_live_logical_types(input_schema) return table, input_schema @@ -173,7 +167,7 @@ def require_system_tag_without_field_metadata( "Arrow field metadata on a system tag. Rebuild the cache." ) raise InputValidationError( - f"Custom system-tag column {field.name!r} has Arrow field metadata. " + f"System-tag column {field.name!r} has Arrow field metadata. " "Remove the field metadata before building the source." ) @@ -189,58 +183,13 @@ def validate_source_table(table: pa.Table, *, stored_cache: bool = False) -> pa. The same table, with fields and values unchanged. """ require_supported_nullable_types(table.schema) - require_custom_system_tags( - table, - [ - name - for name in table.column_names - if name.startswith(constants.SYSTEM_TAG_PREFIX) - ], - stored_cache=stored_cache, - ) - return table - - -def require_custom_system_tags( - table: pa.Table, - names: Collection[str], - *, - schema: pa.Schema | None = None, - stored_cache: bool = False, -) -> None: - """Validate custom system-tag declarations and values. - - Args: - table: The source's Arrow columns. - names: The columns nominated as system tags. - schema: The declared fields if the reader has yet to apply them. - stored_cache: Report the rebuild remedy for a persisted source cache. - - Raises: - ValueError: If a nominated column is missing from the source table. - InputValidationError: If a nominated column has field metadata, can - hold nulls or is not text. - """ - if not names: - return - fields = table.schema if schema is None else schema - available = set(fields.names).intersection(table.column_names) - if missing := sorted(set(names) - available): - raise ValueError( - f"system_tag_columns not found in table: {missing}. " - f"Available columns: {sorted(available)}" - ) - for name in names: - field = fields.field(name) + for index, field in enumerate(table.schema): + if not field.name.startswith(constants.SYSTEM_TAG_PREFIX): + continue require_system_tag_without_field_metadata(field, stored_cache=stored_cache) - if schema is not None: - require_system_tag_without_field_metadata( - table.schema.field(name), stored_cache=stored_cache - ) - has_nulls = table.column(name).null_count > 0 if ( field.nullable - or has_nulls + or table.column(index).null_count or not ( pa.types.is_string(field.type) or pa.types.is_large_string(field.type) @@ -248,80 +197,10 @@ def require_custom_system_tags( ) ): raise InputValidationError( - f"Custom system-tag column {name!r} has type {field.type} " - f"({'nullable' if field.nullable else 'non-nullable'}" - f"{', contains null values' if has_nulls else ''}). " - "Declare a non-nullable string column with no null values " - "and convert its values to text first." - ) - - -def declare_native_custom_system_tags( - table: pa.Table, names: Collection[str] -) -> pa.Table: - """Declare native custom system tags as required large strings. - - Args: - table: A table inferred from native Python values. - names: The columns nominated as custom system tags. - - Returns: - The table with nominated fields declared as non-nullable large strings. - - Raises: - InputValidationError: If a nominated column is not text or contains nulls. - """ - if not names: - return table - require_custom_system_tags_values(table, names) - schema = pa.schema( - [ - pa.field( - field.name, - pa.large_string(), - nullable=False, - metadata=field.metadata, - ) - if field.name in names - else field - for field in table.schema - ], - metadata=cast(dict[bytes | str, bytes | str] | None, table.schema.metadata), - ) - return table.cast(schema) - - -def require_custom_system_tags_values(table: pa.Table, names: Collection[str]) -> None: - """Validate values and types before declaring native custom system tags. - - Args: - table: A table inferred from native Python values. - names: The columns nominated as custom system tags. - - Raises: - ValueError: If a nominated column is missing. - InputValidationError: If a nominated column is not text or contains nulls. - """ - if missing := sorted(set(names) - set(table.column_names)): - raise ValueError( - f"system_tag_columns not found in table: {missing}. " - f"Available columns: {sorted(table.column_names)}" - ) - for name in names: - field = table.schema.field(name) - require_system_tag_without_field_metadata(field) - has_nulls = table.column(name).null_count > 0 - if has_nulls or 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"Custom system-tag column {name!r} has type {field.type} " - f"({'contains null values' if has_nulls else 'non-text values'}). " - "Declare a non-nullable string column with no null values " - "and convert its values to text first." + f"System-tag column {field.name!r} must be a non-nullable string " + "column with no null values." ) + return table def normalize_record_id_columns( @@ -654,7 +533,6 @@ class SourceStreamResult: source_id: str source_name: str tag_columns: tuple[str, ...] - system_tag_columns: tuple[str, ...] data_tags: tuple[str, ...] = () @@ -674,7 +552,6 @@ def build( tag_columns: Collection[str], source_name: str | None = None, record_id_columns: str | Collection[str] | None = (), - system_tag_columns: Collection[str] = (), kind_part: str | None = None, data_tags: Collection[str] = (), *, @@ -705,7 +582,6 @@ def build( (``key_row_identifier``), which follows the row regardless of its position (given a stable ``source_id``). Empty: the row's position, ``row_``, stable only while row order is. - system_tag_columns: Additional system-level tag columns. kind_part: The kind part of the source id, ``_v``, for example ``dict_v1`` (``source_ids.kind_part``). Required: the source id is ``:`` (``source_ids.build_source_id``). @@ -746,7 +622,7 @@ def build( hash_in_key_order, source_name=source_name, key_columns=key_columns ) tag_columns_tuple = tuple(tag_columns) - system_tag_columns_tuple = tuple(system_tag_columns) + schema_utils.require_names_not_system_tags(table.column_names) require_supported_nullable_types(table.schema) data_tags_tuple = tuple(c for c in tag_columns_tuple if c in data_tags) if unknown := set(data_tags) - set(tag_columns_tuple): @@ -764,29 +640,27 @@ def build( if not from_origin: require_live_logical_types( table.schema if input_schema is None else input_schema, - exclude=system_tag_columns_tuple, ) # Dictionary-encoded columns are not currently supported (ITL-1264, # ITL-1277). The stream refuses them too; checking first reports the # dictionary, not a key column error, and before anything is hashed. It runs - # before the system columns are dropped: a hand-built meta, source-info or - # system-tag column holding a dictionary is refused, not dropped silently. + # before dropping reserved meta and source-info columns so an unsupported + # column type is reported even in those columns. if found := schema_utils.dictionary_columns(table.schema): raise schema_utils.dictionary_columns_error( - found, tag_columns_tuple, data_tags_tuple, system_tag_columns_tuple + found, tag_columns_tuple, data_tags_tuple ) # Nor are columns of a type the schema hash rejects (a union, a list view, a # run-end-encoded type; ITL-640): refused here first, as the stream refuses # them, with the same message. if found := schema_utils.schema_hash_rejected_columns(table.schema): raise schema_utils.schema_hash_rejected_columns_error( - found, tag_columns_tuple, data_tags_tuple, system_tag_columns_tuple + found, tag_columns_tuple, data_tags_tuple ) # 1. Drop system columns from raw input. table = arrow_utils.drop_system_columns(table) - require_custom_system_tags(table, system_tag_columns_tuple) # 2. Validate tag_columns. A table with no columns at all (e.g. a # DictSource built from no rows and no schema) gets its own error, since @@ -858,10 +732,9 @@ def build( source_id = build_source_id(kind, version, source_name) # 7. Attach the source-info tokens and the system tags. - stream = self.attach_provenance( + stream = self._attach_provenance( table, tag_columns=tag_columns_tuple, - system_tag_columns=system_tag_columns_tuple, schema_hash=schema_hash, source_id=source_id, row_identifiers=identifiers, @@ -875,16 +748,14 @@ def build( source_id=source_id, source_name=source_name, tag_columns=tag_columns_tuple, - system_tag_columns=system_tag_columns_tuple, data_tags=data_tags_tuple, ) - def attach_provenance( + def _attach_provenance( self, table: pa.Table, *, tag_columns: Sequence[str], - system_tag_columns: Sequence[str], schema_hash: str, source_id: str, row_identifiers: Sequence[str], @@ -904,7 +775,6 @@ def attach_provenance( Args: table: The rows, with nullable flags already set correctly. tag_columns: Column names forming the tag for each row. - system_tag_columns: Additional system-level tag columns. schema_hash: The source's schema hash, which names its system-tag columns. source_id: The canonical source name. row_identifiers: One identifier per row, identifying the row within the @@ -937,22 +807,20 @@ def attach_provenance( row_identifiers, ) # Nullable flags are already correct — the caller set them. - return source_stream( + return _source_stream( table, self._data_context.type_converter, tag_columns=tag_columns, - system_tag_columns=system_tag_columns, data_tags=data_tags, data_context=self._data_context, ) -def source_stream( +def _source_stream( table: pa.Table, converter: TypeConverterProtocol, *, tag_columns: Collection[str], - system_tag_columns: Collection[str] = (), data_tags: Collection[str] = (), data_context: DataContext | None = None, ) -> ArrowTableStream: @@ -971,10 +839,9 @@ def source_stream( dict_keys.refuse_repeated_dict_keys(table.column(index), converter) except RepeatedDictKeyError as exc: raise exc.in_column(field.name) from exc - return stream_from_derived_table( + return ArrowTableStream._from_derived_table( table, tag_columns=tag_columns, - system_tag_columns=system_tag_columns, data_tags=data_tags, data_context=data_context, ) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index d3ffaff3a..75cf54d8e 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -4,7 +4,7 @@ import logging from collections.abc import Collection, Iterator from datetime import datetime -from typing import Any +from typing import Any, Self import pyarrow as pa @@ -53,9 +53,7 @@ class ArrowTableStream(MaterializedOutput, StreamBase): 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. + System-tag columns are reserved for Orcapod's provenance. """ # The table's rows are held, not computed: a run() view says "all N rows", as @@ -66,30 +64,23 @@ def __init__( self, table: "pa.Table", tag_columns: Collection[str] = (), - system_tag_columns: Collection[str] = (), source_info: dict[str, SourceInfoValue] | None = None, 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. Args: - table: The rows: tag, data, system-tag and source-info columns. + table: The rows: tag, data and source-info columns. tag_columns: The user tag columns. - system_tag_columns: Columns to rename into system tags. source_info: Source-info tokens to add, by column. producer: The pod that produced the stream, if any. upstreams: The streams the producer read. 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: @@ -101,11 +92,41 @@ 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. + Also if a column name is reserved for system tags. """ + schema_utils.require_names_not_system_tags(table.column_names) super().__init__(**kwargs) + self._initialize( + table, tag_columns, source_info, producer, upstreams, data_tags + ) + @classmethod + def _from_derived_table( + cls, + table: pa.Table, + *, + tag_columns: Collection[str] = (), + data_tags: Collection[str] = (), + producer: PodProtocol | None = None, + upstreams: tuple[StreamProtocol, ...] = (), + data_context: str | contexts.DataContext | None = None, + label: str | None = None, + ) -> Self: + """Wrap a table whose system tags were built by Orcapod.""" + stream = cls.__new__(cls) + super(ArrowTableStream, stream).__init__(data_context=data_context, label=label) + stream._initialize(table, tag_columns, None, producer, upstreams, data_tags) + return stream + + def _initialize( + self, + table: pa.Table, + tag_columns: Collection[str], + source_info: dict[str, SourceInfoValue] | None, + producer: PodProtocol | None, + upstreams: tuple[StreamProtocol, ...], + data_tags: Collection[str], + ) -> None: self._producer = producer self._upstreams = upstreams if upstreams: @@ -115,25 +136,17 @@ def __init__( # ITL-1277): every source and operator result becomes a stream here, so this # refuses them all, tags and data alike. if found := schema_utils.dictionary_columns(table.schema): - raise schema_utils.dictionary_columns_error( - found, tag_columns, data_tags, system_tag_columns - ) + raise schema_utils.dictionary_columns_error(found, tag_columns, data_tags) # Nor are columns of a type the schema hash rejects (a union, a list view, a # run-end-encoded type; developer, November 21, 2026, ITL-640): a stream's # identity is its Arrow schema hash, which cannot hold them. if found := schema_utils.schema_hash_rejected_columns(table.schema): raise schema_utils.schema_hash_rejected_columns_error( - found, tag_columns, data_tags, system_tag_columns + found, tag_columns, data_tags ) - 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 - ) + # Check before normalization so an invalid value is reported with its column. + self._require_valid_system_tags(table) # Every table Orcapod presents is in its large variants (ITL-1122). table = arrow_utils.normalize_table_to_large_types(table, keep_null=True) @@ -169,15 +182,6 @@ def __init__( self._system_tag_columns = tuple( c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) ) - if system_tag_renames: - table = table.rename_columns( - [system_tag_renames.get(c, c) for c in table.column_names] - ) - - self._system_tag_columns += tuple( - f"{constants.SYSTEM_TAG_PREFIX}{c}" for c in system_tag_columns - ) - self._all_tag_columns = self._tag_columns + self._system_tag_columns if delta := set(tag_columns) - set(self._tag_columns): raise ValueError( @@ -233,8 +237,6 @@ def __init__( # nullable=True → T | None, nullable=False → T. # The tag schema lists the tags in tag order, as ``keys()`` does and as the # data schema follows ``_data_columns``; never in table layout (ITL-1365). - # A declared name the table does not hold (renamed into a system tag, or a - # system tag that is not there) is left out, as before. names = set(self._table.column_names) tag_schema = pa.schema( self._table.schema.field(name) @@ -260,39 +262,12 @@ def __init__( 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) + def _require_valid_system_tags(table: pa.Table) -> None: + """Require non-null string values in every system-tag column.""" + for index, field in enumerate(table.schema): + name = field.name + if not name.startswith(constants.SYSTEM_TAG_PREFIX): + continue if not ( pa.types.is_string(field.type) or pa.types.is_large_string(field.type) @@ -306,21 +281,6 @@ def _require_valid_system_tags( 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.""" @@ -658,32 +618,3 @@ 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 916afcf81..b3c6ffe51 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1825,12 +1825,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 stream_from_derived_table + from orcapod.core.streams.arrow_table_stream import ArrowTableStream typed = typed_zero_row_table(self) if typed is None: return None - return stream_from_derived_table( + return ArrowTableStream._from_derived_table( typed, tag_columns=self.keys()[0], data_tags=stream_data_tags(self), diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 67466d532..a4992e6de 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -806,6 +806,19 @@ def require_names_not_meta(names: Collection[str]) -> None: ) +def require_names_not_system_tags(names: Collection[str]) -> None: + """Refuse public input fields in Orcapod's system-tag namespace.""" + from orcapod.system_constants import constants + + prefixes = (constants.SYSTEM_TAG_PREFIX, "_tag::") + for name in sorted(names): + if name.startswith(prefixes): + raise InputValidationError( + f"column name {name!r} is reserved for Orcapod system tags; " + "give the column another name." + ) + + DICTIONARY_COLUMNS_NOT_SUPPORTED = ( "dictionary-encoded columns are not currently supported in Orcapod" ) @@ -1023,7 +1036,6 @@ def dictionary_columns_error( found: "Sequence[tuple[str, pa.DataType, pa.DataType]]", tag_columns: Collection[str], data_tags: Collection[str], - system_tag_columns: Collection[str] = (), ) -> InputValidationError: """Return the error refusing the dictionary-encoded columns ``found``. @@ -1036,8 +1048,6 @@ def dictionary_columns_error( found: The columns, as ``dictionary_columns`` returns them. tag_columns: The stream's tag columns, in tag order. data_tags: The tags that are data-tags. - system_tag_columns: Names the stream will read as system tags beside those with - the system-tag prefix. Returns: An ``InputValidationError`` naming each column (tags first, in tag order, then @@ -1050,7 +1060,7 @@ def dictionary_columns_error( key=lambda item: (0, tags.index(item[0])) if item[0] in tags else (1, 0), ) lines = [ - f" - {_column_role(name, tag_columns, data_tags, system_tag_columns)} column " + f" - {_column_role(name, tag_columns, data_tags)} column " f"{name!r} has type {arrow_type} (decoded: {decoded})" for name, arrow_type, decoded in ordered ] @@ -1075,7 +1085,6 @@ def _column_role( name: str, tag_columns: Collection[str], data_tags: Collection[str], - system_tag_columns: Collection[str], ) -> str: """The role a stream gives the column ``name``, for an error that names it.""" from orcapod.system_constants import constants @@ -1084,7 +1093,7 @@ def _column_role( return "data-tag" if name in tag_columns: return "tag" - if name in system_tag_columns or name.startswith(constants.SYSTEM_TAG_PREFIX): + if name.startswith(constants.SYSTEM_TAG_PREFIX): return "system-tag" if name.startswith(constants.INPUT_SOURCE_PREFIX): return "input source-info" @@ -1185,7 +1194,6 @@ def schema_hash_rejected_columns_error( found: "Sequence[tuple[str, pa.DataType]]", tag_columns: Collection[str], data_tags: Collection[str], - system_tag_columns: Collection[str] = (), ) -> InputValidationError: """Return the error refusing the columns ``found`` whose types the schema hash rejects. @@ -1195,8 +1203,6 @@ def schema_hash_rejected_columns_error( found: The columns, as ``schema_hash_rejected_columns`` returns them. tag_columns: The stream's tag columns, in tag order. data_tags: The tags that are data-tags. - system_tag_columns: Names the stream will read as system tags beside those with - the system-tag prefix. Returns: An ``InputValidationError`` naming each column (tags first, in tag order, then @@ -1208,7 +1214,7 @@ def schema_hash_rejected_columns_error( key=lambda item: (0, tags.index(item[0])) if item[0] in tags else (1, 0), ) lines = [ - f" - {_column_role(name, tag_columns, data_tags, system_tag_columns)} column " + f" - {_column_role(name, tag_columns, data_tags)} column " f"{name!r} has type {arrow_type}" for name, arrow_type in ordered ] @@ -1245,6 +1251,7 @@ def require_names_not_system(names: Collection[str]) -> None: reserved_prefixes = { constants.SYSTEM_TAG_PREFIX: "system tags", + "_tag::": "system tags", constants.SOURCE_PREFIX: "source info", constants.INPUT_SOURCE_PREFIX: "input source info", } diff --git a/test-specification/unit/test_stream.py b/test-specification/unit/test_stream.py index 407062888..d6f48e2e1 100644 --- a/test-specification/unit/test_stream.py +++ b/test-specification/unit/test_stream.py @@ -76,17 +76,13 @@ def test_basic_construction(self): stream = _make_stream() assert stream is not None - def test_construction_with_system_tag_columns(self): - """Stream accepts system_tag_columns parameter.""" - table = pa.table( - { - "id": pa.array([1, 2], type=pa.int64()), - "value": pa.array(["a", "b"], type=pa.large_string()), - "sys": pa.array(["s1", "s2"], type=pa.large_string()), - } - ) - stream = ArrowTableStream(table, tag_columns=["id"], system_tag_columns=["sys"]) - assert stream is not None + def test_system_tag_namespace_is_reserved(self): + """Public Arrow streams refuse reserved system-tag columns.""" + from orcapod.errors import InputValidationError + + table = _simple_table().append_column("_tag_sys", pa.array(["s"] * 3)) + with pytest.raises(InputValidationError, match="'_tag_sys'.*reserved"): + ArrowTableStream(table, tag_columns=["id"]) def test_construction_with_source_info(self): """Stream accepts source_info dict parameter.""" @@ -173,12 +169,10 @@ def test_keys_with_column_config_system_tags(self): { "id": pa.array([1], type=pa.int64()), "value": pa.array(["a"], type=pa.large_string()), - "sys_col": pa.array(["s"], type=pa.large_string()), + "_tag_sys_col": pa.array(["s"], type=pa.large_string()), } ) - stream = ArrowTableStream( - table, tag_columns=["id"], system_tag_columns=["sys_col"] - ) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) tag_keys_default, _ = stream.keys() tag_keys_all, _ = stream.keys(columns=ColumnConfig(system_tags=True)) # Default: system tags excluded from keys @@ -190,12 +184,10 @@ def test_keys_with_all_info(self): { "id": pa.array([1], type=pa.int64()), "value": pa.array(["a"], type=pa.large_string()), - "sys_col": pa.array(["s"], type=pa.large_string()), + "_tag_sys_col": pa.array(["s"], type=pa.large_string()), } ) - stream = ArrowTableStream( - table, tag_columns=["id"], system_tag_columns=["sys_col"] - ) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) tag_keys_all, _ = stream.keys(all_info=True) assert len(tag_keys_all) > 1 # id + system tag(s) @@ -272,10 +264,10 @@ def test_schema_with_system_tags_config(self): { "id": pa.array([1], type=pa.int64()), "value": pa.array(["a"], type=pa.large_string()), - "sys": pa.array(["s"], type=pa.large_string()), + "_tag_sys": pa.array(["s"], type=pa.large_string()), } ) - stream = ArrowTableStream(table, tag_columns=["id"], system_tag_columns=["sys"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) tag_schema_default, _ = stream.output_schema() tag_schema_with_sys, _ = stream.output_schema( columns=ColumnConfig(system_tags=True) @@ -385,12 +377,10 @@ def test_default_excludes_system_tags(self): { "id": pa.array([1], type=pa.int64()), "val": pa.array(["x"], type=pa.large_string()), - "stag": pa.array(["t"], type=pa.large_string()), + "_tag_stag": pa.array(["t"], type=pa.large_string()), } ) - stream = ArrowTableStream( - table, tag_columns=["id"], system_tag_columns=["stag"] - ) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) tag_keys, _ = stream.keys() # System tag columns are prefixed with _tag_ internally assert all(not k.startswith("_tag_") for k in tag_keys) @@ -422,12 +412,10 @@ def test_system_tags_in_as_table(self): { "id": pa.array([1], type=pa.int64()), "val": pa.array(["x"], type=pa.large_string()), - "stag": pa.array(["t"], type=pa.large_string()), + "_tag_stag": pa.array(["t"], type=pa.large_string()), } ) - stream = ArrowTableStream( - table, tag_columns=["id"], system_tag_columns=["stag"] - ) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) table_default = stream.as_table() table_with_sys = stream.as_table(columns=ColumnConfig(system_tags=True)) assert table_with_sys.num_columns > table_default.num_columns diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 2be341b87..8715910a0 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -102,7 +102,9 @@ def test_raw_system_tag_fields_survive_a_record_batch_channel() -> None: ], schema=schema, ) - stream = ArrowTableStream(table, tag_columns=("subject", "trial")) + stream = ArrowTableStream._from_derived_table( + table, tag_columns=("subject", "trial") + ) async def forward() -> StreamProtocol: output = OutputChannel(stream) @@ -169,7 +171,7 @@ def shaped_source(kind: pa.DataType, n: int = 2) -> ArrowTableStream: [nested_value("seed", kind)] * n, kind, ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=["subject", "trial"], data_tags=["trial"] ) @@ -1168,7 +1170,7 @@ def test_the_first_batch_fixes_the_column_order(retain: bool, declared: bool) -> stream = ( source() if declared - else _UntypedStream( + else _UntypedStream._from_derived_table( table, tag_columns=["subject", "trial"], data_tags=["trial"] ) ) @@ -1224,7 +1226,7 @@ def test_a_reordered_batch_must_still_have_the_streams_columns(declared: bool) - stream = ( source() if declared - else _UntypedStream( + else _UntypedStream._from_derived_table( table, tag_columns=["subject", "trial"], data_tags=["trial"] ) ) @@ -1637,7 +1639,7 @@ def test_without_arrow_types_the_names_are_still_the_streams() -> None: """A stream with no typed zero-row table: the first record batch gives the Arrow types, but a batch whose columns contradict the stream's keys is refused.""" table = source().as_table(columns=ALL) - stream = _UntypedStream( + stream = _UntypedStream._from_derived_table( table, tag_columns=["subject", "trial"], data_tags=["trial"] ) assert not stream.arrow_types_declared # no Arrow types without rows @@ -1660,7 +1662,7 @@ async def write() -> int: def test_a_refused_first_batch_sets_no_schema() -> None: """Without Arrow types in the description, a refused first batch sets nothing: a correct batch sent next is taken.""" - stream = _UntypedStream( + stream = _UntypedStream._from_derived_table( source().as_table(columns=ALL), tag_columns=["subject", "trial"], data_tags=["trial"], @@ -2152,7 +2154,7 @@ def test_a_batch_with_a_duplicate_column_is_refused() -> None: """Without Arrow types the names are compared as a multiset: a duplicate is refused (Codex on PR #485, round 5).""" table = source().as_table(columns=ALL) - stream = _UntypedStream( + stream = _UntypedStream._from_derived_table( table, tag_columns=["subject", "trial"], data_tags=["trial"] ) (batch,) = batches_of(stream) @@ -2276,7 +2278,7 @@ def test_batches_send_accepts_are_assembled(case: str) -> None: parts, declared, tokens = ONE_TYPE_CASES[case] stream = shaped_source(declared) if case == "zero_rows_first": - stream = _UntypedStream( + stream = _UntypedStream._from_derived_table( stream.as_table(columns=ALL), tag_columns=["subject", "trial"], data_tags=["trial"], @@ -2323,7 +2325,7 @@ def test_a_batch_that_declares_another_token_type_is_refused_at_send( if order == "as_listed" else list(reversed(TWO_TYPE_CASES[case])) ) - stream = _UntypedStream( + stream = _UntypedStream._from_derived_table( shaped_source(first).as_table(columns=ALL), tag_columns=["subject", "trial"], data_tags=["trial"], @@ -2405,8 +2407,10 @@ def test_channel_keeps_first_system_tag_declaration_and_entry_id() -> None: [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"]) - first, second = batches_of(ArrowTableStream(table, tag_columns=["k"]), rows=1) + stream = _UntypedStream._from_derived_table(table, tag_columns=["k"]) + first, second = batches_of( + ArrowTableStream._from_derived_table(table, tag_columns=["k"]), rows=1 + ) async def read(pieces: Sequence[pa.RecordBatch]): channel = OutputChannel(stream) diff --git a/tests/test_channels/test_record_batch_review_findings.py b/tests/test_channels/test_record_batch_review_findings.py index ba224bce7..e92211eda 100644 --- a/tests/test_channels/test_record_batch_review_findings.py +++ b/tests/test_channels/test_record_batch_review_findings.py @@ -550,7 +550,7 @@ def test_a_batch_with_a_column_twice_is_refused(declared: bool, kind: str) -> No stream = ( source() if declared - else _UntypedStream( + else _UntypedStream._from_derived_table( table, tag_columns=["subject", "trial"], data_tags=["trial"] ) ) 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 65f3f073c..f45da98a7 100644 --- a/tests/test_core/data_tags/test_operator_node_storage.py +++ b/tests/test_core/data_tags/test_operator_node_storage.py @@ -564,7 +564,7 @@ def test_merge_join_cache_keeps_declared_system_tag_fields( from orcapod.operators import MergeJoin from orcapod.streams import ArrowTableStream - left = ArrowTableStream( + left = ArrowTableStream._from_derived_table( pa.table({"k": [1, 2], "x": [3, 4], "_tag_custom": ["one", "two"]}), tag_columns=["k"], ) diff --git a/tests/test_core/datagrams/test_rows_of_table.py b/tests/test_core/datagrams/test_rows_of_table.py index 354c1d2e9..68d39bd24 100644 --- a/tests/test_core/datagrams/test_rows_of_table.py +++ b/tests/test_core/datagrams/test_rows_of_table.py @@ -577,7 +577,7 @@ def test_rows_of_a_table_built_from_rows_are_the_constructors() -> None: ] ) assert table.column("x").num_chunks == table.num_rows > 1 - rebuilt: Any = ArrowTableStream(table, tag_columns=["k", "g"]) + rebuilt: Any = ArrowTableStream._from_derived_table(table, tag_columns=["k", "g"]) rows = list(rebuilt.iter_data()) diff --git a/tests/test_core/function_pod/test_function_pod_decorator.py b/tests/test_core/function_pod/test_function_pod_decorator.py index 3f6e3f662..076b9b282 100644 --- a/tests/test_core/function_pod/test_function_pod_decorator.py +++ b/tests/test_core/function_pod/test_function_pod_decorator.py @@ -14,7 +14,14 @@ import pyarrow as pa import pytest -from orcapod.core.function_pod import FunctionPodStream, FunctionPod, function_pod +from orcapod.core.data_function import PythonDataFunction +from orcapod.core.function_pod import ( + FunctionPod, + FunctionPodStream, + function_pod, + side_effect_function_pod, +) +from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import FunctionPodProtocol, StreamProtocol from ..conftest import make_int_stream @@ -219,3 +226,41 @@ def test_wraps_preserves_annotations(self): def test_wraps_preserves_docstring(self): assert documented.__doc__ == "Multiply x by two." assert documented.__doc__ == documented.__wrapped__.__doc__ + + +@pytest.mark.parametrize( + "name", + [ + "_tag_forged", + "_tag::forged", + "_tag_source_id::extra", + "_tag_record_id::extra", + "_source_forged", + "_input_source_forged", + "__forged", + "__delta_rs_source", + "_context_key", + ], +) +@pytest.mark.parametrize( + "route", ["decorator", "from_fn", "side_effect", "constructor"] +) +def test_function_pods_refuse_reserved_output_keys(name: str, route: str) -> None: + def forged(x: int) -> tuple[int, str | None]: + return x + 1, "forged" + + keys = ["y", name] + with pytest.raises(InputValidationError, match=rf"{name!r}.*reserved"): + if route == "decorator": + _ = function_pod( + output_keys=keys, output_schema={"y": int, name: str | None} + )(forged) + elif route == "from_fn": + _ = FunctionPod.from_fn(forged, output_keys=keys) + elif route == "side_effect": + _ = side_effect_function_pod(forged, output_keys=keys, ctx_arg_name="x") + else: + data_function = PythonDataFunction(forged, output_keys=keys) + _ = FunctionPod( + data_function, # pyright: ignore[reportArgumentType] # PythonDataFunction's protocol typing is incomplete. + ) diff --git a/tests/test_core/function_pod/test_function_pod_node.py b/tests/test_core/function_pod/test_function_pod_node.py index ad09f0248..6510db8f3 100644 --- a/tests/test_core/function_pod/test_function_pod_node.py +++ b/tests/test_core/function_pod/test_function_pod_node.py @@ -60,19 +60,19 @@ def _make_node_with_system_tags( schema = pa.schema( [ pa.field("id", pa.int64(), nullable=False), - pa.field("run", pa.large_string(), nullable=False), + pa.field("_tag_run", pa.large_string(), nullable=False), pa.field("x", pa.int64(), nullable=False), ] ) table = pa.table( { "id": list(range(n)), - "run": [f"r{i}" for i in range(n)], + "_tag_run": [f"r{i}" for i in range(n)], "x": list(range(n)), }, schema=schema, ) - stream = ArrowTableStream(table, tag_columns=["id"], system_tag_columns=["run"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) return FunctionJobNode( function_pod=FunctionPod(data_function=pf), input_stream=stream, diff --git a/tests/test_core/operators/test_aggregated_list_types.py b/tests/test_core/operators/test_aggregated_list_types.py index 22add24f1..e7634e66f 100644 --- a/tests/test_core/operators/test_aggregated_list_types.py +++ b/tests/test_core/operators/test_aggregated_list_types.py @@ -196,7 +196,9 @@ def _in_list_layout(stream: StreamProtocol) -> ArrowTableStream: The stream presents ``large_list`` again (ITL-1122). """ tag_columns, _ = stream.keys() - return ArrowTableStream(_list_layout_table(stream), tag_columns=tag_columns) + return ArrowTableStream._from_derived_table( + _list_layout_table(stream), tag_columns=tag_columns + ) class TestAggregatedContentHashes: @@ -228,7 +230,7 @@ def test_stream_content_hash_matches_the_list_layout( """The whole output stream's content hash is layout-independent too.""" _, _, result = aggregated assert ( - ArrowTableStream( + ArrowTableStream._from_derived_table( result.as_table(columns={"source": True, "system_tags": True}), tag_columns=result.keys()[0], ).content_hash() diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 7efa528e9..1ae19b56b 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -491,7 +491,7 @@ def _changed_branches( index = table.column_names.index(name) table = table.set_column(index, table.schema.field(index), values) streams.append( - ArrowTableStream( + ArrowTableStream._from_derived_table( table.select(["k", "ta", *data, *system_tags]), tag_columns=["k", "ta"] ) ) @@ -509,7 +509,7 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: "_tag_record_id::x": pa.array(["r1", "r2", "r3"], pa.large_string()), } ) - return ArrowTableStream(table, tag_columns=["k", "f"]) + return ArrowTableStream._from_derived_table(table, tag_columns=["k", "f"]) CASES = [ @@ -1121,10 +1121,12 @@ def test_tied_join_table_keeps_declared_identifier_fields( if reverse_columns: table = table.select(list(reversed(schema.names))) inputs.append( - ArrowTableStream(table, tag_columns=("k", "g"), data_tags=("k", "g")) + ArrowTableStream._from_derived_table( + table, tag_columns=("k", "g"), data_tags=("k", "g") + ) ) empty_inputs.append( - ArrowTableStream( + ArrowTableStream._from_derived_table( table.slice(0, 0), tag_columns=("k", "g"), data_tags=("k", "g") ) ) @@ -1190,7 +1192,11 @@ def _tied_join_inputs( [dict(zip(names, (key, source_id, record_id, revision), strict=True))], schema=schema, ) - inputs.append(ArrowTableStream(table, tag_columns=["k"], data_tags=["k"])) + inputs.append( + ArrowTableStream._from_derived_table( + table, tag_columns=["k"], data_tags=["k"] + ) + ) assert len({stream.pipeline_hash() for stream in inputs}) == 1 return inputs @@ -1328,12 +1334,14 @@ def test_standalone_tied_join_keeps_custom_tags_with_ids(arity: int) -> None: assert tag.system_tags() == expected -def _tied_declaration_inputs(arity: int, variant: str) -> list[StreamProtocol]: +def _tied_declaration_inputs( + arity: int, variant: str, *, revision_first: bool = False +) -> list[StreamProtocol]: """Vary the declaration or values of the tied Join's custom revision tag. Nullable changes the first field's nullability, owner and extension add their respective metadata keys, and distinct varies the values. Source - uses a nominated ArrowTableSource tag with a required string field and data-tag k. + uses the library provenance pair with a required revision field and data-tag k. """ if variant == "source": ids = ("az", "z", "zz", "zzz")[:arity] @@ -1343,18 +1351,29 @@ def _tied_declaration_inputs(arity: int, variant: str) -> list[StreamProtocol]: pa.field("rev", pa.large_string(), False), ] ) - sources: list[StreamProtocol] = [ + sources = [ ArrowTableSource( pa.Table.from_pylist([{"k": 1, "rev": f"rev-{source_id}"}], schema), tag_columns=["k"], - system_tag_columns=["rev"], source_id=source_id, ) for source_id in ids ] for source in sources: + table = source.as_table(columns={"system_tags": True, "source": True}) + revision = table["rev"] + table = table.drop_columns(["rev", "_source_rev"]) + # The historical table put the revision before the provenance pair. + # Its row schema put the pair first. Supply each mode its original order. + position = 1 if revision_first else table.num_columns + table = table.add_column( + position, pa.field("_tag_rev", pa.large_string(), False), revision + ) + source._stream = ArrowTableStream._from_derived_table( + table, tag_columns=["k"], data_tags=["k"] + ) assert source.keys() == (("k",), ("k",)) - return sources + return list(sources) inputs: list[StreamProtocol] = [] for position in range(arity): metadata_key = { @@ -1389,7 +1408,11 @@ def _tied_declaration_inputs(arity: int, variant: str) -> list[StreamProtocol]: }, schema=schema, ) - inputs.append(ArrowTableStream(table, tag_columns=["k"], data_tags=["k"])) + inputs.append( + ArrowTableStream._from_derived_table( + table, tag_columns=["k"], data_tags=["k"] + ) + ) assert len({stream.pipeline_hash() for stream in inputs}) == 1 return inputs @@ -1431,7 +1454,8 @@ def _tied_declaration_snapshot(arity: int, variant: str, mode: str) -> str: hasher = get_default_arrow_hasher() snapshot = sha256() columns = {"system_tags": True} - for order in itertools.permutations(_tied_declaration_inputs(arity, variant)): + inputs = _tied_declaration_inputs(arity, variant, revision_first=mode != "rows") + for order in itertools.permutations(inputs): table, rows = _tied_join_outputs(mode, Join(), order) snapshot.update(_ipc_bytes(table.sort_by("k"))) for tag, data in sorted(rows, key=lambda row: cast(int, row[0].as_dict()["k"])): @@ -1545,7 +1569,9 @@ def test_tied_join_with_asymmetric_empty_input_matches_main( .drop(["_tag_source_id", "_tag_record_id"]) .slice(0, 0) ) - inputs[-1] = ArrowTableStream(empty_table, tag_columns=["k"], data_tags=["k"]) + inputs[-1] = ArrowTableStream._from_derived_table( + empty_table, tag_columns=["k"], data_tags=["k"] + ) for order in itertools.permutations(inputs): join = Join() tags, _ = join.output_schema(*order, columns=columns) @@ -1562,7 +1588,7 @@ def test_join_suffixes_distinguish_hashes_with_the_same_prefix(reverse: bool) -> """Disambiguate inputs by full pipeline hash in every Join mode.""" source_id, record_id, custom = "_tag_source_id", "_tag_record_id", "_tag_rev" left, right = [ - ArrowTableStream( + ArrowTableStream._from_derived_table( pa.table( { "k": [1], @@ -1638,7 +1664,7 @@ def test_raw_stream_rows_keep_system_tag_flags_and_metadata( ) if reverse_columns: table = table.select(list(reversed(schema.names))) - stream = ArrowTableStream(table, tag_columns=("k", "g")) + stream = ArrowTableStream._from_derived_table(table, tag_columns=("k", "g")) columns = {"system_tags": True} for tag, data in stream.iter_data(): assert isinstance(tag, Tag) @@ -2093,7 +2119,9 @@ def _with_meta(source: StreamProtocol, meta: dict[str, Column]) -> ArrowTableStr table = table.append_column(name, column) tags, data = source.keys() data_tags = [name for name in tags if name in data] - return ArrowTableStream(table, tag_columns=tags, data_tags=data_tags) + return ArrowTableStream._from_derived_table( + table, tag_columns=tags, data_tags=data_tags + ) def _meta_columns(prefix: str, n_rows: int) -> dict[str, Column]: @@ -3120,7 +3148,7 @@ def _token_stream( if name == first and first_token is not None: values = [first_token, *values[1:]] table = with_token_column(table, name, values, kind) - return ArrowTableStream(table, tag_columns=list(tags)) + return ArrowTableStream._from_derived_table(table, tag_columns=list(tags)) def _listed(kind: pa.DataType, levels: int) -> pa.DataType: diff --git a/tests/test_core/operators/test_barrier_keeps_data_context.py b/tests/test_core/operators/test_barrier_keeps_data_context.py index 2c644867c..529894166 100644 --- a/tests/test_core/operators/test_barrier_keeps_data_context.py +++ b/tests/test_core/operators/test_barrier_keeps_data_context.py @@ -50,17 +50,14 @@ def _stream(context: contexts.DataContext, data: tuple[str, str]) -> ArrowTableS "g": pa.array([3, 1, 2], pa.int64()), data[0]: pa.array([0.5, 0.25, 0.125], pa.float64()), data[1]: pa.array([1, 2, 3], pa.int64()), - "origin": pa.array(["r1", "r2", "r3"], pa.large_string()), + "_tag_origin": pa.array(["r1", "r2", "r3"], pa.large_string()), constants.CONTEXT_KEY: pa.array( [context.context_key] * 3, pa.large_string() ), } ) - return ArrowTableStream( - table, - tag_columns=["h", "g"], - system_tag_columns=["origin"], - data_context=context, + return ArrowTableStream._from_derived_table( + table, tag_columns=["h", "g"], data_context=context ) diff --git a/tests/test_core/operators/test_description_system_tags.py b/tests/test_core/operators/test_description_system_tags.py index 57350544c..b228b3703 100644 --- a/tests/test_core/operators/test_description_system_tags.py +++ b/tests/test_core/operators/test_description_system_tags.py @@ -57,7 +57,7 @@ def _raw(spec: Spec, arrangement: Arrangement, *, meta: bool) -> ArrowTableStrea "__note", pa.array([f"n{i}" for i in range(table.num_rows)], pa.large_string()), ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=list(arrangement.tag_order), data_tags=stream_data_tags(source), diff --git a/tests/test_core/operators/test_drop_nulls.py b/tests/test_core/operators/test_drop_nulls.py index 72fe31e41..ebe73129c 100644 --- a/tests/test_core/operators/test_drop_nulls.py +++ b/tests/test_core/operators/test_drop_nulls.py @@ -679,7 +679,7 @@ def test_no_argument_leaves_system_and_source_columns_alone() -> None: source_x = f"{constants.SOURCE_PREFIX}x" position = before.schema.get_field_index(source_x) nullable_token = before.schema.field(position).with_nullable(True) - stream = ArrowTableStream( + stream = ArrowTableStream._from_derived_table( before.set_column( position, nullable_token, @@ -820,7 +820,7 @@ def test_no_argument_leaves_meta_columns_alone() -> None: pa.field(meta, pa.large_string(), nullable=True), pa.array([None, "m2", "m3", "m4"], pa.large_string()), ) - stream = ArrowTableStream(table, tag_columns=["id"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["id"]) result = DropNulls()(stream) rows = list(result.iter_data()) assert [tag["id"] for tag, _ in rows] == [1] diff --git a/tests/test_core/operators/test_group_by.py b/tests/test_core/operators/test_group_by.py index 72aeb9d1a..332fa94c2 100644 --- a/tests/test_core/operators/test_group_by.py +++ b/tests/test_core/operators/test_group_by.py @@ -316,7 +316,7 @@ def grouped(order: list[int]) -> list[Any]: "v": [2, 1], } table = pa.table({k: [v[i] for i in order] for k, v in rows.items()}) - stream = ArrowTableStream(table, tag_columns=["g"]) + stream = ArrowTableStream._from_derived_table(table, tag_columns=["g"]) return GroupBy(by=["g"]).process(stream).as_table().column("v").to_pylist() assert grouped([0, 1]) == grouped([1, 0]) == [[1, 2]] diff --git a/tests/test_core/operators/test_held_context_keys.py b/tests/test_core/operators/test_held_context_keys.py index 8c86eb185..4264fb740 100644 --- a/tests/test_core/operators/test_held_context_keys.py +++ b/tests/test_core/operators/test_held_context_keys.py @@ -115,7 +115,7 @@ def _stream(arrangement: Arrangement) -> ArrowTableStream: ), ) tag_columns, data_columns = source.keys() - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=tag_columns, data_tags=[name for name in tag_columns if name in data_columns], @@ -134,7 +134,7 @@ def _right(stream: ArrowTableStream, ids: tuple[int, ...]) -> ArrowTableStream: for name in data_columns }, } - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table.take(positions).rename_columns( [renames.get(name, name) for name in table.column_names] ), @@ -303,7 +303,7 @@ async def execute() -> list[Row]: outgoing: Channel[Row] = Channel() for index, key in enumerate(HELD_KEYS): # Form each channel row in its own registered stream context. - singleton = ArrowTableStream( + singleton = ArrowTableStream._from_derived_table( table.slice(index, 1), tag_columns=stream.keys()[0], data_tags=[ diff --git a/tests/test_core/operators/test_index_pick_arrow_types.py b/tests/test_core/operators/test_index_pick_arrow_types.py index c56173153..be7690233 100644 --- a/tests/test_core/operators/test_index_pick_arrow_types.py +++ b/tests/test_core/operators/test_index_pick_arrow_types.py @@ -1045,3 +1045,23 @@ async def test_unmappable_pick_fallback_raises_where_needed( monkeypatch.undo() with pytest.raises(ValueError, match=r"Pick: .*'c'.*int"): _ = await _execute_rows(op, source) + + +@pytest.mark.parametrize( + "name", + [ + "_tag_forged", + "_tag::forged", + "_source_forged", + "_input_source_forged", + "__forged", + "_context_key", + ], +) +@pytest.mark.parametrize("operator", ["index", "pick"]) +def test_index_and_pick_refuse_reserved_output_names(name: str, operator: str) -> None: + with pytest.raises(InputValidationError, match=rf"{name!r}.*reserved"): + if operator == "index": + Index("values", 0, out=name) + else: + Pick("values", "x", out=name) diff --git a/tests/test_core/operators/test_merge_join_arrow_types.py b/tests/test_core/operators/test_merge_join_arrow_types.py index 7c2cbe7f8..998378194 100644 --- a/tests/test_core/operators/test_merge_join_arrow_types.py +++ b/tests/test_core/operators/test_merge_join_arrow_types.py @@ -819,13 +819,19 @@ def _relayout( an override changes. """ tag_columns, _ = stream.keys() - return ArrowTableStream(_relayout_table(stream, overrides), tag_columns=tag_columns) + return ArrowTableStream._from_derived_table( + _relayout_table(stream, overrides), tag_columns=tag_columns + ) def _stream_hash(stream: StreamProtocol) -> str: """Return the content hash of ``stream``'s full table.""" table = stream.as_table(columns={"source": True, "system_tags": True}) - return ArrowTableStream(table, tag_columns=stream.keys()[0]).content_hash().to_hex() + return ( + ArrowTableStream._from_derived_table(table, tag_columns=stream.keys()[0]) + .content_hash() + .to_hex() + ) class TestContentHashes: diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 12d67d9e9..f27924dd1 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -530,7 +530,7 @@ def test_the_provenance_columns_have_the_row_built_schema() -> None: ), ] ) - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( pa.table( [ pa.array([1, 2], pa.int64()), @@ -676,7 +676,7 @@ 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 keeps its nullable string field when both rows have a value.""" - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1, 2], pa.int64()), @@ -802,8 +802,8 @@ def test_rejoin_over_job_nodes_with_rows_of_two_data_contexts( "k": pa.array([1, 2], pa.int64()), "x": pa.array([1.0, 2.0], pa.float64()), "y": pa.array([3, 4], pa.int64()), - "source_id::a": pa.array(["s", "s"], pa.large_string()), - "record_id::a": pa.array(["r0", "r1"], pa.large_string()), + "_tag_source_id::a": pa.array(["s", "s"], pa.large_string()), + "_tag_record_id::a": pa.array(["r0", "r1"], pa.large_string()), constants.CONTEXT_KEY: pa.array( [contexts.get_default_context().context_key, other_context.context_key], pa.large_string(), @@ -818,9 +818,7 @@ def test_rejoin_over_job_nodes_with_rows_of_two_data_contexts( ] ) ) - raw = ArrowTableStream( - table, tag_columns=["k"], system_tag_columns=["source_id::a", "record_id::a"] - ) + raw = ArrowTableStream._from_derived_table(table, tag_columns=["k"]) job = PipelineJob(name="rejoin-contexts", database=InMemoryArrowDatabase()) with job: branch = operators.MapData({"x": "u", "y": "v"})(raw, label="branch") diff --git a/tests/test_core/operators/test_rejoin.py b/tests/test_core/operators/test_rejoin.py index 0a4200690..cdf285c53 100644 --- a/tests/test_core/operators/test_rejoin.py +++ b/tests/test_core/operators/test_rejoin.py @@ -421,7 +421,9 @@ def _tied(k: list[float]) -> ArrowTableStream: f"{constants.SYSTEM_TAG_PREFIX}record_id::x": ["r1", "r2"], } ) - return ArrowTableStream(table, tag_columns=["k", "g"], data_tags=["k", "g"]) + return ArrowTableStream._from_derived_table( + table, tag_columns=["k", "g"], data_tags=["k", "g"] + ) def test_stated_system_tags_are_compared_even_beside_an_input_that_states_none() -> ( @@ -448,7 +450,7 @@ def _float_tag_branch(level: list[float], data: str) -> ArrowTableStream: data: pa.array([0.5, 0.25], pa.float64()), } ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( arrow_utils.add_system_tag_columns(table, "origin", "source", ["r1", "r2"]), tag_columns=["g", "level"], ) @@ -482,17 +484,14 @@ def _in_context(context: contexts.DataContext, data: str) -> ArrowTableStream: "g": pa.array([1, 2, 3], pa.int64()), "h": pa.array(["a", "b", "c"], pa.large_string()), data: pa.array([0.5, 0.25, 0.125], pa.float64()), - "origin": pa.array(["r1", "r2", "r3"], pa.large_string()), + "_tag_origin": pa.array(["r1", "r2", "r3"], pa.large_string()), constants.CONTEXT_KEY: pa.array( [context.context_key] * 3, pa.large_string() ), } ) - return ArrowTableStream( - table, - tag_columns=["g", "h"], - system_tag_columns=["origin"], - data_context=context, + return ArrowTableStream._from_derived_table( + table, tag_columns=["g", "h"], data_context=context ) @@ -547,17 +546,14 @@ def _wide_in_context(context: contexts.DataContext) -> ArrowTableStream: "x": pa.array([0.5, 0.25, 0.125], pa.float64()), "y": pa.array(["p", "q", "r"], pa.large_string()), "z": pa.array([True, False, True], pa.bool_()), - "origin": pa.array(["r1", "r2", "r3"], pa.large_string()), + "_tag_origin": pa.array(["r1", "r2", "r3"], pa.large_string()), constants.CONTEXT_KEY: pa.array( [context.context_key] * 3, pa.large_string() ), } ) - return ArrowTableStream( - table, - tag_columns=["g", "h"], - system_tag_columns=["origin"], - data_context=context, + return ArrowTableStream._from_derived_table( + table, tag_columns=["g", "h"], data_context=context ) @@ -668,7 +664,7 @@ def _branch( for name in table.column_names if name.startswith(constants.SOURCE_PREFIX) or name == constants.CONTEXT_KEY ] - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table.select([*tags, *data, *system_tags, *hidden]), tag_columns=list(tags), data_tags=list(data_tags), @@ -863,10 +859,10 @@ def _repeated(n: int, data: str, k: list[int] | None = None) -> ArrowTableStream { "k": pa.array(k or [1] * n, pa.int64()), data: pa.array(range(n), pa.int64()), - "origin": pa.array(["x"] * n, pa.large_string()), + "_tag_origin": pa.array(["x"] * n, pa.large_string()), } ) - return ArrowTableStream(table, tag_columns=["k"], system_tag_columns=["origin"]) + return ArrowTableStream._from_derived_table(table, tag_columns=["k"]) def _join_sizes(compute: Any) -> tuple[Any, list[int]]: @@ -960,12 +956,11 @@ def branch(data: str, k: list[int] | None, n: int) -> ArrowTableStream: columns |= { "g": pa.array([7] * n, pa.int64()), data: pa.array(range(n), pa.int64()), - "origin": pa.array(["r"] * n, pa.large_string()), + "_tag_origin": pa.array(["r"] * n, pa.large_string()), } - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table(columns), tag_columns=[name for name in ("k", "g") if name in columns], - system_tag_columns=["origin"], ) inputs = { @@ -1139,12 +1134,10 @@ def _one_row(data: str, k: int, h: int, origin: str = "r") -> ArrowTableStream: "k": pa.array([k], pa.int64()), "h": pa.array([h], pa.int8()), data: pa.array([0.5], pa.float64()), - "origin": pa.array([origin], pa.large_string()), + "_tag_origin": pa.array([origin], pa.large_string()), } ) - return ArrowTableStream( - table, tag_columns=["k", "h"], system_tag_columns=["origin"] - ) + return ArrowTableStream._from_derived_table(table, tag_columns=["k", "h"]) def _in_canonical_order(*data: str) -> list[str]: @@ -1279,13 +1272,11 @@ def mixed(keys: list[str], data: str) -> ArrowTableStream: "g": pa.array([1, 2, 3], pa.int64()), "h": pa.array(["a", "b", "c"], pa.large_string()), data: pa.array([0.5, 0.25, 0.125], pa.float64()), - "origin": pa.array(["r1", "r2", "r3"], pa.large_string()), + "_tag_origin": pa.array(["r1", "r2", "r3"], pa.large_string()), constants.CONTEXT_KEY: pa.array(keys, pa.large_string()), } ) - return ArrowTableStream( - table, tag_columns=["g", "h"], system_tag_columns=["origin"] - ) + return ArrowTableStream._from_derived_table(table, tag_columns=["g", "h"]) a = mixed([OTHER_CONTEXT, default, OTHER_CONTEXT], "x") b = mixed([OTHER_CONTEXT, default, default], "y") diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 22566c853..2579c4732 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -170,7 +170,7 @@ def _raw_stream() -> ArrowTableStream: schema = table.schema.set( position, table.schema.field(position).with_metadata({b"m": b"v"}) ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.Table.from_arrays(table.columns, schema=schema), tag_columns=["k", "j"] ) @@ -246,7 +246,7 @@ def _with_source_x(values: list[Any], kind: pa.DataType) -> ArrowTableStream: (the token-shape rule, ITL-1491). The stream keeps the source's system-tag pair, so a job slot accepts it (Codex on PR #485). """ - return ArrowTableStream( + return ArrowTableStream._from_derived_table( with_token_column(_source_table(), "x", values, kind), tag_columns=["k"] ) @@ -497,4 +497,8 @@ def test_a_source_with_a_nullable_system_tag_is_not_bound() -> None: ) slot = next(label for label in job.nodes if label != "selected") with pytest.raises(SourceSpecMismatchError, match="record_id"): - job.bind(sources={slot: ArrowTableStream(with_null, tag_columns=["k"])}) + job.bind( + sources={ + slot: ArrowTableStream._from_derived_table(with_null, tag_columns=["k"]) + } + ) diff --git a/tests/test_core/operators/test_semijoin_nested.py b/tests/test_core/operators/test_semijoin_nested.py index ab9a2b06a..4afd34493 100644 --- a/tests/test_core/operators/test_semijoin_nested.py +++ b/tests/test_core/operators/test_semijoin_nested.py @@ -197,7 +197,9 @@ def async_semijoin_rows(left: StreamProtocol, right: StreamProtocol) -> list[Row def zero_rows(stream: StreamProtocol) -> ArrowTableStream: """``stream`` with no rows, keeping its schema, source info and system tags.""" table = stream.as_table(columns=ALL_COLUMNS) - return ArrowTableStream(table.slice(0, 0), tag_columns=stream.keys()[0]) + return ArrowTableStream._from_derived_table( + table.slice(0, 0), tag_columns=stream.keys()[0] + ) # ── nested and logical non-key columns ────────────────────────────────────── diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 55954dd55..b7307dc18 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -905,7 +905,7 @@ def test_join_keeps_nullable_tied_raw_system_tag_fields() -> None: ] ) inputs = tuple( - ArrowTableStream( + ArrowTableStream._from_derived_table( pa.Table.from_arrays( [ pa.array([1]), @@ -963,7 +963,7 @@ def _data_tag_stream(data: str, tokens: list[list[str]]) -> ArrowTableStream: """ token_list = pa.large_list(pa.large_string()) values = pa.large_list(pa.int64()) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([[1], [2]], values), @@ -1100,7 +1100,7 @@ def stream(data: str, tokens: list[list[str]]) -> ArrowTableStream: def _empty_data_tag_stream(data: str) -> ArrowTableStream: """``_data_tag_stream``'s columns, with no row.""" - return ArrowTableStream( + return ArrowTableStream._from_derived_table( _data_tag_stream(data, [["x"], ["y"]]) .as_table(columns=TRANSPORT_COLUMNS) .slice(0, 0), @@ -1300,7 +1300,7 @@ def _with_meta(spec: Spec, arrangement: Arrangement) -> ArrowTableStream: table = table.append_column( "__note", pa.array([f"n{i}" for i in range(table.num_rows)], pa.large_string()) ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=list(arrangement.tag_order), data_tags=stream_data_tags(source), @@ -1530,7 +1530,7 @@ def test_merge_join_preserves_system_tag_declarations(matched: list[int]) -> Non pa.field("_tag_nullable", pa.large_string(), metadata={b"owner": b"raw"}), pa.field("_tag_required", pa.large_string(), nullable=False), ] - left = ArrowTableStream( + left = ArrowTableStream._from_derived_table( pa.Table.from_arrays( [ pa.array([1, 2]), @@ -1620,7 +1620,7 @@ def test_filtering_join_kernels_preserve_system_tag_fields( name, pa.large_string(), nullable=nullable, metadata={b"owner": b"raw"} ) values = pa.array(["selected", "another"], field.type) - left = ArrowTableStream( + left = ArrowTableStream._from_derived_table( pa.Table.from_arrays( [pa.array([1, 2]), pa.array([10, 20]), values], schema=pa.schema( @@ -1631,7 +1631,7 @@ def test_filtering_join_kernels_preserve_system_tag_fields( ) right_table = pa.table({"k": [1, 2], "y": [30, 40]}) if kind == "rejoin": - right = ArrowTableStream( + right = ArrowTableStream._from_derived_table( right_table.append_column(field, values), tag_columns=["k"] ) operator = Rejoin() diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py index 1a477858a..eb635b799 100644 --- a/tests/test_core/operators/test_streaming_rejoin.py +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -134,16 +134,15 @@ def _hand_branch( ) -> ArrowTableStream: """A hand-built branch: tag ``k``, one system tag, data column ``data``.""" n = len(origin) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array(tag, pa.int64()), data: pa.array([float(i) for i in range(n)], pa.float64()), - "origin": pa.array(origin, pa.large_string()), + "_tag_origin": pa.array(origin, pa.large_string()), } ), tag_columns=["k"], - system_tag_columns=["origin"], ) @@ -167,16 +166,15 @@ def test_different_origin_rows_do_not_match_and_a_null_tag_equals_a_null() -> No def _repeated(n: int, data: str, k: list[int] | None = None) -> ArrowTableStream: """``n`` rows of ONE origin row: tag ``k``, one system tag, data ``data`` = 0..n-1.""" - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "k": pa.array(k or [1] * n, pa.int64()), data: pa.array(range(n), pa.int64()), - "origin": pa.array(["x"] * n, pa.large_string()), + "_tag_origin": pa.array(["x"] * n, pa.large_string()), } ), tag_columns=["k"], - system_tag_columns=["origin"], ) @@ -333,19 +331,18 @@ def get_context(key: Any = None) -> contexts.DataContext: # pyright: ignore[rep def _in_context(context: contexts.DataContext, data: str) -> ArrowTableStream: """A raw stream of the given data context: tag ``g``, one system tag, ``data``.""" - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { "g": pa.array([1, 2, 3], pa.int64()), data: pa.array([0.5, 0.25, 0.125], pa.float64()), - "origin": pa.array(["r1", "r2", "r3"], pa.large_string()), + "_tag_origin": pa.array(["r1", "r2", "r3"], pa.large_string()), constants.CONTEXT_KEY: pa.array( [context.context_key] * 3, pa.large_string() ), } ), tag_columns=["g"], - system_tag_columns=["origin"], data_context=context, ) @@ -381,16 +378,15 @@ def test_refusals_are_the_sync_paths_before_the_first_batch() -> None: ) ) left = _hand_branch("a", origin=["r1"], tag=[1]) - retyped = ArrowTableStream( + retyped = ArrowTableStream._from_derived_table( pa.table( { "k": pa.array([1], pa.int32()), "b": pa.array([0.0]), - "origin": pa.array(["r1"], pa.large_string()), + "_tag_origin": pa.array(["r1"], pa.large_string()), } ), tag_columns=["k"], - system_tag_columns=["origin"], ) for inputs in ( (origin.select_data_columns(["depth"]), joined), @@ -522,15 +518,14 @@ def keyed(data: str, k: list[int]) -> ArrowTableStream: return _repeated(len(k), data, k) def plain(data: str) -> ArrowTableStream: - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.table( { data: pa.array([10, 20], pa.int64()), - "origin": pa.array(["x", "x"], pa.large_string()), + "_tag_origin": pa.array(["x", "x"], pa.large_string()), } ), tag_columns=[], - system_tag_columns=["origin"], ) inputs = _in_canonical_order( diff --git a/tests/test_core/sources/test_cached_source.py b/tests/test_core/sources/test_cached_source.py index 8730e6695..8a1bb45ec 100644 --- a/tests/test_core/sources/test_cached_source.py +++ b/tests/test_core/sources/test_cached_source.py @@ -14,11 +14,14 @@ from __future__ import annotations +from pathlib import Path + + import pyarrow as pa import pytest -from orcapod.core.sources import ArrowTableSource, CachedSource -from orcapod.databases import InMemoryArrowDatabase +from orcapod.core.sources import ArrowTableSource, CachedSource, CSVSource +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants @@ -619,3 +622,28 @@ def test_cached_data_matches_source(self, simple_source, db): # Same column names and row count assert set(original_table.column_names) == set(cached_table.column_names) assert original_table.num_rows == cached_table.num_rows + + +@pytest.mark.parametrize("location", ["wrapper", "inner"]) +def test_cached_source_refuses_saved_system_tags_before_replaying_old_rows( + tmp_path: Path, location: str +) -> None: + csv_path = tmp_path / "data.csv" + csv_path.write_text("k,x,rev\n1,10,old\n") + source = CSVSource( + str(csv_path), + tag_columns=["k"], + tag_only_columns=True, + source_id="stable", + ) + database = DeltaTableDatabase(tmp_path / "cache") + cache = CachedSource(source, database) + assert cache.as_table()["x"].to_pylist() == [10] + config = cache.to_config() + legacy_config = config if location == "wrapper" else config["inner_source"] + legacy_config["system_tag_columns"] = ["rev"] + csv_path.write_text("k,x,rev\n1,99,current\n") + + with pytest.raises(ValueError, match=r"system_tag_columns.*rev"): + reopened = CachedSource.from_config(config) + assert reopened.as_table()["x"].to_pylist() != [10], "replayed the old cache" diff --git a/tests/test_core/sources/test_db_table_source.py b/tests/test_core/sources/test_db_table_source.py index 6375826b8..218ca462b 100644 --- a/tests/test_core/sources/test_db_table_source.py +++ b/tests/test_core/sources/test_db_table_source.py @@ -529,29 +529,6 @@ def test_to_config_explicit_source_id_preserved(self, connector): config = src.to_config() assert config["source_name"] == "custom_id" - def test_to_config_system_tag_columns_preserved(self, connector, monkeypatch): - get_column_info = connector.get_column_info - - def with_non_nullable_session_id(table_name: str) -> list[ColumnInfo]: - """Declare the connector's string key as non-nullable.""" - return [ - ColumnInfo(info.name, info.arrow_type, nullable=False) - if info.name == "session_id" - else info - for info in get_column_info(table_name) - ] - - monkeypatch.setattr(connector, "get_column_info", with_non_nullable_session_id) - src = DBTableSource( - connector, - "measurements", - system_tag_columns=["session_id"], - source_id="lab.db", - tag_only_columns=True, - ) - config = src.to_config() - assert config["system_tag_columns"] == ["session_id"] - class TestQueryOverride: def test_custom_query_overrides_default_select(self, measurements_table): @@ -587,40 +564,3 @@ def iter_batches(self, query, params=None, batch_size=1000): tag_only_columns=True, ) assert src.as_table().num_rows == 2 # only s2, s3 have trial > 1 - - -@pytest.mark.parametrize("nullable", [True, False]) -def test_db_source_checks_the_batch_system_tag_declaration_without_column_info( - nullable: bool, -) -> None: - """A null-free batch cannot supply the missing non-nullable tag declaration.""" - from orcapod.errors import InputValidationError - - class BatchSchemaConnector(MockDBConnector): - def get_column_info(self, table_name: str) -> list[ColumnInfo]: - return [] - - table = pa.table( - {"id": [1], "extra": ["tag"]}, - schema=pa.schema( - [ - pa.field("id", pa.int64(), nullable=False), - pa.field("extra", pa.large_string(), nullable=nullable), - ] - ), - ) - conn = BatchSchemaConnector({"rows": table}, {"rows": ["id"]}) - if nullable: - with pytest.raises(InputValidationError, match="extra.*nullable"): - _ = DBTableSource( - conn, "rows", source_id="db", system_tag_columns=["extra"] - ) - else: - source = DBTableSource( - conn, "rows", source_id="db", system_tag_columns=["extra"] - ) - assert ( - not source.as_table(columns={"system_tags": True}) - .schema.field("_tag_extra") - .nullable - ) diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index fe74ab2e4..9fd4c4e21 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -252,18 +252,17 @@ def test_the_message_gives_each_role_type_and_decoded_type() -> None: @pytest.mark.parametrize( - ("column", "role", "kwargs"), + ("column", "role"), [ - ("rid", "system-tag", {"system_tag_columns": ["rid"]}), - ("_tag_source_id::abc", "system-tag", {}), - ("_source_v", "source-info", {}), - ("__note", "meta", {}), - ("_context_key", "data context", {}), + ("_tag_source_id::abc", "system-tag"), + ("_source_v", "source-info"), + ("__note", "meta"), + ("_context_key", "data context"), ], - ids=["named-system-tag", "prefixed-system-tag", "source-info", "meta", "context"], + ids=["prefixed-system-tag", "source-info", "meta", "context"], ) def test_a_raw_stream_refuses_a_dictionary_in_orcapods_own_columns( - column: str, role: str, kwargs: dict[str, Any] + column: str, role: str ) -> None: """Orcapod writes these as plain strings; only a hand-built table can hold a dictionary there, and it is refused the same way, with its role.""" @@ -277,20 +276,17 @@ def test_a_raw_stream_refuses_a_dictionary_in_orcapods_own_columns( } ) with pytest.raises(InputValidationError) as info: - ArrowTableStream(table, tag_columns=["a", "b"], **kwargs) + ArrowTableStream._from_derived_table(table, tag_columns=["a", "b"]) assert f"- {role} column {column!r} has type dictionary<" in str(info.value) OWN_COLUMNS = { "__note": "meta", "_source_v": "source-info", - "_tag_source_id::abc": "system-tag", } -@pytest.mark.parametrize( - "own", [("__note",), ("_source_v",), ("_tag_source_id::abc",), tuple(OWN_COLUMNS)] -) +@pytest.mark.parametrize("own", [("__note",), ("_source_v",), tuple(OWN_COLUMNS)]) @pytest.mark.parametrize("with_user_column", [False, True], ids=["alone", "beside-v"]) @pytest.mark.parametrize("own_first", [False, True], ids=["user-first", "own-first"]) def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( diff --git a/tests/test_core/sources/test_keyed_default_source_id.py b/tests/test_core/sources/test_keyed_default_source_id.py index 03ffa33ee..278155f7c 100644 --- a/tests/test_core/sources/test_keyed_default_source_id.py +++ b/tests/test_core/sources/test_keyed_default_source_id.py @@ -561,13 +561,12 @@ def test_build_takes_hash_in_key_order_by_keyword_only() -> None: table = pa.Table.from_pylist(ROWS, schema=SCHEMA) positional: Any = builder.build # the signature refuses this; call it untyped with pytest.raises(TypeError): - positional(table, TAGS, None, TAGS, (), "arrow_table_v1", (), True) + positional(table, TAGS, None, TAGS, "arrow_table_v1", (), True) result = builder.build( table, TAGS, None, TAGS, - (), "arrow_table_v1", (), hash_in_key_order=True, diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index eccd8406e..032fad18f 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -1,4 +1,4 @@ -"""Source boundaries validate Arrow Null and explicitly nominated system tags.""" +"""Source boundaries validate Arrow fields and reserve the system-tag namespace.""" from __future__ import annotations @@ -26,7 +26,6 @@ from orcapod.contexts.stored import with_data_context from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode -from orcapod.core.row_ids import entry_id, instance_id, record_id from orcapod.core.sources import ( ArrowTableSource, CachedSource, @@ -56,7 +55,7 @@ from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.sources import RootSource from orcapod.system_constants import constants -from orcapod.types import CacheMode, ColumnInfo, Cursor, DataValue +from orcapod.types import CacheMode, ColumnInfo, Cursor, DataValue, Schema from orcapod.utils.arrow_utils import ( normalize_extension_columns, normalize_to_large_types, @@ -87,7 +86,6 @@ class _SourceOptions(TypedDict): tag_columns: Collection[str] tag_only_columns: bool | Collection[str] source_id: str - system_tag_columns: Collection[str] class _Connector(MockDBConnector): @@ -108,6 +106,14 @@ def get_column_info(self, table_name: str) -> list[ColumnInfo]: ) ] + +class _PostgreSQLConnector(_Connector): + """Mock the PostgreSQL connector's location and saved connection settings.""" + + def __init__(self, table: pa.Table, dsn: str) -> None: + super().__init__(table) + self.dsn = dsn + def current_location(self) -> tuple[str, int, str, str]: """Return the connected server's canonical location.""" return "localhost", 5432, "test", "public" @@ -116,6 +122,10 @@ def given_server(self) -> tuple[str, str]: """Return the server specified in the connection string.""" return "localhost", "" + def to_config(self) -> dict[str, Any]: + """Return the connection settings read by PostgreSQLTableSource.""" + return {"dsn": self.dsn} + def _source( kind: str, @@ -123,30 +133,41 @@ def _source( path: Path, monkeypatch: pytest.MonkeyPatch, *, - system_tag_columns: Collection[str] = (), tags: Collection[str] = TAGS, tag_only_columns: bool | Collection[str] = True, -) -> StreamProtocol: + **kwargs: Any, +) -> ( + ArrowTableSource + | DictSource + | DataFrameSource + | CSVSource + | DeltaTableSource + | DBTableSource + | SpiralDBTableSource +): """Build the named source over the same columns using its regular reader.""" options: _SourceOptions = { "tag_columns": tags, "tag_only_columns": tag_only_columns, "source_id": "rows", - "system_tag_columns": system_tag_columns, } if kind == "arrow": - return ArrowTableSource(table, **options) + return ArrowTableSource(table, **options, **kwargs) if kind == "dict": - return DictSource(table.to_pylist(), data_schema=table.schema, **options) + return DictSource( + table.to_pylist(), data_schema=table.schema, **options, **kwargs + ) if kind == "dataframe": - return DataFrameSource(pl.from_arrow(table), schema=table.schema, **options) + return DataFrameSource( + pl.from_arrow(table), schema=table.schema, **options, **kwargs + ) if kind == "csv": file = path / "rows.csv" pa_csv.write_csv(table, file) - return CSVSource(str(file), schema=table.schema, **options) + return CSVSource(str(file), schema=table.schema, **options, **kwargs) if kind == "delta": deltalake.write_deltalake(path / "delta", table) - return DeltaTableSource(path / "delta", **options) + return DeltaTableSource(path / "delta", **options, **kwargs) if kind == "sqlite": if any(field.metadata for field in table.schema): # SQLite cannot store Arrow field metadata. Supply it at the reader boundary. @@ -154,11 +175,11 @@ def _source( "orcapod.core.sources.sqlite_table_source.SQLiteConnector", lambda *_: _Connector(table), ) - return SQLiteTableSource(path / "rows.db", "rows", **options) + return SQLiteTableSource(path / "rows.db", "rows", **options, **kwargs) file = path / "rows.db" types = {pa.string(): "TEXT", pa.int64(): "INTEGER"} cols = ", ".join( - f"{f.name} {types[f.type]}" + ("" if f.nullable else " NOT NULL") + f'"{f.name}" {types[f.type]}' + ("" if f.nullable else " NOT NULL") for f in table.schema ) with sqlite3.connect(file) as conn: @@ -168,7 +189,7 @@ def _source( f"INSERT INTO rows VALUES ({placeholders})", [tuple(row.values()) for row in table.to_pylist()], ) - return SQLiteTableSource(file, "rows", **options) + return SQLiteTableSource(file, "rows", **options, **kwargs) if kind == "spiral": with fake_spiral_sdk.install(path / "spiral"): project = fake_spiral_sdk.ExternalProject("project") @@ -176,16 +197,17 @@ def _source( "default.rows", key_schema=pa.schema([table.schema.field("k")]) ).write(table) project.table("default.rows").record(table.schema) - return SpiralDBTableSource("project", "rows", **options) - connector = _Connector(table) + return SpiralDBTableSource("project", "rows", **options, **kwargs) if kind == "postgres": monkeypatch.setattr( "orcapod.core.sources.postgresql_table_source.PostgreSQLConnector", - lambda *args, **kwargs: connector, + lambda dsn: _PostgreSQLConnector(table, dsn), + ) + return PostgreSQLTableSource( + "postgresql://localhost/test", "rows", **options, **kwargs ) - return PostgreSQLTableSource("postgresql://localhost/test", "rows", **options) assert kind == "db" - return DBTableSource(connector, "rows", **options) + return DBTableSource(_Connector(table), "rows", **options, **kwargs) def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: @@ -270,6 +292,80 @@ def _stored_paths() -> pa.Table: return normalize_extension_columns(_live_paths()) +@pytest.mark.parametrize("kind", SOURCE_KINDS) +@pytest.mark.parametrize("name", ["_tag_application", "_tag::application"]) +def test_source_refuses_reserved_system_tag_columns( + kind: str, name: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + table = _table(pa.field(name, pa.string(), nullable=False), ["a", "b"]) + with pytest.raises(InputValidationError, match=rf"{name!r}.*reserved"): + _source(kind, table, tmp_path, monkeypatch) + + +@pytest.mark.parametrize("kind", SOURCE_KINDS) +def test_source_constructor_has_no_system_tag_columns_argument( + kind: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) + with pytest.raises(TypeError, match="system_tag_columns"): + _source(kind, table, tmp_path, monkeypatch, system_tag_columns=["extra"]) + + +@pytest.mark.parametrize("kind", SOURCE_KINDS) +@pytest.mark.asyncio +async def test_source_builds_its_provenance_pair( + kind: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) + source = _source(kind, table, tmp_path, monkeypatch) + sync = source.as_table(columns={"system_tags": True}) + batches = pa.Table.from_batches(await source.open_channel().collect()) + names = [ + name + for name in sync.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + assert len(names) == 2 + source_id = next( + name for name in names if name.startswith(constants.SYSTEM_TAG_SOURCE_ID_PREFIX) + ) + record_id = next( + name for name in names if name.startswith(constants.SYSTEM_TAG_RECORD_ID_PREFIX) + ) + assert source_id.split("::", 1)[1] == record_id.split("::", 1)[1] + assert sync[source_id].to_pylist() == [source.source_id] * 2 + assert len(set(sync[record_id].to_pylist())) == 2 + assert batches.select(names).equals(sync.select(names)) + assert "system_tag_columns" not in source.to_config() + + +@pytest.mark.parametrize("kind", SOURCE_KINDS) +def test_saved_nonempty_system_tag_columns_are_refused(kind: str) -> None: + with pytest.raises(ValueError, match="system_tag_columns.*extra"): + SOURCE_KINDS[kind].from_config({"system_tag_columns": ["extra"]}) + + +@pytest.mark.parametrize("kind", ["csv", "delta", "sqlite", "postgres", "spiral"]) +@pytest.mark.parametrize("legacy", [False, True]) +def test_saved_config_loads_without_system_tags( + kind: str, legacy: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) + source = _source(kind, table, tmp_path, monkeypatch) + config = source.to_config() + if legacy: + config["system_tag_columns"] = [] + sdk = ( + fake_spiral_sdk.install(tmp_path / "spiral") + if kind == "spiral" + else contextlib.nullcontext() + ) + with sdk: + restored = SOURCE_KINDS[kind].from_config(config) + assert restored.to_config() == source.to_config() + assert restored.as_table(all_info=True).equals(source.as_table(all_info=True)) + + @pytest.mark.parametrize("kind", SOURCE_KINDS) @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize("role", ["tag", "data", "data-tag"]) @@ -487,136 +583,6 @@ async def read() -> list[tuple[DataValue, DataValue]]: assert asyncio.run(read()) == expected -@pytest.mark.parametrize("kind", SOURCE_KINDS) -@pytest.mark.parametrize( - ("arrow_type", "nullable", "values"), - [ - (pa.int64(), False, [7, 8]), - (pa.string(), True, ["a", "b"]), - (pa.string(), True, ["a", None]), - ], -) -def test_rejects_invalid_custom_system_tag_columns( - kind: str, - arrow_type: pa.DataType, - nullable: bool, - values: list[Any], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - table = _table(pa.field("extra", arrow_type, nullable=nullable), values) - with pytest.raises(InputValidationError, match=r"'extra'.*non-null.*text"): - _source(kind, table, tmp_path, monkeypatch, system_tag_columns=["rev", "extra"]) - - -@pytest.mark.parametrize("kind", SOURCE_KINDS) -@pytest.mark.parametrize( - "names", - [("missing",), ("extra", "missing", "rev"), ("rev", "missing", "extra")], -) -def test_refuses_missing_custom_system_tag_columns( - kind: str, - names: tuple[str, ...], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) - with pytest.raises(ValueError, match=r"system_tag_columns not found.*'missing'"): - _source(kind, table, tmp_path, monkeypatch, system_tag_columns=names) - - -@pytest.mark.parametrize("kind", SOURCE_KINDS) -@pytest.mark.parametrize( - "metadata", - [ - {b"owner": b"research"}, - {b"ARROW:extension:name": b"user.opaque", b"ARROW:extension:metadata": b""}, - ], - ids=["ordinary", "extension"], -) -@pytest.mark.parametrize("names", [("extra",), ("extra", "rev"), ("rev", "extra")]) -def test_refuses_field_metadata_on_custom_system_tags( - kind: str, - metadata: dict[bytes, bytes], - names: tuple[str, ...], - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - table = _table( - pa.field("extra", pa.string(), nullable=False, metadata=metadata), ["a", "b"] - ) - with pytest.raises( - InputValidationError, match=r"'extra'.*[Rr]emove.*field metadata" - ): - _source(kind, table, tmp_path, monkeypatch, system_tag_columns=names) - - -def test_metadata_free_custom_system_tag_pins_its_row_ids() -> None: - schema = pa.schema( - [ - pa.field("k", pa.int64(), False), - pa.field("g", pa.large_string(), False), - pa.field("x", pa.int64(), False), - pa.field("y", pa.large_string(), False), - pa.field("custom", pa.large_string(), False), - ] - ) - raw = pa.Table.from_pydict( - { - "k": [1, 2], - "g": ["a", "b"], - "x": [3, 4], - "y": ["v", "w"], - "custom": ["p", "q"], - }, - schema=schema, - ) - source = ArrowTableSource( - raw, - tag_columns=TAGS, - tag_only_columns=True, - system_tag_columns=["custom"], - source_id="meta", - ) - hasher = source.data_context.arrow_hasher - actual = [] - for tag, data in source.iter_data(): - entry = entry_id(hasher, tag, data) - instance = instance_id(hasher, tag, data) - record = record_id(hasher, source.content_hash(), instance, UUID(int=40)) - actual.append((entry.to_hex(), instance.to_hex(), record.to_hex())) - # The instance and record IDs include the renamed input-token fields. - assert actual == [ - ( - "00000266ff2e58dd5c1cb957ac9ff249ae13e17918a263847f8e2f65d756f746b3f561", - "000002901df30a2ba140f32dbf43fec67d5d05b93d43bdb713c5ee9da604df0fba61fe", - "00000230cd4fe35505c96c89980db40437e444042e52df8f0117521f7f55ceb651db3b", - ), - ( - "0000029689a4a738cf93bbcfde75085dc43bac31570b0b368eff34b0f3d0fa427769c1", - "0000023448cf6a0cceaa94adcfbf1b67e743d3cb08b4dc57f8dc43e2f26a7cc266bfa6", - "00000230008bd2bc72708ead139fe14cac0fe8107521cfc70089cc44c3b43e0d7a9df9", - ), - ] - - -@pytest.mark.parametrize("kind", SOURCE_KINDS) -def test_accepts_two_non_nullable_string_system_tags( - kind: str, - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) - source = _source( - kind, table, tmp_path, monkeypatch, system_tag_columns=["extra", "rev"] - ) - tags, _ = source.output_schema(columns={"system_tags": True}) - assert {name: tags[name] for name in ("_tag_extra", "_tag_rev")} == { - "_tag_extra": str, - "_tag_rev": str, - } - - @pytest.mark.parametrize("kind", [kind for kind in SOURCE_KINDS if kind != "sqlite"]) def test_refuses_arrow_null_from_readers( kind: str, @@ -644,17 +610,6 @@ def test_dataframe_schema_can_type_null_values() -> None: ) -@pytest.mark.parametrize( - "kind", ["arrow", "dict", "dataframe", "csv", "db", "postgres"] -) -def test_rejects_null_value_even_under_a_non_nullable_system_tag_field( - kind: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - table = _table(pa.field("extra", pa.string(), nullable=False), ["a", None]) - with pytest.raises(InputValidationError, match=r"'extra'.*contains null values"): - _source(kind, table, tmp_path, monkeypatch, system_tag_columns=["extra", "rev"]) - - def test_sqlite_sql_null_is_a_value_in_a_typed_column( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -687,12 +642,14 @@ def test_no_declared_type_for_python_none_still_infers_a_string() -> None: class _Poll: """Minimal impl for testing schema validation before the first fetch.""" - def __init__(self, schema: pa.Schema | None, batch: FrameInitTypes) -> None: + def __init__( + self, schema: Schema | pa.Schema | None, batch: FrameInitTypes + ) -> None: self._schema = schema self._batch = batch - def schema(self) -> pa.Schema | None: - """Return the optional Arrow schema.""" + def schema(self) -> Schema | pa.Schema | None: + """Return the optional schema declaration.""" return self._schema def identity(self) -> str: @@ -721,6 +678,17 @@ async def close(self) -> None: """There is no connection to close.""" +@pytest.mark.parametrize("name", ["_tag_application", "_tag::application"]) +@pytest.mark.parametrize("arrow", [False, True], ids=["python", "arrow"]) +def test_polling_refuses_system_tags_in_the_declared_schema( + name: str, arrow: bool +) -> None: + table = pa.table({"k": [1], name: ["a"]}) + schema = table.schema if arrow else Schema({"k": int, name: str}) + with pytest.raises(InputValidationError, match=rf"{name!r}.*reserved"): + PollingSource(_Poll(schema, table), ["k"], record_id_columns="k") + + @pytest.mark.parametrize("values", [[], [[None], []]]) def test_polling_refuses_null_in_declaration_and_batch(values: list[Any]) -> None: table = _table(pa.field("__unused", pa.large_list(pa.null())), values) @@ -901,7 +869,7 @@ def test_native_arrow_logical_fields( offsets = pa.array([0, 1, 2], type=pa.int32()) # All routes validate system columns before discarding them. Use one to # exercise the nested guard independently of existing hash and cast limits. - nested_name = f"{constants.SYSTEM_TAG_PREFIX}logical" + nested_name = f"{constants.META_PREFIX}logical" if layout == "struct": array = pa.StructArray.from_arrays([paths, others], fields=[path, other]) table = pa.table({nested_name: array}) @@ -1075,13 +1043,16 @@ def test_reopened_cache_refuses_legacy_system_tag_metadata( _table(pa.field("extra", pa.string(), False), ["a", "b"]), tag_columns=TAGS, tag_only_columns=True, - system_tag_columns=["extra"], source_id="rows", ) cache = source.cached(DeltaTableDatabase(tmp_path)) columns = {"source": True, "system_tags": True} records = source.as_table(columns=columns) - name = "_tag_extra" + name = next( + name + for name in records.column_names + if name.startswith(constants.SYSTEM_TAG_SOURCE_ID_PREFIX) + ) pos = records.schema.get_field_index(name) field = records.schema.field(pos).with_metadata( {b"ARROW:extension:name": b"user.opaque"} @@ -1103,7 +1074,7 @@ async def consume() -> None: with pytest.raises( InputValidationError, - match=r"'_tag_extra'.*cache.*written.*field metadata.*[Rr]ebuild", + match=r"_tag_source_id.*cache.*written.*field metadata.*[Rr]ebuild", ): if route == "table": reopened.as_table(columns=columns) @@ -1146,76 +1117,6 @@ def __arrow_c_stream__(self, requested_schema: Any = None) -> Any: return self.stream.__arrow_c_stream__(requested_schema) -@pytest.mark.parametrize( - "representation", ["table", "batch", "reader", "stream", "array", "dual"] -) -@pytest.mark.parametrize("row_count", [0, 2]) -@pytest.mark.parametrize("declare_schema", [False, True]) -@pytest.mark.parametrize("field_metadata", [None, {b"owner": b"research"}]) -def test_dataframe_source_validates_arrow_inputs_before_polars( - representation: str, - row_count: int, - declare_schema: bool, - field_metadata: dict[bytes | str, bytes | str] | None, -) -> None: - clean = _table(pa.field("extra", pa.string(), False), ["a", "b"][:row_count]) - pos = clean.schema.get_field_index("extra") - table = ( - clean - if field_metadata is None - else clean.set_column( - pos, - clean.schema.field(pos).with_metadata(field_metadata), - clean.column(pos), - ) - ) - batch = pa.RecordBatch.from_arrays( - [c.combine_chunks() for c in table.columns], schema=table.schema - ) - representations = { - "table": table, - "batch": batch, - "reader": table.to_reader(max_chunksize=1), - "stream": _ArrowStreamExporter(table), - "array": _ArrowArrayExporter(batch), - "dual": _DualArrowExporter(batch, clean), - } - data = representations[representation] - schema = clean.schema if declare_schema else None - - if field_metadata is not None: - with pytest.raises( - InputValidationError, match=r"'extra'.*[Rr]emove.*field metadata" - ): - DataFrameSource( - data, - schema=schema, - tag_columns=TAGS, - system_tag_columns=["rev", "extra"], - ) - else: - source = DataFrameSource( - data, schema=schema, tag_columns=TAGS, system_tag_columns=["rev", "extra"] - ) - expected = DataFrameSource( - clean, schema=schema, tag_columns=TAGS, system_tag_columns=["rev", "extra"] - ) - columns = {"system_tags": True, "source": True} - actual_table = source.as_table(columns=columns) - assert actual_table.num_rows == row_count - assert actual_table.equals( - expected.as_table(columns=columns), check_metadata=True - ) - assert source.source_id == expected.source_id - assert source.content_hash() == expected.content_hash() - assert source.pipeline_hash() == expected.pipeline_hash() - - if isinstance(data, (_ArrowArrayExporter, _ArrowStreamExporter)): - assert data.exports == 1 - if isinstance(data, _DualArrowExporter): - assert data.stream_exports == 0 - - @pytest.mark.parametrize( "route", [ @@ -1236,7 +1137,6 @@ def test_bound_proxy_refuses_delegated_system_tag_metadata( _table(pa.field("extra", pa.string(), False), ["a", "b"]), tag_columns=TAGS, tag_only_columns=True, - system_tag_columns=["extra"], source_id="rows", ) tags, data = source.output_schema() @@ -1251,9 +1151,14 @@ def test_bound_proxy_refuses_delegated_system_tag_metadata( proxy.bind(source) columns = {"system_tags": True} table = source.as_table(columns=columns) - pos = table.schema.get_field_index("_tag_extra") + name = next( + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_SOURCE_ID_PREFIX) + ) + pos = table.schema.get_field_index(name) field = table.schema.field(pos).with_metadata({b"owner": b"research"}) - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( table.set_column(pos, field, table.column(pos)), tag_columns=TAGS, ) @@ -1265,7 +1170,7 @@ async def consume() -> None: _ = [row async for row in proxy.async_iter_data()] with pytest.raises( - InputValidationError, match=r"'_tag_extra'.*[Rr]emove.*field metadata" + InputValidationError, match=r"_tag_source_id.*[Rr]emove.*field metadata" ): if route == "bind": proxy.bind(source) @@ -1390,50 +1295,6 @@ def get_all_records( derived.as_table() -@pytest.mark.parametrize("metadata", [None, {b"owner": b"research"}]) -def test_spiral_validates_field_metadata_on_a_tag_copy_nominated_as_a_system_tag( - tmp_path: Path, - metadata: dict[bytes, bytes] | None, -) -> None: - schema = pa.schema( - [pa.field("k", pa.string(), False, metadata), pa.field("x", pa.int8(), False)] - ) - table = pa.Table.from_pylist([{"k": "a", "x": 1}, {"k": "b", "x": 2}], schema) - with fake_spiral_sdk.install(tmp_path): - external = fake_spiral_sdk.ExternalProject("project").create_table( - "default.rows", key_schema=pa.schema([schema.field("k")]) - ) - external.write(table) - external.record(schema) - - def build() -> SpiralDBTableSource: - return SpiralDBTableSource( - "project", - "rows", - tag_columns=["k"], - tag_only_columns=True, - tags_as_data={"k": "copy"}, - system_tag_columns=["copy"], - ) - - if metadata is not None: - with pytest.raises( - InputValidationError, match=r"'copy'.*[Rr]emove.*field metadata" - ): - build() - return - source = build() - columns = {"system_tags": True} - assert source.as_table(columns=columns).column("_tag_copy").to_pylist() == [ - "a", - "b", - ] - assert [tag.system_tags()["_tag_copy"] for tag, _ in source.iter_data()] == [ - "a", - "b", - ] - - def test_spiral_validates_reserved_null_in_an_empty_scan_batch( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -1481,119 +1342,6 @@ def test_bound_proxy_keeps_projections_row_order() -> None: ) -@pytest.mark.parametrize("representation", ["table", "reader", "stream"]) -def test_dataframe_source_refuses_nullable_arrow_custom_system_tag( - representation: str, -) -> None: - """Converting a declared nullable custom system tag never makes it required.""" - table = _table(pa.field("extra", pa.string(), nullable=True), ["a", "b"]) - if representation == "reader": - data = table.to_reader() - elif representation == "stream": - data = _ArrowStreamExporter(table) - else: - data = table - with pytest.raises(InputValidationError, match=r"'extra'.*nullable"): - ArrowTableSource(table, tag_columns=TAGS, system_tag_columns=["extra"]) - with pytest.raises(InputValidationError, match=r"'extra'.*nullable"): - DataFrameSource(data, tag_columns=TAGS, system_tag_columns=["extra"]) - - -@pytest.mark.parametrize("representation", ["table", "reader", "stream"]) -@pytest.mark.parametrize("raw", ["text", "integer", "null", "metadata"]) -def test_dataframe_source_uses_explicit_custom_system_tag_declaration( - representation: str, raw: str -) -> None: - base = pa.field("extra", pa.string(), nullable=True) - match = "non-text values" - if raw == "integer": - table = _table(pa.field("extra", pa.int64()), [1, 2]) - elif raw == "null": - table = _table(base, ["a", None]) - match = "contains null values" - elif raw == "metadata": - table = _table(base.with_metadata({b"origin": b"raw"}), ["a", "b"]) - match = "field metadata" - else: - table = _table(base, ["a", "b"]) - if representation == "reader": - data = table.to_reader() - elif representation == "stream": - data = _ArrowStreamExporter(table) - else: - data = table - schema = table.schema.set( - table.schema.get_field_index("extra"), base.with_nullable(False) - ) - if raw != "text": - with pytest.raises(InputValidationError, match=match): - DataFrameSource( - data, schema=schema, tag_columns=TAGS, system_tag_columns=["extra"] - ) - return - source = DataFrameSource( - data, schema=schema, tag_columns=TAGS, system_tag_columns=["extra"] - ) - result = source.as_table(columns={"system_tags": True}) - assert not result.schema.field("_tag_extra").nullable - assert result["_tag_extra"].to_pylist() == ["a", "b"] - - -@pytest.mark.parametrize("representation", ["pandas", "polars"]) -def test_dataframe_source_declares_native_custom_system_tag_required_large_string( - representation: str, -) -> None: - """Native frame system tags have a value-independent declared field.""" - values = { - "g": ["a", "b"], - "k": ["a", "b"], - "x": [1, 2], - "extra": ["one", "two"], - } - data = pd.DataFrame(values) if representation == "pandas" else pl.DataFrame(values) - source = DataFrameSource(data, tag_columns=TAGS, system_tag_columns=["extra"]) - field = source.as_table(columns={"system_tags": True}).schema.field("_tag_extra") - assert field.type == pa.large_string() - assert not field.nullable - - -@pytest.mark.parametrize("representation", ["pandas", "polars"]) -@pytest.mark.parametrize("values", [["one", None], [1, 2]]) -@pytest.mark.parametrize("explicit_schema", [False, True]) -def test_dataframe_source_rejects_invalid_native_custom_system_tag( - representation: str, values: list[object], explicit_schema: bool -) -> None: - """Native custom system tags reject null and non-text values.""" - data_values = { - "g": ["a", "b"], - "k": ["a", "b"], - "x": [1, 2], - "extra": values, - } - data = ( - pd.DataFrame(data_values) - if representation == "pandas" - else pl.DataFrame(data_values) - ) - schema = ( - pa.schema( - [ - pa.field("g", pa.large_string()), - pa.field("k", pa.large_string()), - pa.field("x", pa.int64()), - pa.field("extra", pa.large_string(), nullable=False), - ] - ) - if explicit_schema - else None - ) - expected_type = "int64" if isinstance(values[0], int) else "large_string" - with pytest.raises(InputValidationError, match=rf"'extra'.*type {expected_type}"): - DataFrameSource( - data, schema=schema, tag_columns=TAGS, system_tag_columns=["extra"] - ) - - def test_dataframe_source_preserves_declared_arrow_data_field() -> None: field = pa.field("x", pa.int64(), nullable=True, metadata={b"unit": b"kg"}) table = pa.Table.from_arrays( @@ -1603,29 +1351,21 @@ def test_dataframe_source_preserves_declared_arrow_data_field() -> None: assert source.as_table().schema.field("x").equals(field, check_metadata=True) -def test_dict_source_declares_custom_system_tag_required_large_string() -> None: - """Dict system tags use the same fixed declaration as native frames.""" - source = DictSource( - [ - {"g": "a", "k": "a", "x": 1, "extra": "one"}, - {"g": "b", "k": "b", "x": 2, "extra": "two"}, - ], - tag_columns=TAGS, - system_tag_columns=["extra"], - ) - field = source.as_table(columns={"system_tags": True}).schema.field("_tag_extra") - assert field.type == pa.large_string() - assert not field.nullable +@pytest.mark.parametrize("source_type", [ListSource, SourceProxy]) +def test_non_reconstructible_source_refuses_saved_system_tags( + source_type: type[ListSource] | type[SourceProxy], +) -> None: + with pytest.raises(ValueError, match=r"system_tag_columns.*rev"): + source_type.from_config({"system_tag_columns": ["rev"]}) -@pytest.mark.parametrize("values", [["one", None], [1, 2]]) -def test_dict_source_rejects_invalid_custom_system_tag( - values: list[str | None | int], -) -> None: - """Dict system tags reject null and non-text values.""" - rows = [ - {"g": "a", "k": "a", "x": 1, "extra": values[0]}, - {"g": "b", "k": "b", "x": 2, "extra": values[1]}, - ] - with pytest.raises(InputValidationError, match=r"'extra'"): - _ = DictSource(rows, tag_columns=TAGS, system_tag_columns=["extra"]) +def test_polling_source_refuses_saved_system_tags_before_loading_impl() -> None: + with pytest.raises(ValueError, match=r"system_tag_columns.*rev"): + PollingSource.from_config( + {"system_tag_columns": ["rev"], "impl_module": "nonexistent_poll_impl"} + ) + + +def test_derived_source_refuses_saved_system_tags_before_loading_origin() -> None: + with pytest.raises(ValueError, match=r"system_tag_columns.*rev"): + DerivedSource.from_config({"system_tag_columns": ["rev"], "origin": {}}) diff --git a/tests/test_core/sources/test_source_check_for_new_data.py b/tests/test_core/sources/test_source_check_for_new_data.py index 270b039ce..ef40060ec 100644 --- a/tests/test_core/sources/test_source_check_for_new_data.py +++ b/tests/test_core/sources/test_source_check_for_new_data.py @@ -602,14 +602,7 @@ def _rev_rows(rev: str) -> pa.Table: ) -def _system_tag_values(source: Any) -> list[Any]: - table = source.as_table(columns={"system_tags": True}) - names = [n for n in table.column_names if "rev" in n and n != "rev"] - names = names or ["rev"] - return sorted(str(v) for n in names for v in table.column(n).to_pylist()) - - -def test_delta_a_change_in_a_system_tag_column_only_is_taken_in( +def test_delta_a_change_in_a_regular_column_only_is_taken_in( tmp_path: Path, ) -> None: path = tmp_path / "rev" @@ -618,30 +611,28 @@ def test_delta_a_change_in_a_system_tag_column_only_is_taken_in( path, tag_columns="k", record_id_columns="k", - system_tag_columns=["rev"], tag_only_columns=True, ) deltalake.write_deltalake(str(path), _rev_rows("b"), mode="overwrite") assert source.check_for_new_data() is True - assert "a" not in _system_tag_values(source) + assert source.as_table()["rev"].to_pylist() == ["b", "b"] -def test_csv_a_change_in_a_system_tag_column_only_is_taken_in(tmp_path: Path) -> None: +def test_csv_a_change_in_a_regular_column_only_is_taken_in(tmp_path: Path) -> None: path = tmp_path / "rev.csv" path.write_text("k,x,rev\n0,0,a\n1,10,a\n") source = CSVSource( str(path), tag_columns="k", record_id_columns="k", - system_tag_columns=["rev"], tag_only_columns=True, ) path.write_text("k,x,rev\n0,0,b\n1,10,b\n") assert source.check_for_new_data() is True - assert "a" not in _system_tag_values(source) + assert source.as_table()["rev"].to_pylist() == ["b", "b"] -def test_sqlite_a_change_in_a_system_tag_column_only_is_taken_in( +def test_sqlite_a_change_in_a_regular_column_only_is_taken_in( tmp_path: Path, ) -> None: path = tmp_path / "rev.db" @@ -655,13 +646,12 @@ def test_sqlite_a_change_in_a_system_tag_column_only_is_taken_in( path, "t", record_id_columns="k", - system_tag_columns=["rev"], tag_only_columns=True, ) with sqlite3.connect(path) as conn: conn.execute("UPDATE t SET rev = 'b'") assert source.check_for_new_data() is True - assert "a" not in _system_tag_values(source) + assert source.as_table()["rev"].to_pylist() == ["b", "b"] def test_two_derived_sources_over_one_source_both_take_in_its_change( diff --git a/tests/test_core/sources/test_source_protocol_conformance.py b/tests/test_core/sources/test_source_protocol_conformance.py index 509b67a06..a64aed383 100644 --- a/tests/test_core/sources/test_source_protocol_conformance.py +++ b/tests/test_core/sources/test_source_protocol_conformance.py @@ -461,15 +461,15 @@ def test_df_source_missing_tag_column_raises(self): DataFrameSource(data=df, tag_columns="nonexistent", tag_only_columns=True) def test_arrow_source_strips_system_columns_from_input(self): - """System columns in the input table are silently dropped.""" + """Source-info columns in the input table are stripped.""" table = pa.table( { "x": pa.array([1, 2], type=pa.int64()), - "_tag_something": pa.array(["a", "b"], type=pa.large_string()), + "_source_x": pa.array(["a", "b"], type=pa.large_string()), } ) src = ArrowTableSource(table=table, infer_nullable=True) # system columns should not appear in data keys tag_keys, data_keys = src.keys() - assert "_tag_something" not in tag_keys - assert "_tag_something" not in data_keys + assert "_source_x" not in tag_keys + assert "_source_x" not in data_keys diff --git a/tests/test_core/sources/test_sources_comprehensive.py b/tests/test_core/sources/test_sources_comprehensive.py index ab21a4661..234807c15 100644 --- a/tests/test_core/sources/test_sources_comprehensive.py +++ b/tests/test_core/sources/test_sources_comprehensive.py @@ -16,7 +16,7 @@ TagProtocol.as_dict() protocol, identity_structure stability - ArrowTableSource: table property, source_id controls provenance tokens, negative row index raises, duplicate record_id takes first match, - system_tag_columns forwarded, integer record_id_column values + integer record_id_column values - SourceRegistry: replace() returns None when no prior entry, replace() with empty source_id raises, register() with None raises, __repr__ """ @@ -294,17 +294,17 @@ def test_string_tag_columns_accepted(self): assert "value" in data_keys def test_system_columns_stripped_from_polars_input(self): - """Polars DataFrames with system-prefix columns have those columns dropped.""" + """Source-info columns in a Polars input are stripped.""" df = pl.DataFrame( { "x": [1, 2], - "_tag_something": ["a", "b"], + "_source_x": ["a", "b"], } ) src = DataFrameSource(data=df) tag_keys, data_keys = src.keys() - assert "_tag_something" not in tag_keys - assert "_tag_something" not in data_keys + assert "_source_x" not in tag_keys + assert "_source_x" not in data_keys def test_source_id_in_provenance_tokens(self): df = pl.DataFrame({"id": [1, 2, 3], "value": ["a", "b", "c"]}) @@ -484,16 +484,6 @@ def test_source_id_controls_provenance_tokens(self): token = t.column(source_cols[0])[0].as_py() assert token.startswith("arrow_table_v1:my_source::") - def test_system_tag_columns_forwarded_to_stream(self): - """system_tag_columns passed at construction are preserved.""" - table = pa.table({"x": [1, 2], "sys_col": ["a", "b"]}) - src = ArrowTableSource( - table=table, system_tag_columns=["sys_col"], infer_nullable=True - ) - assert src.as_table(columns={"system_tags": True}).column( - "_tag_sys_col" - ).to_pylist() == ["a", "b"] - def test_as_table_all_info_includes_system_tag_columns(self): """as_table(all_info=True) exposes paired _tag_source_id and _tag_record_id columns.""" from orcapod.system_constants import constants diff --git a/tests/test_core/sources/test_stream_builder.py b/tests/test_core/sources/test_stream_builder.py index 4bdd53335..a5e06a641 100644 --- a/tests/test_core/sources/test_stream_builder.py +++ b/tests/test_core/sources/test_stream_builder.py @@ -9,7 +9,7 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder, SourceStreamResult from orcapod.core.sources.arrow_table_source import ArrowTableSource -from orcapod.errors import RowIdentifierError +from orcapod.errors import InputValidationError, RowIdentifierError class TestSourceStreamBuilder: @@ -25,6 +25,21 @@ def test_build_returns_source_stream_result(self, builder): result = builder.build(table, tag_columns=["id"], kind_part="arrow_table_v1") assert isinstance(result, SourceStreamResult) + def test_build_refuses_user_system_tags(self, builder): + table = pa.table({"id": [1, 2], "x": [10, 20], "_tag_user": ["a", "b"]}) + with pytest.raises(InputValidationError, match="'_tag_user'.*reserved"): + builder.build(table, tag_columns=["id"], kind_part="arrow_table_v1") + + def test_build_has_no_system_tag_columns_argument(self, builder): + table = pa.table({"id": [1, 2], "x": [10, 20]}) + with pytest.raises(TypeError, match="system_tag_columns"): + builder.build( + table, + tag_columns=["id"], + kind_part="arrow_table_v1", + system_tag_columns=["x"], + ) + def test_build_stream_has_correct_row_count(self, builder): table = pa.table({"id": pa.array([1, 2, 3]), "x": pa.array([10, 20, 30])}) result = builder.build(table, tag_columns=["id"], kind_part="arrow_table_v1") diff --git a/tests/test_core/streams/test_head_sorting.py b/tests/test_core/streams/test_head_sorting.py index 6c242bef9..4a5029f0b 100644 --- a/tests/test_core/streams/test_head_sorting.py +++ b/tests/test_core/streams/test_head_sorting.py @@ -350,8 +350,8 @@ def test_a_tagless_stream_with_system_tags_keeps_its_canonical_identity_order() """ from orcapod.core.streams import ArrowTableStream - table = pa.table({"record_id": ["b", "c", "a"], "x": [1, 2, 3]}) - stream = ArrowTableStream(table, tag_columns=[], system_tag_columns=["record_id"]) + table = pa.table({"_tag_record_id": ["b", "c", "a"], "x": [1, 2, 3]}) + stream = ArrowTableStream._from_derived_table(table, tag_columns=[]) ordered = stream.as_table(columns={"system_tags": True, "sort_by_tags": True}) shown = next(c for c in ordered.column_names if c.endswith("record_id")) assert ordered.column(shown).to_pylist() == ["a", "b", "c"] diff --git a/tests/test_core/streams/test_identity_order_regression.py b/tests/test_core/streams/test_identity_order_regression.py index 11a036e01..2975cf36e 100644 --- a/tests/test_core/streams/test_identity_order_regression.py +++ b/tests/test_core/streams/test_identity_order_regression.py @@ -116,7 +116,12 @@ def build(shape: tuple[Any, ...], rows: list[int] | None = None) -> ArrowTableSt table = pa.table([columns[c] for c in names], names=names) if rows is not None: table = table.take(pa.array(rows, pa.int64())) - return ArrowTableStream(table, tag_columns=tags, system_tag_columns=system) + return ArrowTableStream._from_derived_table( + table.rename_columns( + ["_tag_" + name if name in system else name for name in table.column_names] + ), + tag_columns=tags, + ) @pytest.mark.parametrize("shape", shapes()) diff --git a/tests/test_core/streams/test_iter_data_chunk_layouts.py b/tests/test_core/streams/test_iter_data_chunk_layouts.py index edd0b6370..8596897cb 100644 --- a/tests/test_core/streams/test_iter_data_chunk_layouts.py +++ b/tests/test_core/streams/test_iter_data_chunk_layouts.py @@ -211,7 +211,7 @@ def _system_tag_stream( ) columns["x"] = _chunked([i * 10 for i in range(n)], data_sizes, pa.int64()) columns["y"] = _chunked([f"v{i}" for i in range(n)], data_sizes, pa.large_string()) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.Table.from_pydict(columns), tag_columns=["id"] if tag_sizes is not None else [], ) diff --git a/tests/test_core/streams/test_raw_stream_tag_order.py b/tests/test_core/streams/test_raw_stream_tag_order.py index 8fad71c35..155531634 100644 --- a/tests/test_core/streams/test_raw_stream_tag_order.py +++ b/tests/test_core/streams/test_raw_stream_tag_order.py @@ -74,10 +74,14 @@ def _stream( table = pa.table([COLUMNS[name] for name in names], names=names) if rows is not None: table = table.take(pa.array(rows, pa.int64())) - return ArrowTableStream( - table, + return ArrowTableStream._from_derived_table( + table.rename_columns( + [ + "_tag_" + name if name in system_order else name + for name in table.column_names + ] + ), tag_columns=list(tag_order), - system_tag_columns=list(system_order), data_tags=data_tags, ) @@ -242,36 +246,31 @@ def _empty(fields: list[pa.Field[Any]], **kwargs: Any) -> ArrowTableStream: @pytest.mark.parametrize( - ("left", "right", "kwargs"), + ("left", "right"), [ - ([K, pa.field("x", pa.int64())], [K, pa.field("y", pa.int64())], {}), - ([K, pa.field("x", pa.int64())], [K, pa.field("x", pa.large_string())], {}), + ([K, pa.field("x", pa.int64())], [K, pa.field("y", pa.int64())]), + ([K, pa.field("x", pa.int64())], [K, pa.field("x", pa.large_string())]), ( [K, pa.field("x", pa.int64(), nullable=True)], [K, pa.field("x", pa.int64(), nullable=False)], - {}, ), ( [K, pa.field("x", pa.int64())], [K, pa.field("x", pa.int64()), pa.field("z", pa.float64())], - {}, ), ( [K, pa.field("x", pa.int64())], - [K, pa.field("x", pa.int64()), pa.field("s1", pa.large_string())], - {"system_tag_columns": ["s1"]}, + [K, pa.field("x", pa.int64()), pa.field("_tag_s1", pa.large_string())], ), ], ids=["data-name", "data-type", "nullability", "extra-data-column", "system-tag"], ) def test_streams_with_no_rows_and_different_columns_differ( - left: list[pa.Field[Any]], right: list[pa.Field[Any]], kwargs: dict[str, Any] + left: list[pa.Field[Any]], right: list[pa.Field[Any]] ) -> None: """The identity table is hashed whole, so its schema counts even with no rows.""" - other = ( - ArrowTableStream(pa.schema(right).empty_table(), tag_columns=["k"], **kwargs) - if kwargs - else _empty(right) + other = ArrowTableStream._from_derived_table( + pa.schema(right).empty_table(), tag_columns=["k"] ) assert _empty(left).content_hash() != other.content_hash() diff --git a/tests/test_core/streams/test_system_tag_validation.py b/tests/test_core/streams/test_system_tag_validation.py index 251114853..619057ca0 100644 --- a/tests/test_core/streams/test_system_tag_validation.py +++ b/tests/test_core/streams/test_system_tag_validation.py @@ -3,7 +3,7 @@ from __future__ import annotations import re -from typing import cast +from typing import Any, cast import pyarrow as pa import pytest @@ -11,13 +11,27 @@ 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.sources import ArrowTableSource 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("name", ["_tag_application", "_tag::application"]) +def test_public_stream_refuses_system_tag_names(name: str) -> None: + with pytest.raises(InputValidationError, match=rf"{name!r}.*reserved"): + ArrowTableStream(pa.table({"data": [1, 2], name: ["a", "b"]})) + + +def test_public_stream_has_no_system_tag_columns_argument() -> None: + constructor: Any = ArrowTableStream + with pytest.raises(TypeError, match="system_tag_columns"): + constructor( + pa.table({"data": [1, 2], "tag": ["a", "b"]}), system_tag_columns=["tag"] + ) + + @pytest.mark.parametrize( ("dtype", "values", "nullable", "message"), [ @@ -26,92 +40,41 @@ (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" + """Internal tables validate system-tag fields and values.""" + name = 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) + ArrowTableStream._from_derived_table(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.""" + """Wrapping an internal table 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) + stream = ArrowTableStream._from_derived_table(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.field("_tag_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) + left = ArrowTableStream._from_derived_table(left_table) + right = ArrowTableStream._from_derived_table(right_table) joined = Join()(left, right).as_table(columns={"system_tags": True}) system_names = [ name @@ -127,9 +90,8 @@ def test_join_extends_complete_pairs_and_custom_system_tags() -> None: @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 + custom_name: str, operation: str, execution: str ) -> None: """An ordinary custom string tag survives extension, LOG and further operators.""" from orcapod.channels import Channel, ReadableChannel @@ -144,17 +106,11 @@ async def test_extended_custom_id_tags_survive_operator_log( 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"]) + pa.field(f"_tag_{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], - ) + left: StreamProtocol = ArrowTableStream._from_derived_table( + table, tag_columns=["k"] ) right: StreamProtocol = ArrowTableSource( pa.table({"k": [1, 2], "y": [5, 6]}), @@ -216,14 +172,14 @@ async def test_extended_custom_id_tags_survive_operator_log( ) -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.""" +def test_public_stream_refuses_a_detached_system_tag() -> None: + """A detached system-tag column still belongs to Orcapod.""" from orcapod.operators import Batch - table = pa.table({"x": [1], "source_id": ["custom"]}) - source = ArrowTableStream(table, system_tag_columns=["source_id"]) + table = pa.table({"x": [1], "_tag_source_id": ["derived"]}) + source = ArrowTableStream._from_derived_table(table) detached = Batch(batch_size=1)(source).as_table(columns={"system_tags": True}) - _, partner = system_tag_column_names(source.pipeline_hash().to_hex()) + (name,) = (c for c in detached.column_names if c.startswith("_tag_source_id")) - with pytest.raises(InputValidationError, match=re.escape(partner)): + with pytest.raises(InputValidationError, match=rf"{re.escape(name)}.*reserved"): _ = ArrowTableStream(detached) diff --git a/tests/test_core/streams/test_token_shape.py b/tests/test_core/streams/test_token_shape.py index 121699615..cc6bb080b 100644 --- a/tests/test_core/streams/test_token_shape.py +++ b/tests/test_core/streams/test_token_shape.py @@ -434,7 +434,12 @@ def test_a_logical_list_counts_as_one_list_layer(aggregation: str) -> None: columns={"source": True, "system_tags": True} ) tags = [n for n in ("g", "k") if n in system.column_names] - assert ArrowTableStream(system, tag_columns=tags).as_table().num_rows > 0 + assert ( + ArrowTableStream._from_derived_table(system, tag_columns=tags) + .as_table() + .num_rows + > 0 + ) def test_an_operator_over_a_valid_stream_keeps_it_valid() -> None: diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 4034b43b6..2f8109ac1 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -145,7 +145,7 @@ make_source, ) from .order_rules import KNOWN_VIOLATIONS, ORDER_EXCEPTIONS -from .sources.test_source_arrow_validation import _Connector +from .sources.test_source_arrow_validation import _Connector, _PostgreSQLConnector from tests.test_databases import fake_spiral_sdk pytestmark = [ @@ -1113,12 +1113,11 @@ def test_database_stream_and_rows_agree_on_tag_data_and_token_fields( ) _assert_stream_and_row_fields(stream, native_async=False) else: - connector = _Connector(raw) # The shared fixture defaults to a different key; use this table's key. if kind is PostgreSQLTableSource: monkeypatch.setattr( "orcapod.core.sources.postgresql_table_source.PostgreSQLConnector", - lambda *args, **kwargs: connector, + lambda dsn: _PostgreSQLConnector(raw, dsn), ) stream = PostgreSQLTableSource( "postgresql://localhost/test", @@ -1129,7 +1128,7 @@ def test_database_stream_and_rows_agree_on_tag_data_and_token_fields( ) else: stream = DBTableSource( - connector, + _Connector(raw), "rows", tag_columns=tags, source_id="rows", diff --git a/tests/test_databases/test_delta_merge_reserved_names.py b/tests/test_databases/test_delta_merge_reserved_names.py index f39b4f42b..9a44ede26 100644 --- a/tests/test_databases/test_delta_merge_reserved_names.py +++ b/tests/test_databases/test_delta_merge_reserved_names.py @@ -16,7 +16,6 @@ from __future__ import annotations -import asyncio from pathlib import Path from typing import cast @@ -24,8 +23,6 @@ import pyarrow as pa import pytest -from orcapod import PipelineJob, function_pod -from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase from orcapod.databases.delta_lake_databases import MERGE_RESERVED_COLUMNS from orcapod.errors import InputValidationError, UnstorableColumnError @@ -118,41 +115,6 @@ def test_a_stored_table_holding_a_reserved_name_takes_no_append( db.flush() # a no-op -@function_pod(output_keys=["__delta_rs_source"]) -def _reserved(v: int) -> int: - return v - - -@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) -def test_a_job_writing_a_reserved_name_stops_at_its_first_write( - tmp_path: Path, use_async: bool -) -> None: - source = ArrowTableSource( - pa.Table.from_arrays( - [pa.array([1, 2], pa.int64()), pa.array([1, 2], pa.int64())], - schema=pa.schema( - [ - pa.field("k", pa.int64(), nullable=False), - pa.field("v", pa.int64(), nullable=False), - ] - ), - ), - tag_columns=["k"], - tag_only_columns=True, - source_id="s", - record_id_columns=["k"], - ) - with pytest.raises(UnstorableColumnError, match="MERGE reserves"): - database = DeltaTableDatabase(tmp_path) - job = PipelineJob(name="itl1377", database=database) - with job: - _reserved.pod(source, label="fn") - if use_async: - asyncio.run(job.run_async()) - else: - job.run() - - def test_a_nested_field_with_a_reserved_name_is_kept(tmp_path: Path) -> None: """Only a top-level column collides with the planner's columns.""" db = DeltaTableDatabase(tmp_path) diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index 20be2e211..b4b48ab4b 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -1003,7 +1003,6 @@ def schema_source_stream_builder() -> dict[str, Any]: out[f"{variant}.schema_hash"] = result.schema_hash out[f"{variant}.table_hash"] = result.table_hash.to_string() out[f"{variant}.source_id"] = result.source_id - out[f"{variant}.system_tag_columns"] = list(result.system_tag_columns) out.update(_prefixed(variant, stream_summary(result.stream))) return out @@ -3505,20 +3504,16 @@ def pipeline_tagless_producerless_stream() -> dict[str, Any]: def table(record_ids: list[str], xs: list[int]) -> pa.Table: return pa.table( [pa.array(record_ids, pa.string()), pa.array(xs, pa.int64())], - names=["record_id", "x"], + names=["_tag_record_id", "x"], ) rows = table(["b", "c", "a"], [1, 2, 3]) reordered = table(["c", "a", "b"], [2, 3, 1]) return { - "as_given": ArrowTableStream( - rows, tag_columns=[], system_tag_columns=["record_id"] - ) + "as_given": ArrowTableStream._from_derived_table(rows) .content_hash() .to_string(), - "reordered": ArrowTableStream( - reordered, tag_columns=[], system_tag_columns=["record_id"] - ) + "reordered": ArrowTableStream._from_derived_table(reordered) .content_hash() .to_string(), } diff --git a/tests/test_hashing/test_hash_label_rule.py b/tests/test_hashing/test_hash_label_rule.py index 0a7ed9e04..b92922844 100644 --- a/tests/test_hashing/test_hash_label_rule.py +++ b/tests/test_hashing/test_hash_label_rule.py @@ -760,20 +760,20 @@ def _bare_stream( context_key: str | None = None, ) -> ArrowTableStream: """Build a one-row stream with no producer; each argument sets one value.""" - names = ["id", "x", "__note", "_tag_origin"] + names = ["id", "x", "__note", "_tag_origin", "_source_x"] arrays: list[pa.Array[Any]] = [ pa.array([tag], pa.large_string()), pa.array([data], pa.int64()), pa.array([meta], pa.large_string()), pa.array([system_tag], pa.large_string()), + pa.array([source_info], pa.large_string()), ] if context_key is not None: names.append("_context_key") arrays.append(pa.array([context_key], pa.large_string())) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( pa.Table.from_arrays(arrays, names=names), tag_columns=["id"], - source_info={"x": source_info}, ) diff --git a/tests/test_hashing/test_wrong_hash_findings.py b/tests/test_hashing/test_wrong_hash_findings.py index 645dda42b..c6a20d645 100644 --- a/tests/test_hashing/test_wrong_hash_findings.py +++ b/tests/test_hashing/test_wrong_hash_findings.py @@ -79,7 +79,7 @@ def _stream_with_source_ids(source_ids: list[str | None]) -> ArrowTableStream: ), } ) - return ArrowTableStream(table, tag_columns=["g", "k"]) + return ArrowTableStream._from_derived_table(table, tag_columns=["g", "k"]) def _folded_source_id(stream: Any) -> str: diff --git a/tests/test_pipeline/test_aggregation_job.py b/tests/test_pipeline/test_aggregation_job.py index d8a073c74..287432db9 100644 --- a/tests/test_pipeline/test_aggregation_job.py +++ b/tests/test_pipeline/test_aggregation_job.py @@ -241,7 +241,7 @@ def unary_static_process(self, stream): pa.field(column, list_type, nullable=False), pa.array(values, type=list_type), ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=self.by, data_context=grouped.data_context, # pyright: ignore[reportAttributeAccessIssue] # not on StreamProtocol, as in GroupBy itself (ITL-844) diff --git a/tests/test_pipeline/test_bind_keeps_node_schemas.py b/tests/test_pipeline/test_bind_keeps_node_schemas.py index d8c2ece12..36ffda5c0 100644 --- a/tests/test_pipeline/test_bind_keeps_node_schemas.py +++ b/tests/test_pipeline/test_bind_keeps_node_schemas.py @@ -75,7 +75,7 @@ def _record_id_first(source: ArrowTableSource) -> ArrowTableStream: assert len(pair) == 2 and constants.SYSTEM_TAG_SOURCE_ID_PREFIX in pair[0] swap = {pair[0]: pair[1], pair[1]: pair[0]} reordered = table.select([swap.get(name, name) for name in names]) - return ArrowTableStream(reordered, tag_columns=["id"]) + return ArrowTableStream._from_derived_table(reordered, tag_columns=["id"]) NODES = ("src", "renamed", "inc") diff --git a/tests/test_pipeline/test_bind_narrower_source.py b/tests/test_pipeline/test_bind_narrower_source.py index 9fe55a257..14bc4c427 100644 --- a/tests/test_pipeline/test_bind_narrower_source.py +++ b/tests/test_pipeline/test_bind_narrower_source.py @@ -1041,7 +1041,7 @@ def _stream_with_system_tags(columns: dict[str, pa.Array[Any]]) -> ArrowTableStr ] ), ) - return ArrowTableStream(table, tag_columns=["id"]) + return ArrowTableStream._from_derived_table(table, tag_columns=["id"]) SOURCE_ID = "_tag_source_id::abc" diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py index 89b6d9a06..1c73eb64d 100644 --- a/tests/test_pipeline/test_delta_refusals_in_jobs.py +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -49,7 +49,7 @@ def unary_static_process(self, stream: Any) -> Any: shape = pa.large_list(pa.field("item", pa.uint8(), nullable=nullable)) wrapped = pa.array([[v] for v in values], shape) table = table.set_column(table.schema.get_field_index("v"), "v", wrapped) - return ArrowTableStream(table, tag_columns=stream.keys()[0]) + return ArrowTableStream._from_derived_table(table, tag_columns=stream.keys()[0]) def _source(keys: list[int], values: list[int]) -> ArrowTableSource: @@ -146,7 +146,7 @@ def test_annotated_list_reaches_delta_operator_log( infer_nullable=True, ) table = source.as_table(columns={"source": True, "system_tags": True}) - stream = ArrowTableStream( + stream = ArrowTableStream._from_derived_table( table.append_column(pa.field("extra", extra.type, nullable=False), extra), tag_columns=["k"], ) diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index 02813d6a0..9b9959b55 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -194,7 +194,7 @@ def test_a_value_the_held_rows_do_not_hold_is_refused() -> None: changed = table.set_column( table.schema.get_field_index("x"), "x", pa.array([101, 104], pa.int64()) ) - vars(source)["_stream"] = ArrowTableStream( + vars(source)["_stream"] = ArrowTableStream._from_derived_table( changed, tag_columns=["k", "g"], data_context=stream.data_context ) with pytest.raises(ProvenanceInconsistencyError): @@ -432,7 +432,7 @@ def test_a_function_reading_a_source_refuses_a_changed_snapshot() -> None: changed = table.set_column( table.schema.get_field_index("x"), "x", pa.array([101], pa.int64()) ) - vars(source)["_stream"] = ArrowTableStream( + vars(source)["_stream"] = ArrowTableStream._from_derived_table( changed, tag_columns=["k", "g"], data_context=stream.data_context ) with pytest.raises(ProvenanceInconsistencyError, match="not the input"): @@ -1200,7 +1200,7 @@ def test_a_held_token_that_contradicts_the_mapping_raises() -> None: "_source_x", pa.array(["s::row_0::y"], pa.large_string()), ) - vars(node)["_cached_output_stream"] = ArrowTableStream( + vars(node)["_cached_output_stream"] = ArrowTableStream._from_derived_table( changed, tag_columns=["k", "g"] ) with pytest.raises(ProvenanceInconsistencyError, match="another column"): @@ -1358,7 +1358,7 @@ def test_a_selection_token_that_contradicts_the_operator_raises( table.schema.field(at), pa.array(["a::row_0::y[0]"], table.schema.field(at).type), ) - vars(node)["_cached_output_stream"] = ArrowTableStream( + vars(node)["_cached_output_stream"] = ArrowTableStream._from_derived_table( changed, tag_columns=["k", "i"], data_context=held.data_context ) with pytest.raises(ProvenanceInconsistencyError): @@ -1595,7 +1595,7 @@ def test_a_merged_key_token_is_verified() -> None: table.schema.field(at), pa.array(["a::row_0::k"], table.schema.field(at).type), ) - vars(node)["_cached_output_stream"] = ArrowTableStream( + vars(node)["_cached_output_stream"] = ArrowTableStream._from_derived_table( changed, tag_columns=["k", "i"], data_tags=["k", "i"], @@ -2704,7 +2704,7 @@ def feed(name: str, rid: int, value: int) -> DictSource: a, b = feed("tenant:a", 1, 10), feed("tenant:b", 2, 20) tables = [s.as_table(columns={"source": True, "system_tags": True}) for s in (a, b)] - mixed = ArrowTableStream( + mixed = ArrowTableStream._from_derived_table( pa.concat_tables(tables), tag_columns=["rid"], label="mixed" ) store = DeltaTableDatabase(tmp_path / "db") @@ -2758,7 +2758,7 @@ def feed(name: str, rid: int, value: int) -> DictSource: a, b = feed("tenant:a", 1, 10), feed("tenant:b", 2, 20) slot = a.source_id if overlap else "slot" tables = [s.as_table(columns={"source": True, "system_tags": True}) for s in (a, b)] - mixed = ArrowTableStream( + mixed = ArrowTableStream._from_derived_table( pa.concat_tables(tables), tag_columns=["rid"], label="mixed" ) store = DeltaTableDatabase(tmp_path / "db") @@ -2892,7 +2892,11 @@ def test_repeated_identical_inputs_before_a_batch_never_trace_wrongly( label="f", ) ) - job.bind(sources={"slot": ArrowTableStream(repeated, tag_columns=["k"])}) + job.bind( + sources={ + "slot": ArrowTableStream._from_derived_table(repeated, tag_columns=["k"]) + } + ) run(job, mode) batches = job.nodes["Batch"].as_table().to_pylist() assert sorted(k for b in batches for k in b["k"]) == sorted(order) @@ -3110,7 +3114,7 @@ def test_a_folded_list_needs_one_element_per_member() -> None: longer = pa.array( [v + [0.5] for v in table.column(at).to_pylist()], table.schema.field(at).type ) - vars(node)["_cached_output_stream"] = ArrowTableStream( + vars(node)["_cached_output_stream"] = ArrowTableStream._from_derived_table( table.set_column(at, table.schema.field(at), longer), tag_columns=["animal"], data_context=held.data_context, diff --git a/tests/test_pipeline/test_review_findings_510.py b/tests/test_pipeline/test_review_findings_510.py index 19cd7e3ac..a311f2b32 100644 --- a/tests/test_pipeline/test_review_findings_510.py +++ b/tests/test_pipeline/test_review_findings_510.py @@ -184,8 +184,8 @@ def keys(self, **kwargs: Any) -> Any: def _with_system_tag(column: pa.Array[Any]) -> ArrowTableStream: - table = pa.table({"k": [1, 2], "x": [10, 20], "e": column}) - return ArrowTableStream(table, tag_columns=["k"], system_tag_columns=["e"]) + table = pa.table({"k": [1, 2], "x": [10, 20], "_tag_e": column}) + return ArrowTableStream._from_derived_table(table, tag_columns=["k"]) @pytest.mark.parametrize( diff --git a/tests/test_pipeline/test_row_ids_review_2.py b/tests/test_pipeline/test_row_ids_review_2.py index 575cea501..5fefc8f00 100644 --- a/tests/test_pipeline/test_row_ids_review_2.py +++ b/tests/test_pipeline/test_row_ids_review_2.py @@ -251,7 +251,13 @@ def seed() -> DictSource: job = PipelineJob(name="scope", database=database) with job: add.pod(seed(), label="f") - job.bind(sources={"slot": ArrowTableStream(table, tag_columns=["k", "j"])}) + job.bind( + sources={ + "slot": ArrowTableStream._from_derived_table( + table, tag_columns=["k", "j"] + ) + } + ) _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) jobs[session] = job assert calls["add"] == 4 @@ -805,7 +811,9 @@ def _data_tag_stream(tags: tuple[str, ...]) -> ArrowTableStream: [pa.field(n, columns[n][1], nullable=columns[n][2]) for n in names] ), ) - return ArrowTableStream(table, tag_columns=list(tags), data_tags=["d", "e"]) + return ArrowTableStream._from_derived_table( + table, tag_columns=list(tags), data_tags=["d", "e"] + ) def _two_nodes_on( diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index bf26da772..169991d5d 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -129,7 +129,7 @@ def test_a_narrower_raw_bind_keeps_the_slots_system_tag_order() -> None: record_id = next(n for n in table.column_names if "record_id" in n) others = [n for n in table.column_names if n not in (source_id, record_id)] reversed_pair = table.select([*others, record_id, source_id]) - raw = ArrowTableStream(reversed_pair, tag_columns=["k"]) + raw = ArrowTableStream._from_derived_table(reversed_pair, tag_columns=["k"]) database = InMemoryArrowDatabase() job = PipelineJob(name="reversed_pair", database=database) @@ -335,7 +335,10 @@ def test_a_bound_tap_stream_delivers_every_row_as_main_does() -> None: [ pytest.param(lambda: _plain().select_data_columns(["x"]), id="operator"), pytest.param( - lambda: ArrowTableStream(_source_table(), tag_columns=["k"]), id="raw" + lambda: ArrowTableStream._from_derived_table( + _source_table(), tag_columns=["k"] + ), + id="raw", ), ], ) @@ -553,7 +556,7 @@ def unary_static_process(self, stream: Any) -> Any: plain = [n for n in names if not n.startswith("_source_")] source = ["_source_y", "_source_x"] rest = [n for n in names if n.startswith("_source_") and n not in source] - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table.select([*plain, "y", "x", *source, *rest]), tag_columns=["k"] ) @@ -601,7 +604,7 @@ def _stream(self) -> Any: @_stream.setter def _stream(self, base: Any) -> None: - self.saved_stream = _FilteringStream( + self.saved_stream = _FilteringStream._from_derived_table( base.as_table(columns={"source": True, "system_tags": True}), tag_columns=["k"], ) @@ -670,7 +673,7 @@ def _swapped(stream: Any, first: str, second: str, tags: list[str]) -> Any: names = list(table.column_names) a, b = names.index(first), names.index(second) names[a], names[b] = names[b], names[a] - return ArrowTableStream(table.select(names), tag_columns=tags) + return ArrowTableStream._from_derived_table(table.select(names), tag_columns=tags) @pytest.mark.parametrize("replay", [False, True], ids=["log", "replay"]) @@ -740,7 +743,7 @@ def test_a_result_of_another_stream_kind_takes_mains_row_path() -> None: class Filtering(SelectDataColumns): def unary_static_process(self, stream: Any) -> Any: table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) - return _FilteringStream(table, tag_columns=["k"]) + return _FilteringStream._from_derived_table(table, tag_columns=["k"]) database = InMemoryArrowDatabase() job = PipelineJob(name="other_kind", database=database) @@ -921,7 +924,7 @@ def unary_static_process(self, stream: Any) -> Any: f"{constants.SYSTEM_TAG_PREFIX}region", pa.array(values[: table.num_rows], pa.large_string()), ) - return kind(table, tag_columns=["k"]) + return kind._from_derived_table(table, tag_columns=["k"]) return AddSystemTag(["x"]) @@ -968,26 +971,28 @@ def test_a_nullable_raw_system_tag_is_stored_with_its_declared_field() -> None: ) -def test_a_source_refuses_a_non_text_custom_system_tag() -> None: - """Source-built system tags must be non-nullable text.""" +def test_a_source_refuses_a_prefixed_system_tag() -> None: + """Public tables reserve the system-tag prefix for Orcapod.""" from orcapod.core.streams.base import system_tags_as_rows_give schema = pa.schema( [ pa.field("k", pa.int64(), nullable=False), pa.field("x", pa.int64(), nullable=False), - pa.field("region", pa.int16(), nullable=False), + pa.field("_tag_region", pa.int16(), nullable=False), ] ) - with pytest.raises(InputValidationError, match=r"'region'.*non-nullable string"): + with pytest.raises(InputValidationError, match=r"'_tag_region'.*reserved"): ArrowTableSource( pa.Table.from_pylist( - [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], + [ + {"k": 1, "x": 10, "_tag_region": 1}, + {"k": 2, "x": 20, "_tag_region": 2}, + ], schema=schema, ), tag_columns=["k"], tag_only_columns=True, - system_tag_columns=["region"], source_id="s", ) stock = _plain() @@ -1073,7 +1078,7 @@ def unary_static_process(self, stream: Any) -> Any: if route == "eager": return out table = out.as_table(columns={"source": True, "system_tags": True}) - return Unproven(table, tag_columns=["k"]) + return Unproven._from_derived_table(table, tag_columns=["k"]) table = pa.table({"k": [1, 2], "x": [10, 20], "y": [1, 2]}) upstream = Undated(table, tag_columns=["k"]) @@ -1107,7 +1112,7 @@ def test_a_lazy_output_describes_itself_without_converting_python_types( source = ArrowTableSource( base, tag_columns=["k"], tag_only_columns=True, source_id="s" ) - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( source.as_table(columns={"source": True, "system_tags": True}), tag_columns=["k"], ) @@ -1191,7 +1196,7 @@ def unary_static_process(self, stream: Any) -> Any: table = out.as_table(columns={"source": True, "system_tags": True}) field = pa.field(name, pa.large_string(), nullable=False, metadata=metadata) table = table.append_column(field, pa.array(values, pa.large_string())) - return ArrowTableStream(table, tag_columns=["k"]) + return ArrowTableStream._from_derived_table(table, tag_columns=["k"]) database = InMemoryArrowDatabase() job = PipelineJob(name="system_tag_kinds", database=database) diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 24cf7221f..fe6a56809 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -297,6 +297,17 @@ def test_load_shares_repeated_configs_written_by_main( assert job.nodes["b"].as_table().to_pylist() == ROWS +def test_load_refuses_a_saved_custom_system_tag(tmp_path: Path) -> None: + fixture = Path(__file__).with_name("fixtures") / "itl_1469_main_shared_source.json" + saved = json.loads(fixture.read_text()) + saved["bindings"]["sources"]["b"]["system_tag_columns"] = ["revision"] + path = tmp_path / "custom-tags.json" + path.write_text(json.dumps(saved)) + + with pytest.raises(ValueError, match="system_tag_columns.*revision"): + PipelineJob.load(path) + + def test_itl_1554_loading_shared_slots_feeding_the_same_pod(tmp_path: Path) -> None: """Record the existing read-only DAG failure for this shared-source topology.""" db = InMemoryArrowDatabase() diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index 35a229ed5..511e283a0 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -574,7 +574,7 @@ def test_a_source_info_depth_is_the_declared_one_in_the_description_and_the_rows ).as_table(columns={"source": True, "system_tags": True}) position = table.schema.get_field_index("_source_x") strings = pa.large_list(pa.large_string()) - raw = ArrowTableStream( + raw = ArrowTableStream._from_derived_table( table.set_column( position, pa.field("_source_x", strings, nullable=True), diff --git a/tests/test_pipeline/test_token_types_end_to_end.py b/tests/test_pipeline/test_token_types_end_to_end.py index 6e6edcc74..cb3cf3488 100644 --- a/tests/test_pipeline/test_token_types_end_to_end.py +++ b/tests/test_pipeline/test_token_types_end_to_end.py @@ -146,7 +146,9 @@ def _with_tokens( table = source.as_table(columns={"source": True, "system_tags": True}) for name, (values, kind) in tokens.items(): table = with_token_column(table, name, values, kind) - return ArrowTableStream(table, tag_columns=list(ARRANGEMENTS[arrangement][0])) + return ArrowTableStream._from_derived_table( + table, tag_columns=list(ARRANGEMENTS[arrangement][0]) + ) def _counting(name: str, x: Any, w: Any) -> Any: @@ -635,7 +637,9 @@ def _data_tag_stream(tags: tuple[str, ...]) -> ArrowTableStream: pa.field(column, kind, nullable=True), pa.array(values, kind), ) - return ArrowTableStream(table, tag_columns=list(tags), data_tags=list(tags)) + return ArrowTableStream._from_derived_table( + table, tag_columns=list(tags), data_tags=list(tags) + ) def _data_tag_job( diff --git a/tests/test_pipeline/test_token_types_review_1.py b/tests/test_pipeline/test_token_types_review_1.py index 04185512a..3110f18d7 100644 --- a/tests/test_pipeline/test_token_types_review_1.py +++ b/tests/test_pipeline/test_token_types_review_1.py @@ -145,7 +145,7 @@ def _with_tokens( pa.field(column, kind, nullable=True), pa.array(values, kind), ) - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table, tag_columns=list(tags), data_tags=list(tags) if data_tags else [] ) @@ -589,7 +589,9 @@ def test_the_whole_table_form_drops_a_token_fields_own_metadata(tags: str) -> No table.schema.field(index).with_metadata({"top": "level"}), table.column(index), ) - marked = ArrowTableStream(table, tag_columns=list(order), data_tags=list(order)) + marked = ArrowTableStream._from_derived_table( + table, tag_columns=list(order), data_tags=list(order) + ) built, _, _ = StaticOutputOperatorPod._rows_to_table(list(marked.iter_data())) # pyright: ignore[reportPrivateUsage] # the rows' form assert table.schema.field("_source_x").metadata == {b"top": b"level"} formed = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # the whole-table form diff --git a/tests/test_pipeline/test_token_types_review_2.py b/tests/test_pipeline/test_token_types_review_2.py index 33644e872..288c25fdf 100644 --- a/tests/test_pipeline/test_token_types_review_2.py +++ b/tests/test_pipeline/test_token_types_review_2.py @@ -237,7 +237,7 @@ def bound(name: str, data: tuple[str, str]) -> ArrowTableStream: columns={"source": True, "system_tags": True} ) if name == empty: - return ArrowTableStream( + return ArrowTableStream._from_derived_table( table.slice(0, 0), tag_columns=list(order), data_tags=list(order) ) table = table.set_column( @@ -245,7 +245,9 @@ def bound(name: str, data: tuple[str, str]) -> ArrowTableStream: pa.field("_source_k", TOKENS), pa.array([["p"], ["q"]], TOKENS), ) - return ArrowTableStream(table, tag_columns=list(order), data_tags=list(order)) + return ArrowTableStream._from_derived_table( + table, tag_columns=list(order), data_tags=list(order) + ) for orchestrator in ORCHESTRATORS.values(): job = PipelineJob(name="empty_input", database=InMemoryArrowDatabase())