From 789c1a2b1998bf100744fa1444126364fa72d2de Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 15:40:56 -0800 Subject: [PATCH 1/9] fix(arrow): declare Join system tags non-nullable and validate sources (ITL-1543) --- .zed/rules | 7 +- CLAUDE.md | 7 +- changelog.d/ITL-1543.md | 11 + docs/dev/design_issues/ITL-1543-AS2.md | 14 + src/orcapod/core/operators/streaming_joins.py | 21 +- .../core/sources/arrow_table_source.py | 2 + src/orcapod/core/sources/cached_source.py | 23 +- src/orcapod/core/sources/csv_source.py | 15 +- src/orcapod/core/sources/data_frame_source.py | 8 + src/orcapod/core/sources/db_table_source.py | 2 + src/orcapod/core/sources/derived_source.py | 8 +- src/orcapod/core/sources/dict_source.py | 2 + src/orcapod/core/sources/polling_source.py | 13 +- .../core/sources/spiraldb_table_source.py | 10 +- src/orcapod/core/sources/stream_builder.py | 71 +++- src/orcapod/utils/arrow_utils.py | 30 +- .../operators/test_async_sync_equivalence.py | 19 + .../operators/test_streaming_joins.py | 108 ++++- .../test_core/sources/test_db_table_source.py | 16 +- .../sources/test_source_arrow_validation.py | 399 ++++++++++++++++++ 20 files changed, 717 insertions(+), 69 deletions(-) create mode 100644 changelog.d/ITL-1543.md create mode 100644 docs/dev/design_issues/ITL-1543-AS2.md create mode 100644 tests/test_core/sources/test_source_arrow_validation.py diff --git a/.zed/rules b/.zed/rules index ded11c753..470dbb27d 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1342,8 +1342,11 @@ data. The rules: - Every output column takes the large-normalized form of its input type (arrow_utils.normalize_to_large_types: string to large_string, binary to large_binary, list to large_list, recursively). Width, nullability and logical (extension) types are never - changed; int8 stays int8, and null stays null (operators and the type converter pass - keep_null=True; only Data maps null to large_string, the function's default). + 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. + Custom system-tag columns on a source must be non-nullable text and contain no null values. + A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + A row built by `Data` still gives an untyped null the `large_string` type. PolarsFilter is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (arrow_utils.restore_column_types and restore_schema_nullability). Every other operator takes its values from the input's Arrow diff --git a/CLAUDE.md b/CLAUDE.md index d7ec10c7b..1a54c33b5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1390,8 +1390,11 @@ data. The rules: - Every output column takes the large-normalized form of its input type (`arrow_utils.normalize_to_large_types`: `string` to `large_string`, `binary` to `large_binary`, `list` to `large_list`, recursively). Width, nullability and logical (extension) types are never - changed; `int8` stays `int8`, and `null` stays `null` (operators and the type converter pass - `keep_null=True`; only `Data` maps `null` to `large_string`, the function's default). + 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. + Custom system-tag columns on a source must be non-nullable text and contain no null values. + A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + A row built by `Data` still gives an untyped null the `large_string` type. `PolarsFilter` is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (`arrow_utils.restore_column_types` and `restore_schema_nullability`). Every other operator takes its values from the input's Arrow diff --git a/changelog.d/ITL-1543.md b/changelog.d/ITL-1543.md new file mode 100644 index 000000000..109882db9 --- /dev/null +++ b/changelog.d/ITL-1543.md @@ -0,0 +1,11 @@ +### Breaking changes and migration + +- Sources reject Arrow `null` fields at any depth, including in reserved columns. + Declare a supported nullable column type for missing values. +- A custom system-tag column on a source must be a non-nullable string column + with no null values. Convert custom tags to text before building the source. + +### Fixed + +- Join declares sorted system tags non-nullable when its inputs tie on pipeline + hash. Existing entry IDs, instance IDs, record IDs and operator hashes stay the same. diff --git a/docs/dev/design_issues/ITL-1543-AS2.md b/docs/dev/design_issues/ITL-1543-AS2.md new file mode 100644 index 000000000..88251de24 --- /dev/null +++ b/docs/dev/design_issues/ITL-1543-AS2.md @@ -0,0 +1,14 @@ +## `src/orcapod/core/streams/` + +### AS2 — A stream's Arrow table and its rows can disagree about column types +**Status:** in progress +**Severity:** high +**Issue:** ITL-1543 + +The stream defines the Arrow schema of each row. Today a row can rebuild its +columns in a different form, which makes identity and storage depend on how the +data was read. For example, a Join of streams tied on pipeline hash can declare +its sorted system tags nullable, although its rows have non-nullable system tags. + +Part A corrects that Join schema and rejects Arrow Null in sources, including +nested Null. Part B remains open and makes rows use the stream's field definitions. diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 8089f0715..3d2f6b766 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -64,8 +64,9 @@ batch of pairs gives the sync rows. - **Field flags.** A batch's flags are the sync result's, except the system-tag and source-info fields: a complete table decides those by its values (``StaticOutputOperatorPod._flag_by_values``, - the last step of F), so a kernel declares every such field nullable and the stream made - from its batches settles them. + the last step of F). The input layout declares these fields nullable and the stream + made from the batches settles them. Join's sorted system-tag fields are already + declared non-nullable when the kernel emits them. A kernel holds only what can still match: a side's rows are dropped when the other side closes (nothing can arrive to match them), and an arriving row is not kept once the @@ -130,13 +131,15 @@ _ROW = ("__streaming_left_row", "__streaming_right_row") -def _settled_by_values(schema: pa.Schema) -> pa.Schema: - """``schema`` with every system-tag and source-info field nullable. +def _settled_by_values(schema: pa.Schema, *, system_tags: bool = True) -> pa.Schema: + """``schema`` with source-info and, optionally, system-tag fields nullable. What a kernel declares for the fields a complete table decides by its values (``StaticOutputOperatorPod._flag_by_values``): one record batch of many cannot. """ - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + prefixes = (constants.SOURCE_PREFIX,) + if system_tags: + prefixes = (*prefixes, constants.SYSTEM_TAG_PREFIX) return pa.schema( [ field.with_nullable(True) if field.name.startswith(prefixes) else field @@ -646,8 +649,9 @@ def _check_settled_token_types( def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: """The record batches of the output tables, holding ``output_columns``. - Every system-tag and source-info field is declared nullable: the complete - table's values decide those flags (``StaticOutputOperatorPod._flag_by_values``). + A source-info field is nullable until the complete table settles its flag + (``StaticOutputOperatorPod._flag_by_values``). System tags keep the field + from the kernel so Join's sorted tags retain their non-nullable declaration. """ batches: list[pa.RecordBatch] = [] for table in tables: @@ -655,7 +659,8 @@ def _emitted(self, tables: list[pa.Table]) -> list[pa.RecordBatch]: self._emitted_any = True table = table.select(list(self.output_columns)).combine_chunks() table = pa.Table.from_arrays( - table.columns, schema=_settled_by_values(table.schema) + table.columns, + schema=_settled_by_values(table.schema, system_tags=False), ) batches.extend(table.to_batches()) return batches diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f05485472..c31370727 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -9,6 +9,7 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + require_supported_nullable_types, ) from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -109,6 +110,7 @@ def __init__( tag_columns = _normalize_column_list(tag_columns) if infer_nullable: + require_supported_nullable_types(table.schema) logger.debug( "infer_nullable=True: deriving nullable flags from data " "(nullable=True only for columns with null_count > 0)" diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 55065699b..15501c76c 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -14,6 +14,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id +from orcapod.core.sources.stream_builder import require_supported_nullable_types from orcapod.errors import ( CachedSourceIdMismatchError, InputValidationError, @@ -269,7 +270,10 @@ def source_name(self) -> str: def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": """The wrapped source's Arrow schemas: the cache stores that source's rows.""" - return typed_arrow_schemas(self._source) + schemas = typed_arrow_schemas(self._source) + for schema in schemas: + require_supported_nullable_types(schema) + return schemas # ------------------------------------------------------------------------- # Cache path — scoped to source's content hash @@ -357,7 +361,15 @@ def _live_records(self) -> pa.Table: refuse_restricted_cache_input(self._source) require_same_data_context(self._source.data_context_key, self.data_context_key) live_table = self._source.as_table( - columns={"source": True, "system_tags": True} + columns={"source": True, "system_tags": True, "meta": True} + ) + require_supported_nullable_types(live_table.schema) + live_table = live_table.drop( + [ + name + for name in live_table.column_names + if name.startswith(constants.META_PREFIX) + ] ) # Compute per-row record hashes for dedup: hash the full row including @@ -519,6 +531,7 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": ) if records is None: return None + require_supported_nullable_types(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) if records.num_rows < stored_rows and not self._skipped_rows_reported: @@ -669,6 +682,7 @@ def _empty_table(self) -> pa.Table: merged.update(data_schema) type_converter = self.data_context.type_converter arrow_schema = type_converter.python_schema_to_arrow_schema(merged) + require_supported_nullable_types(arrow_schema) return pa.Table.from_pylist([], schema=arrow_schema) @property @@ -716,7 +730,10 @@ def _typed_zero_row_table(self) -> "pa.Table | None": See ``typed_zero_row_table``; neither the cache nor the source is read. """ - return typed_zero_row_table(self._source) + table = typed_zero_row_table(self._source) + if table is not None: + require_supported_nullable_types(table.schema) + return table def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the wrapped source.""" diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index f39681d9e..e6d087c68 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -18,6 +18,8 @@ normalize_record_id_columns, SourceStreamBuilder, SourceStreamResult, + require_custom_system_tags, + require_supported_nullable_types, ) from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -119,7 +121,9 @@ def _refuse_overflow(values: pa.ChunkedArray[Any], texts: pa.ChunkedArray[Any]) ) -def _read_declared(path: str, schema: pa.Schema) -> pa.Table: +def _read_declared( + path: str, schema: pa.Schema, system_tag_columns: Collection[str] +) -> 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 @@ -246,7 +250,8 @@ 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 ) - # A null in a non-nullable field raises here, naming the field. + require_custom_system_tags(table, system_tag_columns, schema=schema) + # A null in an ordinary non-nullable field raises here, naming the field. return table.cast(schema) @@ -343,9 +348,13 @@ def _read_table(self) -> pa.Table: if self._schema is None: table: pa.Table = pa_csv.read_csv(self._access_path) + require_supported_nullable_types(table.schema) return table.cast(arrow_utils.infer_schema_nullable(table)) + require_supported_nullable_types(self._schema) try: - return _read_declared(self._access_path, self._schema) + return _read_declared( + self._access_path, self._schema, self._system_tag_columns + ) 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). diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6c65bf64d..54a563f88 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -12,6 +12,8 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + require_custom_system_tags, + require_supported_nullable_types, ) from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -78,6 +80,9 @@ def __init__( tag_columns = _normalize_column_list(tag_columns) + require_supported_nullable_types( + polars_data_utils.get_system_columns(df).to_arrow().schema + ) df = polars_data_utils.drop_system_columns(df) missing = set(tag_columns) - set(df.columns) @@ -86,10 +91,13 @@ def __init__( arrow_table = df.to_arrow() if schema is not None: + require_supported_nullable_types(schema) + require_custom_system_tags(arrow_table, system_tag_columns, schema=schema) arrow_table = arrow_table.cast(schema) else: # Polars defaults all fields to nullable=True; infer the correct # flags from the actual data before passing to the builder. + require_supported_nullable_types(arrow_table.schema) arrow_table = arrow_table.cast( arrow_utils.infer_schema_nullable(arrow_table) ) diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 86ea349d5..55f0c82b7 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -26,6 +26,7 @@ from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import keep_nullable_columns, same_rows from orcapod.core.sources.stream_builder import ( + require_supported_nullable_types, normalize_record_id_columns, SourceStreamBuilder, SourceStreamResult, @@ -245,6 +246,7 @@ def _read_table( # No column info available — fall back to inferring nullable flags # from actual data so columns without nulls are not spuriously marked # nullable=True (Arrow's default). + 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) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1c4a57228..dfaa6fceb 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -19,6 +19,7 @@ from orcapod.core.sources.reload import same_rows from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( + require_supported_nullable_types, SourceStreamBuilder, normalize_record_id_columns, ) @@ -486,6 +487,7 @@ def _origin_records(self) -> "pa.Table | None": records = self._origin.get_all_records() if records is None: return None + require_supported_nullable_types(records.schema) try: stored = stored_data_tags(records.schema) except ValueError as exc: @@ -542,13 +544,16 @@ def _empty_origin_table(self) -> "pa.Table": names = list(dict.fromkeys([*tag_keys, *data_keys])) typed = typed_zero_row_table(self._origin) if isinstance(typed, pa.Table): + require_supported_nullable_types(typed.schema) return typed.select(names) # An origin that cannot type its zero-row table states its Arrow types (a # read-only loaded operator, from its saved text), or gives its declared # Python schema, converted (``typed_arrow_schemas``). tag_arrow, data_arrow = typed_arrow_schemas(self._origin) fields = {field.name: field for field in (*tag_arrow, *data_arrow)} - return pa.schema([fields[name] for name in names]).empty_table() + schema = pa.schema([fields[name] for name in names]) + require_supported_nullable_types(schema) + return schema.empty_table() def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": """This source's Arrow schemas: its origin's columns (ITL-640). @@ -796,6 +801,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) + require_supported_nullable_types(table.schema) return ArrowTableStream( table, 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 fdf7c1f34..d45d68a92 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -10,6 +10,7 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + require_supported_nullable_types, ) from orcapod.types import DataValue, SchemaLike from orcapod.utils import arrow_utils @@ -64,6 +65,7 @@ def __init__( # pa.Schema directly via data_schema; route to the converter accordingly. rows = [dict(row) for row in data] if isinstance(data_schema, pa.Schema): + require_supported_nullable_types(data_schema) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, arrow_schema=data_schema, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index de4cd3e1e..3b4f65398 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -28,6 +28,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + require_supported_nullable_types, ) from orcapod.core.streams.view import ( ViewStatus, @@ -45,7 +46,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Cursor, PollingConfig, Schema -from orcapod.utils import arrow_utils, polars_data_utils +from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.utils.schema_utils import ( _normalize_column_list, @@ -329,6 +330,7 @@ def __init__( self._declared_arrow: pa.Schema | None = None unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): + require_supported_nullable_types(unified_schema) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). self._declared_arrow = declaration_form_schema( @@ -366,6 +368,7 @@ def __init__( self._declared_arrow = declared_arrow_schema( unified_schema, self.data_context.type_converter ) + require_supported_nullable_types(self._declared_arrow) # ------------------------------------------------------------------------- # Schema helpers — fetch-free schema computation from declared schemas @@ -558,6 +561,7 @@ def _typed_zero_row_table(self) -> pa.Table | None: table = typed_zero_row_table(batch) if table is None: return None + require_supported_nullable_types(table.schema) zero_rows = ArrowTableStream(table=table, tag_columns=self._tag_columns) result = zero_rows if result is None else self._combine(result, zero_rows) return typed_zero_row_table(result) @@ -895,9 +899,9 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: ) df = df.with_columns([pl.from_arrow(c) for c in sub_table]) - df = polars_data_utils.drop_system_columns(df) - - arrow_table = df.to_arrow() + raw = df.to_arrow() + require_supported_nullable_types(raw.schema) + arrow_table = arrow_utils.drop_system_columns(raw) # Establish canonical schema on first call; apply it on every call. if self._canonical_arrow_schema is None: @@ -1080,6 +1084,7 @@ def _combine( ], promote_options="default", ) + require_supported_nullable_types(combined.schema) return ArrowTableStream(table=combined, tag_columns=self._tag_columns) def _mark_new_rows(self, committed: ArrowTableStream | None) -> bool: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8d534e5a3..8663987c6 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -56,6 +56,8 @@ from orcapod.core.sources.source_ids import joined_location, location_source_name from orcapod.core.sources.derived_source import validate_tags_as_data from orcapod.core.sources.stream_builder import ( + require_custom_system_tags, + require_supported_nullable_types, SourceStreamBuilder, key_column_type_allowed, normalize_record_id_columns, @@ -383,6 +385,7 @@ def __init__( ) self._table_id = table.table_id schema = table.arrow_schema() + 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. self._asof = asof if asof is not None else (table.version() or None) @@ -892,9 +895,10 @@ def _read_batches( asof=asof, ): for start in range(0, batch.num_rows, self._batch_rows): - rows = arrow_utils.drop_system_columns( - pa.Table.from_batches([batch.slice(start, self._batch_rows)]) - ) + raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)]) + require_supported_nullable_types(raw.schema) + rows = arrow_utils.drop_system_columns(raw) + require_custom_system_tags(rows, self._system_tag_columns) # Metadata too: field metadata is how a column's logical type is # recorded, and the schema hash was computed at construction. if not rows.schema.equals(self._table_schema, check_metadata=True): diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 5fbb8eb52..f9097ec7f 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -23,7 +23,7 @@ require_source_name, ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.errors import RowIdentifierError +from orcapod.errors import InputValidationError, RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.system_constants import constants from orcapod.types import ContentHash @@ -36,6 +36,73 @@ from orcapod.protocols.hashing_protocols import ArrowHasherProtocol +def _contains_null_type(arrow_type: pa.DataType) -> bool: + """Return whether an Arrow type contains the Null type at any depth.""" + if isinstance(arrow_type, pa.BaseExtensionType): + return _contains_null_type(arrow_type.storage_type) + if pa.types.is_dictionary(arrow_type): + return _contains_null_type(arrow_type.value_type) + return pa.types.is_null(arrow_type) or any( + _contains_null_type(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + +def require_supported_nullable_types(schema: pa.Schema) -> None: + """Refuse source columns containing the Arrow Null type, even with zero rows.""" + columns = sorted( + (field.name, str(field.type)) + for field in schema + if _contains_null_type(field.type) + ) + if columns: + names = ", ".join(f"{name!r} ({arrow_type})" for name, arrow_type in columns) + raise InputValidationError( + f"Source column(s) {names} contain Arrow type null. " + "Please declare a supported nullable type." + ) + + +def require_custom_system_tags( + table: pa.Table, + names: Collection[str], + *, + schema: pa.Schema | None = None, +) -> None: + """Validate custom system-tag types, field flags and values before wrapping. + + 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. + + Raises: + InputValidationError: If a nominated column is not non-nullable text. + """ + fields = table.schema if schema is None else schema + for name in names: + if name not in table.column_names or name not in fields.names: + continue + field = fields.field(name) + has_nulls = table.column(name).null_count > 0 + if ( + field.nullable + or 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"({'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 normalize_record_id_columns( record_id_columns: str | Collection[str] | None, ) -> tuple[str, ...] | None: @@ -455,6 +522,7 @@ def build( ) tag_columns_tuple = tuple(tag_columns) system_tag_columns_tuple = tuple(system_tag_columns) + 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): raise ValueError( @@ -487,6 +555,7 @@ def build( # 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 diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 88f4010bd..689588eae 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1755,24 +1755,18 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": # Replace columns with sorted values for pos_idx, (sid_col, rid_col) in enumerate(paired_cols): - if sid_col: - orig_type = table.column(sid_col).type - tbl_idx = table.column_names.index(sid_col) - table = table.drop(sid_col) - table = table.add_column( - tbl_idx, - sid_col, - pa.array(sorted_sid[pos_idx], type=orig_type), - ) - if rid_col: - orig_type = table.column(rid_col).type - tbl_idx = table.column_names.index(rid_col) - table = table.drop(rid_col) - table = table.add_column( - tbl_idx, - rid_col, - pa.array(sorted_rid[pos_idx], type=orig_type), - ) + 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=False + ) + table = table.set_column( + index, field, pa.array(values, type=field.type) + ) return table diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index d444c445f..1a6a54096 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -753,6 +753,25 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: ), ), ), + Case( + "ref_join_4_three_tied", + Join, + lambda: ( + *( + _source( + { + "k": pa.array([1, 2, 3], pa.int16()), + "g": pa.array(["x", "y", "x"], pa.large_string()), + }, + ("k", "g"), + name, + with_data_tags=True, + ) + for name in ("p", "q", "r") + ), + source_b(with_data_tags=True), + ), + ), Case( # The group key's merged token, merged again by the join (ITL-1017). "ref_join_after_group_by", diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 4aad0842d..5b3bf6e9c 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -78,7 +78,6 @@ def _arranged(spec: Spec, variant: str, roles: str) -> ArrowTableSource: SEEDS = range(12) # The fields whose flags a complete table decides by its values. -SETTLED_PREFIXES = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) # Batch sizes drawn for the cuts: empty and one-row batches included. SIZES = (0, 1, 1, 2, 3, 5, 64) @@ -228,11 +227,11 @@ def assert_same_rows( """ for batch in batches: assert batch.schema.names == list(kernel.output_columns) - # One schema for every batch of the run; the fields a complete table decides - # by its values are declared nullable (``_flag_by_values`` settles them). + # One schema for every batch of the run. The complete table settles the + # source-info flags. Join has already settled its sorted system tags. assert batch.schema.equals(batches[0].schema, check_metadata=True) for field in batch.schema: - if field.name.startswith(SETTLED_PREFIXES): + if field.name.startswith(constants.SOURCE_PREFIX): assert field.nullable, field.name got = ( pa.Table.from_batches(batches) @@ -823,9 +822,6 @@ def test_a_null_typed_input_that_ends_empty_is_read_in_its_zero_row_form() -> No def test_merge_join_over_a_join_of_inputs_of_one_pipeline_hash() -> None: - # A Join of inputs tied on pipeline hash declares its system tags nullable; a table - # built from its rows flags them by their values. MergeJoin over it, in the kernel, - # declares them nullable and the complete table settles them as the sync path's. def tied(source_id: str, keys: list[int], groups: list[str]) -> ArrowTableSource: return ArrowTableSource( pa.table( @@ -840,12 +836,58 @@ def tied(source_id: str, keys: list[int], groups: list[str]) -> ArrowTableSource source_id=source_id, ) - joined = Join()( + tied_inputs = ( tied("a", [1, 2, 3], ["x", "y", "x"]), tied("b", [2, 1, 3], ["y", "x", "x"]), tied("c", [3, 2, 1], ["x", "y", "x"]), ) - other = _keyed_source("o", "int", 6, {"z": pa.int64()}, 4) + other = _keyed_source("o", "int", 6, {"z": pa.int64(), "w": pa.int8()}, 4) + assert len({source.pipeline_hash() for source in tied_inputs}) == 1 + columns = {"system_tags": True} + operator = Join() + expected_values = None + for ordered in itertools.permutations(tied_inputs): + inputs = (*ordered, other) + joined = operator(*inputs) + computed = operator.static_process(*inputs) + table = joined.as_table(columns=columns) + prediction = joined.output_schema(columns=columns) + assert prediction == computed.output_schema(columns=columns) + tag_schema, _ = prediction + names = [ + name for name in tag_schema if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + assert len(names) == 8 + fields = table.select(names).schema + assert all( + field.type == pa.large_string() and not field.nullable for field in fields + ) + assert all( + tag.as_table(columns=columns).select(names).schema == fields + for tag, _ in joined.iter_data() + ) + values = table.sort_by("k").select(names).to_pylist() + if expected_values is None: + expected_values = values + assert values == expected_values + + kernel = StreamingJoin(operator, inputs) + zero = kernel.zero_row_result.as_table(columns=columns) + assert zero.num_rows == 0 + assert zero.select(names).schema == fields + out = [] + for i, source in enumerate(inputs): + for batch in _sent(source).to_batches(): + out.extend(kernel.push(i, batch)) + assert out + tied_hash = tied_inputs[0].pipeline_hash().to_hex() + tied_names = [name for name in names if f"::{tied_hash}:" in name] + assert len(tied_names) == 6 + emitted = pa.Table.from_batches(out).sort_by("k").select(tied_names) + assert emitted.schema == table.select(tied_names).schema + assert emitted.to_pylist() == table.sort_by("k").select(tied_names).to_pylist() + + joined = operator(*tied_inputs) for inputs in ((joined, other), (other, joined)): _check(_merge_kernel, MergeJoin().static_process, inputs) _check(_join_kernel, Join().static_process, inputs, seeds=range(4)) @@ -1027,20 +1069,42 @@ def test_an_empty_run_ends_with_the_types_of_the_sync_result( assert_same_rows(out, instance, want) -def test_a_source_refuses_a_null_typed_column() -> None: - # The kernels' domain is what a job carries (module docstring): no source takes a - # ``null``-typed column, with rows or without, tag or data. - for table, tags in ( - (pa.table({"k": [1], "x": pa.array([None], pa.null())}), ["k"]), - (pa.table({"k": pa.array([None], pa.null()), "x": [1]}), ["k"]), - ( - pa.table({"k": pa.array([], pa.int64()), "x": pa.array([], pa.null())}), - ["k"], - ), - ): - with pytest.raises(ValueError, match="type null"): +@pytest.mark.parametrize("row_count", [0, 2]) +@pytest.mark.parametrize("column", ["k", "x", "__unused"]) +@pytest.mark.parametrize( + "bad_type", + [ + pa.null(), + pa.large_list(pa.null()), + pa.struct([("child", pa.null())]), + ], +) +def test_a_source_refuses_a_null_typed_column( + row_count: int, column: str, bad_type: pa.DataType +) -> None: + arrays: dict[str, pa.Array[Any]] = { + "k": pa.array([1] * row_count, pa.int64()), + "g": pa.array(["group"] * row_count, pa.large_string()), + "x": pa.array([2] * row_count, pa.int64()), + "y": pa.array([3] * row_count, pa.int64()), + } + fields: dict[str, pa.Field[Any]] = { + name: pa.field(name, values.type, nullable=False) + for name, values in arrays.items() + } + arrays[column] = pa.array([None] * row_count, type=bad_type) + fields[column] = pa.field(column, bad_type) + for order in (list(fields), list(reversed(fields))): + table = pa.Table.from_arrays( + [arrays[name] for name in order], + schema=pa.schema([fields[name] for name in order]), + ) + with pytest.raises( + InputValidationError, + match=rf"{column!r}.*declare a supported nullable type", + ): ArrowTableSource( - table, tag_columns=tags, tag_only_columns=True, source_id="s" + table, tag_columns=["k", "g"], tag_only_columns=True, source_id="s" ) diff --git a/tests/test_core/sources/test_db_table_source.py b/tests/test_core/sources/test_db_table_source.py index 0b37f6180..a0e704989 100644 --- a/tests/test_core/sources/test_db_table_source.py +++ b/tests/test_core/sources/test_db_table_source.py @@ -523,7 +523,19 @@ 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): + 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", @@ -532,7 +544,7 @@ def test_to_config_system_tag_columns_preserved(self, connector): tag_only_columns=True, ) config = src.to_config() - assert "system_tag_columns" in config + assert config["system_tag_columns"] == ["session_id"] class TestQueryOverride: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py new file mode 100644 index 000000000..72c105e0f --- /dev/null +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -0,0 +1,399 @@ +"""Source boundaries validate Arrow Null and explicitly nominated system tags.""" + +from __future__ import annotations + +import sqlite3 +from collections.abc import Collection +from pathlib import Path +from typing import Any, TypedDict + +import deltalake +import polars as pl +import pyarrow as pa +import pyarrow.csv as pa_csv +import pytest + +from orcapod import PipelineJob +from orcapod.contexts.stored import with_data_context +from orcapod.core.sources import ( + ArrowTableSource, + CachedSource, + CSVSource, + DBTableSource, + DataFrameSource, + DeltaTableSource, + DictSource, + ListSource, + PollingSource, + PostgreSQLTableSource, + SpiralDBTableSource, + SQLiteTableSource, +) +from orcapod.core.sources.source_proxy import SourceProxy +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError +from orcapod.operators import DropNulls +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.types import ColumnInfo, Cursor +from tests.test_core.sources.test_db_table_source import MockDBConnector +from tests.test_databases import fake_spiral_sdk + +TAGS = ("g", "k") +SOURCE_KINDS = ( + "arrow", + "dict", + "dataframe", + "csv", + "delta", + "db", + "postgres", + "spiral", + "sqlite", +) + + +class _SourceOptions(TypedDict): + """Keyword arguments supported by the sources in the validation matrix.""" + + tag_columns: Collection[str] + tag_only_columns: bool + source_id: str + system_tag_columns: Collection[str] + + +class _Connector(MockDBConnector): + """Mock connector exposing the declared flags of an Arrow table.""" + + def __init__(self, table: pa.Table) -> None: + super().__init__({"rows": table}, {"rows": ["k"]}) + self.table = table + + def get_column_info(self, table_name: str) -> list[ColumnInfo]: + """Return the database's field declarations.""" + return [ + ColumnInfo(info.name, info.arrow_type, field.nullable) + for info, field in zip( + super().get_column_info(table_name), + self.table.schema, + strict=True, + ) + ] + + def current_location(self) -> tuple[str, int, str, str]: + """Return the connected server's canonical location.""" + return "localhost", 5432, "test", "public" + + def given_server(self) -> tuple[str, str]: + """Return the server specified in the connection string.""" + return "localhost", "" + + +def _source( + kind: str, + table: pa.Table, + path: Path, + monkeypatch: pytest.MonkeyPatch, + *, + system_tag_columns: Collection[str] = (), +) -> StreamProtocol: + """Build the named source over the same columns using its regular reader.""" + options: _SourceOptions = { + "tag_columns": TAGS, + "tag_only_columns": True, + "source_id": "rows", + "system_tag_columns": system_tag_columns, + } + if kind == "arrow": + return ArrowTableSource(table, **options) + if kind == "dict": + return DictSource(table.to_pylist(), data_schema=table.schema, **options) + if kind == "dataframe": + return DataFrameSource(pl.from_arrow(table), schema=table.schema, **options) + if kind == "csv": + file = path / "rows.csv" + pa_csv.write_csv(table, file) + return CSVSource(str(file), schema=table.schema, **options) + if kind == "delta": + deltalake.write_deltalake(path / "delta", table) + return DeltaTableSource(path / "delta", **options) + if kind == "sqlite": + 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") + for f in table.schema + ) + with sqlite3.connect(file) as conn: + conn.execute(f"CREATE TABLE rows ({cols}, PRIMARY KEY (k))") + placeholders = ", ".join("?" for _ in table.schema) + conn.executemany( + f"INSERT INTO rows VALUES ({placeholders})", + [tuple(row.values()) for row in table.to_pylist()], + ) + return SQLiteTableSource(file, "rows", **options) + if kind == "spiral": + with fake_spiral_sdk.install(path / "spiral"): + project = fake_spiral_sdk.ExternalProject("project") + project.create_table( + "default.rows", key_schema=pa.schema([table.schema.field("k")]) + ).write(table) + project.table("default.rows").record(table.schema) + return SpiralDBTableSource("project", "rows", **options) + connector = _Connector(table) + if kind == "postgres": + monkeypatch.setattr( + "orcapod.core.sources.postgresql_table_source.PostgreSQLConnector", + lambda *args, **kwargs: connector, + ) + return PostgreSQLTableSource("postgresql://localhost/test", "rows", **options) + assert kind == "db" + return DBTableSource(connector, "rows", **options) + + +def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: + """Two tags, two ordinary data columns and two additional columns.""" + schema = pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("g", pa.string(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.int64(), nullable=False), + pa.field("rev", pa.string(), nullable=False), + field, + ] + ) + return pa.Table.from_pylist( + [ + dict(k=i, g="G", x=2, y=3, rev="r", **{field.name: value}) + for i, value in enumerate(values) + ], + schema=schema, + ) + + +@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) +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, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + column = "unused" if kind == "spiral" else "__unused" + table = _table(pa.field(column, pa.null()), [None, None]) + with pytest.raises( + InputValidationError, match=rf"{column!r}.*declare a supported nullable type" + ): + _source(kind, table, tmp_path, monkeypatch) + + +def test_dataframe_schema_can_type_null_values() -> None: + table = _table(pa.field("extra", pa.null()), [None, None]) + schema = pa.schema( + [f.with_type(pa.string()) if f.name == "extra" else f for f in table.schema] + ) + source = DataFrameSource( + pl.from_arrow(table), schema=schema, tag_columns=TAGS, tag_only_columns=True + ) + assert source.as_table().schema.field("extra") == pa.field( + "extra", pa.large_string() + ) + + +@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: + table = _table(pa.field("extra", pa.string()), [None, None]) + source = _source("sqlite", table, tmp_path, monkeypatch) + assert source.as_table().schema.field("extra") == pa.field( + "extra", pa.large_string() + ) + assert source.as_table().column("extra").to_pylist() == [None, None] + + +def test_list_source_declared_any_does_not_turn_into_a_string() -> None: + with pytest.raises( + InputValidationError, match=r"'x'.*declare a supported nullable type" + ): + ListSource( + "x", [None, None], data_schema={"element_index": int, "x": Any | None} + ) + + +def test_no_declared_type_for_python_none_still_infers_a_string() -> None: + sources = [ + ListSource("x", [None, None]), + DictSource([{"x": None, "y": 1}, {"x": None, "y": 2}]), + ] + for source in sources: + assert source.as_table().schema.field("x") == pa.field("x", pa.large_string()) + + +class _Poll: + """Minimal impl for testing schema validation before the first fetch.""" + + def __init__(self, schema: pa.Schema | None, batch: pl.DataFrame) -> None: + self._schema = schema + self._batch = batch + + def schema(self) -> pa.Schema | None: + """Return the optional Arrow schema.""" + return self._schema + + def identity(self) -> str: + """Return a stable identity for this poll.""" + return "test poll" + + def to_config(self) -> None: + """This implementation holds a test batch in memory.""" + + @classmethod + def from_config(cls, config: dict[str, Any]) -> _Poll: + """Reject loading this in-memory implementation.""" + raise NotImplementedError + + async def fetch( + self, cursor: Cursor[int] | None = None + ) -> tuple[Cursor[int], pl.DataFrame]: + """Return the prepared batch on the initial fetch.""" + return Cursor(value=0), self._batch + + async def poll(self, cursor: Cursor[int] | None = None) -> bool: + """There are no rows after the initial fetch.""" + return False + + async def close(self) -> None: + """There is no connection to close.""" + + +@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) + batch = pl.from_arrow(table) + assert isinstance(batch, pl.DataFrame) + with pytest.raises( + InputValidationError, match=r"'__unused'.*declare a supported nullable type" + ): + PollingSource( + _Poll(table.schema, batch), TAGS, source_id="poll", record_id_columns="k" + ) + poll = PollingSource( + _Poll(None, batch), TAGS, source_id="poll", record_id_columns="k" + ) + with pytest.raises( + InputValidationError, match=r"'__unused'.*declare a supported nullable type" + ): + poll.check_for_new_data() + + +def test_a_raw_arrow_table_stream_preserves_nested_null() -> None: + field = pa.field("extra", pa.large_list(pa.null())) + table = _table(field, [[None], []]) + assert ( + ArrowTableStream(table, tag_columns=TAGS).as_table().schema.field("extra") + == field + ) + + +def test_cached_source_refuses_an_existing_stored_null_column() -> None: + table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) + source = ArrowTableSource( + table, tag_columns=TAGS, tag_only_columns=True, source_id="rows" + ) + tag_schema, data_schema = source.output_schema() + proxy = SourceProxy( + source_id=source.source_id, + content_hash_str=source.content_hash().to_string(), + pipeline_hash_str=source.pipeline_hash().to_string(), + tag_schema=tag_schema, + data_schema=data_schema, + ) + database = InMemoryArrowDatabase() + cached = CachedSource(proxy, cache_database=database) + raw = source.as_table(columns={"source": True, "system_tags": True}) + raw = raw.append_column("__unused", pa.nulls(2)) + raw = raw.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) + database.add_records( + cached.cache_path, + with_data_context(raw, source.data_context_key), + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=True, + ) + with pytest.raises( + InputValidationError, match=r"'__unused'.*declare a supported nullable type" + ): + cached.as_table() + + +@pytest.mark.parametrize("row_count", [0, 2]) +def test_derived_source_refuses_stored_null_in_its_direct_table_view( + row_count: int, monkeypatch: pytest.MonkeyPatch +) -> None: + table = _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]) + source = ArrowTableSource( + table, tag_columns=TAGS, tag_only_columns=True, source_id="rows" + ) + job = PipelineJob(name="derived", database=InMemoryArrowDatabase()) + with job: + DropNulls(["x", "y"])(source, label="origin") + node = job.nodes["origin"] + stored = ( + source.as_table() + .slice(0, row_count) + .append_column("__unused", pa.nulls(row_count)) + ) + monkeypatch.setattr(node, "get_all_records", lambda *args, **kwargs: stored) + derived = node.as_source() + with pytest.raises( + InputValidationError, match=r"'__unused'.*declare a supported nullable type" + ): + derived.as_table() From 08d2c67005130e1a82df06d33c1e596e5b6c5ee3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 15:46:23 -0800 Subject: [PATCH 2/9] fix(sources): reject missing custom system tag columns (ITL-1543) --- changelog.d/ITL-1543.md | 3 ++- src/orcapod/core/sources/stream_builder.py | 13 ++++++++++--- .../sources/test_source_arrow_validation.py | 16 ++++++++++++++++ .../sources/test_sources_comprehensive.py | 6 ++++-- 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/changelog.d/ITL-1543.md b/changelog.d/ITL-1543.md index 109882db9..dcd89ab55 100644 --- a/changelog.d/ITL-1543.md +++ b/changelog.d/ITL-1543.md @@ -3,7 +3,8 @@ - Sources reject Arrow `null` fields at any depth, including in reserved columns. Declare a supported nullable column type for missing values. - A custom system-tag column on a source must be a non-nullable string column - with no null values. Convert custom tags to text before building the source. + with no null values. Sources also reject missing names in `system_tag_columns`. + Convert custom tags to text before building the source. ### Fixed diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index f9097ec7f..b54428354 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -69,7 +69,7 @@ def require_custom_system_tags( *, schema: pa.Schema | None = None, ) -> None: - """Validate custom system-tag types, field flags and values before wrapping. + """Validate custom system-tag names, types, field flags and values. Args: table: The source's Arrow columns. @@ -77,12 +77,19 @@ def require_custom_system_tags( schema: The declared fields if the reader has yet to apply them. Raises: + ValueError: If a nominated column is missing from the source table. InputValidationError: If a nominated column is not non-nullable 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: - if name not in table.column_names or name not in fields.names: - continue field = fields.field(name) has_nulls = table.column(name).null_count > 0 if ( diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 72c105e0f..818a651c5 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -194,6 +194,22 @@ def test_rejects_invalid_custom_system_tag_columns( _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) def test_accepts_two_non_nullable_string_system_tags( kind: str, diff --git a/tests/test_core/sources/test_sources_comprehensive.py b/tests/test_core/sources/test_sources_comprehensive.py index 22e695752..ab21a4661 100644 --- a/tests/test_core/sources/test_sources_comprehensive.py +++ b/tests/test_core/sources/test_sources_comprehensive.py @@ -486,11 +486,13 @@ def test_source_id_controls_provenance_tokens(self): def test_system_tag_columns_forwarded_to_stream(self): """system_tag_columns passed at construction are preserved.""" - table = pa.table({"x": pa.array([1, 2], type=pa.int64())}) + table = pa.table({"x": [1, 2], "sys_col": ["a", "b"]}) src = ArrowTableSource( table=table, system_tag_columns=["sys_col"], infer_nullable=True ) - assert "sys_col" in src._system_tag_columns + 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 969ed0936ccbbb0357cb02891fdf5e5134e20c7a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 15:59:46 -0800 Subject: [PATCH 3/9] fix(arrow): honor Join field declarations and validate raw source reads (ITL-1543) --- .zed/rules | 4 +- CLAUDE.md | 4 +- changelog.d/ITL-1543.md | 6 +- src/orcapod/core/operators/join.py | 19 +++- src/orcapod/core/operators/streaming_joins.py | 28 ++++- src/orcapod/core/sources/derived_source.py | 12 +- .../core/sources/spiraldb_table_source.py | 17 ++- src/orcapod/utils/arrow_utils.py | 54 ++++++--- .../operators/test_streaming_joins.py | 63 ++++++++++- .../sources/test_source_arrow_validation.py | 104 +++++++++++++++++- 10 files changed, 274 insertions(+), 37 deletions(-) diff --git a/.zed/rules b/.zed/rules index 470dbb27d..987b73fd3 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1344,7 +1344,9 @@ 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. - Custom system-tag columns on a source must be non-nullable text and contain no null values. + A source's custom system-tag names must each identify an existing non-nullable text + column with no null values. When Join sorts tied system tags, an output field is + nullable if any of the corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. A row built by `Data` still gives an untyped null the `large_string` type. PolarsFilter is the one operator that still round-trips its columns through Polars; it diff --git a/CLAUDE.md b/CLAUDE.md index 1a54c33b5..0c732eed0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1392,7 +1392,9 @@ 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. - Custom system-tag columns on a source must be non-nullable text and contain no null values. + A source's custom system-tag names must each identify an existing non-nullable text + column with no null values. When Join sorts tied system tags, an output field is + nullable if any of the corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. A row built by `Data` still gives an untyped null the `large_string` type. `PolarsFilter` is the one operator that still round-trips its columns through Polars; it diff --git a/changelog.d/ITL-1543.md b/changelog.d/ITL-1543.md index dcd89ab55..5c5313a53 100644 --- a/changelog.d/ITL-1543.md +++ b/changelog.d/ITL-1543.md @@ -8,5 +8,7 @@ ### Fixed -- Join declares sorted system tags non-nullable when its inputs tie on pipeline - hash. Existing entry IDs, instance IDs, record IDs and operator hashes stay the same. +- Join uses the declared fields of inputs tied on pipeline hash to set the + sorted system tags' nullability. The tag is non-nullable when every + corresponding input field is non-nullable. Existing entry IDs, instance IDs, + record IDs and operator hashes for source inputs stay the same. diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 430957232..06cdcfd26 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -3,7 +3,7 @@ import itertools import json from collections.abc import Callable, Collection, Mapping, Sequence -from typing import Any, ClassVar +from typing import Any, ClassVar, get_args import polars as pl import pyarrow as pa @@ -44,7 +44,7 @@ TagProtocol, ) from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, ContentHash, DataValue, Schema +from orcapod.types import ColumnConfig, ContentHash, DataType, DataValue, Schema from orcapod.utils import arrow_utils, schema_utils # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a @@ -422,7 +422,7 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: n_char = self.orcapod_config.hashing.system_tag_n_char ordered_streams = self.order_input_streams(*streams) - system_tag_fields: dict[str, type] = {} + system_tag_fields: dict[str, DataType] = {} for idx, stream in enumerate(ordered_streams): stream_tag_schema, _ = stream.output_schema(columns={"system_tags": True}) for col_name, col_type in stream_tag_schema.items(): @@ -432,7 +432,18 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: f"{stream.pipeline_hash().to_hex(n_char)}:{idx}" ) system_tag_fields[new_name] = col_type - return Schema(system_tag_fields) + 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() + } + ) + return Schema( + { + name: kind | None if nullable[name] else kind + for name, kind in system_tag_fields.items() + } + ) def static_process(self, *streams: StreamProtocol) -> StreamProtocol: """Join the streams on their shared tag columns. diff --git a/src/orcapod/core/operators/streaming_joins.py b/src/orcapod/core/operators/streaming_joins.py index 3d2f6b766..fae5beed5 100644 --- a/src/orcapod/core/operators/streaming_joins.py +++ b/src/orcapod/core/operators/streaming_joins.py @@ -148,7 +148,9 @@ def _settled_by_values(schema: pa.Schema, *, system_tags: bool = True) -> pa.Sch ) -def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: +def _row_built_zero_rows( + stream: StreamProtocol, *, keep_system_tag_flags: bool = False +) -> 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 @@ -156,6 +158,7 @@ def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: Args: stream: An input stream (its description). + keep_system_tag_flags: Use the input's declared system-tag nullability. Returns: The zero-row stream in the row-built form, and whether its Arrow types differ @@ -166,6 +169,14 @@ def _row_built_zero_rows(stream: StreamProtocol) -> tuple[StreamProtocol, bool]: 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 = pod._flag_by_values(row_built_columns(table, stream.keys())) # pyright: ignore[reportPrivateUsage] # F's last step + if keep_system_tag_flags: + fields = [ + field.with_nullable(table.schema.field(field.name).nullable) + 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 ) @@ -413,6 +424,7 @@ class StreamingJoinKernel(ABC): # How many inputs the operator takes; ``None`` for one or more. ARITY: ClassVar[int | None] = None + KEEP_SYSTEM_TAG_FLAGS: ClassVar[bool] = False def __init__( self, operator: StaticOutputOperatorPod, inputs: Sequence[StreamProtocol] @@ -427,13 +439,21 @@ 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) for stream in self.inputs] + built = [ + _row_built_zero_rows( + stream, keep_system_tag_flags=self.KEEP_SYSTEM_TAG_FLAGS + ) + 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) # The schema of every batch of an input, in its row-built layout; the fields a # complete table decides by values declared nullable. self._layouts: tuple[pa.Schema, ...] = tuple( - _settled_by_values(stream.as_table(columns=TRANSPORT_COLUMNS).schema) + _settled_by_values( + stream.as_table(columns=TRANSPORT_COLUMNS).schema, + system_tags=not self.KEEP_SYSTEM_TAG_FLAGS, + ) for stream in self._zero_rows ) self._closed: list[bool] = [False] * len(self.inputs) @@ -687,6 +707,8 @@ class StreamingJoin(StreamingJoinKernel): inputs: Its input streams, in call order. """ + KEEP_SYSTEM_TAG_FLAGS: ClassVar[bool] = True + def __init__(self, operator: Join, inputs: Sequence[StreamProtocol]) -> None: super().__init__(operator, inputs) self._join = operator diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index dfaa6fceb..aeef4bfd5 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -37,7 +37,7 @@ from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import schema_utils +from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: @@ -484,10 +484,18 @@ def _origin_records(self) -> "pa.Table | None": """ if isinstance(self._origin, RootSource): return self._origin.as_table() - records = self._origin.get_all_records() + records = self._origin.get_all_records(all_info=True) if records is None: return None require_supported_nullable_types(records.schema) + records = arrow_utils.drop_columns_with_prefix( + records, + ( + constants.META_PREFIX, + constants.SOURCE_PREFIX, + constants.SYSTEM_TAG_PREFIX, + ), + ) try: stored = stored_data_tags(records.schema) except ValueError as exc: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8663987c6..5464a8837 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -428,7 +428,11 @@ def __init__( tag_columns=resolved_tags, source_name=self._source_name, kind_part=self.kind_part(), - system_tag_columns=system_tag_columns, + 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: @@ -454,7 +458,7 @@ def __init__( tag_columns=template.tag_columns, source_name=self._source_name, kind_part=self.kind_part(), - system_tag_columns=template.system_tag_columns, + system_tag_columns=system_tag_columns, data_tags=self._data_tags, ) self._stream = template.stream @@ -894,11 +898,10 @@ def _read_batches( limit=limit, asof=asof, ): - for start in range(0, batch.num_rows, self._batch_rows): + 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_supported_nullable_types(raw.schema) rows = arrow_utils.drop_system_columns(raw) - require_custom_system_tags(rows, self._system_tag_columns) # Metadata too: field metadata is how a column's logical type is # recorded, and the schema hash was computed at construction. if not rows.schema.equals(self._table_schema, check_metadata=True): @@ -921,9 +924,13 @@ def _read_batches( f"{sorted(repeated)[0]} appears in two rows; key values " "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( - self._with_tag_copies(rows), + rows, tag_columns=self._tag_columns, system_tag_columns=self._system_tag_columns, schema_hash=self._schema_hash, diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 689588eae..c49d1f429 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1665,6 +1665,41 @@ def _parse_system_tag_column( 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. @@ -1688,17 +1723,10 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": if not sys_tag_cols: return table - # Parse all system tag columns and group by provenance_path - # groups[provenance_path][position] = {field_type: col_name} - groups: dict[str, dict[str, dict[str, str]]] = {} - for col in sys_tag_cols: - parsed = _parse_system_tag_column(col) - if parsed is None: - continue - field_type, provenance_path, position = parsed - groups.setdefault(provenance_path, {}).setdefault(position, {})[field_type] = ( - col - ) + 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) : @@ -1708,7 +1736,7 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": ] # For each provenance_path group with >1 position, sort paired tuples per row - for provenance_path, positions in groups.items(): + for positions in groups.values(): if len(positions) <= 1: continue @@ -1762,7 +1790,7 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": if name is not None: index = table.schema.get_field_index(name) field = pa.field( - name, table.schema.field(index).type, nullable=False + name, table.schema.field(index).type, nullable=nullable[name] ) table = table.set_column( index, field, pa.array(values, type=field.type) diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 5b3bf6e9c..8422ffbb5 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -34,6 +34,7 @@ from typing import Any import pyarrow as pa +import pyarrow.parquet as pq import pytest from orcapod.core.operators import Join, MergeJoin, SemiJoin @@ -846,8 +847,7 @@ def tied(source_id: str, keys: list[int], groups: list[str]) -> ArrowTableSource columns = {"system_tags": True} operator = Join() expected_values = None - for ordered in itertools.permutations(tied_inputs): - inputs = (*ordered, other) + for inputs in itertools.permutations((*tied_inputs, other)): joined = operator(*inputs) computed = operator.static_process(*inputs) table = joined.as_table(columns=columns) @@ -883,9 +883,9 @@ def tied(source_id: str, keys: list[int], groups: list[str]) -> ArrowTableSource tied_hash = tied_inputs[0].pipeline_hash().to_hex() tied_names = [name for name in names if f"::{tied_hash}:" in name] assert len(tied_names) == 6 - emitted = pa.Table.from_batches(out).sort_by("k").select(tied_names) - assert emitted.schema == table.select(tied_names).schema - assert emitted.to_pylist() == table.sort_by("k").select(tied_names).to_pylist() + emitted = pa.Table.from_batches(out).sort_by("k").select(names) + assert emitted.schema == fields + assert emitted.to_pylist() == values joined = operator(*tied_inputs) for inputs in ((joined, other), (other, joined)): @@ -893,6 +893,59 @@ def tied(source_id: str, keys: list[int], groups: list[str]) -> ArrowTableSource _check(_join_kernel, Join().static_process, inputs, seeds=range(4)) +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), + ] + ) + inputs = tuple( + ArrowTableStream( + pa.Table.from_arrays( + [ + pa.array([1]), + pa.array([source], pa.large_string()), + pa.array([record], pa.large_string()), + ], + schema=schema, + ), + tag_columns=["k"], + data_tags=["k"], + ) + for source, record in (("a", None), ("b", "r"), ("c", "s")) + ) + assert len({stream.pipeline_hash() for stream in inputs}) == 1 + columns = {"system_tags": True} + for ordered in itertools.permutations(inputs): + operator = Join() + joined = operator(*ordered) + expected = joined.as_table(columns=columns) + record_fields = [ + f for f in expected.schema if f.name.startswith("_tag_record_id") + ] + assert len(record_fields) == 3 + assert all(f.nullable for f in record_fields) + pq.write_table(expected, pa.BufferOutputStream()) + assert joined.output_schema(columns=columns) == operator.static_process( + *ordered + ).output_schema(columns=columns) + kernel = StreamingJoin(operator, ordered) + names = expected.column_names + assert ( + kernel.zero_row_result.as_table(columns=columns).select(names).schema + == expected.schema + ) + emitted = [ + result + for i, stream in enumerate(ordered) + for batch in _transport(stream).to_batches() + for result in kernel.push(i, batch) + ] + assert pa.Table.from_batches(emitted).select(names).equals(expected) + + # --------------------------------------------------------------------------- # A refusal that depends on values is raised when its batch arrives # --------------------------------------------------------------------------- diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 818a651c5..ff7f5d0b2 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -15,6 +15,7 @@ from orcapod import PipelineJob from orcapod.contexts.stored import with_data_context +from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.sources import ( ArrowTableSource, CachedSource, @@ -35,7 +36,7 @@ from orcapod.errors import InputValidationError from orcapod.operators import DropNulls from orcapod.protocols.core_protocols import StreamProtocol -from orcapod.types import ColumnInfo, Cursor +from orcapod.types import CacheMode, ColumnInfo, Cursor from tests.test_core.sources.test_db_table_source import MockDBConnector from tests.test_databases import fake_spiral_sdk @@ -413,3 +414,104 @@ def test_derived_source_refuses_stored_null_in_its_direct_table_view( InputValidationError, match=r"'__unused'.*declare a supported nullable type" ): derived.as_table() + + +@pytest.mark.parametrize("copy_tags", [False, True]) +def test_derived_source_checks_reserved_columns_before_filtering_storage( + copy_tags: bool, +) -> None: + class NullMetadataStore(InMemoryArrowDatabase): + """Inject a reserved Arrow Null column at the database read boundary.""" + + def get_all_records( + self, record_path: tuple[str, ...], *args: Any, **kwargs: Any + ) -> pa.Table | None: + """Add a reserved column to the stored operator table.""" + table = super().get_all_records(record_path, *args, **kwargs) + if table is not None and record_path[-1] == "odb_v2": + return table.append_column("__raw_missing", pa.nulls(table.num_rows)) + return table + + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + store = NullMetadataStore() + job = PipelineJob(name="derived", database=store) + with job: + DropNulls(["x", "y"])(source, label="origin") + node = job.nodes["origin"] + assert isinstance(node, OperatorJobNode) + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.LOG) + job.run() + derived = ( + node.as_source(tags_as_data={"k": "copied"}, source_id="new") + if copy_tags + else node.as_source() + ) + with pytest.raises( + InputValidationError, + match=r"'__raw_missing'.*declare a supported nullable type", + ): + derived.as_table() + + +def test_spiral_can_nominate_a_tag_copy_as_a_custom_system_tag( + tmp_path: Path, +) -> None: + schema = pa.schema( + [pa.field("k", pa.string(), False), 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) + source = SpiralDBTableSource( + "project", + "rows", + tag_columns=["k"], + tag_only_columns=True, + tags_as_data={"k": "copy"}, + system_tag_columns=["copy"], + ) + 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: + schema = pa.schema( + [pa.field("k", pa.string(), False), pa.field("x", pa.int8(), False)] + ) + table = pa.Table.from_pylist([{"k": "a", "x": 1}], 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) + source = SpiralDBTableSource("project", "rows", tag_only_columns=True) + handle = source._lookup_table() # pyright: ignore[reportPrivateUsage] # intercept the scan boundary + invalid = schema.append(pa.field("__unused", pa.null())) + batch = pa.RecordBatch.from_arrays( + [pa.array([], f.type) for f in invalid], schema=invalid + ) + monkeypatch.setattr(source, "_lookup_table", lambda: handle) + monkeypatch.setattr(handle, "scan_batches", lambda **kwargs: iter([batch])) + with pytest.raises( + InputValidationError, match=r"'__unused'.*declare a supported nullable type" + ): + source.as_table() From 705d60b042e7879348ef9e295dd5ca4d6b46030f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 16:12:15 -0800 Subject: [PATCH 4/9] fix(streams): preserve declared system tag fields in rows (ITL-1543) --- .zed/rules | 4 + CLAUDE.md | 4 + changelog.d/ITL-1543.md | 3 + docs/dev/design_issues/ITL-1543-AS2.md | 4 +- src/orcapod/core/datagrams/datagram.py | 5 +- src/orcapod/core/datagrams/tag_data.py | 48 ++++-- src/orcapod/core/operators/join.py | 144 ++++++++++-------- .../core/operators/static_output_pod.py | 49 +++--- src/orcapod/core/record_batch_channels.py | 31 ++-- src/orcapod/core/streams/base.py | 57 +++---- .../test_native_async_operators.py | 12 +- .../test_record_batch_channels.py | 55 +++++++ .../operators/test_async_sync_equivalence.py | 88 +++++++++++ .../sources/test_source_arrow_validation.py | 44 ++++++ tests/test_core/test_order_invariance.py | 28 ++++ 15 files changed, 433 insertions(+), 143 deletions(-) diff --git a/.zed/rules b/.zed/rules index 987b73fd3..f18cfde3b 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1348,6 +1348,10 @@ data. The rules: column with no null values. When Join sorts tied system tags, an output field is nullable if any of the corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + A row's system-tag fields come from its stream, including raw streams. Join + uses those declarations on the async row path as well as in its tables. + Source-info token declarations and the row-built gate are tracked separately + under ITL-1557 and the PR 601 follow-up. A row built by `Data` still gives an untyped null the `large_string` type. PolarsFilter is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (arrow_utils.restore_column_types and diff --git a/CLAUDE.md b/CLAUDE.md index 0c732eed0..1ddd16092 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1396,6 +1396,10 @@ data. The rules: column with no null values. When Join sorts tied system tags, an output field is nullable if any of the corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. + A row's system-tag fields come from its stream, including raw streams. Join + uses those declarations on the async row path as well as in its tables. + Source-info token declarations and the row-built gate are tracked separately + under ITL-1557 and the PR 601 follow-up. A row built by `Data` still gives an untyped null the `large_string` type. `PolarsFilter` is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (`arrow_utils.restore_column_types` and diff --git a/changelog.d/ITL-1543.md b/changelog.d/ITL-1543.md index 5c5313a53..517111610 100644 --- a/changelog.d/ITL-1543.md +++ b/changelog.d/ITL-1543.md @@ -12,3 +12,6 @@ sorted system tags' nullability. The tag is non-nullable when every corresponding input field is non-nullable. Existing entry IDs, instance IDs, record IDs and operator hashes for source inputs stay the same. +- Rows preserve the stream's Arrow fields for system tags, including width, + nullability, and metadata. Standalone async Join uses those fields as well. + IDs can change for hand-built streams with unusual system-tag fields. diff --git a/docs/dev/design_issues/ITL-1543-AS2.md b/docs/dev/design_issues/ITL-1543-AS2.md index 88251de24..463c9c12f 100644 --- a/docs/dev/design_issues/ITL-1543-AS2.md +++ b/docs/dev/design_issues/ITL-1543-AS2.md @@ -11,4 +11,6 @@ data was read. For example, a Join of streams tied on pipeline hash can declare its sorted system tags nullable, although its rows have non-nullable system tags. Part A corrects that Join schema and rejects Arrow Null in sources, including -nested Null. Part B remains open and makes rows use the stream's field definitions. +nested Null. Part B carries a stream's system-tag fields through row and batch +reads, including the standalone async Join. Source-info flag decisions remain +open in ITL-1557, and the existing row-built guard remains pending PR 601. diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 23acd12ac..f5d74dac2 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -356,6 +356,7 @@ def _rows_of_table( """ if table.num_rows == 0: return + original_table = table table = arrow_utils.normalize_table_to_large_types(table) row_contexts: list[Any | None] | None = None if constants.CONTEXT_KEY in table.column_names and data_context is None: @@ -365,7 +366,9 @@ def _rows_of_table( if apart_prefix is not None: apart = [c for c in data_table.column_names if c.startswith(apart_prefix)] if apart: - apart_table = data_table.select(apart) + apart_table = arrow_utils.normalize_table_to_large_types( + original_table.select(apart), keep_null=True + ) data_table = data_table.drop_columns(apart) # The optional tables that are there, and where each is in a row's tuple. optional = [meta_table, apart_table, beside] diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index d00efbad3..dff802d65 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -90,6 +90,7 @@ def __init__( data = _pa.Table.from_batches([data]) extracted_sys_tags: dict[str, DataValue] + system_tag_table = None if isinstance(data, _pa.Table): # Arrow path: call super() first, then extract system-tag columns from @@ -107,9 +108,12 @@ def __init__( if c.startswith(constants.SYSTEM_TAG_PREFIX) ] if sys_tag_cols: + system_tag_table = arrow_utils.normalize_table_to_large_types( + data.select(sys_tag_cols), keep_null=True + ) extracted_sys_tags = ( self._data_context.type_converter.arrow_table_to_python_dicts( - self._data_table.select(sys_tag_cols) # type: ignore[union-attr] + system_tag_table )[0] ) self._data_table = self._data_table.drop_columns(sys_tag_cols) # type: ignore[union-attr] @@ -138,7 +142,10 @@ def __init__( **kwargs, ) - self._set_system_tags({**extracted_sys_tags, **(system_tags or {})}) + if system_tag_table is not None and not system_tags: + self._set_system_tag_table(system_tag_table, extracted_sys_tags) + else: + self._set_system_tags({**extracted_sys_tags, **(system_tags or {})}) def _set_system_tags(self, system_tags: dict[str, DataValue]) -> None: """Hold ``system_tags`` as this tag's system tags.""" @@ -147,6 +154,20 @@ def _set_system_tags(self, system_tags: dict[str, DataValue]) -> None: [self._system_tags], default_type=str ) self._system_tags_table: "pa.Table | None" = None + self._system_tags_from_arrow = False + + def _set_system_tag_table( + self, table: "pa.Table", values: dict[str, DataValue] + ) -> None: + """Hold the system-tag fields and values supplied by an Arrow table.""" + self._system_tags_table = table + self._system_tags = values + self._system_tags_python_schema = Schema( + self._data_context.type_converter.arrow_schema_to_python_schema( + table.schema + ) + ) + self._system_tags_from_arrow = True @classmethod def rows_of( @@ -178,13 +199,15 @@ def rows_of( table, data_context, apart_prefix=constants.SYSTEM_TAG_PREFIX ) for tag, system_tag_row, _ in rows: - tag._set_system_tags( - tag._data_context.type_converter.arrow_table_to_python_dicts( - system_tag_row - )[0] - if system_tag_row is not None - else {} - ) + if system_tag_row is None: + tag._set_system_tags({}) + else: + tag._set_system_tag_table( + system_tag_row, + tag._data_context.type_converter.arrow_table_to_python_dicts( + system_tag_row + )[0], + ) yield tag # ------------------------------------------------------------------ @@ -287,7 +310,12 @@ def copy(self, include_cache: bool = True, preserve_id: bool = False) -> Self: new_tag = super().copy(include_cache=include_cache, preserve_id=preserve_id) new_tag._system_tags = dict(self._system_tags) new_tag._system_tags_python_schema = self._system_tags_python_schema - new_tag._system_tags_table = self._system_tags_table if include_cache else None + new_tag._system_tags_from_arrow = self._system_tags_from_arrow + new_tag._system_tags_table = ( + self._system_tags_table + if include_cache or self._system_tags_from_arrow + else None + ) return new_tag diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 06cdcfd26..27b8e9c82 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -2,7 +2,7 @@ import functools import itertools import json -from collections.abc import Callable, Collection, Mapping, Sequence +from collections.abc import Callable, Collection, Sequence from typing import Any, ClassVar, get_args import polars as pl @@ -44,7 +44,7 @@ TagProtocol, ) from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, ContentHash, DataType, DataValue, Schema +from orcapod.types import ColumnConfig, ContentHash, DataType, Schema from orcapod.utils import arrow_utils, schema_utils # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a @@ -769,8 +769,6 @@ async def _streaming_join( suffixes: Per-input system-tag suffixes (positional). """ n = len(inputs) - block_sep = constants.BLOCK_SEPARATOR - if n == 2: # Join in canonical order so the merged tag and data keys follow # the order ``output_schema`` defines, whatever the operand order. @@ -783,7 +781,7 @@ def merge_fn( rt: TagProtocol, rp: DataProtocol, ) -> tuple[TagProtocol, DataProtocol]: - return self._merge_pair_rename(lt, lp, rt, rp, pair_suffixes, block_sep) + return self._merge_pair_rename(lt, lp, rt, rp, pair_suffixes) await self._binary_streaming_join( inputs[left_idx], inputs[right_idx], output, merge_fn @@ -840,9 +838,6 @@ async def _staggered_join( """ from orcapod.channels import Channel - block_sep = constants.BLOCK_SEPARATOR - sys_prefix = constants.SYSTEM_TAG_PREFIX - canon_order = self._canonical_input_order(suffixes) async with asyncio.TaskGroup() as tg: @@ -858,8 +853,6 @@ async def _staggered_join( inputs[orig_idx], ch.writer, suffixes[orig_idx], - block_sep, - sys_prefix, ) ) renamed_readers.append(ch.reader) @@ -1065,8 +1058,6 @@ async def _rename_sys_tags( ch_in: ReadableChannel[tuple[TagProtocol, DataProtocol]], ch_out: WritableChannel[tuple[TagProtocol, DataProtocol]], suffix: str, - block_sep: str, - sys_prefix: str, ) -> None: """Read rows and rename system-tag keys by appending the per-input suffix. @@ -1076,16 +1067,11 @@ async def _rename_sys_tags( """ try: async for tag, pkt in ch_in: - sys_tags = tag.system_tags() - if sys_tags: - renamed: dict[str, DataValue] = {} - for k, v in sys_tags.items(): - new_key = ( - f"{k}{block_sep}{suffix}" if k.startswith(sys_prefix) else k - ) - renamed[new_key] = v + if (system_tags := Join._system_tag_table(tag)) is not None: tag = Join._build_tag( - Join._merge_tag_tables(tag, None), renamed, tag.data_context_key + Join._merge_tag_tables(tag, None), + arrow_utils.append_to_system_tags(system_tags, suffix), + tag.data_context_key, ) await ch_out.send((tag, pkt)) finally: @@ -1156,10 +1142,31 @@ def _merge_tag_tables( ] return pa.Table.from_arrays(columns, schema=pa.schema(list(fields.values()))) + @staticmethod + def _system_tag_table(tag: TagProtocol) -> "pa.Table | None": + """Return the system-tag columns of a row, with their Arrow fields.""" + columns = {"system_tags": True} + names = [ + name + for name in tag.keys(columns=columns) + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + return tag.as_table(columns=columns).select(names) if names else None + + @staticmethod + def _join_system_tag_tables( + tables: Sequence["pa.Table | None"], + ) -> "pa.Table | None": + """Join the system-tag tables and sort tied positions.""" + present = [table for table in tables if table is not None] + if not present: + return None + return Join._sort_merged_system_tags(arrow_utils.hstack_tables(*present)) + @staticmethod def _build_tag( table: "pa.Table | None", - system_tags: Mapping[str, DataValue], + system_tags: "pa.Table | None", data_context_key: str, ) -> TagProtocol: """Build a ``Tag`` from a merged Arrow table and its system tags. @@ -1175,8 +1182,13 @@ def _build_tag( from orcapod.core.datagrams import Tag if table is None: - return Tag({}, system_tags=system_tags, data_context=data_context_key) - return Tag(table, system_tags=system_tags, data_context=data_context_key) + return Tag( + system_tags if system_tags is not None else {}, + data_context=data_context_key, + ) + if system_tags is not None: + table = arrow_utils.hstack_tables(table, system_tags) + return Tag(table, data_context=data_context_key) @staticmethod def _merge_data( @@ -1292,7 +1304,6 @@ def _merge_pair_rename( right_tag: TagProtocol, right_pkt: DataProtocol, suffixes: list[str], - block_sep: str, ) -> tuple[TagProtocol, DataProtocol]: """Merge a matched pair, renaming system tags with per-side suffixes. @@ -1300,18 +1311,13 @@ def _merge_pair_rename( during the merge (not pre-renamed). The merged row is built from the inputs' Arrow tables, in the left (canonically first) tag's context. """ - sys_prefix = constants.SYSTEM_TAG_PREFIX - - # Rename and merge system tags - merged_sys: dict[str, DataValue] = {} - for i, tag in enumerate((left_tag, right_tag)): - for k, v in tag.system_tags().items(): - new_key = ( - f"{k}{block_sep}{suffixes[i]}" if k.startswith(sys_prefix) else k - ) - merged_sys[new_key] = v - - merged_sys = Join._sort_merged_system_tags(merged_sys) + tables = [ + arrow_utils.append_to_system_tags(table, suffix) + if (table := Join._system_tag_table(tag)) is not None + else None + for tag, suffix in zip((left_tag, right_tag), suffixes, strict=True) + ] + merged_sys = Join._join_system_tag_tables(tables) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, @@ -1334,13 +1340,9 @@ def _merge_pair_passthrough( inputs' Arrow tables, in the left (canonically first) tag's context. ``final`` is true only for the chain's last step (see ``_merge_data``). """ - # Combine system tags (already renamed) - merged_sys: dict[str, DataValue] = {} - merged_sys.update(left_tag.system_tags()) - merged_sys.update(right_tag.system_tags()) - - # Sort within same-provenance-path groups for commutativity - merged_sys = Join._sort_merged_system_tags(merged_sys) + merged_sys = Join._join_system_tag_tables( + [Join._system_tag_table(left_tag), Join._system_tag_table(right_tag)] + ) merged_tag = Join._build_tag( Join._merge_tag_tables(left_tag, right_tag), merged_sys, @@ -1351,7 +1353,7 @@ def _merge_pair_passthrough( ) @staticmethod - def _sort_merged_system_tags(merged_sys: dict) -> dict: + def _sort_merged_system_tags(table: "pa.Table") -> "pa.Table": """Sort system tag values within same-provenance-path groups. When two joined inputs share a pipeline_hash, their system tag @@ -1367,7 +1369,7 @@ def _sort_merged_system_tags(merged_sys: dict) -> dict: # Parse keys → groups[provenance_path][position][field_type] = key groups: dict[str, dict[str, dict[str, str]]] = {} - for key in merged_sys: + for key in table.column_names: if not key.startswith(sys_prefix): continue base, sep, position = key.rpartition(field_sep) @@ -1382,31 +1384,43 @@ def _sort_merged_system_tags(merged_sys: dict) -> dict: 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(): + take_from: dict[str, str] = {} + for positions in groups.values(): if len(positions) <= 1: continue - sorted_pos_keys = sorted(positions.keys(), key=int) + positions_in_order = sorted(positions, 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)) + def sort_key(fields: dict[str, str]) -> tuple[Any, Any]: + source = fields.get(sid_field) + record = fields.get(rid_field) + source_value = table.column(source)[0].as_py() if source else None + record_value = table.column(record)[0].as_py() if record else None + return source_value or "", record_value or b"" - 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] + sorted_fields = sorted( + (positions[position] for position in positions_in_order), key=sort_key + ) + for position, source_fields in zip(positions_in_order, sorted_fields): + for kind, name in positions[position].items(): + if kind in source_fields: + take_from[name] = source_fields[kind] - return merged_sys + if not take_from: + return table + nullable = arrow_utils.sorted_system_tag_nullability( + {field.name: field.nullable for field in table.schema} + ) + sources = [take_from.get(name, name) for name in table.column_names] + fields = [ + field.with_nullable( + nullable[field.name] or table.schema.field(source).nullable + ) + for field, source in zip(table.schema, sources) + ] + return pa.Table.from_arrays( + [table.column(source) for source in sources], schema=pa.schema(fields) + ) def rows_dropped_text( self, diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cae6813fe..fec9d377a 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -516,23 +516,23 @@ def _kept_output( return StaticOutputOperatorPod._zero_rows_in_row_order(result) @staticmethod - def _flag_by_values(table: pa.Table) -> pa.Table: - """Flag each system-tag and source-info field nullable only when it holds a null. + def _flag_by_values(table: pa.Table, *, system_tags: bool = True) -> pa.Table: + """Flag value-based fields nullable only when they hold a null. - The last step of F (``_row_built_form``), which needs the complete table. A table - built from rows takes its system tags and source-info tokens from each row's - values, so those fields are non-nullable unless a value is missing, whatever - flags the table the rows came from had (a join over inputs tied on pipeline hash - declares its system tags nullable). The table built from rows also carries no - schema metadata (``arrow_utils.hstack_tables``), so none is kept. + The row-built form settles source-info flags from the complete table. + Callers that settle both provenance groups use this for transport layouts. + The table built from rows carries no schema metadata. Args: table: A table of user tags, system tags, data and source info. + system_tags: Also settle system-tag flags from values. Returns: The same arrays under the new field flags, with no schema metadata. """ - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) + prefixes = (constants.SOURCE_PREFIX,) + if system_tags: + prefixes = (*prefixes, constants.SYSTEM_TAG_PREFIX) fields = [ field.with_nullable(table.column(i).null_count > 0) if field.name.startswith(prefixes) @@ -615,11 +615,11 @@ def _row_built_form( F in the ITL-1347 spec: the same table, without making the rows. Two steps: - per slice (``streams.base.row_built_columns``), what each row decides on its - own: the columns, their order, their large types, and the provenance fields' - form (no system-tag field metadata, source-info lists of nullable items); + own: the columns, their order, the declared system-tag fields, and the + source-info fields in the form the rows give them; - on the complete table, what depends on the values of every row: each source-info column's type, from its tokens (``_type_source_info_by_values``), - then the system-tag and source-info field flags (``_flag_by_values``). + then the source-info field flags (``_flag_by_values``). The equality with ``_rows_to_table`` is tested over every operator, source kind, column role and raw-stream provenance shape (ITL-1347, L0-L2). @@ -642,7 +642,8 @@ def _row_built_form( return StaticOutputOperatorPod._flag_by_values( StaticOutputOperatorPod._type_source_info_by_values( row_built_columns(table, keys) - ) + ), + system_tags=False, ) except RowBuiltFormUnavailable: raise @@ -1317,10 +1318,10 @@ def stream_from_batches( (``InputChannel.to_stream``), and the record batches a row-by-row operator is applied to. The batches are put under one another in the order given, and the table is handed on as a node hands its rows to its successors - (``_output_stream``): in the row-built form, each system-tag and source-info field - flagged nullable only when one of its values is null (decided over the complete - table, never per batch), with ``stream``'s identity: its producer, upstreams, - pipeline hash and data context. With no batch it is ``stream``'s zero-row input, + (``_output_stream``): declared system-tag flags are restored and source-info + flags are settled from values over the complete table. The result keeps + ``stream``'s producer, upstreams, pipeline hash and data context. + With no batch it is ``stream``'s zero-row input, typed by its description and never by rows. Args: @@ -1335,6 +1336,20 @@ def stream_from_batches( table = concatenate_batches(batches) if table is None: return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator + declared = typed_zero_row_table(stream) + fields = [] + for field, column in zip(table.schema, table.columns, strict=True): + if field.name.startswith(constants.SYSTEM_TAG_PREFIX): + typed = ( + declared.schema.field(field.name) + if declared is not None and field.name in declared.column_names + else None + ) + field = field.with_nullable( + typed.nullable if typed is not None else column.null_count > 0 + ) + fields.append(field) + table = pa.Table.from_arrays(table.columns, schema=pa.schema(fields)) return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's table, _keys_in_delivered_order(stream.keys(), table.column_names), stream ) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 3e94bbe12..9e3613e14 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -414,20 +414,22 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: converted: type strictness), the same nullability (and no null where the description's field is not nullable) and the same field metadata. A ``null`` type of the description (anywhere in a column's type) is carried as - ``large_string``, as a row's datagram stores it, and only null values are taken - there. Whether a system-tag or source-info field is nullable is not compared: it - follows the values of the complete table (``_flag_by_values``). Nor is a - source-info column's type, which follows its tokens over the complete table - (``_type_source_info_by_values``): it must only be a token type (``large_string``, - or ``large_list`` of a token type). + ``large_string`` outside system tags, and only null values are taken there. + System-tag field metadata must match the description. Batches may differ in + their top-level provenance flags. The complete stream uses the declared system-tag + flags and settles source-info flags from values. A source-info column may + carry any token type (``large_string`` or ``large_list`` of a token type). + The complete table settles its type in ``_type_source_info_by_values``. """ sent = batch.schema if sorted(declared.names) != sorted(sent.names): return f"it has {sent.names}, the stream has {declared.names}" - provenance = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, column in enumerate(sent): expected = declared.field(column.name) - carried = arrow_utils.normalize_to_large_types(expected.type) + system_tag = column.name.startswith(constants.SYSTEM_TAG_PREFIX) + carried = arrow_utils.normalize_to_large_types( + expected.type, keep_null=system_tag + ) if column.name.startswith(constants.SOURCE_PREFIX): if not _is_token_type(column.type): return f"column {column.name!r} is {column.type}, not a token type" @@ -445,12 +447,15 @@ def _schema_mismatch(declared: pa.Schema, batch: pa.RecordBatch) -> str | None: f"column {column.name!r} holds values where the stream's type " + f"{expected.type} holds only nulls" ) - if column.name.startswith(provenance): - # A row builds these from its values: no field metadata at any depth. - if column.metadata or not column.type.equals( - _without_metadata(column.type), check_metadata=True + if system_tag: + if (expected.metadata or None) != (column.metadata or None) or not ( + column.type.equals(carried, check_metadata=True) ): - return f"column {column.name!r} carries field metadata" + return f"column {column.name!r} carries field metadata that differs from its stream" + if not expected.nullable and batch.column(index).null_count: + return ( + f"column {column.name!r} holds nulls, the stream's is not nullable" + ) continue if expected.nullable != column.nullable: flags = {True: "nullable", False: "not nullable"} diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..4702d08df 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -85,14 +85,10 @@ def reads_as_its_class(obj: object, cls: type) -> bool: def system_tags_as_rows_give(table: pa.Table) -> bool: - """Whether every system-tag column is what the row rebuild gives: non-null text. + """Whether the optimized row-building path may use these system tags. - ``main`` rebuilt a node's table from its rows, whose system tags are typed from - their values: a ``large_string`` field, non-nullable, with no field metadata (the - only kind library code makes). A whole table is its rows only when its system tags - are already so, in their values as in their fields: a narrow integer, a nullable - field, a null value (also in a field declared non-nullable) or field metadata (an - Arrow extension's, which a tag drops) is decided by the rows (ITL-1347). + The optimized path still uses the ITL-1347 gate for non-nullable text + without field metadata. The row path now carries declared system-tag fields. Args: table: The table. @@ -272,13 +268,10 @@ def row_built_columns( column of ``table``. 3. Normalized to the large types without keeping ``null``: each row's datagram stores a ``null`` column as ``large_string`` (``Datagram._init_from_table``). - 4. The system-tag and source-info fields as a row builds them from its values - (``row_built_provenance``): no field metadata, and a source-info list of the - form its tokens give. + 4. Leave system-tag fields as declared. Give source-info fields the form their + tokens give (``row_built_provenance``). - Whether a system-tag or source-info field is nullable depends on its values over - the complete table (``StaticOutputOperatorPod._flag_by_values``), so it is not - decided here. + Source-info field nullability is settled over the complete table. Args: table: A table of user tags, system tags, data and source info. @@ -288,11 +281,14 @@ def row_built_columns( Returns: The same values, selected and ordered, in their large types. """ - return row_built_provenance( - arrow_utils.normalize_table_to_large_types( - table.select(row_built_names(table.column_names, keys)) - ) - ) + selected = table.select(row_built_names(table.column_names, keys)) + normalized = arrow_utils.normalize_table_to_large_types(selected) + for index, field in enumerate(selected.schema): + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) and ( + field.type != normalized.schema.field(index).type + ): + normalized = normalized.set_column(index, field, selected.column(index)) + return row_built_provenance(normalized) def _source_info_value_type(kind: pa.DataType) -> pa.DataType: @@ -319,9 +315,9 @@ def _source_info_value_type(kind: pa.DataType) -> pa.DataType: def row_built_provenance(table: pa.Table) -> pa.Table: - """Give ``table``'s system-tag and source-info fields the form a row builds. + """Give ``table``'s source-info fields the form a row builds. - A row rebuilds its system tags and its source info from their values, so their + A row still builds its source info from its values, so those fields carry no field metadata, and a source-info column has the type its tokens give (``_source_info_value_type``): a list's item field named ``item`` and nullable at every depth. The values are unchanged: a type that differs only in @@ -344,8 +340,6 @@ def row_built_provenance(table: pa.Table) -> pa.Table: if kind != field.type: column = column.cast(kind) new_field = pa.field(field.name, kind, nullable=field.nullable) - elif field.name.startswith(constants.SYSTEM_TAG_PREFIX): - new_field = field.remove_metadata() else: new_field = field changed = changed or not new_field.equals(field, check_metadata=True) @@ -443,8 +437,9 @@ def stream_arrow_schema( converted by its data context (``arrow_types_declared`` is then false), and one whose schema is known only by polling (nothing declared, nothing polled: ``schema_requires_io``) answers with no column. Each - system-tag and source-info field is stated nullable: a table decides its flag from - its values (F's last step). A source-info field's type is stated as the declared + source-info field is stated nullable: a table decides its flag from + its values (F's last step). System-tag fields keep their declared flags and + metadata. A source-info field's type is stated as the declared token type; a complete table decides it from its tokens (``StaticOutputOperatorPod._type_source_info_by_values``), so consumers must not rely on it. A ``null`` column keeps the zero-row ``null`` type; rows @@ -508,9 +503,8 @@ def stream_arrow_schema( keys = given_keys if given_keys is not None else keys_of_rows(table, typed.keys()) names = row_built_names(table.column_names, keys) schema = row_built_provenance(table.select(names)).schema - prefixes = (constants.SYSTEM_TAG_PREFIX, constants.SOURCE_PREFIX) for index, field in enumerate(schema): - if field.name.startswith(prefixes): + if field.name.startswith(constants.SOURCE_PREFIX): schema = schema.set(index, field.with_nullable(True)) # pyright: ignore[reportUnknownMemberType] # stubs leave Field unparametrized return schema @@ -563,13 +557,10 @@ async def next(self) -> pa.RecordBatch | None: def _row_built_table(self) -> pa.Table: """The stream's table in the row-built form: its one read. - The table first: reading it is the stream's one read (an unpolled source polls - here), and its keys are then known without another. Its system tags must be - what rows give (``system_tags_as_rows_give``: non-null text, no field - metadata); otherwise, as on the eager routes of a job, the table is the one - its rows build (``main``'s row path), so a narrow or nullable system tag is - retyped as a row retypes it. Only a stream that holds such a column (a raw - ``ArrowTableStream``) is read that way, and its reads have no effect. + The table first: reading it is the stream's one read (an unpolled source + polls here), and its keys are then known without another. The existing + system-tag gate sends other fields through the row path, which carries + their declared system-tag fields. """ table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(table): diff --git a/tests/test_channels/test_native_async_operators.py b/tests/test_channels/test_native_async_operators.py index 82c774af7..9cf7cc944 100644 --- a/tests/test_channels/test_native_async_operators.py +++ b/tests/test_channels/test_native_async_operators.py @@ -2245,7 +2245,9 @@ def test_sorts_same_provenance_path_by_value(self): "_tag_source_id::abc123:1": "a_source", "_tag_record_id::abc123:1": "a_record", } - result = Join._sort_merged_system_tags(merged_sys) + result = Join._sort_merged_system_tags( + pa.Table.from_pylist([merged_sys]) + ).to_pylist()[0] # After sorting, position 0 should have the smaller values assert result["_tag_source_id::abc123:0"] == "a_source" @@ -2259,7 +2261,9 @@ def test_single_position_unchanged(self): "_tag_source_id::abc123:0": "only_source", "_tag_record_id::abc123:0": "only_record", } - result = Join._sort_merged_system_tags(merged_sys) + result = Join._sort_merged_system_tags( + pa.Table.from_pylist([merged_sys]) + ).to_pylist()[0] assert result == merged_sys def test_non_system_tag_keys_ignored(self): @@ -2269,7 +2273,9 @@ def test_non_system_tag_keys_ignored(self): "_tag_source_id::abc123:0": "src0", "_tag_record_id::abc123:0": "rec0", } - result = Join._sort_merged_system_tags(merged_sys) + result = Join._sort_merged_system_tags( + pa.Table.from_pylist([merged_sys]) + ).to_pylist()[0] assert result["regular_key"] == "value" diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index d4416e6db..3e03282a6 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -69,6 +69,61 @@ TIMEOUT = 5.0 +def test_raw_system_tag_fields_survive_a_record_batch_channel() -> None: + """A channel carries a stream's system-tag Arrow fields through to its rows.""" + system = pa.schema( + [ + pa.field("_tag_rank", pa.int8(), False, metadata={b"purpose": b"rank"}), + pa.field("_tag_label", pa.large_string(), True), + ] + ) + schema = pa.schema( + [ + pa.field("subject", pa.large_string(), False), + pa.field("trial", pa.int16(), False), + pa.field("x", pa.int8(), False), + pa.field("y", pa.int8(), False), + *system, + ] + ) + table = pa.Table.from_arrays( + [ + pa.array(values, field.type) + for values, field in zip( + (["a", "b"], [1, 2], [3, 4], [5, 6], [7, 8], ["a", None]), + schema, + strict=True, + ) + ], + schema=schema, + ) + stream = ArrowTableStream(table, tag_columns=("subject", "trial")) + + async def forward() -> StreamProtocol: + output = OutputChannel(stream) + async for batch in stream.open_channel(): + assert batch.select(system.names).schema.equals(system, check_metadata=True) + await output.send(batch) + await output.close() + return output.result() + + assert pa.schema([stream.arrow_schema().field(n) for n in system.names]).equals( + system, check_metadata=True + ) + rebuilt = run(forward) + assert ( + rebuilt.as_table(columns=ALL) + .select(system.names) + .schema.equals(system, check_metadata=True) + ) + for tag, _ in rebuilt.iter_data(): + assert ( + tag.as_table(columns=ALL) + .select(system.names) + .schema.equals(system, check_metadata=True) + ) + + def run(make: Callable[[], Awaitable[T]]) -> T: """Run a coroutine to its end; a channel that never wakes fails the test.""" diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 1a6a54096..b2e30bbe2 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -15,6 +15,7 @@ import asyncio import decimal +import itertools import re from collections.abc import Callable, Sequence from dataclasses import dataclass @@ -28,6 +29,7 @@ from orcapod.contexts import get_default_context, get_default_type_converter from orcapod.core.cached_function_pod import CachedFunctionPod from orcapod.core.data_function import PythonDataFunction +from orcapod.core.datagrams import Tag from orcapod.core.function_pod import FunctionPod from orcapod.core.operators import ( AddTags, @@ -1013,6 +1015,92 @@ def test_async_rows_equal_sync_rows(case: Case) -> None: ) +@pytest.mark.parametrize("reverse_columns", [False, True]) +def test_standalone_async_join_rows_keep_declared_system_tag_fields( + reverse_columns: bool, +) -> None: + 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 = [] + for source, records in (("a", [None, "q"]), ("b", ["r", "t"]), ("c", ["s", "u"])): + 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=schema, + ) + if reverse_columns: + table = table.select(list(reversed(schema.names))) + inputs.append( + ArrowTableStream(table, tag_columns=("k", "g"), data_tags=("k", "g")) + ) + assert len({stream.pipeline_hash() for stream in inputs}) == 1 + columns = {"system_tags": True} + for ordered in itertools.permutations(inputs): + stream = Join()(*ordered) + table = stream.as_table(columns=columns) + 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) + assert tag_table.schema.equals( + table.select(tag_table.column_names).schema, check_metadata=True + ) + data_table = data.as_table() + assert data_table.schema.equals( + table.select(data_table.column_names).schema, check_metadata=True + ) + + +@pytest.mark.parametrize("reverse_columns", [False, True]) +def test_raw_stream_rows_keep_system_tag_width_flags_and_metadata( + reverse_columns: bool, +) -> None: + schema = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("g", pa.large_string(), False), + pa.field("x", pa.int16(), False), + pa.field("y", pa.large_string(), True), + pa.field("_tag_rank", pa.int8(), False, metadata={b"purpose": b"rank"}), + pa.field("_tag_label", pa.large_string(), True), + ] + ) + table = pa.Table.from_pylist( + [ + {"k": 1, "g": "a", "x": 4, "y": "x", "_tag_rank": 7, "_tag_label": "a"}, + {"k": 2, "g": "b", "x": 5, "y": None, "_tag_rank": 8, "_tag_label": None}, + ], + schema=schema, + ) + if reverse_columns: + table = table.select(list(reversed(schema.names))) + stream = ArrowTableStream(table, tag_columns=("k", "g")) + columns = {"system_tags": True} + for tag, data in stream.iter_data(): + assert isinstance(tag, Tag) + for row in (tag, tag.copy(include_cache=False)): + got = row.as_table(columns=columns) + assert got.schema.equals( + table.select(got.column_names).schema, check_metadata=True + ) + got_data = data.as_table() + assert got_data.schema.equals( + table.select(got_data.column_names).schema, check_metadata=True + ) + + # ── inputs that are not root sources (ITL-906) ────────────────────────────── diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index ff7f5d0b2..470308051 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -391,6 +391,50 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: cached.as_table() +@pytest.mark.parametrize("stored_flag", [False, True]) +def test_cached_source_reads_older_token_field_flags_as_stored( + stored_flag: bool, +) -> None: + """A cache read uses the stored schema when its original source is unavailable.""" + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + tags, data = source.output_schema() + proxy = SourceProxy( + source_id=source.source_id, + content_hash_str=source.content_hash().to_string(), + pipeline_hash_str=source.pipeline_hash().to_string(), + tag_schema=tags, + data_schema=data, + ) + database = InMemoryArrowDatabase() + cache = CachedSource(proxy, cache_database=database) + columns = {"source": True, "system_tags": True} + table = source.as_table(columns=columns) + token = "_source_extra" + position = table.schema.get_field_index(token) + table = table.set_column( + position, + table.schema.field(position).with_nullable(stored_flag), + table.column(position), + ) + table = table.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) + database.add_records( + cache.cache_path, + with_data_context(table, source.data_context_key), + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=True, + ) + assert cache.as_table(columns=columns).schema.field(token).nullable is stored_flag + assert all( + data.source_info_table().schema.field(token).nullable + for _, data in cache.iter_data() + ) + + @pytest.mark.parametrize("row_count", [0, 2]) def test_derived_source_refuses_stored_null_in_its_direct_table_view( row_count: int, monkeypatch: pytest.MonkeyPatch diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 9cdabf77b..1040a7074 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -923,6 +923,34 @@ def test_a_source_stream_or_pod_does_not_depend_on_the_arrangement_of_its_input( assert_all_equal(results) +@pytest.mark.parametrize( + "case", [*STREAM_CASES], ids=[case.label for case in STREAM_CASES] +) +def test_stream_and_rows_agree_on_tag_and_primary_data_fields( + case: StreamCase, tmp_path: Path +) -> None: + """Rows keep the stream's declared fields across tag orders and layouts.""" + columns = {"system_tags": True} + for order, layout in ARRANGEMENTS: + stream = case.build(case.roles[0], order, layout, tmp_path) + table = stream.as_table(columns=columns) + rows = [list(stream.iter_data())] + if case.with_async: + rows.append( + asyncio.run(_run_async(stream.producer, list(stream.upstreams))) + ) + for path_rows in rows: + assert len(path_rows) == table.num_rows + for tag, data in path_rows: + for row_table in (tag.as_table(columns=columns), data.as_table()): + assert all( + field.equals( + table.schema.field(field.name), check_metadata=True + ) + for field in row_table.schema + ) + + @pytest.mark.parametrize("role", ROLES) def test_the_order_of_a_function_pods_inputs_changes_nothing(role: str) -> None: """``pod(a, b)`` joins its inputs: their order is not part of anything.""" From d74dd593b011f01076a895bce9644c132e64609d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 16:37:07 -0800 Subject: [PATCH 5/9] fix(streams): reconcile system tag fields across source and Join paths (ITL-1543) --- .zed/rules | 7 +- CLAUDE.md | 7 +- changelog.d/ITL-1543.md | 6 + src/orcapod/core/operators/join.py | 8 +- src/orcapod/core/row_ids.py | 19 +- src/orcapod/core/sources/db_table_source.py | 13 +- src/orcapod/core/sources/stream_builder.py | 26 ++- src/orcapod/utils/arrow_utils.py | 27 ++- .../operators/test_async_sync_equivalence.py | 43 ++++- .../operators/test_record_batch_execution.py | 20 +-- .../sources/test_source_arrow_validation.py | 116 ++++++++++-- tests/test_core/test_order_invariance.py | 165 +++++++++++++++--- tests/test_core/test_row_ids.py | 29 +++ .../test_pipeline/test_review_findings_510.py | 22 +-- tests/test_pipeline/test_rows_on_read.py | 52 +++--- 15 files changed, 441 insertions(+), 119 deletions(-) diff --git a/.zed/rules b/.zed/rules index f18cfde3b..00ede7595 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1345,8 +1345,11 @@ 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. A source's custom system-tag names must each identify an existing non-nullable text - column with no null values. When Join sorts tied system tags, an output field is - nullable if any of the corresponding input fields can hold a null. + 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. When Join sorts tied system tags, it declares + the rebuilt fields without operand metadata. A rebuilt field is nullable if any of the + corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. A row's system-tag fields come from its stream, including raw streams. Join uses those declarations on the async row path as well as in its tables. diff --git a/CLAUDE.md b/CLAUDE.md index 1ddd16092..cb6f53381 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1393,8 +1393,11 @@ 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. A source's custom system-tag names must each identify an existing non-nullable text - column with no null values. When Join sorts tied system tags, an output field is - nullable if any of the corresponding input fields can hold a null. + 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. When Join sorts tied system tags, it declares + the rebuilt fields without operand metadata. A rebuilt field is nullable if any of the + corresponding input fields can hold a null. A raw `ArrowTableStream` still preserves `null` in its table in ITL-1543 part A. A row's system-tag fields come from its stream, including raw streams. Join uses those declarations on the async row path as well as in its tables. diff --git a/changelog.d/ITL-1543.md b/changelog.d/ITL-1543.md index 517111610..a5e29a0e3 100644 --- a/changelog.d/ITL-1543.md +++ b/changelog.d/ITL-1543.md @@ -5,6 +5,9 @@ - A custom system-tag column on a source must be a non-nullable string column with no null values. Sources also reject missing names in `system_tag_columns`. Convert custom tags to text before building the source. +- Sources refuse Arrow field metadata on nominated custom system tags, including + tag copies nominated with `system_tag_columns`. Remove the field metadata before + building the source. ITL-1561 tracks re-evaluating this restriction. ### Fixed @@ -15,3 +18,6 @@ - Rows preserve the stream's Arrow fields for system tags, including width, nullability, and metadata. Standalone async Join uses those fields as well. IDs can change for hand-built streams with unusual system-tag fields. +- Standalone async Join uses the same fields as the table and sync rows for + sorted system tags of tied inputs. Entry-ID errors for a raw Arrow Null system + tag name the column and ask for a supported nullable type. diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 27b8e9c82..fb14c24d6 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -440,7 +440,7 @@ def _predict_system_tag_schema(self, *streams: StreamProtocol) -> Schema: ) return Schema( { - name: kind | None if nullable[name] else kind + name: kind | None if nullable.get(name, False) else kind for name, kind in system_tag_fields.items() } ) @@ -1413,8 +1413,10 @@ def sort_key(fields: dict[str, str]) -> tuple[Any, Any]: ) sources = [take_from.get(name, name) for name in table.column_names] fields = [ - field.with_nullable( - nullable[field.name] or table.schema.field(source).nullable + arrow_utils.sorted_system_tag_field(field, nullable[field.name]) + if field.name in nullable + else field.with_nullable( + field.nullable or table.schema.field(source).nullable ) for field, source in zip(table.schema, sources) ] diff --git a/src/orcapod/core/row_ids.py b/src/orcapod/core/row_ids.py index ecdaf05aa..d854c74d1 100644 --- a/src/orcapod/core/row_ids.py +++ b/src/orcapod/core/row_ids.py @@ -34,6 +34,7 @@ import pyarrow as pa from orcapod.system_constants import constants +from orcapod.utils.arrow_utils import contains_null_type if TYPE_CHECKING: from orcapod.protocols.core_protocols import DataProtocol, TagProtocol @@ -89,7 +90,23 @@ def entry_id( Returns: The entry id. """ - return hasher.hash_table(entry_id_preimage(tag, data)) + preimage = entry_id_preimage(tag, data) + try: + return hasher.hash_table(preimage) + except ValueError as exc: + raw_null_tags = [ + repr(field.name) + for field in preimage.schema + if field.name.startswith(constants.SYSTEM_TAG_PREFIX) + and contains_null_type(field.type) + ] + if raw_null_tags: + names = ", ".join(raw_null_tags) + raise ValueError( + f"{exc}. Declare a supported nullable type for the raw Arrow Null " + f"system-tag column(s) {names}." + ) from exc + raise def instance_id_preimage(entry: "ContentHash", data: "DataProtocol") -> "pa.Table": diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 55f0c82b7..cf3cb6b97 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -166,6 +166,7 @@ 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. @@ -173,7 +174,6 @@ def __init__( # Step 4: Enrich via SourceStreamBuilder (same pipeline as all other RootSources) self._tag_columns: Collection[str] = resolved_tag_columns - self._system_tag_columns: Collection[str] = system_tag_columns # Every declared tag is a data-tag unless kept tag-only (ITL-1023); a # rebuild after a check (ITL-1102) applies the same choice. data_tags = source_data_tags(self._tag_columns, tag_only_columns) @@ -235,7 +235,16 @@ def _read_table( db_nullable = {ci.name: ci.nullable for ci in col_infos} db_schema = pa.schema( [ - pa.field(f.name, f.type, nullable=db_nullable.get(f.name, True)) + # Keep nominated metadata visible to source validation. Other + # fields retain the database-backed schema used for hashing. + pa.field( + 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 ] ) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index b54428354..2c9ad4407 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -36,24 +36,12 @@ from orcapod.protocols.hashing_protocols import ArrowHasherProtocol -def _contains_null_type(arrow_type: pa.DataType) -> bool: - """Return whether an Arrow type contains the Null type at any depth.""" - if isinstance(arrow_type, pa.BaseExtensionType): - return _contains_null_type(arrow_type.storage_type) - if pa.types.is_dictionary(arrow_type): - return _contains_null_type(arrow_type.value_type) - return pa.types.is_null(arrow_type) or any( - _contains_null_type(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) - ) - - def require_supported_nullable_types(schema: pa.Schema) -> None: """Refuse source columns containing the Arrow Null type, even with zero rows.""" columns = sorted( (field.name, str(field.type)) for field in schema - if _contains_null_type(field.type) + if arrow_utils.contains_null_type(field.type) ) if columns: names = ", ".join(f"{name!r} ({arrow_type})" for name, arrow_type in columns) @@ -69,7 +57,7 @@ def require_custom_system_tags( *, schema: pa.Schema | None = None, ) -> None: - """Validate custom system-tag names, types, field flags and values. + """Validate custom system-tag declarations and values. Args: table: The source's Arrow columns. @@ -78,7 +66,8 @@ def require_custom_system_tags( Raises: ValueError: If a nominated column is missing from the source table. - InputValidationError: If a nominated column is not non-nullable text. + InputValidationError: If a nominated column has field metadata, can + hold nulls or is not text. """ if not names: return @@ -91,6 +80,13 @@ def require_custom_system_tags( ) for name in names: field = fields.field(name) + # ITL-1561: Re-evaluate which Arrow field metadata a system tag may carry. + # Extension metadata reaches the row hash now that rows use stream fields. + if field.metadata or table.schema.field(name).metadata: + raise InputValidationError( + f"Custom system-tag column {name!r} has Arrow field metadata. " + "Remove the field metadata before building the source." + ) has_nulls = table.column(name).null_count > 0 if ( field.nullable diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c49d1f429..ea33a5623 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -1248,6 +1248,18 @@ def make_schema_non_nullable(schema: "pa.Schema") -> "pa.Schema": ) +def contains_null_type(arrow_type: "pa.DataType") -> bool: + """Return whether an Arrow type contains the Null type at any depth.""" + if isinstance(arrow_type, pa.BaseExtensionType): + return contains_null_type(arrow_type.storage_type) + if pa.types.is_dictionary(arrow_type): + return contains_null_type(arrow_type.value_type) + return pa.types.is_null(arrow_type) or any( + contains_null_type(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + def infer_schema_nullable(table: "pa.Table") -> "pa.Schema": """Return a schema where each field's nullable flag is inferred from actual data. @@ -1682,9 +1694,9 @@ def _system_tag_position_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(): + """Return nullability for the source/record fields rebuilt by a tied sort.""" + nullable: dict[str, bool] = {} + for positions in _system_tag_position_groups(nullable_by_name.keys()).values(): if len(positions) <= 1: continue for prefix in ( @@ -1700,6 +1712,11 @@ def sorted_system_tag_nullability( return nullable +def sorted_system_tag_field(field: "pa.Field[Any]", nullable: bool) -> "pa.Field[Any]": + """Declare a tied field without metadata from any one operand.""" + return field.with_nullable(nullable).remove_metadata() + + def sort_system_tag_values(table: "pa.Table") -> "pa.Table": """Sort paired system tag values for columns that share the same provenance path. @@ -1789,8 +1806,8 @@ def sort_system_tag_values(table: "pa.Table") -> "pa.Table": ): if name is not None: index = table.schema.get_field_index(name) - field = pa.field( - name, table.schema.field(index).type, nullable=nullable[name] + field = sorted_system_tag_field( + table.schema.field(index), nullable[name] ) table = table.set_column( index, field, pa.array(values, type=field.type) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index b2e30bbe2..31595c3aa 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -1016,8 +1016,10 @@ def test_async_rows_equal_sync_rows(case: Case) -> None: @pytest.mark.parametrize("reverse_columns", [False, True]) +@pytest.mark.parametrize("metadata", ["none", "same", "different"]) def test_standalone_async_join_rows_keep_declared_system_tag_fields( reverse_columns: bool, + metadata: str, ) -> None: source_id = "_tag_source_id::seed" record_id = "_tag_record_id::seed" @@ -1030,7 +1032,21 @@ def test_standalone_async_join_rows_keep_declared_system_tag_fields( ] ) inputs = [] + empty_inputs = [] for source, records in (("a", [None, "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} @@ -1038,19 +1054,38 @@ def test_standalone_async_join_rows_keep_declared_system_tag_fields( zip(("x", "y"), records, strict=True) ) ], - schema=schema, + schema=fields, ) if reverse_columns: table = table.select(list(reversed(schema.names))) inputs.append( ArrowTableStream(table, tag_columns=("k", "g"), data_tags=("k", "g")) ) + empty_inputs.append( + ArrowTableStream( + 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 ordered in itertools.permutations(inputs): - stream = Join()(*ordered) + 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) - for rows in (list(stream.iter_data()), async_rows(Join(), *ordered)): + 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) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index f6762c14d..c0bedfa82 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -660,13 +660,8 @@ def test_empty_source_info_lists_are_typed_from_their_tokens(layout: str) -> Non assert got.schema.field("_source_x").type == pa.large_list(pa.large_string()) -def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: - """Pins a stream no job can run: a raw stream whose system-tag column holds a string - and a null. The job's sync path refuses it (the rows' system-tag fields differ in - their flags), and so does the channel, which builds such a stream from - its rows (CodeRabbit on PR #510); a job never sees such a stream, - because a source with a nullable system tag cannot be bound to a slot - (``SourceSpecMismatchError``).""" +def test_a_raw_nullable_system_tag_keeps_its_field_in_a_job_and_channel() -> None: + """The stream's nullable string field applies to rows with and without a value.""" raw = ArrowTableStream( pa.table( { @@ -678,12 +673,11 @@ def test_a_system_tag_with_a_null_is_refused_by_the_job_sync_path() -> None: ), tag_columns=["k"], ) - assert _schema_outcome(lambda: _job_sync(SelectDataColumns(["x"]), raw)) == ( - "refused", - "ArrowInvalid", - ) - with pytest.raises(pa.ArrowInvalid): - run_on_channels(SelectDataColumns(["x"]), [raw], None) + expected = raw.as_table(columns=ALL).select([SYSTEM_TAG]) + sync = _job_sync(SelectDataColumns(["x"]), raw) + channel = run_on_channels(SelectDataColumns(["x"]), [raw], None) + for result in (sync, channel): + assert_same_table(result.as_table(columns=ALL).select([SYSTEM_TAG]), expected) # --- Ending the output and closing the inputs ------------------------------------------------ diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 470308051..28df9a809 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -6,6 +6,7 @@ from collections.abc import Collection from pathlib import Path from typing import Any, TypedDict +from uuid import UUID import deltalake import polars as pl @@ -16,6 +17,7 @@ from orcapod import PipelineJob from orcapod.contexts.stored import with_data_context 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, @@ -119,6 +121,13 @@ def _source( deltalake.write_deltalake(path / "delta", table) return DeltaTableSource(path / "delta", **options) if kind == "sqlite": + if any(field.metadata for field in table.schema): + # SQLite cannot store Arrow field metadata. Supply it at the reader boundary. + monkeypatch.setattr( + "orcapod.core.sources.sqlite_table_source.SQLiteConnector", + lambda *_: _Connector(table), + ) + return SQLiteTableSource(path / "rows.db", "rows", **options) file = path / "rows.db" types = {pa.string(): "TEXT", pa.int64(): "INTEGER"} cols = ", ".join( @@ -211,6 +220,81 @@ def test_refuses_missing_custom_system_tag_columns( _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, @@ -502,11 +586,13 @@ def get_all_records( derived.as_table() -def test_spiral_can_nominate_a_tag_copy_as_a_custom_system_tag( +@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), pa.field("x", pa.int8(), False)] + [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): @@ -515,14 +601,24 @@ def test_spiral_can_nominate_a_tag_copy_as_a_custom_system_tag( ) external.write(table) external.record(schema) - source = SpiralDBTableSource( - "project", - "rows", - tag_columns=["k"], - tag_only_columns=True, - tags_as_data={"k": "copy"}, - system_tag_columns=["copy"], - ) + + 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", diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 1040a7074..e2fb9e006 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -47,6 +47,7 @@ import sys import warnings from collections.abc import Callable, Sequence +from contextlib import aclosing from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -81,6 +82,7 @@ from orcapod.system_constants import ( OPERATOR_DB_SCHEMA_VERSION, PIPELINE_DB_SCHEMA_VERSION, + constants, ) from orcapod.types import Condition from orcapod.operators import ( @@ -112,12 +114,14 @@ ArrowTableSource, CachedSource, CSVSource, + DBTableSource, DataFrameSource, DeltaTableSource, DerivedSource, DictSource, ListSource, PollingSource, + PostgreSQLTableSource, SQLiteTableSource, SpiralDBTableSource, ) @@ -140,6 +144,8 @@ make_source, ) from .order_rules import KNOWN_VIOLATIONS, ORDER_EXCEPTIONS +from .sources.test_source_arrow_validation import _Connector +from tests.test_databases import fake_spiral_sdk pytestmark = [ pytest.mark.filterwarnings( @@ -857,18 +863,16 @@ def _side_effect(role: str, order: int, layout: str, _tmp: Path) -> Any: "SQLiteTableSource": "sqlite_table_source", "PollingSource": "polling_source", "CachedSource": "cached_source", - "DerivedSource": "derived_source_tags_as_data", # plain: test_a_job_... + "DerivedSource": "derived_source_tags_as_data", # plain: test_plain_derived_source_... "ArrowTableStream": "raw_arrow_table_stream", } NOT_APPLICABLE: dict[str, str] = { "RootSource": "the abstract base of every source", "StreamBase": "the abstract base of every stream", - "StreamView": "a view of rows a stream already has; it orders nothing", + "StreamView": "exposes its table and has no sync or async datagram iterator", "SourceProxy": "stands in for a source a loaded job cannot rebuild; it reads nothing", - "DBTableSource": "the base of the database sources; SQLiteTableSource is its case", - "PostgreSQLTableSource": "needs a PostgreSQL server; a DBTableSource like SQLite", - "SpiralDBTableSource": "needs a SpiralDB project; reads through the same builder", } +CONNECTOR_KINDS = (DBTableSource, PostgreSQLTableSource, SpiralDBTableSource) def _kind_names() -> set[str]: @@ -889,8 +893,9 @@ def _kind_names() -> set[str]: def test_every_exported_source_and_stream_kind_has_a_case() -> None: """A new source or stream kind fails here until it has a case (or a reason).""" - assert _kind_names() == set(KIND_CASES) | set(NOT_APPLICABLE) - assert not set(KIND_CASES) & set(NOT_APPLICABLE) + tested = set(KIND_CASES) | {kind.__name__ for kind in CONNECTOR_KINDS} + assert _kind_names() == tested | set(NOT_APPLICABLE) + assert not tested & set(NOT_APPLICABLE) labels = {case.label for case in STREAM_CASES} assert set(KIND_CASES.values()) <= labels @@ -923,32 +928,144 @@ def test_a_source_stream_or_pod_does_not_depend_on_the_arrangement_of_its_input( assert_all_equal(results) +async def _iter_async_rows(stream: Any, count: int) -> list[Any]: + async with aclosing(stream.async_iter_data()) as rows: + if isinstance(stream, PollingSource): + # Polling subscriptions are live. Read the rows of the finite snapshot. + async with asyncio.timeout(5): + return [await anext(rows) for _ in range(count)] + return [row async for row in rows] + + +def _assert_stream_and_row_fields(stream: Any, *, native_async: bool) -> None: + columns = {"system_tags": True} + table = stream.as_table(columns=columns) + user_tags, data_names = stream.keys() + tag_names = set(user_tags) | { + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + } + sync_rows = list(stream.iter_data()) + async_rows = asyncio.run( + _run_async(stream.producer, list(stream.upstreams)) + if native_async + else _iter_async_rows(stream, table.num_rows) + ) + for path, rows in (("sync", sync_rows), ("async", async_rows)): + assert len(rows) == table.num_rows, path + for tag, data in rows: + tag_table, data_table = tag.as_table(columns=columns), data.as_table() + assert set(tag_table.column_names) == tag_names, path + assert set(data_table.column_names) == set(data_names), path + for row_table in (tag_table, data_table): + expected = table.select(row_table.column_names).schema + assert row_table.schema.equals(expected, check_metadata=True), ( + path, + row_table.schema, + expected, + ) + + @pytest.mark.parametrize( "case", [*STREAM_CASES], ids=[case.label for case in STREAM_CASES] ) def test_stream_and_rows_agree_on_tag_and_primary_data_fields( case: StreamCase, tmp_path: Path ) -> None: - """Rows keep the stream's declared fields across tag orders and layouts.""" - columns = {"system_tags": True} + """Compare row fields to the table in both modes across tag orders and layouts. + + Connector-backed kinds have their own fixture below. The only exclusions + are the abstract RootSource and StreamBase, StreamView (table only), and + SourceProxy (represents a missing source and cannot read rows). + The standalone SideEffectPod exposes the stream iterator. Async delivery + through the job executor is exercised by the job tests below. + """ for order, layout in ARRANGEMENTS: stream = case.build(case.roles[0], order, layout, tmp_path) - table = stream.as_table(columns=columns) - rows = [list(stream.iter_data())] - if case.with_async: - rows.append( - asyncio.run(_run_async(stream.producer, list(stream.upstreams))) + _assert_stream_and_row_fields(stream, native_async=case.with_async) + + +@pytest.mark.parametrize("kind", CONNECTOR_KINDS, ids=lambda kind: kind.__name__) +def test_database_stream_and_rows_agree_on_tag_and_primary_data_fields( + kind: type[DBTableSource] | type[SpiralDBTableSource], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """DB and PostgreSQL use a connector double. SpiralDB scans a local SDK fake.""" + for i, (order, layout) in enumerate(ARRANGEMENTS): + raw = table(MAIN, order, layout) + tags = MAIN.tag_orders()[order] + if kind is SpiralDBTableSource: + with fake_spiral_sdk.install(tmp_path / str(i)): + external = fake_spiral_sdk.ExternalProject("project").create_table( + "default.rows", + key_schema=raw.select(MAIN.tags).schema, + ) + external.write(raw) + external.record(raw.schema) + stream = SpiralDBTableSource( + "project", + "rows", + tag_columns=tags, + tag_only_columns=True, + ) + _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, + ) + stream = PostgreSQLTableSource( + "postgresql://localhost/test", + "rows", + tag_columns=tags, + tag_only_columns=True, + record_id_columns=MAIN.tags, + ) + else: + stream = DBTableSource( + connector, + "rows", + tag_columns=tags, + source_id="rows", + tag_only_columns=True, + record_id_columns=MAIN.tags, + ) + _assert_stream_and_row_fields(stream, native_async=False) + + +def test_plain_derived_source_and_rows_agree_on_primary_data_fields() -> None: + for order, layout in ARRANGEMENTS: + job = PipelineJob(name="fields", database=InMemoryArrowDatabase()) + with job: + SelectDataColumns(["d1", "d2", "d3"])( + source(MAIN, PLAIN, order, layout), label="selected" ) - for path_rows in rows: - assert len(path_rows) == table.num_rows - for tag, data in path_rows: - for row_table in (tag.as_table(columns=columns), data.as_table()): - assert all( - field.equals( - table.schema.field(field.name), check_metadata=True - ) - for field in row_table.schema - ) + node = job.nodes["selected"] + node.attach_databases(pipeline_database=job.database, cache_mode=CacheMode.LOG) + job.run() + _assert_stream_and_row_fields(node.as_source(), native_async=False) + + +@pytest.mark.parametrize( + "case", + [ + pytest.param(case, id=case.label) + for cases in OPERATOR_CASES.values() + for case in cases + ], +) +def test_operator_stream_and_rows_agree_on_tag_and_primary_data_fields( + case: OperatorCase, +) -> None: + """Exercise every exported operator's native sync and async row paths.""" + for order, layout in ARRANGEMENTS: + stream = case.build()(*case.sources(case.roles[0], order, layout)) + _assert_stream_and_row_fields(stream, native_async=True) @pytest.mark.parametrize("role", ROLES) diff --git a/tests/test_core/test_row_ids.py b/tests/test_core/test_row_ids.py index 4d552a5a7..7c86aa7a0 100644 --- a/tests/test_core/test_row_ids.py +++ b/tests/test_core/test_row_ids.py @@ -21,6 +21,7 @@ from orcapod.core.data_function import output_source_info from orcapod.core.datagrams import Data, Tag from orcapod.core.datagrams.tag_data import EmptyData +from orcapod.core.streams import ArrowTableStream from orcapod.system_constants import constants HASHER = get_default_context().arrow_hasher @@ -54,6 +55,34 @@ def _binary(value: bytes) -> "pa.Array[Any]": return pa.array([value], type=pa.large_binary()) +@pytest.mark.parametrize( + ("arrow_type", "values"), + [(pa.null(), [None, None]), (pa.large_list(pa.null()), [[None], [None, None]])], +) +def test_entry_id_explains_how_to_replace_a_raw_null_system_tag( + arrow_type: pa.DataType, + values: list[Any], +) -> None: + name = "_tag_record_id::seed" + stream = ArrowTableStream( + pa.table( + { + "subject": pa.array(["m1", "m2"], pa.large_string()), + "session": [1, 2], + "_tag_source_id::seed": pa.array( + ["source", "source"], pa.large_string() + ), + name: pa.array(values, type=arrow_type), + "weight": [25, 30], + } + ), + tag_columns=["subject", "session"], + ) + for tag, data in stream.iter_data(): + with pytest.raises(ValueError, match=rf"{name}.*supported nullable type"): + row_ids.entry_id(HASHER, tag, data) + + class TestEntryId: def test_the_preimage_is_the_tags_the_system_tags_and_the_labelled_data_hash( self, diff --git a/tests/test_pipeline/test_review_findings_510.py b/tests/test_pipeline/test_review_findings_510.py index d2467f69f..b41697476 100644 --- a/tests/test_pipeline/test_review_findings_510.py +++ b/tests/test_pipeline/test_review_findings_510.py @@ -180,7 +180,7 @@ def keys(self, **kwargs: Any) -> Any: assert reads == [1] -# ── streams/base.py:550 (2): system tags the rows retype take the row path ──── +# ── streams/base.py:550 (2): raw stream system-tag fields on channels ───────── def _with_system_tag(column: pa.Array[Any]) -> ArrowTableStream: @@ -197,12 +197,10 @@ def _with_system_tag(column: pa.Array[Any]) -> ArrowTableStream: ], ids=["int16", "int32", "string"], ) -def test_a_channel_on_a_stream_gives_the_rows_system_tag_types( +def test_a_channel_on_a_raw_stream_keeps_the_declared_system_tag_field( column: pa.Array[Any], ) -> None: - """A channel opened on an exact ``ArrowTableStream`` whose system tag rows would - retype delivers what the rows build (``main``'s row path), e.g. ``int16`` as - ``int64``.""" + """Both the channel and the row-built table carry the stream's declared field.""" from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams.base import ZERO_ROW_INPUT_COLUMNS @@ -212,16 +210,18 @@ def test_a_channel_on_a_stream_gives_the_rows_system_tag_types( list(stream.iter_data()), stream ).as_table(columns=ZERO_ROW_INPUT_COLUMNS) (name,) = [n for n in delivered.column_names if n.startswith("_tag")] - assert delivered.schema.field(name).type == built.schema.field(name).type + expected = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS).schema.field(name) + assert delivered.schema.field(name).equals(expected, check_metadata=True) + assert built.schema.field(name).equals(expected, check_metadata=True) assert delivered[name].to_pylist() == built[name].to_pylist() -def test_a_channel_on_a_stream_whose_rows_cannot_make_one_table_raises() -> None: - """A string system tag holding a null and a value: the rows cannot make one - table; the channel raises what ``main``'s row build raises.""" +def test_a_channel_keeps_null_values_in_a_nullable_raw_system_tag() -> None: + """A single nullable field can hold the rows with and without a value.""" stream = _with_system_tag(pa.array(["a", None], pa.large_string())) - with pytest.raises(pa.ArrowInvalid): - asyncio.run(stream.open_channel().collect()) + table = pa.Table.from_batches(asyncio.run(stream.open_channel().collect())) + assert table.schema.field("_tag_e").equals(pa.field("_tag_e", pa.large_string())) + assert table.column("_tag_e").to_pylist() == ["a", None] def _arrow_table_source() -> ArrowTableSource: diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 1aac055ef..490d493e7 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -18,6 +18,7 @@ from orcapod import PipelineJob from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError from orcapod.operators import Batch from orcapod.pipeline.dag import OrcaDAG from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -911,10 +912,8 @@ def _system_tag_job(values: list[int | None], exact: bool) -> tuple[Any, Any]: return job, database -def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: - """A result over an exact ``ArrowTableStream`` with an ``int16`` system tag: kept, - stored and record-hashed as ``main``'s rows give it (``int64``, non-null), the - same as ``main``'s own row path (an unproven stream) gives.""" +def test_a_narrow_raw_system_tag_is_stored_with_its_declared_field() -> None: + """Both the exact stream and the fallback row path keep the declared field.""" from orcapod.system_constants import constants name = f"{constants.SYSTEM_TAG_PREFIX}region" @@ -924,35 +923,34 @@ def test_a_narrow_system_tag_is_stored_as_the_rows_give() -> None: job.run() node: Any = job.nodes["marked"] kept = node.as_table(columns={"system_tags": True}).schema.field(name) - assert (kept.type, kept.nullable) == (pa.int64(), False) + assert kept.equals(pa.field(name, pa.int16()), check_metadata=True) stored[exact] = database.at("log").get_all_records( node._stored_table_path, # pyright: ignore[reportPrivateUsage] # the raw LOG table record_id_column="_record_hash", ) for table in stored.values(): field = table.schema.field(name) - assert (field.type, field.nullable) == (pa.int64(), False) + assert field.equals(pa.field(name, pa.int16()), check_metadata=True) assert ( stored[True]["_record_hash"].to_pylist() == stored[False]["_record_hash"].to_pylist() ) -def test_a_null_system_tag_raises_at_the_operator_as_main_does() -> None: - """With a null among its values, ``main``'s rows cannot make one table: the - operator raises ``ArrowInvalid`` before its end event, as on ``main``.""" +def test_an_operator_keeps_null_values_in_a_nullable_raw_system_tag() -> None: + """A nullable declared field lets rows with and without a value share a table.""" job, _ = _system_tag_job([None, 2], exact=True) observer = _NodeEvents() - with pytest.raises(pa.ArrowInvalid): - job.run(observer=observer) + job.run(observer=observer) assert ("start", "marked") in observer.events - assert ("end", "marked") not in observer.events + assert ("end", "marked") in observer.events + table = job.nodes["marked"].as_table(columns={"system_tags": True}) + assert table.schema.field("_tag_region").equals(pa.field("_tag_region", pa.int16())) + assert table.column("_tag_region").to_pylist() == [None, 2] -def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: - """The source route's guard: an exact ``ArrowTableSource`` whose system tag is a - narrow integer has a table that is not its rows (they give ``int64``); a stock - source's system tags are what the rows give.""" +def test_a_source_refuses_a_non_text_custom_system_tag() -> None: + """Source-built system tags must be non-nullable text.""" from orcapod.core.streams.base import system_tags_as_rows_give schema = pa.schema( @@ -962,17 +960,17 @@ def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: pa.field("region", pa.int16(), nullable=False), ] ) - narrow = ArrowTableSource( - pa.Table.from_pylist( - [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], - schema=schema, - ), - tag_columns=["k"], - tag_only_columns=True, - system_tag_columns=["region"], - source_id="s", - ) - assert not system_tags_as_rows_give(narrow.as_table(columns={"system_tags": True})) + with pytest.raises(InputValidationError, match=r"'region'.*non-nullable string"): + ArrowTableSource( + pa.Table.from_pylist( + [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], + schema=schema, + ), + tag_columns=["k"], + tag_only_columns=True, + system_tag_columns=["region"], + source_id="s", + ) stock = _plain() assert system_tags_as_rows_give(stock.as_table(columns={"system_tags": True})) From 5d3f24bee1e0ce72f59ba33cd12388840b219484 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 16:52:32 -0800 Subject: [PATCH 6/9] fix(streams): validate replayed source tags and share tied Join sorting (ITL-1543) --- changelog.d/ITL-1543.md | 6 +- src/orcapod/core/operators/join.py | 74 +--------- src/orcapod/core/sources/cached_source.py | 35 +++-- src/orcapod/core/sources/data_frame_source.py | 6 + src/orcapod/core/sources/derived_source.py | 4 +- src/orcapod/core/sources/polling_source.py | 11 +- src/orcapod/core/sources/source_proxy.py | 23 +++- src/orcapod/core/sources/stream_builder.py | 54 +++++++- .../test_native_async_operators.py | 23 ++-- .../operators/test_async_sync_equivalence.py | 64 +++++++++ .../sources/test_source_arrow_validation.py | 130 +++++++++++++++++- tests/test_core/test_order_invariance.py | 20 ++- 12 files changed, 328 insertions(+), 122 deletions(-) diff --git a/changelog.d/ITL-1543.md b/changelog.d/ITL-1543.md index a5e29a0e3..f552f242c 100644 --- a/changelog.d/ITL-1543.md +++ b/changelog.d/ITL-1543.md @@ -7,7 +7,8 @@ Convert custom tags to text before building the source. - Sources refuse Arrow field metadata on nominated custom system tags, including tag copies nominated with `system_tag_columns`. Remove the field metadata before - building the source. ITL-1561 tracks re-evaluating this restriction. + building the source. Rebuild a source cache if it was written with field + metadata on a system tag. ITL-1561 tracks re-evaluating this restriction. ### Fixed @@ -19,5 +20,6 @@ nullability, and metadata. Standalone async Join uses those fields as well. IDs can change for hand-built streams with unusual system-tag fields. - Standalone async Join uses the same fields as the table and sync rows for - sorted system tags of tied inputs. Entry-ID errors for a raw Arrow Null system + sorted system tags of tied inputs, and leaves custom tags with their operands. + Entry-ID errors for a raw Arrow Null system tag name the column and ask for a supported nullable type. diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index fb14c24d6..ef9ad59ca 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -1161,7 +1161,7 @@ def _join_system_tag_tables( present = [table for table in tables if table is not None] if not present: return None - return Join._sort_merged_system_tags(arrow_utils.hstack_tables(*present)) + return arrow_utils.sort_system_tag_values(arrow_utils.hstack_tables(*present)) @staticmethod def _build_tag( @@ -1352,78 +1352,6 @@ def _merge_pair_passthrough( left_tag, left_pkt, right_tag, right_pkt, final=final ) - @staticmethod - def _sort_merged_system_tags(table: "pa.Table") -> "pa.Table": - """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 table.column_names: - 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) :] - - take_from: dict[str, str] = {} - for positions in groups.values(): - if len(positions) <= 1: - continue - - positions_in_order = sorted(positions, key=int) - - def sort_key(fields: dict[str, str]) -> tuple[Any, Any]: - source = fields.get(sid_field) - record = fields.get(rid_field) - source_value = table.column(source)[0].as_py() if source else None - record_value = table.column(record)[0].as_py() if record else None - return source_value or "", record_value or b"" - - sorted_fields = sorted( - (positions[position] for position in positions_in_order), key=sort_key - ) - for position, source_fields in zip(positions_in_order, sorted_fields): - for kind, name in positions[position].items(): - if kind in source_fields: - take_from[name] = source_fields[kind] - - if not take_from: - return table - nullable = arrow_utils.sorted_system_tag_nullability( - {field.name: field.nullable for field in table.schema} - ) - sources = [take_from.get(name, name) for name in table.column_names] - fields = [ - arrow_utils.sorted_system_tag_field(field, nullable[field.name]) - if field.name in nullable - else field.with_nullable( - field.nullable or table.schema.field(source).nullable - ) - for field, source in zip(table.schema, sources) - ] - return pa.Table.from_arrays( - [table.column(source) for source in sources], schema=pa.schema(fields) - ) - def rows_dropped_text( self, position: int, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 15501c76c..a7ac3bdb2 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -14,7 +14,10 @@ from orcapod.config import OrcapodConfig from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id -from orcapod.core.sources.stream_builder import require_supported_nullable_types +from orcapod.core.sources.stream_builder import ( + require_supported_nullable_types, + validate_source_table, +) from orcapod.errors import ( CachedSourceIdMismatchError, InputValidationError, @@ -363,7 +366,7 @@ def _live_records(self) -> pa.Table: live_table = self._source.as_table( columns={"source": True, "system_tags": True, "meta": True} ) - require_supported_nullable_types(live_table.schema) + validate_source_table(live_table) live_table = live_table.drop( [ name @@ -423,9 +426,7 @@ def _source_modified_time(self) -> datetime | None: def _cached_record_hashes(self) -> set[bytes]: """The record hashes of the rows cached under the current data context.""" self._account_for_stale_tables() - records = self._cache_database.get_all_records( - self.cache_path, record_id_column=self.HASH_COLUMN_NAME - ) + records = self._read_cache_table() if records is None: return set() records = keep_rows_of_data_context(records, self.data_context_key) @@ -495,6 +496,17 @@ def check_for_new_data(self) -> bool: self._update_modified_time() return True + def _read_cache_table(self) -> pa.Table | None: + """Read and validate the physical cache before using any of its columns.""" + records = self._cache_database.get_all_records( + self.cache_path, record_id_column=self.HASH_COLUMN_NAME + ) + return ( + None + if records is None + else validate_source_table(records, stored_cache=True) + ) + def _read_cached_records(self) -> "pa.Table | None": """Read the cached rows written under the current data context. @@ -526,12 +538,9 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": InputValidationError: If a cached column reads back as another Arrow type. """ self._account_for_stale_tables() - records = self._cache_database.get_all_records( - self.cache_path, record_id_column=self.HASH_COLUMN_NAME - ) + records = self._read_cache_table() if records is None: return None - require_supported_nullable_types(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) if records.num_rows < stored_rows and not self._skipped_rows_reported: @@ -559,9 +568,7 @@ def _require_rows_of_this_source(self) -> None: """ if self._source_ids_checked: return - records = self._cache_database.get_all_records( - self.cache_path, record_id_column=self.HASH_COLUMN_NAME - ) + records = self._read_cache_table() if records is None: return self._require_source_ids( @@ -731,9 +738,7 @@ def _typed_zero_row_table(self) -> "pa.Table | None": See ``typed_zero_row_table``; neither the cache nor the source is read. """ table = typed_zero_row_table(self._source) - if table is not None: - require_supported_nullable_types(table.schema) - return table + return None if table is None else validate_source_table(table) def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the wrapped source.""" diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 54a563f88..6ee764b16 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -14,6 +14,7 @@ normalize_record_id_columns, require_custom_system_tags, require_supported_nullable_types, + require_system_tag_without_field_metadata, ) from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -65,6 +66,11 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) + # Polars does not preserve Arrow field metadata across this conversion. + if isinstance(data, (pa.Table, pa.RecordBatch)): + for field in data.schema: + if field.name in system_tag_columns: + require_system_tag_without_field_metadata(field) df = pl.DataFrame(data) # Convert any Object-dtype columns to Arrow-compatible types. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index aeef4bfd5..a9bf44561 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -20,6 +20,7 @@ from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( require_supported_nullable_types, + validate_source_table, SourceStreamBuilder, normalize_record_id_columns, ) @@ -809,9 +810,8 @@ 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) - require_supported_nullable_types(table.schema) return ArrowTableStream( - table, + validate_source_table(table), tag_columns=self._origin.keys()[0], data_tags=self._data_tags(), ) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b4f65398..17a3bc733 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -29,6 +29,7 @@ SourceStreamBuilder, normalize_record_id_columns, require_supported_nullable_types, + validate_source_table, ) from orcapod.core.streams.view import ( ViewStatus, @@ -561,8 +562,9 @@ def _typed_zero_row_table(self) -> pa.Table | None: table = typed_zero_row_table(batch) if table is None: return None - require_supported_nullable_types(table.schema) - zero_rows = ArrowTableStream(table=table, tag_columns=self._tag_columns) + zero_rows = ArrowTableStream( + table=validate_source_table(table), tag_columns=self._tag_columns + ) result = zero_rows if result is None else self._combine(result, zero_rows) return typed_zero_row_table(result) @@ -1084,8 +1086,9 @@ def _combine( ], promote_options="default", ) - require_supported_nullable_types(combined.schema) - return ArrowTableStream(table=combined, tag_columns=self._tag_columns) + return ArrowTableStream( + table=validate_source_table(combined), tag_columns=self._tag_columns + ) def _mark_new_rows(self, committed: ArrowTableStream | None) -> bool: """Move the modified time to now if the batch just committed holds rows. diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..143a044fb 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -17,6 +17,7 @@ from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id +from orcapod.core.sources.stream_builder import validate_source_table from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -259,10 +260,18 @@ def _typed_zero_row_table(self) -> pa.Table | None: See ``typed_zero_row_table``. An unbound proxy knows only its stored Python schema (a known limitation, ITL-912). """ - return typed_zero_row_table(self._delegate) + table = typed_zero_row_table(self._delegate) + return None if table is None else validate_source_table(table) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: - return self._require_delegate().iter_data() + delegate = self._require_delegate() + + def checked_rows() -> Iterator[tuple[TagProtocol, DataProtocol]]: + for tag, data in delegate.iter_data(): + validate_source_table(tag.as_table(columns={"system_tags": True})) + yield tag, data + + return checked_rows() def as_table( self, @@ -270,7 +279,9 @@ def as_table( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> pa.Table: - return self._require_delegate().as_table(columns=columns, all_info=all_info) + return validate_source_table( + self._require_delegate().as_table(columns=columns, all_info=all_info) + ) def head( self, @@ -281,9 +292,9 @@ def head( ) -> StreamView: """Return the bound source's head, or no rows when no live source is bound.""" if self._delegate is not None: - return head_of( - self._delegate.head(n, columns=columns, all_info=all_info), self - ) + view = self._delegate.head(n, columns=columns, all_info=all_info) + validate_source_table(view.table) + return head_of(view, self) check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) return self._head_without_rows( diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 2c9ad4407..3a76b4eca 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -51,11 +51,54 @@ def require_supported_nullable_types(schema: pa.Schema) -> None: ) +def require_system_tag_without_field_metadata( + field: pa.Field[Any], *, stored_cache: bool = False +) -> None: + """Refuse field metadata on a system tag before it can reach source rows.""" + # Stopgap (ITL-1561): re-evaluate what metadata a system-tag field may carry. + # Extension metadata reaches the row hash now that rows use stream fields. + if not field.metadata: + return + if stored_cache: + raise InputValidationError( + f"System-tag column {field.name!r}: the source cache was written with " + "Arrow field metadata on a system tag. Rebuild the cache." + ) + raise InputValidationError( + f"Custom system-tag column {field.name!r} has Arrow field metadata. " + "Remove the field metadata before building the source." + ) + + +def validate_source_table(table: pa.Table, *, stored_cache: bool = False) -> pa.Table: + """Validate an enriched table presented by a source without the source builder. + + Args: + table: Source fields and values, with system tags already named as such. + stored_cache: Report the rebuild remedy for a persisted source cache. + + Returns: + 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. @@ -63,6 +106,7 @@ def require_custom_system_tags( 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. @@ -80,12 +124,10 @@ def require_custom_system_tags( ) for name in names: field = fields.field(name) - # ITL-1561: Re-evaluate which Arrow field metadata a system tag may carry. - # Extension metadata reaches the row hash now that rows use stream fields. - if field.metadata or table.schema.field(name).metadata: - raise InputValidationError( - f"Custom system-tag column {name!r} has Arrow field metadata. " - "Remove the field metadata before building the source." + 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 ( diff --git a/tests/test_channels/test_native_async_operators.py b/tests/test_channels/test_native_async_operators.py index 9cf7cc944..058ab42c9 100644 --- a/tests/test_channels/test_native_async_operators.py +++ b/tests/test_channels/test_native_async_operators.py @@ -43,6 +43,7 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.system_constants import constants from orcapod.types import ContentHash +from orcapod.utils.arrow_utils import sort_system_tag_values # --------------------------------------------------------------------------- @@ -2231,8 +2232,8 @@ 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.""" +class TestSortSystemTagValues: + """Unit tests for the sorter shared by both Join paths.""" def test_sorts_same_provenance_path_by_value(self): """System tag values at different positions within the same provenance @@ -2245,9 +2246,9 @@ def test_sorts_same_provenance_path_by_value(self): "_tag_source_id::abc123:1": "a_source", "_tag_record_id::abc123:1": "a_record", } - result = Join._sort_merged_system_tags( - pa.Table.from_pylist([merged_sys]) - ).to_pylist()[0] + result = sort_system_tag_values(pa.Table.from_pylist([merged_sys])).to_pylist()[ + 0 + ] # After sorting, position 0 should have the smaller values assert result["_tag_source_id::abc123:0"] == "a_source" @@ -2261,9 +2262,9 @@ def test_single_position_unchanged(self): "_tag_source_id::abc123:0": "only_source", "_tag_record_id::abc123:0": "only_record", } - result = Join._sort_merged_system_tags( - pa.Table.from_pylist([merged_sys]) - ).to_pylist()[0] + result = sort_system_tag_values(pa.Table.from_pylist([merged_sys])).to_pylist()[ + 0 + ] assert result == merged_sys def test_non_system_tag_keys_ignored(self): @@ -2273,9 +2274,9 @@ def test_non_system_tag_keys_ignored(self): "_tag_source_id::abc123:0": "src0", "_tag_record_id::abc123:0": "rec0", } - result = Join._sort_merged_system_tags( - pa.Table.from_pylist([merged_sys]) - ).to_pylist()[0] + result = sort_system_tag_values(pa.Table.from_pylist([merged_sys])).to_pylist()[ + 0 + ] assert result["regular_key"] == "value" diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 31595c3aa..50ba4c2f6 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -1098,6 +1098,70 @@ def test_standalone_async_join_rows_keep_declared_system_tag_fields( ) +@pytest.mark.parametrize("reverse_columns", [False, True]) +def test_tied_join_keeps_custom_system_tags_with_their_operand( + reverse_columns: bool, +) -> None: + source_id, record_id, custom = ( + "_tag_source_id::seed", + "_tag_record_id::seed", + "_tag_rev::seed", + ) + inputs = {} + for name in "abc": + 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(), False), + pa.field( + custom, pa.large_string(), name == "a", {b"owner": name.encode()} + ), + ] + ) + table = pa.Table.from_pylist( + [ + { + "k": i, + "g": group, + source_id: name, + record_id: record, + custom: f"{name}{i}", + } + for i, (group, record) in enumerate((("x", "p"), ("y", "q")), start=1) + ], + schema=schema, + ) + if reverse_columns: + table = table.select(list(reversed(table.column_names))) + inputs[name] = ArrowTableStream( + table, tag_columns=["k", "g"], data_tags=["k", "g"] + ) + assert len({stream.pipeline_hash() for stream in inputs.values()}) == 1 + columns = {"system_tags": True} + for order in itertools.permutations(inputs): + operands = [inputs[name] for name in order] + join = Join() + stream = join(*operands) + expected = stream.as_table(columns=columns) + prediction, _ = join.output_schema(*operands, columns=columns) + names = sorted( + name for name in expected.column_names if name.startswith(custom) + ) + for name, owner in zip(names, order, strict=True): + assert expected[name].to_pylist() == [f"{owner}1", f"{owner}2"] + assert prediction[name] == (str | None if owner == "a" else str) + for rows in (list(stream.iter_data()), async_rows(join, *operands)): + assert len(rows) == expected.num_rows + actual = pa.concat_tables( + [tag.as_table(columns=columns).select(names) for tag, _ in rows] + ) + target = expected.select(names) + assert actual.equals(target, check_metadata=True) + assert actual.schema.equals(target.schema, check_metadata=True) + + @pytest.mark.parametrize("reverse_columns", [False, True]) def test_raw_stream_rows_keep_system_tag_width_flags_and_metadata( reverse_columns: bool, diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 28df9a809..e5ba349d6 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import sqlite3 from collections.abc import Collection from pathlib import Path @@ -34,7 +35,7 @@ ) from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams import ArrowTableStream -from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import InputValidationError from orcapod.operators import DropNulls from orcapod.protocols.core_protocols import StreamProtocol @@ -475,6 +476,133 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: cached.as_table() +@pytest.mark.parametrize("route", ["table", "rows", "async_rows", "stored"]) +def test_reopened_cache_refuses_legacy_system_tag_metadata( + route: str, + tmp_path: Path, +) -> None: + source = ArrowTableSource( + _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" + pos = records.schema.get_field_index(name) + field = records.schema.field(pos).with_metadata( + {b"ARROW:extension:name": b"user.opaque"} + ) + records = records.set_column(pos, field, records.column(pos)) + records = records.append_column( + CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"]) + ) + DeltaTableDatabase(tmp_path).add_records( + cache.cache_path, + with_data_context(records, source.data_context_key), + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=True, + ) + reopened = CachedSource.from_config(cache.to_config()) + + async def consume() -> None: + _ = [row async for row in reopened.async_iter_data()] + + with pytest.raises( + InputValidationError, + match=r"'_tag_extra'.*cache.*written.*field metadata.*[Rr]ebuild", + ): + if route == "table": + reopened.as_table(columns=columns) + elif route == "rows": + list(reopened.iter_data()) + elif route == "async_rows": + asyncio.run(consume()) + else: + reopened.get_all_records() + + +@pytest.mark.parametrize("as_batch", [False, True]) +@pytest.mark.parametrize("declare_schema", [False, True]) +def test_dataframe_source_validates_nominated_arrow_fields_before_polars( + as_batch: bool, + declare_schema: bool, +) -> None: + table = _table( + pa.field("extra", pa.string(), False, metadata={b"owner": b"research"}), + ["a", "b"], + ) + data = table.to_batches()[0] if as_batch else table + schema = ( + table.schema.set( + table.num_columns - 1, table.schema.field("extra").remove_metadata() + ) + if declare_schema + else None + ) + with pytest.raises( + InputValidationError, match=r"'extra'.*[Rr]emove.*field metadata" + ): + DataFrameSource( + data, + schema=schema, + tag_columns=TAGS, + system_tag_columns=["rev", "extra"], + ) + + +@pytest.mark.parametrize("route", ["table", "rows", "async_rows", "head"]) +def test_bound_proxy_refuses_delegated_system_tag_metadata( + route: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = ArrowTableSource( + _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() + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + tags, + data, + ) + proxy.bind(source) + columns = {"system_tags": True} + table = source.as_table(columns=columns) + pos = table.schema.get_field_index("_tag_extra") + field = table.schema.field(pos).with_metadata({b"owner": b"research"}) + raw = ArrowTableStream( + table.set_column(pos, field, table.column(pos)), + tag_columns=TAGS, + ) + monkeypatch.setattr(source, "as_table", raw.as_table) + monkeypatch.setattr(source, "iter_data", raw.iter_data) + monkeypatch.setattr(source, "head", raw.head) + + 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" + ): + if route == "table": + proxy.as_table(columns=columns) + elif route == "rows": + list(proxy.iter_data()) + elif route == "async_rows": + asyncio.run(consume()) + else: + proxy.head(columns=columns) + + @pytest.mark.parametrize("stored_flag", [False, True]) def test_cached_source_reads_older_token_field_flags_as_stored( stored_flag: bool, diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index e2fb9e006..7c91c05c4 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -75,6 +75,7 @@ ) from orcapod.core.nodes.operator_node import OPERATOR_RECORDED_AT_COL from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import RestrictedAggregationWarning @@ -790,6 +791,20 @@ def _cached_source(role: str, order: int, layout: str, _tmp: Path) -> Any: ) +def _bound_source_proxy(role: str, order: int, layout: str, _tmp: Path) -> Any: + delegate = source(MAIN, role, order, layout) + tags, data = delegate.output_schema() + proxy = SourceProxy( + delegate.source_id, + delegate.content_hash().to_string(), + delegate.pipeline_hash().to_string(), + tags, + data, + ) + proxy.bind(delegate) + return proxy + + def _derived_source(role: str, order: int, layout: str, _tmp: Path) -> Any: return DerivedSource( source(MAIN, role, order, layout), @@ -842,6 +857,7 @@ def _side_effect(role: str, order: int, layout: str, _tmp: Path) -> Any: # PollingSource takes no tag_only_columns: its tags are plain. StreamCase("polling_source", _polling_source, roles=(PLAIN,)), StreamCase("cached_source", _cached_source), + StreamCase("bound_source_proxy", _bound_source_proxy), StreamCase("derived_source_tags_as_data", _derived_source), StreamCase("raw_arrow_table_stream", _raw_stream), StreamCase("function_pod_call", _pod_call, with_async=True), @@ -863,6 +879,7 @@ def _side_effect(role: str, order: int, layout: str, _tmp: Path) -> Any: "SQLiteTableSource": "sqlite_table_source", "PollingSource": "polling_source", "CachedSource": "cached_source", + "SourceProxy": "bound_source_proxy", "DerivedSource": "derived_source_tags_as_data", # plain: test_plain_derived_source_... "ArrowTableStream": "raw_arrow_table_stream", } @@ -870,7 +887,6 @@ def _side_effect(role: str, order: int, layout: str, _tmp: Path) -> Any: "RootSource": "the abstract base of every source", "StreamBase": "the abstract base of every stream", "StreamView": "exposes its table and has no sync or async datagram iterator", - "SourceProxy": "stands in for a source a loaded job cannot rebuild; it reads nothing", } CONNECTOR_KINDS = (DBTableSource, PostgreSQLTableSource, SpiralDBTableSource) @@ -977,7 +993,7 @@ def test_stream_and_rows_agree_on_tag_and_primary_data_fields( Connector-backed kinds have their own fixture below. The only exclusions are the abstract RootSource and StreamBase, StreamView (table only), and - SourceProxy (represents a missing source and cannot read rows). + the unbound form of SourceProxy (cannot read rows). The standalone SideEffectPod exposes the stream iterator. Async delivery through the job executor is exercised by the job tests below. """ From ab136d0fc13f5a7b5b1c9415733c78732720b683 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 17:04:03 -0800 Subject: [PATCH 7/9] fix(sources): validate Arrow exporters before Polars conversion (ITL-1543) --- src/orcapod/core/sources/data_frame_source.py | 32 ++++- .../sources/test_source_arrow_validation.py | 114 ++++++++++++++---- 2 files changed, 119 insertions(+), 27 deletions(-) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6ee764b16..dd6b0a51a 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -2,8 +2,9 @@ import logging from collections.abc import Collection -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar, cast +import pandas as pd import polars as pl import pyarrow as pa @@ -20,7 +21,11 @@ from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - from polars._typing import FrameInitTypes + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) logger = logging.getLogger(__name__) @@ -66,12 +71,27 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) - # Polars does not preserve Arrow field metadata across this conversion. - if isinstance(data, (pa.Table, pa.RecordBatch)): - for field in data.schema: + # Keep pandas and Polars on their native paths even if they export Arrow. + # For Arrow inputs, materialize once before Polars drops field metadata. + if not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)) and ( + hasattr(data, "__arrow_c_stream__") or hasattr(data, "__arrow_c_array__") + ): + # Like Polars, prefer the array export when both are available. + if hasattr(data, "__arrow_c_array__"): + batch = pa.record_batch(cast("ArrowArrayExportable", data)) + arrow_input = pa.Table.from_batches([batch]) + else: + arrow_input = pa.table(cast("ArrowStreamExportable", data)) + for field in arrow_input.schema: if field.name in system_tag_columns: require_system_tag_without_field_metadata(field) - df = pl.DataFrame(data) + # Polars rechunks native tables but preserves chunks on exporter inputs. + df = cast( + pl.DataFrame, + pl.from_arrow(arrow_input, rechunk=isinstance(data, pa.Table)), + ) + else: + df = pl.DataFrame(data) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index e5ba349d6..d72353008 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -525,33 +525,105 @@ async def consume() -> None: reopened.get_all_records() -@pytest.mark.parametrize("as_batch", [False, True]) +class _ArrowStreamExporter: + def __init__(self, table: pa.Table) -> None: + self.table = table + self.exports = 0 + + def __arrow_c_stream__(self, requested_schema: Any = None) -> Any: + self.exports += 1 + return self.table.__arrow_c_stream__(requested_schema) + + +class _ArrowArrayExporter: + def __init__(self, batch: pa.RecordBatch) -> None: + self.batch = batch + self.exports = 0 + + def __arrow_c_array__(self, requested_schema: Any = None) -> Any: + self.exports += 1 + return self.batch.__arrow_c_array__(requested_schema) + + +class _DualArrowExporter(_ArrowArrayExporter): + def __init__(self, batch: pa.RecordBatch, stream: pa.Table) -> None: + super().__init__(batch) + self.stream = stream + self.stream_exports = 0 + + def __arrow_c_stream__(self, requested_schema: Any = None) -> Any: + self.stream_exports += 1 + 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]) -def test_dataframe_source_validates_nominated_arrow_fields_before_polars( - as_batch: bool, +@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: - table = _table( - pa.field("extra", pa.string(), False, metadata={b"owner": b"research"}), - ["a", "b"], - ) - data = table.to_batches()[0] if as_batch else table - schema = ( - table.schema.set( - table.num_columns - 1, table.schema.field("extra").remove_metadata() + 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), ) - if declare_schema - else None ) - with pytest.raises( - InputValidationError, match=r"'extra'.*[Rr]emove.*field metadata" - ): - DataFrameSource( - data, - schema=schema, - tag_columns=TAGS, - system_tag_columns=["rev", "extra"], + 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", ["table", "rows", "async_rows", "head"]) From d902f4e39a90110ee13840748e23365040853398 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 17:25:48 -0800 Subject: [PATCH 8/9] test(sources): expect refusal of integer system tags (ITL-1543) --- tests/test_pipeline/test_rows_on_read.py | 29 ++++++++++++------------ 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 1aac055ef..c9385598e 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -18,6 +18,7 @@ from orcapod import PipelineJob from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError from orcapod.operators import Batch from orcapod.pipeline.dag import OrcaDAG from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -949,10 +950,8 @@ def test_a_null_system_tag_raises_at_the_operator_as_main_does() -> None: assert ("end", "marked") not in observer.events -def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: - """The source route's guard: an exact ``ArrowTableSource`` whose system tag is a - narrow integer has a table that is not its rows (they give ``int64``); a stock - source's system tags are what the rows give.""" +def test_a_source_refuses_a_non_text_custom_system_tag() -> None: + """Source-built system tags must be non-nullable text.""" from orcapod.core.streams.base import system_tags_as_rows_give schema = pa.schema( @@ -962,17 +961,17 @@ def test_a_source_table_with_other_system_tags_is_not_its_rows() -> None: pa.field("region", pa.int16(), nullable=False), ] ) - narrow = ArrowTableSource( - pa.Table.from_pylist( - [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], - schema=schema, - ), - tag_columns=["k"], - tag_only_columns=True, - system_tag_columns=["region"], - source_id="s", - ) - assert not system_tags_as_rows_give(narrow.as_table(columns={"system_tags": True})) + with pytest.raises(InputValidationError, match=r"'region'.*non-nullable string"): + ArrowTableSource( + pa.Table.from_pylist( + [{"k": 1, "x": 10, "region": 1}, {"k": 2, "x": 20, "region": 2}], + schema=schema, + ), + tag_columns=["k"], + tag_only_columns=True, + system_tag_columns=["region"], + source_id="s", + ) stock = _plain() assert system_tags_as_rows_give(stock.as_table(columns={"system_tags": True})) From 5f518d8137ce7e5796e56e3fd6e21e545c7151a7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 17:27:24 -0800 Subject: [PATCH 9/9] test(datagrams): expect preserved Arrow system tag fields (ITL-1543) --- tests/test_core/datagrams/test_lazy_conversion.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/test_core/datagrams/test_lazy_conversion.py b/tests/test_core/datagrams/test_lazy_conversion.py index 2673b6138..71902bb56 100644 --- a/tests/test_core/datagrams/test_lazy_conversion.py +++ b/tests/test_core/datagrams/test_lazy_conversion.py @@ -310,7 +310,7 @@ def test_copy_before_schema_is_computed_reports_correct_schema(self, include_cac class TestTagLazySystemTagsTable: - """_system_tags_table is built only when system_tags are explicitly requested.""" + """Dictionary tags build their table lazily and Arrow tags keep their fields.""" def test_dict_backed_starts_with_no_system_tags_table(self): t = Tag({"a": 1, f"{SYS}run": "run1"}) @@ -326,8 +326,9 @@ def test_arrow_backed_system_tag_columns_extracted_from_data_table(self): assert sys_col not in t._data_table.column_names # Captured in the system_tags dict assert t._system_tags[sys_col] == "run1" - # Table not yet built - assert t._system_tags_table is None + # Arrow-backed tags retain their declared fields at construction. + assert t._system_tags_table is not None + assert t._system_tags_table.equals(tbl.select([sys_col]), check_metadata=True) def test_system_tags_table_not_built_without_system_tags_flag(self): t = Tag({"a": 1, f"{SYS}run": "run1"})