From 0ced6b134de18b11d2399e54e7e583ad69b9fd8f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 11:28:36 -0800 Subject: [PATCH 01/13] refactor(sources)!: reserve system tags for Orcapod --- .zed/rules | 23 +- CLAUDE.md | 21 +- changelog.d/ITL-1751.md | 7 + docs/concepts/sources.md | 6 +- docs/dev/design_issues/ITL-1751-AS5.md | 14 + src/orcapod/core/nodes/function_node.py | 11 +- src/orcapod/core/nodes/operator_node.py | 19 +- src/orcapod/core/nodes/source_node.py | 15 +- src/orcapod/core/operators/add_tags.py | 4 +- src/orcapod/core/operators/batch.py | 4 +- .../core/operators/column_selection.py | 16 +- src/orcapod/core/operators/drop_nulls.py | 8 +- src/orcapod/core/operators/filter.py | 4 +- src/orcapod/core/operators/filters.py | 6 +- src/orcapod/core/operators/group_by.py | 6 +- src/orcapod/core/operators/index.py | 12 +- src/orcapod/core/operators/join.py | 32 +- src/orcapod/core/operators/mappers.py | 12 +- src/orcapod/core/operators/merge_join.py | 4 +- src/orcapod/core/operators/meta_columns.py | 4 +- src/orcapod/core/operators/pick.py | 12 +- src/orcapod/core/operators/rejoin.py | 4 +- src/orcapod/core/operators/semijoin.py | 10 +- .../core/operators/static_output_pod.py | 51 +- src/orcapod/core/operators/tag_by.py | 6 +- .../core/sources/arrow_table_source.py | 14 +- src/orcapod/core/sources/base.py | 16 +- src/orcapod/core/sources/cached_source.py | 4 +- src/orcapod/core/sources/csv_source.py | 38 +- src/orcapod/core/sources/data_frame_source.py | 49 +- src/orcapod/core/sources/db_table_source.py | 36 +- .../core/sources/delta_table_source.py | 28 +- src/orcapod/core/sources/derived_source.py | 19 +- src/orcapod/core/sources/dict_source.py | 25 +- src/orcapod/core/sources/polling_source.py | 11 +- .../core/sources/postgresql_table_source.py | 8 +- .../core/sources/spiraldb_table_source.py | 45 +- .../core/sources/sqlite_table_source.py | 10 +- src/orcapod/core/sources/stream_builder.py | 187 +------ .../core/streams/arrow_table_stream.py | 159 ++---- src/orcapod/core/streams/base.py | 4 +- src/orcapod/utils/schema_utils.py | 26 +- .../test_record_batch_channels.py | 8 +- .../data_tags/test_operator_node_storage.py | 2 +- .../function_pod/test_function_pod_node.py | 6 +- .../operators/test_aggregated_list_types.py | 2 +- .../operators/test_async_sync_equivalence.py | 50 +- .../test_barrier_keeps_data_context.py | 9 +- .../operators/test_description_system_tags.py | 2 +- tests/test_core/operators/test_group_by.py | 2 +- .../operators/test_held_context_keys.py | 2 +- .../operators/test_merge_join_arrow_types.py | 6 +- .../operators/test_record_batch_execution.py | 12 +- tests/test_core/operators/test_rejoin.py | 47 +- .../operators/test_row_built_form.py | 8 +- .../operators/test_streaming_joins.py | 14 +- .../operators/test_streaming_rejoin.py | 25 +- .../test_core/sources/test_db_table_source.py | 60 -- .../test_dictionary_columns_refused.py | 22 +- .../sources/test_keyed_default_source_id.py | 3 +- .../sources/test_source_arrow_validation.py | 522 ++++-------------- .../sources/test_source_check_for_new_data.py | 22 +- .../sources/test_sources_comprehensive.py | 12 +- tests/test_core/streams/test_head_sorting.py | 4 +- .../streams/test_identity_order_regression.py | 7 +- .../streams/test_iter_data_chunk_layouts.py | 2 +- .../streams/test_raw_stream_tag_order.py | 29 +- .../streams/test_system_tag_validation.py | 110 ++-- tests/test_core/streams/test_token_shape.py | 7 +- tests/test_hashing/golden/cases.py | 11 +- tests/test_hashing/test_hash_label_rule.py | 6 +- tests/test_pipeline/test_aggregation_job.py | 2 +- .../test_bind_keeps_node_schemas.py | 2 +- .../test_bind_narrower_source.py | 2 +- .../test_delta_refusals_in_jobs.py | 4 +- tests/test_pipeline/test_provenance_review.py | 22 +- .../test_pipeline/test_review_findings_510.py | 4 +- tests/test_pipeline/test_row_ids_review_2.py | 12 +- tests/test_pipeline/test_rows_on_read.py | 22 +- .../test_stream_transport_equivalence.py | 2 +- .../test_token_types_end_to_end.py | 8 +- .../test_token_types_review_1.py | 2 +- .../test_token_types_review_2.py | 6 +- 83 files changed, 700 insertions(+), 1390 deletions(-) create mode 100644 changelog.d/ITL-1751.md create mode 100644 docs/dev/design_issues/ITL-1751-AS5.md diff --git a/.zed/rules b/.zed/rules index 1ebebefc1..55c523dde 100644 --- a/.zed/rules +++ b/.zed/rules @@ -995,7 +995,7 @@ of its identity (GroupBy's member_order), never the input's column order. __ prefix — System metadata (ColumnConfig meta) _source_ prefix — Source info provenance (ColumnConfig source) - _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. @@ -1504,19 +1504,14 @@ 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. 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 1304ed83d..e3fb75493 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1552,19 +1552,14 @@ 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. 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..7b4de29d2 --- /dev/null +++ b/changelog.d/ITL-1751.md @@ -0,0 +1,7 @@ +### 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. 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..5904c7501 --- /dev/null +++ b/docs/dev/design_issues/ITL-1751-AS5.md @@ -0,0 +1,14 @@ +## `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. Source configs +omit the removed setting and refuse a saved non-empty list. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3931aab3c..61476a19a 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, @@ -621,11 +618,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( @@ -4114,7 +4111,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 5cce26591..603c84592 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -51,10 +51,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, @@ -483,7 +480,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), @@ -516,11 +513,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( @@ -1329,7 +1326,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(), @@ -1825,8 +1822,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): @@ -2225,7 +2222,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), @@ -2426,8 +2423,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 2e1ec9911..e0abc3525 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -33,10 +33,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, @@ -74,18 +71,18 @@ ) if TYPE_CHECKING: - from orcapod.pipeline.job import PipelineJob - from orcapod.types.explanation import Explanation from orcapod.channels import WritableChannel + from orcapod.pipeline.job import PipelineJob from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, ) - from orcapod.protocols.observability_protocols import ExecutionObserverProtocol from orcapod.protocols.hashing_protocols import ( IdentityWalkProtocol, SemanticHasherProtocol, ) + from orcapod.protocols.observability_protocols import ExecutionObserverProtocol + from orcapod.types.explanation import Explanation logger = logging.getLogger(__name__) @@ -1407,12 +1404,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 @@ -1942,7 +1939,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 925891d76..5230a1b52 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 @@ -330,7 +330,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..fdfebc0af 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__) @@ -471,7 +471,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: else: output_schema = input_schema.append(element_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized output_schema = output_schema.append(token_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized - return 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 870b75784..af6a3c74b 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, @@ -795,13 +792,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 ) @@ -1855,21 +1851,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..bf3a55800 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__) @@ -428,7 +428,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: else: output_schema = input_schema.append(value_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized output_schema = output_schema.append(token_field) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized - return 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 dcfa2a89f..4be3781fe 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -56,7 +56,6 @@ ) from orcapod.core.streams.arrow_table_stream import ( ArrowTableStream, - stream_from_derived_table, ) from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -487,7 +486,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), @@ -510,7 +509,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), @@ -713,7 +712,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), @@ -762,7 +761,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 ) @@ -871,18 +870,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, @@ -938,13 +937,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 @@ -1702,33 +1701,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.""" @@ -1885,19 +1860,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..f8f1ce75b 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -274,6 +274,16 @@ def _source_id_config(self) -> dict[str, Any]: "source_version": self.SOURCE_VERSION, } + @staticmethod + def _require_no_saved_system_tags(config: dict[str, Any]) -> None: + """Refuse saved configurations that nominated custom system tags.""" + 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." + ) + @classmethod def _from_saved_name( cls, config: dict[str, Any], build: Callable[[str | None], _SourceT] @@ -306,7 +316,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 +327,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 5be483a96..f7974460c 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 ( @@ -755,7 +755,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 9492bc553..1217c7bf3 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, +) if TYPE_CHECKING: from polars._typing import FrameInitTypes @@ -59,7 +58,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, *, @@ -71,19 +69,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( @@ -93,15 +80,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" @@ -125,14 +107,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: @@ -140,14 +118,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 () @@ -160,7 +133,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, ) @@ -189,6 +161,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 d81050918..586030028 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), @@ -342,6 +333,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 7343f5798..6d9d4a0f8 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 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 @@ -756,6 +755,8 @@ 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_system_columns(table) 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. @@ -972,7 +973,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 51317377b..3cb0c105c 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 @@ -55,7 +57,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, *, @@ -84,11 +85,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 = self.data_context.type_converter.python_dicts_to_arrow_table( rows, arrow_schema=data_schema, @@ -99,9 +109,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. @@ -119,7 +126,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 @@ -148,6 +154,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/polling_source.py b/src/orcapod/core/sources/polling_source.py index 21331350c..58bdbe483 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.utils.schema_utils import ( _normalize_column_list, @@ -62,7 +62,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 @@ -336,6 +335,7 @@ def __init__( self._declared_arrow: pa.Schema | None = None unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): + schema_utils.require_names_not_system_tags(unified_schema.names) require_supported_nullable_types(unified_schema) require_live_logical_types(unified_schema) # Canonicalize the declaration for comparison to batch schemas (ITL-640). @@ -589,7 +589,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) @@ -935,6 +935,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. @@ -1124,7 +1125,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 58acc1f17..68a255453 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, @@ -300,7 +297,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/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 7dc4afb68..f7d7843ff 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -1812,12 +1812,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 d9d70fba5..2639d26e0 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -804,6 +804,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" ) @@ -1021,7 +1034,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``. @@ -1034,8 +1046,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 @@ -1048,7 +1058,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 ] @@ -1073,7 +1083,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 @@ -1082,7 +1091,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.SOURCE_PREFIX): return "source-info" @@ -1181,7 +1190,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. @@ -1191,8 +1199,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 @@ -1204,7 +1210,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 ] diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 2be341b87..40c608a45 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) @@ -2406,7 +2408,9 @@ def test_channel_keeps_first_system_tag_declaration_and_entry_id() -> None: 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) + 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_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/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..e8b1e9faa 100644 --- a/tests/test_core/operators/test_aggregated_list_types.py +++ b/tests/test_core/operators/test_aggregated_list_types.py @@ -228,7 +228,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 ae37dd608..4fcec79c5 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 @@ -1308,7 +1314,7 @@ def _tied_declaration_inputs(arity: int, variant: str) -> list[StreamProtocol]: 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] @@ -1318,18 +1324,24 @@ 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}) + table = table.drop_columns(["_source_rev"]).rename_columns( + ["_tag_rev" if name == "rev" else name for name in table.column_names] + ) + 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 = { @@ -1364,7 +1376,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 @@ -1496,7 +1512,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) @@ -1513,7 +1531,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], @@ -1589,7 +1607,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) @@ -2044,7 +2062,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]: @@ -3071,7 +3091,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_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..f65aea359 100644 --- a/tests/test_core/operators/test_held_context_keys.py +++ b/tests/test_core/operators/test_held_context_keys.py @@ -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_merge_join_arrow_types.py b/tests/test_core/operators/test_merge_join_arrow_types.py index 7c2cbe7f8..f1ca2067f 100644 --- a/tests/test_core/operators/test_merge_join_arrow_types.py +++ b/tests/test_core/operators/test_merge_join_arrow_types.py @@ -825,7 +825,11 @@ def _relayout( 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..0a0c79f7b 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"] ) @@ -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_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_db_table_source.py b/tests/test_core/sources/test_db_table_source.py index 3c96c2b42..051fc35dc 100644 --- a/tests/test_core/sources/test_db_table_source.py +++ b/tests/test_core/sources/test_db_table_source.py @@ -523,29 +523,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): @@ -581,40 +558,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 077303fc4..493fe7629 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, @@ -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): @@ -123,30 +121,33 @@ 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, +) -> RootSource: """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 +155,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 +169,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 +177,18 @@ 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) + return SpiralDBTableSource("project", "rows", **options, **kwargs) connector = _Connector(table) if kind == "postgres": monkeypatch.setattr( "orcapod.core.sources.postgresql_table_source.PostgreSQLConnector", lambda *args, **kwargs: connector, ) - return PostgreSQLTableSource("postgresql://localhost/test", "rows", **options) + return PostgreSQLTableSource( + "postgresql://localhost/test", "rows", **options, **kwargs + ) assert kind == "db" - return DBTableSource(connector, "rows", **options) + return DBTableSource(connector, "rows", **options, **kwargs) def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: @@ -270,6 +273,74 @@ 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"]) +@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"] = [] + 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 +558,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_keeps_its_existing_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 metadata-free source's hashes at 969ed093. - assert actual == [ - ( - "00000266ff2e58dd5c1cb957ac9ff249ae13e17918a263847f8e2f65d756f746b3f561", - "000002e9be964a36d499b5a1efe697c53d9b7e2e0103b79be7b0e2d489c1be8f7b8636", - "00000279f295215ecb6c92fc49cf4ec41df41327a43c3b351f0baac467b4f45a0f33d2", - ), - ( - "0000029689a4a738cf93bbcfde75085dc43bac31570b0b368eff34b0f3d0fa427769c1", - "000002b6b64a14a2bb8cc662759a15839f8e4e730c89a03230bb8cac2f951fbe8f2002", - "000002fb3fc3affffe0e390dcfb5695db61b332eb2d38f83c2cfab5570c8a956371e18", - ), - ] - - -@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 +585,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: @@ -1075,13 +1005,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 +1036,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 +1079,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 +1099,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 +1113,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 +1132,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 +1257,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 +1304,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( @@ -1601,31 +1311,3 @@ def test_dataframe_source_preserves_declared_arrow_data_field() -> None: ) source = DataFrameSource(table, source_id="declared") 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("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"]) 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_sources_comprehensive.py b/tests/test_core/sources/test_sources_comprehensive.py index ab21a4661..387ebd390 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__ """ @@ -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/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..f296e25b3 100644 --- a/tests/test_core/streams/test_system_tag_validation.py +++ b/tests/test_core/streams/test_system_tag_validation.py @@ -11,13 +11,25 @@ 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: + kwargs = {"system_tag_columns": ["tag"]} + with pytest.raises(TypeError, match="system_tag_columns"): + ArrowTableStream(pa.table({"data": [1, 2], "tag": ["a", "b"]}), **kwargs) + + @pytest.mark.parametrize( ("dtype", "values", "nullable", "message"), [ @@ -26,92 +38,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 +88,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 +104,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 +170,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_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index 04967742a..6ba93dd18 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 @@ -3426,20 +3425,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_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 c22a08ef7..20927cb82 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 ab121b9b9..c82b7727c 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 c98c8f62f..02fab710a 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) @@ -553,7 +553,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"] ) @@ -968,26 +968,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() @@ -1107,7 +1109,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 +1193,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_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 4fa3d00b3..287cbeade 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: @@ -629,7 +631,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 0c1cbc4d9..4c1f705ea 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 [] ) 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()) From 54915fe0b21b7dccd592036d8a21f29a7f68c5b5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 11:33:22 -0800 Subject: [PATCH 02/13] test(streams): migrate provenance fixtures and retain pinned values --- test-specification/unit/test_stream.py | 46 +++++++------------ .../test_record_batch_channels.py | 4 +- .../operators/test_async_sync_equivalence.py | 16 +++++-- tests/test_core/operators/test_drop_nulls.py | 2 +- .../operators/test_held_context_keys.py | 4 +- .../operators/test_row_built_form.py | 2 +- .../operators/test_semijoin_nested.py | 4 +- .../sources/test_source_arrow_validation.py | 12 ++++- .../test_source_protocol_conformance.py | 8 ++-- .../sources/test_sources_comprehensive.py | 8 ++-- .../streams/test_system_tag_validation.py | 8 ++-- tests/test_pipeline/test_rows_on_read.py | 15 +++--- 12 files changed, 70 insertions(+), 59 deletions(-) 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 40c608a45..73f95c9b4 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -171,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"] ) @@ -2407,7 +2407,7 @@ 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"]) + stream = _UntypedStream._from_derived_table(table, tag_columns=["k"]) first, second = batches_of( ArrowTableStream._from_derived_table(table, tag_columns=["k"]), rows=1 ) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 4fcec79c5..9d5d06041 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -1309,7 +1309,9 @@ 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 @@ -1334,8 +1336,13 @@ def _tied_declaration_inputs(arity: int, variant: str) -> list[StreamProtocol]: ] for source in sources: table = source.as_table(columns={"system_tags": True, "source": True}) - table = table.drop_columns(["_source_rev"]).rename_columns( - ["_tag_rev" if name == "rev" else name for name in table.column_names] + 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"] @@ -1398,7 +1405,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"])): diff --git a/tests/test_core/operators/test_drop_nulls.py b/tests/test_core/operators/test_drop_nulls.py index 72fe31e41..c1f081bb4 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, diff --git a/tests/test_core/operators/test_held_context_keys.py b/tests/test_core/operators/test_held_context_keys.py index f65aea359..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] ), diff --git a/tests/test_core/operators/test_row_built_form.py b/tests/test_core/operators/test_row_built_form.py index 0a0c79f7b..2579c4732 100644 --- a/tests/test_core/operators/test_row_built_form.py +++ b/tests/test_core/operators/test_row_built_form.py @@ -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"] ) 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/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 493fe7629..7e034a2b6 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -124,7 +124,15 @@ def _source( tags: Collection[str] = TAGS, tag_only_columns: bool | Collection[str] = True, **kwargs: Any, -) -> RootSource: +) -> ( + ArrowTableSource + | DictSource + | DataFrameSource + | CSVSource + | DeltaTableSource + | DBTableSource + | SpiralDBTableSource +): """Build the named source over the same columns using its regular reader.""" options: _SourceOptions = { "tag_columns": tags, @@ -831,7 +839,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}) 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 387ebd390..234807c15 100644 --- a/tests/test_core/sources/test_sources_comprehensive.py +++ b/tests/test_core/sources/test_sources_comprehensive.py @@ -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"]}) diff --git a/tests/test_core/streams/test_system_tag_validation.py b/tests/test_core/streams/test_system_tag_validation.py index f296e25b3..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 @@ -25,9 +25,11 @@ def test_public_stream_refuses_system_tag_names(name: str) -> None: def test_public_stream_has_no_system_tag_columns_argument() -> None: - kwargs = {"system_tag_columns": ["tag"]} + constructor: Any = ArrowTableStream with pytest.raises(TypeError, match="system_tag_columns"): - ArrowTableStream(pa.table({"data": [1, 2], "tag": ["a", "b"]}), **kwargs) + constructor( + pa.table({"data": [1, 2], "tag": ["a", "b"]}), system_tag_columns=["tag"] + ) @pytest.mark.parametrize( diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 02fab710a..cd3695c42 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -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", ), ], ) @@ -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"]) @@ -1075,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"]) From ba5bb06efc423f9a7ed8619d7811f7caac472f2a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 11:37:04 -0800 Subject: [PATCH 03/13] test(sources): verify reserved tags across readers and saved jobs --- src/orcapod/core/sources/derived_source.py | 4 +++- .../test_channels/test_record_batch_channels.py | 14 +++++++------- .../operators/test_aggregated_list_types.py | 4 +++- tests/test_core/operators/test_drop_nulls.py | 2 +- .../operators/test_merge_join_arrow_types.py | 4 +++- .../sources/test_source_arrow_validation.py | 14 ++++++++++---- tests/test_core/sources/test_stream_builder.py | 17 ++++++++++++++++- .../test_source_object_registration.py | 11 +++++++++++ .../test_pipeline/test_token_types_review_1.py | 4 +++- 9 files changed, 57 insertions(+), 17 deletions(-) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 6d9d4a0f8..fb33acfb0 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -756,7 +756,9 @@ def _derive_from( 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_system_columns(table) + 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. diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 73f95c9b4..8715910a0 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -1170,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"] ) ) @@ -1226,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"] ) ) @@ -1639,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 @@ -1662,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"], @@ -2154,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) @@ -2278,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"], @@ -2325,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"], diff --git a/tests/test_core/operators/test_aggregated_list_types.py b/tests/test_core/operators/test_aggregated_list_types.py index e8b1e9faa..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: diff --git a/tests/test_core/operators/test_drop_nulls.py b/tests/test_core/operators/test_drop_nulls.py index c1f081bb4..ebe73129c 100644 --- a/tests/test_core/operators/test_drop_nulls.py +++ b/tests/test_core/operators/test_drop_nulls.py @@ -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_merge_join_arrow_types.py b/tests/test_core/operators/test_merge_join_arrow_types.py index f1ca2067f..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,7 +819,9 @@ 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: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 7e034a2b6..f59005bda 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -334,7 +334,7 @@ def test_saved_nonempty_system_tag_columns_are_refused(kind: str) -> None: SOURCE_KINDS[kind].from_config({"system_tag_columns": ["extra"]}) -@pytest.mark.parametrize("kind", ["csv", "delta", "sqlite"]) +@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 @@ -344,9 +344,15 @@ def test_saved_config_loads_without_system_tags( config = source.to_config() if legacy: config["system_tag_columns"] = [] - 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)) + 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) 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_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_token_types_review_1.py b/tests/test_pipeline/test_token_types_review_1.py index 4c1f705ea..8054bfff4 100644 --- a/tests/test_pipeline/test_token_types_review_1.py +++ b/tests/test_pipeline/test_token_types_review_1.py @@ -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 From fe7d2e8d417043db3d99483ed8af085405479d66 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 11:40:04 -0800 Subject: [PATCH 04/13] test(provenance): migrate remaining batch and hashing fixtures --- tests/test_channels/test_record_batch_review_findings.py | 2 +- tests/test_hashing/test_wrong_hash_findings.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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_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: From 28b742daf07acfdd04d4753e5a05bf9ebdadaf16 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 12:09:21 -0800 Subject: [PATCH 05/13] test(datagrams): rebuild tagged rows through the private stream factory --- tests/test_core/datagrams/test_rows_of_table.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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()) From 8591355a5f8e0c9ad70de832a4e118ba070c2f41 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 12:21:35 -0800 Subject: [PATCH 06/13] fix(sources): reserve system tags in Python polling schemas --- src/orcapod/core/sources/polling_source.py | 8 ++++++- .../sources/test_source_arrow_validation.py | 21 +++++++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 58bdbe483..8df17f81e 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -334,8 +334,14 @@ 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): - schema_utils.require_names_not_system_tags(unified_schema.names) require_supported_nullable_types(unified_schema) require_live_logical_types(unified_schema) # Canonicalize the declaration for comparison to batch schemas (ITL-640). diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index f59005bda..13eea08c8 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -55,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, @@ -631,12 +631,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: @@ -665,6 +667,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) From cc7ed448bc1b652a7481cdee97adab2c5d7996ad Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:06:25 -0800 Subject: [PATCH 07/13] fix(provenance)!: refuse legacy cache configs and reserved pod outputs --- .zed/rules | 5 +- CLAUDE.md | 7 ++- changelog.d/ITL-1751.md | 3 ++ docs/dev/design_issues/ITL-1751-AS5.md | 6 ++- src/orcapod/core/function_pod.py | 7 +++ src/orcapod/core/operators/index.py | 1 + src/orcapod/core/operators/pick.py | 1 + src/orcapod/core/sources/base.py | 14 ++++-- src/orcapod/core/sources/cached_source.py | 2 + src/orcapod/core/sources/derived_source.py | 1 + src/orcapod/core/sources/list_source.py | 4 +- src/orcapod/core/sources/polling_source.py | 1 + src/orcapod/core/sources/source_proxy.py | 1 + src/orcapod/utils/schema_utils.py | 1 + .../test_function_pod_decorator.py | 47 ++++++++++++++++++- .../operators/test_index_pick_arrow_types.py | 20 ++++++++ tests/test_core/sources/test_cached_source.py | 32 ++++++++++++- .../sources/test_source_arrow_validation.py | 37 +++++++++++++-- .../test_delta_merge_reserved_names.py | 38 --------------- 19 files changed, 174 insertions(+), 54 deletions(-) diff --git a/.zed/rules b/.zed/rules index 08a1cf681..a437da799 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1522,7 +1522,10 @@ data. The rules: 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. Orcapod constructs system tags (ITL-1751). Public source and stream inputs refuse - columns in the system-tag namespace. Tables built by operators, sources, row transport + 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. diff --git a/CLAUDE.md b/CLAUDE.md index 3766a2a76..5cd4fa105 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 @@ -1567,7 +1567,10 @@ data. The rules: 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. Orcapod constructs system tags (ITL-1751). Public source and stream inputs refuse - columns in the system-tag namespace. Tables built by operators, sources, row transport + 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. diff --git a/changelog.d/ITL-1751.md b/changelog.d/ITL-1751.md index 7b4de29d2..d233a6b90 100644 --- a/changelog.d/ITL-1751.md +++ b/changelog.d/ITL-1751.md @@ -5,3 +5,6 @@ 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/dev/design_issues/ITL-1751-AS5.md b/docs/dev/design_issues/ITL-1751-AS5.md index 5904c7501..dc29b217a 100644 --- a/docs/dev/design_issues/ITL-1751-AS5.md +++ b/docs/dev/design_issues/ITL-1751-AS5.md @@ -10,5 +10,7 @@ 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. Source configs -omit the removed setting and refuse a saved non-empty list. +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 973bc85d8..4f41746c5 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -134,6 +134,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/operators/index.py b/src/orcapod/core/operators/index.py index fdfebc0af..6d38f4a63 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -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 diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index bf3a55800..f36c87c0b 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -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 diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index f8f1ce75b..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,15 +274,21 @@ def _source_id_config(self) -> dict[str, Any]: "source_version": self.SOURCE_VERSION, } - @staticmethod - def _require_no_saved_system_tags(config: dict[str, Any]) -> None: - """Refuse saved configurations that nominated custom system tags.""" + @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( diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 57a3431e0..2085dcad1 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -264,6 +264,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: diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 0dc6b64b8..614f4fd55 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -468,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). diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 1433cbc71..88e397e0d 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -178,8 +178,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 8df17f81e..8486dad95 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -759,6 +759,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 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/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index bdf2e1cf2..1cfee5301 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -1249,6 +1249,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/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/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/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_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 13eea08c8..032fad18f 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -106,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" @@ -114,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, @@ -186,17 +198,16 @@ def _source( ).write(table) project.table("default.rows").record(table.schema) return SpiralDBTableSource("project", "rows", **options, **kwargs) - connector = _Connector(table) 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 ) assert kind == "db" - return DBTableSource(connector, "rows", **options, **kwargs) + return DBTableSource(_Connector(table), "rows", **options, **kwargs) def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: @@ -1338,3 +1349,23 @@ def test_dataframe_source_preserves_declared_arrow_data_field() -> None: ) source = DataFrameSource(table, source_id="declared") assert source.as_table().schema.field("x").equals(field, check_metadata=True) + + +@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"]}) + + +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_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) From a962ddd639f777033c7b29fd8deba161a62de9e8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:07:35 -0800 Subject: [PATCH 08/13] fix(join): keep tied provenance bundles together (ITL-1628) --- .zed/rules | 5 +- CLAUDE.md | 5 +- changelog.d/ITL-1628.md | 12 + docs/dev/design_issues/ITL-1628-CJ1.md | 13 + docs/dev/design_issues/ITL-1629-CJ2.md | 13 + docs/dev/design_issues/ITL-1631-CJ3.md | 12 + docs/reference/hashing.md | 10 +- src/orcapod/contexts/data/v1.json | 4 +- src/orcapod/core/datagrams/tag_data.py | 19 +- src/orcapod/core/nodes/operator_node.py | 16 +- src/orcapod/core/operators/join.py | 364 +++++----- src/orcapod/core/operators/streaming_joins.py | 41 +- src/orcapod/utils/arrow_utils.py | 171 ----- .../unit/test_arrow_data_utils.py | 25 - .../test_native_async_operators.py | 42 -- .../operators/test_async_sync_equivalence.py | 684 +++++------------- tests/test_core/operators/test_operators.py | 167 +---- .../operators/test_streaming_joins.py | 4 +- tests/test_core/test_order_invariance.py | 40 + tests/test_hashing/golden/cases.py | 54 ++ .../golden/data/v1/pipeline-02.json | 38 +- 21 files changed, 594 insertions(+), 1145 deletions(-) create mode 100644 changelog.d/ITL-1628.md create mode 100644 docs/dev/design_issues/ITL-1628-CJ1.md create mode 100644 docs/dev/design_issues/ITL-1629-CJ2.md create mode 100644 docs/dev/design_issues/ITL-1631-CJ3.md diff --git a/.zed/rules b/.zed/rules index 08a1cf681..46491cc70 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1314,8 +1314,9 @@ these preimages anywhere else. 1. Name-preserving — single-stream ops. Column name/value pass through unchanged. 2. Name-extending — multi-input ops. System tag column name gets ::{pipeline_hash}:{canonical_position} appended. Commutative operators sort by - pipeline_hash and sort system tag values per row. MergeJoin is ordered (ITL-1281): the - position is the argument index and nothing is sorted. + pipeline_hash. For tied inputs, Join orders each row's complete provenance bundles, + keeping all of an input's source and record IDs together. MergeJoin is ordered + (ITL-1281): the position is the argument index. 3. Reducing — many→one ops (Batch, GroupBy). Data columns become list[T]; Batch makes every user tag list[T] and keeps it a tag, while GroupBy keeps its scalar keys and drops every other user tag (ITL-1070). No tag ever moves to the data group. Source-info columns become diff --git a/CLAUDE.md b/CLAUDE.md index 3357f477e..ff7a4d62b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1344,8 +1344,9 @@ are defined in one module, `core/row_ids.py`; never build one of these preimages through unchanged. 2. **Name-extending** — multi-input ops (join, merge join). Each input's system tag column name gets `::{pipeline_hash}:{canonical_position}` appended. Commutative operators - canonically order inputs by `pipeline_hash` and sort system tag values per row. `MergeJoin` - is ordered (ITL-1281): the position is the argument index and nothing is sorted. + canonically order inputs by `pipeline_hash`. For tied inputs, `Join` orders each row's + complete provenance bundles, keeping all of an input's source and record IDs together. + `MergeJoin` is ordered (ITL-1281): the position is the argument index. 3. **Reducing** — many→one ops (`Batch`, `GroupBy`). Data columns become `list[T]`; `Batch` makes every user tag `list[T]` and keeps it a tag, while `GroupBy` keeps its scalar keys and drops every other user tag (ITL-1070). No tag ever moves to the data group. Source-info diff --git a/changelog.d/ITL-1628.md b/changelog.d/ITL-1628.md new file mode 100644 index 000000000..2ef4955ae --- /dev/null +++ b/changelog.d/ITL-1628.md @@ -0,0 +1,12 @@ +### Breaking changes and migration + +- Entry IDs can change for rows from a Join with structurally tied inputs, such + as a diamond whose old output mixed branches' provenance. Recompute affected + outputs and any downstream results keyed by their entry IDs. The same stored + path can contain old and corrected records if it is reused. + +### Fixed + +- Join keeps all source and record IDs of each tied input together, including + joined and folded provenance. Tables, row channels, and record batches use + the same ordering and keep the declared nullability of the identifiers. diff --git a/docs/dev/design_issues/ITL-1628-CJ1.md b/docs/dev/design_issues/ITL-1628-CJ1.md new file mode 100644 index 000000000..8b7053c44 --- /dev/null +++ b/docs/dev/design_issues/ITL-1628-CJ1.md @@ -0,0 +1,13 @@ +## `src/orcapod/core/operators/join.py` — tied inputs + +### CJ1 — Tied diamond Joins mix provenance between branches +**Status:** resolved +**Severity:** high +**Issue:** ITL-1628 + +Sorting each source/record pair independently could mix leaves of tied nested +Joins. For example, branches over `(0, a, z)` and `(0, b, c)` could become +`(0, a, c)` and `(0, b, z)`. + +**Fix:** Join compares each tied operand's complete provenance tuple and moves +all of its source and record IDs together. diff --git a/docs/dev/design_issues/ITL-1629-CJ2.md b/docs/dev/design_issues/ITL-1629-CJ2.md new file mode 100644 index 000000000..8b28c7d42 --- /dev/null +++ b/docs/dev/design_issues/ITL-1629-CJ2.md @@ -0,0 +1,13 @@ +## `src/orcapod/core/operators/join.py` — tied inputs + +### CJ2 — Pairwise row joins diverged from tables on sparse system tags +**Status:** resolved +**Severity:** high +**Issue:** ITL-1629 + +A custom system tag missing from one tied operand could appear at different +positions on row channels and tables. + +**Fix:** ITL-1751 reserves system tags for the library. For its paired +identifiers, the row channel, table and batch kernel use the same whole-bundle +ordering after the last join step. The regression covers three tied operands. diff --git a/docs/dev/design_issues/ITL-1631-CJ3.md b/docs/dev/design_issues/ITL-1631-CJ3.md new file mode 100644 index 000000000..1fe0f56bc --- /dev/null +++ b/docs/dev/design_issues/ITL-1631-CJ3.md @@ -0,0 +1,12 @@ +## `src/orcapod/core/operators/join.py` — tied inputs + +### CJ3 — Tied Join rows narrowed record ID declarations +**Status:** resolved +**Severity:** high +**Issue:** ITL-1631 + +Row channels and table iteration inferred tied record ID fields from individual +values, even when the table declared those fields nullable. + +**Fix:** Join preserves Arrow field declarations on every path. A position's +record ID field is nullable when any corresponding input field is nullable. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index ae1a5c41e..904a0ba6d 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1263,10 +1263,12 @@ and `k` such stages stacked carry each one `2 ** k` times (ITL-1114). The table `head()` and the notebook preview of a stream that has not run are built from carries the system tag columns too, so those calls are as wide as the joins make them (ITL-1132). -Join sorts source and record IDs as pairs within each printed provenance path. -Sync and record-batch tables keep custom system tags in their input positions. -Standalone row channels sort custom tags on the same path with the ID pair. -Join rows on these tied paths infer their system-tag fields from values. +For inputs with the same pipeline hash, Join orders each row's complete provenance bundles. +All source and record IDs of one input travel together, including IDs from earlier joins +and folds. It orders provenance paths by name and compares the source ID before the record +ID at each path. A standalone raw stream has an empty provenance bundle, which comes first. +Tables, row channels, and record batches keep the same field declarations. A field is +nullable if any corresponding field that can move into it is nullable. --- diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index 107a08dbd..0450514e5 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -253,10 +253,10 @@ "date": "2026-11-29", "release": null, "added": { - "pipeline-02.json": "cca93cb45ed48622bc58e77d344f8e536a89ee1d5da63c6a8d0b121361c64b5f" + "pipeline-02.json": "b4566234fe4fe71cb0eece34ee2987c95dac503beb40896df1d7acb4d17121f6" }, "previous": "4d7e6efa1eb0e72175a18d6b40b933d61c6817b1499d590b10e7d016b642f6ba", - "digest": "a900909f035bbec5eb67869b6b0c87648bcf3446171f2d16a862f5f3e672c437" + "digest": "5f06ae2f640b36fe24b6c04648495dd2d6643d7d4c501cfaa3f87803ebf8a917" } ], "provisional": { diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 15a2a086f..510652f7b 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -18,7 +18,7 @@ import logging import uuid -from collections.abc import Collection, Iterator, Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from typing import cast, TYPE_CHECKING, Any, Self import pyarrow as pa @@ -197,8 +197,6 @@ def rows_of( cls, table: "pa.Table", data_context: "str | contexts.DataContext | None" = None, - *, - infer_system_tags: Collection[str] = (), ) -> Iterator[Self]: """Yield the tag of each row of ``table``, in row order. @@ -213,7 +211,6 @@ def rows_of( table: The rows: user-tag and system-tag columns. data_context: The data context of every tag; ``None`` reads each row's own from the table's data-context column, or takes the default. - infer_system_tags: Tied Join fields built from Python values. Yields: One tag per row. @@ -227,20 +224,6 @@ def rows_of( for tag, system_tag_row, _ in rows: if system_tag_row is None: tag._set_system_tags({}) - elif infer_system_tags: - names = system_tag_row.column_names - infer = [name for name in names if name in infer_system_tags] - values = tag.converter.arrow_table_to_python_dicts( - system_tag_row.select(infer) - )[0] - tag._set_system_tags(values) - if len(infer) != len(names): - kept = system_tag_row.drop_columns(infer) - tag._set_system_tag_table( - arrow_utils.hstack_tables( - kept, tag._ensure_system_tags_table() - ).select(names) - ) else: tag._set_system_tag_table(system_tag_row) yield tag diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 611e0c242..bbdb1794c 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1490,17 +1490,6 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: declared = self._typed_zero_row_table() if declared is not None: - from orcapod.core.operators.join import Join - - # On tied Join paths, the table describes the input declarations - # while rows infer their own provenance fields from the values. - row_inferred = ( - self._operator.row_inferred_system_tags( - self._input_streams, declared.column_names - ) - if isinstance(self._operator, Join) - else frozenset() - ) expected_fields = {field.name: field for field in declared.schema} actual_fields = {field.name: field for field in output_table.schema} for name in sorted(expected_fields.keys() | actual_fields.keys()): @@ -1509,10 +1498,7 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: if ( expected is not None and actual is not None - and ( - name in row_inferred - or expected.equals(actual, check_metadata=True) - ) + and expected.equals(actual, check_metadata=True) ): continue raise InputValidationError( diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index ff3c1fb35..b7b99e3e5 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -2,8 +2,8 @@ import functools import itertools import json -from collections import Counter -from collections.abc import Callable, Collection, Iterator, Sequence +import re +from collections.abc import Callable, Collection, Sequence from typing import Any, ClassVar, get_args import polars as pl @@ -76,27 +76,158 @@ _COMMON_JOIN_KEY = "_common" -def repeated_system_tag_suffixes(suffixes: Sequence[str]) -> frozenset[str]: - """Return the printed positional suffixes whose hash prefix occurs twice or more.""" - prefixes = [suffix.rsplit(constants.FIELD_SEPARATOR, 1)[0] for suffix in suffixes] - counts = Counter(prefixes) - return frozenset( - constants.BLOCK_SEPARATOR + suffix - for suffix, prefix in zip(suffixes, prefixes, strict=True) - if counts[prefix] > 1 - ) +# A source schema digest followed by joined or folded pipeline digests. +_PROVENANCE_PATH = re.compile(r"[0-9a-f]{64}(?:::[0-9a-f]{64}(?::(?:0|[1-9][0-9]*))?)*") + + +@functools.lru_cache(maxsize=256) +def _system_tag_bundle_layout( + names: tuple[str, ...], suffixes: tuple[str, ...] +) -> tuple[tuple[str, ...], tuple[str, ...], tuple[tuple[tuple[str, ...], ...], ...]]: + """Plan column moves and align comparable bundles by their provenance paths.""" + source_prefix, record_prefix = arrow_utils.system_tag_column_names("") + by_suffix: dict[str, set[str]] = {suffix: set() for suffix in suffixes} + for name in names: + base, _, suffix = name.rpartition(constants.BLOCK_SEPARATOR) + prefix, separator, path = base.partition(constants.BLOCK_SEPARATOR) + if ( + suffix not in by_suffix + or prefix + separator not in (source_prefix, record_prefix) + or not _PROVENANCE_PATH.fullmatch(path) + ): + raise InputValidationError( + f"Join: unrecognized system-tag column {name!r}." + ) + by_suffix[suffix].add(base) + groups: dict[str, list[str]] = {} + for suffix, fields in by_suffix.items(): + for field in fields: + _, _, path = field.partition(constants.BLOCK_SEPARATOR) + if not set(arrow_utils.system_tag_column_names(path)) <= fields: + raise InputValidationError( + f"Join: system-tag column {field!r} has no matching identifier column." + ) + digest, _, _ = suffix.rpartition(constants.FIELD_SEPARATOR) + groups.setdefault(digest, []).append(suffix) + + inputs: dict[str, tuple[str, ...]] = {} + outputs: dict[str, tuple[str, ...]] = {} + tied = [] + for group in groups.values(): + if len(group) < 2: + continue + group.sort( + key=lambda suffix: int(suffix.rsplit(constants.FIELD_SEPARATOR, 1)[1]) + ) + paths = { + suffix: tuple( + name + for source in sorted( + field + for field in by_suffix[suffix] + if field.startswith(source_prefix) + ) + for name in (source, record_prefix + source.removeprefix(source_prefix)) + ) + for suffix in group + } + # A standalone raw stream can tie with a source and carry no provenance. + # Order layouts first (an empty bundle first), then sort values among + # operands with the same layout so every row has the same columns. + ranked = sorted(group, key=paths.__getitem__) + matched: dict[tuple[str, ...], list[tuple[str, ...]]] = {} + if len(set(paths.values())) > 1: + group_names = [ + ( + f"{name}{constants.BLOCK_SEPARATOR}{current}", + f"{name}{constants.BLOCK_SEPARATOR}{position}", + ) + for current, position in zip(ranked, group, strict=True) + for name in paths[current] + ] + inputs[group[0]], outputs[group[0]] = map( + tuple, zip(*group_names, strict=True) + ) + for current, position in zip(ranked, group, strict=True): + if shape := paths[current]: + matched.setdefault(shape, []).append( + tuple( + f"{name}{constants.BLOCK_SEPARATOR}{position}" for name in shape + ) + ) + tied.extend(tuple(group) for group in matched.values() if len(group) > 1) + + # Keep the existing physical layout for equally shaped ties and untied + # operands. For a mixed layout, fill its column slots in canonical order. + def column_order(moves: dict[str, tuple[str, ...]]) -> tuple[str, ...]: + slots = {name: suffix for suffix, group in inputs.items() for name in group} + ordered = {suffix: iter(group) for suffix, group in moves.items()} + return tuple( + next(ordered[suffix]) if (suffix := slots.get(name)) else name + for name in names + ) + + return column_order(inputs), column_order(outputs), tuple(tied) -def _system_tag_names_with_suffixes( - names: Collection[str], suffixes: Collection[str] -) -> frozenset[str]: - """Select system-tag fields from operands whose printed hash suffix is shared.""" - endings = tuple(suffixes) - return frozenset( + +def sort_join_system_tag_bundles(table: pa.Table, suffixes: Sequence[str]) -> pa.Table: + """Sort each row's tied operands as whole bundles, with null IDs last.""" + names = tuple( name - for name in names - if name.startswith(constants.SYSTEM_TAG_PREFIX) and name.endswith(endings) + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) ) + original, canonical, ties = _system_tag_bundle_layout(names, tuple(suffixes)) + if original != names or canonical != names: + columns = set(names) + source, target = iter(original), iter(canonical) + indices = [ + next(source) if name in columns else name for name in table.column_names + ] + renamed = [ + next(target) if name in columns else name for name in table.column_names + ] + table = table.select(indices).rename_columns(renamed) + for bundles in ties: + fields = [ + tuple(table.schema.field(name) for name in bundle) for bundle in bundles + ] + if any( + not pa.types.is_large_string(field.type) + for bundle in fields + for field in bundle + ): + raise InputValidationError( + "Join: system-tag identifiers must be large strings." + ) + nullable = [ + any(field.nullable for field in aligned) + for aligned in zip(*fields, strict=True) + ] + members = [ + zip(*(table[name].to_pylist() for name in bundle), strict=True) + for bundle in bundles + ] + ordered_rows = [ + sorted( + row, + key=lambda bundle: tuple((value is None, value) for value in bundle), + ) + for row in zip(*members, strict=True) + ] + for position, bundle in enumerate(fields): + for index, field in enumerate(bundle): + # A tied field can receive the value declared by any member. + declared = pa.field(field.name, field.type, nullable=nullable[index]) + table = table.set_column( + table.schema.get_field_index(field.name), + declared, + pa.array( + [row[position][index] for row in ordered_rows], type=field.type + ), + ) + return table def _with_common_key(table: "pa.Table") -> "pa.Table": @@ -611,18 +742,28 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: f"{stream.pipeline_hash().to_hex()}:{idx}" ) system_tag_fields[new_name] = col_type - nullable = arrow_utils.sorted_system_tag_nullability( - { - name: kind is type(None) or type(None) in get_args(kind) - for name, kind in system_tag_fields.items() - } + suffixes = tuple( + self._compute_system_tag_suffixes( + [stream.pipeline_hash() for stream in streams] + ) ) - return Schema( - { - name: kind | None if nullable[name] else kind - for name, kind in system_tag_fields.items() - } + original, canonical, ties = _system_tag_bundle_layout( + tuple(system_tag_fields), suffixes ) + system_tag_fields = { + target: system_tag_fields[source] + for source, target in zip(original, canonical, strict=True) + } + for bundles in ties: + for aligned in zip(*bundles, strict=True): + if any( + (kind := system_tag_fields[name]) is type(None) + or type(None) in get_args(kind) + for name in aligned + ): + for name in aligned: + system_tag_fields[name] |= type(None) + return Schema(system_tag_fields) def static_process(self, *streams: StreamProtocol) -> StreamProtocol: """Join the streams on their shared tag columns. @@ -743,8 +884,10 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: for name in sorted(merged_source): table = self._fold_source_column(table, name) - # Sort system tag values for same-pipeline-hash streams to ensure commutativity - table = arrow_utils.sort_system_tag_values(table) + suffixes = self._compute_system_tag_suffixes( + [stream.pipeline_hash() for stream in streams] + ) + table = sort_join_system_tag_bundles(table, suffixes) # Lay the columns out in the order ``output_schema`` defines (see # ``_joined_user_schemas``): tags, then data, then the hidden columns. @@ -760,52 +903,12 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: + data_order + [col for col in table.column_names if col not in listed] ) - return self._join_result_stream( + return ArrowTableStream._from_derived_table( result_table, - streams, tag_columns=tuple(tag_order), data_tags=data_tag_names(tag_schema, data_schema), ) - def row_inferred_system_tags( - self, streams: Sequence[StreamProtocol], names: Collection[str] - ) -> frozenset[str]: - """Return the Join output columns whose row tags are built from values.""" - suffixes = self._compute_system_tag_suffixes( - [stream.pipeline_hash() for stream in streams] - ) - return _system_tag_names_with_suffixes( - names, repeated_system_tag_suffixes(suffixes) - ) - - def _join_result_stream( - self, - result_table: pa.Table, - streams: Sequence[StreamProtocol], - *, - tag_columns: Collection[str], - data_tags: Collection[str], - ) -> ArrowTableStream: - """Keep the table's fields and apply tied provenance inference to row reads.""" - inferred = self.row_inferred_system_tags(streams, result_table.column_names) - if any( - field.name in inferred - and ( - field.nullable - or field.metadata - or not pa.types.is_large_string(field.type) - ) - for field in result_table.schema - ): - tied = _TiedJoinStream._from_derived_table( - result_table, tag_columns=tag_columns, data_tags=data_tags - ) - tied._inferred_system_tags = inferred - return tied - return ArrowTableStream._from_derived_table( - result_table, tag_columns=tag_columns, data_tags=data_tags - ) - @staticmethod def _merge_source_columns( table: "pa.Table", left_name: str, right_name: str @@ -1005,7 +1108,6 @@ async def _streaming_join( """ n = len(inputs) if n == 2: - repeated_suffixes = repeated_system_tag_suffixes(suffixes) # Join in canonical order so the merged tag and data keys follow # the order ``output_schema`` defines, whatever the operand order. left_idx, right_idx = self._canonical_input_order(suffixes) @@ -1017,9 +1119,7 @@ def merge_fn( rt: TagProtocol, rp: DataProtocol, ) -> tuple[TagProtocol, DataProtocol]: - return self._merge_pair_rename( - lt, lp, rt, rp, pair_suffixes, repeated_suffixes - ) + return self._merge_pair_rename(lt, lp, rt, rp, pair_suffixes) await self._binary_streaming_join( inputs[left_idx], @@ -1087,7 +1187,6 @@ async def _staggered_join( # compared with every other input's as it arrives, whether or not any row # matches (the sync path compares the inputs' tables before it joins). first_rows: dict[int, tuple[TagProtocol, DataProtocol]] = {} - repeated_suffixes = repeated_system_tag_suffixes(suffixes) def declare(position: int, tag: TagProtocol, data: DataProtocol) -> None: for other, (other_tag, other_data) in sorted(first_rows.items()): @@ -1110,7 +1209,6 @@ def declare(position: int, tag: TagProtocol, data: DataProtocol) -> None: inputs[orig_idx], ch.writer, suffixes[orig_idx], - repeated_suffixes, functools.partial(declare, position), ) ) @@ -1137,7 +1235,7 @@ def declare(position: int, tag: TagProtocol, data: DataProtocol) -> None: self._merge_pair_passthrough, final=is_last, merged_so_far=merged_so_far, - repeated_suffixes=repeated_suffixes, + suffixes=suffixes, ), ) ) @@ -1331,7 +1429,6 @@ async def _rename_sys_tags( ch_in: ReadableChannel[tuple[TagProtocol, DataProtocol]], ch_out: WritableChannel[tuple[TagProtocol, DataProtocol]], suffix: str, - repeated_suffixes: Collection[str], on_first_row: Callable[[TagProtocol, DataProtocol], None], ) -> None: """Read rows and rename system-tag keys by appending the per-input suffix. @@ -1352,7 +1449,6 @@ async def _rename_sys_tags( Join._merge_tag_tables(tag, None), arrow_utils.append_to_system_tags(system_tags, suffix), tag.data_context_key, - repeated_suffixes, ) await ch_out.send((tag, pkt)) finally: @@ -1439,35 +1535,13 @@ def _build_tag( table: "pa.Table | None", system_tags: "pa.Table | None", data_context_key: str, - repeated_suffixes: Collection[str], ) -> TagProtocol: - """Build a tag, sorting by value for tied system-tag paths.""" + """Build a tag from its declared Arrow fields.""" if system_tags is None: return Tag( table if table is not None else {}, data_context=data_context_key ) - names = system_tags.column_names - tied_names = _system_tag_names_with_suffixes(names, repeated_suffixes) - if tied_names: - from orcapod.contexts import resolve_context - - converter = resolve_context(data_context_key).type_converter - tied = system_tags.select([name for name in names if name in tied_names]) - values = Join._sort_merged_system_tags( - converter.arrow_table_to_python_dicts(tied)[0] - ) - if len(tied_names) == len(names): - return Tag( - table if table is not None else {}, - system_tags=values, - data_context=data_context_key, - ) - inferred = Tag({}, system_tags=values, data_context=data_context_key) - kept = system_tags.drop_columns(list(tied_names)) - inferred_table = inferred._ensure_system_tags_table() # pyright: ignore[reportPrivateUsage] # use Tag's system-field inference - system_tags = arrow_utils.hstack_tables(kept, inferred_table).select(names) - if table is not None: system_tags = arrow_utils.hstack_tables(table, system_tags) return Tag(system_tags, data_context=data_context_key) @@ -1713,7 +1787,6 @@ def _merge_pair_rename( right_tag: TagProtocol, right_pkt: DataProtocol, suffixes: list[str], - repeated_suffixes: Collection[str], ) -> tuple[TagProtocol, DataProtocol]: """Merge a matched pair, renaming system tags with per-side suffixes. @@ -1726,12 +1799,15 @@ def _merge_pair_rename( for tag, suffix in zip((left_tag, right_tag), suffixes, strict=True) if (table := Join._system_tag_table(tag)) is not None ] - merged_sys = arrow_utils.hstack_tables(*tables) if tables else None + merged_sys = ( + sort_join_system_tag_bundles(arrow_utils.hstack_tables(*tables), suffixes) + if tables + else None + ) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, left_tag.data_context_key, - repeated_suffixes, ) return merged_tag, Join._merge_data(left_tag, left_pkt, right_tag, right_pkt) @@ -1742,7 +1818,7 @@ def _merge_pair_passthrough( right_tag: TagProtocol, right_pkt: DataProtocol, *, - repeated_suffixes: Collection[str], + suffixes: Sequence[str], final: bool = True, merged_so_far: set[str] | None = None, ) -> tuple[TagProtocol, DataProtocol]: @@ -1760,11 +1836,12 @@ def _merge_pair_passthrough( if (table := Join._system_tag_table(tag)) is not None ] merged_sys = arrow_utils.hstack_tables(*tables) if tables else None + if final and merged_sys is not None: + merged_sys = sort_join_system_tag_bundles(merged_sys, suffixes) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, left_tag.data_context_key, - repeated_suffixes, ) return merged_tag, Join._merge_data( left_tag, @@ -1775,64 +1852,6 @@ def _merge_pair_passthrough( merged_so_far=merged_so_far, ) - @staticmethod - def _sort_merged_system_tags(merged_sys: dict) -> dict: - """Sort system tag values within same-provenance-path groups. - - When two joined inputs share a pipeline_hash, their system tag - columns share a provenance path but occupy different canonical - positions. Sorting the paired (source_id, record_id) values - across positions ensures commutativity — mirroring what - ``sort_system_tag_values`` does on Arrow tables in - ``static_process``. - """ - sys_prefix = constants.SYSTEM_TAG_PREFIX - block_sep = constants.BLOCK_SEPARATOR - field_sep = constants.FIELD_SEPARATOR - - # Parse keys → groups[provenance_path][position][field_type] = key - groups: dict[str, dict[str, dict[str, str]]] = {} - for key in merged_sys: - if not key.startswith(sys_prefix): - continue - base, sep, position = key.rpartition(field_sep) - if not sep or not position.isdigit(): - continue - after_prefix = base[len(sys_prefix) :] - field_type, bsep, prov_path = after_prefix.partition(block_sep) - if not bsep: - continue - groups.setdefault(prov_path, {}).setdefault(position, {})[field_type] = key - - sid_field = constants.SYSTEM_TAG_SOURCE_ID_PREFIX[len(sys_prefix) :] - rid_field = constants.SYSTEM_TAG_RECORD_ID_PREFIX[len(sys_prefix) :] - - for _prov_path, positions in groups.items(): - if len(positions) <= 1: - continue - - sorted_pos_keys = sorted(positions.keys(), key=int) - - # Collect (sort_key, {field_type: value}) per position - entries: list[tuple[tuple, dict[str, object]]] = [] - for pos in sorted_pos_keys: - fmap = positions[pos] - sid_val = merged_sys.get(fmap.get(sid_field, "")) - rid_val = merged_sys.get(fmap.get(rid_field, "")) - vals = {ft: merged_sys[k] for ft, k in fmap.items()} - entries.append(((sid_val or "", rid_val or b""), vals)) - - entries.sort(key=lambda e: e[0]) - - # Write sorted values back to the original position keys - for pos, (_, sorted_vals) in zip(sorted_pos_keys, entries): - fmap = positions[pos] - for field_type, key in fmap.items(): - if field_type in sorted_vals: - merged_sys[key] = sorted_vals[field_type] - - return merged_sys - def rows_dropped_text( self, position: int, @@ -1851,14 +1870,3 @@ def identity_structure(self) -> Any: def __repr__(self) -> str: return "Join()" - - -class _TiedJoinStream(ArrowTableStream): - """A Join table whose tied system-tag fields are inferred on row reads.""" - - _inferred_system_tags: frozenset[str] - - def _iter_tags(self, table: pa.Table) -> Iterator[Tag]: - return Tag.rows_of( - table, self.data_context, infer_system_tags=self._inferred_system_tags - ) diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 8bf696552..0efc2fc3b 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -76,7 +76,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Collection, Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from typing import Any, ClassVar import numpy as np @@ -94,7 +94,7 @@ _matched_pairs, # pyright: ignore[reportPrivateUsage] # Join's one rule _with_common_key, # pyright: ignore[reportPrivateUsage] # Join's one rule null_token_list_error, - repeated_system_tag_suffixes, + sort_join_system_tag_bundles, ) from orcapod.core.operators.base import require_shared_arrow_type from orcapod.core.operators.merge_join import ( @@ -130,9 +130,7 @@ _ROW = ("__streaming_left_row", "__streaming_right_row") -def _row_built_zero_rows( - stream: StreamProtocol, *, strip_system_tag_metadata: bool = False -) -> tuple[StreamProtocol, bool]: +def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: """``stream`` with no rows, as an input rebuilt from rows of it reads. The zero-row input (``_materialize_upstream`` with no rows) put through F: what @@ -140,7 +138,6 @@ def _row_built_zero_rows( Args: stream: An input stream (its description). - strip_system_tag_metadata: Use the row-built fields of a tied Join input. Returns: The zero-row stream in the row-built form, and whether its Arrow types differ @@ -151,14 +148,6 @@ def _row_built_zero_rows( zero = pod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the operators' one form of an input table = zero.as_table(columns=ZERO_ROW_INPUT_COLUMNS) row_built = row_built_columns(table, stream.keys()).replace_schema_metadata(None) - if strip_system_tag_metadata: - fields = [ - field.remove_metadata() - if field.name.startswith(constants.SYSTEM_TAG_PREFIX) - else field - for field in row_built.schema - ] - row_built = pa.Table.from_arrays(row_built.columns, schema=pa.schema(fields)) differs = any( field.type != table.schema.field(field.name).type for field in row_built.schema ) @@ -411,8 +400,6 @@ def __init__( self, operator: StaticOutputOperatorPod, inputs: Sequence[StreamProtocol], - *, - strip_system_tag_metadata: Collection[int] = (), ) -> None: if not inputs or (self.ARITY is not None and len(inputs) != self.ARITY): raise ValueError( @@ -424,12 +411,7 @@ def __init__( self.inputs: tuple[StreamProtocol, ...] = tuple(inputs) # Each input as the sync path reads rows of it, with no rows (the row-built # form), and whether that differs from how it reads the input with none. - built = [ - _row_built_zero_rows( - stream, strip_system_tag_metadata=index in strip_system_tag_metadata - ) - for index, stream in enumerate(self.inputs) - ] + built = [_row_built_zero_rows(stream) for stream in self.inputs] self._zero_rows: tuple[StreamProtocol, ...] = tuple(z for z, _ in built) self._null_typed: tuple[bool, ...] = tuple(d for _, d in built) # Every batch uses its input's declared fields in the row-built layout. @@ -687,17 +669,8 @@ class StreamingJoin(StreamingJoinKernel): def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: hashes = [stream.pipeline_hash() for stream in inputs] - suffixes = operator._compute_system_tag_suffixes(hashes) # pyright: ignore[reportPrivateUsage] # Join's naming rule - repeated = repeated_system_tag_suffixes(suffixes) - super().__init__( - operator, - inputs, - strip_system_tag_metadata={ - i - for i, suffix in enumerate(suffixes) - if constants.BLOCK_SEPARATOR + suffix in repeated - }, - ) + self._suffixes = operator._compute_system_tag_suffixes(hashes) # pyright: ignore[reportPrivateUsage] # Join's naming rule + super().__init__(operator, inputs) self._join = operator order = sorted(range(len(inputs)), key=lambda i: hashes[i].to_hex()) self._position = {index: position for position, index in enumerate(order)} @@ -766,7 +739,7 @@ def finish( return table for name in sorted(self._merged_source): table = Join._fold_source_column(table, name) # pyright: ignore[reportPrivateUsage] # Join's one rule - return arrow_utils.sort_system_tag_values(table) + return sort_join_system_tag_bundles(table, self._suffixes) return finish diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c69d5ccdb..3b6375ad4 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1760,177 +1760,6 @@ def aggregated_list_array( return pa.LargeListArray.from_arrays(offsets, values, type=list_type) -def _parse_system_tag_column( - col_name: str, -) -> tuple[str, str, str] | None: - """Parse a system tag column name into (field_type, provenance_path, position). - - For example: - _tag_source_id::abc123::def456:0 - → field_type="source_id", provenance_path="abc123::def456", position="0" - - _tag_record_id::abc123::def456:0 - → field_type="record_id", provenance_path="abc123::def456", position="0" - - Returns None if the column doesn't end with a :position suffix. - """ - # Strip the trailing :position - base, sep, position = col_name.rpartition(constants.FIELD_SEPARATOR) - if not sep or not position.isdigit(): - return None - - # Determine field type by checking known prefixes - prefix = constants.SYSTEM_TAG_PREFIX - if not base.startswith(prefix): - return None - - after_prefix = base[len(prefix) :] # e.g. "source_id::abc123::def456" - - # Extract field_type and provenance_path - # field_type is everything before the first BLOCK_SEPARATOR - field_type, block_sep, provenance_path = after_prefix.partition( - constants.BLOCK_SEPARATOR - ) - if not block_sep: - return None - - return field_type, provenance_path, position - - -def _system_tag_position_groups( - names: Collection[str], -) -> dict[str, dict[str, dict[str, str]]]: - """Group system-tag columns by provenance path, position, and field kind.""" - groups: dict[str, dict[str, dict[str, str]]] = {} - for name in names: - if (parsed := _parse_system_tag_column(name)) is not None: - field_type, provenance_path, position = parsed - groups.setdefault(provenance_path, {}).setdefault(position, {})[ - field_type - ] = name - return groups - - -def sorted_system_tag_nullability( - nullable_by_name: Mapping[str, bool], -) -> dict[str, bool]: - """Give each movable system-tag field the nullability of all its inputs.""" - nullable = dict(nullable_by_name) - for positions in _system_tag_position_groups(nullable).values(): - if len(positions) <= 1: - continue - for prefix in ( - constants.SYSTEM_TAG_SOURCE_ID_PREFIX, - constants.SYSTEM_TAG_RECORD_ID_PREFIX, - ): - kind = prefix.removeprefix(constants.SYSTEM_TAG_PREFIX) - names = [fields[kind] for fields in positions.values() if kind in fields] - can_hold_null = len(names) != len(positions) or any( - nullable_by_name[name] for name in names - ) - nullable.update(dict.fromkeys(names, can_hold_null)) - return nullable - - -def sort_system_tag_values(table: "pa.Table") -> "pa.Table": - """Sort paired system tag values for columns that share the same provenance path. - - System tag columns come in (source_id, record_id) pairs. Columns that differ - only by their canonical position (the final :N) represent streams with the same - pipeline_hash that were joined. For commutativity, paired (source_id, record_id) - tuples must be sorted together per row so that the result is independent of - input order. - - Algorithm: - 1. Parse each system tag column into (field_type, provenance_path, position) - 2. Group by provenance_path — source_id and record_id at the same path+position - are paired - 3. For each group with >1 position, sort per-row by (source_id, record_id) tuples - 4. Assign sorted values back to both columns at each position - """ - sys_tag_cols = [ - c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) - ] - - if not sys_tag_cols: - return table - - groups = _system_tag_position_groups(sys_tag_cols) - nullable = sorted_system_tag_nullability( - {name: table.schema.field(name).nullable for name in sys_tag_cols} - ) - - source_id_field = constants.SYSTEM_TAG_SOURCE_ID_PREFIX[ - len(constants.SYSTEM_TAG_PREFIX) : - ] - record_id_field = constants.SYSTEM_TAG_RECORD_ID_PREFIX[ - len(constants.SYSTEM_TAG_PREFIX) : - ] - - # For each provenance_path group with >1 position, sort paired tuples per row - for positions in groups.values(): - if len(positions) <= 1: - continue - - # Sort positions numerically - sorted_positions = sorted(positions.keys(), key=int) - - # Collect paired column names for each position - paired_cols: list[tuple[str | None, str | None]] = [] - for pos in sorted_positions: - field_map = positions[pos] - sid_col = field_map.get(source_id_field) - rid_col = field_map.get(record_id_field) - paired_cols.append((sid_col, rid_col)) - - # Get values for all paired columns - sid_values = [] - rid_values = [] - for sid_col, rid_col in paired_cols: - sid_values.append( - table.column(sid_col).to_pylist() - if sid_col - else [None] * table.num_rows - ) - rid_values.append( - table.column(rid_col).to_pylist() - if rid_col - else [None] * table.num_rows - ) - - # Sort per row by (source_id, record_id) tuples - n_positions = len(sorted_positions) - sorted_sid: list[list] = [[] for _ in range(n_positions)] - sorted_rid: list[list] = [[] for _ in range(n_positions)] - - for row_idx in range(table.num_rows): - row_tuples = [ - (sid_values[pos_idx][row_idx], rid_values[pos_idx][row_idx]) - for pos_idx in range(n_positions) - ] - row_tuples.sort() - for pos_idx, (sid_val, rid_val) in enumerate(row_tuples): - sorted_sid[pos_idx].append(sid_val) - sorted_rid[pos_idx].append(rid_val) - - # Replace columns with sorted values - for pos_idx, (sid_col, rid_col) in enumerate(paired_cols): - for name, values in ( - (sid_col, sorted_sid[pos_idx]), - (rid_col, sorted_rid[pos_idx]), - ): - if name is not None: - index = table.schema.get_field_index(name) - field = pa.field( - name, table.schema.field(index).type, nullable=nullable[name] - ) - table = table.set_column( - index, field, pa.array(values, type=field.type) - ) - - return table - - def add_source_info( table: "pa.Table", source_info: str | Collection[str] | None, diff --git a/test-specification/unit/test_arrow_data_utils.py b/test-specification/unit/test_arrow_data_utils.py index dfc17c7a2..cffcb28c3 100644 --- a/test-specification/unit/test_arrow_data_utils.py +++ b/test-specification/unit/test_arrow_data_utils.py @@ -18,7 +18,6 @@ append_to_system_tags, drop_columns_with_prefix, drop_system_columns, - sort_system_tag_values, ) @@ -120,30 +119,6 @@ def test_empty_table_returns_empty(self): assert result.num_rows == 0 -# --------------------------------------------------------------------------- -# sort_system_tag_values -# --------------------------------------------------------------------------- - - -class TestSortSystemTagValues: - """Per design, system tag values must be sorted for commutativity in - multi-input operators. Paired (source_id, record_id) tuples are sorted - together per row.""" - - def test_sorts_system_tag_values(self): - # This is a structural test — ensure the function runs without error - # and produces a table with the same shape - table = pa.table({"id": [1, 2], "value": [10, 20]}) - table_with_tags = add_system_tag_columns( - table, - schema_hash="abc", - source_ids="src1", - record_ids=[_make_row_identifier(), _make_row_identifier()], - ) - result = sort_system_tag_values(table_with_tags) - assert result.num_rows == table_with_tags.num_rows - - # --------------------------------------------------------------------------- # add_source_info # --------------------------------------------------------------------------- diff --git a/tests/test_channels/test_native_async_operators.py b/tests/test_channels/test_native_async_operators.py index 2028c19a0..9f5da3a1e 100644 --- a/tests/test_channels/test_native_async_operators.py +++ b/tests/test_channels/test_native_async_operators.py @@ -2343,48 +2343,6 @@ async def test_three_way_system_tags_match_sync(self): assert sync_sys == async_sys -class TestSortMergedSystemTags: - """Unit tests for Join._sort_merged_system_tags.""" - - def test_sorts_same_provenance_path_by_value(self): - """System tag values at different positions within the same provenance - path should be sorted by (source_id, record_id) tuple.""" - merged_sys = { - # Provenance path "abc123", position 0 — higher values - "_tag_source_id::abc123:0": "z_source", - "_tag_record_id::abc123:0": "z_record", - # Provenance path "abc123", position 1 — lower values - "_tag_source_id::abc123:1": "a_source", - "_tag_record_id::abc123:1": "a_record", - } - result = Join._sort_merged_system_tags(merged_sys) - - # After sorting, position 0 should have the smaller values - assert result["_tag_source_id::abc123:0"] == "a_source" - assert result["_tag_record_id::abc123:0"] == "a_record" - assert result["_tag_source_id::abc123:1"] == "z_source" - assert result["_tag_record_id::abc123:1"] == "z_record" - - def test_single_position_unchanged(self): - """Groups with only one position should not be modified.""" - merged_sys = { - "_tag_source_id::abc123:0": "only_source", - "_tag_record_id::abc123:0": "only_record", - } - result = Join._sort_merged_system_tags(merged_sys) - assert result == merged_sys - - def test_non_system_tag_keys_ignored(self): - """Non-system-tag keys should pass through unchanged.""" - merged_sys = { - "regular_key": "value", - "_tag_source_id::abc123:0": "src0", - "_tag_record_id::abc123:0": "rec0", - } - result = Join._sort_merged_system_tags(merged_sys) - assert result["regular_key"] == "value" - - class TestSemiJoinSystemTagEquivalence: """Verify SemiJoin system-tag handling matches between sync and async.""" diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 1ae19b56b..f992aad69 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -16,11 +16,9 @@ import asyncio import decimal import itertools -import math import re from collections.abc import Callable, Sequence from dataclasses import dataclass -from hashlib import sha256 from pathlib import Path from typing import Any, TypeAlias, cast @@ -405,7 +403,7 @@ def _row_schema(tag: TagProtocol, data: DataProtocol) -> pa.Schema: return arrow_utils.join_arrow_schemas(tag_schema, data_schema) -def _paired(expected: list[Row], actual: list[Row]) -> list[tuple[Row, Row]]: +def _paired(expected: Sequence[Row], actual: Sequence[Row]) -> list[tuple[Row, Row]]: """Pair each async row with the sync row that has the same user tags.""" by_key = {_row_key(tag): (tag, data) for tag, data in expected} assert len(by_key) == len(expected), "test inputs must give unique tag rows" @@ -413,7 +411,7 @@ def _paired(expected: list[Row], actual: list[Row]) -> list[tuple[Row, Row]]: return [((tag, data), by_key[_row_key(tag)]) for tag, data in actual] -def assert_equivalent(expected: list[Row], actual: list[Row]) -> None: +def assert_equivalent(expected: Sequence[Row], actual: Sequence[Row]) -> None: """Assert the async rows equal the sync rows in types, order, tags and hashes.""" context = get_default_context() for (tag, data), (sync_tag, sync_data) in _paired(expected, actual): @@ -442,7 +440,7 @@ def assert_equivalent(expected: list[Row], actual: list[Row]) -> None: ) -def assert_same_provenance(expected: list[Row], actual: list[Row]) -> None: +def assert_same_provenance(expected: Sequence[Row], actual: Sequence[Row]) -> None: """Assert the async rows carry the sync rows' source info, column for column.""" for (_, data), (_, sync_data) in _paired(expected, actual): assert data.source_info() == sync_data.source_info() @@ -505,8 +503,10 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: "k": pa.array([1, 2, 3], pa.int16()), "f": pa.array(values, pa.float64()), data: pa.array([10, 20, 30], pa.int32()), - "_tag_source_id::x": pa.array(["s", "s", "s"], pa.large_string()), - "_tag_record_id::x": pa.array(["r1", "r2", "r3"], pa.large_string()), + f"_tag_source_id::{'a' * 64}": pa.array(["s", "s", "s"], pa.large_string()), + f"_tag_record_id::{'a' * 64}": pa.array( + ["r1", "r2", "r3"], pa.large_string() + ), } ) return ArrowTableStream._from_derived_table(table, tag_columns=["k", "f"]) @@ -1076,526 +1076,212 @@ def test_projection_miss_has_the_same_policy_on_both_paths( assert sync_rows(op, empty) == async_rows(op, empty) == [] -@pytest.mark.parametrize("reverse_columns", [False, True]) -@pytest.mark.parametrize("metadata", ["none", "same", "different"]) -def test_tied_join_table_keeps_declared_identifier_fields( - reverse_columns: bool, - metadata: str, -) -> None: - """Keep table identifier flags and infer tied identifiers when reading rows.""" - source_id = "_tag_source_id::seed" - record_id = "_tag_record_id::seed" - schema = pa.schema( - [ - pa.field("k", pa.int64(), False), - pa.field("g", pa.large_string(), False), - pa.field(source_id, pa.large_string(), False), - pa.field(record_id, pa.large_string(), True), - ] - ) - inputs = [] - empty_inputs = [] - for source, records in (("a", ["p", "q"]), ("b", ["r", "t"]), ("c", ["s", "u"])): - field_metadata: dict[bytes | str, bytes | str] | None = ( - None - if metadata == "none" - else {b"owner": b"a" if metadata == "same" else source.encode()} - ) - fields = pa.schema( - [ - field.with_metadata(field_metadata) - if field_metadata is not None and field.name in (source_id, record_id) - else field - for field in schema - ] - ) - table = pa.Table.from_pylist( - [ - {"k": i, "g": group, source_id: source, record_id: record} - for i, (group, record) in enumerate( - zip(("x", "y"), records, strict=True) - ) - ], - schema=fields, - ) - if reverse_columns: - table = table.select(list(reversed(schema.names))) - inputs.append( - ArrowTableStream._from_derived_table( - table, tag_columns=("k", "g"), data_tags=("k", "g") - ) - ) - empty_inputs.append( - ArrowTableStream._from_derived_table( - table.slice(0, 0), tag_columns=("k", "g"), data_tags=("k", "g") - ) - ) - assert len({stream.pipeline_hash() for stream in inputs}) == 1 - columns = {"system_tags": True} - for positions in itertools.permutations(range(len(inputs))): - ordered = [inputs[i] for i in positions] - empty = [empty_inputs[i] for i in positions] - join = Join() - stream = join(*ordered) - table = stream.as_table(columns=columns) - empty_table = join(*empty).as_table(columns=columns) - assert empty_table.num_rows == 0 - assert empty_table.schema.equals(table.schema, check_metadata=True) - tags, _ = join.output_schema(*ordered, columns=columns) - tag_names = [name for name in tags if name.startswith("_tag_")] - assert len(tag_names) == 6 - for name in tag_names: - field = table.schema.field(name) - assert field.metadata is None - assert field.nullable == name.startswith(record_id) - assert tags[name] == (str | None if field.nullable else str) - for rows in (list(stream.iter_data()), async_rows(join, *ordered)): - assert len(rows) == table.num_rows == 2 - for tag, data in rows: - tag_table = tag.as_table(columns=columns) - for field in tag_table.schema: - if field.name.startswith(record_id): - assert field.nullable == (tag_table[field.name].null_count > 0) - assert field.metadata is None - else: - assert field.equals( - table.schema.field(field.name), check_metadata=True - ) - data_table = data.as_table() - assert data_table.schema.equals( - table.select(data_table.column_names).schema, check_metadata=True - ) - - -def _tied_join_inputs( - arity: int, - *, - distinct_revisions: bool = False, -) -> list[ArrowTableStream]: - """Build equal-pipeline inputs with distinct identifiers and optional revision values.""" - names = ["k", "_tag_source_id", "_tag_record_id", "_tag_rev"] - schema = pa.schema( - [pa.field("k", pa.int64(), nullable=False)] - + [pa.field(name, pa.large_string(), nullable=False) for name in names[1:]] - ) - inputs = [] - pairs = ( - ("az", "record-a"), - ("z", "record-z"), - ("zzzz", "record-last"), - ("z", "record-b"), - ) - for index, (source_id, record_id) in enumerate(pairs[:arity]): - key = 1 - revision = f"revision-{index}" if distinct_revisions else "shared" - table = pa.Table.from_pylist( - [dict(zip(names, (key, source_id, record_id, revision), strict=True))], - schema=schema, - ) - 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 - - -def _tied_join_outputs( - mode: str, join: Join, inputs: Sequence[StreamProtocol] -) -> tuple[pa.Table, list[Row]]: - """Return the system-tag view and rows for a tied Join. - - Sync uses the Join table, rows uses the async row tags, and batches uses - the emitted Arrow fields in Join's column order. - """ - columns = {"system_tags": True} - if mode == "rows": - rows = async_rows(join, *inputs) - return ( - pa.concat_tables([tag.as_table(columns=columns) for tag, _ in rows]) - if rows - else pa.table({}) - ), rows - if mode == "sync": - stream = join(*inputs) - return stream.as_table(columns=columns), list(stream.iter_data()) +def _join_batch_table(join: Join, inputs: Sequence[StreamProtocol]) -> pa.Table: + """Run the record-batch kernel to completion, splitting inputs into single rows.""" kernel = StreamingJoin(join, inputs) batches = [ result - for i, operand in enumerate(inputs) - for packet in operand.as_table(columns=TRANSPORT_COLUMNS).to_batches() - for result in kernel.push(i, packet) + for index, stream in enumerate(inputs) + for batch in stream.as_table(columns=TRANSPORT_COLUMNS).to_batches( + max_chunksize=1 + ) + for result in kernel.push(index, batch) ] - batches.extend(result for i in range(len(inputs)) for result in kernel.close(i)) - if not batches: - return kernel.zero_row_result.as_table(columns=columns), [] - table = pa.Table.from_batches(batches) - # The kernel returns Arrow batches. Use Join's row reader to calculate the - # entry IDs corresponding to those tables, and check the emitted fields as-is. - tag_names = inputs[0].keys()[0] - stream = join._join_result_stream( # pyright: ignore[reportPrivateUsage] # the kernel returns tables, not rows - table, inputs, tag_columns=tag_names, data_tags=tag_names + batches.extend( + result for index in range(len(inputs)) for result in kernel.close(index) ) - layout = stream.as_table(columns=columns).column_names - return table.select(layout), list(stream.iter_data()) - - -def _symmetric_tie_snapshot(arity: int, mode: str) -> tuple[str, ...]: - """Digest the Arrow IPC tables and collect the entry IDs in permutation order.""" - hasher = get_default_arrow_hasher() - snapshot = [] - for order in itertools.permutations(_tied_join_inputs(arity)): - table, rows = _tied_join_outputs(mode, Join(), order) - output = pa.BufferOutputStream() - with pa.ipc.new_stream(output, table.schema) as writer: - writer.write_table(table.combine_chunks()) - snapshot.append(sha256(output.getvalue().to_pybytes()).hexdigest()) - snapshot.extend(entry_id(hasher, tag, data).to_string() for tag, data in rows) - return tuple(snapshot) - - -@pytest.mark.parametrize("peer_is_join", [False, True]) -def test_nested_self_join_system_tags_match_in_all_modes(peer_is_join: bool) -> None: - """Raw row channels and batches use the same structural suffixes as tables.""" - table = pa.table({"k": [1, 2], "m": [3, 4]}) - a = ArrowTableSource(table, tag_columns=("k", "m"), source_id="a") - b = ArrowTableSource(table, tag_columns=("k", "m"), source_id="b") - repeated = Join()(a, a) - peer = Join()(a, b) if peer_is_join else b - _, expected = _tied_join_outputs("sync", Join(), (repeated, peer)) - assert expected - hasher = get_default_arrow_hasher() - expected_ids = sorted( - entry_id(hasher, tag, data).to_hex() for tag, data in expected - ) - - for inputs in ((repeated, peer), (peer, repeated)): - for mode in ("sync", "rows", "batches"): - _, actual = _tied_join_outputs(mode, Join(), inputs) - assert_equivalent(expected, actual) - assert ( - sorted(entry_id(hasher, tag, data).to_hex() for tag, data in actual) - == expected_ids - ) - - -# Captured from origin/main at 37f78431, where all permutations and modes agree. -@pytest.mark.parametrize( - ("arity", "table_digest", "expected_entry_id"), - [ - ( - 2, - "da59e70321d0172c50fe3e828b4a1889ce7bab343e24e1c288405a43056b061e", - "arrow_v1:0000029a37059d124668f54cd4a141a99266d84c5ba57f4007947f0ac0bee1e88eadbf", - ), - ( - 3, - "c0745b28e9bfcb112a8ef786e01e9188de67c1f8c9bd15c9dc633dc6ce031bb4", - "arrow_v1:000002b259085d031998a9850c2a998f2e41a76e931410be81f8b1f5198dd1416d5170", - ), - ( - 4, - "e1f1b75a17ac2d9006a7c3bf606050703a8216db58901cb0e515c3da84e90f4a", - "arrow_v1:00000278a840e460fa1d24285bfec361a11ac9a3efc5d0ddea290a6683cdaec5c119fc", - ), - ], -) -@pytest.mark.parametrize("mode", ["sync", "rows", "batches"]) -def test_symmetric_tied_join_matches_main( - arity: int, mode: str, table_digest: str, expected_entry_id: str -) -> None: - """Pin the table and entry IDs for every symmetric input permutation.""" - assert _symmetric_tie_snapshot(arity, mode) == ( - table_digest, - expected_entry_id, - ) * math.factorial(arity) + if not batches: + return kernel.zero_row_result.as_table(columns=TRANSPORT_COLUMNS) + return pa.Table.from_batches(batches) @pytest.mark.parametrize("arity", [2, 3, 4]) -def test_standalone_tied_join_keeps_custom_tags_with_ids(arity: int) -> None: - """Keep each revision value paired with the identifiers from its input.""" - inputs = _tied_join_inputs(arity, distinct_revisions=True) - suffix = inputs[0].pipeline_hash().to_hex() - expected = {} - names = ("_tag_source_id", "_tag_record_id", "_tag_rev") - bundles = [ - tuple(table[name][0].as_py() for name in names) - for table in ( - stream.as_table(columns={"system_tags": True}) for stream in inputs +@pytest.mark.parametrize("fold", ["none", "batch", "group"]) +def test_tied_join_bundles_agree_across_modes(arity: int, fold: str) -> None: + """Every permutation emits the same intact joined or folded provenance bundles.""" + + def source(name: str) -> ArrowTableSource: + keys = [2, 1] if name in ("b", "z", "v") else [1, 2] + return _source({"k": pa.array(keys)}, ("k",), name, with_data_tags=True) + + shared = source("0") + branches: list[StreamProtocol] = [ + Join()(shared, source(low), source(high)) + for low, high in (("a", "z"), ("b", "w"), ("c", "v"), ("d", "u"))[:arity] + ] + if fold == "batch": + branches = [Batch(batch_size=1)(branch) for branch in branches] + elif fold == "group": + branches = [GroupBy(["k"])(branch) for branch in branches] + + hashes = {branch.pipeline_hash() for branch in branches} + assert len(hashes) == 1 + digest = hashes.pop().to_hex() + columns = {"system_tags": True} + source_names = sorted( + name + for name in branches[0].keys(columns=columns)[0] + if name.startswith("_tag_source_id::") + ) + names = [ + name + for source_name in source_names + for name in ( + source_name, + source_name.replace("_tag_source_id", "_tag_record_id", 1), ) ] - for position, values in enumerate(sorted(bundles)): - for name, value in zip(names, values, strict=True): - expected[f"{name}::{suffix}:{position}"] = value - - for order in itertools.permutations(inputs): - [(tag, _)] = async_rows(Join(), *order) - assert tag.system_tags() == expected - - -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. + members = [ + arrow_utils.sort_by_tag_columns(branch.as_table(columns=columns), ("k",)) + .select(names) + .to_pylist() + for branch in branches + ] + expected = [ + { + f"{name}::{digest}:{position}": value + for position, bundle in enumerate( + sorted(tuple(row.values()) for row in rows) + ) + for name, value in zip(names, bundle, strict=True) + } + for rows in zip(*members, strict=True) + ] - Nullable changes the first field's nullability, owner and extension add - their respective metadata keys, and distinct varies the values. Source - uses the library provenance pair with a required revision field and data-tag k. - """ - if variant == "source": - ids = ("az", "z", "zz", "zzz")[:arity] - schema = pa.schema( - [ - pa.field("k", pa.int64(), False), - pa.field("rev", pa.large_string(), False), - ] + baseline = None + hasher = get_default_arrow_hasher() + for order in itertools.permutations(branches): + join = Join() + stream = join(*order) + table = arrow_utils.sort_by_tag_columns( + stream.as_table(columns=TRANSPORT_COLUMNS), ("k",) ) - sources = [ - ArrowTableSource( - pa.Table.from_pylist([{"k": 1, "rev": f"rev-{source_id}"}], schema), - tag_columns=["k"], - 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 list(sources) - inputs: list[StreamProtocol] = [] - for position in range(arity): - metadata_key = { - "owner": b"owner", - "extension": b"ARROW:extension:name", - }.get(variant) - schema = pa.schema( - [ - pa.field("k", pa.int64(), nullable=False), - pa.field("_tag_source_id", pa.large_string(), nullable=False), - pa.field("_tag_record_id", pa.large_string(), nullable=False), - pa.field( - "_tag_rev", - pa.large_string(), - nullable=variant == "nullable" and position == 0, - metadata={metadata_key: str(position).encode()} - if metadata_key - else None, - ), - ] + sync = list(stream.iter_data()) + row_channel = async_rows(join, *order) + batch_table = arrow_utils.sort_by_tag_columns( + _join_batch_table(join, order), ("k",) ) - ids = ("a", "z") if arity == 2 else ("a", "b", "c", "z")[:arity] - source_ids = [ids[position], ids[arity - position - 1]] - table = pa.Table.from_pydict( - { - "k": [0, 1], - "_tag_source_id": source_ids, - "_tag_record_id": [f"record-{source_id}" for source_id in source_ids], - "_tag_rev": [str(position)] * 2 - if variant == "distinct" - else ["same"] * 2, - }, - schema=schema, + assert table.select(list(expected[0])).to_pylist() == expected + assert batch_table.schema.equals(table.schema, check_metadata=True) + assert batch_table.equals(table) + batches = ArrowTableStream._from_derived_table( + batch_table, tag_columns=["k"], data_tags=["k"] ) + for rows in (row_channel, list(batches.iter_data())): + assert_equivalent(sync, rows) + assert_same_provenance(sync, rows) + assert {entry_id(hasher, tag, data) for tag, data in rows} == { + entry_id(hasher, tag, data) for tag, data in sync + } + identity = (stream.pipeline_hash(), stream.content_hash(), table) + if baseline is None: + baseline = identity + else: + assert identity == baseline + + +@pytest.mark.parametrize("arity", [2, 3, 4]) +def test_tied_join_keeps_nullable_record_id_declarations(arity: int) -> None: + """Table iteration, batches, and direct LOG writes keep the output declaration.""" + originals = [ + _source({"k": pa.array([1, 2])}, ("k",), name, with_data_tags=True) + for name in ("a", "b", "c", "z")[:arity] + ] + inputs = [] + for index, source in enumerate(originals): + table = source.as_table(columns=TRANSPORT_COLUMNS) + if index == 0: + record = next( + name + for name in table.column_names + if name.startswith("_tag_record_id::") + ) + field_index = table.schema.get_field_index(record) + field = table.schema.field(field_index).with_nullable(True) + table = table.set_column(field_index, field, table[record]) 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 - - -def _ipc_bytes(table: pa.Table) -> bytes: - """Serialize a table with rebuilt buffers for a stable snapshot.""" - output = pa.BufferOutputStream() - with pa.ipc.new_stream(output, table.schema) as writer: - writer.write_table(pa.Table.from_pylist(table.to_pylist(), schema=table.schema)) - return output.getvalue().to_pybytes() - -@pytest.mark.parametrize("arity", [2, 3, 4]) -def test_commutative_hash_counts_content_equal_inputs(arity: int) -> None: - """Source equality changes neither the flat nor the nested structure.""" - distinct = _tied_declaration_inputs(arity, "same") - equal = _tied_declaration_inputs(arity, "same")[0] - first = distinct[0] - assert first is not equal and first == equal - - variants = (distinct, [first] * arity, [first, equal, *distinct[2:]]) - direct = [Join()(*inputs) for inputs in variants] - assert len({stream.pipeline_hash() for stream in direct}) == 1 - assert len({Join()(stream, first).pipeline_hash() for stream in direct}) == 1 - assert direct[1].pipeline_hash() != Join()(*([first] * (arity + 1))).pipeline_hash() - - for inputs, stream in zip(variants, direct, strict=True): - sync = list(stream.iter_data()) - async_ = async_rows(Join(), *inputs) - assert len(sync) == len(async_) == 2 - hasher = get_default_arrow_hasher() - assert sorted( - entry_id(hasher, tag, data).to_string() for tag, data in sync - ) == (sorted(entry_id(hasher, tag, data).to_string() for tag, data in async_)) - - -def _tied_declaration_snapshot(arity: int, variant: str, mode: str) -> str: - """Digest all tables, row declarations, and entry IDs in permutation order.""" - hasher = get_default_arrow_hasher() - snapshot = sha256() columns = {"system_tags": True} - 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"])): - snapshot.update(_ipc_bytes(tag.as_table(columns=columns))) - snapshot.update(entry_id(hasher, tag, data).to_string().encode()) - return snapshot.hexdigest() - - -# Captured from origin/main at 37f78431. Normalize IPC array buffers before -# hashing so representation details such as buffer padding cannot affect this. -@pytest.mark.parametrize( - ("arity", "mode", "expected"), - [ - (2, "sync", "280a42832ee7f60b55ad196d02b9cfaf1e2c85d7d0503db828ab303ebb1320c0"), - (2, "rows", "9314587b25beec1a7584b1d1591aba5897a4f0d31e6a281582160153931764a2"), - ( - 2, - "batches", - "26d1cbeaa025d775dedb3f0d961c40d15cd958c7684d9c616d1ceced779545dd", - ), - (3, "sync", "cd68e71f26e095b30152cf7957d282c6aa5d136e0975098c327566e75e83f87b"), - (3, "rows", "f0845a9b6838c6fe841f070cdf2c488395132e8da736e5356c73e7fa64997ee2"), - ( - 3, - "batches", - "033fe0d17906706f270dac8d17123d4f97e88b661fe7c2c0f692e3fdd087e0b8", - ), - (4, "sync", "fb5f218d39d728d6f2f5d30baa0858ae72964208b0a66c99d6886d94ba90b5ae"), - (4, "rows", "a5c00b4f0b7b1e63c687bb0f08cf4a6adfddf652aebf5534773b0f1dc5869454"), - ( - 4, - "batches", - "2e1e2be35f60e429a95c62526db88cdee44912e1d65fe5b1afd825d4132e5c56", - ), - ], -) -def test_tied_join_declarations_and_entry_ids_match_main( - arity: int, mode: str, expected: str -) -> None: - """Pin main's per-mode table and row declarations and entry IDs.""" - fingerprints = [ - _tied_declaration_snapshot(arity, variant, mode) - for variant in ("nullable", "extension", "owner", "distinct", "source") - ] - assert sha256("".join(fingerprints).encode()).hexdigest() == expected - - -@pytest.mark.parametrize("variant", ["nullable", "extension", "owner"]) -@pytest.mark.parametrize("mode", ["run", "sync", "async"]) -def test_tied_join_direct_log_matches_main(variant: str, mode: str) -> None: - """Pin the stored system-tag fields and entry IDs of all direct LOG routes.""" - operands = _tied_declaration_inputs(2, variant) - store = InMemoryArrowDatabase() - node = OperatorJobNode( - Join(), operands, pipeline_database=store, cache_mode=CacheMode.LOG - ) - - async def run() -> list[Row]: - """Execute the node over row channels and collect its output.""" - channels: list[Channel[Row]] = [Channel(buffer_size=8) for _ in operands] - output: Channel[Row] = Channel(buffer_size=8) - for stream, channel in zip(operands, channels, strict=True): - for row in stream.iter_data(): - await channel.writer.send(row) - await channel.writer.close() - await node.async_execute( - [channel.reader for channel in channels], output.writer + for ordered in (inputs, inputs[::-1]): + join = Join() + stream = join(*ordered) + table = stream.as_table(columns=columns) + records = [ + field.name + for field in table.schema + if field.name.startswith("_tag_record_id::") + ] + assert len(records) == arity + tags, _ = join.output_schema(*ordered, columns=columns) + assert all(tags[name] == str | None for name in records) + assert all(table.schema.field(name).nullable for name in records) + batch = _join_batch_table(join, ordered) + assert batch.select(table.column_names).schema.equals( + table.schema, check_metadata=True ) - return await output.reader.collect() + for rows in (stream.iter_data(), async_rows(join, *ordered)): + for tag, _ in rows: + assert tag.as_table(columns=columns).schema.equals( + table.schema, check_metadata=True + ) - if mode == "run": + store = InMemoryArrowDatabase() + node = OperatorJobNode( + join, ordered, pipeline_database=store, cache_mode=CacheMode.LOG + ) node.run() - rows = list(node.iter_data()) - elif mode == "sync": - rows = list(node.execute(*operands).iter_data()) - else: - rows = asyncio.run(run()) - columns = {"system_tags": True} - hasher = get_default_arrow_hasher() - ids = [entry_id(hasher, tag, data) for tag, data in rows] - assert sorted(digest.to_string() for digest in ids) == [ - "arrow_v1:00000237bf6d56a4fbd90a304813372028248268b9561e94a279986a92d83506c6b1d6", - "arrow_v1:0000023c89fc6badf559f658c77af9ee84b5a1d3644995eb9a6c24d0b9e0193e958ce1", - ] - store.flush() - (path,) = store.list_table_paths() - stored = store.get_all_records(path, record_id_column="_record_hash") - assert stored is not None - assert sorted(cast(list[bytes], stored[ENTRY_ID_COL].to_pylist())) == sorted( - digest.to_prefixed_digest() for digest in ids - ) - for tag, _ in rows: - for field in tag.as_table(columns=columns).schema: - if field.name.startswith("_tag_"): - assert stored.schema.field(field.name).equals( - field, check_metadata=True - ) + store.flush() + (path,) = store.list_table_paths() + stored = store.get_all_records(path, record_id_column="_record_hash") + assert stored is not None + assert stored.select(records).schema.equals( + table.select(records).schema, check_metadata=True + ) + assert stored[ENTRY_ID_COL].to_pylist() == [ + entry_id(get_default_arrow_hasher(), tag, data).to_prefixed_digest() + for tag, data in node.iter_data() + ] -@pytest.mark.parametrize("arity", [2, 3, 4]) -@pytest.mark.parametrize("mode", ["sync", "rows", "batches"]) -def test_tied_join_with_asymmetric_empty_input_matches_main( - arity: int, mode: str -) -> None: - """Keep the zero-row layout when a tied input omits its identifier pair.""" - inputs = _tied_join_inputs(arity) +def test_tied_join_orders_raw_and_sourced_layouts() -> None: + """A raw operand naturally has the empty provenance bundle.""" + table = pa.table({"k": [1]}) + raw = ArrowTableStream(table, tag_columns=["k"], data_tags=["k"]) + a, z = [ + ArrowTableSource(table, tag_columns=["k"], source_id=name) + for name in ("a", "z") + ] + operands: tuple[StreamProtocol, ...] = (raw, a, z) + assert len({operand.pipeline_hash() for operand in operands}) == 1 columns = {"system_tags": True} - empty_table = ( - inputs[-1] - .as_table(columns=columns) - .drop(["_tag_source_id", "_tag_record_id"]) - .slice(0, 0) - ) - inputs[-1] = ArrowTableStream._from_derived_table( - empty_table, tag_columns=["k"], data_tags=["k"] - ) - for order in itertools.permutations(inputs): + expected = Join()(*operands).as_table(columns=TRANSPORT_COLUMNS) + for ordered in itertools.permutations(operands): join = Join() - tags, _ = join.output_schema(*order, columns=columns) - for prefix in ("_tag_source_id", "_tag_record_id"): - assert sum(name.startswith(prefix) for name in tags) == arity - 1 - table, rows = _tied_join_outputs(mode, join, order) - assert not rows and not table.num_rows - if mode != "rows": - assert set(table.column_names) == set(tags) + stream = join(*ordered) + result = stream.as_table(columns=TRANSPORT_COLUMNS) + assert result.equals(expected, check_metadata=True) + assert _join_batch_table(join, ordered).equals(expected, check_metadata=True) + assert_equivalent(list(stream.iter_data()), async_rows(join, *ordered)) + tags, _ = join.output_schema(*ordered, columns=columns) + assert tuple(tags) == stream.keys(columns=columns)[0] @pytest.mark.parametrize("reverse", [False, True]) def test_join_suffixes_distinguish_hashes_with_the_same_prefix(reverse: bool) -> None: """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._from_derived_table( pa.table( { "k": [1], data: [1], - source_id: [owner], - record_id: [f"{owner}-record"], - custom: [f"{owner}-revision"], + f"_tag_source_id::{'a' * 64}": [owner], + f"_tag_record_id::{'a' * 64}": [f"{owner}-record"], } ), tag_columns=["k"], @@ -1607,33 +1293,21 @@ def test_join_suffixes_distinguish_hashes_with_the_same_prefix(reverse: bool) -> right.pipeline_hash().to_hex(), ) assert left_hash[0] == right_hash[0] - assert right_hash < left_hash operands = (right, left) if reverse else (left, right) join = Join() columns = {"system_tags": True} [(tag, _)] = async_rows(join, *operands) - kernel = StreamingJoin(join, operands) - batches = [ - result - for index, operand in enumerate(operands) - for batch in operand.as_table(columns=TRANSPORT_COLUMNS).to_batches() - for result in kernel.push(index, batch) - ] expected = { - f"{field}::{digest}:{position}": value - for position, (digest, owner) in enumerate( - ((right_hash, "right"), (left_hash, "left")) - ) - for field, value in ( - (source_id, owner), - (record_id, f"{owner}-record"), - (custom, f"{owner}-revision"), + f"{name}::{stream.pipeline_hash().to_hex()}:{position}": value + for position, stream in enumerate( + sorted(operands, key=lambda operand: operand.pipeline_hash().to_hex()) ) + for name, value in next(stream.iter_data())[0].system_tags().items() } for result in ( tag.as_table(columns=columns), join(*operands).as_table(columns=columns), - pa.Table.from_batches(batches), + _join_batch_table(join, operands), ): assert result.select(list(expected)).to_pylist() == [expected] @@ -2098,7 +1772,7 @@ def _meta_table(data: DataProtocol) -> pa.Table: return data.as_table(columns={"meta": True}).select(list(data.meta_columns)) -def assert_same_meta(expected: list[Row], actual: list[Row]) -> None: +def assert_same_meta(expected: Sequence[Row], actual: Sequence[Row]) -> None: """Assert the async rows carry the sync rows' meta columns. Names, order, Arrow types, nullability and values must all match. diff --git a/tests/test_core/operators/test_operators.py b/tests/test_core/operators/test_operators.py index ab4db2c5b..503abfb3c 100644 --- a/tests/test_core/operators/test_operators.py +++ b/tests/test_core/operators/test_operators.py @@ -1697,152 +1697,31 @@ def test_intermediate_operators_produce_different_stream_hash(self): assert index_str == str(expected_idx) -class TestSortSystemTagValues: - """Tests for the sort_system_tag_values utility that ensures commutativity - by sorting paired (source_id, record_id) system tag values per row.""" - - @staticmethod - def _make_paired_cols(constants, provenance_path, position): - """Build paired source_id/record_id column names for a given provenance path and position.""" - sid = f"{constants.SYSTEM_TAG_SOURCE_ID_PREFIX}{constants.BLOCK_SEPARATOR}{provenance_path}{constants.FIELD_SEPARATOR}{position}" - rid = f"{constants.SYSTEM_TAG_RECORD_ID_PREFIX}{constants.BLOCK_SEPARATOR}{provenance_path}{constants.FIELD_SEPARATOR}{position}" - return sid, rid - - def test_sorts_paired_values_across_same_provenance_path(self): - """Paired (source_id, record_id) columns sharing a provenance path - should have their values sorted per row by (source_id, record_id) tuples.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid_0, rid_0 = self._make_paired_cols(constants, "abc::ph123", "0") - sid_1, rid_1 = self._make_paired_cols(constants, "abc::ph123", "1") - - table = pa.table( - { - "id": [1, 2], - sid_0: pa.array(["zzz_source", "aaa_source"], type=pa.large_string()), - rid_0: pa.array(["row_0", "row_0"], type=pa.large_string()), - sid_1: pa.array(["aaa_source", "zzz_source"], type=pa.large_string()), - rid_1: pa.array(["row_1", "row_1"], type=pa.large_string()), - } - ) - - result = sort_system_tag_values(table) - - # After sorting by (source_id, record_id), position :0 should have the smaller tuple - # Row 0: ("zzz_source", "row_0") vs ("aaa_source", "row_1") → sorted: aaa first - assert result.column(sid_0).to_pylist()[0] == "aaa_source" - assert result.column(rid_0).to_pylist()[0] == "row_1" - assert result.column(sid_1).to_pylist()[0] == "zzz_source" - assert result.column(rid_1).to_pylist()[0] == "row_0" - - # Row 1: ("aaa_source", "row_0") vs ("zzz_source", "row_1") → already sorted - assert result.column(sid_0).to_pylist()[1] == "aaa_source" - assert result.column(rid_0).to_pylist()[1] == "row_0" - assert result.column(sid_1).to_pylist()[1] == "zzz_source" - assert result.column(rid_1).to_pylist()[1] == "row_1" - - def test_does_not_sort_different_provenance_paths(self): - """Columns with different provenance paths should NOT have their values sorted.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - # Two different provenance paths (different pipeline hashes) - sid_a, rid_a = self._make_paired_cols(constants, "abc::ph_AAA", "0") - sid_b, rid_b = self._make_paired_cols(constants, "abc::ph_BBB", "0") - - table = pa.table( - { - "id": [1], - sid_a: pa.array(["zzz"], type=pa.large_string()), - rid_a: pa.array(["row_0"], type=pa.large_string()), - sid_b: pa.array(["aaa"], type=pa.large_string()), - rid_b: pa.array(["row_1"], type=pa.large_string()), - } - ) - - result = sort_system_tag_values(table) - - # Values should be untouched since provenance paths differ - assert result.column(sid_a).to_pylist() == ["zzz"] - assert result.column(sid_b).to_pylist() == ["aaa"] - - def test_no_op_for_single_position_groups(self): - """Groups with only one position should be left untouched.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid, rid = self._make_paired_cols(constants, "abc::ph123", "0") - - table = pa.table( - { - "id": [1, 2], - sid: pa.array(["hello", "world"], type=pa.large_string()), - rid: pa.array(["row_0", "row_1"], type=pa.large_string()), - } - ) - - result = sort_system_tag_values(table) - assert result.column(sid).to_pylist() == ["hello", "world"] - assert result.column(rid).to_pylist() == ["row_0", "row_1"] - - def test_preserves_non_system_tag_columns(self): - """Non-system-tag columns should be completely unaffected.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid_0, rid_0 = self._make_paired_cols(constants, "abc::ph123", "0") - sid_1, rid_1 = self._make_paired_cols(constants, "abc::ph123", "1") +@pytest.mark.parametrize("kind", ["custom", "unpaired", "bad_path"]) +def test_join_refuses_unrecognized_system_tag_layout(kind: str) -> None: + """A tied Join cannot order corrupt library-owned provenance.""" + from orcapod.errors import InputValidationError + from orcapod.utils.arrow_utils import system_tag_column_names + def operand(path: str, names: tuple[str, ...]) -> ArrowTableStream: table = pa.table( - { - "id": [1, 2], - "data": ["foo", "bar"], - sid_0: pa.array(["zzz", "aaa"], type=pa.large_string()), - rid_0: pa.array(["r0", "r0"], type=pa.large_string()), - sid_1: pa.array(["aaa", "zzz"], type=pa.large_string()), - rid_1: pa.array(["r1", "r1"], type=pa.large_string()), - } + {"k": [1], **{name: pa.array([path], pa.large_string()) for name in names}} ) - - result = sort_system_tag_values(table) - assert result.column("id").to_pylist() == [1, 2] - assert result.column("data").to_pylist() == ["foo", "bar"] - - def test_three_way_group_sorts_correctly(self): - """Three positions sharing the same provenance path should all be sorted together.""" - from orcapod.system_constants import constants - from orcapod.utils.arrow_utils import sort_system_tag_values - - sid_0, rid_0 = self._make_paired_cols(constants, "abc::ph123", "0") - sid_1, rid_1 = self._make_paired_cols(constants, "abc::ph123", "1") - sid_2, rid_2 = self._make_paired_cols(constants, "abc::ph123", "2") - - table = pa.table( - { - sid_0: pa.array(["cherry", "banana"], type=pa.large_string()), - rid_0: pa.array(["r0", "r0"], type=pa.large_string()), - sid_1: pa.array(["apple", "cherry"], type=pa.large_string()), - rid_1: pa.array(["r1", "r1"], type=pa.large_string()), - sid_2: pa.array(["banana", "apple"], type=pa.large_string()), - rid_2: pa.array(["r2", "r2"], type=pa.large_string()), - } + return ArrowTableStream._from_derived_table( + table, tag_columns=["k"], data_tags=["k"] ) - result = sort_system_tag_values(table) - - # Row 0: tuples are (cherry,r0), (apple,r1), (banana,r2) → sorted: (apple,r1), (banana,r2), (cherry,r0) - assert result.column(sid_0).to_pylist()[0] == "apple" - assert result.column(rid_0).to_pylist()[0] == "r1" - assert result.column(sid_1).to_pylist()[0] == "banana" - assert result.column(rid_1).to_pylist()[0] == "r2" - assert result.column(sid_2).to_pylist()[0] == "cherry" - assert result.column(rid_2).to_pylist()[0] == "r0" - - # Row 1: tuples are (banana,r0), (cherry,r1), (apple,r2) → sorted: (apple,r2), (banana,r0), (cherry,r1) - assert result.column(sid_0).to_pylist()[1] == "apple" - assert result.column(rid_0).to_pylist()[1] == "r2" - assert result.column(sid_1).to_pylist()[1] == "banana" - assert result.column(rid_1).to_pylist()[1] == "r0" - assert result.column(sid_2).to_pylist()[1] == "cherry" - assert result.column(rid_2).to_pylist()[1] == "r1" + digest = "a" * 64 + pair = system_tag_column_names(digest) + names, message = { + "custom": ((*pair, "_tag_extra"), "unrecognized system-tag column"), + "unpaired": (pair[:1], "has no matching identifier"), + "bad_path": ( + system_tag_column_names("unrecognized"), + "unrecognized system-tag column", + ), + }[kind] + left, right = operand("left", pair), operand("right", names) + assert left.pipeline_hash() == right.pipeline_hash() + with pytest.raises(InputValidationError, match=message): + _ = Join().static_process(left, right) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index b7307dc18..89477aac5 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -900,8 +900,8 @@ def test_join_keeps_nullable_tied_raw_system_tag_fields() -> None: schema = pa.schema( [ pa.field("k", pa.int64(), False), - pa.field("_tag_source_id::seed", pa.large_string(), False), - pa.field("_tag_record_id::seed", pa.large_string(), True), + pa.field(f"_tag_source_id::{'a' * 64}", pa.large_string(), False), + pa.field(f"_tag_record_id::{'a' * 64}", pa.large_string(), True), ] ) inputs = tuple( diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 4034b43b6..a715e31d0 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -677,6 +677,46 @@ def test_the_order_of_the_inputs_of_a_commutative_operator_changes_nothing( ) +def test_tied_join_diamond_keeps_each_branch_together() -> None: + """The outer Join keeps (0, a, z) and (0, b, c) as intact cohorts.""" + table = pa.table({"k": [1, 2]}) + shared, a, b, c, z = [ + ArrowTableSource(table, tag_columns=["k"], source_id=name) + for name in ("0", "a", "b", "c", "z") + ] + results = {} + for left in itertools.permutations((shared, a, z)): + for right in itertools.permutations((shared, b, c)): + branches = (Join()(*left), Join()(*right)) + assert branches[0].pipeline_hash() == branches[1].pipeline_hash() + digest = branches[0].pipeline_hash().to_hex() + branch_values = [ + sorted( + str(value) + for name, value in tag.system_tags().items() + if name.startswith("_tag_source_id::") + ) + for branch in branches + for tag, _ in itertools.islice(branch.iter_data(), 1) + ] + for reverse in (False, True): + joined = Join()(*(branches[::-1] if reverse else branches)) + for tag, _ in joined.iter_data(): + cohorts = [ + sorted( + str(value) + for name, value in tag.system_tags().items() + if name.startswith("_tag_source_id::") + and name.endswith(f"::{digest}:{i}") + ) + for i in range(2) + ] + assert cohorts == branch_values + results[str(len(results))] = with_async(joined) + assert len(results) == 72 + assert_all_equal(results) + + def test_the_commutative_case_is_the_join() -> None: """``Join`` declares itself commutative; ``SemiJoin`` and ``MergeJoin`` (ITL-1281) are ordered.""" diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index b4b48ab4b..4641aff05 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -2053,6 +2053,60 @@ def pipeline_join_pod() -> dict[str, Any]: return out +def tied_join_sources() -> tuple[Any, Any, Any, Any, Any]: + """Build two matching rows in each branch of the tied Join review example.""" + from orcapod.sources import ArrowTableSource + + table = pa.Table.from_arrays( + [pa.array([1, 2]), pa.array([3, 4])], + schema=pa.schema( + [pa.field("k", pa.int64(), False), pa.field("l", pa.int64(), False)] + ), + ) + + def source(name: str) -> Any: + return ArrowTableSource(table, tag_columns=["k", "l"], source_id=name) + + return source("0"), source("a"), source("b"), source("c"), source("z") + + +def _join_entry_ids_and_system_tags(stream: Any) -> dict[str, Any]: + """Pin the provenance fields of each row and the entry ID hashed from them.""" + from orcapod.contexts import get_default_arrow_hasher + from orcapod.core.row_ids import entry_id + from orcapod.system_constants import constants + + hasher = get_default_arrow_hasher() + out: dict[str, Any] = {} + for tag, data in stream.iter_data(): + row = _row_key(tag.as_dict()) + for name, value in tag.as_dict(columns={"system_tags": True}).items(): + if name.startswith(constants.SYSTEM_TAG_PREFIX): + out[f"row[{row}].{name}"] = _jsonable(value) + out[f"row[{row}].entry_id"] = entry_id(hasher, tag, data).to_string() + return out + + +@case("pipeline", "tied_join") +def pipeline_tied_join() -> dict[str, Any]: + """Two equal-schema inputs preserve their system tags and row identities.""" + from orcapod.operators import Join + + _, a, b, _, _ = tied_join_sources() + return _join_entry_ids_and_system_tags(Join()(a, b)) + + +@case("pipeline", "tied_join_diamond") +def pipeline_tied_join_diamond() -> dict[str, Any]: + """An outer tie keeps the two inner branches' provenance bundles intact.""" + from orcapod.operators import Join + + shared, a, b, c, z = tied_join_sources() + return _join_entry_ids_and_system_tags( + Join()(Join()(shared, a, z), Join()(shared, b, c)) + ) + + @case("pipeline", "merge_join", provisional=("MergeJoin",)) def pipeline_merge_join() -> dict[str, Any]: from orcapod.operators import MergeJoin, SelectDataColumns diff --git a/tests/test_hashing/golden/data/v1/pipeline-02.json b/tests/test_hashing/golden/data/v1/pipeline-02.json index 47164f1de..fe34c92b7 100644 --- a/tests/test_hashing/golden/data/v1/pipeline-02.json +++ b/tests/test_hashing/golden/data/v1/pipeline-02.json @@ -492,5 +492,41 @@ "_tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc" ], "tagless_producerless_stream.as_given": "content_hash_v1:fa17a6e9bf92315a00d492fed8e98d95deaec4421b124a001896393d3cd77462", - "tagless_producerless_stream.reordered": "content_hash_v1:fa17a6e9bf92315a00d492fed8e98d95deaec4421b124a001896393d3cd77462" + "tagless_producerless_stream.reordered": "content_hash_v1:fa17a6e9bf92315a00d492fed8e98d95deaec4421b124a001896393d3cd77462", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "row_0", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "row_0", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "arrow_table_v1:a", + "tied_join.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "arrow_table_v1:b", + "tied_join.row[{\"k\":1,\"l\":3}].entry_id": "arrow_v1:000002bda2b2721ffcd32058b94c1f7b5244ddc8af0985d9a8cfc592cb0c3aaf1d572e", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "row_1", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "row_1", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0": "arrow_table_v1:a", + "tied_join.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1": "arrow_table_v1:b", + "tied_join.row[{\"k\":2,\"l\":4}].entry_id": "arrow_v1:000002d836247c0e8fe6764547481ae36b419265d2393f840388ee2db76f200f9e8657", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:a", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:b", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:z", + "tied_join_diamond.row[{\"k\":1,\"l\":3}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:c", + "tied_join_diamond.row[{\"k\":1,\"l\":3}].entry_id": "arrow_v1:000002b6ad095086966d207ea3cef12b1a3cf55f699ab2ad59a19a5d3f2c2bf8bd3019", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_record_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "row_1", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:0::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:0", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:a", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:1::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:b", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:0": "arrow_table_v1:z", + "tied_join_diamond.row[{\"k\":2,\"l\":4}]._tag_source_id::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5::215b13728e5783ab826ba102f4c35d16a2b64a81494a8497b244572330e010b5:2::abea99a1c570cbb0ebec409e917fd0a4db9f13a88351f04d8d1a406bfb66499c:1": "arrow_table_v1:c", + "tied_join_diamond.row[{\"k\":2,\"l\":4}].entry_id": "arrow_v1:0000028a9b6e40369d0350a8b84ec071cd267d2ea581c8055bfa1e0ed55bc914af175d" } From 3f87840355878cba5282cf9913cfb2c79dab1614 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:12:12 -0800 Subject: [PATCH 09/13] test(join): cover tied source permutations and LOG entry points --- .../operators/test_async_sync_equivalence.py | 61 +++++++++++++------ 1 file changed, 43 insertions(+), 18 deletions(-) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index f992aad69..300044d77 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -1096,23 +1096,25 @@ def _join_batch_table(join: Join, inputs: Sequence[StreamProtocol]) -> pa.Table: @pytest.mark.parametrize("arity", [2, 3, 4]) -@pytest.mark.parametrize("fold", ["none", "batch", "group"]) -def test_tied_join_bundles_agree_across_modes(arity: int, fold: str) -> None: +@pytest.mark.parametrize("shape", ["source", "diamond", "batch", "group"]) +def test_tied_join_bundles_agree_across_modes(arity: int, shape: str) -> None: """Every permutation emits the same intact joined or folded provenance bundles.""" def source(name: str) -> ArrowTableSource: keys = [2, 1] if name in ("b", "z", "v") else [1, 2] return _source({"k": pa.array(keys)}, ("k",), name, with_data_tags=True) - shared = source("0") - branches: list[StreamProtocol] = [ - Join()(shared, source(low), source(high)) - for low, high in (("a", "z"), ("b", "w"), ("c", "v"), ("d", "u"))[:arity] - ] - if fold == "batch": - branches = [Batch(batch_size=1)(branch) for branch in branches] - elif fold == "group": - branches = [GroupBy(["k"])(branch) for branch in branches] + pairs = (("a", "z"), ("b", "w"), ("c", "v"), ("d", "u"))[:arity] + branches: list[StreamProtocol] + if shape == "source": + branches = [source(low) for low, _ in pairs] + else: + shared = source("0") + branches = [Join()(shared, source(low), source(high)) for low, high in pairs] + if shape == "batch": + branches = [Batch(batch_size=1)(branch) for branch in branches] + elif shape == "group": + branches = [GroupBy(["k"])(branch) for branch in branches] hashes = {branch.pipeline_hash() for branch in branches} assert len(hashes) == 1 @@ -1181,7 +1183,8 @@ def source(name: str) -> ArrowTableSource: @pytest.mark.parametrize("arity", [2, 3, 4]) -def test_tied_join_keeps_nullable_record_id_declarations(arity: int) -> None: +@pytest.mark.parametrize("mode", ["run", "execute", "channel"]) +def test_tied_join_keeps_nullable_record_id_declarations(arity: int, mode: str) -> None: """Table iteration, batches, and direct LOG writes keep the output declaration.""" originals = [ _source({"k": pa.array([1, 2])}, ("k",), name, with_data_tags=True) @@ -1234,7 +1237,26 @@ def test_tied_join_keeps_nullable_record_id_declarations(arity: int) -> None: node = OperatorJobNode( join, ordered, pipeline_database=store, cache_mode=CacheMode.LOG ) - node.run() + + async def run_channel() -> list[Row]: + channels = [Channel[Row](buffer_size=8) for _ in ordered] + output = Channel[Row](buffer_size=8) + for operand, channel in zip(ordered, channels, strict=True): + for row in operand.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + await node.async_execute( + [channel.reader for channel in channels], output.writer + ) + return await output.reader.collect() + + if mode == "run": + _ = node.run() + rows = list(node.iter_data()) + elif mode == "execute": + rows = list(node.execute(*ordered).iter_data()) + else: + rows = asyncio.run(run_channel()) store.flush() (path,) = store.list_table_paths() stored = store.get_all_records(path, record_id_column="_record_hash") @@ -1242,16 +1264,19 @@ def test_tied_join_keeps_nullable_record_id_declarations(arity: int) -> None: assert stored.select(records).schema.equals( table.select(records).schema, check_metadata=True ) - assert stored[ENTRY_ID_COL].to_pylist() == [ + assert sorted(stored[ENTRY_ID_COL].to_pylist()) == sorted( entry_id(get_default_arrow_hasher(), tag, data).to_prefixed_digest() - for tag, data in node.iter_data() - ] + for tag, data in rows + ) -def test_tied_join_orders_raw_and_sourced_layouts() -> None: +@pytest.mark.parametrize("empty", [False, True]) +def test_tied_join_orders_raw_and_sourced_layouts(empty: bool) -> None: """A raw operand naturally has the empty provenance bundle.""" table = pa.table({"k": [1]}) - raw = ArrowTableStream(table, tag_columns=["k"], data_tags=["k"]) + raw = ArrowTableStream( + table.slice(0, 0) if empty else table, tag_columns=["k"], data_tags=["k"] + ) a, z = [ ArrowTableSource(table, tag_columns=["k"], source_id=name) for name in ("a", "z") From a354905743d9b3b69c3412cb51f72923f81b5beb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:13:32 -0800 Subject: [PATCH 10/13] test(join): type the stored entry IDs in the LOG regression --- tests/test_core/operators/test_async_sync_equivalence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 300044d77..d97759752 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -1264,7 +1264,7 @@ async def run_channel() -> list[Row]: assert stored.select(records).schema.equals( table.select(records).schema, check_metadata=True ) - assert sorted(stored[ENTRY_ID_COL].to_pylist()) == sorted( + assert sorted(cast(list[bytes], stored[ENTRY_ID_COL].to_pylist())) == sorted( entry_id(get_default_arrow_hasher(), tag, data).to_prefixed_digest() for tag, data in rows ) From 0eed91859ed0a7b9c1c05f5e71d3997a9233748e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:27:24 -0800 Subject: [PATCH 11/13] test(sources): use the PostgreSQL double in the ordering audit --- tests/test_core/test_order_invariance.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) 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", From a059a561f59ca980d54caad21c6eb1fb7092a4a2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:47:33 -0800 Subject: [PATCH 12/13] test(join): use library identifiers in stream validation fixtures --- .../streams/test_system_tag_validation.py | 76 +++++++++---------- 1 file changed, 37 insertions(+), 39 deletions(-) diff --git a/tests/test_core/streams/test_system_tag_validation.py b/tests/test_core/streams/test_system_tag_validation.py index 619057ca0..06ce419c9 100644 --- a/tests/test_core/streams/test_system_tag_validation.py +++ b/tests/test_core/streams/test_system_tag_validation.py @@ -13,9 +13,7 @@ from orcapod.errors import InputValidationError 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") +from orcapod.utils.arrow_utils import add_system_tag_columns @pytest.mark.parametrize("name", ["_tag_application", "_tag::application"]) @@ -65,35 +63,36 @@ def test_nullable_string_field_is_preserved_when_values_are_present() -> None: assert result.schema.field(name).equals(pa.field(name, pa.large_string())) -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("_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._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 - for name in joined.column_names +def test_join_extends_complete_identifier_pairs() -> None: + """Join extends each source's qualified source-ID and record-ID pair.""" + left = ArrowTableSource(pa.table({"x": [1]}), source_id="left") + right = ArrowTableSource(pa.table({"y": [2]}), source_id="right") + config = {"system_tags": True} + joined = Join()(left, right).as_table(columns=config) + system_tags = { + name: value + for name, value in joined.to_pylist()[0].items() if name.startswith(constants.SYSTEM_TAG_PREFIX) - ] - assert len(system_names) == 5 - custom = next(name for name in system_names if name.startswith("_tag_label::")) - assert joined.column(custom).to_pylist() == ["custom"] + } + ordered = sorted((left, right), key=lambda stream: stream.pipeline_hash().to_hex()) + expected = { + f"{name}::{stream.pipeline_hash().to_hex()}:{position}": values[0] + for position, stream in enumerate(ordered) + for name, values in stream.as_table(columns=config).to_pydict().items() + if name.startswith(constants.SYSTEM_TAG_PREFIX) + } + assert len(expected) == 4 + assert system_tags == expected @pytest.mark.asyncio -@pytest.mark.parametrize("custom_name", ["source_id", "record_id"]) +@pytest.mark.parametrize("identifier", ["source_id", "record_id"]) @pytest.mark.parametrize("operation", ["join", "merge_join", "batch", "group_by"]) @pytest.mark.parametrize("execution", ["sync", "async"]) -async def test_extended_custom_id_tags_survive_operator_log( - custom_name: str, operation: str, execution: str +async def test_extended_identifier_tags_survive_operator_log( + identifier: str, operation: str, execution: str ) -> None: - """An ordinary custom string tag survives extension, LOG and further operators.""" + """A library identifier survives extension, LOG and further operators.""" from orcapod.channels import Channel, ReadableChannel from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.databases import InMemoryArrowDatabase @@ -105,12 +104,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(f"_tag_{custom_name}", pa.string(), nullable=False), - pa.array(["a", "b"]), - ) - left: StreamProtocol = ArrowTableStream._from_derived_table( - table, tag_columns=["k"] + left: StreamProtocol = ArrowTableSource( + pa.table({"k": [1, 2], "x": [3, 4]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="left", ) right: StreamProtocol = ArrowTableSource( pa.table({"k": [1, 2], "y": [5, 6]}), @@ -128,14 +126,15 @@ async def test_extended_custom_id_tags_survive_operator_log( config = {"system_tags": True} expected = operator(*inputs).as_table(columns=config) - suffix = left.pipeline_hash().to_hex() - prefix = f"{constants.SYSTEM_TAG_PREFIX}{custom_name}{constants.BLOCK_SEPARATOR}" + prefix = f"{constants.SYSTEM_TAG_PREFIX}{identifier}{constants.BLOCK_SEPARATOR}" + (base_name,) = ( + name for name in left.keys(columns=config)[0] if name.startswith(prefix) + ) + path = f"{base_name}{constants.BLOCK_SEPARATOR}{left.pipeline_hash().to_hex()}" [extended_name] = [ name for name in expected.column_names - if name == prefix + suffix - or name.startswith(prefix + suffix + constants.FIELD_SEPARATOR) - and constants.BLOCK_SEPARATOR not in name[len(prefix) :] + if name == path or name.startswith(path + constants.FIELD_SEPARATOR) ] assert expected[extended_name].null_count == 0 projected = SelectDataColumns(["x"])(operator(*inputs)).as_table(columns=config) @@ -176,10 +175,9 @@ 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], "_tag_source_id": ["derived"]}) - source = ArrowTableStream._from_derived_table(table) + source = ArrowTableSource(pa.table({"x": [1]}), source_id="original") detached = Batch(batch_size=1)(source).as_table(columns={"system_tags": True}) (name,) = (c for c in detached.column_names if c.startswith("_tag_source_id")) with pytest.raises(InputValidationError, match=rf"{re.escape(name)}.*reserved"): - _ = ArrowTableStream(detached) + _ = ArrowTableStream(detached.select(["x", name])) From 0d86c6517c7a9938615bfbe5f24ad1d2691c6a37 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 17:22:07 -0800 Subject: [PATCH 13/13] docs: describe tied Join provenance ordering --- .zed/rules | 7 ++++--- CLAUDE.md | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.zed/rules b/.zed/rules index e82a7426b..63e52b65f 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1530,9 +1530,10 @@ data. The rules: 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. + Join sorts each row's complete provenance bundles among tied inputs after all operands + are present, keeping each input's source and record IDs together. The sync table, row + channel, and record-batch paths use the declared Arrow system-tag types and nullability, + widening corresponding fields among tied inputs when any declaration is nullable. 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 2e99b27a3..8b45e6619 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1575,9 +1575,10 @@ data. The rules: 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. + Join sorts each row's complete provenance bundles among tied inputs after all operands + are present, keeping each input's source and record IDs together. The sync table, row + channel, and record-batch paths use the declared Arrow system-tag types and nullability, + widening corresponding fields among tied inputs when any declaration is nullable. 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