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/4] 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/4] 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/4] 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 d902f4e39a90110ee13840748e23365040853398 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 17:25:48 -0800 Subject: [PATCH 4/4] 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}))