From 135592e42c34bc29797593380c591a41ced84677 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:12:18 -0800 Subject: [PATCH 1/9] fix(sources): reject stored logical Arrow columns (ITL-1333) --- changelog.d/ITL-1333.md | 4 + docs/concepts/logical-type-identifiers.md | 6 + docs/dev/design_issues/ITL-1333-BL17.md | 15 + src/orcapod/core/sources/csv_source.py | 2 + src/orcapod/core/sources/data_frame_source.py | 27 +- src/orcapod/core/sources/db_table_source.py | 2 + .../core/sources/delta_table_source.py | 2 + src/orcapod/core/sources/derived_source.py | 1 + src/orcapod/core/sources/dict_source.py | 2 + src/orcapod/core/sources/polling_source.py | 10 +- .../core/sources/spiraldb_table_source.py | 2 + src/orcapod/core/sources/stream_builder.py | 85 ++++- .../sources/test_source_arrow_validation.py | 290 +++++++++++++++++- 13 files changed, 417 insertions(+), 31 deletions(-) create mode 100644 changelog.d/ITL-1333.md create mode 100644 docs/dev/design_issues/ITL-1333-BL17.md diff --git a/changelog.d/ITL-1333.md b/changelog.d/ITL-1333.md new file mode 100644 index 000000000..a335259cb --- /dev/null +++ b/changelog.d/ITL-1333.md @@ -0,0 +1,4 @@ +### Fixed + +- Sources reject Arrow fields that carry a logical type annotation on plain storage, + including nested fields. The error names the column and its logical type. diff --git a/docs/concepts/logical-type-identifiers.md b/docs/concepts/logical-type-identifiers.md index 4503148a5..7e366c24f 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -28,6 +28,12 @@ Two columns with the same identifier hold values in the same layout, hashed by t rule. Orcapod treats the identifier as opaque. It never interprets the metadata; it only stores it, hashes it and compares it byte for byte. +When you supply Arrow data to a source, logical columns must use their live Arrow +extension types. A plain storage field with an extension annotation is refused, including +inside a list, struct or map. Pass the column as its logical type, or remove the extension +annotation if the column is meant to hold plain data. Orcapod continues to decode its own +stored results when reading caches and derived sources. + ## Where the identifier goes - **Stored with the column.** The name and metadata are written as the column's diff --git a/docs/dev/design_issues/ITL-1333-BL17.md b/docs/dev/design_issues/ITL-1333-BL17.md new file mode 100644 index 000000000..2bf9f1806 --- /dev/null +++ b/docs/dev/design_issues/ITL-1333-BL17.md @@ -0,0 +1,15 @@ +## `src/orcapod/core/sources/` + +### BL17 — A source read a stored logical column as plain data +**Status:** resolved +**Severity:** high +**Issue:** ITL-1333 + +An Arrow source could read a Path column as text when the Arrow field carried the type +identifier in metadata. A live extension array with the same values had the same pipeline +and content hashes but gave downstream functions Path objects. + +**Fix:** Refuse external Arrow fields that carry logical annotations on their storage type, +including nested fields. Live extension fields and the existing decoding of Orcapod-owned +stored records retain their behavior. Resolving stored logical types at external source +boundaries is planned separately. diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index e44f9c189..270fc1b82 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -20,6 +20,7 @@ SourceStreamResult, require_custom_system_tags, require_supported_nullable_types, + require_live_logical_types, ) from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -351,6 +352,7 @@ def _read_table(self) -> pa.Table: require_supported_nullable_types(table.schema) return table.cast(arrow_utils.infer_schema_nullable(table)) require_supported_nullable_types(self._schema) + require_live_logical_types(self._schema, exclude=self._system_tag_columns) try: return _read_declared( self._access_path, self._schema, self._system_tag_columns diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index a435b32fb..171f5c99a 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -4,7 +4,6 @@ from collections.abc import Collection from typing import TYPE_CHECKING, Any, ClassVar, cast -import pandas as pd import polars as pl import pyarrow as pa @@ -13,9 +12,11 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + read_arrow_frame_input, declare_native_custom_system_tags, require_custom_system_tags, require_custom_system_tags_values, + require_live_logical_types, require_supported_nullable_types, ) from orcapod.errors import InputValidationError @@ -23,11 +24,7 @@ from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - from polars._typing import ( - ArrowArrayExportable, - ArrowStreamExportable, - FrameInitTypes, - ) + from polars._typing import FrameInitTypes logger = logging.getLogger(__name__) @@ -74,17 +71,11 @@ def __init__( super().__init__(source_id=source_id, **kwargs) arrow_input_schema = None - # 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)) + if ( + arrow_input := read_arrow_frame_input( + data, system_tag_columns=system_tag_columns + ) + ) is not None: if schema is None: require_custom_system_tags(arrow_input, system_tag_columns) else: @@ -93,6 +84,7 @@ def __init__( arrow_input, system_tag_columns, schema=schema ) arrow_input_schema = arrow_input.schema + require_live_logical_types(arrow_input_schema) # Polars rechunks native tables but preserves chunks on exporter inputs. df = cast( pl.DataFrame, @@ -138,6 +130,7 @@ def __init__( require_custom_system_tags( arrow_table, system_tag_columns, schema=schema ) + require_live_logical_types(schema) arrow_table = arrow_table.cast(schema) elif arrow_input_schema is not None: arrow_table = arrow_utils.restore_schema_nullability( diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 7bb5019de..d81050918 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -28,6 +28,7 @@ from orcapod.core.sources.stream_builder import ( require_custom_system_tags, require_supported_nullable_types, + require_live_logical_types, normalize_record_id_columns, SourceStreamBuilder, SourceStreamResult, @@ -229,6 +230,7 @@ def _read_table( if not batches: raise ValueError(f"Table {self._table_name!r} is empty.") table: pa.Table = pa.Table.from_batches(batches) + require_live_logical_types(table.schema, exclude=self._system_tag_columns) # Apply database-defined nullability: the connector's get_column_info # returns the authoritative nullable flag per column from the DB schema. col_infos = connector.get_column_info(self._table_name) diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 8a9b272f1..a0261b1be 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -16,6 +16,7 @@ from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, SourceStreamBuilder, + require_live_logical_types, SourceStreamResult, ) from orcapod.databases.storage_utils import delta_to_pyarrow_dataset @@ -148,6 +149,7 @@ def check_for_new_data(self) -> bool: return False table = self._read_table() if not table.schema.equals(self._table.schema, check_metadata=True): + require_live_logical_types(table.schema) raise ValueError( f"Delta table {str(self._delta_table_path)!r} changed its columns at " f"version {version}: the source was built with {self._table.schema}, " diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1b00e7b05..64f3582fc 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -673,6 +673,7 @@ def _derive_from( source_name=self.source_name, kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), + from_origin=True, ) return result.stream diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 26eefb169..51317377b 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -16,6 +16,7 @@ normalize_record_id_columns, declare_native_custom_system_tags, require_supported_nullable_types, + require_live_logical_types, ) from orcapod.types import DataValue, SchemaLike from orcapod.utils import arrow_utils @@ -87,6 +88,7 @@ def __init__( # pa.Schema directly via data_schema; route to the converter accordingly. if isinstance(data_schema, pa.Schema): require_supported_nullable_types(data_schema) + require_live_logical_types(data_schema, exclude=system_tag_columns) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, arrow_schema=data_schema, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 6157f0893..14fedcfdf 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -28,6 +28,8 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + read_arrow_frame_input, + require_live_logical_types, require_supported_nullable_types, validate_source_table, ) @@ -332,8 +334,8 @@ def __init__( unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): require_supported_nullable_types(unified_schema) - # Logical types in one form first: a field declared with its identifier - # in ARROW:extension:* metadata is that logical type (ITL-640). + require_live_logical_types(unified_schema) + # Canonicalize the declaration for comparison to batch schemas (ITL-640). self._declared_arrow = declaration_form_schema( pa.schema( [ @@ -874,6 +876,10 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ + arrow_input = read_arrow_frame_input(data) + if arrow_input is not None: + require_live_logical_types(arrow_input.schema) + data = arrow_input df = pl.DataFrame(data) if len(df.columns) == 0: logger.debug( diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dcdd309c5..e12972379 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -63,6 +63,7 @@ from orcapod.core.sources.stream_builder import ( require_custom_system_tags, require_supported_nullable_types, + require_live_logical_types, SourceStreamBuilder, key_column_type_allowed, normalize_record_id_columns, @@ -934,6 +935,7 @@ def _read_batches( for start in range(0, max(batch.num_rows, 1), self._batch_rows): raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)]) require_supported_nullable_types(raw.schema) + require_live_logical_types(raw.schema) rows = arrow_utils.drop_system_columns(raw) # Metadata too: field metadata is how a column's logical type is # recorded, and the schema hash was computed at construction. diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 743de64aa..51e824d29 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -10,7 +10,7 @@ import datetime import json -from collections.abc import Collection, Sequence +from collections.abc import Collection, Iterator, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -24,6 +24,10 @@ ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError, RowIdentifierError +from orcapod.logical_types.canonical_form import ( + EXTENSION_METADATA_KEY, + EXTENSION_NAME_KEY, +) from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.system_constants import constants from orcapod.types import ContentHash @@ -31,10 +35,79 @@ from orcapod.utils.schema_utils import compute_schema_hash if TYPE_CHECKING: + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) + from orcapod.contexts import DataContext from orcapod.protocols.hashing_protocols import ArrowHasherProtocol +def _stored_logical_fields(field: pa.Field[Any]) -> Iterator[tuple[str, str]]: + """Yield the field paths and identifiers of logical types in storage form.""" + arrow_type = field.type + if isinstance(arrow_type, pa.BaseExtensionType): + # The live extension owns its storage layout. + return + metadata = field.metadata or {} + name = metadata.get(EXTENSION_NAME_KEY) + payload = metadata.get(EXTENSION_METADATA_KEY) + if name is not None: + decoded = name.decode("utf-8", errors="backslashreplace") + yield repr(field.name), f"{decoded!r} ({payload or b''!r})" + elif payload is not None: + yield repr(field.name), f" ({payload!r})" + for index in range(arrow_type.num_fields): + for path, identifier in _stored_logical_fields(arrow_type.field(index)): + yield f"{field.name!r}.{path}", identifier + + +def require_live_logical_types( + schema: pa.Schema, *, exclude: Collection[str] = () +) -> None: + """Refuse stored logical fields in external Arrow inputs, at any depth. + + Early checks before a lossy conversion may exclude custom system tags, + which already have their own metadata validation. + """ + columns = sorted( + f"{path} ({identifier})" + for field in schema + if field.name not in exclude + for path, identifier in _stored_logical_fields(field) + ) + if columns: + raise InputValidationError( + f"Source column(s) {', '.join(columns)} carry logical types in stored form. " + "Pass each column as its logical Arrow extension type, or drop the " + "annotation if the column is meant as plain data." + ) + + +def read_arrow_frame_input( + data: FrameInitTypes, *, system_tag_columns: Collection[str] = () +) -> pa.Table | None: + """Read an Arrow frame input, preserving its schema for validation before Polars.""" + import pandas as pd + import polars as pl + + if isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)): + return None + if isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): + # The C import can rehydrate known extensions. Check the supplied schema + # first, then keep the existing import path and its field metadata handling. + require_live_logical_types(data.schema, exclude=system_tag_columns) + # Like Polars, prefer the array export when both are available. + if hasattr(data, "__arrow_c_array__"): + batch = pa.record_batch(cast("ArrowArrayExportable", data)) + return pa.Table.from_batches([batch]) + if hasattr(data, "__arrow_c_stream__"): + return pa.table(cast("ArrowStreamExportable", data)) + return None + + def require_supported_nullable_types(schema: pa.Schema) -> None: """Refuse source columns containing the Arrow Null type, even with zero rows.""" columns = sorted( @@ -570,6 +643,7 @@ def build( data_tags: Collection[str] = (), *, hash_in_key_order: bool = False, + from_origin: bool = False, ) -> SourceStreamResult: """Run the full enrichment pipeline. @@ -608,6 +682,8 @@ def build( (ITL-1272). The stream keeps the rows in the order given. Off by default: the rows are hashed in the order given, which the user may have chosen on purpose. Needs key columns and no ``source_id``. + from_origin: The table came from an existing Orcapod source or job + node, after that origin's own validation and decoding. Returns: SourceStreamResult with enriched stream and metadata. @@ -619,8 +695,8 @@ def build( ``kind_part`` is not given or is not ``_v``, or if the source id it builds is not valid, or if ``hash_in_key_order`` is given with a ``source_name`` or without key columns. - InputValidationError: If a column's type is, or contains, a - dictionary: dictionary-encoded columns are not currently supported + InputValidationError: If an external column carries a stored logical + type, or if a column's type is or contains a dictionary (ITL-1264, ITL-1277). """ # Whole-argument checks first, before the table is read. @@ -664,8 +740,11 @@ def build( ) # 1. Drop system columns from raw input. + raw_schema = table.schema table = arrow_utils.drop_system_columns(table) require_custom_system_tags(table, system_tag_columns_tuple) + if not from_origin: + require_live_logical_types(raw_schema) # 2. Validate tag_columns. A table with no columns at all (e.g. a # DictSource built from no rows and no schema) gets its own error, since diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 3f69e887d..f151086df 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -5,20 +5,24 @@ import asyncio import sqlite3 from collections.abc import Collection +from dataclasses import dataclass from pathlib import Path from typing import Any, TypedDict from uuid import UUID import deltalake +import numpy as np import pandas as pd import polars as pl import pyarrow as pa import pyarrow.csv as pa_csv import pytest -from orcapod import PipelineJob +from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context from orcapod.contexts.stored import with_data_context from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.row_ids import entry_id, instance_id, record_id from orcapod.core.sources import ( ArrowTableSource, @@ -36,11 +40,20 @@ ) from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams import ArrowTableStream -from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.databases import ( + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, +) from orcapod.errors import InputValidationError from orcapod.operators import DropNulls -from orcapod.protocols.core_protocols import StreamProtocol -from orcapod.types import CacheMode, ColumnInfo, Cursor +from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.types import CacheMode, ColumnInfo, Cursor, DataValue +from orcapod.utils.arrow_utils import ( + normalize_extension_columns, + normalize_to_large_types, +) from tests.test_core.sources.test_db_table_source import MockDBConnector from tests.test_databases import fake_spiral_sdk @@ -62,7 +75,7 @@ class _SourceOptions(TypedDict): """Keyword arguments supported by the sources in the validation matrix.""" tag_columns: Collection[str] - tag_only_columns: bool + tag_only_columns: bool | Collection[str] source_id: str system_tag_columns: Collection[str] @@ -101,11 +114,13 @@ def _source( monkeypatch: pytest.MonkeyPatch, *, system_tag_columns: Collection[str] = (), + tags: Collection[str] = TAGS, + tag_only_columns: bool | Collection[str] = True, ) -> StreamProtocol: """Build the named source over the same columns using its regular reader.""" options: _SourceOptions = { - "tag_columns": TAGS, - "tag_only_columns": True, + "tag_columns": tags, + "tag_only_columns": tag_only_columns, "source_id": "rows", "system_tag_columns": system_tag_columns, } @@ -184,6 +199,237 @@ def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: ) +def _live_paths() -> pa.Table: + converter = get_default_context().type_converter + return converter.python_dicts_to_arrow_table( + [ + {"path": Path("a"), "other": Path("b")}, + {"path": Path("c"), "other": Path("d")}, + ] + ) + + +def _stored_paths() -> pa.Table: + return normalize_extension_columns(_live_paths()) + + +@pytest.mark.parametrize("kind", SOURCE_KINDS) +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("role", ["tag", "data", "data-tag"]) +def test_sources_refuse_stored_logical_columns( + kind: str, reverse: bool, role: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + paths = _stored_paths() + extension_name = "orcapod.path" + if kind == "delta": + # Delta's Arrow reader already restores registered extensions. + extension_name = "test.unregistered.path" + for index, field in enumerate(paths.schema): + paths = paths.set_column( + index, + field.with_metadata( + { + b"ARROW:extension:name": extension_name.encode(), + b"ARROW:extension:metadata": b'{"version":1}', + } + ), + paths.column(index), + ) + table = _table(pa.field("extra", pa.string(), False), ["a", "b"]) + for field in paths.schema: + table = table.append_column(field, paths[field.name]) + tags = TAGS if role == "data" else (*TAGS, "path", "other") + if reverse: + table = table.select(table.column_names[::-1]) + tags = tags[::-1] + with pytest.raises(InputValidationError) as error: + _ = _source( + kind, + table, + tmp_path, + monkeypatch, + tags=tags, + tag_only_columns=TAGS if role == "data-tag" else True, + ) + message = str(error.value) + assert "'path'" in message and "'other'" in message + assert extension_name in message + assert "extension type" in message and "drop the annotation" in message + + +@dataclass +class StoredPoint: + x: int + + +@pytest.mark.parametrize( + "value", + [UUID(int=1), StoredPoint(1), {1, 2}, np.array([1, 2])], + ids=["uuid", "user-class", "native-set", "numpy-array"], +) +def test_arrow_source_refuses_other_stored_logical_types(value: Any) -> None: + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_python_class(StoredPoint) + live = converter.python_dicts_to_arrow_table([{"value": value}]) + stored = normalize_extension_columns(live) + extension = live.schema.field("value").type + assert isinstance(extension, pa.ExtensionType) + with pytest.raises(InputValidationError) as error: + ArrowTableSource(stored) + assert "'value'" in str(error.value) + assert extension.extension_name in str(error.value) + + +@pytest.mark.parametrize("container", ["list", "struct", "map"]) +def test_arrow_source_refuses_nested_stored_logical_types(container: str) -> None: + path = _stored_paths().schema.field("path") + if container == "list": + nested = pa.list_(path) + value = ["a"] + elif container == "struct": + nested = pa.struct([pa.field("items", pa.list_(path))]) + value = {"items": ["a"]} + else: + key = path.with_name("key").with_nullable(False) + item = path.with_name("value") + nested = pa.map_(key, item) # pyright: ignore[reportArgumentType] # PyArrow accepts fields. + value = [("a", "b")] + table = pa.Table.from_arrays( + [pa.array([value], nested)], schema=pa.schema([pa.field("nested", nested)]) + ) + with pytest.raises(InputValidationError) as error: + ArrowTableSource(table) + message = str(error.value) + assert "'nested'" in message and "orcapod.path" in message + if container == "map": + assert ".'key'" in message and ".'value'" in message + + +@pytest.mark.parametrize("declare_schema", [False, True]) +def test_dataframe_refuses_stored_form_before_conversion(declare_schema: bool) -> None: + stored = _stored_paths() + plain_schema = pa.schema([field.remove_metadata() for field in stored.schema]) + with pytest.raises(InputValidationError, match="orcapod.path"): + DataFrameSource(stored, schema=plain_schema if declare_schema else None) + + +@pytest.mark.parametrize("role", ["tag", "data", "data-tag"]) +@pytest.mark.parametrize("reverse", [False, True]) +def test_live_logical_types_with_annotations_keep_table_hashes_and_rows( + role: str, reverse: bool +) -> None: + live = _live_paths() + stored = normalize_extension_columns(live) + plain = _table(pa.field("extra", pa.large_string(), False), ["a", "b"]) + plain = plain.cast( + pa.schema( + [ + field.with_type(normalize_to_large_types(field.type)) + for field in plain.schema + ] + ) + ) + annotated = plain + for field in live.schema: + annotated = annotated.append_column( + stored.schema.field(field.name).with_type(field.type), live[field.name] + ) + plain = plain.append_column(field, live[field.name]) + tags = TAGS if role == "data" else (*TAGS, "path", "other") + if reverse: + annotated = annotated.select(annotated.column_names[::-1]) + plain = plain.select(plain.column_names[::-1]) + tags = tags[::-1] + tag_only = TAGS if role == "data-tag" else tags + actual = ArrowTableSource(annotated, tag_columns=tags, tag_only_columns=tag_only) + expected = ArrowTableSource(plain, tag_columns=tags, tag_only_columns=tag_only) + assert actual.as_table().equals(annotated, check_metadata=True) + assert actual.content_hash() == expected.content_hash() + assert actual.pipeline_hash() == expected.pipeline_hash() + + def paths(tag: TagProtocol, data: DataProtocol) -> tuple[DataValue, DataValue]: + row = tag if role == "tag" else data + return row["path"], row["other"] + + async def read() -> list[tuple[DataValue, DataValue]]: + return [paths(t, d) async for t, d in actual.async_iter_data()] + + assert [paths(t, d) for t, d in actual.iter_data()] == [ + (Path("a"), Path("b")), + (Path("c"), Path("d")), + ] + assert asyncio.run(read()) == [(Path("a"), Path("b")), (Path("c"), Path("d"))] + + +def test_raw_stream_still_reads_stored_logical_columns_as_storage() -> None: + stored = _stored_paths() + stream = ArrowTableStream(stored) + assert stream.as_table().equals(stored, check_metadata=True) + assert [(data["path"], data["other"]) for _, data in stream.iter_data()] == [ + ("a", "b"), + ("c", "d"), + ] + + +@function_pod(output_keys=("path", "other")) +def _copy_paths(path: Path, other: Path) -> tuple[Path, Path]: + """Return both logical columns unchanged.""" + return path, other + + +@pytest.mark.parametrize("origin", ["cache", "operator", "function"]) +def test_library_stored_logical_columns_are_still_decoded( + origin: str, tmp_path: Path +) -> None: + live = _live_paths().append_column("g", pa.array(["a", "b"])) + live = live.append_column("k", pa.array([1, 2])) + source = ArrowTableSource(live, tag_columns=TAGS, tag_only_columns=True) + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + database = ExtensionAwareDatabase(DeltaTableDatabase(tmp_path), converter) + if origin == "cache": + cache = source.cached(database) + cache.as_table() + reader = CachedSource.from_config(cache.to_config()) + else: + job = PipelineJob(name="paths", database=database) + with job: + if origin == "operator": + DropNulls(["other", "path"])(source, label="copy") + else: + _copy_paths.pod(source, label="copy") + node = job.nodes["copy"] + if origin == "operator": + assert isinstance(node, OperatorJobNode) + node.attach_databases(pipeline_database=database, cache_mode=CacheMode.LOG) + else: + assert isinstance(node, FunctionJobNode) + job.run() + records = node.get_all_records() + assert records is not None + assert ( + records.select(["path", "other"]).to_pylist() + == live.select(["path", "other"]).to_pylist() + ) + reader = node.as_source( + tags_as_data={"g": "group", "k": "key"}, source_id="copy" + ) + assert ( + reader.as_table().select(["path", "other"]).to_pylist() + == live.select(["path", "other"]).to_pylist() + ) + + async def read() -> list[tuple[DataValue, DataValue]]: + return [ + (data["path"], data["other"]) async for _, data in reader.async_iter_data() + ] + + expected = [(Path("a"), Path("b")), (Path("c"), Path("d"))] + assert [(data["path"], data["other"]) for _, data in reader.iter_data()] == expected + assert asyncio.run(read()) == expected + + @pytest.mark.parametrize("kind", SOURCE_KINDS) @pytest.mark.parametrize( ("arrow_type", "nullable", "values"), @@ -384,7 +630,9 @@ def test_no_declared_type_for_python_none_still_infers_a_string() -> None: class _Poll: """Minimal impl for testing schema validation before the first fetch.""" - def __init__(self, schema: pa.Schema | None, batch: pl.DataFrame) -> None: + def __init__( + self, schema: pa.Schema | None, batch: pl.DataFrame | pa.Table + ) -> None: self._schema = schema self._batch = batch @@ -406,7 +654,7 @@ def from_config(cls, config: dict[str, Any]) -> _Poll: async def fetch( self, cursor: Cursor[int] | None = None - ) -> tuple[Cursor[int], pl.DataFrame]: + ) -> tuple[Cursor[int], pl.DataFrame | pa.Table]: """Return the prepared batch on the initial fetch.""" return Cursor(value=0), self._batch @@ -438,6 +686,30 @@ def test_polling_refuses_null_in_declaration_and_batch(values: list[Any]) -> Non poll.check_for_new_data() +@pytest.mark.parametrize("declare_schema", [False, True]) +@pytest.mark.parametrize("reverse", [False, True]) +def test_polling_refuses_stored_logical_types( + declare_schema: bool, reverse: bool +) -> None: + table = _stored_paths().append_column("k", pa.array([1, 2])) + if reverse: + table = table.select(table.column_names[::-1]) + + def build() -> None: + poll = PollingSource( + _Poll(table.schema if declare_schema else None, table), + ["k"], + source_id="poll", + record_id_columns="k", + ) + poll.check_for_new_data() + + with pytest.raises(InputValidationError) as error: + build() + assert "'path'" in str(error.value) and "'other'" in str(error.value) + assert "orcapod.path" in str(error.value) + + def test_a_raw_arrow_table_stream_preserves_nested_null() -> None: field = pa.field("extra", pa.large_list(pa.null())) table = _table(field, [[None], []]) From 68706abbd36299e163666199cf1d68cef15f63f6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:15:37 -0800 Subject: [PATCH 2/9] test(sources): update logical form coverage for source intake --- docs/reference/hashing.md | 6 +- tests/test_hashing/test_logical_type_forms.py | 72 ++++++++++++------- .../test_schema_hash_storage_form.py | 27 +++++-- 3 files changed, 69 insertions(+), 36 deletions(-) diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 157986c24..62be3d9d3 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1890,9 +1890,9 @@ The same walker gives the form of every other place a schema is compared or save type at the top of a column becomes the live type, which is what a source holds and what gives the column its Python type. Arrow cannot build an empty table with an extension type inside a list, struct or map, so an identifier nested in a plain container is never made - live: it stays in the storage form, and the slot, a source of the same table and the - slot made from that source have one Python schema, one Arrow schema and one pipeline - hash. + live. Blueprint slots, saved schemas and raw Arrow streams can still carry the stored + identifier. Sources, including a polling implementation's Arrow declaration, require + incoming logical fields to be live extension types. Python declarations produce implicitly nullable nested fields in data context v1. For example, `list[int]` and `list[int | None]` convert to the same Arrow type diff --git a/tests/test_hashing/test_logical_type_forms.py b/tests/test_hashing/test_logical_type_forms.py index c1fdfd5c2..5c5aee96c 100644 --- a/tests/test_hashing/test_logical_type_forms.py +++ b/tests/test_hashing/test_logical_type_forms.py @@ -39,10 +39,12 @@ from orcapod.core.nodes.source_node import SourceNode from orcapod.core.operators import Index, MapData, Pick from orcapod.core.sources import ArrowTableSource, PollingSource +from orcapod.core.sources.stream_builder import SourceStreamBuilder +from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import typed_arrow_schemas, typed_zero_row_table from orcapod.databases import InMemoryArrowDatabase -from orcapod.errors import SourceSpecMismatchError +from orcapod.errors import InputValidationError, SourceSpecMismatchError from orcapod.pipeline import ( AsyncPipelineOrchestrator, Pipeline, @@ -296,13 +298,11 @@ async def close(self) -> None: @pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") -@pytest.mark.parametrize("form", ["live", "metadata"]) -def test_a_polling_source_declared_in_metadata_form_takes_its_rows(form: str) -> None: - """A metadata-form ``Path`` declares ``Path`` and takes its rows.""" +def test_a_polling_source_declared_in_live_form_takes_its_rows() -> None: + """A live Path declaration supplies Path rows.""" table = _path_table() - declared = table.schema if form == "live" else _metadata_form(table.schema) source = PollingSource( - _TableImpl(table, declared), + _TableImpl(table, table.schema), tag_columns=["k", "g"], record_id_columns=["k", "g"], source_id="forms", @@ -311,6 +311,18 @@ def test_a_polling_source_declared_in_metadata_form_takes_its_rows(form: str) -> assert source.as_table().num_rows == 2 +def test_a_polling_source_refuses_a_stored_form_declaration() -> None: + """Even with live rows, an external source declaration needs live fields.""" + table = _path_table() + with pytest.raises(InputValidationError, match=r"'w'.*'x'.*stored form"): + _ = PollingSource( + _TableImpl(table, _metadata_form(table.schema)), + tag_columns=["k", "g"], + record_id_columns=["k", "g"], + source_id="forms", + ) + + @pytest.mark.parametrize("form", ["live", "metadata"]) def test_a_slot_declared_in_metadata_form_binds_its_logical_type(form: str) -> None: """A metadata-form slot declares ``Path``, binds the source and runs.""" @@ -635,39 +647,47 @@ def test_an_arrow_declared_slot_with_a_nested_identifier_works( @pytest.mark.parametrize(("container", "identifier"), NESTED_CASES) class TestNestedIdentifier: - """An identifier nested in a plain struct or list: the source, its slots, a save and load.""" - - def _source(self, table: pa.Table) -> ArrowTableSource: - """An in-memory source of ``table`` with tags ``k``, ``g``.""" - return ArrowTableSource( - table, tag_columns=["k", "g"], tag_only_columns=True, source_id="nested" + """Nested stored identifiers in an internal stream, its slots, and its saved form.""" + + def _stream(self, table: pa.Table) -> ArrowTableStream: + """Build a stream like an internal read, with provenance for pipeline binding.""" + return ( + SourceStreamBuilder(get_default_context()) + .build( + table, + tag_columns=["k", "g"], + source_name="nested", + kind_part="arrow_table_v1", + from_origin=True, + ) + .stream ) @pytest.mark.parametrize("live", [False, True], ids=["storage child", "live child"]) - def test_an_arrow_declared_slot_is_the_source_and_its_stream_slot( + def test_an_arrow_declared_slot_matches_the_stream_slot( self, container: str, identifier: str, live: bool ) -> None: - """Declared slot, stream slot and source: one Python schema, Arrow schema and hash.""" + """Declared slot and internal stream slot have the same schemas and hash.""" tags, data, table = _nested(container, identifier, live=live) - source = self._source(table) + stream = self._stream(table) declared = SourceNode(name="src", tag_schema=tags, data_schema=data) - from_stream = SourceNode.from_stream(source, name="src") + from_stream = SourceNode.from_stream(stream, name="src") # One Python schema, one Arrow schema, one pipeline hash (coordinator's # condition on the declaration form, PR 454). assert declared.pipeline_hash() == from_stream.pipeline_hash() - assert declared.pipeline_hash() == source.pipeline_hash() + assert declared.pipeline_hash() == stream.pipeline_hash() assert declared.output_schema() == from_stream.output_schema() - assert declared.output_schema() == source.output_schema() + assert declared.output_schema() == stream.output_schema() assert typed_arrow_schemas(declared) == typed_arrow_schemas(from_stream) - assert typed_arrow_schemas(declared) == typed_arrow_schemas(source) + assert typed_arrow_schemas(declared) == typed_arrow_schemas(stream) for tags_or_data in typed_arrow_schemas(declared): assert tags_or_data.empty_table().num_rows == 0 def test_the_identifier_is_part_of_the_hash( self, container: str, identifier: str ) -> None: - """Without its nested identifier, the source is another identity.""" - tags, data, table = _nested(container, identifier) + """Without its nested identifier, the stream has another identity.""" + _, _, table = _nested(container, identifier) plain = table.cast( pa.schema( [ @@ -677,7 +697,7 @@ def test_the_identifier_is_part_of_the_hash( ) ) assert ( - self._source(plain).pipeline_hash() != self._source(table).pipeline_hash() + self._stream(plain).pipeline_hash() != self._stream(table).pipeline_hash() ) @pytest.mark.parametrize("live", [False, True], ids=["storage child", "live child"]) @@ -693,16 +713,16 @@ def test_the_saved_text_reads_back_typed_and_hashed( assert restored.empty_table().num_rows == 0 assert restored == _data_schema(table.schema) assert _hasher().hash_schema(restored) == _hasher().hash_schema(data) - source_types = self._source(table).output_schema()[1] + source_types = self._stream(table).output_schema()[1] restored_types = _converter().arrow_schema_to_python_schema(restored) assert dict(restored_types) == dict(source_types) def test_a_saved_slot_loads_and_binds( self, container: str, identifier: str, tmp_path: Path ) -> None: - """Both slot forms save and load to the source's identity, and the loaded slot runs.""" + """Both slot forms save and load to the stream's identity, and the slot runs.""" tags, data, table = _nested(container, identifier) - source = self._source(table) + source = self._stream(table) slots = { "declared": SourceNode(name="src", tag_schema=tags, data_schema=data), "from a stream": SourceNode.from_stream(source, name="src"), @@ -729,7 +749,7 @@ def test_a_saved_slot_loads_and_binds( job = PipelineJob(name="nested", database=InMemoryArrowDatabase()) with job: MapData({"x": "z"})(loaded_slot, label="renamed") - job.bind(sources={"src": self._source(table)}) + job.bind(sources={"src": self._stream(table)}) job.run() assert job.nodes["renamed"].as_table().num_rows == 2, label diff --git a/tests/test_hashing/test_schema_hash_storage_form.py b/tests/test_hashing/test_schema_hash_storage_form.py index e39538903..089f7bd54 100644 --- a/tests/test_hashing/test_schema_hash_storage_form.py +++ b/tests/test_hashing/test_schema_hash_storage_form.py @@ -46,7 +46,7 @@ from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.sqlite_connector import SQLiteConnector -from orcapod.errors import UnstorableColumnError +from orcapod.errors import InputValidationError, UnstorableColumnError from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError from orcapod.sources import ArrowTableSource from orcapod.system_constants import constants @@ -767,8 +767,6 @@ def _read_back(database: Any, table: pa.Table) -> pa.Table: InMemoryArrowDatabase(), table ), "delta": lambda table, root: _read_back(DeltaTableDatabase(root / "delta"), table), - "metadata form": lambda table, root: normalize_extension_columns(table), - "unregistered": lambda table, root: _unregistered_table(table), } @@ -780,11 +778,25 @@ class TestIdentityPaths: def test_a_source_has_one_identity_however_its_table_arrives( self, kind: str, form: str, tmp_path: Path ) -> None: - """In memory, reordered, read back, metadata or unregistered: one identity.""" + """Live columns in memory, reordered or read back have one identity.""" table = _table(kind, tmp_path / "values") given = SOURCE_FORMS[form](table, tmp_path) assert _identity(_source(given)) == _identity(_source(table)) + @pytest.mark.parametrize("form", ["metadata", "unregistered"]) + def test_sources_refuse_columns_with_stored_identifiers( + self, kind: str, form: str, tmp_path: Path + ) -> None: + """The source refuses its columns if only storage and annotations are present.""" + table = _table(kind, tmp_path / "values") + given = ( + normalize_extension_columns(table) + if form == "metadata" + else _unregistered_table(table) + ) + with pytest.raises(InputValidationError, match=r"'v1'.*'v2'.*stored form"): + _ = _source(given) + def test_the_sqlite_connector_refuses_the_type( self, kind: str, tmp_path: Path ) -> None: @@ -806,7 +818,7 @@ def test_another_type_is_another_identity(self, kind: str, tmp_path: Path) -> No def test_another_identifier_is_another_identity( self, kind: str, tmp_path: Path ) -> None: - """The same table, its identifier's metadata changed: another source.""" + """The same schema with another identifier has another schema hash.""" stored = normalize_extension_columns(_table(kind, tmp_path / "values")) def bumped(field: pa.Field[Any]) -> pa.Field[Any]: @@ -820,8 +832,9 @@ def bumped(field: pa.Field[Any]) -> pa.Field[Any]: return field.with_metadata(cast("dict[bytes | str, bytes | str]", metadata)) other = stored.cast(pa.schema([bumped(field) for field in stored.schema])) - first, second = _identity(_source(stored)), _identity(_source(other)) - assert first[1] != second[1] and first[2] != second[2] + assert _hasher().hash_schema(stored.schema) != _hasher().hash_schema( + other.schema + ) def _slots(self, kind: str, tmp_path: Path) -> dict[str, SourceNode]: """The slot declared in Python types, in each Arrow form, and from a stream.""" From dc32d93d35d1ac52ab47ca73a895b0634508a3ac Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:35:54 -0800 Subject: [PATCH 3/9] test(spiral): cover refusal of stored logical float fields --- ..._spiraldb_table_source_float_equalities.py | 50 +++++++++++-------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py b/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py index a4ada0214..800e88e9e 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py +++ b/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py @@ -23,12 +23,14 @@ import pyarrow as pa import pytest +from orcapod.errors import InputValidationError from orcapod.logical_types.canonical_form import ( EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, ) from orcapod.sources import SpiralDBTableSource from orcapod.types import Condition, col +from orcapod.types.condition import check_restriction from tests.test_databases import fake_spiral_sdk _PROJECT = "workshop-sample" @@ -242,11 +244,9 @@ def test_exact_float_column_equalities_select_rows( @pytest.fixture() -def logical_float_source( - project: fake_spiral_sdk.ExternalProject, -) -> SpiralDBTableSource: - """Read a logical column whose float storage carries its extension identity.""" - schema = pa.schema( +def logical_float_schema() -> pa.Schema: + """Declare a logical column whose float storage carries its extension identity.""" + return pa.schema( [ pa.field("id", pa.int64()), pa.field( @@ -259,35 +259,41 @@ def logical_float_source( ), ] ) + + +def test_source_refuses_a_stored_logical_float( + project: fake_spiral_sdk.ExternalProject, logical_float_schema: pa.Schema +) -> None: + """An externally recorded storage schema is refused before a scan.""" table = project.create_table("default.logical", key_schema=[("id", pa.int64())]) - table.write(pa.table({"id": [0, 1], "v": [0.1, 1.0]}, schema=schema)) - table.record(schema) - return SpiralDBTableSource(_PROJECT, "logical", tag_only_columns=True) + table.write(pa.table({"id": [0, 1], "v": [0.1, 1.0]}, schema=logical_float_schema)) + table.record(logical_float_schema) + with pytest.raises(InputValidationError, match=r"'v'.*test\.measurement"): + _ = SpiralDBTableSource(_PROJECT, "logical", tag_only_columns=True) + assert fake_spiral_sdk.scan_log == [] def test_logical_float_equality_refuses_integer( - logical_float_source: SpiralDBTableSource, -): - """The logical column retains its existing Python float requirement.""" + logical_float_schema: pa.Schema, +) -> None: + """The predicate validator requires a Python float for the logical column.""" with pytest.raises(TypeError, match=r"column 'v'.*value 1 is a int"): - logical_float_source.where(v=1) - assert fake_spiral_sdk.scan_log == [] + check_restriction(Condition.of({"v": 1}), logical_float_schema) def test_logical_float_equality_accepts_exact_float( - logical_float_source: SpiralDBTableSource, -): - """An exact Python float can still select a row by its stored value.""" - assert _ids(logical_float_source.where(v=1.0)) == [1] + logical_float_schema: pa.Schema, +) -> None: + """The predicate validator accepts a Python float the storage can hold exactly.""" + check_restriction(Condition.of({"v": 1.0}), logical_float_schema) def test_logical_float_equality_refuses_inexact_float( - logical_float_source: SpiralDBTableSource, -): - """A logical float column also requires exact representation.""" + logical_float_schema: pa.Schema, +) -> None: + """The predicate validator refuses a float the storage cannot hold exactly.""" with pytest.raises(TypeError, match=r"column 'v'.*cannot hold 0\.1 exactly"): - logical_float_source.where(v=0.1) - assert fake_spiral_sdk.scan_log == [] + check_restriction(Condition.of({"v": 0.1}), logical_float_schema) def test_huge_integer_equality_is_refused(project: fake_spiral_sdk.ExternalProject): From 38488945b6ac22b63e21057edcfb7847261263d5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:15:21 -0800 Subject: [PATCH 4/9] fix(sources): preserve logical form at frame intake --- docs/dev/design_issues/ITL-1333-BL17.md | 8 +- src/orcapod/core/sources/data_frame_source.py | 13 +- src/orcapod/core/sources/polling_source.py | 22 ++-- src/orcapod/core/sources/stream_builder.py | 48 ++++++-- .../sources/test_source_arrow_validation.py | 114 ++++++++++++++++-- 5 files changed, 166 insertions(+), 39 deletions(-) diff --git a/docs/dev/design_issues/ITL-1333-BL17.md b/docs/dev/design_issues/ITL-1333-BL17.md index 2bf9f1806..0aa733fc9 100644 --- a/docs/dev/design_issues/ITL-1333-BL17.md +++ b/docs/dev/design_issues/ITL-1333-BL17.md @@ -10,6 +10,8 @@ identifier in metadata. A live extension array with the same values had the same and content hashes but gave downstream functions Path objects. **Fix:** Refuse external Arrow fields that carry logical annotations on their storage type, -including nested fields. Live extension fields and the existing decoding of Orcapod-owned -stored records retain their behavior. Resolving stored logical types at external source -boundaries is planned separately. +including nested fields in pandas Arrow-backed columns. For native PyArrow inputs, use the +original field type before a C round-trip can change it. For third-party Arrow C exporters, +use the field type and metadata after importing into PyArrow. The existing decoding of +Orcapod-owned stored records retains its behavior. Resolving stored logical types at +external source boundaries is planned separately. diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 171f5c99a..eff17b919 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -7,13 +7,13 @@ import polars as pl import pyarrow as pa -from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags -from orcapod.core.sources.stream_builder import SourceStreamBuilder +from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( + SourceStreamBuilder, + declare_native_custom_system_tags, normalize_record_id_columns, read_arrow_frame_input, - declare_native_custom_system_tags, require_custom_system_tags, require_custom_system_tags_values, require_live_logical_types, @@ -70,12 +70,13 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) - arrow_input_schema = None + input_schema = arrow_input_schema = None if ( - arrow_input := read_arrow_frame_input( + arrow_frame := read_arrow_frame_input( data, system_tag_columns=system_tag_columns ) ) is not None: + arrow_input, input_schema = arrow_frame if schema is None: require_custom_system_tags(arrow_input, system_tag_columns) else: @@ -84,7 +85,6 @@ def __init__( arrow_input, system_tag_columns, schema=schema ) arrow_input_schema = arrow_input.schema - require_live_logical_types(arrow_input_schema) # Polars rechunks native tables but preserves chunks on exporter inputs. df = cast( pl.DataFrame, @@ -158,6 +158,7 @@ def __init__( record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, system_tag_columns=system_tag_columns, + input_schema=input_schema if schema is None else None, ) self._stream = result.stream diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 77d386cab..590e91f13 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -16,7 +16,7 @@ import threading from collections.abc import Collection from math import floor -from typing import Any, ClassVar, Generic, TYPE_CHECKING, TypeVar, cast +from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast import polars as pl import pyarrow as pa @@ -25,7 +25,6 @@ from orcapod.core.identity_chains import refuse_identity_io from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import hash_source_name -from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, @@ -34,22 +33,23 @@ require_supported_nullable_types, validate_source_table, ) -from orcapod.core.streams.view import ( - ViewStatus, - StreamView, -) from orcapod.core.streams.base import ( check_head_size, typed_zero_row_table, ) +from orcapod.core.streams.view import ( + StreamView, + ViewStatus, +) from orcapod.errors import ( CursorInvalidatedError, InputValidationError, RowIdentifierError, SchemaInconsistencyError, ) +from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.system_constants import constants -from orcapod.types import ContentHash, ColumnConfig, Cursor, PollingConfig, Schema +from orcapod.types import ColumnConfig, ContentHash, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.utils.schema_utils import ( @@ -59,11 +59,11 @@ ) if TYPE_CHECKING: - from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from polars._typing import FrameInitTypes from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from orcapod.types import Schema T = TypeVar("T") @@ -905,10 +905,8 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - arrow_input = read_arrow_frame_input(data) - if arrow_input is not None: - require_live_logical_types(arrow_input.schema) - data = arrow_input + if (arrow_frame := read_arrow_frame_input(data)) is not None: + data, _ = arrow_frame df = pl.DataFrame(data) if len(df.columns) == 0: logger.debug( diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 51e824d29..d3cd5b698 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -88,24 +88,44 @@ def require_live_logical_types( def read_arrow_frame_input( data: FrameInitTypes, *, system_tag_columns: Collection[str] = () -) -> pa.Table | None: - """Read an Arrow frame input, preserving its schema for validation before Polars.""" +) -> tuple[pa.Table, pa.Schema] | None: + """Read Arrow frame inputs and validate annotations before Polars can drop them.""" import pandas as pd import polars as pl - if isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)): + if isinstance(data, pd.DataFrame): + # Arrow-backed dtypes retain nested field metadata. Check them before + # Polars reads the frame, while keeping its normal conversion for pandas. + require_live_logical_types( + pa.schema( + pa.field(str(name), dtype.pyarrow_dtype) + for name, dtype in data.dtypes.items() + if isinstance(dtype, pd.ArrowDtype) + ) + ) + return None + if isinstance(data, (pl.DataFrame, pl.Series)): return None + input_schema = None if isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): - # The C import can rehydrate known extensions. Check the supplied schema - # first, then keep the existing import path and its field metadata handling. - require_live_logical_types(data.schema, exclude=system_tag_columns) + # C import can rehydrate stored fields or turn live extensions into storage. + # The original PyArrow field type is authoritative for native inputs. + input_schema = data.schema + require_live_logical_types(input_schema, exclude=system_tag_columns) # Like Polars, prefer the array export when both are available. if hasattr(data, "__arrow_c_array__"): batch = pa.record_batch(cast("ArrowArrayExportable", data)) - return pa.Table.from_batches([batch]) - if hasattr(data, "__arrow_c_stream__"): - return pa.table(cast("ArrowStreamExportable", data)) - return None + table = pa.Table.from_batches([batch]) + elif hasattr(data, "__arrow_c_stream__"): + table = pa.table(cast("ArrowStreamExportable", data)) + else: + return None + if input_schema is None: + # C exporters describe live and stored extensions the same way. Validate + # the imported field types and any annotations that remain on storage. + input_schema = table.schema + require_live_logical_types(input_schema, exclude=system_tag_columns) + return table, input_schema def require_supported_nullable_types(schema: pa.Schema) -> None: @@ -644,6 +664,7 @@ def build( *, hash_in_key_order: bool = False, from_origin: bool = False, + input_schema: pa.Schema | None = None, ) -> SourceStreamResult: """Run the full enrichment pipeline. @@ -684,6 +705,9 @@ def build( have chosen on purpose. Needs key columns and no ``source_id``. from_origin: The table came from an existing Orcapod source or job node, after that origin's own validation and decoding. + input_schema: The original Arrow schema when frame conversion can + change the representation of a logical field. Used only to + determine whether the external input carried stored logical types. Returns: SourceStreamResult with enriched stream and metadata. @@ -744,7 +768,9 @@ def build( table = arrow_utils.drop_system_columns(table) require_custom_system_tags(table, system_tag_columns_tuple) if not from_origin: - require_live_logical_types(raw_schema) + require_live_logical_types( + raw_schema if input_schema is None else input_schema + ) # 2. Validate tag_columns. A table with no columns at all (e.g. a # DictSource built from no rows and no schema) gets its own error, since diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index f151086df..b38c459b9 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -7,7 +7,7 @@ from collections.abc import Collection from dataclasses import dataclass from pathlib import Path -from typing import Any, TypedDict +from typing import TYPE_CHECKING, Any, TypedDict from uuid import UUID import deltalake @@ -17,19 +17,20 @@ import pyarrow as pa import pyarrow.csv as pa_csv import pytest +from arro3.core import Table as ArroTable from orcapod import PipelineJob, function_pod from orcapod.contexts import get_default_context from orcapod.contexts.stored import with_data_context -from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.row_ids import entry_id, instance_id, record_id from orcapod.core.sources import ( ArrowTableSource, CachedSource, CSVSource, - DBTableSource, DataFrameSource, + DBTableSource, DeltaTableSource, DictSource, ListSource, @@ -57,6 +58,9 @@ from tests.test_core.sources.test_db_table_source import MockDBConnector from tests.test_databases import fake_spiral_sdk +if TYPE_CHECKING: + from polars._typing import FrameInitTypes + TAGS = ("g", "k") SOURCE_KINDS = ( "arrow", @@ -630,9 +634,7 @@ def test_no_declared_type_for_python_none_still_infers_a_string() -> None: class _Poll: """Minimal impl for testing schema validation before the first fetch.""" - def __init__( - self, schema: pa.Schema | None, batch: pl.DataFrame | pa.Table - ) -> None: + def __init__(self, schema: pa.Schema | None, batch: FrameInitTypes) -> None: self._schema = schema self._batch = batch @@ -654,7 +656,7 @@ def from_config(cls, config: dict[str, Any]) -> _Poll: async def fetch( self, cursor: Cursor[int] | None = None - ) -> tuple[Cursor[int], pl.DataFrame | pa.Table]: + ) -> tuple[Cursor[int], FrameInitTypes]: """Return the prepared batch on the initial fetch.""" return Cursor(value=0), self._batch @@ -710,6 +712,104 @@ def build() -> None: assert "orcapod.path" in str(error.value) +class _UnregisteredExtension(pa.ExtensionType): + """A live PyArrow extension that has never been registered.""" + + def __init__(self) -> None: + super().__init__(pa.large_string(), "test.source.live") + + def __arrow_ext_serialize__(self) -> bytes: + return b"{}" + + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> _UnregisteredExtension: + return cls() + + +def _frame_source(kind: str, data: FrameInitTypes) -> StreamProtocol: + """Read a frame through the source constructor or a public poll.""" + if kind == "dataframe": + return DataFrameSource(data, tag_columns=["k"], tag_only_columns=True) + poll = PollingSource( + _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" + ) + poll.check_for_new_data() + return poll + + +@pytest.mark.parametrize("kind", ["dataframe", "polling"]) +@pytest.mark.parametrize("container", ["table", "batch", "reader"]) +def test_frame_sources_accept_live_unregistered_extensions( + kind: str, container: str +) -> None: + storage = pa.array(["a", "b"], type=pa.large_string()) + plain = pa.table({"k": [1, 2], "value": storage}) + live = plain.set_column( + 1, "value", pa.ExtensionArray.from_storage(_UnregisteredExtension(), storage) + ) + assert isinstance(live.schema.field("value").type, pa.BaseExtensionType) + if container == "table": + data = live + elif container == "batch": + data = live.to_batches()[0] + else: + data = live.to_reader() + actual = _frame_source(kind, data) + expected = _frame_source(kind, plain) + actual_table = actual.as_table() + assert actual_table.equals(expected.as_table()) + assert actual_table.schema.field("value").metadata == ( + { + b"ARROW:extension:name": b"test.source.live", + b"ARROW:extension:metadata": b"{}", + } + if kind == "dataframe" + else None + ) + assert [row["value"] for _, row in actual.iter_data()] == ["a", "b"] + + +@pytest.mark.parametrize("kind", ["dataframe", "polling"]) +def test_frame_sources_refuse_nested_stored_pandas_arrow_fields(kind: str) -> None: + child = pa.field( + "item", + pa.large_string(), + metadata={b"ARROW:extension:name": b"test.source.stored"}, + ) + nested = pa.array([{"item": "a"}, {"item": "b"}], type=pa.struct([child])) + table = pa.table({"k": [1, 2], "value": nested}) + frame = table.to_pandas(types_mapper=pd.ArrowDtype) + with pytest.raises( + InputValidationError, match=r"'value'\.'item'.*test\.source\.stored" + ): + _frame_source(kind, frame) + + +@pytest.mark.parametrize("kind", ["dataframe", "polling"]) +def test_frame_sources_validate_the_arrow_import_of_an_arro3_export(kind: str) -> None: + stored = _stored_paths().append_column("k", pa.array([1, 2])) + assert not isinstance(stored.schema.field("path").type, pa.BaseExtensionType) + exported = ArroTable.from_arrow(stored) + assert isinstance( + pa.table(exported).schema.field("path").type, pa.BaseExtensionType + ) + assert [row["path"] for _, row in _frame_source(kind, exported).iter_data()] == [ + Path("a"), + Path("c"), + ] + + field = stored.schema.field("path").with_metadata( + {b"ARROW:extension:name": b"test.source.stored"} + ) + exported = ArroTable.from_arrow(stored.set_column(0, field, stored.column("path"))) + imported_field = pa.table(exported).schema.field("path") + assert imported_field.equals(field, check_metadata=True) + with pytest.raises(InputValidationError, match=r"'path'.*test\.source\.stored"): + _frame_source(kind, exported) + + def test_a_raw_arrow_table_stream_preserves_nested_null() -> None: field = pa.field("extra", pa.large_list(pa.null())) table = _table(field, [[None], []]) From 6a1f4d2407919f85a426e2fa6fa2bccb3dde98f4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:35:24 -0800 Subject: [PATCH 5/9] test(delta): exercise annotated storage after source intake --- tests/test_pipeline/test_delta_refusals_in_jobs.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py index 4b5420c00..4acafa7cf 100644 --- a/tests/test_pipeline/test_delta_refusals_in_jobs.py +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -119,7 +119,7 @@ def test_a_function_with_output_keys_differing_in_case_stops( def test_annotated_list_reaches_delta_operator_log( tmp_path: Path, use_async: bool, registered: bool ) -> None: - """A tagged Arrow source carries annotated storage to the logging operator.""" + """A raw Arrow stream carries annotated storage to the logging operator.""" from orcapod.contexts import get_default_context path_type: Any = get_default_context().type_converter.python_type_to_arrow_type( @@ -138,17 +138,22 @@ def test_annotated_list_reaches_delta_operator_log( type=pa.large_list(item), ) source = ArrowTableSource( - pa.table({"k": [1, 2], "x": [10, 20], "extra": extra}), + pa.table({"k": [1, 2], "x": [10, 20]}), tag_columns=["k"], tag_only_columns=True, record_id_columns=["k"], source_id="input", infer_nullable=True, ) + table = source.as_table(columns={"source": True, "system_tags": True}) + stream = ArrowTableStream( + table.append_column(pa.field("extra", extra.type, nullable=False), extra), + tag_columns=["k"], + ) database = DeltaTableDatabase(tmp_path) job = PipelineJob(name="itl1372", database=database) with job: - source.map_data({"x": "z"}, label="renamed") + stream.map_data({"x": "z"}, label="renamed") job.nodes["renamed"].attach_databases(database, cache_mode=CacheMode.LOG) with pytest.raises(OrcapodDatabaseWriteError) as error: _run(job, use_async) From 959001cd3068bd9f635927151a6b17d7fd51c2d7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:54:04 -0800 Subject: [PATCH 6/9] docs(sources): show refusal of stored UUID list items --- docs/concepts/sources.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index fc99ce262..80bac7e41 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -228,20 +228,22 @@ nullable item. Use matching nested flags when joining sources or binding a slot. The inner field's `nullable` flag is part of a list column's type. Orcapod preserves the inner field's name and metadata in the source's Arrow schema. When hashing the schema, -Orcapod ignores the item name and ordinary metadata. An Arrow extension identifier, -stored in `ARROW:extension:*` metadata, contributes to the hash. +Orcapod ignores the item name and ordinary metadata. An Arrow extension identifier +contributes to the schema hash. If a plain storage field carries that identifier only in +`ARROW:extension:*` metadata, the source refuses it, including on a list item. Streaming joins compare the types of incoming user columns without considering list item names or metadata. They check source-info columns more strictly. When validating a materialized operator result against its declared schema before caching it, Orcapod also checks the item names and metadata of the fields it validates. -This example compares the original source's pipeline hash with the hash after each schema -change. +This example compares pipeline hashes for ordinary list item changes and shows what happens +when a stored logical type reaches the source. ```python import pyarrow as pa +from orcapod.errors import InputValidationError from orcapod.sources import ArrowTableSource @@ -261,8 +263,11 @@ print("Required item:", original == list_source(nullable=False).pipeline_hash()) # Required item: False uuid_metadata = {"ARROW:extension:name": "arrow.uuid", "ARROW:extension:metadata": ""} -print("UUID extension:", original == list_source(metadata=uuid_metadata).pipeline_hash()) -# UUID extension: False +try: + list_source(metadata=uuid_metadata) +except InputValidationError as exc: + print(exc) +# Source column(s) 'values'.'item' ('arrow.uuid' (b'')) carry logical types in stored form. Pass each column as its logical Arrow extension type, or drop the annotation if the column is meant as plain data. ``` When `DictSource` or `ListSource` builds a source from Python values, it checks the From dde0a6ee97b034476f2f5b128e08f70d9acaff60 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:41:40 -0800 Subject: [PATCH 7/9] fix(sources): validate Polars annotations before schema conversion --- src/orcapod/core/sources/data_frame_source.py | 9 +- src/orcapod/core/sources/polling_source.py | 15 ++- .../sources/test_source_arrow_validation.py | 126 ++++++++++++++++-- 3 files changed, 131 insertions(+), 19 deletions(-) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index eff17b919..a6db9e54f 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -113,9 +113,10 @@ def __init__( tag_columns = _normalize_column_list(tag_columns) - require_supported_nullable_types( - polars_data_utils.get_system_columns(df).to_arrow().schema - ) + system_schema = polars_data_utils.get_system_columns(df).to_arrow().schema + require_supported_nullable_types(system_schema) + if input_schema is None: + require_live_logical_types(system_schema) df = polars_data_utils.drop_system_columns(df) missing = set(tag_columns) - set(df.columns) @@ -123,6 +124,8 @@ def __init__( raise ValueError(f"TagProtocol column(s) not found in data: {missing}") arrow_table = df.to_arrow() + if input_schema is None: + require_live_logical_types(arrow_table.schema, exclude=system_tag_columns) if schema is not None: require_supported_nullable_types(schema) if arrow_input_schema is None: diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 590e91f13..2015cfcb3 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -905,7 +905,8 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - if (arrow_frame := read_arrow_frame_input(data)) is not None: + arrow_frame = read_arrow_frame_input(data) + if arrow_frame is not None: data, _ = arrow_frame df = pl.DataFrame(data) if len(df.columns) == 0: @@ -914,9 +915,13 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: self.source_id, ) return None - return self._build_stream_from_df(df) + return self._build_stream_from_df( + df, arrow_input_checked=arrow_frame is not None + ) - def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: + def _build_stream_from_df( + self, df: pl.DataFrame, *, arrow_input_checked: bool + ) -> ArrowTableStream | None: """Build an ``ArrowTableStream`` from a Polars DataFrame. Returns ``None`` on the infer-once path when the batch has zero rows and @@ -934,6 +939,10 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: raw = df.to_arrow() require_supported_nullable_types(raw.schema) + # An Arrow input has already been checked against its authoritative schema. + # Polars conversion can export a live, unregistered extension as storage. + if not arrow_input_checked: + require_live_logical_types(raw.schema) arrow_table = arrow_utils.drop_system_columns(raw) # Establish canonical schema on first call; apply it on every call. diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index b38c459b9..b3eea62f2 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -3,8 +3,9 @@ from __future__ import annotations import asyncio +import contextlib import sqlite3 -from collections.abc import Collection +from collections.abc import Collection, Iterator from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, TypedDict @@ -19,6 +20,7 @@ import pytest from arro3.core import Table as ArroTable +import orcapod.sources as public_sources from orcapod import PipelineJob, function_pod from orcapod.contexts import get_default_context from orcapod.contexts.stored import with_data_context @@ -32,12 +34,14 @@ DataFrameSource, DBTableSource, DeltaTableSource, + DerivedSource, DictSource, ListSource, PollingSource, PostgreSQLTableSource, SpiralDBTableSource, SQLiteTableSource, + stream_builder, ) from orcapod.core.sources.source_proxy import SourceProxy from orcapod.core.streams import ArrowTableStream @@ -50,6 +54,7 @@ from orcapod.operators import DropNulls from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.sources import RootSource from orcapod.types import CacheMode, ColumnInfo, Cursor, DataValue from orcapod.utils.arrow_utils import ( normalize_extension_columns, @@ -62,17 +67,17 @@ from polars._typing import FrameInitTypes TAGS = ("g", "k") -SOURCE_KINDS = ( - "arrow", - "dict", - "dataframe", - "csv", - "delta", - "db", - "postgres", - "spiral", - "sqlite", -) +SOURCE_KINDS = { + "arrow": ArrowTableSource, + "dict": DictSource, + "dataframe": DataFrameSource, + "csv": CSVSource, + "delta": DeltaTableSource, + "db": DBTableSource, + "postgres": PostgreSQLTableSource, + "spiral": SpiralDBTableSource, + "sqlite": SQLiteTableSource, +} class _SourceOptions(TypedDict): @@ -203,6 +208,53 @@ def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: ) +def test_exported_sources_reach_stored_form_validation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Exercise the validation walker through each public external source.""" + checked: set[str] = set() + walk = stream_builder._stored_logical_fields # pyright: ignore[reportPrivateUsage] + + def record(field: pa.Field[Any]) -> Iterator[tuple[str, str]]: + checked.add(field.name) + yield from walk(field) + + monkeypatch.setattr(stream_builder, "_stored_logical_fields", record) + # These have no external Arrow intake. They delegate to a bound source or + # decode Orcapod's own records (covered by the stored-record round-trip test). + internal_sources = {RootSource, CachedSource, DerivedSource, SourceProxy} + kinds = {source: kind for kind, source in SOURCE_KINDS.items()} + for name in public_sources.__all__: + source_type: object = getattr(public_sources, name) + if not isinstance(source_type, type) or not issubclass(source_type, RootSource): + continue + if source_type in internal_sources: + continue + checked.clear() + table = pa.table({"k": [1, 2], "g": ["a", "b"], "payload": ["c", "d"]}) + if source_type is ListSource: + source = ListSource("payload", ["c", "d"]) + elif source_type is PollingSource: + source = PollingSource( + _Poll(None, pl.DataFrame(table)), + ["k"], + source_id="poll", + record_id_columns="k", + ) + assert source.check_for_new_data() + else: + assert source_type in kinds, f"Add an intake case for {name}" + path = tmp_path / name + path.mkdir() + with monkeypatch.context() as patches: + built = _source(kinds[source_type], table, path, patches) + # Sources may defer validation until they start reading rows. + _ = built.as_table() + source = built + assert type(source) is source_type + assert "payload" in checked, f"{name} skipped stored-form validation" + + def _live_paths() -> pa.Table: converter = get_default_context().type_converter return converter.python_dicts_to_arrow_table( @@ -662,7 +714,7 @@ async def fetch( async def poll(self, cursor: Cursor[int] | None = None) -> bool: """There are no rows after the initial fetch.""" - return False + return cursor is None async def close(self) -> None: """There is no connection to close.""" @@ -712,6 +764,54 @@ def build() -> None: assert "orcapod.path" in str(error.value) +@pytest.mark.parametrize("route", ["dataframe", "polling-sync", "polling-async"]) +@pytest.mark.parametrize("reverse", [False, True]) +def test_plain_schema_cannot_hide_stored_polars_fields( + route: str, reverse: bool +) -> None: + """Validate the data's annotations even when the declaration has none.""" + extension_name = "test.polars.stored" + frame = pl.DataFrame( + {"k": [1, 2], "path": ["a", "b"], "other": ["c", "d"]} + ).with_columns( + pl.col("path", "other").ext.to(pl.Extension(extension_name, pl.String, "{}")) + ) + if reverse: + frame = frame.select(frame.columns[::-1]) + incoming = frame.to_arrow().schema + for name in ("path", "other"): + field = incoming.field(name) + assert field.type == pa.large_string() + assert field.metadata == { + b"ARROW:extension:name": extension_name.encode(), + b"ARROW:extension:metadata": b"{}", + } + plain_schema = pa.schema([field.remove_metadata() for field in incoming]) + + async def read_async(poll: PollingSource[int]) -> None: + async with contextlib.aclosing(poll.async_iter_data()) as rows: + _ = await anext(rows) + + with pytest.raises(InputValidationError) as error: + if route == "dataframe": + _ = DataFrameSource(frame, schema=plain_schema, tag_columns=["k"]) + else: + poll = PollingSource( + _Poll(plain_schema, frame), + ["k"], + source_id="poll", + record_id_columns="k", + ) + if route == "polling-sync": + _ = poll.check_for_new_data() + else: + asyncio.run(read_async(poll)) + message = str(error.value) + assert "'other'" in message and "'path'" in message + assert message.count(extension_name) == 2 + assert "stored form" in message and "drop the annotation" in message + + class _UnregisteredExtension(pa.ExtensionType): """A live PyArrow extension that has never been registered.""" From 0632f95a300d10fc2eb71bf366911fa22c990b58 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:23:50 -0800 Subject: [PATCH 8/9] fix(sources): validate native Arrow fields before C import --- docs/dev/design_issues/ITL-1333-BL17.md | 7 +- src/orcapod/core/sources/data_frame_source.py | 2 +- src/orcapod/core/sources/polling_source.py | 15 +-- src/orcapod/core/sources/stream_builder.py | 31 +++-- .../sources/test_source_arrow_validation.py | 117 ++++++++++++++++++ 5 files changed, 150 insertions(+), 22 deletions(-) diff --git a/docs/dev/design_issues/ITL-1333-BL17.md b/docs/dev/design_issues/ITL-1333-BL17.md index 0aa733fc9..8047b5626 100644 --- a/docs/dev/design_issues/ITL-1333-BL17.md +++ b/docs/dev/design_issues/ITL-1333-BL17.md @@ -10,8 +10,9 @@ identifier in metadata. A live extension array with the same values had the same and content hashes but gave downstream functions Path objects. **Fix:** Refuse external Arrow fields that carry logical annotations on their storage type, -including nested fields in pandas Arrow-backed columns. For native PyArrow inputs, use the -original field type before a C round-trip can change it. For third-party Arrow C exporters, -use the field type and metadata after importing into PyArrow. The existing decoding of +including nested fields in pandas Arrow-backed columns. For native PyArrow inputs, including +struct arrays and chunked struct arrays, use the original fields before a C round-trip can +change their types. For third-party Arrow C exporters, use the field type and metadata +after importing into PyArrow. The existing decoding of Orcapod-owned stored records retains its behavior. Resolving stored logical types at external source boundaries is planned separately. diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index a6db9e54f..9492bc553 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -161,7 +161,7 @@ def __init__( record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, system_tag_columns=system_tag_columns, - input_schema=input_schema if schema is None else None, + input_schema=input_schema if schema is None else schema, ) self._stream = result.stream diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 2015cfcb3..0e31346c2 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -906,8 +906,9 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ arrow_frame = read_arrow_frame_input(data) + input_schema = None if arrow_frame is not None: - data, _ = arrow_frame + data, input_schema = arrow_frame df = pl.DataFrame(data) if len(df.columns) == 0: logger.debug( @@ -915,12 +916,10 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: self.source_id, ) return None - return self._build_stream_from_df( - df, arrow_input_checked=arrow_frame is not None - ) + return self._build_stream_from_df(df, input_schema=input_schema) def _build_stream_from_df( - self, df: pl.DataFrame, *, arrow_input_checked: bool + self, df: pl.DataFrame, *, input_schema: pa.Schema | None ) -> ArrowTableStream | None: """Build an ``ArrowTableStream`` from a Polars DataFrame. @@ -941,8 +940,9 @@ def _build_stream_from_df( require_supported_nullable_types(raw.schema) # An Arrow input has already been checked against its authoritative schema. # Polars conversion can export a live, unregistered extension as storage. - if not arrow_input_checked: - require_live_logical_types(raw.schema) + if input_schema is None: + input_schema = raw.schema + require_live_logical_types(input_schema) arrow_table = arrow_utils.drop_system_columns(raw) # Establish canonical schema on first call; apply it on every call. @@ -992,6 +992,7 @@ def _build_stream_from_df( source_name=self._source_name, kind_part=self.kind_part(), record_id_columns=self._record_id_columns, + input_schema=input_schema, ) return result.stream diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index d3cd5b698..38070e460 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -47,7 +47,7 @@ def _stored_logical_fields(field: pa.Field[Any]) -> Iterator[tuple[str, str]]: """Yield the field paths and identifiers of logical types in storage form.""" - arrow_type = field.type + arrow_type: pa.DataType = field.type if isinstance(arrow_type, pa.BaseExtensionType): # The live extension owns its storage layout. return @@ -59,6 +59,9 @@ def _stored_logical_fields(field: pa.Field[Any]) -> Iterator[tuple[str, str]]: yield repr(field.name), f"{decoded!r} ({payload or b''!r})" elif payload is not None: yield repr(field.name), f" ({payload!r})" + # PyArrow exposes the dictionary's value type separately from its fields. + if isinstance(arrow_type, pa.DictionaryType): + yield from _stored_logical_fields(pa.field(field.name, arrow_type.value_type)) for index in range(arrow_type.num_fields): for path, identifier in _stored_logical_fields(arrow_type.field(index)): yield f"{field.name!r}.{path}", identifier @@ -106,11 +109,17 @@ def read_arrow_frame_input( return None if isinstance(data, (pl.DataFrame, pl.Series)): return None + # C import can rehydrate stored fields or turn live extensions into storage. + # The original PyArrow fields are authoritative for native inputs. input_schema = None if isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): - # C import can rehydrate stored fields or turn live extensions into storage. - # The original PyArrow field type is authoritative for native inputs. input_schema = data.schema + elif isinstance(data, (pa.Array, pa.ChunkedArray)) and pa.types.is_struct( + data.type + ): + # Passing the StructType directly to pa.schema would also use C import. + input_schema = pa.schema(list(data.type)) + if input_schema is not None: require_live_logical_types(input_schema, exclude=system_tag_columns) # Like Polars, prefer the array export when both are available. if hasattr(data, "__arrow_c_array__"): @@ -705,9 +714,8 @@ def build( have chosen on purpose. Needs key columns and no ``source_id``. from_origin: The table came from an existing Orcapod source or job node, after that origin's own validation and decoding. - input_schema: The original Arrow schema when frame conversion can - change the representation of a logical field. Used only to - determine whether the external input carried stored logical types. + input_schema: The Arrow schema to validate for stored logical types + when a conversion may have changed the fields in the table. Returns: SourceStreamResult with enriched stream and metadata. @@ -746,6 +754,12 @@ def build( # so say so here rather than report the tag as missing (ITL-1080). schema_utils.require_names_not_meta(tag_columns_tuple) + if not from_origin: + require_live_logical_types( + table.schema if input_schema is None else input_schema, + exclude=system_tag_columns_tuple, + ) + # Dictionary-encoded columns are not currently supported (ITL-1264, # ITL-1277). The stream refuses them too; checking first reports the # dictionary, not a key column error, and before anything is hashed. It runs @@ -764,13 +778,8 @@ def build( ) # 1. Drop system columns from raw input. - raw_schema = table.schema table = arrow_utils.drop_system_columns(table) require_custom_system_tags(table, system_tag_columns_tuple) - if not from_origin: - require_live_logical_types( - raw_schema if input_schema is None else input_schema - ) # 2. Validate tag_columns. A table with no columns at all (e.g. a # DictSource built from no rows and no schema) gets its own error, since diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index b3eea62f2..384deda16 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -55,6 +55,7 @@ from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.sources import RootSource +from orcapod.system_constants import constants from orcapod.types import CacheMode, ColumnInfo, Cursor, DataValue from orcapod.utils.arrow_utils import ( normalize_extension_columns, @@ -871,6 +872,122 @@ def test_frame_sources_accept_live_unregistered_extensions( assert [row["value"] for _, row in actual.iter_data()] == ["a", "b"] +@pytest.mark.parametrize( + "route", ["arrow", "dataframe", "polling-sync", "polling-async"] +) +@pytest.mark.parametrize("layout", ["top-level", "struct", "list", "map"]) +@pytest.mark.parametrize("registered", [False, True], ids=["unregistered", "path"]) +@pytest.mark.parametrize("stored", [False, True], ids=["live", "stored"]) +def test_native_arrow_logical_fields( + route: str, layout: str, registered: bool, stored: bool +) -> None: + """Validate the original field types before any Arrow C import.""" + if registered: + leaves = _live_paths() + else: + ext = _UnregisteredExtension() + leaves = pa.table( + { + name: pa.ExtensionArray.from_storage( + ext, pa.array(values, type=pa.large_string()) + ) + for name, values in (("path", ["a", "c"]), ("other", ["b", "d"])) + } + ) + if stored: + leaves = normalize_extension_columns(leaves) + path, other = leaves.schema + paths, others = (column.combine_chunks() for column in leaves.columns) + offsets = pa.array([0, 1, 2], type=pa.int32()) + # All routes validate system columns before discarding them. Use one to + # exercise the nested guard independently of existing hash and cast limits. + nested_name = f"{constants.SYSTEM_TAG_PREFIX}logical" + if layout == "struct": + array = pa.StructArray.from_arrays([paths, others], fields=[path, other]) + table = pa.table({nested_name: array}) + elif layout == "list": + array = pa.ListArray.from_arrays(offsets, paths, type=pa.list_(path)) + table = pa.table({nested_name: array}) + elif layout == "map": + key = path.with_name("key").with_nullable(False) + item = other.with_name("value") + map_type = pa.map_(key, item) # pyright: ignore[reportArgumentType] # PyArrow accepts fields. + # PyArrow accepts int32 offsets and an explicit map type. + array = pa.MapArray.from_arrays( + offsets, + paths, + others, + type=map_type, # pyright: ignore[reportArgumentType] + ) + table = pa.table({nested_name: array}) + else: + table = leaves + table = table.append_column("k", pa.array([1, 2])) + if layout != "top-level": + table = table.append_column("payload", pa.array([1, 2])) + name = "path" if layout == "top-level" else "payload" + + async def read_async(poll: PollingSource[int]) -> object: + async with contextlib.aclosing(poll.async_iter_data()) as rows: + _, data = await anext(rows) + return data[name] + + def read(data: FrameInitTypes) -> object: + if route == "arrow": + return next(ArrowTableSource(table).iter_data())[1][name] + if route == "dataframe": + return next(DataFrameSource(data).iter_data())[1][name] + poll = PollingSource( + _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" + ) + if route == "polling-async": + return asyncio.run(read_async(poll)) + assert poll.check_for_new_data() + return next(poll.iter_data())[1][name] + + # A struct exported as an array or a stream can change the field types when + # imported through the Arrow C interface. Cover both native representations. + native_inputs: list[FrameInitTypes] = [table] + if route != "arrow": + struct = table.to_struct_array() + native_inputs.extend([struct, struct.chunk(0)]) + for data in native_inputs: + if stored: + with pytest.raises(InputValidationError, match="stored form") as error: + _ = read(data) + message = str(error.value) + assert ("orcapod.path" if registered else "test.source.live") in message + if layout in ("top-level", "struct"): + assert "'path'" in message and "'other'" in message + elif layout == "list": + assert f"{nested_name!r}.'path'" in message + else: + assert ".'key'" in message and ".'value'" in message + else: + expected = Path("a") if registered else "a" + assert read(data) == (expected if layout == "top-level" else 1) + + +@pytest.mark.parametrize( + "list_kind", + ["list", "large-list", "fixed-size-list", "list-view", "large-list-view"], +) +def test_stored_field_in_dictionary_value_list(list_kind: str) -> None: + child = _stored_paths().schema.field("path") + list_type = { + "list": pa.list_(child), + "large-list": pa.large_list(child), + "fixed-size-list": pa.list_(child, 1), + "list-view": pa.list_view(child), + "large-list-view": pa.large_list_view(child), + }[list_kind] + # PyArrow permits a nested dictionary value type. + encoded = pa.dictionary(pa.int8(), list_type) # pyright: ignore[reportArgumentType] + schema = pa.schema([pa.field("encoded", encoded)]) + with pytest.raises(InputValidationError, match=r"'encoded'\.'path'.*orcapod.path"): + stream_builder.require_live_logical_types(schema) + + @pytest.mark.parametrize("kind", ["dataframe", "polling"]) def test_frame_sources_refuse_nested_stored_pandas_arrow_fields(kind: str) -> None: child = pa.field( From cba65038c7f9f3fc6195d3553429d1d7b740d905 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:24:52 -0800 Subject: [PATCH 9/9] test(sources): account for PyArrow map offset stub --- tests/test_core/sources/test_source_arrow_validation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 384deda16..077303fc4 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -914,7 +914,7 @@ def test_native_arrow_logical_fields( map_type = pa.map_(key, item) # pyright: ignore[reportArgumentType] # PyArrow accepts fields. # PyArrow accepts int32 offsets and an explicit map type. array = pa.MapArray.from_arrays( - offsets, + offsets, # pyright: ignore[reportArgumentType] paths, others, type=map_type, # pyright: ignore[reportArgumentType]