diff --git a/.zed/rules b/.zed/rules index 987b73fd3..00ede7595 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1345,9 +1345,16 @@ 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. + 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..cb6f53381 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1393,9 +1393,16 @@ 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. + 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..f552f242c 100644 --- a/changelog.d/ITL-1543.md +++ b/changelog.d/ITL-1543.md @@ -5,6 +5,10 @@ - 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. Rebuild a source cache if it was written with field + metadata on a system tag. ITL-1561 tracks re-evaluating this restriction. ### Fixed @@ -12,3 +16,10 @@ 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. +- Standalone async Join uses the same fields as the table and sync rows for + 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/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..ef9ad59ca 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 @@ -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() } ) @@ -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 arrow_utils.sort_system_tag_values(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, @@ -1350,64 +1352,6 @@ def _merge_pair_passthrough( left_tag, left_pkt, right_tag, right_pkt, final=final ) - @staticmethod - def _sort_merged_system_tags(merged_sys: dict) -> dict: - """Sort system tag values within same-provenance-path groups. - - When two joined inputs share a pipeline_hash, their system tag - columns share a provenance path but occupy different canonical - positions. Sorting the paired (source_id, record_id) values - across positions ensures commutativity — mirroring what - ``sort_system_tag_values`` does on Arrow tables in - ``static_process``. - """ - sys_prefix = constants.SYSTEM_TAG_PREFIX - block_sep = constants.BLOCK_SEPARATOR - field_sep = constants.FIELD_SEPARATOR - - # Parse keys → groups[provenance_path][position][field_type] = key - groups: dict[str, dict[str, dict[str, str]]] = {} - for key in merged_sys: - if not key.startswith(sys_prefix): - continue - base, sep, position = key.rpartition(field_sep) - if not sep or not position.isdigit(): - continue - after_prefix = base[len(sys_prefix) :] - field_type, bsep, prov_path = after_prefix.partition(block_sep) - if not bsep: - continue - groups.setdefault(prov_path, {}).setdefault(position, {})[field_type] = key - - sid_field = constants.SYSTEM_TAG_SOURCE_ID_PREFIX[len(sys_prefix) :] - rid_field = constants.SYSTEM_TAG_RECORD_ID_PREFIX[len(sys_prefix) :] - - for _prov_path, positions in groups.items(): - if len(positions) <= 1: - continue - - sorted_pos_keys = sorted(positions.keys(), key=int) - - # Collect (sort_key, {field_type: value}) per position - entries: list[tuple[tuple, dict[str, object]]] = [] - for pos in sorted_pos_keys: - fmap = positions[pos] - sid_val = merged_sys.get(fmap.get(sid_field, "")) - rid_val = merged_sys.get(fmap.get(rid_field, "")) - vals = {ft: merged_sys[k] for ft, k in fmap.items()} - entries.append(((sid_val or "", rid_val or b""), vals)) - - entries.sort(key=lambda e: e[0]) - - # Write sorted values back to the original position keys - for pos, (_, sorted_vals) in zip(sorted_pos_keys, entries): - fmap = positions[pos] - for field_type, key in fmap.items(): - if field_type in sorted_vals: - merged_sys[key] = sorted_vals[field_type] - - return merged_sys - def rows_dropped_text( self, position: int, 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/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/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..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 @@ -14,12 +15,17 @@ 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 if TYPE_CHECKING: - from polars._typing import FrameInitTypes + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) logger = logging.getLogger(__name__) @@ -65,7 +71,27 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) - df = pl.DataFrame(data) + # 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) + # 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/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/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 b54428354..3a76b4eca 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) @@ -63,22 +51,67 @@ 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 names, types, field flags and values. + """Validate custom system-tag declarations and values. Args: table: The source's Arrow columns. names: The columns nominated as system tags. schema: The declared fields if the reader has yet to apply them. + stored_cache: Report the rebuild remedy for a persisted source cache. Raises: ValueError: If a nominated column is missing from the source table. - InputValidationError: If a nominated column 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 +124,11 @@ def require_custom_system_tags( ) for name in names: field = fields.field(name) + require_system_tag_without_field_metadata(field, stored_cache=stored_cache) + if schema is not None: + require_system_tag_without_field_metadata( + table.schema.field(name), stored_cache=stored_cache + ) has_nulls = table.column(name).null_count > 0 if ( field.nullable 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/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_channels/test_native_async_operators.py b/tests/test_channels/test_native_async_operators.py index 82c774af7..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,7 +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(merged_sys) + 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" @@ -2259,7 +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(merged_sys) + 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): @@ -2269,7 +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(merged_sys) + result = sort_system_tag_values(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/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"}) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 1a6a54096..50ba4c2f6 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,191 @@ 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" + schema = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("g", pa.large_string(), False), + pa.field(source_id, pa.large_string(), False), + pa.field(record_id, pa.large_string(), True), + ] + ) + inputs = [] + empty_inputs = [] + for source, records in (("a", [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} + for i, (group, record) in enumerate( + zip(("x", "y"), records, strict=True) + ) + ], + schema=fields, + ) + if reverse_columns: + table = table.select(list(reversed(schema.names))) + inputs.append( + ArrowTableStream(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 positions in itertools.permutations(range(len(inputs))): + ordered = [inputs[i] for i in positions] + empty = [empty_inputs[i] for i in positions] + join = Join() + stream = join(*ordered) + table = stream.as_table(columns=columns) + empty_table = join(*empty).as_table(columns=columns) + assert empty_table.num_rows == 0 + assert empty_table.schema.equals(table.schema, check_metadata=True) + tags, _ = join.output_schema(*ordered, columns=columns) + tag_names = [name for name in tags if name.startswith("_tag_")] + assert len(tag_names) == 6 + for name in tag_names: + field = table.schema.field(name) + assert field.metadata is None + assert field.nullable == name.startswith(record_id) + assert tags[name] == (str | None if field.nullable else str) + for rows in (list(stream.iter_data()), async_rows(join, *ordered)): + assert len(rows) == table.num_rows == 2 + for tag, data in rows: + tag_table = tag.as_table(columns=columns) + 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_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, +) -> 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/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 ff7f5d0b2..d72353008 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -2,10 +2,12 @@ from __future__ import annotations +import asyncio import sqlite3 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 +18,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, @@ -32,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 @@ -119,6 +122,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 +221,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, @@ -391,6 +476,249 @@ 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() + + +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]) +@pytest.mark.parametrize("field_metadata", [None, {b"owner": b"research"}]) +def test_dataframe_source_validates_arrow_inputs_before_polars( + representation: str, + row_count: int, + declare_schema: bool, + field_metadata: dict[bytes | str, bytes | str] | None, +) -> None: + clean = _table(pa.field("extra", pa.string(), False), ["a", "b"][:row_count]) + pos = clean.schema.get_field_index("extra") + table = ( + clean + if field_metadata is None + else clean.set_column( + pos, + clean.schema.field(pos).with_metadata(field_metadata), + clean.column(pos), + ) + ) + batch = pa.RecordBatch.from_arrays( + [c.combine_chunks() for c in table.columns], schema=table.schema + ) + representations = { + "table": table, + "batch": batch, + "reader": table.to_reader(max_chunksize=1), + "stream": _ArrowStreamExporter(table), + "array": _ArrowArrayExporter(batch), + "dual": _DualArrowExporter(batch, clean), + } + data = representations[representation] + schema = clean.schema if declare_schema else None + + if field_metadata is not None: + with pytest.raises( + InputValidationError, match=r"'extra'.*[Rr]emove.*field metadata" + ): + DataFrameSource( + data, + schema=schema, + tag_columns=TAGS, + system_tag_columns=["rev", "extra"], + ) + else: + source = DataFrameSource( + data, schema=schema, tag_columns=TAGS, system_tag_columns=["rev", "extra"] + ) + expected = DataFrameSource( + clean, schema=schema, tag_columns=TAGS, system_tag_columns=["rev", "extra"] + ) + columns = {"system_tags": True, "source": True} + actual_table = source.as_table(columns=columns) + assert actual_table.num_rows == row_count + assert actual_table.equals( + expected.as_table(columns=columns), check_metadata=True + ) + assert source.source_id == expected.source_id + assert source.content_hash() == expected.content_hash() + assert source.pipeline_hash() == expected.pipeline_hash() + + if isinstance(data, (_ArrowArrayExporter, _ArrowStreamExporter)): + assert data.exports == 1 + if isinstance(data, _DualArrowExporter): + assert data.stream_exports == 0 + + +@pytest.mark.parametrize("route", ["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, +) -> 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 @@ -458,11 +786,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): @@ -471,14 +801,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 9cdabf77b..7c91c05c4 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 @@ -74,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 @@ -81,6 +83,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 +115,14 @@ ArrowTableSource, CachedSource, CSVSource, + DBTableSource, DataFrameSource, DeltaTableSource, DerivedSource, DictSource, ListSource, PollingSource, + PostgreSQLTableSource, SQLiteTableSource, SpiralDBTableSource, ) @@ -140,6 +145,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( @@ -784,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), @@ -836,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), @@ -857,18 +879,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_... + "SourceProxy": "bound_source_proxy", + "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", - "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", + "StreamView": "exposes its table and has no sync or async datagram iterator", } +CONNECTOR_KINDS = (DBTableSource, PostgreSQLTableSource, SpiralDBTableSource) def _kind_names() -> set[str]: @@ -889,8 +909,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,6 +944,146 @@ 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: + """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 + 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. + """ + for order, layout in ARRANGEMENTS: + stream = case.build(case.roles[0], order, layout, tmp_path) + _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" + ) + 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) 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.""" 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 c9385598e..490d493e7 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -912,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" @@ -925,29 +923,30 @@ 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_refuses_a_non_text_custom_system_tag() -> None: