From f30ed2fbd2edccb6afa8d9404d7af24308c38c29 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:39:16 -0800 Subject: [PATCH 01/21] fix(sources)!: refuse reserved column names instead of dropping them (ITL-1165) --- .zed/rules | 6 + CLAUDE.md | 6 + changelog.d/ITL-1165.md | 15 ++ docs/concepts/streams.md | 9 ++ docs/dev/design_issues/ITL-1165-RN1.md | 7 +- src/orcapod/core/data_function.py | 1 + src/orcapod/core/operators/index.py | 3 +- src/orcapod/core/operators/pick.py | 3 +- src/orcapod/core/sources/data_frame_source.py | 2 + src/orcapod/core/sources/db_table_source.py | 8 +- src/orcapod/core/sources/derived_source.py | 4 + src/orcapod/core/sources/polling_source.py | 9 +- .../core/sources/spiraldb_table_source.py | 8 +- src/orcapod/core/sources/stream_builder.py | 37 +++-- src/orcapod/utils/schema_utils.py | 38 ++--- .../operators/test_async_sync_equivalence.py | 9 +- .../operators/test_mappers_strict.py | 5 +- tests/test_core/operators/test_pick_index.py | 25 ++- .../test_dictionary_columns_refused.py | 10 +- .../sources/test_source_arrow_validation.py | 143 +++++++++++++++++- .../test_source_protocol_conformance.py | 14 +- .../sources/test_sources_comprehensive.py | 13 +- .../test_core/sources/test_stream_builder.py | 11 +- .../test_delta_merge_reserved_names.py | 10 +- tests/test_pipeline/test_provenance_review.py | 22 ++- 25 files changed, 325 insertions(+), 93 deletions(-) create mode 100644 changelog.d/ITL-1165.md diff --git a/.zed/rules b/.zed/rules index f618cedcb..8d803e02b 100644 --- a/.zed/rules +++ b/.zed/rules @@ -963,6 +963,12 @@ of its identity (GroupBy's member_order), never the input's column order. ### Column naming conventions +All column names beginning with `_` are reserved for Orcapod (ITL-1165). Sources refuse +raw input with these names and tell callers to rename the columns or drop them first. +The source's `system_tag_columns` option retains its custom system-tag validation. +Operators and function pods validate new user column names with +`schema_utils.require_names_not_system`. + __ prefix — System metadata (ColumnConfig meta) _source_ prefix — Source info provenance (ColumnConfig source) _tag:: prefix — System tag (ColumnConfig system_tags) diff --git a/CLAUDE.md b/CLAUDE.md index 538313dd0..2b4f8eb8f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -986,6 +986,12 @@ of its identity (GroupBy's `member_order`), never the input's column order. ### Column naming conventions +All column names beginning with `_` are reserved for Orcapod (ITL-1165). Sources refuse +raw input with these names and tell callers to rename the columns or drop them first. +The source's `system_tag_columns` option retains its custom system-tag validation. +Operators and function pods validate new user column names with +`schema_utils.require_names_not_system`. + | Prefix | Meaning | Example | Controlled by | |--------|---------|---------|---------------| | `__` | System metadata | `__data_id`, `__pod_version` | `ColumnConfig(meta=True)` | diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md new file mode 100644 index 000000000..34c8d50d2 --- /dev/null +++ b/changelog.d/ITL-1165.md @@ -0,0 +1,15 @@ +### Breaking changes and migration + +- Column names that begin with `_` are reserved. Sources refuse these columns instead + of silently dropping them. Rename your own columns or drop reserved columns before + building the source. When reading a table that Orcapod wrote, drop its system columns + first. The `system_tag_columns` option retains its existing validation. +- Operator output and rename targets and function pod output keys must use names that + do not begin with `_`. A saved configuration with a reserved function pod output key + is refused when the pod is rebuilt. Rename the output key and update its downstream + references in the pipeline before saving a new configuration. + +### Fixed + +- `Pick` and `Index` reject reserved `out` names at construction, so their output + columns stay visible in stream tables. diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 40c13de07..4b29158a8 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -323,6 +323,15 @@ shortcut) to control which column groups are included. | `content_hash` | Content hash column | `_content_hash` | | `sort_by_tags` | Sort rows by tag columns | (ordering only) | +Every column name beginning with `_` is reserved for Orcapod. Use another name for +user tags, data columns, operator outputs and function pod output keys. Underscores +after the first character are allowed. + +When reading a table back as a source, drop its system columns first. If you still +have the original stream, `stream.as_table()` gives you its user-facing columns. +The source's `system_tag_columns` option still lets you nominate input columns as +custom system tags under its existing validation rules. + Pass config as a dict or a `ColumnConfig` object: ```python diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index a71fd0d3a..4f874f8c3 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -1,7 +1,7 @@ ## Cross-cutting ### RN1 — Reserved `_` column names: sources silently drop them, `Pick` / `Index` accept them as new names -**Status:** open +**Status:** resolved **Severity:** medium **Issue:** ITL-1165 @@ -25,3 +25,8 @@ November 16, 2026 while fixing ITL-1160, probed on that branch): To decide: which names are reserved; then a source refuses such a column with an error naming it instead of dropping it, and `Pick` / `Index` refuse a reserved `out` name through the same helper as the mappers. + +**Fix:** Reserve all leading-underscore column names for Orcapod. Raw source readers +report the offending columns and how to remove or rename them. The same rule covers +new operator names and function pod output keys. Custom system-tag declarations retain +their existing validation. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index acf8e48ac..2d2adb34c 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -825,6 +825,7 @@ def __init__( output_keys = [output_keys] # A copy taken once: a later change to the caller's list changes nothing. output_keys = tuple(output_keys) + schema_utils.require_names_not_system(output_keys) self._output_keys = output_keys if function_name is None: if hasattr(self._function, "__name__"): diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index cbb6c2c37..fd7402915 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -66,10 +66,9 @@ def __init__( ) -> None: self.column = column self.i = i - # A data column never gets a meta column's name (ITL-1080): refused here, - # as ``MapData`` refuses it, so no path can produce one and drop it. if out is not None: schema_utils.require_names_not_meta([out]) + schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out self.fail_on_miss = fail_on_miss diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 09824160d..cb83db9e3 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -68,10 +68,9 @@ def __init__( ) -> None: self.column = column self.key = key - # A data column never gets a meta column's name (ITL-1080): refused here, - # as ``MapData`` refuses it, so no path can produce one and drop it. if out is not None: schema_utils.require_names_not_meta([out]) + schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out self.fail_on_miss = fail_on_miss diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 54a563f88..1c17b5ab7 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -13,6 +13,7 @@ from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, require_custom_system_tags, + require_source_column_names, require_supported_nullable_types, ) from orcapod.utils import arrow_utils, polars_data_utils @@ -83,6 +84,7 @@ def __init__( require_supported_nullable_types( polars_data_utils.get_system_columns(df).to_arrow().schema ) + require_source_column_names(df.columns, system_tag_columns) df = polars_data_utils.drop_system_columns(df) missing = set(tag_columns) - set(df.columns) diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 55f0c82b7..5c19bd9a4 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -26,6 +26,7 @@ from orcapod.core.sources.source_ids import location_source_name from orcapod.core.sources.reload import keep_nullable_columns, same_rows from orcapod.core.sources.stream_builder import ( + require_source_column_names, require_supported_nullable_types, normalize_record_id_columns, SourceStreamBuilder, @@ -166,6 +167,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 +175,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) @@ -224,13 +225,16 @@ def _read_table( """ if self._table_name not in connector.get_table_names(): raise ValueError(f"Table {self._table_name!r} not found in database.") + col_infos = connector.get_column_info(self._table_name) + require_source_column_names( + [info.name for info in col_infos], self._system_tag_columns + ) batches = list(connector.iter_batches(self._query)) if not batches: raise ValueError(f"Table {self._table_name!r} is empty.") table: pa.Table = pa.Table.from_batches(batches) # 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) if col_infos: db_nullable = {ci.name: ci.nullable for ci in col_infos} db_schema = pa.schema( diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index aeef4bfd5..a47b6d133 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -610,6 +610,10 @@ def _derive_from( table: Rows of the origin. tags_as_data: Maps a tag column of the origin to the name of its copy. """ + # A job node's stored records can include the context of their own rows. + # The builder attaches this source's context when it enriches the user columns. + if constants.CONTEXT_KEY in table.column_names: + table = table.drop([constants.CONTEXT_KEY]) for tag, name in tags_as_data.items(): # The copy is the tag's own Arrow column under a renamed field, so its # type, nullability and field metadata are the tag's exactly. diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b4f65398..3b0aeee5c 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -28,6 +28,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + require_source_column_names, require_supported_nullable_types, ) from orcapod.core.streams.view import ( @@ -331,6 +332,7 @@ def __init__( unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): require_supported_nullable_types(unified_schema) + require_source_column_names(unified_schema.names) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). self._declared_arrow = declaration_form_schema( @@ -369,6 +371,7 @@ def __init__( unified_schema, self.data_context.type_converter ) require_supported_nullable_types(self._declared_arrow) + require_source_column_names(self._declared_arrow.names) # ------------------------------------------------------------------------- # Schema helpers — fetch-free schema computation from declared schemas @@ -899,9 +902,9 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: ) df = df.with_columns([pl.from_arrow(c) for c in sub_table]) - raw = df.to_arrow() - require_supported_nullable_types(raw.schema) - arrow_table = arrow_utils.drop_system_columns(raw) + arrow_table = df.to_arrow() + require_supported_nullable_types(arrow_table.schema) + require_source_column_names(arrow_table.column_names) # Establish canonical schema on first call; apply it on every call. if self._canonical_arrow_schema is None: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 2ea3de773..16d9c0f50 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -62,6 +62,7 @@ from orcapod.core.sources.derived_source import validate_tags_as_data from orcapod.core.sources.stream_builder import ( require_custom_system_tags, + require_source_column_names, require_supported_nullable_types, SourceStreamBuilder, key_column_type_allowed, @@ -786,9 +787,9 @@ def check_for_new_data(self) -> bool: # One lookup per check (ITL-1350): a table dropped and created again since # is found by this lookup, and its schema and version come from it. table = self._lookup_table() - schema = arrow_utils.drop_system_columns( - table.arrow_schema().empty_table() - ).schema + raw_schema = table.arrow_schema() + require_source_column_names(raw_schema.names, self._system_tag_columns) + schema = arrow_utils.drop_system_columns(raw_schema.empty_table()).schema if not schema.equals(self._table_schema, check_metadata=True): raise ValueError( f"SpiralDB table {self._qualified!r}: " @@ -903,6 +904,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_source_column_names(raw.column_names, self._system_tag_columns) 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 b54428354..681e847ca 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -1,7 +1,7 @@ """Compositional builder for enriching raw Arrow tables into source streams. Extracts the enrichment pipeline that was previously embedded in -``ArrowTableSource.__init__``: dropping system columns, validating tags, +``ArrowTableSource.__init__``: validating input columns and tags, computing schema/table hashes, adding source-info provenance, adding system tag columns, and wrapping the result in an ``ArrowTableStream``. """ @@ -63,6 +63,27 @@ def require_supported_nullable_types(schema: pa.Schema) -> None: ) +def require_source_column_names( + names: Collection[str], system_tag_columns: Collection[str] = () +) -> None: + """Refuse raw source columns in the system namespace. + + Args: + names: Raw input column names. + system_tag_columns: Columns explicitly nominated as system tags. These + follow the builder's existing custom system-tag validation. + + Raises: + InputValidationError: If a raw column uses a reserved name. + """ + try: + schema_utils.require_names_not_system(set(names) - set(system_tag_columns)) + except InputValidationError as exc: + raise InputValidationError( + f"{exc} To build the source, rename the reserved columns or drop them first." + ) from exc + + def require_custom_system_tags( table: pa.Table, names: Collection[str], @@ -516,9 +537,9 @@ 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 - (ITL-1264, ITL-1277). + InputValidationError: If a raw column has a reserved name, or its + type is, or contains, a dictionary. Dictionary-encoded columns + are not currently supported (ITL-1264, ITL-1277). """ # Whole-argument checks first, before the table is read. key_columns = normalize_record_id_columns(record_id_columns) or () @@ -539,10 +560,6 @@ def build( # Tag-only columns: the tags that are not also data. tag_only_tuple = tuple(c for c in tag_columns_tuple if c not in data_tags_tuple) - # A tag never has a meta column's name; the meta columns are dropped next, - # so say so here rather than report the tag as missing (ITL-1080). - schema_utils.require_names_not_meta(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 @@ -560,7 +577,9 @@ def build( found, tag_columns_tuple, data_tags_tuple, system_tag_columns_tuple ) - # 1. Drop system columns from raw input. + # 1. Refuse reserved names before any system columns could be dropped. + require_source_column_names(table.column_names, system_tag_columns_tuple) + schema_utils.require_names_not_meta(tag_columns_tuple) table = arrow_utils.drop_system_columns(table) require_custom_system_tags(table, system_tag_columns_tuple) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index f0322d3f2..dff601535 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -1037,38 +1037,22 @@ def schema_hash_rejected_columns_error( def require_names_not_system(names: Collection[str]) -> None: - """Raise if a tag or data column name is one a stream reads as a system column. - - A stream reads a column whose name starts with the system-tag prefix - (``_tag_``) as a system tag, one that starts with the source-info prefix - (``_source_``) as source info, and the context key column (``_context_key``) - as the data context, so a tag or data column renamed to such a name stops - being one (ITL-1160). The meta prefix has its own check, - ``require_names_not_meta``. + """Raise if any user column name begins with the reserved underscore. Args: names: Tag or data column names. Raises: - InputValidationError: If a name starts with the system-tag or the - source-info prefix, or is the context key column. The message names - the column. + InputValidationError: If any name starts with the reserved prefix. The + message names every offending column. """ from orcapod.system_constants import constants - reserved_prefixes = { - constants.SYSTEM_TAG_PREFIX: "system tags", - constants.SOURCE_PREFIX: "source info", - } - for name in sorted(names): - for prefix, kind in reserved_prefixes.items(): - if name.startswith(prefix): - raise InputValidationError( - f"column name {name!r} starts with {prefix!r}, which is reserved " - f"for {kind}; a tag or data column needs another name." - ) - if name == constants.CONTEXT_KEY: - raise InputValidationError( - f"column name {name!r} is reserved for the data context; a tag or " - "data column needs another name." - ) + prefix = constants.DATAGRAM_PREFIX + reserved = sorted({name for name in names if name.startswith(prefix)}) + if reserved: + columns = ", ".join(repr(name) for name in reserved) + raise InputValidationError( + f"Column names {columns} start with {prefix!r}, which is reserved " + "for system columns. A tag or data column needs another name." + ) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 1a6a54096..5271c6efd 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -917,6 +917,11 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: lambda: Index("l8", 0, out="first"), lambda: (source_a(with_data_tags=True),), ), + Case( + "ref_pick", + lambda: Pick("d", "q", out="picked"), + lambda: (source_a(with_data_tags=True),), + ), Case( "ref_drop_nulls_all", lambda: DropNulls(), @@ -2246,8 +2251,8 @@ def test_a_stream_refuses_a_tag_named_with_the_meta_prefix() -> None: def test_a_source_refuses_a_tag_named_with_the_meta_prefix() -> None: - """Not "tag column not found": the source would drop the meta column first.""" - with pytest.raises(InputValidationError, match="'__g'.*reserved for meta"): + """The source reports the reserved name even when it was requested as a tag.""" + with pytest.raises(InputValidationError, match="'__g'.*drop them first"): _ = ArrowTableSource( _table_with_meta_named_column(), tag_columns=["k", "__g"], diff --git a/tests/test_core/operators/test_mappers_strict.py b/tests/test_core/operators/test_mappers_strict.py index d2cab25e3..a9c3555fe 100644 --- a/tests/test_core/operators/test_mappers_strict.py +++ b/tests/test_core/operators/test_mappers_strict.py @@ -491,9 +491,8 @@ def test_the_stream_methods_refuse_a_system_column_name( getattr(_source(), method)({old_name: new_name}) -@pytest.mark.parametrize("new_name", ["_age", "_content_hash"]) -def test_other_underscore_names_stay_usable_as_new_names(new_name: str) -> None: - """Only names a stream reads as system columns are refused (see ITL-1160).""" +@pytest.mark.parametrize("new_name", ["age_", "content_hash"]) +def test_underscores_after_the_first_character_are_allowed(new_name: str) -> None: source = _source() for stream, async_op in ( (source.map_data({"age": new_name}), MapData({"age": new_name})), diff --git a/tests/test_core/operators/test_pick_index.py b/tests/test_core/operators/test_pick_index.py index 91ebbcd12..970efe456 100644 --- a/tests/test_core/operators/test_pick_index.py +++ b/tests/test_core/operators/test_pick_index.py @@ -3,16 +3,39 @@ from __future__ import annotations import pytest +from re import escape from orcapod.logical_types.base_logical_type import BaseLogicalType import dataclasses -from orcapod.core.operators import Pick +from orcapod.core.operators import AddTags, MapColumns, MapData, MapTags, Pick, TagBy from orcapod.core.sources import DictSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.core.operators import Index +@pytest.mark.parametrize( + "build", + [ + lambda name: Index("items", 0, out=name), + lambda name: Pick("scores", "speed", out=name), + lambda name: MapColumns({"x": name}), + lambda name: MapData({"x": name}), + lambda name: MapTags({"x": name}), + lambda name: AddTags({name: "value"}), + lambda name: TagBy(name), + ], + ids=["index", "pick", "map-columns", "map-data", "map-tags", "add-tags", "tag-by"], +) +@pytest.mark.parametrize( + "name", + ["_", "_foo", "_tag_y", "_tag::y", "_source_y", "_content_hash", "_context_key"], +) +def test_operators_refuse_reserved_column_names(build, name: str) -> None: + with pytest.raises(InputValidationError, match=escape(repr(name))): + build(name) + + class ConcreteLogicalType(BaseLogicalType): """Minimal concrete subclass for testing defaults.""" diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index 2168d0f63..5125c03a3 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -297,7 +297,7 @@ def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( own: tuple[str, ...], with_user_column: bool, own_first: bool ) -> None: """The builder checks before it drops system columns (CodeRabbit on PR 455): a - dictionary-free system column is still stripped, a dictionary one is refused.""" + dictionary-encoded system column is refused with its role.""" user: dict[str, pa.Array[Any]] = { "a": pa.array(["x", "y"]), "b": pa.array(["p", "q"]), @@ -317,7 +317,7 @@ def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( assert ("- data column 'v'" in message) == with_user_column -def test_a_dictionary_free_system_column_is_still_stripped() -> None: +def test_a_dictionary_free_system_column_is_also_refused() -> None: table = pa.table( { "a": ["x", "y"], @@ -326,8 +326,10 @@ def test_a_dictionary_free_system_column_is_still_stripped() -> None: "v": [1, 2], } ) - source = ArrowTableSource(table, tag_columns=["a"], tag_only_columns=True) - assert source.keys() == (("a",), ("v",)) + with pytest.raises( + InputValidationError, match="'__note'.*'_source_v'.*drop them first" + ): + ArrowTableSource(table, tag_columns=["a"], tag_only_columns=True) def test_an_opaque_type_over_a_dictionary_is_refused() -> None: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index ff7f5d0b2..248c8efab 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -3,6 +3,7 @@ from __future__ import annotations import sqlite3 +from re import escape from collections.abc import Collection from pathlib import Path from typing import Any, TypedDict @@ -58,7 +59,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] @@ -97,11 +98,13 @@ def _source( monkeypatch: pytest.MonkeyPatch, *, system_tag_columns: Collection[str] = (), + tag_columns: 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": tag_columns, + "tag_only_columns": tag_only_columns, "source_id": "rows", "system_tag_columns": system_tag_columns, } @@ -122,7 +125,7 @@ def _source( file = path / "rows.db" types = {pa.string(): "TEXT", pa.int64(): "INTEGER"} cols = ", ".join( - f"{f.name} {types[f.type]}" + ("" if f.nullable else " NOT NULL") + f'"{f.name}" {types[f.type]}' + ("" if f.nullable else " NOT NULL") for f in table.schema ) with sqlite3.connect(file) as conn: @@ -152,6 +155,108 @@ def _source( return DBTableSource(connector, "rows", **options) +@pytest.mark.parametrize("kind", SOURCE_KINDS) +@pytest.mark.parametrize("role", ["data", "tag", "data-tag"]) +@pytest.mark.parametrize("first", [False, True]) +def test_raw_sources_refuse_all_reserved_columns( + kind: str, role: str, first: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + table = pa.table( + { + "g": ["a", "b"], + "k": [1, 2], + "x": [3, 4], + "y": [5, 6], + "_foo": ["a", "b"], + "_content_hash": ["c", "d"], + } + ) + if first: + table = table.select(["_content_hash", "g", "_foo", "k", "y", "x"]) + tags = TAGS if role == "data" else (*TAGS, "_foo") + with pytest.raises(InputValidationError, match="drop them first") as info: + _source( + kind, + table, + tmp_path, + monkeypatch, + tag_columns=tags, + tag_only_columns=TAGS if role == "data-tag" else True, + ) + assert "'_foo'" in str(info.value) + assert "'_content_hash'" in str(info.value) + + +@pytest.mark.parametrize( + "name", + [ + "_", + "_foo", + "_tag_y", + "_tag::y", + "_source_y", + "_content_hash", + "_context_key", + "__meta", + ], +) +def test_list_source_refuses_reserved_value_column(name: str) -> None: + with pytest.raises(InputValidationError, match=escape(repr(name))): + ListSource(name, [10, 20]) + + +def test_list_source_refuses_reserved_tags() -> None: + def tags(value: int, index: int) -> dict[str, int]: + return {"k": index, "g": value, "_foo": value, "_content_hash": index} + + with pytest.raises( + InputValidationError, match="'_content_hash'.*'_foo'.*drop them first" + ): + ListSource("value", [10, 20], tag_function=tags) + + +def test_rereading_an_orcapod_table_requires_dropping_system_columns() -> None: + source = DictSource( + [ + {"g": "a", "k": 1, "x": 3, "y": 4}, + {"g": "b", "k": 2, "x": 5, "y": 6}, + ], + tag_columns=TAGS, + tag_only_columns=True, + ) + raw = source.as_table(all_info=True) + system_columns = [name for name in raw.column_names if name.startswith("_")] + with pytest.raises(InputValidationError, match="drop them first") as info: + ArrowTableSource(raw, tag_columns=TAGS, tag_only_columns=True) + assert system_columns + assert all(repr(name) in str(info.value) for name in system_columns) + rebuilt = ArrowTableSource( + raw.drop(system_columns), tag_columns=TAGS, tag_only_columns=True + ) + assert rebuilt.as_table().equals(source.as_table()) + + +def test_database_refuses_reserved_columns_before_reading_rows() -> None: + class SchemaOnlyConnector(_Connector): + def iter_batches(self, query, params=None, batch_size=1000): + pytest.fail("a reserved database column must prevent reading rows") + + table = _table(pa.field("_foo", pa.string()), ["a", "b"]) + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + DBTableSource( + SchemaOnlyConnector(table), "rows", tag_columns=TAGS, source_id="rows" + ) + + +def test_source_accepts_underscores_after_the_first_character() -> None: + source = DictSource( + [{"foo_": "a", "a_b": 1, "tag_x": 2, "other": 3}], + tag_columns=["foo_", "a_b"], + tag_only_columns=True, + ) + assert source.keys() == (("foo_", "a_b"), ("tag_x", "other")) + + def _table(field: pa.Field[Any], values: list[Any]) -> pa.Table: """Two tags, two ordinary data columns and two additional columns.""" schema = pa.schema( @@ -234,7 +339,7 @@ def test_refuses_arrow_null_from_readers( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - column = "unused" if kind == "spiral" else "__unused" + column = "unused" table = _table(pa.field(column, pa.null()), [None, None]) with pytest.raises( InputValidationError, match=rf"{column!r}.*declare a supported nullable type" @@ -332,6 +437,34 @@ async def close(self) -> None: """There is no connection to close.""" +@pytest.mark.parametrize("declare", [True, False], ids=["schema", "batch"]) +@pytest.mark.parametrize("as_tag", [True, False], ids=["tag", "data"]) +def test_polling_refuses_reserved_schema_and_batch_columns( + declare: bool, as_tag: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + table = _table(pa.field("_foo", pa.string()), ["a", "b"]) + table = table.append_column("_source_x", pa.array(["p", "q"])) + batch = pl.from_arrow(table) + assert isinstance(batch, pl.DataFrame) + tags = (*TAGS, "_foo") if as_tag else TAGS + if declare: + + async def unexpected_fetch(*args: Any, **kwargs: Any) -> None: + pytest.fail("a reserved declared column must prevent polling") + + monkeypatch.setattr(_Poll, "fetch", unexpected_fetch) + with pytest.raises(InputValidationError, match="drop them first") as info: + source = PollingSource( + _Poll(table.schema if declare else None, batch), + tags, + source_id="poll", + record_id_columns="k", + ) + source.check_for_new_data() + assert "'_foo'" in str(info.value) + assert "'_source_x'" in str(info.value) + + @pytest.mark.parametrize("values", [[], [[None], []]]) def test_polling_refuses_null_in_declaration_and_batch(values: list[Any]) -> None: table = _table(pa.field("__unused", pa.large_list(pa.null())), values) diff --git a/tests/test_core/sources/test_source_protocol_conformance.py b/tests/test_core/sources/test_source_protocol_conformance.py index 509b67a06..ceb8f4e37 100644 --- a/tests/test_core/sources/test_source_protocol_conformance.py +++ b/tests/test_core/sources/test_source_protocol_conformance.py @@ -16,6 +16,8 @@ import pyarrow as pa import pytest + +from orcapod.errors import InputValidationError import polars as pl from orcapod.core.sources import ( @@ -460,16 +462,14 @@ def test_df_source_missing_tag_column_raises(self): with pytest.raises(ValueError, match="not found"): DataFrameSource(data=df, tag_columns="nonexistent", tag_only_columns=True) - def test_arrow_source_strips_system_columns_from_input(self): - """System columns in the input table are silently dropped.""" + def test_arrow_source_refuses_system_columns_in_input(self): table = pa.table( { "x": pa.array([1, 2], type=pa.int64()), "_tag_something": pa.array(["a", "b"], type=pa.large_string()), } ) - src = ArrowTableSource(table=table, infer_nullable=True) - # system columns should not appear in data keys - tag_keys, data_keys = src.keys() - assert "_tag_something" not in tag_keys - assert "_tag_something" not in data_keys + with pytest.raises( + InputValidationError, match="'_tag_something'.*drop them first" + ): + ArrowTableSource(table=table, infer_nullable=True) diff --git a/tests/test_core/sources/test_sources_comprehensive.py b/tests/test_core/sources/test_sources_comprehensive.py index ab21a4661..3f2b64f06 100644 --- a/tests/test_core/sources/test_sources_comprehensive.py +++ b/tests/test_core/sources/test_sources_comprehensive.py @@ -29,6 +29,8 @@ import polars as pl import pytest +from orcapod.errors import InputValidationError + from orcapod.core.sources import ( ArrowTableSource, CSVSource, @@ -293,18 +295,17 @@ def test_string_tag_columns_accepted(self): assert "id" in tag_keys assert "value" in data_keys - def test_system_columns_stripped_from_polars_input(self): - """Polars DataFrames with system-prefix columns have those columns dropped.""" + def test_system_columns_refused_in_polars_input(self): df = pl.DataFrame( { "x": [1, 2], "_tag_something": ["a", "b"], } ) - src = DataFrameSource(data=df) - tag_keys, data_keys = src.keys() - assert "_tag_something" not in tag_keys - assert "_tag_something" not in data_keys + with pytest.raises( + InputValidationError, match="'_tag_something'.*drop them first" + ): + DataFrameSource(data=df) def test_source_id_in_provenance_tokens(self): df = pl.DataFrame({"id": [1, 2, 3], "value": ["a", "b", "c"]}) diff --git a/tests/test_core/sources/test_stream_builder.py b/tests/test_core/sources/test_stream_builder.py index ce96a7fe0..e1c590189 100644 --- a/tests/test_core/sources/test_stream_builder.py +++ b/tests/test_core/sources/test_stream_builder.py @@ -9,7 +9,7 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder, SourceStreamResult from orcapod.core.sources.arrow_table_source import ArrowTableSource -from orcapod.errors import RowIdentifierError +from orcapod.errors import InputValidationError, RowIdentifierError class TestSourceStreamBuilder: @@ -96,7 +96,7 @@ def test_build_with_record_id_column(self, builder): ) assert result.stream.as_table().num_rows == 2 - def test_build_drops_system_columns_from_input(self, builder): + def test_build_refuses_system_columns_in_input(self, builder): table = pa.table( { "id": pa.array([1]), @@ -104,9 +104,10 @@ def test_build_drops_system_columns_from_input(self, builder): "__system_col": pa.array(["sys"]), } ) - result = builder.build(table, tag_columns=["id"], kind_part="arrow_table_v1") - tag_schema, data_schema = result.stream.output_schema() - assert "__system_col" not in data_schema + with pytest.raises( + InputValidationError, match="'__system_col'.*drop them first" + ): + builder.build(table, tag_columns=["id"], kind_part="arrow_table_v1") class TestSourceStreamBuilderRespectsSchema: diff --git a/tests/test_databases/test_delta_merge_reserved_names.py b/tests/test_databases/test_delta_merge_reserved_names.py index f39b4f42b..14e4f3171 100644 --- a/tests/test_databases/test_delta_merge_reserved_names.py +++ b/tests/test_databases/test_delta_merge_reserved_names.py @@ -118,13 +118,13 @@ def test_a_stored_table_holding_a_reserved_name_takes_no_append( db.flush() # a no-op -@function_pod(output_keys=["__delta_rs_source"]) -def _reserved(v: int) -> int: +@function_pod(output_keys=["v`output"]) +def _unstorable(v: int) -> int: return v @pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) -def test_a_job_writing_a_reserved_name_stops_at_its_first_write( +def test_a_job_writing_an_unstorable_name_stops_at_its_first_write( tmp_path: Path, use_async: bool ) -> None: source = ArrowTableSource( @@ -142,11 +142,11 @@ def test_a_job_writing_a_reserved_name_stops_at_its_first_write( source_id="s", record_id_columns=["k"], ) - with pytest.raises(UnstorableColumnError, match="MERGE reserves"): + with pytest.raises(UnstorableColumnError, match="backtick"): database = DeltaTableDatabase(tmp_path) job = PipelineJob(name="itl1377", database=database) with job: - _reserved.pod(source, label="fn") + _unstorable.pod(source, label="fn") if use_async: asyncio.run(job.run_async()) else: diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index 72ae41561..5a929e84a 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -27,7 +27,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import ProvenanceInconsistencyError +from orcapod.errors import InputValidationError, ProvenanceInconsistencyError from orcapod.operators import ( Batch, DropTagColumns, @@ -1005,18 +1005,28 @@ def test_an_inner_list_of_nested_folds_traces_its_members() -> None: ] -@function_pod(output_keys="_total") -def underscored(x: int, y: int) -> int: +@function_pod(output_keys="total") +def total(x: int, y: int) -> int: return x + y -def test_an_underscore_data_column_of_an_empty_run_is_a_data_column() -> None: +@pytest.mark.parametrize("name", ["_total", "_content_hash", "__delta_rs_source"]) +def test_a_function_refuses_a_reserved_output_name_at_definition(name: str) -> None: + with pytest.raises(InputValidationError, match=repr(name)): + function_pod(output_keys=name)(total_for_reserved_output) + + +def total_for_reserved_output(x: int, y: int) -> int: + return x + y + + +def test_a_data_column_of_an_empty_run_is_a_data_column() -> None: source = table_source(rows_kgxy(("a", "1", 1, 2)), TWO_BY_TWO, ["k", "g"], "src") job = PipelineJob(name="under", database=InMemoryArrowDatabase()) with job: - underscored.pod(Filter({"x": 999})(source), label="sums") + total.pod(Filter({"x": 999})(source), label="sums") job.run() - empty = job.nodes["sums"].trace({"k": "a", "g": "1"}, "_total") + empty = job.nodes["sums"].trace({"k": "a", "g": "1"}, "total") assert (empty.status, empty.matched) == ("no_match", 0) with pytest.raises(ValueError, match="not a data column"): job.nodes["sums"].trace({"k": "a", "g": "1"}, "k") From afb14bc87efdac287ad96a2dd170bafe19e1144b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:54:19 -0800 Subject: [PATCH 02/21] test(semijoin): use a legal column name in the warning test --- tests/test_core/operators/test_semijoin_tag_keys.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_core/operators/test_semijoin_tag_keys.py b/tests/test_core/operators/test_semijoin_tag_keys.py index 7c29c688c..3a015e64e 100644 --- a/tests/test_core/operators/test_semijoin_tag_keys.py +++ b/tests/test_core/operators/test_semijoin_tag_keys.py @@ -263,7 +263,7 @@ def test_filter_without_the_warning() -> None: """Reduce the right input to its tags plus one renamed data column: no warning.""" source = left_source() subset = PolarsFilter(constraints={"id": 2})(left_source()) - keys_only = subset.select_data_columns(["x"]).map_data({"x": "_x"}) + keys_only = subset.select_data_columns(["x"]).map_data({"x": "right_x"}) with warnings.catch_warnings(): warnings.simplefilter("error", SemiJoinIgnoredColumnWarning) result = SemiJoin()(source, keys_only) From a54db1ee1b612cca5d4663f5d3f07ee86a2097ba Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:17:57 -0800 Subject: [PATCH 03/21] fix(sources): validate raw fields before source inference and projection --- changelog.d/ITL-1165.md | 5 +- src/orcapod/core/function_pod.py | 4 +- src/orcapod/core/sources/csv_source.py | 4 + src/orcapod/core/sources/data_frame_source.py | 68 +++++++- src/orcapod/core/sources/dict_source.py | 6 + src/orcapod/core/sources/list_source.py | 9 ++ src/orcapod/core/sources/polling_source.py | 5 +- src/orcapod/core/sources/stream_builder.py | 16 +- .../sources/test_source_arrow_validation.py | 152 +++++++++++++++++- tests/test_pipeline/test_provenance_review.py | 42 ++++- 10 files changed, 297 insertions(+), 14 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index 34c8d50d2..fab8daf38 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -6,8 +6,9 @@ first. The `system_tag_columns` option retains its existing validation. - Operator output and rename targets and function pod output keys must use names that do not begin with `_`. A saved configuration with a reserved function pod output key - is refused when the pod is rebuilt. Rename the output key and update its downstream - references in the pipeline before saving a new configuration. + is refused when the pod is rebuilt, including when the original callable is + unavailable and loading would normally use a proxy. Rename the output key and update + its downstream references in the pipeline before saving a new configuration. ### Fixed diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index d2ff1fb3e..742b80614 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -119,10 +119,12 @@ def __init__( f"(schema keys: {list(data_function.input_data_schema.keys())})" ) self._ctx_arg_name: str | None = ctx_arg_name + output_schema = data_function.output_data_schema + schema_utils.require_names_not_system(output_schema.keys()) # Register types for schema validation, excluding ctx (not a data column). self.data_context.type_converter.ensure_types_registered_for_schemas( self.input_data_schema, - data_function.output_data_schema, + output_schema, ) def computed_label(self) -> str | None: diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index e6d087c68..3fcb5a02b 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -19,6 +19,7 @@ SourceStreamBuilder, SourceStreamResult, require_custom_system_tags, + require_source_column_names, require_supported_nullable_types, ) from orcapod.utils import arrow_utils @@ -198,6 +199,7 @@ def as_text(columns: list[str], include: list[str]) -> pa_csv.ConvertOptions: table = parse(as_text(text_like, [])) # text-like columns only: one parse else: table = parse(pa_csv.ConvertOptions(column_types=reader_types)) + require_source_column_names(table.column_names, system_tag_columns) if table.column_names != schema.names: raise ValueError( f"the file's columns {table.column_names} are not the schema's fields " @@ -349,8 +351,10 @@ def _read_table(self) -> pa.Table: if self._schema is None: table: pa.Table = pa_csv.read_csv(self._access_path) require_supported_nullable_types(table.schema) + require_source_column_names(table.column_names, self._system_tag_columns) return table.cast(arrow_utils.infer_schema_nullable(table)) require_supported_nullable_types(self._schema) + require_source_column_names(self._schema.names, 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 1c17b5ab7..03426b63b 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -1,7 +1,8 @@ from __future__ import annotations import logging -from collections.abc import Collection +from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence, Sized +from itertools import chain from typing import TYPE_CHECKING, Any, ClassVar import polars as pl @@ -14,8 +15,10 @@ normalize_record_id_columns, require_custom_system_tags, require_source_column_names, + require_source_row_names, require_supported_nullable_types, ) +from orcapod.errors import InputValidationError from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -25,6 +28,64 @@ logger = logging.getLogger(__name__) +def _checked_frame_rows( + rows: Iterator[Any], system_tag_columns: Collection[str] +) -> Iterator[Any]: + """Inspect mapping rows at their original pace and stop on a reserved name.""" + try: + first = next(rows) + except StopIteration: + return + if not isinstance(first, Mapping): + yield from chain((first,), rows) + return + for row in chain((first,), rows): + if isinstance(row, Mapping): + try: + require_source_column_names(row.keys(), system_tag_columns) + except InputValidationError: + # Gather the remaining names for the diagnostic before inference + # can drop the offending row's fields. + try: + require_source_row_names( + ( + item + for item in chain((row,), rows) + if isinstance(item, Mapping) + ), + system_tag_columns, + ) + except InputValidationError as error: + raise error from None + yield row + + +def source_dataframe( + data: FrameInitTypes, system_tag_columns: Collection[str] = () +) -> pl.DataFrame: + """Check mapping names before Polars infers a schema from a sample of rows. + + Args: + data: Raw data accepted by the Polars DataFrame constructor. + system_tag_columns: Columns nominated as custom system tags. + + Returns: + The original input converted with Polars' normal inference. + """ + if isinstance(data, Mapping): + require_source_column_names(data.keys(), system_tag_columns) + elif isinstance(data, Sequence): + if data and isinstance(data[0], Mapping): + require_source_row_names(data, system_tag_columns) + elif ( + isinstance(data, Iterable) + and not isinstance(data, Sized) + and not hasattr(data, "__arrow_c_stream__") + ): + data = _checked_frame_rows(iter(data), system_tag_columns) + return pl.DataFrame(data) + + class DataFrameSource(RootSource): """A source backed by a Polars DataFrame (or any Polars-compatible data). @@ -66,7 +127,8 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) - df = pl.DataFrame(data) + df = source_dataframe(data, system_tag_columns) + require_source_column_names(df.columns, system_tag_columns) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] @@ -84,7 +146,6 @@ def __init__( require_supported_nullable_types( polars_data_utils.get_system_columns(df).to_arrow().schema ) - require_source_column_names(df.columns, system_tag_columns) df = polars_data_utils.drop_system_columns(df) missing = set(tag_columns) - set(df.columns) @@ -94,6 +155,7 @@ def __init__( arrow_table = df.to_arrow() if schema is not None: require_supported_nullable_types(schema) + require_source_column_names(schema.names, system_tag_columns) require_custom_system_tags(arrow_table, system_tag_columns, schema=schema) arrow_table = arrow_table.cast(schema) else: diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index d45d68a92..23b9025c2 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -10,6 +10,8 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + require_source_column_names, + require_source_row_names, require_supported_nullable_types, ) from orcapod.types import DataValue, SchemaLike @@ -64,13 +66,17 @@ def __init__( # Accept either a Python SchemaLike (Mapping[str, type]) or a # pa.Schema directly via data_schema; route to the converter accordingly. rows = [dict(row) for row in data] + require_source_row_names(rows, system_tag_columns) if isinstance(data_schema, pa.Schema): require_supported_nullable_types(data_schema) + require_source_column_names(data_schema.names, system_tag_columns) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, arrow_schema=data_schema, ) else: + if data_schema is not None: + require_source_column_names(data_schema.keys(), system_tag_columns) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, python_schema=data_schema, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f18da3433..74e3dffd2 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -7,6 +7,8 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + require_source_column_names, + require_source_row_names, ) from orcapod.protocols.core_protocols import TagProtocol from orcapod.types import SchemaLike @@ -79,6 +81,12 @@ def __init__( """ super().__init__(source_id=source_id, **kwargs) + declared_names = {name} + if expected_tag_keys is not None: + declared_names.update(expected_tag_keys) + if data_schema is not None: + declared_names.update(data_schema.keys()) + require_source_column_names(declared_names) self.name = name self._elements = list(data) @@ -101,6 +109,7 @@ def __init__( row = dict(tag_fields) row[name] = element rows.append(row) + require_source_row_names(rows) tag_columns = ( list(self._expected_tag_keys) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b0aeee5c..4e24393ee 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -23,6 +23,7 @@ from typing_extensions import override from orcapod.core.sources.base import RootSource +from orcapod.core.sources.data_frame_source import source_dataframe 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 ( @@ -352,6 +353,7 @@ def __init__( ) ) if unified_schema is not None: + require_source_column_names(unified_schema.keys()) tag_cols_set = set(self._tag_columns) missing = tag_cols_set - set(unified_schema.keys()) if missing: @@ -371,7 +373,6 @@ def __init__( unified_schema, self.data_context.type_converter ) require_supported_nullable_types(self._declared_arrow) - require_source_column_names(self._declared_arrow.names) # ------------------------------------------------------------------------- # Schema helpers — fetch-free schema computation from declared schemas @@ -877,7 +878,7 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - df = pl.DataFrame(data) + df = source_dataframe(data) if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 615d44932..1fef611a2 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, Iterable, Mapping, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -84,6 +84,20 @@ def require_source_column_names( ) from exc +def require_source_row_names( + rows: Iterable[Mapping[str, object]], system_tag_columns: Collection[str] = () +) -> None: + """Validate all row keys before an input schema can infer or project fields. + + Args: + rows: Raw row mappings. + system_tag_columns: Columns nominated as custom system tags. + """ + require_source_column_names( + {name for row in rows for name in row}, system_tag_columns + ) + + def require_custom_system_tags( table: pa.Table, names: Collection[str], diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 248c8efab..34c6e4d39 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -2,9 +2,11 @@ from __future__ import annotations +import asyncio +import contextlib import sqlite3 from re import escape -from collections.abc import Collection +from collections.abc import Collection, Iterator from pathlib import Path from typing import Any, TypedDict @@ -187,6 +189,90 @@ def test_raw_sources_refuse_all_reserved_columns( assert "'_content_hash'" in str(info.value) +@pytest.mark.parametrize("arrow_schema", [False, True], ids=["python", "arrow"]) +def test_dict_source_refuses_reserved_fields_omitted_from_schema( + arrow_schema: bool, +) -> None: + schema = ( + pa.schema( + [ + ("g", pa.string()), + ("k", pa.int64()), + ("x", pa.int64()), + ("y", pa.int64()), + ] + ) + if arrow_schema + else {"g": str, "k": int, "x": int, "y": int} + ) + rows = [ + {"g": "a", "k": 1, "x": 2, "y": 3, "_foo": 4}, + {"g": "b", "k": 2, "x": 3, "y": 4, "_source_x": 5}, + ] + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + DictSource(rows, tag_columns=TAGS, tag_only_columns=True, data_schema=schema) + + +def test_csv_refuses_reserved_declared_columns_before_parsing_values( + tmp_path: Path, +) -> None: + path = tmp_path / "rows.csv" + path.write_text("g,k,x,y,_foo,_source_x\na,1,2,3,invalid,token\n") + schema = pa.schema( + [ + ("g", pa.string()), + ("k", pa.int64()), + ("x", pa.int64()), + ("y", pa.int64()), + ("_foo", pa.int64()), + ("_source_x", pa.string()), + ] + ) + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + CSVSource(str(path), tag_columns=TAGS, tag_only_columns=True, schema=schema) + + +def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: + rows = [{"g": 0, "k": i, "x": i + 1, "y": i + 2} for i in range(1002)] + names = ("_foo", "_source_x") + if reverse: + names = names[::-1] + rows[-2][names[0]] = 3 + rows[-1][names[1]] = 4 + return rows + + +@pytest.mark.parametrize("iterable", [list, iter], ids=["sequence", "iterator"]) +def test_dataframe_source_checks_fields_beyond_polars_inference(iterable) -> None: + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + DataFrameSource( + iterable(_late_reserved_rows(False)), + tag_columns=TAGS, + tag_only_columns=True, + ) + + +def test_dataframe_source_preserves_inference_for_single_pass_rows() -> None: + def rows() -> Iterator[dict[str, int]]: + row = {"g": 0, "k": 0, "x": 1, "y": 2} + for i in range(1002): + row["k"] = i + yield row + + expected = DataFrameSource( + pl.DataFrame(rows()), tag_columns=TAGS, tag_only_columns=True + ) + source = DataFrameSource(rows(), tag_columns=TAGS, tag_only_columns=True) + assert source.as_table().equals(expected.as_table()) + assert source.source_id == expected.source_id + + @pytest.mark.parametrize( "name", [ @@ -205,6 +291,35 @@ def test_list_source_refuses_reserved_value_column(name: str) -> None: ListSource(name, [10, 20]) +@pytest.mark.parametrize("data", [[], [10, 20]], ids=["empty", "projected"]) +def test_list_source_refuses_reserved_value_name_even_without_arrow_field( + data: list[int], +) -> None: + schema = {"element_index": int} if data else None + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + ListSource("_foo", data, data_schema=schema) + + +def test_list_source_refuses_reserved_tags_omitted_from_schema() -> None: + def tags(value: int, index: int) -> dict[str, int]: + return ( + {"k": index, "g": value, "_foo": value} + if index + else {"k": index, "g": value, "_source_x": value} + ) + + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + ListSource( + "x", + [10, 20], + tag_function=tags, + expected_tag_keys=TAGS, + data_schema={"k": int, "g": int, "x": int}, + ) + + def test_list_source_refuses_reserved_tags() -> None: def tags(value: int, index: int) -> dict[str, int]: return {"k": index, "g": value, "_foo": value, "_content_hash": index} @@ -403,7 +518,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 | list[dict[str, int]] + ) -> None: self._schema = schema self._batch = batch @@ -425,18 +542,45 @@ 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 | list[dict[str, int]]]: """Return the prepared batch on the initial fetch.""" return Cursor(value=0), self._batch async def poll(self, cursor: Cursor[int] | None = None) -> bool: """There are no rows after the initial fetch.""" - return False + return cursor is None async def close(self) -> None: """There is no connection to close.""" +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["foo-first", "source-first"]) +@pytest.mark.parametrize("as_tag", [False, True], ids=["data", "tag"]) +def test_polling_checks_raw_fields_beyond_polars_inference( + use_async: bool, reverse: bool, as_tag: bool +) -> None: + tags = (*TAGS, "_foo") if as_tag else TAGS + source = PollingSource( + _Poll(None, _late_reserved_rows(reverse)), + tags, + source_id="poll", + record_id_columns="k", + ) + + async def read_first() -> None: + async with contextlib.aclosing(source.async_iter_data()) as rows: + await anext(rows) + + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + if use_async: + asyncio.run(read_first()) + else: + source.check_for_new_data() + + @pytest.mark.parametrize("declare", [True, False], ids=["schema", "batch"]) @pytest.mark.parametrize("as_tag", [True, False], ids=["tag", "data"]) def test_polling_refuses_reserved_schema_and_batch_columns( diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index 5a929e84a..b4a91f9a3 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -24,10 +24,12 @@ import pyarrow as pa import pytest -from orcapod import PipelineJob, function_pod +from orcapod import FunctionPod, PipelineJob, function_pod +from orcapod.core.data_function import PythonDataFunction from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import InputValidationError, ProvenanceInconsistencyError +from orcapod.types import Schema from orcapod.operators import ( Batch, DropTagColumns, @@ -1020,6 +1022,44 @@ def total_for_reserved_output(x: int, y: int) -> int: return x + y +def _pair_for_reserved_outputs(x: int, y: int) -> tuple[int, int]: + return x, y + + +@pytest.mark.parametrize( + "outputs", [("_foo", "_content_hash"), ("_content_hash", "_foo")] +) +def test_public_function_pod_validates_custom_declared_outputs( + outputs: tuple[str, str], +) -> None: + class CustomFunction(PythonDataFunction): + @property + def output_data_schema(self) -> Schema: + return Schema(dict.fromkeys(outputs, int)) + + custom = CustomFunction(_pair_for_reserved_outputs, output_keys=["left", "right"]) + with pytest.raises(InputValidationError, match="'_content_hash'.*'_foo'"): + FunctionPod(data_function=custom) + + +@pytest.mark.parametrize("missing_callable", [False, True], ids=["importable", "proxy"]) +def test_saved_function_pod_refuses_reserved_outputs(missing_callable: bool) -> None: + config = FunctionPod.from_fn( + _pair_for_reserved_outputs, ["left", "right"] + ).to_config() + function_config = config["data_function"]["config"] + function_config["output_keys"] = ["_foo", "_content_hash"] + output_schema = function_config["output_data_schema"] + function_config["output_data_schema"] = { + "_foo": output_schema["left"], + "_content_hash": output_schema["right"], + } + if missing_callable: + function_config["callable_name"] = "unavailable_function" + with pytest.raises(InputValidationError, match="'_content_hash'.*'_foo'"): + FunctionPod.from_config(config, fallback_to_proxy=missing_callable) + + def test_a_data_column_of_an_empty_run_is_a_data_column() -> None: source = table_source(rows_kgxy(("a", "1", 1, 2)), TWO_BY_TWO, ["k", "g"], "src") job = PipelineJob(name="under", database=InMemoryArrowDatabase()) From 151737fb0924fb56d6aacfa6a6200d2196b943f9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:21:28 -0800 Subject: [PATCH 04/21] test(pods): verify the custom function fixture implements the protocol --- tests/test_pipeline/test_provenance_review.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index b4a91f9a3..0642e897a 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -19,16 +19,18 @@ from __future__ import annotations from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest +from typing_extensions import override from orcapod import FunctionPod, PipelineJob, function_pod from orcapod.core.data_function import PythonDataFunction from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import InputValidationError, ProvenanceInconsistencyError +from orcapod.protocols.core_protocols import DataFunctionProtocol from orcapod.types import Schema from orcapod.operators import ( Batch, @@ -1034,12 +1036,17 @@ def test_public_function_pod_validates_custom_declared_outputs( ) -> None: class CustomFunction(PythonDataFunction): @property + @override def output_data_schema(self) -> Schema: return Schema(dict.fromkeys(outputs, int)) - custom = CustomFunction(_pair_for_reserved_outputs, output_keys=["left", "right"]) + custom = cast( + object, + CustomFunction(_pair_for_reserved_outputs, output_keys=["left", "right"]), + ) + assert isinstance(custom, DataFunctionProtocol) with pytest.raises(InputValidationError, match="'_content_hash'.*'_foo'"): - FunctionPod(data_function=custom) + _ = FunctionPod(data_function=custom) @pytest.mark.parametrize("missing_callable", [False, True], ids=["importable", "proxy"]) From 76f18641c81ce2474ad03e0a3fdc5cbbadc74ee1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:48:46 -0800 Subject: [PATCH 05/21] fix(sources): reject unsafe Python frame row layouts --- changelog.d/ITL-1165.md | 5 + src/orcapod/core/sources/data_frame_source.py | 173 ++++++++++++---- .../sources/test_source_arrow_validation.py | 190 +++++++++++++++++- 3 files changed, 328 insertions(+), 40 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index fab8daf38..c33be7bd4 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -9,6 +9,11 @@ is refused when the pod is rebuilt, including when the original callable is unavailable and loading would normally use a proxy. Rename the output key and update its downstream references in the pipeline before saving a new configuration. +- Python row inputs to `DataFrameSource` and `PollingSource` need the same field names + in every non-null row. Use mappings throughout, or use one dataclass or Pydantic + model class throughout. Mixed row classes could put values in the wrong column and + are now refused. For positional rows or Pydantic rows with extra fields, use explicit + mappings with the intended column names. ### Fixed diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 03426b63b..d011dd93d 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -2,11 +2,13 @@ import logging from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence, Sized -from itertools import chain -from typing import TYPE_CHECKING, Any, ClassVar +from dataclasses import fields, is_dataclass +from itertools import chain, repeat +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple import polars as pl import pyarrow as pa +from pydantic import BaseModel from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags @@ -15,7 +17,6 @@ normalize_record_id_columns, require_custom_system_tags, require_source_column_names, - require_source_row_names, require_supported_nullable_types, ) from orcapod.errors import InputValidationError @@ -28,67 +29,169 @@ logger = logging.getLogger(__name__) +class _FrameRow(NamedTuple): + """A row and its layout before Polars infers any columns.""" + + value: Any + names: tuple[str, ...] + row_type: type + extras: tuple[str, ...] = () + + +def _describe_frame_row(value: Any, index: int) -> _FrameRow | None: + """Read top-level field names while preserving typed row values.""" + if value is None: + return None + if isinstance(value, Mapping): + names = tuple(value) + if not all(isinstance(name, str) for name in names): + raise InputValidationError(f"Source row {index} needs string field names.") + return _FrameRow(value if isinstance(value, dict) else dict(value), names, dict) + if isinstance(value, BaseModel): + extras = tuple(value.model_extra or ()) + return _FrameRow( + value, (*type(value).model_fields, *extras), type(value), extras + ) + if is_dataclass(value) and not isinstance(value, type): + return _FrameRow( + value, tuple(field.name for field in fields(value)), type(value) + ) + raise InputValidationError( + f"Source row {index} ({type(value).__name__}) needs named fields. " + "Use a mapping, dataclass or Pydantic model." + ) + + def _checked_frame_rows( - rows: Iterator[Any], system_tag_columns: Collection[str] -) -> Iterator[Any]: - """Inspect mapping rows at their original pace and stop on a reserved name.""" - try: - first = next(rows) - except StopIteration: - return - if not isinstance(first, Mapping): - yield from chain((first,), rows) - return - for row in chain((first,), rows): - if isinstance(row, Mapping): + rows: Iterable[_FrameRow | None], system_tag_columns: Collection[str] +) -> Iterator[_FrameRow | None]: + """Check every named layout before yielding the row to Polars.""" + first: _FrameRow | None = None + expected: set[str] = set() + for index, row in enumerate(rows): + if row is not None: try: - require_source_column_names(row.keys(), system_tag_columns) - except InputValidationError: - # Gather the remaining names for the diagnostic before inference - # can drop the offending row's fields. - try: - require_source_row_names( - ( - item - for item in chain((row,), rows) - if isinstance(item, Mapping) - ), - system_tag_columns, - ) - except InputValidationError as error: - raise error from None + require_source_column_names(row.names, system_tag_columns) + except InputValidationError as exc: + raise InputValidationError(f"Source row {index}. {exc}") from exc + if row.extras: + raise InputValidationError( + f"Source row {index} has extra model fields {list(row.extras)!r}. " + "Declare these fields on the model or use a mapping." + ) + names = set(row.names) + if first is None: + first, expected = row, names + if names != expected: + raise InputValidationError( + f"Source row {index} has different field names. " + f"Missing {sorted(expected - names)!r}, extra {sorted(names - expected)!r}." + ) + if row.row_type is not first.row_type or ( + row.row_type is not dict and row.names != first.names + ): + raise InputValidationError( + f"Source row {index} has a different layout " + f"({row.row_type.__name__} fields {row.names!r}). " + f"Use the same row layout ({first.row_type.__name__} fields " + f"{first.names!r}) or use mappings throughout." + ) yield row +def _frame_from_checked_rows( + rows: Iterator[_FrameRow | None], *, materialized: bool +) -> pl.DataFrame: + """Keep Polars' typed conversion for a single verified layout.""" + leading_nulls = 0 + for first in rows: + if first is not None: + break + leading_nulls += 1 + else: + return pl.DataFrame([None] * leading_nulls) + + all_rows = chain(repeat(None, leading_nulls), (first,), rows) + if first.row_type is dict: + values = (row.value if row is not None else None for row in all_rows) + return pl.DataFrame(list(values) if materialized else values) + + null_positions: set[int] = set() + + def typed_values() -> Iterator[Any]: + for index, row in enumerate(all_rows): + if row is None: + null_positions.add(index) + else: + yield row.value + + typed = typed_values() + frame = pl.DataFrame(list(typed) if materialized else typed) + if tuple(frame.columns) != first.names: + raise InputValidationError( + f"Source row {leading_nulls} declares fields {first.names!r}, " + f"but Polars returned {frame.columns!r}. Use mappings for these rows." + ) + if null_positions: + indices = iter(range(frame.height)) + positions = [ + None if index in null_positions else next(indices) + for index in range(frame.height + len(null_positions)) + ] + frame = frame.select( + pl.all().gather(pl.Series(positions, dtype=pl.get_index_type())) + ) + return frame + + def source_dataframe( data: FrameInitTypes, system_tag_columns: Collection[str] = () ) -> pl.DataFrame: - """Check mapping names before Polars infers a schema from a sample of rows. + """Validate named row layouts before Polars can project or relabel fields. Args: data: Raw data accepted by the Polars DataFrame constructor. system_tag_columns: Columns nominated as custom system tags. Returns: - The original input converted with Polars' normal inference. + The validated input converted with Polars' normal inference. """ if isinstance(data, Mapping): require_source_column_names(data.keys(), system_tag_columns) + return pl.DataFrame(data) elif isinstance(data, Sequence): - if data and isinstance(data[0], Mapping): - require_source_row_names(data, system_tag_columns) + if all(isinstance(column, pl.Series) for column in data): + return pl.DataFrame(data) + rows = [_describe_frame_row(row, index) for index, row in enumerate(data)] + require_source_column_names( + {name for row in rows if row is not None for name in row.names}, + system_tag_columns, + ) + return _frame_from_checked_rows( + _checked_frame_rows(rows, system_tag_columns), materialized=True + ) elif ( isinstance(data, Iterable) and not isinstance(data, Sized) and not hasattr(data, "__arrow_c_stream__") ): - data = _checked_frame_rows(iter(data), system_tag_columns) + return _frame_from_checked_rows( + _checked_frame_rows( + (_describe_frame_row(row, index) for index, row in enumerate(data)), + system_tag_columns, + ), + materialized=False, + ) return pl.DataFrame(data) class DataFrameSource(RootSource): """A source backed by a Polars DataFrame (or any Polars-compatible data). + Python rows must be mappings with the same keys, or dataclass or Pydantic + rows of one class with the same declared fields. Declare Pydantic extras as + fields or put them in mappings. A ``None`` row keeps its position as a null row. + The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 34c6e4d39..b8cf597e6 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -7,6 +7,7 @@ import sqlite3 from re import escape from collections.abc import Collection, Iterator +from dataclasses import dataclass from pathlib import Path from typing import Any, TypedDict @@ -15,6 +16,7 @@ import pyarrow as pa import pyarrow.csv as pa_csv import pytest +from pydantic import BaseModel, ConfigDict from orcapod import PipelineJob from orcapod.contexts.stored import with_data_context @@ -248,9 +250,10 @@ def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: @pytest.mark.parametrize("iterable", [list, iter], ids=["sequence", "iterator"]) def test_dataframe_source_checks_fields_beyond_polars_inference(iterable) -> None: - with pytest.raises( - InputValidationError, match="'_foo'.*'_source_x'.*drop them first" - ): + message = "'_foo'.*drop them first" + if iterable is list: + message = "'_foo'.*'_source_x'.*drop them first" + with pytest.raises(InputValidationError, match=message): DataFrameSource( iterable(_late_reserved_rows(False)), tag_columns=TAGS, @@ -273,6 +276,163 @@ def rows() -> Iterator[dict[str, int]]: assert source.source_id == expected.source_id +def test_dataframe_source_stops_after_the_first_invalid_iterator_row() -> None: + def rows() -> Iterator[dict[str, int]]: + yield {"k": 1, "x": 2, "_foo": 3, "_source_x": 4} + pytest.fail("reserved fields must stop iteration") + + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + DataFrameSource(rows(), tag_columns=["k"]) + + +@dataclass +class _FrameRow: + k: int + x: int + + +@dataclass +class _ReservedFrameRow: + k: int + _foo: int + + +@dataclass +class _ExtendedFrameRow(_FrameRow): + _foo: int + + +@dataclass +class _RenamedFrameRow: + k: int + y: int + + +@dataclass +class _ReorderedFrameRow: + x: int + k: int + + +@dataclass +class _TypedFrameRow: + k: int + x: float + + +class _TypedFrameModel(BaseModel): + k: int + x: list[int] + + +class _FrameModel(BaseModel): + model_config = ConfigDict(extra="allow") + + k: int + x: int + + +FRAME_ROW_CASES = [ + pytest.param( + [None] + + [{"k": i, "x": i + 2} for i in range(101)] + + [{"k": 101, "x": 102, "_foo": 12345}], + "'_foo'.*drop them first", + id="leading-null", + ), + pytest.param( + [_FrameRow(i, i + 2) for i in range(101)] + [_ReservedFrameRow(101, 12345)], + "'_foo'.*drop them first", + id="dataclass-replacement", + ), + pytest.param( + [_FrameRow(i, i + 2) for i in range(101)] + + [_ExtendedFrameRow(101, 102, 12345)], + "'_foo'.*drop them first", + id="dataclass-extension", + ), + pytest.param( + [_FrameModel(k=i, x=i + 2) for i in range(101)] + + [_FrameModel.model_validate({"k": 101, "x": 102, "_foo": 12345})], + "'_foo'.*drop them first", + id="pydantic-extra", + ), + pytest.param( + [_FrameRow(i, i + 2) for i in range(101)] + [_RenamedFrameRow(101, 12345)], + r"row 101.*field names.*'x'.*'y'", + id="different-legal-fields", + ), + pytest.param( + [_FrameRow(1, 2), _ReorderedFrameRow(4, 3)], + r"row 1.*layout.*'k'.*'x'", + id="reordered-typed-fields", + ), + pytest.param( + [_FrameModel.model_validate({"k": 1, "x": 2, "extra": 3})], + r"row 0.*extra.*'extra'", + id="legal-model-extra", + ), + pytest.param( + [(1, 2), (3, 4)], + r"row 0.*named fields", + id="unnamed-rows", + ), +] + + +@pytest.mark.parametrize("rows, message", FRAME_ROW_CASES) +@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) +def test_dataframe_source_checks_named_row_shapes( + rows: list[Any], message: str, use_iterator: bool +) -> None: + with pytest.raises(InputValidationError, match=message): + DataFrameSource(iter(rows) if use_iterator else rows) + + +@pytest.mark.parametrize( + ("rows", "arrow_type"), + [ + ([_TypedFrameRow(1, 2)], pa.float64()), + ([_TypedFrameModel(k=1, x=[])], pa.large_list(pa.int64())), + ], + ids=["dataclass-float", "pydantic-empty-list"], +) +@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) +def test_homogeneous_typed_rows_keep_schema_and_identity( + rows: list[Any], arrow_type: pa.DataType, use_iterator: bool +) -> None: + expected = DataFrameSource(pl.DataFrame(rows), tag_columns=["k"]) + source = DataFrameSource(iter(rows) if use_iterator else rows, tag_columns=["k"]) + assert source.as_table().schema.field("x").type == arrow_type + assert source.as_table().equals(expected.as_table()) + assert source.source_id == expected.source_id + assert source.content_hash() == expected.content_hash() + assert source.pipeline_hash() == expected.pipeline_hash() + + +@pytest.mark.parametrize( + "rows", + [ + [None, {"k": 1, "x": 2}, None, {"x": 4, "k": 3}], + [None, _FrameRow(1, 2), None, _FrameRow(3, 4)], + ], + ids=["mapping", "dataclass"], +) +@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) +def test_frame_rows_keep_null_positions_and_match_mapping_fields_by_name( + rows: list[Any], use_iterator: bool +) -> None: + source = DataFrameSource(iter(rows) if use_iterator else rows, tag_columns=["k"]) + assert source.as_table().to_pylist() == [ + {"k": None, "x": None}, + {"k": 1, "x": 2}, + {"k": None, "x": None}, + {"k": 3, "x": 4}, + ] + + @pytest.mark.parametrize( "name", [ @@ -519,7 +679,7 @@ class _Poll: """Minimal impl for testing schema validation before the first fetch.""" def __init__( - self, schema: pa.Schema | None, batch: pl.DataFrame | list[dict[str, int]] + self, schema: pa.Schema | None, batch: pl.DataFrame | list[Any] ) -> None: self._schema = schema self._batch = batch @@ -542,7 +702,7 @@ def from_config(cls, config: dict[str, Any]) -> _Poll: async def fetch( self, cursor: Cursor[int] | None = None - ) -> tuple[Cursor[int], pl.DataFrame | list[dict[str, int]]]: + ) -> tuple[Cursor[int], pl.DataFrame | list[Any]]: """Return the prepared batch on the initial fetch.""" return Cursor(value=0), self._batch @@ -554,6 +714,26 @@ async def close(self) -> None: """There is no connection to close.""" +@pytest.mark.parametrize("rows, message", FRAME_ROW_CASES) +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_polling_checks_named_row_shapes( + rows: list[Any], message: str, use_async: bool +) -> None: + source = PollingSource( + _Poll(None, rows), ["k"], source_id="poll", record_id_columns="k" + ) + + async def read_first() -> None: + async with contextlib.aclosing(source.async_iter_data()) as records: + await anext(records, None) + + with pytest.raises(InputValidationError, match=message): + if use_async: + asyncio.run(read_first()) + else: + source.as_table() + + @pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize("reverse", [False, True], ids=["foo-first", "source-first"]) @pytest.mark.parametrize("as_tag", [False, True], ids=["data", "tag"]) From 79d90d15591354b2847f295d525ef9fc156b0f82 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 20:23:40 -0800 Subject: [PATCH 06/21] fix(sources): validate Pydantic row fields and raw CSV headers --- changelog.d/ITL-1165.md | 5 +- src/orcapod/core/sources/csv_source.py | 32 +++++- src/orcapod/core/sources/data_frame_source.py | 89 ++++++++++++++--- src/orcapod/utils/schema_utils.py | 9 +- .../sources/test_source_arrow_validation.py | 98 ++++++++++++++++++- 5 files changed, 210 insertions(+), 23 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index c33be7bd4..461c2fcca 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -12,8 +12,9 @@ - Python row inputs to `DataFrameSource` and `PollingSource` need the same field names in every non-null row. Use mappings throughout, or use one dataclass or Pydantic model class throughout. Mixed row classes could put values in the wrong column and - are now refused. For positional rows or Pydantic rows with extra fields, use explicit - mappings with the intended column names. + are now refused. For positional rows or Pydantic rows with computed fields, extra + attributes or custom serialization, use explicit mappings with the intended column + names. ### Fixed diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 3fcb5a02b..295636f9b 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -1,6 +1,8 @@ from __future__ import annotations +import csv import functools +import io import math import os import re @@ -30,6 +32,25 @@ case, with an optional sign and surrounding spaces.""" +def _require_csv_header_names( + stream: pa.NativeFile, system_tag_columns: Collection[str] +) -> None: + """Check the first nonempty CSV record before Arrow parses any values.""" + with io.TextIOWrapper( + stream, # pyright: ignore[reportArgumentType] # NativeFile implements the buffer methods TextIOWrapper uses. + encoding="utf-8-sig", + errors="surrogateescape", + newline="", + ) as text: + try: + names = next((row for row in csv.reader(text) if row), None) + except csv.Error: + # Let Arrow handle headers outside the text reader's limits. + return + if names is not None: + require_source_column_names(names, system_tag_columns) + + def _storage_type(declared: pa.DataType) -> pa.DataType: """Return a type's storage type: itself, or a logical type's storage.""" while isinstance(declared, pa.ExtensionType): @@ -159,6 +180,10 @@ def _read_declared( import pyarrow.compute as pc import pyarrow.csv as pa_csv + # Check the same snapshot the typed parser will receive. + with pa.input_stream(path) as stream: + data = stream.read() + _require_csv_header_names(pa.BufferReader(data), system_tag_columns) reader_types: dict[str, pa.DataType] = {} for field in schema: try: @@ -168,8 +193,6 @@ def _read_declared( raise text_like = [f.name for f in schema if _is_text_like(f.type)] # One snapshot of the file, and one set of read and parse options, for every parse. - with pa.input_stream(path) as stream: - data = stream.read() read_options = pa_csv.ReadOptions() parse_options = pa_csv.ParseOptions() # pyarrow's default null markers, which the reader applies to other columns. @@ -349,12 +372,15 @@ def _read_table(self) -> pa.Table: import pyarrow.csv as pa_csv if self._schema is None: + _require_csv_header_names( + pa.input_stream(self._access_path), self._system_tag_columns + ) table: pa.Table = pa_csv.read_csv(self._access_path) require_supported_nullable_types(table.schema) require_source_column_names(table.column_names, self._system_tag_columns) return table.cast(arrow_utils.infer_schema_nullable(table)) - require_supported_nullable_types(self._schema) require_source_column_names(self._schema.names, self._system_tag_columns) + require_supported_nullable_types(self._schema) 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 d011dd93d..0cad37ad4 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -21,7 +21,7 @@ ) from orcapod.errors import InputValidationError from orcapod.utils import arrow_utils, polars_data_utils -from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.utils.schema_utils import _normalize_column_list, reserved_system_names if TYPE_CHECKING: from polars._typing import FrameInitTypes @@ -35,7 +35,41 @@ class _FrameRow(NamedTuple): value: Any names: tuple[str, ...] row_type: type - extras: tuple[str, ...] = () + non_column_names: tuple[str, ...] = () + + @property + def exposed_names(self) -> tuple[str, ...]: + """Return declared and other field names exposed by the row.""" + return (*self.names, *self.non_column_names) + + +def _describe_model_row(value: BaseModel, index: int) -> _FrameRow: + """Read the model's field names without running its serialization code.""" + model = type(value) + declared = model.model_fields + computed = model.model_computed_fields + if not isinstance(computed, Mapping): + # Older Pydantic releases exposed this on the instance. + computed = value.model_computed_fields + exposed = ( + set(computed) + | {info.alias for info in computed.values() if info.alias is not None} + | set(value.model_extra or ()) + | set(value.__pydantic_extra__ or ()) + | value.model_fields_set + | vars(value).keys() + ) + if model.model_config.get("serialize_by_alias"): + exposed.update( + field.serialization_alias + for field in declared.values() + if field.serialization_alias is not None + ) + if not all(isinstance(name, str) for name in exposed): + raise InputValidationError(f"Source row {index} needs string field names.") + return _FrameRow( + value, tuple(declared), model, tuple(sorted(exposed - declared.keys())) + ) def _describe_frame_row(value: Any, index: int) -> _FrameRow | None: @@ -48,10 +82,7 @@ def _describe_frame_row(value: Any, index: int) -> _FrameRow | None: raise InputValidationError(f"Source row {index} needs string field names.") return _FrameRow(value if isinstance(value, dict) else dict(value), names, dict) if isinstance(value, BaseModel): - extras = tuple(value.model_extra or ()) - return _FrameRow( - value, (*type(value).model_fields, *extras), type(value), extras - ) + return _describe_model_row(value, index) if is_dataclass(value) and not isinstance(value, type): return _FrameRow( value, tuple(field.name for field in fields(value)), type(value) @@ -71,14 +102,25 @@ def _checked_frame_rows( for index, row in enumerate(rows): if row is not None: try: - require_source_column_names(row.names, system_tag_columns) + require_source_column_names(row.exposed_names, system_tag_columns) except InputValidationError as exc: raise InputValidationError(f"Source row {index}. {exc}") from exc - if row.extras: + if row.non_column_names: raise InputValidationError( - f"Source row {index} has extra model fields {list(row.extras)!r}. " - "Declare these fields on the model or use a mapping." + f"Source row {index} exposes extra or computed model fields " + f"{list(row.non_column_names)!r} outside its declared columns. " + "Use a mapping or a model without computed or extra fields." ) + if isinstance(row.value, BaseModel): + model = type(row.value) + if ( + model.model_dump is not BaseModel.model_dump + or model.__pydantic_decorators__.model_serializers + ): + raise InputValidationError( + f"Source row {index} has serialized field names that cannot be " + "verified from its declared model fields. Use a mapping." + ) names = set(row.names) if first is None: first, expected = row, names @@ -99,6 +141,23 @@ def _checked_frame_rows( yield row +def _require_materialized_row_names( + rows: Sequence[_FrameRow | None], system_tag_columns: Collection[str] +) -> None: + """Report all reserved names and the first row exposing one.""" + names = {name for row in rows if row is not None for name in row.exposed_names} + try: + require_source_column_names(names, system_tag_columns) + except InputValidationError as exc: + reserved = reserved_system_names(names) - set(system_tag_columns) + first = next( + index + for index, row in enumerate(rows) + if row is not None and not reserved.isdisjoint(row.exposed_names) + ) + raise InputValidationError(f"Source row {first}. {exc}") from exc + + def _frame_from_checked_rows( rows: Iterator[_FrameRow | None], *, materialized: bool ) -> pl.DataFrame: @@ -163,10 +222,7 @@ def source_dataframe( if all(isinstance(column, pl.Series) for column in data): return pl.DataFrame(data) rows = [_describe_frame_row(row, index) for index, row in enumerate(data)] - require_source_column_names( - {name for row in rows if row is not None for name in row.names}, - system_tag_columns, - ) + _require_materialized_row_names(rows, system_tag_columns) return _frame_from_checked_rows( _checked_frame_rows(rows, system_tag_columns), materialized=True ) @@ -189,8 +245,9 @@ class DataFrameSource(RootSource): """A source backed by a Polars DataFrame (or any Polars-compatible data). Python rows must be mappings with the same keys, or dataclass or Pydantic - rows of one class with the same declared fields. Declare Pydantic extras as - fields or put them in mappings. A ``None`` row keeps its position as a null row. + rows of one class with the same declared fields. Put extra or computed + Pydantic fields in mappings, and use mappings for models with custom + serialization. A ``None`` row keeps its position as a null row. The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index dff601535..63e7362b1 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -1036,6 +1036,13 @@ def schema_hash_rejected_columns_error( ) +def reserved_system_names(names: Iterable[str]) -> set[str]: + """Return the names in Orcapod's reserved column namespace.""" + from orcapod.system_constants import constants + + return {name for name in names if name.startswith(constants.DATAGRAM_PREFIX)} + + def require_names_not_system(names: Collection[str]) -> None: """Raise if any user column name begins with the reserved underscore. @@ -1049,7 +1056,7 @@ def require_names_not_system(names: Collection[str]) -> None: from orcapod.system_constants import constants prefix = constants.DATAGRAM_PREFIX - reserved = sorted({name for name in names if name.startswith(prefix)}) + reserved = sorted(reserved_system_names(names)) if reserved: columns = ", ".join(repr(name) for name in reserved) raise InputValidationError( diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index b8cf597e6..7759ac7bf 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -16,7 +16,13 @@ import pyarrow as pa import pyarrow.csv as pa_csv import pytest -from pydantic import BaseModel, ConfigDict +from pydantic import ( + BaseModel, + ConfigDict, + SerializerFunctionWrapHandler, + computed_field, + model_serializer, +) from orcapod import PipelineJob from orcapod.contexts.stored import with_data_context @@ -238,6 +244,21 @@ def test_csv_refuses_reserved_declared_columns_before_parsing_values( CSVSource(str(path), tag_columns=TAGS, tag_only_columns=True, schema=schema) +@pytest.mark.parametrize("declared", [True, False], ids=["declared", "inferred"]) +def test_csv_refuses_reserved_header_before_parsing_bad_rows( + tmp_path: Path, declared: bool +) -> None: + path = tmp_path / "rows.csv" + path.write_text( + '\ufeff\r\nk,x,"_foo","_source_x"\r\n1,invalid,token,source,extra\r\n' + ) + schema = pa.schema([("k", pa.int64()), ("x", pa.int64())]) if declared else None + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + CSVSource(str(path), tag_columns=["k"], schema=schema) + + def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: rows = [{"g": 0, "k": i, "x": i + 1, "y": i + 2} for i in range(1002)] names = ("_foo", "_source_x") @@ -334,6 +355,45 @@ class _FrameModel(BaseModel): x: int +class _PlainFrameModel(BaseModel): + k: int + x: int + + +class _ReservedComputedFrameModel(_PlainFrameModel): + @computed_field # type: ignore[prop-decorator] + @property + def _foo(self) -> int: + return 12345 + + +class _ComputedFrameModel(_PlainFrameModel): + @computed_field # type: ignore[prop-decorator] + @property + def total(self) -> int: + raise AssertionError( + "checking the row layout must not evaluate computed fields" + ) + + +class _SerializedFrameModel(BaseModel): + k: int + x: _PlainFrameModel + + @model_serializer(mode="wrap") + def _serialize(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: + fields = handler(self) + if self.k > 100: + fields["_foo"] = 12345 + return fields + + +def _model_with_explicit_attribute() -> _PlainFrameModel: + row = _PlainFrameModel(k=2, x=4) + object.__setattr__(row, "_raw", 12345) + return row + + FRAME_ROW_CASES = [ pytest.param( [None] @@ -359,6 +419,42 @@ class _FrameModel(BaseModel): "'_foo'.*drop them first", id="pydantic-extra", ), + pytest.param( + [_ReservedComputedFrameModel(k=1, x=2)], + r"row 0.*'_foo'.*drop them first", + id="pydantic-reserved-computed", + ), + pytest.param( + [ + _PlainFrameModel(k=1, x=2), + _PlainFrameModel(k=2, x=4).model_copy(update={"_foo": 3}), + ], + r"row 1.*'_foo'.*drop them first", + id="pydantic-reserved-undeclared", + ), + pytest.param( + [_PlainFrameModel(k=1, x=2), _model_with_explicit_attribute()], + r"row 1.*'_raw'.*drop them first", + id="pydantic-explicit-instance-attribute", + ), + pytest.param( + [_ComputedFrameModel(k=1, x=2)], + r"row 0.*'total'.*mapping", + id="pydantic-ordinary-computed", + ), + pytest.param( + [_PlainFrameModel(k=1, x=2).model_copy(update={"total": 3})], + r"row 0.*'total'.*mapping", + id="pydantic-ordinary-undeclared", + ), + pytest.param( + [ + _SerializedFrameModel(k=i, x=_PlainFrameModel(k=i, x=i + 2)) + for i in range(102) + ], + r"row 0.*serialized field names.*mapping", + id="pydantic-dynamic-serialization", + ), pytest.param( [_FrameRow(i, i + 2) for i in range(101)] + [_RenamedFrameRow(101, 12345)], r"row 101.*field names.*'x'.*'y'", From 4905e192ac72385913b75b7b11b99831f973a396 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 00:46:15 -0800 Subject: [PATCH 07/21] fix(validation): close reserved column review gaps --- changelog.d/ITL-1165.md | 3 +- docs/dev/design_issues/ITL-1165-RN1.md | 5 +- src/orcapod/core/data_function.py | 8 +- src/orcapod/core/function_pod.py | 16 +- src/orcapod/core/sources/csv_source.py | 49 +++- src/orcapod/core/sources/data_frame_source.py | 14 +- src/orcapod/core/sources/db_table_source.py | 5 +- .../core/sources/delta_table_source.py | 5 + .../function_pod/test_output_conformance.py | 107 ++++++++- .../sources/test_source_arrow_validation.py | 217 ++++++++++++++++-- 10 files changed, 385 insertions(+), 44 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index 461c2fcca..32deea824 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -14,7 +14,8 @@ model class throughout. Mixed row classes could put values in the wrong column and are now refused. For positional rows or Pydantic rows with computed fields, extra attributes or custom serialization, use explicit mappings with the intended column - names. + names. For sparse mappings, include missing keys with `None` where appropriate. + Pass named Polars Series as a list of columns to either source. ### Fixed diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index 4f874f8c3..c35a174e1 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -28,5 +28,6 @@ helper as the mappers. **Fix:** Reserve all leading-underscore column names for Orcapod. Raw source readers report the offending columns and how to remove or rename them. The same rule covers -new operator names and function pod output keys. Custom system-tag declarations retain -their existing validation. +new operator names and function pod output keys, including user data returned by custom +functions before caching or emission. Custom system-tag declarations retain their +existing validation. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index dba616607..98bf90d6f 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1605,7 +1605,8 @@ def call( Raises: InputValidationError: If ``data`` is of another data context than this function's; the wrapped function has not been called then, whatever - ``skip_cache_lookup`` and ``skip_cache_insert`` are. + ``skip_cache_lookup`` and ``skip_cache_insert`` are. Also raised if + the wrapped function returns a data column with a reserved name. """ # Checked before anything else: with ``skip_cache_lookup`` the lookup, which # checks it too, does not run, and the function must not be called. @@ -1621,6 +1622,7 @@ def call( return output_data output_data = self._data_function.call(data, logger=logger, **kwargs) if output_data is not None: + schema_utils.require_names_not_system(output_data.keys()) if not skip_cache_insert: var_dg, exec_dg = self._build_metadata_datagrams() self._cache.store( @@ -1648,7 +1650,8 @@ async def async_call( Raises: InputValidationError: If ``data`` is of another data context than this - function's; the wrapped function has not been called then. + function's; the wrapped function has not been called then. Also raised + if the wrapped function returns a data column with a reserved name. """ # Checked before anything else: with ``skip_cache_lookup`` the lookup, which # checks it too, does not run, and the function must not be called. @@ -1666,6 +1669,7 @@ async def async_call( data, logger=logger, **kwargs ) if output_data is not None: + schema_utils.require_names_not_system(output_data.keys()) if not skip_cache_insert: var_dg, exec_dg = self._build_metadata_datagrams() self._cache.store( diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 755abce6c..4d1d38a7d 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -360,13 +360,19 @@ def process_data( Returns: A ``(tag, output_data)`` tuple; ``output_data`` is ``None`` if the function filters the data out. + + Raises: + InputValidationError: If a returned data column uses a reserved name. """ extra: dict[str, Any] = {} if self._ctx_arg_name is not None: extra[self._ctx_arg_name] = self._build_invocation_context( tag, data, run_id=run_id ) - return tag, self.data_function.call(data, logger=logger, **extra) + output = self.data_function.call(data, logger=logger, **extra) + if output is not None: + schema_utils.require_names_not_system(output.keys()) + return tag, output async def async_process_data( self, @@ -391,13 +397,19 @@ async def async_process_data( Returns: A ``(tag, output_data)`` tuple; ``output_data`` is ``None`` if the function filters the data out. + + Raises: + InputValidationError: If a returned data column uses a reserved name. """ extra: dict[str, Any] = {} if self._ctx_arg_name is not None: extra[self._ctx_arg_name] = self._build_invocation_context( tag, data, run_id=run_id ) - return tag, await self.data_function.async_call(data, logger=logger, **extra) + output = await self.data_function.async_call(data, logger=logger, **extra) + if output is not None: + schema_utils.require_names_not_system(output.keys()) + return tag, output def add_post_run_hook(self, hook: PostRunHook) -> None: """Register a post-run hook on this pod. diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 295636f9b..cdff47ee0 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -1,6 +1,5 @@ from __future__ import annotations -import csv import functools import io import math @@ -31,6 +30,43 @@ """The texts pyarrow's CSV reader reads as an infinity: ``inf`` or ``infinity``, any case, with an optional sign and surrounding spaces.""" +_CSV_UNQUOTED = re.compile(r"[^,\r\n]*") +_CSV_QUOTED = re.compile(r'(?:[^"]++|"")*+') + + +def _csv_header_names(text: io.TextIOBase) -> list[str]: + """Read the first nonempty CSV record without a field size limit.""" + line = next((line for line in text if line not in ("\n", "\r", "\r\n")), "") + if not line: + return [] + + names: list[str] = [] + pos = 0 + while True: + quoted: list[str] = [] + if line[pos : pos + 1] == '"': + pos += 1 + while True: + field = _CSV_QUOTED.match(line, pos) + assert field is not None + quoted.append(field[0]) + pos = field.end() + if pos < len(line): + pos += 1 # Closing quote. Doubled quotes belong to the field. + break + line = text.readline() + if not line: + return names # Leave the unfinished field for Arrow to diagnose. + pos = 0 + + field = _CSV_UNQUOTED.match(line, pos) + assert field is not None + names.append("".join(quoted).replace('""', '"') + field[0]) + pos = field.end() + if line[pos : pos + 1] != ",": + return names + pos += 1 + def _require_csv_header_names( stream: pa.NativeFile, system_tag_columns: Collection[str] @@ -42,13 +78,8 @@ def _require_csv_header_names( errors="surrogateescape", newline="", ) as text: - try: - names = next((row for row in csv.reader(text) if row), None) - except csv.Error: - # Let Arrow handle headers outside the text reader's limits. - return - if names is not None: - require_source_column_names(names, system_tag_columns) + names = _csv_header_names(text) + require_source_column_names(names, system_tag_columns) def _storage_type(declared: pa.DataType) -> pa.DataType: @@ -376,8 +407,8 @@ def _read_table(self) -> pa.Table: pa.input_stream(self._access_path), self._system_tag_columns ) table: pa.Table = pa_csv.read_csv(self._access_path) - require_supported_nullable_types(table.schema) require_source_column_names(table.column_names, self._system_tag_columns) + require_supported_nullable_types(table.schema) return table.cast(arrow_utils.infer_schema_nullable(table)) require_source_column_names(self._schema.names, self._system_tag_columns) require_supported_nullable_types(self._schema) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 0cad37ad4..d3b7d5448 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -89,7 +89,8 @@ def _describe_frame_row(value: Any, index: int) -> _FrameRow | None: ) raise InputValidationError( f"Source row {index} ({type(value).__name__}) needs named fields. " - "Use a mapping, dataclass or Pydantic model." + "Use a mapping, dataclass or Pydantic model for rows. " + "Pass named Polars Series as a list of columns." ) @@ -127,7 +128,9 @@ def _checked_frame_rows( if names != expected: raise InputValidationError( f"Source row {index} has different field names. " - f"Missing {sorted(expected - names)!r}, extra {sorted(names - expected)!r}." + f"Missing {sorted(expected - names)!r}, extra {sorted(names - expected)!r}. " + "Use the same field names in every row. For mappings, add missing " + "fields with None where appropriate and remove unintended fields." ) if row.row_type is not first.row_type or ( row.row_type is not dict and row.names != first.names @@ -209,7 +212,7 @@ def source_dataframe( """Validate named row layouts before Polars can project or relabel fields. Args: - data: Raw data accepted by the Polars DataFrame constructor. + data: Tabular or column input, or Python rows with a consistent named layout. system_tag_columns: Columns nominated as custom system tags. Returns: @@ -242,12 +245,13 @@ def source_dataframe( class DataFrameSource(RootSource): - """A source backed by a Polars DataFrame (or any Polars-compatible data). + """A source backed by a Polars DataFrame or supported tabular or column input. Python rows must be mappings with the same keys, or dataclass or Pydantic rows of one class with the same declared fields. Put extra or computed Pydantic fields in mappings, and use mappings for models with custom - serialization. A ``None`` row keeps its position as a null row. + serialization. A ``None`` row keeps its position as a null row. Pass + named Polars Series as a list of columns. The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 5c19bd9a4..17166e1ee 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -229,7 +229,10 @@ def _read_table( require_source_column_names( [info.name for info in col_infos], self._system_tag_columns ) - batches = list(connector.iter_batches(self._query)) + batches: list[pa.RecordBatch] = [] + for batch in connector.iter_batches(self._query): + require_source_column_names(batch.schema.names, self._system_tag_columns) + batches.append(batch) if not batches: raise ValueError(f"Table {self._table_name!r} is empty.") table: pa.Table = pa.Table.from_batches(batches) diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..57ec6a939 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -15,6 +15,7 @@ from orcapod.core.sources.reload import same_rows from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + require_source_column_names, SourceStreamBuilder, SourceStreamResult, ) @@ -106,6 +107,10 @@ def __init__( def _read_table(self) -> "pa.Table": """Read the table at the Delta version ``self._delta_table`` is loaded at.""" + require_source_column_names( + [field.name for field in self._delta_table.schema().fields], + self._system_tag_columns, + ) # The Delta log stores field-level nullable flags; to_pyarrow_dataset() # preserves them exactly — no inference needed. return delta_to_pyarrow_dataset( diff --git a/tests/test_core/function_pod/test_output_conformance.py b/tests/test_core/function_pod/test_output_conformance.py index 97ec6d331..00b7612f7 100644 --- a/tests/test_core/function_pod/test_output_conformance.py +++ b/tests/test_core/function_pod/test_output_conformance.py @@ -35,14 +35,16 @@ import pytest from pydantic import BaseModel +from typing_extensions import override from orcapod import PipelineJob, errors, function_pod -from orcapod.core.data_function import PythonDataFunction +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction from orcapod.core.datagrams import Data from orcapod.core.function_pod import FunctionPod from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver +from orcapod.protocols.core_protocols import DataFunctionProtocol, DataProtocol from orcapod.sources import DictSource @@ -314,26 +316,123 @@ class _NamedOutputs(NamedTuple): ("first", "_second"), _TWO_TEXT, errors.OutputContainerTypeError, - id="multiple-outputs", + id="reserved-last", + ), + pytest.param( + ("_second", "first"), + _TWO_TEXT[::-1], + errors.OutputContainerTypeError, + id="reserved-first", ), ], ) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) def test_reserved_output_names_are_refused_before_return_validation( reserved_keys: str | tuple[str, ...], allowed_keys: str | tuple[str, ...], return_error: type[errors.OutputTypeError], + asynchronous: bool, ) -> None: - fn = _multi_output_function(tuple[str, str], {"first": "a", "second": "b"}) + fn = _multi_output_function( + tuple[str, str], {"first": "a", "second": "b"}, asynchronous=asynchronous + ) with pytest.raises(errors.InputValidationError, match="reserved"): _ = PythonDataFunction(fn, output_keys=reserved_keys) data_function = PythonDataFunction(fn, output_keys=allowed_keys) with pytest.raises(return_error, match="returned dict") as caught: - _ = data_function.call(Data({"x": 7, "y": "b"})) + data = Data({"x": 7, "y": "b"}) + if asynchronous: + _ = asyncio.run(data_function.async_call(data)) + else: + _ = data_function.call(data) assert type(caught.value) is return_error +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["original", "reversed"]) +@pytest.mark.parametrize("path", ["standalone", "job", "data-function-cache"]) +def test_public_function_pod_rejects_reserved_returned_data_keys( + asynchronous: bool, reverse: bool, path: str +) -> None: + """A custom function's row can contain keys its declared outputs did not.""" + items = [("out", 4), ("_tag_fake", 5), ("_content_hash", 6), ("_foo", 7)] + if reverse: + items.reverse() + + def declared(x: int, y: int) -> int: + return x + y + + class CustomFunction(PythonDataFunction): + @override + def call(self, data: DataProtocol, **kwargs: object) -> Data: + return Data( + dict(items), + meta_info={"__debug": "diagnostic"}, + source_info={"out": "token"}, + ) + + @override + async def async_call(self, data: DataProtocol, **kwargs: object) -> Data: + return self.call(data, **kwargs) + + source = DictSource( + [{"k": 1, "g": "a", "x": 2, "y": 3}, {"k": 2, "g": "b", "x": 4, "y": 5}], + tag_columns=["g", "k"] if reverse else ["k", "g"], + tag_only_columns=True, + ) + function = cast(object, CustomFunction(declared, output_keys=["out"])) + assert isinstance(function, DataFunctionProtocol) + cache = ( + CachedDataFunction(function, result_database=InMemoryArrowDatabase()) + if path == "data-function-cache" + else None + ) + pod = FunctionPod(cache if cache is not None else function) + message = "'_content_hash'.*'_foo'.*'_tag_fake'.*reserved" + if path == "job": + job = PipelineJob(name="custom_output", database=InMemoryArrowDatabase()) + with job: + _ = pod(source, label="node") + observer = _CrashRecorder() + orchestrator = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + with pytest.warns(errors.RowFailuresWarning, match=message): + _ = job.run(orchestrator=orchestrator, observer=observer) + assert len(observer.crashes) == 2 + for error in observer.crashes: + assert isinstance(error, errors.InputValidationError) + assert all(name in str(error) for name, _ in items if name.startswith("_")) + records = job.nodes["node"].get_all_records() + assert records is None or records.num_rows == 0 + else: + stream = pod(source) + + async def collect() -> list[DataProtocol]: + return [output async for _, output in stream.async_iter_data()] + + with pytest.raises(errors.InputValidationError, match=message): + if asynchronous: + _ = asyncio.run(collect()) + else: + _ = list(stream.iter_data()) + if cache is not None: + assert all( + cache.get_cached_output_for_data(data) is None + for _, data in source.iter_data() + ) + # Legal data, metadata and source information still pass through. + items[:] = [("out", 4)] + outputs = ( + asyncio.run(collect()) + if asynchronous + else [output for _, output in stream.iter_data()] + ) + assert [output.as_dict() for output in outputs] == [{"out": 4}, {"out": 4}] + + @pytest.mark.parametrize( ("annotation", "returned", "keys"), [ diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 7759ac7bf..c01db8d55 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -245,18 +245,60 @@ def test_csv_refuses_reserved_declared_columns_before_parsing_values( @pytest.mark.parametrize("declared", [True, False], ids=["declared", "inferred"]) +@pytest.mark.parametrize("header_kind", ["short", "long-quoted", "long-unquoted"]) +@pytest.mark.parametrize("refresh", [False, True], ids=["construction", "refresh"]) def test_csv_refuses_reserved_header_before_parsing_bad_rows( - tmp_path: Path, declared: bool + tmp_path: Path, declared: bool, header_kind: str, refresh: bool ) -> None: path = tmp_path / "rows.csv" + schema = pa.schema([("k", pa.int64()), ("x", pa.int64())]) if declared else None + + def build() -> CSVSource: + return CSVSource( + str(path), tag_columns=["k"], tag_only_columns=True, schema=schema + ) + + source = None + if refresh: + path.write_text("k,x\n1,2\n3,4\n") + source = build() + # Cross the csv module's default size limit with a quoted field and an escaped quote. + first = ( + '"' + "x" * 131073 + '\r\n,""name"' + if header_kind == "long-quoted" + else "x" * 131073 + if header_kind == "long-unquoted" + else "k" + ) path.write_text( - '\ufeff\r\nk,x,"_foo","_source_x"\r\n1,invalid,token,source,extra\r\n' + f'\ufeff\r\n{first},x,"_foo","_source_x"\r\n1,invalid,token,source,extra\r\n' ) - schema = pa.schema([("k", pa.int64()), ("x", pa.int64())]) if declared else None with pytest.raises( InputValidationError, match="'_foo'.*'_source_x'.*drop them first" ): - CSVSource(str(path), tag_columns=["k"], schema=schema) + if source is not None: + source.check_for_new_data() + else: + build() + + +def test_dataframe_source_guides_series_iterators_to_named_columns() -> None: + columns = [ + pl.Series(name, values) + for name, values in { + "k": [1, 2], + "g": ["a", "b"], + "x": [3, 4], + "y": [5, 6], + }.items() + ] + with pytest.raises(InputValidationError, match=r"Series.*list of columns"): + DataFrameSource(iter(columns), tag_columns=TAGS, tag_only_columns=True) + source = DataFrameSource(columns, tag_columns=TAGS, tag_only_columns=True) + assert source.as_table().to_pylist() == [ + {"k": 1, "g": "a", "x": 3, "y": 5}, + {"k": 2, "g": "b", "x": 4, "y": 6}, + ] def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: @@ -305,7 +347,7 @@ def rows() -> Iterator[dict[str, int]]: with pytest.raises( InputValidationError, match="'_foo'.*'_source_x'.*drop them first" ): - DataFrameSource(rows(), tag_columns=["k"]) + DataFrameSource(rows(), tag_columns=["k"], tag_only_columns=True) @dataclass @@ -340,12 +382,31 @@ class _ReorderedFrameRow: @dataclass class _TypedFrameRow: k: int + g: str x: float + y: int + + +@dataclass +class _ReorderedTypedFrameRow: + y: int + g: str + x: float + k: int class _TypedFrameModel(BaseModel): k: int + g: str + x: list[int] + y: int + + +class _ReorderedTypedFrameModel(BaseModel): + y: int + g: str x: list[int] + k: int class _FrameModel(BaseModel): @@ -457,9 +518,14 @@ def _model_with_explicit_attribute() -> _PlainFrameModel: ), pytest.param( [_FrameRow(i, i + 2) for i in range(101)] + [_RenamedFrameRow(101, 12345)], - r"row 101.*field names.*'x'.*'y'", + r"row 101.*field names.*'x'.*'y'.*same field names", id="different-legal-fields", ), + pytest.param( + [{"k": 1, "g": 2, "x": 3, "y": 4}, {"g": 5, "k": 6, "y": 7, "z": 8}], + r"row 1.*Missing \['x'\], extra \['z'\].*same field names.*None", + id="sparse-mapping", + ), pytest.param( [_FrameRow(1, 2), _ReorderedFrameRow(4, 3)], r"row 1.*layout.*'k'.*'x'", @@ -488,24 +554,51 @@ def test_dataframe_source_checks_named_row_shapes( @pytest.mark.parametrize( - ("rows", "arrow_type"), + ("row_type", "x_values", "arrow_type"), [ - ([_TypedFrameRow(1, 2)], pa.float64()), - ([_TypedFrameModel(k=1, x=[])], pa.large_list(pa.int64())), + (_TypedFrameRow, (2, 4.5), pa.float64()), + (_ReorderedTypedFrameRow, (2, 4.5), pa.float64()), + (_TypedFrameModel, ([], [4, 5]), pa.large_list(pa.int64())), + (_ReorderedTypedFrameModel, ([], [4, 5]), pa.large_list(pa.int64())), ], - ids=["dataclass-float", "pydantic-empty-list"], + ids=["dataclass", "dataclass-reordered", "pydantic", "pydantic-reordered"], ) @pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("tag_order", [TAGS, TAGS[::-1]], ids=["g-k", "k-g"]) def test_homogeneous_typed_rows_keep_schema_and_identity( - rows: list[Any], arrow_type: pa.DataType, use_iterator: bool + row_type: type, + x_values: tuple[Any, Any], + arrow_type: pa.DataType, + use_iterator: bool, + tag_order: tuple[str, ...], ) -> None: - expected = DataFrameSource(pl.DataFrame(rows), tag_columns=["k"]) - source = DataFrameSource(iter(rows) if use_iterator else rows, tag_columns=["k"]) + rows = [ + row_type(k=1, g="a", x=x_values[0], y=3), + row_type(k=2, g="b", x=x_values[1], y=5), + ] + frame = pl.DataFrame(rows) + expected = DataFrameSource(frame, tag_columns=tag_order, tag_only_columns=True) + canonical = DataFrameSource( + frame.select("k", "g", "x", "y"), tag_columns=TAGS, tag_only_columns=True + ) + source = DataFrameSource( + iter(rows) if use_iterator else rows, + tag_columns=tag_order, + tag_only_columns=True, + ) assert source.as_table().schema.field("x").type == arrow_type + assert source.as_table().schema == expected.as_table().schema assert source.as_table().equals(expected.as_table()) - assert source.source_id == expected.source_id - assert source.content_hash() == expected.content_hash() - assert source.pipeline_hash() == expected.pipeline_hash() + assert ( + source.as_table() + .select(["k", "g", "x", "y"]) + .equals(canonical.as_table().select(["k", "g", "x", "y"])) + ) + assert source.source_id == expected.source_id == canonical.source_id + assert source.content_hash() == expected.content_hash() == canonical.content_hash() + assert ( + source.pipeline_hash() == expected.pipeline_hash() == canonical.pipeline_hash() + ) @pytest.mark.parametrize( @@ -520,7 +613,9 @@ def test_homogeneous_typed_rows_keep_schema_and_identity( def test_frame_rows_keep_null_positions_and_match_mapping_fields_by_name( rows: list[Any], use_iterator: bool ) -> None: - source = DataFrameSource(iter(rows) if use_iterator else rows, tag_columns=["k"]) + source = DataFrameSource( + iter(rows) if use_iterator else rows, tag_columns=["k"], tag_only_columns=True + ) assert source.as_table().to_pylist() == [ {"k": None, "x": None}, {"k": 1, "x": 2}, @@ -615,9 +710,95 @@ def iter_batches(self, query, params=None, batch_size=1000): table = _table(pa.field("_foo", pa.string()), ["a", "b"]) with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): DBTableSource( - SchemaOnlyConnector(table), "rows", tag_columns=TAGS, source_id="rows" + SchemaOnlyConnector(table), + "rows", + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + + +@pytest.mark.parametrize("metadata", ["absent", "partial"]) +@pytest.mark.parametrize("refresh", [False, True], ids=["construction", "refresh"]) +def test_database_refuses_reserved_batch_names_with_incomplete_metadata( + metadata: str, refresh: bool +) -> None: + class Connector(_Connector): + def get_column_info(self, table_name: str) -> list[ColumnInfo]: + if metadata == "absent": + return [] + return [ + ColumnInfo(field.name, field.type, field.nullable) + for field in list(self.table.schema)[:2] + ] + + def iter_batches( + self, query: str, params: Any = None, batch_size: int = 1000 + ) -> Iterator[pa.RecordBatch]: + yield from self.table.to_batches(max_chunksize=1) + if "_foo" in self.table.column_names: + pytest.fail("a reserved name in a batch must prevent further fetches") + + reserved = _table(pa.field("_foo", pa.string()), ["a", "b"]).append_column( + "_source_x", pa.array(["c", "d"]) + ) + connector = Connector(reserved.drop(["_foo", "_source_x"]) if refresh else reserved) + + def build() -> DBTableSource: + return DBTableSource( + connector, "rows", tag_columns=TAGS, tag_only_columns=True, source_id="rows" ) + if refresh: + source = build() + old = source.as_table() + connector.table = reserved + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + source.check_for_new_data() + assert source.as_table().equals(old) + else: + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + build() + + +@pytest.mark.parametrize("refresh", [False, True], ids=["construction", "refresh"]) +def test_delta_refuses_reserved_names_before_scanning( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, refresh: bool +) -> None: + path = tmp_path / "delta" + reserved = _table(pa.field("_foo", pa.string()), ["a", "b"]).append_column( + "_source_x", pa.array(["c", "d"]) + ) + + def fail_scan(*args: Any, **kwargs: Any) -> None: + pytest.fail("the Delta log already declares the reserved columns") + + def build() -> DeltaTableSource: + return DeltaTableSource(path, tag_columns=TAGS, tag_only_columns=True) + + if refresh: + deltalake.write_deltalake(path, reserved.drop(["_foo", "_source_x"])) + source = build() + old = source.as_table() + deltalake.write_deltalake(path, reserved, mode="append", schema_mode="merge") + monkeypatch.setattr(deltalake.DeltaTable, "to_pyarrow_dataset", fail_scan) + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + source.check_for_new_data() + assert source.as_table().equals(old) + else: + deltalake.write_deltalake(path, reserved) + monkeypatch.setattr(deltalake.DeltaTable, "to_pyarrow_dataset", fail_scan) + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + build() + def test_source_accepts_underscores_after_the_first_character() -> None: source = DictSource( From 6ff1f799500534c8854ecf13be2cff5baa463273 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 01:57:20 -0800 Subject: [PATCH 08/21] fix(validation): refuse reserved keys on pod cache hits and close review gaps Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-1165.md | 3 + docs/dev/design_issues/ITL-1165-RN1.md | 4 +- src/orcapod/core/cached_function_pod.py | 16 ++-- .../core/sources/arrow_table_source.py | 8 +- src/orcapod/core/sources/data_frame_source.py | 25 ++++-- src/orcapod/core/sources/polling_source.py | 3 +- .../test_cached_function_pod_job.py | 79 ++++++++++++++++++- .../sources/test_source_arrow_validation.py | 53 ++++++++++++- 8 files changed, 169 insertions(+), 22 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index 32deea824..6bb041815 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -21,3 +21,6 @@ - `Pick` and `Index` reject reserved `out` names at construction, so their output columns stay visible in stream tables. +- Pod-level cache hits refuse reserved user output keys before returning the row. +- PollingSource reports reserved column names in Polars batches before converting + columns or validating their Arrow types. diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index c35a174e1..02d929ef9 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -29,5 +29,5 @@ helper as the mappers. **Fix:** Reserve all leading-underscore column names for Orcapod. Raw source readers report the offending columns and how to remove or rename them. The same rule covers new operator names and function pod output keys, including user data returned by custom -functions before caching or emission. Custom system-tag declarations retain their -existing validation. +functions before caching or emission and user keys read from a pod-level cache. +Custom system-tag declarations retain their existing validation. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index f2f116113..97115f952 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -33,6 +33,7 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol +from orcapod.utils.schema_utils import require_names_not_system if TYPE_CHECKING: import pyarrow as pa @@ -191,6 +192,11 @@ def lookup_cached_data(self, data: DataProtocol) -> DataProtocol | None: cached = self._cache.lookup(data, data_context_key=self.data_context_key) if cached is None: return None + return self._cache_hit_output(cached) + + def _cache_hit_output(self, cached: DataProtocol) -> DataProtocol: + """Validate a stored output before passing it to the caller.""" + require_names_not_system(cached.keys()) return cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) def process_data( @@ -220,10 +226,9 @@ def process_data( A ``(tag, output_data)`` tuple; output_data is ``None`` if the inner function filters the data out. """ - cached = self._cache.lookup(data, data_context_key=self.data_context_key) + cached = self.lookup_cached_data(data) if cached is not None: module_logger.info("Pod-level cache hit") - cached = cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) return tag, cached tag, output = self._function_pod.process_data( @@ -251,7 +256,7 @@ def process_data( module_logger.info( "A result for this input was stored meanwhile; using it" ) - output = stored.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) + output = self._cache_hit_output(stored) else: output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) return tag, output @@ -282,10 +287,9 @@ async def async_process_data( A ``(tag, output_data)`` tuple; output_data is ``None`` if the inner function filters the data out. """ - cached = self._cache.lookup(data, data_context_key=self.data_context_key) + cached = self.lookup_cached_data(data) if cached is not None: module_logger.info("Pod-level cache hit") - cached = cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) return tag, cached tag, output = await self._function_pod.async_process_data( @@ -313,7 +317,7 @@ async def async_process_data( module_logger.info( "A result for this input was stored meanwhile; using it" ) - output = stored.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) + output = self._cache_hit_output(stored) else: output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) return tag, output diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index c31370727..f342b545c 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -23,9 +23,11 @@ class ArrowTableSource(RootSource): """A source backed by an in-memory PyArrow Table. - Uses ``SourceStreamBuilder`` to strip system columns, add per-row - source-info provenance columns and a system tag column encoding the - schema hash, then wraps the result in an ``ArrowTableStream``. + ``SourceStreamBuilder`` refuses reserved column names beginning with ``_``. + Rename your own columns or drop system columns before building the source. + The builder adds per-row source-info provenance columns and a system tag + column encoding the schema hash, then wraps the result in an + ``ArrowTableStream``. Nullable handling ----------------- diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index d3b7d5448..418276acb 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -43,7 +43,7 @@ def exposed_names(self) -> tuple[str, ...]: return (*self.names, *self.non_column_names) -def _describe_model_row(value: BaseModel, index: int) -> _FrameRow: +def _describe_model_row(value: BaseModel) -> _FrameRow: """Read the model's field names without running its serialization code.""" model = type(value) declared = model.model_fields @@ -66,34 +66,43 @@ def _describe_model_row(value: BaseModel, index: int) -> _FrameRow: if field.serialization_alias is not None ) if not all(isinstance(name, str) for name in exposed): - raise InputValidationError(f"Source row {index} needs string field names.") + raise InputValidationError("needs string field names.") return _FrameRow( value, tuple(declared), model, tuple(sorted(exposed - declared.keys())) ) -def _describe_frame_row(value: Any, index: int) -> _FrameRow | None: +def _describe_frame_row(value: Any) -> _FrameRow | None: """Read top-level field names while preserving typed row values.""" if value is None: return None if isinstance(value, Mapping): names = tuple(value) if not all(isinstance(name, str) for name in names): - raise InputValidationError(f"Source row {index} needs string field names.") + raise InputValidationError("needs string field names.") return _FrameRow(value if isinstance(value, dict) else dict(value), names, dict) if isinstance(value, BaseModel): - return _describe_model_row(value, index) + return _describe_model_row(value) if is_dataclass(value) and not isinstance(value, type): return _FrameRow( value, tuple(field.name for field in fields(value)), type(value) ) raise InputValidationError( - f"Source row {index} ({type(value).__name__}) needs named fields. " + f"({type(value).__name__}) needs named fields. " "Use a mapping, dataclass or Pydantic model for rows. " "Pass named Polars Series as a list of columns." ) +def _describe_frame_rows(values: Iterable[Any]) -> Iterator[_FrameRow | None]: + """Attach the input row's index to an error from its descriptor.""" + for index, value in enumerate(values): + try: + yield _describe_frame_row(value) + except InputValidationError as exc: + raise InputValidationError(f"Source row {index} {exc}") from exc + + def _checked_frame_rows( rows: Iterable[_FrameRow | None], system_tag_columns: Collection[str] ) -> Iterator[_FrameRow | None]: @@ -224,7 +233,7 @@ def source_dataframe( elif isinstance(data, Sequence): if all(isinstance(column, pl.Series) for column in data): return pl.DataFrame(data) - rows = [_describe_frame_row(row, index) for index, row in enumerate(data)] + rows = list(_describe_frame_rows(data)) _require_materialized_row_names(rows, system_tag_columns) return _frame_from_checked_rows( _checked_frame_rows(rows, system_tag_columns), materialized=True @@ -236,7 +245,7 @@ def source_dataframe( ): return _frame_from_checked_rows( _checked_frame_rows( - (_describe_frame_row(row, index) for index, row in enumerate(data)), + _describe_frame_rows(data), system_tag_columns, ), materialized=False, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 4e24393ee..910fb9b32 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -895,6 +895,8 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: skipped so that a spurious all-non-nullable schema is never recorded. """ + require_source_column_names(df.columns) + # Handle Object-dtype columns (same pattern as DataFrameSource) object_columns = [c for c in df.columns if df[c].dtype == pl.Object] if object_columns: @@ -905,7 +907,6 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: arrow_table = df.to_arrow() require_supported_nullable_types(arrow_table.schema) - require_source_column_names(arrow_table.column_names) # Establish canonical schema on first call; apply it on every call. if self._canonical_arrow_schema is None: diff --git a/tests/test_core/function_pod/test_cached_function_pod_job.py b/tests/test_core/function_pod/test_cached_function_pod_job.py index 18cda53ab..afa72c6c6 100644 --- a/tests/test_core/function_pod/test_cached_function_pod_job.py +++ b/tests/test_core/function_pod/test_cached_function_pod_job.py @@ -10,6 +10,7 @@ from __future__ import annotations +import asyncio import json from collections.abc import Callable from pathlib import Path @@ -17,10 +18,12 @@ import pytest -from orcapod import PipelineJob +from orcapod import PipelineJob, errors from orcapod.core.cached_function_pod import CachedFunctionPod +from orcapod.core.datagrams import Data, Datagram from orcapod.core.function_pod import FunctionPod from orcapod.core.operators import Join +from orcapod.core.result_cache import ResultCache from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -182,6 +185,80 @@ def test_row_in_the_pod_cache_is_not_recomputed_by_a_job() -> None: assert counter.calls == [5] +@pytest.mark.parametrize( + "path", + [ + "lookup", + "stream-sync", + "stream-async", + "job-sync", + "job-async", + "late-hit-sync", + "late-hit-async", + ], +) +def test_pod_cache_refuses_reserved_output_keys( + path: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stored row written before output validation must fail on every hit path.""" + counter = Counter() + pod = counter.pod() + cache_db = InMemoryArrowDatabase() + cached = CachedFunctionPod(pod, result_database=cache_db) + source = make_source() + cache = ResultCache( + cache_db, pod.uri, pod.data_function.declaration.revision_component + ) + inputs = [data for _, data in source.iter_data()] + for data in inputs: + cache.store( + data, + Data({"total": 5, "_foo": 6, "_tag_fake": 7}), + Datagram({}), + Datagram({}), + data_context_key=pod.data_context_key, + ) + match = "'_foo'.*'_tag_fake'.*reserved" + if path == "lookup": + with pytest.raises(errors.InputValidationError, match=match): + _ = cached.lookup_cached_data(inputs[0]) + elif path.startswith("job-"): + job = PipelineJob(name="reject_reserved", database=InMemoryArrowDatabase()) + with job: + _ = cached(source, label="add") + with pytest.warns(errors.RowFailuresWarning, match=match): + _ = job.run(orchestrator=ORCHESTRATORS[path.removeprefix("job-")]()) + records = job.nodes["add"].get_all_records() + assert records is None or records.num_rows == 0 + else: + if path.startswith("late-hit-"): + # Make the first lookup miss. The conditional write will find the row. + lookup = cache_db.get_records_with_column_value + miss = True + + def miss_first_lookup(*args: Any, **kwargs: Any): + nonlocal miss + if miss: + miss = False + return None + return lookup(*args, **kwargs) + + monkeypatch.setattr( + cache_db, "get_records_with_column_value", miss_first_lookup + ) + stream = cached(source) + + async def consume() -> None: + _ = [row async for row in stream.async_iter_data()] + + with pytest.raises(errors.InputValidationError, match=match): + if path.endswith("-async"): + asyncio.run(consume()) + else: + _ = list(stream.iter_data()) + assert counter.calls == ([2] if path.startswith("late-hit-") else []) + + def test_inputs_are_joined_once() -> None: counter = Counter() cached_pod = CachedFunctionPod( diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index c01db8d55..73e4c8f76 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -301,6 +301,22 @@ def test_dataframe_source_guides_series_iterators_to_named_columns() -> None: ] +@pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) +def test_dataframe_source_adds_row_context_to_field_name_error( + as_iterator: bool, +) -> None: + rows: list[Any] = [{"k": 1, "g": "a", "x": 3, "y": 5}, {1: 2}] + with pytest.raises( + InputValidationError, match=r"Source row 1.*needs string field names" + ) as info: + _ = DataFrameSource( + iter(rows) if as_iterator else rows, tag_columns=TAGS, tag_only_columns=True + ) + cause = info.value.__cause__ + assert isinstance(cause, InputValidationError) + assert str(cause) == "needs string field names." + + def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: rows = [{"g": 0, "k": i, "x": i + 1, "y": i + 2} for i in range(1002)] names = ("_foo", "_source_x") @@ -702,6 +718,13 @@ def test_rereading_an_orcapod_table_requires_dropping_system_columns() -> None: assert rebuilt.as_table().equals(source.as_table()) +def test_arrow_source_documents_reserved_column_refusal() -> None: + table = pa.table({"k": [1, 2], "g": ["a", "b"], "x": [3, 4], "_foo": [5, 6]}) + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + _ = ArrowTableSource(table, tag_columns=TAGS, tag_only_columns=True) + assert "refuses reserved column names" in (ArrowTableSource.__doc__ or "") + + def test_database_refuses_reserved_columns_before_reading_rows() -> None: class SchemaOnlyConnector(_Connector): def iter_batches(self, query, params=None, batch_size=1000): @@ -1011,6 +1034,26 @@ async def read_first() -> None: source.as_table() +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_polling_refuses_reserved_frame_names_before_preprocessing( + use_async: bool, +) -> None: + batch = pl.DataFrame({"k": [1, 2], "x": [None, None], "_foo": [3, 4]}) + source = PollingSource( + _Poll(None, batch), ["k"], source_id="poll", record_id_columns="k" + ) + + async def read_first() -> None: + async with contextlib.aclosing(source.async_iter_data()) as rows: + await anext(rows) + + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + if use_async: + asyncio.run(read_first()) + else: + source.as_table() + + @pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize("reverse", [False, True], ids=["foo-first", "source-first"]) @pytest.mark.parametrize("as_tag", [False, True], ids=["data", "tag"]) @@ -1077,11 +1120,19 @@ def test_polling_refuses_null_in_declaration_and_batch(values: list[Any]) -> Non PollingSource( _Poll(table.schema, batch), TAGS, source_id="poll", record_id_columns="k" ) + # A polled batch checks names first, as DataFrameSource does. poll = PollingSource( _Poll(None, batch), TAGS, source_id="poll", record_id_columns="k" ) + with pytest.raises(InputValidationError, match=r"'__unused'.*drop them first"): + poll.check_for_new_data() + legal = pl.from_arrow(_table(pa.field("unused", pa.large_list(pa.null())), values)) + assert isinstance(legal, pl.DataFrame) + poll = PollingSource( + _Poll(None, legal), TAGS, source_id="poll", record_id_columns="k" + ) with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" + InputValidationError, match=r"'unused'.*declare a supported nullable type" ): poll.check_for_new_data() From 4f5bf1f065866e64dd433936941738964d7449c8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:36:08 -0800 Subject: [PATCH 09/21] fix(validation): refuse reserved names on stored result reads --- changelog.d/ITL-1165.md | 13 +- docs/dev/design_issues/ITL-1165-RN1.md | 4 +- src/orcapod/core/nodes/function_node.py | 17 +- src/orcapod/core/nodes/operator_node.py | 12 +- src/orcapod/core/result_cache.py | 61 ++++++- .../core/sources/arrow_table_source.py | 2 + src/orcapod/core/sources/cached_source.py | 5 + src/orcapod/core/sources/data_frame_source.py | 35 +++- src/orcapod/core/sources/dict_source.py | 2 +- src/orcapod/core/sources/polling_source.py | 2 +- .../core/sources/spiraldb_table_source.py | 2 +- src/orcapod/core/sources/stream_builder.py | 2 +- src/orcapod/utils/schema_utils.py | 27 ++++ .../test_cached_function_pod_job.py | 48 ++++++ .../test_dictionary_columns_refused.py | 17 +- .../sources/test_source_arrow_validation.py | 149 ++++++++++++++++-- 16 files changed, 348 insertions(+), 50 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index 6bb041815..6b0de182a 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -10,8 +10,8 @@ unavailable and loading would normally use a proxy. Rename the output key and update its downstream references in the pipeline before saving a new configuration. - Python row inputs to `DataFrameSource` and `PollingSource` need the same field names - in every non-null row. Use mappings throughout, or use one dataclass or Pydantic - model class throughout. Mixed row classes could put values in the wrong column and + in every non-null row. Use mappings throughout, or use one namedtuple, dataclass + or Pydantic model class throughout. Mixed row classes could put values in the wrong column and are now refused. For positional rows or Pydantic rows with computed fields, extra attributes or custom serialization, use explicit mappings with the intended column names. For sparse mappings, include missing keys with `None` where appropriate. @@ -21,6 +21,9 @@ - `Pick` and `Index` reject reserved `out` names at construction, so their output columns stay visible in stream tables. -- Pod-level cache hits refuse reserved user output keys before returning the row. -- PollingSource reports reserved column names in Polars batches before converting - columns or validating their Arrow types. +- Stored function results refuse reserved user output keys before a cache lookup, + job replay or provenance read can reconstruct a row. +- Operator caches and cached sources refuse stored user columns in the reserved + namespace before presenting their rows. +- Raw Arrow and polling sources report reserved column names before validating + their Arrow types. diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index 02d929ef9..780abfb1e 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -29,5 +29,7 @@ helper as the mappers. **Fix:** Reserve all leading-underscore column names for Orcapod. Raw source readers report the offending columns and how to remove or rename them. The same rule covers new operator names and function pod output keys, including user data returned by custom -functions before caching or emission and user keys read from a pod-level cache. +functions before caching or emission and user keys read from stored results. Operator +caches and cached sources check user columns before exposing rows, including when an +operator's records feed a derived source. Custom system-tag declarations retain their existing validation. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9809760af..1e0869d0c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -33,6 +33,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.result_cache import read_stored_result_table from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.function_pod import ( fall_through_tags, @@ -3641,8 +3642,8 @@ def _stored_provenance( ) for database, path in places: database.refresh_table(path) - stored = database.get_all_records( - path, record_id_column=constants.DATA_RECORD_ID + stored = read_stored_result_table( + database, path, record_id_column=constants.DATA_RECORD_ID ) if stored is not None: found.append(keep_rows_of_data_context(stored, context_key)) @@ -3739,7 +3740,8 @@ def _fetch_joined_records( eph_results: pa.Table | None = None persistent_df = pl.DataFrame() if persistent_taginfo_df.height > 0: - results = self._cached_function_pod.result_database.get_all_records( + results = read_stored_result_table( + self._cached_function_pod.result_database, self._cached_function_pod.record_path, record_id_column=constants.DATA_RECORD_ID, ) @@ -3768,11 +3770,10 @@ def _fetch_joined_records( if ephemeral_taginfo_df.height > 0: eph_frame: pl.DataFrame | None = None if self._ephemeral_cached_pod is not None: - eph_results = ( - self._ephemeral_cached_pod.result_database.get_all_records( - self._ephemeral_cached_pod.record_path, - record_id_column=constants.DATA_RECORD_ID, - ) + eph_results = read_stored_result_table( + self._ephemeral_cached_pod.result_database, + self._ephemeral_cached_pod.record_path, + record_id_column=constants.DATA_RECORD_ID, ) if eph_results is not None: eph_results = keep_rows_of_data_context(eph_results, context_key).drop( diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 4f4632f3d..0033ed17a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -94,7 +94,7 @@ from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION, constants import orcapod.core.row_ids as row_ids from orcapod.types import CacheMode, ColumnConfig, ContentHash, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, schema_utils logger = logging.getLogger(__name__) @@ -1573,6 +1573,16 @@ def _read_current_context_records(self) -> "pa.Table | None": ) if records is None: return None + schema_utils.require_stored_stream_column_names( + records.column_names, + ( + self.HASH_COLUMN_NAME, + constants.NODE_CONTENT_HASH_COL, + constants.DATA_CONTEXT_COL, + *_STORED_ONLY_COLUMNS, + ), + self._pipeline_database.base_path + self._stored_table_path, + ) self._check_stored_data_tags(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 23ec35096..cefecb332 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -15,7 +15,11 @@ import pyarrow as pa from orcapod.core.data_function_types import StoredColumn -from orcapod.errors import OrcapodDatabaseReadError, OrcapodDatabaseWriteError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + OrcapodDatabaseWriteError, +) from orcapod.hashing.arrow_hashers import ARROW_HASH_LABEL from orcapod.contexts.stored import ( StaleTables, @@ -33,6 +37,8 @@ constants, ) +from orcapod.utils.schema_utils import require_names_not_system + if TYPE_CHECKING: from orcapod.protocols.core_protocols.datagrams import DatagramProtocol @@ -82,6 +88,47 @@ def pod_timestamp_type() -> pa.DataType: """ +def read_stored_result_table( + database: ArrowDatabaseProtocol, + path: tuple[str, ...], + *, + record_id_column: str | None = None, +) -> pa.Table | None: + """Read a raw result table and refuse reserved user names before decoding.""" + table = database.get_all_records(path, record_id_column=record_id_column) + if table is not None: + _check_result_table(table, database.base_path + path, record_id_column) + return table + + +def _check_result_table( + table: pa.Table, path: tuple[str, ...], record_id_column: str | None +) -> None: + """Refuse reserved output names using the result table's own column roles.""" + names = set(table.column_names) + bookkeeping = {column.name for column in COMMON_RESULT_COLUMNS} + if record_id_column is not None: + bookkeeping.add(record_id_column) + bookkeeping.update( + name + for name in names + if name.startswith( + (constants.PF_VARIATION_PREFIX, constants.PF_EXECUTION_PREFIX) + ) + ) + source_info = { + f"{constants.SOURCE_PREFIX}{name}" + for name in names + if not name.startswith(constants.DATAGRAM_PREFIX) + } + try: + require_names_not_system(names - bookkeeping - source_info) + except InputValidationError as exc: + raise InputValidationError( + f"{exc} Stored result table: {'/'.join(path)}" + ) from exc + + class ResultCache: """Shared result caching backed by an ``ArrowDatabaseProtocol``. @@ -279,6 +326,12 @@ def lookup( if result_table is None or result_table.num_rows == 0: return None + _check_result_table( + result_table, + self._result_database.base_path + self._versioned_record_path, + RECORD_ID_COL, + ) + if result_table.num_rows > 1: logger.info( "Cache conflict resolution: %d records for constraints %s, " @@ -485,8 +538,10 @@ def get_all_records( self._account_for_stale_tables(data_context_key) record_id_column = constants.DATA_RECORD_ID if include_system_columns else None - result_table = self._result_database.get_all_records( - self._versioned_record_path, record_id_column=record_id_column + result_table = read_stored_result_table( + self._result_database, + self._versioned_record_path, + record_id_column=record_id_column, ) if result_table is None: return None diff --git a/src/orcapod/core/sources/arrow_table_source.py b/src/orcapod/core/sources/arrow_table_source.py index f342b545c..474aba218 100644 --- a/src/orcapod/core/sources/arrow_table_source.py +++ b/src/orcapod/core/sources/arrow_table_source.py @@ -9,6 +9,7 @@ from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, + require_source_column_names, require_supported_nullable_types, ) from orcapod.utils import arrow_utils @@ -112,6 +113,7 @@ def __init__( tag_columns = _normalize_column_list(tag_columns) if infer_nullable: + require_source_column_names(table.column_names, system_tag_columns) require_supported_nullable_types(table.schema) logger.debug( "infer_nullable=True: deriving nullable flags from data " diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 15501c76c..cf061f71f 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -531,6 +531,11 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": ) if records is None: return None + schema_utils.require_stored_stream_column_names( + records.column_names, + (self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL), + self._cache_database.base_path + self.cache_path, + ) require_supported_nullable_types(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 418276acb..1ed526e61 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -6,6 +6,8 @@ from itertools import chain, repeat from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple +import numpy as np +import pandas as pd import polars as pl import pyarrow as pa from pydantic import BaseModel @@ -87,10 +89,14 @@ def _describe_frame_row(value: Any) -> _FrameRow | None: return _FrameRow( value, tuple(field.name for field in fields(value)), type(value) ) + if isinstance(value, tuple): + names = getattr(type(value), "_fields", None) + if isinstance(names, tuple) and all(isinstance(name, str) for name in names): + return _FrameRow(value, names, type(value)) raise InputValidationError( f"({type(value).__name__}) needs named fields. " - "Use a mapping, dataclass or Pydantic model for rows. " - "Pass named Polars Series as a list of columns." + "Use a mapping, namedtuple, dataclass or Pydantic model for rows. " + "Pass named Polars or pandas Series or pandas Index objects as a list of columns." ) @@ -232,6 +238,23 @@ def source_dataframe( return pl.DataFrame(data) elif isinstance(data, Sequence): if all(isinstance(column, pl.Series) for column in data): + require_source_column_names( + {column.name for column in data}, system_tag_columns + ) + return pl.DataFrame(data) + first = next((value for value in data if value is not None), None) + if isinstance(first, (pd.Series, pd.Index, np.ndarray)): + # These sequences use Polars' column conversion. Check pandas names + # before conversion can fail or discard a column. + require_source_column_names( + { + column.name + for column in data + if isinstance(column, (pd.Series, pd.Index)) + and isinstance(column.name, str) + }, + system_tag_columns, + ) return pl.DataFrame(data) rows = list(_describe_frame_rows(data)) _require_materialized_row_names(rows, system_tag_columns) @@ -256,11 +279,11 @@ def source_dataframe( class DataFrameSource(RootSource): """A source backed by a Polars DataFrame or supported tabular or column input. - Python rows must be mappings with the same keys, or dataclass or Pydantic - rows of one class with the same declared fields. Put extra or computed + Python rows must be mappings with the same keys, or namedtuple, dataclass + or Pydantic rows of one class with the same declared fields. Put extra or computed Pydantic fields in mappings, and use mappings for models with custom serialization. A ``None`` row keeps its position as a null row. Pass - named Polars Series as a list of columns. + named Polars Series, pandas Series or pandas Index objects as a list of columns. The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). @@ -327,8 +350,8 @@ def __init__( arrow_table = df.to_arrow() if schema is not None: - require_supported_nullable_types(schema) require_source_column_names(schema.names, system_tag_columns) + require_supported_nullable_types(schema) require_custom_system_tags(arrow_table, system_tag_columns, schema=schema) arrow_table = arrow_table.cast(schema) else: diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 23b9025c2..ce60876bc 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -68,8 +68,8 @@ def __init__( rows = [dict(row) for row in data] require_source_row_names(rows, system_tag_columns) if isinstance(data_schema, pa.Schema): - require_supported_nullable_types(data_schema) require_source_column_names(data_schema.names, system_tag_columns) + require_supported_nullable_types(data_schema) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, arrow_schema=data_schema, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 910fb9b32..69b201abd 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -332,8 +332,8 @@ def __init__( self._declared_arrow: pa.Schema | None = None unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): - require_supported_nullable_types(unified_schema) require_source_column_names(unified_schema.names) + require_supported_nullable_types(unified_schema) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). self._declared_arrow = declaration_form_schema( diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 4115aec56..2464d78c5 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -933,8 +933,8 @@ 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_source_column_names(raw.column_names, self._system_tag_columns) + require_supported_nullable_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 1fef611a2..1db152238 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -564,6 +564,7 @@ def build( ) tag_columns_tuple = tuple(tag_columns) system_tag_columns_tuple = tuple(system_tag_columns) + require_source_column_names(table.column_names, system_tag_columns_tuple) require_supported_nullable_types(table.schema) data_tags_tuple = tuple(c for c in tag_columns_tuple if c in data_tags) if unknown := set(data_tags) - set(tag_columns_tuple): @@ -592,7 +593,6 @@ def build( ) # 1. Refuse reserved names before any system columns could be dropped. - require_source_column_names(table.column_names, system_tag_columns_tuple) schema_utils.require_names_not_meta(tag_columns_tuple) table = arrow_utils.drop_system_columns(table) require_custom_system_tags(table, system_tag_columns_tuple) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 13d8c3a1f..3ea64f679 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -1099,3 +1099,30 @@ def require_names_not_system(names: Collection[str]) -> None: f"Column names {columns} start with {prefix!r}, which is reserved " "for system columns. A tag or data column needs another name." ) + + +def require_stored_stream_column_names( + names: Collection[str], bookkeeping: Collection[str], path: Sequence[str] +) -> None: + """Validate the user columns of a stored stream and name its table on error. + + Stored streams carry system tags and source info alongside the user columns. + System tags have their own prefix. Source info names the column it describes. + """ + from orcapod.system_constants import constants + + system_columns = { + name + for name in names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + or ( + name.startswith(constants.SOURCE_PREFIX) + and name.removeprefix(constants.SOURCE_PREFIX) in names + ) + } + try: + require_names_not_system(set(names) - set(bookkeeping) - system_columns) + except InputValidationError as exc: + raise InputValidationError( + f"{exc} Stored stream table: {'/'.join(path)}" + ) from exc diff --git a/tests/test_core/function_pod/test_cached_function_pod_job.py b/tests/test_core/function_pod/test_cached_function_pod_job.py index afa72c6c6..ed3005250 100644 --- a/tests/test_core/function_pod/test_cached_function_pod_job.py +++ b/tests/test_core/function_pod/test_cached_function_pod_job.py @@ -16,6 +16,7 @@ from pathlib import Path from typing import Any +import pyarrow as pa import pytest from orcapod import PipelineJob, errors @@ -323,3 +324,50 @@ def test_saved_job_equals_the_uncached_pods_and_loads( {"k": 1, "total": 5}, {"k": 2, "total": 10}, ] + + +@pytest.mark.parametrize("mode", ["ordinary", "load-only", "records", "derived"]) +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_function_job_refuses_reserved_stored_result_keys( + mode: str, orchestrator: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + counter = Counter() + store = DeltaTableDatabase(tmp_path / "store") + job = run_job(counter.pod(), store, orchestrator) + job_path = tmp_path / "job.json" + job.save(job_path) + counter.calls.clear() + read = DeltaTableDatabase.get_all_records + + def read_legacy_result( + database: DeltaTableDatabase, path: tuple[str, ...], *args: Any, **kwargs: Any + ) -> pa.Table | None: + table = read(database, path, *args, **kwargs) + if path[-1] == "rdb_v1" and table is not None: + return table.append_column( + "_foo", pa.array([6] * table.num_rows) + ).append_column("_tag_fake", pa.array([7] * table.num_rows)) + return table + + monkeypatch.setattr(DeltaTableDatabase, "get_all_records", read_legacy_result) + if mode == "load-only": + job = PipelineJob.load(job_path, database=store) + job.bind(sources={"s": make_source()}) + elif mode == "ordinary": + job = PipelineJob(name="j", database=store) + with job: + _ = counter.pod()(make_source(), label="add") + node = job.nodes["add"] + with pytest.raises( + errors.InputValidationError, match="'_foo'.*'_tag_fake'.*reserved.*rdb_v1" + ): + if mode == "records": + _ = node.get_all_records() + elif mode == "derived": + _ = node.as_source().as_table() + else: + _ = job.run( + orchestrator=ORCHESTRATORS[orchestrator](), + load_only=mode == "load-only", + ) + assert counter.calls == [] diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index 5125c03a3..db3de0835 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -281,23 +281,18 @@ def test_a_raw_stream_refuses_a_dictionary_in_orcapods_own_columns( assert f"- {role} column {column!r} has type dictionary<" in str(info.value) -OWN_COLUMNS = { - "__note": "meta", - "_source_v": "source-info", - "_tag_source_id::abc": "system-tag", -} +OWN_COLUMNS = ("__note", "_source_v", "_tag_source_id::abc") @pytest.mark.parametrize( - "own", [("__note",), ("_source_v",), ("_tag_source_id::abc",), tuple(OWN_COLUMNS)] + "own", [("__note",), ("_source_v",), ("_tag_source_id::abc",), OWN_COLUMNS] ) @pytest.mark.parametrize("with_user_column", [False, True], ids=["alone", "beside-v"]) @pytest.mark.parametrize("own_first", [False, True], ids=["user-first", "own-first"]) -def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( +def test_a_source_reports_reserved_names_before_dictionary_types( own: tuple[str, ...], with_user_column: bool, own_first: bool ) -> None: - """The builder checks before it drops system columns (CodeRabbit on PR 455): a - dictionary-encoded system column is refused with its role.""" + """A reserved raw name is refused before the dictionary diagnostic.""" user: dict[str, pa.Array[Any]] = { "a": pa.array(["x", "y"]), "b": pa.array(["p", "q"]), @@ -313,8 +308,8 @@ def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) message = str(info.value) for name in own: - assert f"- {OWN_COLUMNS[name]} column {name!r} has type dictionary<" in message - assert ("- data column 'v'" in message) == with_user_column + assert repr(name) in message + assert "drop them first" in message def test_a_dictionary_free_system_column_is_also_refused() -> None: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 73e4c8f76..ef60ec8a1 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -979,7 +979,7 @@ class _Poll: """Minimal impl for testing schema validation before the first fetch.""" def __init__( - self, schema: pa.Schema | None, batch: pl.DataFrame | list[Any] + self, schema: pa.Schema | None, batch: pl.DataFrame | list[Any] | Iterator[Any] ) -> None: self._schema = schema self._batch = batch @@ -1002,7 +1002,7 @@ def from_config(cls, config: dict[str, Any]) -> _Poll: async def fetch( self, cursor: Cursor[int] | None = None - ) -> tuple[Cursor[int], pl.DataFrame | list[Any]]: + ) -> tuple[Cursor[int], pl.DataFrame | list[Any] | Iterator[Any]]: """Return the prepared batch on the initial fetch.""" return Cursor(value=0), self._batch @@ -1114,9 +1114,7 @@ def test_polling_refuses_null_in_declaration_and_batch(values: list[Any]) -> Non table = _table(pa.field("__unused", pa.large_list(pa.null())), values) batch = pl.from_arrow(table) assert isinstance(batch, pl.DataFrame) - with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" - ): + with pytest.raises(InputValidationError, match=r"'__unused'.*drop them first"): PollingSource( _Poll(table.schema, batch), TAGS, source_id="poll", record_id_columns="k" ) @@ -1162,7 +1160,7 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: database = InMemoryArrowDatabase() cached = CachedSource(proxy, cache_database=database) raw = source.as_table(columns={"source": True, "system_tags": True}) - raw = raw.append_column("__unused", pa.nulls(2)) + raw = raw.append_column("unused", pa.nulls(2)) raw = raw.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) database.add_records( cached.cache_path, @@ -1171,7 +1169,7 @@ def test_cached_source_refuses_an_existing_stored_null_column() -> None: flush=True, ) with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" + InputValidationError, match=r"'unused'.*declare a supported nullable type" ): cached.as_table() @@ -1238,7 +1236,7 @@ def get_all_records( ) with pytest.raises( InputValidationError, - match=r"'__raw_missing'.*declare a supported nullable type", + match=r"'__raw_missing'.*reserved.*odb_v2", ): derived.as_table() @@ -1296,7 +1294,136 @@ def test_spiral_validates_reserved_null_in_an_empty_scan_batch( ) monkeypatch.setattr(source, "_lookup_table", lambda: handle) monkeypatch.setattr(handle, "scan_batches", lambda **kwargs: iter([batch])) - with pytest.raises( - InputValidationError, match=r"'__unused'.*declare a supported nullable type" - ): + with pytest.raises(InputValidationError, match=r"'__unused'.*drop them first"): source.as_table() + + +@pytest.mark.parametrize( + "kind", ["arrow", "arrow-infer", "dict-schema", "frame-schema", "poll-declaration"] +) +def test_raw_reserved_names_precede_arrow_type_validation(kind: str) -> None: + table = pa.table({"k": [1, 2], "x": [3, 4], "_one": [None, None], "_two": [4, 5]}) + with pytest.raises( + InputValidationError, match="'_one'.*'_two'.*rename.*drop them first" + ): + if kind == "poll-declaration": + PollingSource( + _Poll(table.schema, []), ["k"], source_id="poll", record_id_columns="k" + ) + else: + ArrowTableSource(table, ["k"], infer_nullable=kind == "arrow-infer") + + +@pytest.mark.parametrize( + "kind", ["pandas-series", "pandas-index", "namedtuple", "numpy"] +) +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +def test_named_frame_inputs_keep_polars_conversion(kind: str, path: str) -> None: + from collections import namedtuple + + import numpy as np + import pandas as pd + + batch: list[Any] + if kind == "pandas-series": + batch = [pd.Series([1, 2], name="k"), pd.Series([3, 4], name="x")] + elif kind == "pandas-index": + batch = [pd.Index([1, 2], name="k"), pd.Index([3, 4], name="x")] + elif kind.startswith("namedtuple"): + row = namedtuple("FrameRecord", ["k", "x"]) + batch = [row(1, 3), row(2, 4)] + else: + batch = [np.array([1, 2]), np.array([3, 4])] + + data = iter(batch) if kind == "namedtuple-iterator" else batch + frame = pl.DataFrame(batch) + key, value = frame.columns + expected = frame.to_dicts() + if path == "frame": + source = DataFrameSource(data, [key], tag_only_columns=True) + control = DataFrameSource(frame, [key], tag_only_columns=True) + assert source.as_table().equals(control.as_table(), check_metadata=True) + assert source.source_id == control.source_id + else: + source = PollingSource( + _Poll(None, data), [key], source_id="poll", record_id_columns=key + ) + if path == "poll-sync": + assert source.as_table().to_pylist() == expected + else: + + async def read() -> list[dict[str, Any]]: + async with contextlib.aclosing(source.async_iter_data()) as rows: + return [ + {key: tag.as_dict()[key], value: data.as_dict()[value]} + for tag, data in [await anext(rows) for _ in expected] + ] + + assert asyncio.run(read()) == expected + + +@pytest.mark.parametrize("view", ["operator-replay", "operator-records", "derived"]) +def test_operator_storage_refuses_reserved_user_columns( + view: str, monkeypatch: pytest.MonkeyPatch +) -> None: + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + store = InMemoryArrowDatabase() + job = PipelineJob(name="stored", database=store) + with job: + DropNulls(["x", "y"])(source, label="origin") + node = job.nodes["origin"] + assert isinstance(node, OperatorJobNode) + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.LOG) + job.run() + read = store.get_all_records + + def read_legacy_rows(path: tuple[str, ...], *args: Any, **kwargs: Any): + table = read(path, *args, **kwargs) + if table is not None and path[-1] == "odb_v2": + return table.append_column("_foo", pa.array([4] * table.num_rows)) + return table + + monkeypatch.setattr(store, "get_all_records", read_legacy_rows) + with pytest.raises(InputValidationError, match="'_foo'.*reserved.*odb_v2"): + if view == "operator-records": + node.get_all_records() + elif view == "derived": + node.as_source().as_table() + else: + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.REPLAY) + node.run(load_only=True) + + +def test_cached_source_refuses_reserved_stored_user_columns() -> None: + source = ArrowTableSource( + _table(pa.field("extra", pa.string(), nullable=False), ["a", "b"]), + tag_columns=TAGS, + tag_only_columns=True, + source_id="rows", + ) + tag_schema, data_schema = source.output_schema() + proxy = SourceProxy( + source_id=source.source_id, + content_hash_str=source.content_hash().to_string(), + pipeline_hash_str=source.pipeline_hash().to_string(), + tag_schema=tag_schema, + data_schema=data_schema, + ) + store = InMemoryArrowDatabase() + cached = CachedSource(proxy, cache_database=store) + raw = source.as_table(columns={"source": True, "system_tags": True}) + raw = raw.append_column("_foo", pa.array([4, 5])) + raw = raw.append_column(CachedSource.HASH_COLUMN_NAME, pa.array([b"a", b"b"])) + store.add_records( + cached.cache_path, + with_data_context(raw, source.data_context_key), + record_id_column=CachedSource.HASH_COLUMN_NAME, + flush=True, + ) + with pytest.raises(InputValidationError, match="'_foo'.*reserved.*sdb_v1"): + cached.as_table() From 62f7e4f2609463c889711a48568946807677ce3e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:01:04 -0800 Subject: [PATCH 10/21] fix(validation): check raw frame and callback tag names before conversion --- changelog.d/ITL-1165.md | 2 + docs/dev/design_issues/ITL-1165-RN1.md | 4 + src/orcapod/core/nodes/operator_node.py | 33 ++-- src/orcapod/core/result_cache.py | 33 ++-- src/orcapod/core/sources/cached_source.py | 15 +- src/orcapod/core/sources/data_frame_source.py | 76 ++++++--- src/orcapod/core/sources/list_source.py | 4 + src/orcapod/utils/schema_utils.py | 11 +- .../sources/test_source_arrow_validation.py | 154 +++++++++++++++++- 9 files changed, 268 insertions(+), 64 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index 6b0de182a..da8e65e2e 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -27,3 +27,5 @@ namespace before presenting their rows. - Raw Arrow and polling sources report reserved column names before validating their Arrow types. +- Frame and polling sources report reserved raw names before frame conversion, and + list sources check names in callback tags before projecting their fields. diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index 780abfb1e..e9afcf669 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -32,4 +32,8 @@ new operator names and function pod output keys, including user data returned by functions before caching or emission and user keys read from stored results. Operator caches and cached sources check user columns before exposing rows, including when an operator's records feed a derived source. +Frame and polling sources check names before conversion can relabel them, and list +sources validate callback tags before discarding metadata. A saved operator schema +identifies legacy user names even when a mixed table alone cannot distinguish them +from system tags. Custom system-tag declarations retain their existing validation. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 0033ed17a..81387cfe1 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1573,16 +1573,29 @@ def _read_current_context_records(self) -> "pa.Table | None": ) if records is None: return None - schema_utils.require_stored_stream_column_names( - records.column_names, - ( - self.HASH_COLUMN_NAME, - constants.NODE_CONTENT_HASH_COL, - constants.DATA_CONTEXT_COL, - *_STORED_ONLY_COLUMNS, - ), - self._pipeline_database.base_path + self._stored_table_path, - ) + try: + saved = self._descriptor.get("output_schema") if self._loaded else None + if saved is not None: + # A descriptor distinguishes a legacy user name from a system tag. + schema_utils.require_names_not_system( + set(saved.get("tag", {})) | set(saved.get("data", {})) + ) + schema_utils.require_stored_stream_column_names( + records.column_names, + ( + self.HASH_COLUMN_NAME, + constants.NODE_CONTENT_HASH_COL, + constants.DATA_CONTEXT_COL, + *_STORED_ONLY_COLUMNS, + ), + ) + except InputValidationError as exc: + location = "/".join( + self._pipeline_database.base_path + self._stored_table_path + ) + raise InputValidationError( + f"{exc} Stored stream table: {location}" + ) from exc self._check_stored_data_tags(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index b9b3c8ff8..9e76fca6a 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -184,13 +184,17 @@ def read_stored_result_table( """Read a raw result table and refuse reserved user names before decoding.""" table = database.get_all_records(path, record_id_column=record_id_column) if table is not None: - _check_result_table(table, database.base_path + path, record_id_column) + try: + _check_result_table(table, record_id_column) + except InputValidationError as exc: + location = "/".join(database.base_path + path) + raise InputValidationError( + f"{exc} Stored result table: {location}" + ) from exc return table -def _check_result_table( - table: pa.Table, path: tuple[str, ...], record_id_column: str | None -) -> None: +def _check_result_table(table: pa.Table, record_id_column: str | None) -> None: """Refuse reserved output names using the result table's own column roles.""" names = set(table.column_names) bookkeeping = {column.name for column in COMMON_RESULT_COLUMNS} @@ -208,12 +212,7 @@ def _check_result_table( for name in names if not name.startswith(constants.DATAGRAM_PREFIX) } - try: - require_names_not_system(names - bookkeeping - source_info) - except InputValidationError as exc: - raise InputValidationError( - f"{exc} Stored result table: {'/'.join(path)}" - ) from exc + require_names_not_system(names - bookkeeping - source_info) class ResultCache: @@ -413,11 +412,15 @@ def lookup( if result_table is None or result_table.num_rows == 0: return None - _check_result_table( - result_table, - self._result_database.base_path + self._versioned_record_path, - RECORD_ID_COL, - ) + try: + _check_result_table(result_table, RECORD_ID_COL) + except InputValidationError as exc: + location = "/".join( + self._result_database.base_path + self._versioned_record_path + ) + raise InputValidationError( + f"{exc} Stored result table: {location}" + ) from exc if result_table.num_rows > 1: logger.info( diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index cf061f71f..bfc46ed4a 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -531,11 +531,16 @@ def _read_cached_records_with_hashes(self) -> "pa.Table | None": ) if records is None: return None - schema_utils.require_stored_stream_column_names( - records.column_names, - (self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL), - self._cache_database.base_path + self.cache_path, - ) + try: + schema_utils.require_stored_stream_column_names( + records.column_names, + (self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL), + ) + except InputValidationError as exc: + location = "/".join(self._cache_database.base_path + self.cache_path) + raise InputValidationError( + f"{exc} Stored stream table: {location}" + ) from exc require_supported_nullable_types(records.schema) stored_rows = records.num_rows records = keep_rows_of_data_context(records, self.data_context_key) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 1ed526e61..150b145ae 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -221,6 +221,48 @@ def typed_values() -> Iterator[Any]: return frame +def _frame_from_columns( + columns: Sequence[Any], system_tag_columns: Collection[str] +) -> pl.DataFrame: + """Check named columns and refuse named rows in a column-oriented sequence.""" + names: set[str] = set() + named_series: dict[int, str] = {} + named_rows: dict[int, tuple[str, ...]] = {} + for index, column in enumerate(columns): + if isinstance(column, (pd.Series, pd.Index, pl.Series)): + if column.name is not None and (name := str(column.name)): + names.add(name) + named_series[index] = name + elif isinstance(column, np.ndarray) or column is None: + continue + elif ( + isinstance(column, (Mapping, BaseModel)) + or is_dataclass(column) + or (isinstance(column, tuple) and hasattr(type(column), "_fields")) + ): + row = _describe_frame_row(column) + if row is not None: + names.update(row.exposed_names) + named_rows[index] = row.names + + require_source_column_names(names, system_tag_columns) + if named_rows: + index, fields = next(iter(named_rows.items())) + raise InputValidationError( + f"Source row {index} declares fields {fields!r} in a column-oriented " + "sequence. Pass named rows separately or use named columns." + ) + + frame = pl.DataFrame(columns) + for index, name in named_series.items(): + if index >= frame.width or name != frame.columns[index]: + raise InputValidationError( + f"Input column {index} is named {name!r}, but Polars " + f"returned columns {frame.columns!r}. Use named columns." + ) + return frame + + def source_dataframe( data: FrameInitTypes, system_tag_columns: Collection[str] = () ) -> pl.DataFrame: @@ -233,29 +275,20 @@ def source_dataframe( Returns: The validated input converted with Polars' normal inference. """ - if isinstance(data, Mapping): + if isinstance(data, pd.DataFrame): + require_source_column_names( + [str(name) for name in data.columns], system_tag_columns + ) + elif isinstance(data, (pa.Table, pa.RecordBatch)): + require_source_column_names(data.schema.names, system_tag_columns) + elif isinstance(data, np.ndarray): + require_source_column_names(data.dtype.names or (), system_tag_columns) + elif isinstance(data, Mapping): require_source_column_names(data.keys(), system_tag_columns) - return pl.DataFrame(data) elif isinstance(data, Sequence): - if all(isinstance(column, pl.Series) for column in data): - require_source_column_names( - {column.name for column in data}, system_tag_columns - ) - return pl.DataFrame(data) first = next((value for value in data if value is not None), None) - if isinstance(first, (pd.Series, pd.Index, np.ndarray)): - # These sequences use Polars' column conversion. Check pandas names - # before conversion can fail or discard a column. - require_source_column_names( - { - column.name - for column in data - if isinstance(column, (pd.Series, pd.Index)) - and isinstance(column.name, str) - }, - system_tag_columns, - ) - return pl.DataFrame(data) + if isinstance(first, (pd.Series, pd.Index, np.ndarray, pl.Series)): + return _frame_from_columns(data, system_tag_columns) rows = list(_describe_frame_rows(data)) _require_materialized_row_names(rows, system_tag_columns) return _frame_from_checked_rows( @@ -323,6 +356,8 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) + if schema is not None: + require_source_column_names(schema.names, system_tag_columns) df = source_dataframe(data, system_tag_columns) require_source_column_names(df.columns, system_tag_columns) @@ -350,7 +385,6 @@ def __init__( arrow_table = df.to_arrow() if schema is not None: - require_source_column_names(schema.names, system_tag_columns) require_supported_nullable_types(schema) require_custom_system_tags(arrow_table, system_tag_columns, schema=schema) arrow_table = arrow_table.cast(schema) diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 74e3dffd2..64e617f8c 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -104,6 +104,10 @@ def __init__( rows = [] for idx, element in enumerate(self._elements): tag_fields = tag_function(element, idx) + if isinstance(tag_fields, TagProtocol): + require_source_column_names( + tag_fields.keys(columns={"meta": True, "system_tags": True}) + ) if hasattr(tag_fields, "as_dict"): tag_fields = tag_fields.as_dict() row = dict(tag_fields) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 3ea64f679..e839414f2 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -1102,9 +1102,9 @@ def require_names_not_system(names: Collection[str]) -> None: def require_stored_stream_column_names( - names: Collection[str], bookkeeping: Collection[str], path: Sequence[str] + names: Collection[str], bookkeeping: Collection[str] ) -> None: - """Validate the user columns of a stored stream and name its table on error. + """Validate the user columns of a stored stream. Stored streams carry system tags and source info alongside the user columns. System tags have their own prefix. Source info names the column it describes. @@ -1120,9 +1120,4 @@ def require_stored_stream_column_names( and name.removeprefix(constants.SOURCE_PREFIX) in names ) } - try: - require_names_not_system(set(names) - set(bookkeeping) - system_columns) - except InputValidationError as exc: - raise InputValidationError( - f"{exc} Stored stream table: {'/'.join(path)}" - ) from exc + require_names_not_system(set(names) - set(bookkeeping) - system_columns) diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index ef60ec8a1..1902ad86e 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -9,7 +9,7 @@ from collections.abc import Collection, Iterator from dataclasses import dataclass from pathlib import Path -from typing import Any, TypedDict +from typing import TYPE_CHECKING, Any, TypedDict import deltalake import polars as pl @@ -51,6 +51,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", @@ -978,9 +981,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 | list[Any] | Iterator[Any] - ) -> None: + def __init__(self, schema: pa.Schema | None, batch: FrameInitTypes) -> None: self._schema = schema self._batch = batch @@ -1002,7 +1003,7 @@ def from_config(cls, config: dict[str, Any]) -> _Poll: async def fetch( self, cursor: Cursor[int] | None = None - ) -> tuple[Cursor[int], pl.DataFrame | list[Any] | Iterator[Any]]: + ) -> tuple[Cursor[int], FrameInitTypes]: """Return the prepared batch on the initial fetch.""" return Cursor(value=0), self._batch @@ -1427,3 +1428,146 @@ def test_cached_source_refuses_reserved_stored_user_columns() -> None: ) with pytest.raises(InputValidationError, match="'_foo'.*reserved.*sdb_v1"): cached.as_table() + + +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +@pytest.mark.parametrize( + ("kind", "field"), + [("namedtuple", "_1"), ("namedtuple", "label"), ("series", "_hidden")], +) +def test_numpy_first_batch_refuses_names_that_would_be_lost( + path: str, kind: str, field: str +) -> None: + from collections import namedtuple + + import numpy as np + + column: Any + if kind == "series": + column = pl.Series(field, [3, 4]) + elif field == "_1": + row = namedtuple("ReservedRecord", ["label", "_hidden"], rename=True) + column = row(3, 4) + else: + row = namedtuple("OrdinaryRecord", ["label", "value"]) + column = row(3, 4) + batch = [np.array([1, 2]), column] + + with pytest.raises(InputValidationError, match=escape(repr(field))): + if path == "frame": + DataFrameSource(batch) + else: + source = PollingSource( + _Poll(None, batch), + ["column_0"], + source_id="poll", + record_id_columns="column_0", + ) + if path == "poll-sync": + source.as_table() + else: + + async def read() -> None: + async with contextlib.aclosing(source.async_iter_data()) as rows: + await anext(rows) + + asyncio.run(read()) + + +@pytest.mark.parametrize("system_field", ["_tag_fake", "_tag::fake"]) +def test_list_source_checks_callback_tag_before_projection(system_field: str) -> None: + from orcapod.core.datagrams import Tag + + def tag(value: int, index: int) -> Tag: + return Tag({"label": index, system_field: value, "__meta": value}) + + with pytest.raises(InputValidationError) as exc: + ListSource("value", [1, 2], tag_function=tag, expected_tag_keys=["label"]) + assert repr(system_field) in str(exc.value) + assert "'__meta'" in str(exc.value) + assert "drop them first" in str(exc.value) + + valid = ListSource( + "value", [3], tag_function=lambda _, index: Tag({"label": index}) + ) + assert valid.as_table().to_pylist() == [{"label": 0, "value": 3}] + + +def test_dataframe_source_checks_declared_names_before_reading_input() -> None: + def unreadable() -> Iterator[dict[str, int]]: + yield from () + raise AssertionError("should reject the declared name before reading rows") + + with pytest.raises(InputValidationError, match="'_schema'.*drop them first"): + DataFrameSource(unreadable(), schema=pa.schema([("_schema", pa.int64())])) + + +@pytest.mark.parametrize("kind", ["pandas", "arrow"]) +@pytest.mark.parametrize("path", ["frame", "poll-sync"]) +def test_frame_checks_raw_names_before_duplicate_column_error( + kind: str, path: str +) -> None: + import pandas as pd + + names = ["x", "x", "_one", "_two"] + batch = ( + pd.DataFrame([[1, 2, 3, 4]], columns=pd.Index(names)) + if kind == "pandas" + else pa.Table.from_arrays([pa.array([i]) for i in range(4)], names=names) + ) + with pytest.raises(InputValidationError, match="'_one'.*'_two'.*drop them first"): + if path == "frame": + DataFrameSource(batch) + else: + PollingSource( + _Poll(None, batch), ["x"], source_id="poll", record_id_columns="x" + ).as_table() + + +def test_stored_column_validators_use_only_column_roles() -> None: + from orcapod.core.result_cache import _check_result_table + from orcapod.utils.schema_utils import require_stored_stream_column_names + + with pytest.raises(InputValidationError, match="'_tag_fake'.*reserved"): + _check_result_table(pa.table({"_tag_fake": [1]}), None) + with pytest.raises(InputValidationError, match="'_foo'.*reserved"): + require_stored_stream_column_names(["_foo"], ()) + + +def test_stored_operator_checks_user_names_from_descriptor() -> None: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [3, 4]}), tag_columns=["k"], tag_only_columns=True + ) + store = InMemoryArrowDatabase() + job = PipelineJob(name="stored", database=store) + with job: + DropNulls(["x"])(source, label="origin") + node = job.nodes["origin"] + assert isinstance(node, OperatorJobNode) + node.attach_databases(pipeline_database=store, cache_mode=CacheMode.LOG) + job.run() + + legacy_name = "_tag_legacy" + path = (*node.node_identity_path, "odb_v2") + records = store.get_all_records(path, record_id_column=node.HASH_COLUMN_NAME) + assert records is not None + legacy_records = records.append_column(legacy_name, pa.array([4, 5])) + legacy_store = InMemoryArrowDatabase() + legacy_store.add_records( + path, legacy_records, record_id_column=node.HASH_COLUMN_NAME, flush=True + ) + loaded = OperatorJobNode.from_descriptor( + { + "label": "origin", + "output_schema": {"data": {legacy_name: "int"}}, + "table_scope": "pipeline_hash", + "cache_mode": "log", + "pipeline_path": node.node_identity_path, + }, + operator=None, + input_streams=(), + databases={"pipeline": legacy_store}, + job_content_hash=node.content_hash().to_string(), + ) + with pytest.raises(InputValidationError, match="'_tag_legacy'.*reserved.*odb_v2"): + loaded.get_all_records(all_info=True) From 8021d6ae9942168bfeb3bc02e44bd191b3a8571a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:14:19 -0800 Subject: [PATCH 11/21] fix(sources): preserve compatible Polars row layouts --- changelog.d/ITL-1165.md | 12 +- src/orcapod/core/sources/data_frame_source.py | 271 +++++++++++------- .../sources/test_source_arrow_validation.py | 140 +++++++-- 3 files changed, 287 insertions(+), 136 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index da8e65e2e..001d8c7b3 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -9,13 +9,11 @@ is refused when the pod is rebuilt, including when the original callable is unavailable and loading would normally use a proxy. Rename the output key and update its downstream references in the pipeline before saving a new configuration. -- Python row inputs to `DataFrameSource` and `PollingSource` need the same field names - in every non-null row. Use mappings throughout, or use one namedtuple, dataclass - or Pydantic model class throughout. Mixed row classes could put values in the wrong column and - are now refused. For positional rows or Pydantic rows with computed fields, extra - attributes or custom serialization, use explicit mappings with the intended column - names. For sparse mappings, include missing keys with `None` where appropriate. - Pass named Polars Series as a list of columns to either source. +- Named Python row inputs to `DataFrameSource` and `PollingSource` need the same + field names in every non-null row. Typed rows of the same kind need the same + field layout. For sparse mappings, include missing keys with `None` where + appropriate. If a Pydantic model exposes fields that conversion would drop or + rename, pass mappings with the intended column names. ### Fixed diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 150b145ae..da63bd4ee 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -1,16 +1,25 @@ from __future__ import annotations import logging -from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence, Sized +from collections.abc import ( + Callable, + Collection, + Iterable, + Iterator, + Mapping, + Sequence, + Sized, +) from dataclasses import fields, is_dataclass from itertools import chain, repeat -from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple +from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, cast import numpy as np import pandas as pd import polars as pl import pyarrow as pa from pydantic import BaseModel +from typing_extensions import override from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags @@ -36,13 +45,79 @@ class _FrameRow(NamedTuple): value: Any names: tuple[str, ...] - row_type: type - non_column_names: tuple[str, ...] = () + kind: Literal["mapping", "model", "dataclass", "namedtuple", "series", "positional"] + additional_names: tuple[str, ...] = () @property def exposed_names(self) -> tuple[str, ...]: """Return declared and other field names exposed by the row.""" - return (*self.names, *self.non_column_names) + return (*self.names, *self.additional_names) + + +class _FrameModelRow(BaseModel): + """Present the original Pydantic layout and check any dump Polars uses. + + Polars reads declared field values directly for flat models and calls + `model_dump` when it unpacks nested models. Forward both paths so validation + keeps Polars' original type inference and does not run a serializer twice. + """ + + __slots__: ClassVar[tuple[str, ...]] = ( + "_original", + "_names", + "_system_tag_columns", + ) + if TYPE_CHECKING: + _original: BaseModel + _names: set[str] + _system_tag_columns: Collection[str] + + @classmethod + def from_model( + cls, + value: BaseModel, + names: tuple[str, ...], + system_tag_columns: Collection[str], + ) -> _FrameModelRow: + """Wrap a model that has already been constructed and validated.""" + row = cls.model_construct() + object.__setattr__(row, "_original", value) + object.__setattr__(row, "_names", set(names)) + object.__setattr__(row, "_system_tag_columns", system_tag_columns) + return row + + @override + def __getattribute__(self, name: str) -> Any: + if name in ("__class__", "__dict__"): + return getattr(self._original, name) + return super().__getattribute__(name) + + def __getattr__(self, name: str) -> Any: + return getattr(self._original, name) + + @override + def model_dump(self, **kwargs: object) -> dict[str, object]: + """Validate the serialized field names before they reach inference.""" + dump = cast("Callable[..., object]", self._original.model_dump) + values = dump(**kwargs) + if not isinstance(values, dict): + raise InputValidationError( + "A serialized model row must return a dict with string field names." + ) + fields = cast("dict[object, object]", values) + names = {name for name in fields if isinstance(name, str)} + if len(names) != len(fields): + raise InputValidationError( + "A serialized model row needs string field names." + ) + require_source_column_names(names, self._system_tag_columns) + if names != self._names: + raise InputValidationError( + f"Serialized model row has different fields. Missing " + f"{sorted(self._names - names)!r}, extra " + f"{sorted(names - self._names)!r}. Use a mapping." + ) + return cast("dict[str, object]", fields) def _describe_model_row(value: BaseModel) -> _FrameRow: @@ -61,16 +136,26 @@ def _describe_model_row(value: BaseModel) -> _FrameRow: | value.model_fields_set | vars(value).keys() ) - if model.model_config.get("serialize_by_alias"): - exposed.update( - field.serialization_alias - for field in declared.values() - if field.serialization_alias is not None - ) + aliases = { + field.serialization_alias + for name, field in declared.items() + if model.model_config.get("serialize_by_alias") + and field.serialization_alias is not None + and field.serialization_alias != name + } if not all(isinstance(name, str) for name in exposed): raise InputValidationError("needs string field names.") + if aliases & declared.keys(): + require_source_column_names(aliases) + raise InputValidationError( + f"has serialization aliases {sorted(aliases)!r} that rename existing " + "model fields. Use a mapping." + ) return _FrameRow( - value, tuple(declared), model, tuple(sorted(exposed - declared.keys())) + value, + tuple(declared), + "model", + tuple(sorted((exposed - declared.keys()) | aliases)), ) @@ -82,22 +167,23 @@ def _describe_frame_row(value: Any) -> _FrameRow | None: names = tuple(value) if not all(isinstance(name, str) for name in names): raise InputValidationError("needs string field names.") - return _FrameRow(value if isinstance(value, dict) else dict(value), names, dict) + return _FrameRow( + value if isinstance(value, dict) else dict(value), names, "mapping" + ) if isinstance(value, BaseModel): return _describe_model_row(value) if is_dataclass(value) and not isinstance(value, type): return _FrameRow( - value, tuple(field.name for field in fields(value)), type(value) + value, tuple(field.name for field in fields(value)), "dataclass" ) - if isinstance(value, tuple): - names = getattr(type(value), "_fields", None) + if isinstance(value, Sequence): + names = getattr(value, "_fields", None) if isinstance(names, tuple) and all(isinstance(name, str) for name in names): - return _FrameRow(value, names, type(value)) - raise InputValidationError( - f"({type(value).__name__}) needs named fields. " - "Use a mapping, namedtuple, dataclass or Pydantic model for rows. " - "Pass named Polars or pandas Series or pandas Index objects as a list of columns." - ) + return _FrameRow(value, names, "namedtuple") + if isinstance(value, (pd.Series, pd.Index, pl.Series)): + name = str(value.name) if value.name is not None else "" + return _FrameRow(value, (name,) if name else (), "series") + return _FrameRow(value, (), "positional") def _describe_frame_rows(values: Iterable[Any]) -> Iterator[_FrameRow | None]: @@ -121,23 +207,7 @@ def _checked_frame_rows( require_source_column_names(row.exposed_names, system_tag_columns) except InputValidationError as exc: raise InputValidationError(f"Source row {index}. {exc}") from exc - if row.non_column_names: - raise InputValidationError( - f"Source row {index} exposes extra or computed model fields " - f"{list(row.non_column_names)!r} outside its declared columns. " - "Use a mapping or a model without computed or extra fields." - ) - if isinstance(row.value, BaseModel): - model = type(row.value) - if ( - model.model_dump is not BaseModel.model_dump - or model.__pydantic_decorators__.model_serializers - ): - raise InputValidationError( - f"Source row {index} has serialized field names that cannot be " - "verified from its declared model fields. Use a mapping." - ) - names = set(row.names) + names = set(row.exposed_names) if first is None: first, expected = row, names if names != expected: @@ -147,13 +217,13 @@ def _checked_frame_rows( "Use the same field names in every row. For mappings, add missing " "fields with None where appropriate and remove unintended fields." ) - if row.row_type is not first.row_type or ( - row.row_type is not dict and row.names != first.names + if row.kind != first.kind or ( + row.kind != "mapping" and row.names != first.names ): raise InputValidationError( f"Source row {index} has a different layout " - f"({row.row_type.__name__} fields {row.names!r}). " - f"Use the same row layout ({first.row_type.__name__} fields " + f"({type(row.value).__name__} fields {row.names!r}). " + f"Use the same row layout ({type(first.value).__name__} fields " f"{first.names!r}) or use mappings throughout." ) yield row @@ -176,10 +246,16 @@ def _require_materialized_row_names( raise InputValidationError(f"Source row {first}. {exc}") from exc -def _frame_from_checked_rows( - rows: Iterator[_FrameRow | None], *, materialized: bool +def _frame_from_rows( + data: Iterable[Any], system_tag_columns: Collection[str], *, materialized: bool ) -> pl.DataFrame: - """Keep Polars' typed conversion for a single verified layout.""" + """Use the regular Polars conversion after checking row or column names.""" + rows = _describe_frame_rows(data) + if materialized: + described = list(rows) + _require_materialized_row_names(described, system_tag_columns) + rows = iter(described) + leading_nulls = 0 for first in rows: if first is not None: @@ -189,22 +265,39 @@ def _frame_from_checked_rows( return pl.DataFrame([None] * leading_nulls) all_rows = chain(repeat(None, leading_nulls), (first,), rows) - if first.row_type is dict: - values = (row.value if row is not None else None for row in all_rows) + if first.kind == "series" or (materialized and isinstance(first.value, np.ndarray)): + return _frame_from_columns( + all_rows, system_tag_columns, materialized=materialized + ) + + checked = _checked_frame_rows(all_rows, system_tag_columns) + if first.kind in ("mapping", "positional"): + values = (row.value if row is not None else None for row in checked) return pl.DataFrame(list(values) if materialized else values) null_positions: set[int] = set() def typed_values() -> Iterator[Any]: - for index, row in enumerate(all_rows): + for index, row in enumerate(checked): if row is None: null_positions.add(index) + elif isinstance(row.value, BaseModel): + yield _FrameModelRow.from_model( + row.value, row.exposed_names, system_tag_columns + ) else: yield row.value typed = typed_values() frame = pl.DataFrame(list(typed) if materialized else typed) - if tuple(frame.columns) != first.names: + if first.kind == "model": + expected = set(first.exposed_names) + if set(frame.columns) != expected: + raise InputValidationError( + f"Source row {leading_nulls} exposes model fields {sorted(expected)!r}, " + f"but Polars returned {frame.columns!r}. Use a mapping." + ) + elif tuple(frame.columns) != first.names: raise InputValidationError( f"Source row {leading_nulls} declares fields {first.names!r}, " f"but Polars returned {frame.columns!r}. Use mappings for these rows." @@ -222,38 +315,32 @@ def typed_values() -> Iterator[Any]: def _frame_from_columns( - columns: Sequence[Any], system_tag_columns: Collection[str] + columns: Iterable[_FrameRow | None], + system_tag_columns: Collection[str], + *, + materialized: bool, ) -> pl.DataFrame: """Check named columns and refuse named rows in a column-oriented sequence.""" - names: set[str] = set() named_series: dict[int, str] = {} - named_rows: dict[int, tuple[str, ...]] = {} - for index, column in enumerate(columns): - if isinstance(column, (pd.Series, pd.Index, pl.Series)): - if column.name is not None and (name := str(column.name)): - names.add(name) - named_series[index] = name - elif isinstance(column, np.ndarray) or column is None: - continue - elif ( - isinstance(column, (Mapping, BaseModel)) - or is_dataclass(column) - or (isinstance(column, tuple) and hasattr(type(column), "_fields")) - ): - row = _describe_frame_row(column) - if row is not None: - names.update(row.exposed_names) - named_rows[index] = row.names - - require_source_column_names(names, system_tag_columns) - if named_rows: - index, fields = next(iter(named_rows.items())) - raise InputValidationError( - f"Source row {index} declares fields {fields!r} in a column-oriented " - "sequence. Pass named rows separately or use named columns." - ) - frame = pl.DataFrame(columns) + def checked_columns() -> Iterator[Any]: + for index, column in enumerate(columns): + if column is None: + yield None + continue + if not materialized: + require_source_column_names(column.exposed_names, system_tag_columns) + if column.kind == "series" and column.names: + named_series[index] = column.names[0] + elif column.kind not in ("positional", "series"): + raise InputValidationError( + f"Source row {index} declares fields {column.names!r} in a " + "column-oriented sequence. Pass named rows separately or use named columns." + ) + yield column.value + + values = checked_columns() + frame = pl.DataFrame(list(values) if materialized else values) for index, name in named_series.items(): if index >= frame.width or name != frame.columns[index]: raise InputValidationError( @@ -286,37 +373,25 @@ def source_dataframe( elif isinstance(data, Mapping): require_source_column_names(data.keys(), system_tag_columns) elif isinstance(data, Sequence): - first = next((value for value in data if value is not None), None) - if isinstance(first, (pd.Series, pd.Index, np.ndarray, pl.Series)): - return _frame_from_columns(data, system_tag_columns) - rows = list(_describe_frame_rows(data)) - _require_materialized_row_names(rows, system_tag_columns) - return _frame_from_checked_rows( - _checked_frame_rows(rows, system_tag_columns), materialized=True - ) + return _frame_from_rows(data, system_tag_columns, materialized=True) elif ( isinstance(data, Iterable) and not isinstance(data, Sized) and not hasattr(data, "__arrow_c_stream__") ): - return _frame_from_checked_rows( - _checked_frame_rows( - _describe_frame_rows(data), - system_tag_columns, - ), - materialized=False, - ) + return _frame_from_rows(data, system_tag_columns, materialized=False) return pl.DataFrame(data) class DataFrameSource(RootSource): """A source backed by a Polars DataFrame or supported tabular or column input. - Python rows must be mappings with the same keys, or namedtuple, dataclass - or Pydantic rows of one class with the same declared fields. Put extra or computed - Pydantic fields in mappings, and use mappings for models with custom - serialization. A ``None`` row keeps its position as a null row. Pass - named Polars Series, pandas Series or pandas Index objects as a list of columns. + Named Python rows must supply the same fields. Namedtuple, dataclass and + Pydantic rows can use different classes of the same kind with the same field + layout. Names exposed by a model must be retained as columns, including when + the model is serialized. Positional and scalar inputs use Polars' column + names. A ``None`` row keeps its position as a null row. Named Series can be + passed as a sequence or iterator of columns. The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 1902ad86e..baa6c1d68 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -9,7 +9,7 @@ from collections.abc import Collection, Iterator from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Any, TypedDict +from typing import TYPE_CHECKING, Any, ClassVar, TypedDict import deltalake import polars as pl @@ -19,6 +19,7 @@ from pydantic import ( BaseModel, ConfigDict, + Field, SerializerFunctionWrapHandler, computed_field, model_serializer, @@ -285,23 +286,24 @@ def build() -> CSVSource: build() -def test_dataframe_source_guides_series_iterators_to_named_columns() -> None: - columns = [ - pl.Series(name, values) - for name, values in { - "k": [1, 2], - "g": ["a", "b"], - "x": [3, 4], - "y": [5, 6], - }.items() - ] - with pytest.raises(InputValidationError, match=r"Series.*list of columns"): - DataFrameSource(iter(columns), tag_columns=TAGS, tag_only_columns=True) - source = DataFrameSource(columns, tag_columns=TAGS, tag_only_columns=True) - assert source.as_table().to_pylist() == [ - {"k": 1, "g": "a", "x": 3, "y": 5}, - {"k": 2, "g": "b", "x": 4, "y": 6}, - ] +def test_frame_stops_at_first_reserved_series_in_iterator() -> None: + def columns() -> Iterator[pl.Series]: + yield pl.Series("k", [1, 2]) + yield pl.Series("_foo", [3, 4]) + pytest.fail("reserved columns must stop iteration") + + with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): + DataFrameSource(columns()) + + +@pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) +def test_positional_frame_input_checks_following_row_names(as_iterator: bool) -> None: + from collections import namedtuple + + row = namedtuple("ReservedRecord", ["k", "_hidden"], rename=True) + rows: list[Any] = [(1, 2), row(3, 4)] + with pytest.raises(InputValidationError, match="'_1'.*drop them first"): + DataFrameSource(iter(rows) if as_iterator else rows) @pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) @@ -375,6 +377,12 @@ class _FrameRow: x: int +@dataclass +class _EquivalentFrameRow: + k: int + x: int + + @dataclass class _ReservedFrameRow: k: int @@ -440,6 +448,15 @@ class _PlainFrameModel(BaseModel): x: int +class _EquivalentFrameModel(_PlainFrameModel): + pass + + +class _AliasedFrameModel(_PlainFrameModel): + model_config = ConfigDict(serialize_by_alias=True) + x: int = Field(serialization_alias="value") + + class _ReservedComputedFrameModel(_PlainFrameModel): @computed_field # type: ignore[prop-decorator] @property @@ -468,6 +485,13 @@ def _serialize(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: return fields +class _NestedComputedFrameModel(_SerializedFrameModel): + @computed_field # type: ignore[prop-decorator] + @property + def total(self) -> int: + return self.k + self.x.x + + def _model_with_explicit_attribute() -> _PlainFrameModel: row = _PlainFrameModel(k=2, x=4) object.__setattr__(row, "_raw", 12345) @@ -527,12 +551,17 @@ def _model_with_explicit_attribute() -> _PlainFrameModel: r"row 0.*'total'.*mapping", id="pydantic-ordinary-undeclared", ), + pytest.param( + [_AliasedFrameModel(k=1, x=2)], + r"row 0.*'value'.*mapping", + id="pydantic-discarded-alias", + ), pytest.param( [ _SerializedFrameModel(k=i, x=_PlainFrameModel(k=i, x=i + 2)) for i in range(102) ], - r"row 0.*serialized field names.*mapping", + r"'_foo'.*drop them first", id="pydantic-dynamic-serialization", ), pytest.param( @@ -552,13 +581,13 @@ def _model_with_explicit_attribute() -> _PlainFrameModel: ), pytest.param( [_FrameModel.model_validate({"k": 1, "x": 2, "extra": 3})], - r"row 0.*extra.*'extra'", + r"row 0.*'extra'.*mapping", id="legal-model-extra", ), pytest.param( - [(1, 2), (3, 4)], - r"row 0.*named fields", - id="unnamed-rows", + [{"k": 1, "x": 2}, (3, 4)], + r"row 1.*field names.*'k'.*'x'", + id="mixed-named-and-positional-input", ), ] @@ -1316,7 +1345,24 @@ def test_raw_reserved_names_precede_arrow_type_validation(kind: str) -> None: @pytest.mark.parametrize( - "kind", ["pandas-series", "pandas-index", "namedtuple", "numpy"] + "kind", + [ + "pandas-series", + "pandas-index", + "namedtuple", + "namedtuple-iterator", + "numpy", + "positional", + "positional-iterator", + "scalar", + "scalar-iterator", + "series-iterator", + "mixed-dataclasses", + "mixed-models", + "model-serializer", + "model-dump-override", + "model-computed-column", + ], ) @pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) def test_named_frame_inputs_keep_polars_conversion(kind: str, path: str) -> None: @@ -1325,6 +1371,13 @@ def test_named_frame_inputs_keep_polars_conversion(kind: str, path: str) -> None import numpy as np import pandas as pd + class DumpOverride(_SerializedFrameModel): + calls: ClassVar[list[int]] = [] + + def model_dump(self, **kwargs: Any) -> dict[str, Any]: + self.calls.append(self.k) + return {**super().model_dump(**kwargs), "k": self.k + 10} + batch: list[Any] if kind == "pandas-series": batch = [pd.Series([1, 2], name="k"), pd.Series([3, 4], name="x")] @@ -1333,21 +1386,45 @@ def test_named_frame_inputs_keep_polars_conversion(kind: str, path: str) -> None elif kind.startswith("namedtuple"): row = namedtuple("FrameRecord", ["k", "x"]) batch = [row(1, 3), row(2, 4)] + elif kind.startswith("positional"): + batch = [(1, 3), (2, 4)] + elif kind.startswith("scalar"): + batch = [1, 2] + elif kind == "series-iterator": + batch = [pl.Series("k", [1, 2]), pl.Series("x", [3, 4])] + elif kind == "mixed-dataclasses": + batch = [_FrameRow(1, 3), _EquivalentFrameRow(2, 4)] + elif kind == "mixed-models": + batch = [_PlainFrameModel(k=1, x=3), _EquivalentFrameModel(k=2, x=4)] + elif kind in {"model-serializer", "model-dump-override", "model-computed-column"}: + model = { + "model-serializer": _SerializedFrameModel, + "model-dump-override": DumpOverride, + "model-computed-column": _NestedComputedFrameModel, + }[kind] + batch = [model(k=i, x=_PlainFrameModel(k=i, x=i + 2)) for i in (1, 2)] else: batch = [np.array([1, 2]), np.array([3, 4])] - data = iter(batch) if kind == "namedtuple-iterator" else batch - frame = pl.DataFrame(batch) - key, value = frame.columns + use_iterator = kind.endswith("-iterator") + data = iter(batch) if use_iterator else batch + # Both sources passed the original input straight to Polars on main. + frame = pl.DataFrame(iter(batch) if use_iterator else batch) + key = frame.columns[0] + tags = [key] if frame.width > 1 else [] expected = frame.to_dicts() + expected_dump_calls = DumpOverride.calls.copy() + DumpOverride.calls.clear() if path == "frame": - source = DataFrameSource(data, [key], tag_only_columns=True) - control = DataFrameSource(frame, [key], tag_only_columns=True) + source = DataFrameSource(data, tags, tag_only_columns=True) + control = DataFrameSource(frame, tags, tag_only_columns=True) assert source.as_table().equals(control.as_table(), check_metadata=True) assert source.source_id == control.source_id + assert source.content_hash() == control.content_hash() + assert source.pipeline_hash() == control.pipeline_hash() else: source = PollingSource( - _Poll(None, data), [key], source_id="poll", record_id_columns=key + _Poll(None, data), tags, source_id="poll", record_id_columns=key ) if path == "poll-sync": assert source.as_table().to_pylist() == expected @@ -1356,11 +1433,12 @@ def test_named_frame_inputs_keep_polars_conversion(kind: str, path: str) -> None async def read() -> list[dict[str, Any]]: async with contextlib.aclosing(source.async_iter_data()) as rows: return [ - {key: tag.as_dict()[key], value: data.as_dict()[value]} + {**tag.as_dict(), **data.as_dict()} for tag, data in [await anext(rows) for _ in expected] ] assert asyncio.run(read()) == expected + assert DumpOverride.calls == expected_dump_calls @pytest.mark.parametrize("view", ["operator-replay", "operator-records", "derived"]) From a3d295ac021ed5a1a139cf59d22409a6d88b8977 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:02:03 -0800 Subject: [PATCH 12/21] fix(sources): preserve lossless mixed frame rows --- changelog.d/ITL-1165.md | 13 +- docs/concepts/sources.md | 7 + docs/dev/design_issues/ITL-1165-RN1.md | 6 +- src/orcapod/core/sources/data_frame_source.py | 126 +++++++++++-- src/orcapod/core/sources/dict_source.py | 24 ++- src/orcapod/core/sources/list_source.py | 3 +- src/orcapod/core/sources/stream_builder.py | 16 +- .../operators/test_streaming_joins.py | 12 +- .../sources/test_source_arrow_validation.py | 178 +++++++++++++++++- 9 files changed, 334 insertions(+), 51 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index 001d8c7b3..0b1a872e5 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -10,10 +10,11 @@ unavailable and loading would normally use a proxy. Rename the output key and update its downstream references in the pipeline before saving a new configuration. - Named Python row inputs to `DataFrameSource` and `PollingSource` need the same - field names in every non-null row. Typed rows of the same kind need the same - field layout. For sparse mappings, include missing keys with `None` where - appropriate. If a Pydantic model exposes fields that conversion would drop or - rename, pass mappings with the intended column names. + field names in every non-null named row. A leading namedtuple supplies names + for positional rows of the same width. For sparse mappings, include missing keys + with `None` where appropriate. If typed rows would move a value to another column + or lose precision, pass mappings with the intended names and a type that can + represent all values in the column. ### Fixed @@ -26,4 +27,6 @@ - Raw Arrow and polling sources report reserved column names before validating their Arrow types. - Frame and polling sources report reserved raw names before frame conversion, and - list sources check names in callback tags before projecting their fields. + list sources check names in each callback result before requesting more tags. + Dictionary sources check declared names before reading and check each row from a + custom collection before asking for the next. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 05f70d013..17837574e 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -218,6 +218,13 @@ categorical column) is not a dictionary column: it is a library value, stored an (see [Arrays and other library values](arrays.md)), and is accepted. Supporting dictionary-encoded columns themselves is future work (ITL-1277). +Named Python rows in `DataFrameSource` and `PollingSource` must supply the same fields. +For sparse mappings, include every key and use `None` for missing values. A namedtuple +can supply the column names for positional rows of the same width. Different model or +dataclass classes can share a batch when conversion keeps each field in its named +column and preserves its value. If conversion would lose a value, the error identifies +the column. Use a common type that can represent all its values exactly. + ### A CSV file's types: `schema=` A CSV file holds text only, so `CSVSource` infers each column's type from the file, and diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index e9afcf669..ee4d652a5 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -33,7 +33,11 @@ functions before caching or emission and user keys read from stored results. Ope caches and cached sources check user columns before exposing rows, including when an operator's records feed a derived source. Frame and polling sources check names before conversion can relabel them, and list -sources validate callback tags before discarding metadata. A saved operator schema +sources validate callback tags before discarding metadata or asking for further tags. +DictSource checks declared schemas before consuming rows and checks each row of a +custom collection before advancing it. Frame batches keep matching named layouts when +conversion preserves the values, and reject a mixed typed input if conversion loses +a value. A saved operator schema identifies legacy user names even when a mixed table alone cannot distinguish them from system tags. Custom system-tag declarations retain their existing validation. diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index da63bd4ee..3de69e058 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -1,6 +1,7 @@ from __future__ import annotations import logging +import math from collections.abc import ( Callable, Collection, @@ -11,6 +12,7 @@ Sized, ) from dataclasses import fields, is_dataclass +from enum import Enum from itertools import chain, repeat from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, cast @@ -66,11 +68,13 @@ class _FrameModelRow(BaseModel): "_original", "_names", "_system_tag_columns", + "_dumped_fields", ) if TYPE_CHECKING: _original: BaseModel _names: set[str] _system_tag_columns: Collection[str] + _dumped_fields: dict[str, object] | None @classmethod def from_model( @@ -84,6 +88,7 @@ def from_model( object.__setattr__(row, "_original", value) object.__setattr__(row, "_names", set(names)) object.__setattr__(row, "_system_tag_columns", system_tag_columns) + object.__setattr__(row, "_dumped_fields", None) return row @override @@ -117,7 +122,15 @@ def model_dump(self, **kwargs: object) -> dict[str, object]: f"{sorted(self._names - names)!r}, extra " f"{sorted(names - self._names)!r}. Use a mapping." ) - return cast("dict[str, object]", fields) + result = cast("dict[str, object]", fields) + object.__setattr__(self, "_dumped_fields", result) + return result + + def _frame_fields(self) -> Mapping[str, object]: + """Return the fields Polars read, including any serializer changes.""" + if self._dumped_fields is not None: + return self._dumped_fields + return vars(self._original) def _describe_model_row(value: BaseModel) -> _FrameRow: @@ -210,6 +223,19 @@ def _checked_frame_rows( names = set(row.exposed_names) if first is None: first, expected = row, names + positional_tail = ( + first.kind == "namedtuple" + and row.kind == "positional" + and isinstance(row.value, (tuple, list, np.ndarray)) + and ( + not isinstance(row.value, np.ndarray) + or (row.value.ndim == 1 and row.value.dtype.names is None) + ) + and len(row.value) == len(first.names) + ) + if positional_tail: + yield row + continue if names != expected: raise InputValidationError( f"Source row {index} has different field names. " @@ -218,7 +244,7 @@ def _checked_frame_rows( "fields with None where appropriate and remove unintended fields." ) if row.kind != first.kind or ( - row.kind != "mapping" and row.names != first.names + row.kind == "namedtuple" and row.names != first.names ): raise InputValidationError( f"Source row {index} has a different layout " @@ -229,6 +255,79 @@ def _checked_frame_rows( yield row +def _same_frame_value(supplied: Any, converted: Any) -> bool: + """Compare converted values without rounding mixed numeric inputs.""" + if supplied is converted: + return True + if isinstance(supplied, np.generic): + supplied = supplied.item() + if isinstance(supplied, Enum): + supplied = supplied.value + if is_dataclass(supplied) and not isinstance(supplied, type): + supplied = { + field.name: getattr(supplied, field.name) for field in fields(supplied) + } + if isinstance(supplied, BaseModel): + supplied = vars(supplied) + if isinstance(supplied, Mapping) and isinstance(converted, Mapping): + return all( + _same_frame_value(value, converted.get(name)) and name in converted + for name, value in supplied.items() + ) and all( + name in supplied or value is None for name, value in converted.items() + ) + if isinstance(supplied, (list, tuple, np.ndarray)) and isinstance(converted, list): + return len(supplied) == len(converted) and all( + _same_frame_value(left, right) for left, right in zip(supplied, converted) + ) + if isinstance(supplied, float): + if math.isnan(supplied): + return isinstance(converted, float) and math.isnan(converted) + if supplied == 0 and math.copysign(1, supplied) < 0: + return ( + isinstance(converted, float) + and math.copysign(1, converted) < 0 + and converted == 0 + ) + equal = supplied == converted + return isinstance(equal, (bool, np.bool_)) and bool(equal) + + +def _require_exact_mixed_rows( + frame: pl.DataFrame, + rows: list[tuple[int, _FrameRow, Any]], +) -> None: + """Check a mixed batch against the values each input column supplied.""" + _, first, _ = rows[0] + if all(type(row.value) is type(first.value) for _, row, _ in rows): + return + names = frame.columns + values = [ + column.to_list() if column.dtype == pl.Object else column.to_arrow().to_pylist() + for column in frame + ] + for (index, row, value), converted in zip(rows, zip(*values), strict=True): + if isinstance(value, _FrameModelRow): + supplied = value._frame_fields() + elif row.kind == "dataclass": + supplied = {name: getattr(value, name) for name in row.names} + else: + supplied = dict(zip(first.names, value, strict=True)) + for name, item in zip(names, converted, strict=True): + if _same_frame_value(supplied[name], item): + continue + if row.kind == "dataclass" and row.names != first.names: + raise InputValidationError( + f"Source row {index} has a different layout ({row.names!r}) " + f"from the first row ({first.names!r}), and conversion changed " + f"column {name!r}. Use mappings for these rows." + ) + raise InputValidationError( + f"Source row {index} column {name!r} could not be converted " + "without losing its value. Use values that convert exactly to one type." + ) + + def _require_materialized_row_names( rows: Sequence[_FrameRow | None], system_tag_columns: Collection[str] ) -> None: @@ -276,17 +375,20 @@ def _frame_from_rows( return pl.DataFrame(list(values) if materialized else values) null_positions: set[int] = set() + typed_rows: list[tuple[int, _FrameRow, Any]] = [] def typed_values() -> Iterator[Any]: for index, row in enumerate(checked): if row is None: null_positions.add(index) - elif isinstance(row.value, BaseModel): - yield _FrameModelRow.from_model( + continue + value = row.value + if isinstance(value, BaseModel): + value = _FrameModelRow.from_model( row.value, row.exposed_names, system_tag_columns ) - else: - yield row.value + typed_rows.append((index, row, value)) + yield value typed = typed_values() frame = pl.DataFrame(list(typed) if materialized else typed) @@ -302,6 +404,7 @@ def typed_values() -> Iterator[Any]: f"Source row {leading_nulls} declares fields {first.names!r}, " f"but Polars returned {frame.columns!r}. Use mappings for these rows." ) + _require_exact_mixed_rows(frame, typed_rows) if null_positions: indices = iter(range(frame.height)) positions = [ @@ -386,12 +489,11 @@ def source_dataframe( class DataFrameSource(RootSource): """A source backed by a Polars DataFrame or supported tabular or column input. - Named Python rows must supply the same fields. Namedtuple, dataclass and - Pydantic rows can use different classes of the same kind with the same field - layout. Names exposed by a model must be retained as columns, including when - the model is serialized. Positional and scalar inputs use Polars' column - names. A ``None`` row keeps its position as a null row. Named Series can be - passed as a sequence or iterator of columns. + Named Python rows must supply the same fields. Typed rows can use different + classes of the same kind when conversion keeps every field and value in its + intended column. A namedtuple can be followed by positional rows of the same + width. Entirely unnamed input uses Polars' column names. A ``None`` row keeps + its position as a null row. Named Series can be passed as columns. The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index ce60876bc..7b76ba322 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -11,7 +11,6 @@ from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, require_source_column_names, - require_source_row_names, require_supported_nullable_types, ) from orcapod.types import DataValue, SchemaLike @@ -65,18 +64,31 @@ def __init__( # Accept either a Python SchemaLike (Mapping[str, type]) or a # pa.Schema directly via data_schema; route to the converter accordingly. - rows = [dict(row) for row in data] - require_source_row_names(rows, system_tag_columns) + if data_schema is not None: + names = ( + data_schema.names + if isinstance(data_schema, pa.Schema) + else data_schema.keys() + ) + require_source_column_names(names, system_tag_columns) + if type(data) in (list, tuple) and all(type(row) is dict for row in data): + # All keys are already available without advancing a user iterator. + require_source_column_names( + {name for row in data for name in row}, system_tag_columns + ) + rows = [dict(row) for row in data] + else: + rows = [] + for row in data: + require_source_column_names(row.keys(), system_tag_columns) + rows.append(dict(row)) if isinstance(data_schema, pa.Schema): - require_source_column_names(data_schema.names, system_tag_columns) require_supported_nullable_types(data_schema) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, arrow_schema=data_schema, ) else: - if data_schema is not None: - require_source_column_names(data_schema.keys(), system_tag_columns) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, python_schema=data_schema, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 64e617f8c..7afdb2846 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -8,7 +8,6 @@ SourceStreamBuilder, normalize_record_id_columns, require_source_column_names, - require_source_row_names, ) from orcapod.protocols.core_protocols import TagProtocol from orcapod.types import SchemaLike @@ -111,9 +110,9 @@ def __init__( if hasattr(tag_fields, "as_dict"): tag_fields = tag_fields.as_dict() row = dict(tag_fields) + require_source_column_names(row.keys()) row[name] = element rows.append(row) - require_source_row_names(rows) tag_columns = ( list(self._expected_tag_keys) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 1db152238..cc8709421 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, Iterable, Mapping, Sequence +from collections.abc import Collection, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -84,20 +84,6 @@ def require_source_column_names( ) from exc -def require_source_row_names( - rows: Iterable[Mapping[str, object]], system_tag_columns: Collection[str] = () -) -> None: - """Validate all row keys before an input schema can infer or project fields. - - Args: - rows: Raw row mappings. - system_tag_columns: Columns nominated as custom system tags. - """ - require_source_column_names( - {name for row in rows for name in row}, system_tag_columns - ) - - def require_custom_system_tags( table: pa.Table, names: Collection[str], diff --git a/tests/test_core/operators/test_streaming_joins.py b/tests/test_core/operators/test_streaming_joins.py index 8422ffbb5..abd5480a1 100644 --- a/tests/test_core/operators/test_streaming_joins.py +++ b/tests/test_core/operators/test_streaming_joins.py @@ -1123,7 +1123,7 @@ def test_an_empty_run_ends_with_the_types_of_the_sync_result( @pytest.mark.parametrize("row_count", [0, 2]) -@pytest.mark.parametrize("column", ["k", "x", "__unused"]) +@pytest.mark.parametrize("column", ["k", "x", "unused", "__unused"]) @pytest.mark.parametrize( "bad_type", [ @@ -1152,10 +1152,12 @@ def test_a_source_refuses_a_null_typed_column( [arrays[name] for name in order], schema=pa.schema([fields[name] for name in order]), ) - with pytest.raises( - InputValidationError, - match=rf"{column!r}.*declare a supported nullable type", - ): + message = ( + rf"{column!r}.*drop them first" + if column == "__unused" + else rf"{column!r}.*declare a supported nullable type" + ) + with pytest.raises(InputValidationError, match=message): ArrowTableSource( table, tag_columns=["k", "g"], tag_only_columns=True, source_id="s" ) diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index baa6c1d68..93219db31 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -227,6 +227,41 @@ def test_dict_source_refuses_reserved_fields_omitted_from_schema( DictSource(rows, tag_columns=TAGS, tag_only_columns=True, data_schema=schema) +class _UnreadableRows(Collection[dict[str, int]]): + def __init__(self, first: dict[str, int] | None = None) -> None: + self.first = first + + def __contains__(self, value: object) -> bool: + return value == self.first + + def __len__(self) -> int: + return 2 if self.first is not None else 1 + + def __iter__(self) -> Iterator[dict[str, int]]: + if self.first is not None: + yield self.first + raise AssertionError("the source read past a reserved name") + + +@pytest.mark.parametrize( + "schema", + [ + None, + {"_raw": int, "_also_raw": int}, + pa.schema([("_raw", pa.int64()), ("_also_raw", pa.int64())]), + ], + ids=["row", "python-schema", "arrow-schema"], +) +def test_dict_source_reports_known_reserved_names_before_reading_further( + schema: dict[str, type] | pa.Schema | None, +) -> None: + first = {"x": 1, "_raw": 2, "_also_raw": 3} if schema is None else None + with pytest.raises( + InputValidationError, match="'_also_raw'.*'_raw'.*rename.*drop them first" + ): + DictSource(_UnreadableRows(first), data_schema=schema) + + def test_csv_refuses_reserved_declared_columns_before_parsing_values( tmp_path: Path, ) -> None: @@ -406,6 +441,23 @@ class _ReorderedFrameRow: k: int +@dataclass +class _NestedFrameValue: + value: int + + +@dataclass +class _NestedFrameRow: + k: int + x: _NestedFrameValue + + +@dataclass +class _ReorderedNestedFrameRow: + x: _NestedFrameValue + k: int + + @dataclass class _TypedFrameRow: k: int @@ -701,11 +753,7 @@ def test_list_source_refuses_reserved_value_name_even_without_arrow_field( def test_list_source_refuses_reserved_tags_omitted_from_schema() -> None: def tags(value: int, index: int) -> dict[str, int]: - return ( - {"k": index, "g": value, "_foo": value} - if index - else {"k": index, "g": value, "_source_x": value} - ) + return {"k": index, "g": value, "_foo": value, "_source_x": value} with pytest.raises( InputValidationError, match="'_foo'.*'_source_x'.*drop them first" @@ -729,6 +777,17 @@ def tags(value: int, index: int) -> dict[str, int]: ListSource("value", [10, 20], tag_function=tags) +def test_list_source_reports_reserved_dict_tags_before_next_callback() -> None: + def tags(value: int, index: int) -> dict[str, int]: + assert index == 0, "the source called another callback after a reserved name" + return {"_raw": value, "_also_raw": value} + + with pytest.raises( + InputValidationError, match="'_also_raw'.*'_raw'.*rename.*drop them first" + ): + ListSource("value", [10, 20], tag_function=tags) + + def test_rereading_an_orcapod_table_requires_dropping_system_columns() -> None: source = DictSource( [ @@ -1441,6 +1500,115 @@ async def read() -> list[dict[str, Any]]: assert DumpOverride.calls == expected_dump_calls +@pytest.mark.parametrize( + "kind", ["tuple", "list", "numpy", "reordered-model", "reordered-nested-dataclass"] +) +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +def test_frame_preserves_mixed_rows_with_the_same_columns( + kind: str, iterator: bool, path: str +) -> None: + from collections import namedtuple + + import numpy as np + + class ReverseModel(BaseModel): + x: int + k: int + + rows: list[Any] + if kind == "reordered-model": + rows = [_PlainFrameModel(k=1, x=2), ReverseModel(k=3, x=4)] + elif kind == "reordered-nested-dataclass": + rows = [ + _NestedFrameRow(1, _NestedFrameValue(2)), + _ReorderedNestedFrameRow(_NestedFrameValue(4), 3), + ] + else: + record = namedtuple("Record", ["k", "x"]) + rows = [ + record(1, 2), + {"tuple": tuple, "list": list, "numpy": np.array}[kind]((3, 4)), + ] + frame = pl.DataFrame(iter(rows) if iterator else rows) + expected = [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + if kind == "reordered-nested-dataclass": + expected = [{"k": 1, "x": {"value": 2}}, {"k": 3, "x": {"value": 4}}] + assert frame.to_dicts() == expected + data = iter(rows) if iterator else rows + if path == "frame": + source = DataFrameSource(data, ["k"], tag_only_columns=True) + control = DataFrameSource(frame, ["k"], tag_only_columns=True) + assert source.as_table().equals(control.as_table(), check_metadata=True) + assert source.source_id == control.source_id + assert source.content_hash() == control.content_hash() + assert source.pipeline_hash() == control.pipeline_hash() + else: + poll = PollingSource( + _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" + ) + assert _read_frame_poll(poll, path, 2) == expected + + +def _read_frame_poll( + poll: PollingSource[int], path: str, count: int +) -> list[dict[str, Any]]: + if path == "poll-sync": + return poll.as_table().to_pylist() + + async def read() -> list[dict[str, Any]]: + async with contextlib.aclosing(poll.async_iter_data()) as rows: + return [ + {**tag.as_dict(), **data.as_dict()} + for tag, data in [await anext(rows) for _ in range(count)] + ] + + return asyncio.run(read()) + + +@pytest.mark.parametrize("kind", ["dataclass", "model"]) +@pytest.mark.parametrize("value", [4.9, 4.0], ids=["lossy", "exact"]) +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +def test_frame_refuses_lossy_mixed_typed_values( + kind: str, value: float, iterator: bool, path: str +) -> None: + @dataclass + class FloatRow: + k: int + x: float + + class FloatModel(BaseModel): + k: int + x: float + + rows = ( + [_FrameRow(1, 2), FloatRow(3, value)] + if kind == "dataclass" + else [_PlainFrameModel(k=1, x=2), FloatModel(k=3, x=value)] + ) + data = iter(rows) if iterator else rows + expected = [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + + def read() -> list[dict[str, Any]]: + if path == "frame": + return ( + DataFrameSource(data, ["k"], tag_only_columns=True) + .as_table() + .to_pylist() + ) + poll = PollingSource( + _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" + ) + return _read_frame_poll(poll, path, 2) + + if value == 4.0: + assert read() == expected + else: + with pytest.raises(InputValidationError, match=r"column 'x'.*without losing"): + read() + + @pytest.mark.parametrize("view", ["operator-replay", "operator-records", "derived"]) def test_operator_storage_refuses_reserved_user_columns( view: str, monkeypatch: pytest.MonkeyPatch From fbac66e7568ed81a1aed26fb42640442a81f7184 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:46:20 -0800 Subject: [PATCH 13/21] fix(sources): restore DataFrameSource row conversion --- changelog.d/ITL-1165.md | 11 +- docs/concepts/sources.md | 5 +- docs/dev/design_issues/ITL-1165-RN1.md | 12 +- src/orcapod/core/sources/data_frame_source.py | 20 +- .../sources/test_source_arrow_validation.py | 199 ++++++++++++------ 5 files changed, 156 insertions(+), 91 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index 0b1a872e5..e4745d27f 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -9,7 +9,7 @@ is refused when the pod is rebuilt, including when the original callable is unavailable and loading would normally use a proxy. Rename the output key and update its downstream references in the pipeline before saving a new configuration. -- Named Python row inputs to `DataFrameSource` and `PollingSource` need the same +- Named Python rows returned to `PollingSource` need the same field names in every non-null named row. A leading namedtuple supplies names for positional rows of the same width. For sparse mappings, include missing keys with `None` where appropriate. If typed rows would move a value to another column @@ -26,7 +26,8 @@ namespace before presenting their rows. - Raw Arrow and polling sources report reserved column names before validating their Arrow types. -- Frame and polling sources report reserved raw names before frame conversion, and - list sources check names in each callback result before requesting more tags. - Dictionary sources check declared names before reading and check each row from a - custom collection before asking for the next. +- `DataFrameSource` checks the column names of input frames and of the frame inferred + from Python data. `PollingSource` checks batch names before frame conversion. + List sources check names in each callback result before requesting more tags. + Dictionary sources check declared names before reading and each row from a custom + collection before asking for the next. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 17837574e..efb884616 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -218,7 +218,10 @@ categorical column) is not a dictionary column: it is a library value, stored an (see [Arrays and other library values](arrays.md)), and is accepted. Supporting dictionary-encoded columns themselves is future work (ITL-1277). -Named Python rows in `DataFrameSource` and `PollingSource` must supply the same fields. +`DataFrameSource` uses Polars to infer the columns of Python inputs and checks the +resulting column names for reserved names. + +Named Python rows returned to `PollingSource` must supply the same fields. For sparse mappings, include every key and use `None` for missing values. A namedtuple can supply the column names for positional rows of the same width. Different model or dataclass classes can share a batch when conversion keeps each field in its named diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index ee4d652a5..ba66dd657 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -32,12 +32,12 @@ new operator names and function pod output keys, including user data returned by functions before caching or emission and user keys read from stored results. Operator caches and cached sources check user columns before exposing rows, including when an operator's records feed a derived source. -Frame and polling sources check names before conversion can relabel them, and list -sources validate callback tags before discarding metadata or asking for further tags. -DictSource checks declared schemas before consuming rows and checks each row of a -custom collection before advancing it. Frame batches keep matching named layouts when -conversion preserves the values, and reject a mixed typed input if conversion loses -a value. A saved operator schema +`DataFrameSource` checks the names on incoming frames and on the frame Polars infers +from Python inputs. Polling checks batch names before conversion. Polling batches keep +matching named layouts when conversion preserves the values and reject a mixed typed +input if conversion loses a value. List sources validate callback tags before discarding +metadata or asking for further tags. DictSource checks declared schemas before consuming +rows and checks each row of a custom collection before advancing it. A saved operator schema identifies legacy user names even when a mixed table alone cannot distinguish them from system tags. Custom system-tag declarations retain their existing validation. diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 3de69e058..ee5d0bd04 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -456,7 +456,7 @@ def checked_columns() -> Iterator[Any]: def source_dataframe( data: FrameInitTypes, system_tag_columns: Collection[str] = () ) -> pl.DataFrame: - """Validate named row layouts before Polars can project or relabel fields. + """Convert a polling batch, validating layouts before Polars infers columns. Args: data: Tabular or column input, or Python rows with a consistent named layout. @@ -487,16 +487,12 @@ def source_dataframe( class DataFrameSource(RootSource): - """A source backed by a Polars DataFrame or supported tabular or column input. - - Named Python rows must supply the same fields. Typed rows can use different - classes of the same kind when conversion keeps every field and value in its - intended column. A namedtuple can be followed by positional rows of the same - width. Entirely unnamed input uses Polars' column names. A ``None`` row keeps - its position as a null row. Named Series can be passed as columns. + """A source backed by a Polars DataFrame or other Polars-compatible data. The DataFrame is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). + Column names beginning with an underscore are reserved. For Python row + inputs, the check applies to the columns inferred by Polars. Data-tags (ITL-1023): every declared tag column is a data-tag by default, also a data column of the same name. ``tag_only_columns`` (keyword-only) names the @@ -535,7 +531,13 @@ def __init__( if schema is not None: require_source_column_names(schema.names, system_tag_columns) - df = source_dataframe(data, system_tag_columns) + if isinstance(data, pd.DataFrame): + require_source_column_names( + [str(name) for name in data.columns], system_tag_columns + ) + elif isinstance(data, (pa.Table, pa.RecordBatch)): + require_source_column_names(data.schema.names, system_tag_columns) + df = pl.DataFrame(data) require_source_column_names(df.columns, system_tag_columns) # Convert any Object-dtype columns to Arrow-compatible types. diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 93219db31..a9f664059 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -5,11 +5,13 @@ import asyncio import contextlib import sqlite3 +from array import array +from collections import UserList, deque from re import escape from collections.abc import Collection, Iterator from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Any, ClassVar, TypedDict +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, TypedDict import deltalake import polars as pl @@ -321,37 +323,45 @@ def build() -> CSVSource: build() -def test_frame_stops_at_first_reserved_series_in_iterator() -> None: +def test_polling_stops_at_first_reserved_series_in_iterator() -> None: def columns() -> Iterator[pl.Series]: yield pl.Series("k", [1, 2]) yield pl.Series("_foo", [3, 4]) pytest.fail("reserved columns must stop iteration") with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): - DataFrameSource(columns()) + PollingSource( + _Poll(None, columns()), ["k"], source_id="poll", record_id_columns="k" + ).as_table() @pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) -def test_positional_frame_input_checks_following_row_names(as_iterator: bool) -> None: +def test_dataframe_source_uses_inferred_positional_column_names( + as_iterator: bool, +) -> None: from collections import namedtuple row = namedtuple("ReservedRecord", ["k", "_hidden"], rename=True) rows: list[Any] = [(1, 2), row(3, 4)] - with pytest.raises(InputValidationError, match="'_1'.*drop them first"): - DataFrameSource(iter(rows) if as_iterator else rows) + expected = pl.DataFrame(iter(rows) if as_iterator else rows) + source = DataFrameSource(iter(rows) if as_iterator else rows) + assert source.as_table().to_pylist() == expected.to_dicts() @pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) -def test_dataframe_source_adds_row_context_to_field_name_error( +def test_polling_adds_row_context_to_field_name_error( as_iterator: bool, ) -> None: rows: list[Any] = [{"k": 1, "g": "a", "x": 3, "y": 5}, {1: 2}] with pytest.raises( InputValidationError, match=r"Source row 1.*needs string field names" ) as info: - _ = DataFrameSource( - iter(rows) if as_iterator else rows, tag_columns=TAGS, tag_only_columns=True - ) + PollingSource( + _Poll(None, iter(rows) if as_iterator else rows), + TAGS, + source_id="poll", + record_id_columns="k", + ).as_table() cause = info.value.__cause__ assert isinstance(cause, InputValidationError) assert str(cause) == "needs string field names." @@ -368,16 +378,20 @@ def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: @pytest.mark.parametrize("iterable", [list, iter], ids=["sequence", "iterator"]) -def test_dataframe_source_checks_fields_beyond_polars_inference(iterable) -> None: - message = "'_foo'.*drop them first" - if iterable is list: - message = "'_foo'.*'_source_x'.*drop them first" - with pytest.raises(InputValidationError, match=message): - DataFrameSource( - iterable(_late_reserved_rows(False)), - tag_columns=TAGS, - tag_only_columns=True, - ) +def test_dataframe_source_checks_inferred_column_names(iterable) -> None: + rows = [{"k": 1, "x": 2, "_foo": 3, "_source_x": 4}] + with pytest.raises( + InputValidationError, match="'_foo'.*'_source_x'.*drop them first" + ): + DataFrameSource(iterable(rows), tag_columns=["k"], tag_only_columns=True) + + +@pytest.mark.parametrize("iterable", [list, iter], ids=["sequence", "iterator"]) +def test_dataframe_source_preserves_polars_inference_window(iterable) -> None: + rows = _late_reserved_rows(False) + expected = pl.DataFrame(iterable(rows)) + source = DataFrameSource(iterable(rows), tag_columns=TAGS, tag_only_columns=True) + assert source.as_table().to_pylist() == expected.select(*TAGS, "x", "y").to_dicts() def test_dataframe_source_preserves_inference_for_single_pass_rows() -> None: @@ -395,7 +409,7 @@ def rows() -> Iterator[dict[str, int]]: assert source.source_id == expected.source_id -def test_dataframe_source_stops_after_the_first_invalid_iterator_row() -> None: +def test_polling_stops_after_the_first_invalid_iterator_row() -> None: def rows() -> Iterator[dict[str, int]]: yield {"k": 1, "x": 2, "_foo": 3, "_source_x": 4} pytest.fail("reserved fields must stop iteration") @@ -403,7 +417,9 @@ def rows() -> Iterator[dict[str, int]]: with pytest.raises( InputValidationError, match="'_foo'.*'_source_x'.*drop them first" ): - DataFrameSource(rows(), tag_columns=["k"], tag_only_columns=True) + PollingSource( + _Poll(None, rows()), ["k"], source_id="poll", record_id_columns="k" + ).as_table() @dataclass @@ -644,15 +660,6 @@ def _model_with_explicit_attribute() -> _PlainFrameModel: ] -@pytest.mark.parametrize("rows, message", FRAME_ROW_CASES) -@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) -def test_dataframe_source_checks_named_row_shapes( - rows: list[Any], message: str, use_iterator: bool -) -> None: - with pytest.raises(InputValidationError, match=message): - DataFrameSource(iter(rows) if use_iterator else rows) - - @pytest.mark.parametrize( ("row_type", "x_values", "arrow_type"), [ @@ -701,18 +708,11 @@ def test_homogeneous_typed_rows_keep_schema_and_identity( ) -@pytest.mark.parametrize( - "rows", - [ - [None, {"k": 1, "x": 2}, None, {"x": 4, "k": 3}], - [None, _FrameRow(1, 2), None, _FrameRow(3, 4)], - ], - ids=["mapping", "dataclass"], -) @pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) def test_frame_rows_keep_null_positions_and_match_mapping_fields_by_name( - rows: list[Any], use_iterator: bool + use_iterator: bool, ) -> None: + rows = [None, {"k": 1, "x": 2}, None, {"x": 4, "k": 3}] source = DataFrameSource( iter(rows) if use_iterator else rows, tag_columns=["k"], tag_only_columns=True ) @@ -1105,11 +1105,15 @@ async def close(self) -> None: @pytest.mark.parametrize("rows, message", FRAME_ROW_CASES) @pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) def test_polling_checks_named_row_shapes( - rows: list[Any], message: str, use_async: bool + rows: list[Any], message: str, use_async: bool, use_iterator: bool ) -> None: source = PollingSource( - _Poll(None, rows), ["k"], source_id="poll", record_id_columns="k" + _Poll(None, iter(rows) if use_iterator else rows), + ["k"], + source_id="poll", + record_id_columns="k", ) async def read_first() -> None: @@ -1500,6 +1504,78 @@ async def read() -> list[dict[str, Any]]: assert DumpOverride.calls == expected_dump_calls +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize( + "tail", + [ + range(3, 5), + deque([3, 4]), + array("q", [3, 4]), + UserList([3, 4]), + memoryview(bytes([3, 4])), + bytes([3, 4]), + bytearray([3, 4]), + ], + ids=lambda tail: type(tail).__name__, +) +def test_dataframe_source_accepts_polars_positional_tails( + tail: object, iterator: bool +) -> None: + class Reading(NamedTuple): + k: int + x: int + + rows: list[Any] = [Reading(1, 2), tail] + source = DataFrameSource( + iter(rows) if iterator else rows, ["k"], tag_only_columns=True + ) + assert source.as_table().to_pylist() == [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + + +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("alias", ["k", "other"], ids=["overlapping", "distinct"]) +def test_dataframe_source_preserves_flat_model_columns( + alias: str, iterator: bool +) -> None: + class Reading(_PlainFrameModel): + model_config = ConfigDict(serialize_by_alias=True) + x: int = Field(serialization_alias=alias) + + rows = [Reading(k=1, x=2), Reading(k=3, x=4)] + source = DataFrameSource( + iter(rows) if iterator else rows, ["k"], tag_only_columns=True + ) + assert source.as_table().to_pylist() == [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + + +@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize( + "mixed_classes", [False, True], ids=["same-class", "mixed-class"] +) +def test_dataframe_source_preserves_polars_numeric_inference( + mixed_classes: bool, iterator: bool +) -> None: + class Reading(NamedTuple): + k: int + x: int | float + + class OtherReading(NamedTuple): + k: int + x: int | float + + second = OtherReading if mixed_classes else Reading + rows = [Reading(1, 9_007_199_254_740_993), second(2, 1.5)] + source = DataFrameSource( + iter(rows) if iterator else rows, ["k"], tag_only_columns=True + ) + table = source.as_table() + assert table.schema.field("x").type == pa.float64() + assert table.to_pylist() == [ + {"k": 1, "x": 9_007_199_254_740_992.0}, + {"k": 2, "x": 1.5}, + ] + + @pytest.mark.parametrize( "kind", ["tuple", "list", "numpy", "reordered-model", "reordered-nested-dataclass"] ) @@ -1569,8 +1645,8 @@ async def read() -> list[dict[str, Any]]: @pytest.mark.parametrize("kind", ["dataclass", "model"]) @pytest.mark.parametrize("value", [4.9, 4.0], ids=["lossy", "exact"]) @pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) -@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) -def test_frame_refuses_lossy_mixed_typed_values( +@pytest.mark.parametrize("path", ["poll-sync", "poll-async"]) +def test_polling_refuses_lossy_mixed_typed_values( kind: str, value: float, iterator: bool, path: str ) -> None: @dataclass @@ -1591,12 +1667,6 @@ class FloatModel(BaseModel): expected = [{"k": 1, "x": 2}, {"k": 3, "x": 4}] def read() -> list[dict[str, Any]]: - if path == "frame": - return ( - DataFrameSource(data, ["k"], tag_only_columns=True) - .as_table() - .to_pylist() - ) poll = PollingSource( _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" ) @@ -1676,12 +1746,12 @@ def test_cached_source_refuses_reserved_stored_user_columns() -> None: cached.as_table() -@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) +@pytest.mark.parametrize("path", ["poll-sync", "poll-async"]) @pytest.mark.parametrize( ("kind", "field"), [("namedtuple", "_1"), ("namedtuple", "label"), ("series", "_hidden")], ) -def test_numpy_first_batch_refuses_names_that_would_be_lost( +def test_polling_numpy_first_batch_refuses_names_that_would_be_lost( path: str, kind: str, field: str ) -> None: from collections import namedtuple @@ -1700,24 +1770,13 @@ def test_numpy_first_batch_refuses_names_that_would_be_lost( batch = [np.array([1, 2]), column] with pytest.raises(InputValidationError, match=escape(repr(field))): - if path == "frame": - DataFrameSource(batch) - else: - source = PollingSource( - _Poll(None, batch), - ["column_0"], - source_id="poll", - record_id_columns="column_0", - ) - if path == "poll-sync": - source.as_table() - else: - - async def read() -> None: - async with contextlib.aclosing(source.async_iter_data()) as rows: - await anext(rows) - - asyncio.run(read()) + source = PollingSource( + _Poll(None, batch), + ["column_0"], + source_id="poll", + record_id_columns="column_0", + ) + _read_frame_poll(source, path, 2) @pytest.mark.parametrize("system_field", ["_tag_fake", "_tag::fake"]) From a941f557ba7673bb7185f332f574ab707d3bc01b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:29:07 -0800 Subject: [PATCH 14/21] fix(sources): validate reserved names on the pinned SpiralDB snapshot --- docs/dev/design_issues/ITL-1165-RN1.md | 1 + .../core/sources/spiraldb_table_source.py | 9 ++++- src/orcapod/databases/spiraldb_connector.py | 7 +++- .../sources/test_source_arrow_validation.py | 39 +++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index ba66dd657..63ce30d1d 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -40,4 +40,5 @@ metadata or asking for further tags. DictSource checks declared schemas before c rows and checks each row of a custom collection before advancing it. A saved operator schema identifies legacy user names even when a mixed table alone cannot distinguish them from system tags. +SpiralDB validates the pinned snapshot's column names for historical reads. Custom system-tag declarations retain their existing validation. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 2464d78c5..b52db8149 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -386,7 +386,14 @@ def __init__( "record_id_columns=[...]." ) self._table_id = table.table_id - schema = table.arrow_schema() + schema = table.arrow_schema(asof=asof) + if asof is not None and set(schema.names) == set(primary_key): + # Before the first write SpiralDB exposes only the keys. Keep the + # empty result's data columns from the current schema. + require_source_column_names(schema.names, system_tag_columns) + schema = arrow_utils.drop_system_columns( + table.arrow_schema().empty_table() + ).schema require_supported_nullable_types(schema) # One version for every read of this source object. A given version is # used as it is; a table that was never written has no version to pin. diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 056090f6b..2498df330 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -499,14 +499,17 @@ def key_columns(self) -> list[str]: """The primary-key column names in declaration order (no round trip).""" return list(self._table.key_columns) - def arrow_schema(self) -> pa.Schema: + def arrow_schema(self, *, asof: int | None = None) -> pa.Schema: """The schema of the batches ``scan_batches`` yields (``get_arrow_schema``). + Args: + asof: Read this version, or the version of the lookup if omitted. + Raises: TableSchemaError: If the table's row in the schema table cannot be read, or disagrees with the table. """ - return self._reading(self._table).schema + return self._reading(self._at(asof)).schema def version(self) -> int: """The table's version at the lookup (``get_table_version``).""" diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index a9f664059..c405f5be9 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -1391,6 +1391,35 @@ def test_spiral_validates_reserved_null_in_an_empty_scan_batch( source.as_table() +def test_spiral_validates_reserved_names_at_the_pinned_version(tmp_path: Path) -> None: + """Columns added later cannot block an older SpiralDB snapshot.""" + rows = pa.table({"k": ["a"], "x": [1]}) + with fake_spiral_sdk.install(tmp_path): + project = fake_spiral_sdk.ExternalProject("project") + external = project.create_table( + "default.rows", key_schema=pa.schema([rows.schema.field("k")]) + ) + external.write(rows) + before = external.last_modified_at() + external.write(pa.table({"k": ["b"], "x": [2], "_tag_extra": [3]})) + after = external.last_modified_at() + + historical = SpiralDBTableSource( + "project", "rows", asof=before, tag_only_columns=True + ) + assert historical.as_table().to_pylist() == [{"k": "a", "x": 1}] + empty = SpiralDBTableSource("project", "rows", asof=0, tag_only_columns=True) + assert empty.as_table().column_names == ["k", "x"] + assert empty.as_table().num_rows == 0 + for version in (None, after): + with pytest.raises( + InputValidationError, match="'_tag_extra'.*drop them first" + ): + SpiralDBTableSource( + "project", "rows", asof=version, tag_only_columns=True + ) + + @pytest.mark.parametrize( "kind", ["arrow", "arrow-infer", "dict-schema", "frame-schema", "poll-declaration"] ) @@ -1403,6 +1432,16 @@ def test_raw_reserved_names_precede_arrow_type_validation(kind: str) -> None: PollingSource( _Poll(table.schema, []), ["k"], source_id="poll", record_id_columns="k" ) + elif kind == "dict-schema": + DictSource( + table.select(["k", "x"]).to_pylist(), + tag_columns=["k"], + data_schema=table.schema, + ) + elif kind == "frame-schema": + DataFrameSource( + pl.from_arrow(table.select(["k", "x"])), ["k"], schema=table.schema + ) else: ArrowTableSource(table, ["k"], infer_nullable=kind == "arrow-infer") From af0547b2f0de31aa54d7f99cfc3137942c2d241a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:08:26 -0800 Subject: [PATCH 15/21] test(sources): cover both mixed row layouts --- .../sources/test_source_arrow_validation.py | 60 ++++++++++++++----- 1 file changed, 46 insertions(+), 14 deletions(-) diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index c405f5be9..6a6e1d39e 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -465,12 +465,16 @@ class _NestedFrameValue: @dataclass class _NestedFrameRow: k: int + g: int x: _NestedFrameValue + y: int @dataclass class _ReorderedNestedFrameRow: + y: int x: _NestedFrameValue + g: int k: int @@ -1616,51 +1620,79 @@ class OtherReading(NamedTuple): @pytest.mark.parametrize( - "kind", ["tuple", "list", "numpy", "reordered-model", "reordered-nested-dataclass"] + "kind,reverse", + [ + ("tuple", False), + ("list", False), + ("numpy", False), + ("model", False), + ("model", True), + ("nested-dataclass", False), + ("nested-dataclass", True), + ], ) @pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) @pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) def test_frame_preserves_mixed_rows_with_the_same_columns( - kind: str, iterator: bool, path: str + kind: str, reverse: bool, iterator: bool, path: str ) -> None: from collections import namedtuple import numpy as np + class Model(BaseModel): + k: int + g: int + x: int + y: int + class ReverseModel(BaseModel): + y: int x: int + g: int k: int rows: list[Any] - if kind == "reordered-model": - rows = [_PlainFrameModel(k=1, x=2), ReverseModel(k=3, x=4)] - elif kind == "reordered-nested-dataclass": + tags = ["k", "g"] + if kind == "model": + rows = [Model(k=1, g=2, x=3, y=4), ReverseModel(k=5, g=6, x=7, y=8)] + expected = [{"k": 1, "g": 2, "x": 3, "y": 4}, {"k": 5, "g": 6, "x": 7, "y": 8}] + elif kind == "nested-dataclass": rows = [ - _NestedFrameRow(1, _NestedFrameValue(2)), - _ReorderedNestedFrameRow(_NestedFrameValue(4), 3), + _NestedFrameRow(1, 2, _NestedFrameValue(3), 4), + _ReorderedNestedFrameRow(8, _NestedFrameValue(7), 6, 5), + ] + expected = [ + {"k": 1, "g": 2, "x": {"value": 3}, "y": 4}, + {"k": 5, "g": 6, "x": {"value": 7}, "y": 8}, ] else: + tags = ["k"] record = namedtuple("Record", ["k", "x"]) rows = [ record(1, 2), {"tuple": tuple, "list": list, "numpy": np.array}[kind]((3, 4)), ] + expected = [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + if reverse: + rows.reverse() + expected.reverse() + tags.reverse() frame = pl.DataFrame(iter(rows) if iterator else rows) - expected = [{"k": 1, "x": 2}, {"k": 3, "x": 4}] - if kind == "reordered-nested-dataclass": - expected = [{"k": 1, "x": {"value": 2}}, {"k": 3, "x": {"value": 4}}] assert frame.to_dicts() == expected data = iter(rows) if iterator else rows if path == "frame": - source = DataFrameSource(data, ["k"], tag_only_columns=True) - control = DataFrameSource(frame, ["k"], tag_only_columns=True) - assert source.as_table().equals(control.as_table(), check_metadata=True) + source = DataFrameSource(data, tags, tag_only_columns=True) + control = DataFrameSource(frame, tags, tag_only_columns=True) + table = source.as_table() + assert table.to_pylist() == expected + assert table.equals(control.as_table(), check_metadata=True) assert source.source_id == control.source_id assert source.content_hash() == control.content_hash() assert source.pipeline_hash() == control.pipeline_hash() else: poll = PollingSource( - _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" + _Poll(None, data), tags, source_id="poll", record_id_columns="k" ) assert _read_frame_poll(poll, path, 2) == expected From e6f2e3ffdb8e3df7a58296e30779b45e34bd6b96 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:12:35 -0800 Subject: [PATCH 16/21] fix(validation): close reserved column review gaps --- changelog.d/ITL-1165.md | 5 +- docs/concepts/sources.md | 6 +- docs/dev/design_issues/ITL-1165-RN1.md | 2 + src/orcapod/core/data_function.py | 7 +- src/orcapod/core/result_cache.py | 8 +- src/orcapod/core/sources/data_frame_source.py | 7 +- src/orcapod/core/sources/db_table_source.py | 9 ++- .../test_result_token_column_type.py | 12 +++ .../test_cached_function_pod_job.py | 6 +- .../sources/test_source_arrow_validation.py | 80 ++++++++++++++----- 10 files changed, 101 insertions(+), 41 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index e4745d27f..b4a1ac126 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -20,8 +20,9 @@ - `Pick` and `Index` reject reserved `out` names at construction, so their output columns stay visible in stream tables. -- Stored function results refuse reserved user output keys before a cache lookup, - job replay or provenance read can reconstruct a row. +- Manual function result cache writes refuse reserved user output keys. A cache + lookup that finds a stored result with a reserved output key fails the job run. + Replay and provenance reads also refuse to reconstruct such rows. - Operator caches and cached sources refuse stored user columns in the reserved namespace before presenting their rows. - Raw Arrow and polling sources report reserved column names before validating diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 973e5456a..603eb8d56 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -323,8 +323,10 @@ Named Python rows returned to `PollingSource` must supply the same fields. For sparse mappings, include every key and use `None` for missing values. A namedtuple can supply the column names for positional rows of the same width. Different model or dataclass classes can share a batch when conversion keeps each field in its named -column and preserves its value. If conversion would lose a value, the error identifies -the column. Use a common type that can represent all its values exactly. +column and preserves its value. For batches mixing model or dataclass classes, a +value-loss error identifies the affected column. Use a common type that can represent +all values in that column exactly. Mapping rows use Polars' type inference, which +can round values when a column mixes integers and floats. ### A CSV file's types: `schema=` diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index 63ce30d1d..b82d4d1e8 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -32,6 +32,8 @@ new operator names and function pod output keys, including user data returned by functions before caching or emission and user keys read from stored results. Operator caches and cached sources check user columns before exposing rows, including when an operator's records feed a derived source. +Manual function result cache writes also check output keys, and an invalid cached +result fails the run as a stored-table read error. `DataFrameSource` checks the names on incoming frames and on the frame Polars infers from Python inputs. Polling checks batch names before conversion. Polling batches keep matching named layouts when conversion preserves the values and reject a mixed typed diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 88e59659e..d7e99662e 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1762,7 +1762,12 @@ def record_data( output_data: DataProtocol, skip_duplicates: bool = False, ) -> DataProtocol: - """Record the output data against the input data in the result store.""" + """Record the output data against the input data in the result store. + + Raises: + InputValidationError: If an output column has a reserved name. + """ + schema_utils.require_names_not_system(output_data.keys()) var_dg, exec_dg = self._build_metadata_datagrams() self._cache.store( input_data, diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 65b80e485..ec50e2906 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -434,12 +434,8 @@ def lookup( try: _check_result_table(result_table, RECORD_ID_COL) except InputValidationError as exc: - location = "/".join( - self._result_database.base_path + self._versioned_record_path - ) - raise InputValidationError( - f"{exc} Stored result table: {location}" - ) from exc + path = self._result_database.base_path + self._versioned_record_path + raise OrcapodDatabaseReadError("/".join(path), path) from exc if result_table.num_rows > 1: logger.info( diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 4e701eb79..26ba65324 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -99,11 +99,13 @@ def from_model( @override def __getattribute__(self, name: str) -> Any: + """Expose the original class and field dictionary to Polars.""" if name in ("__class__", "__dict__"): return getattr(self._original, name) return super().__getattribute__(name) def __getattr__(self, name: str) -> Any: + """Read remaining attributes from the original model.""" return getattr(self._original, name) @override @@ -232,7 +234,8 @@ def _checked_frame_rows( positional_tail = ( first.kind == "namedtuple" and row.kind == "positional" - and isinstance(row.value, (tuple, list, np.ndarray)) + and isinstance(row.value, (Sequence, np.ndarray)) + and not isinstance(row.value, str) and ( not isinstance(row.value, np.ndarray) or (row.value.ndim == 1 and row.value.dtype.names is None) @@ -384,6 +387,7 @@ def _frame_from_rows( typed_rows: list[tuple[int, _FrameRow, Any]] = [] def typed_values() -> Iterator[Any]: + """Track null positions and the typed rows supplied to Polars.""" for index, row in enumerate(checked): if row is None: null_positions.add(index) @@ -433,6 +437,7 @@ def _frame_from_columns( named_series: dict[int, str] = {} def checked_columns() -> Iterator[Any]: + """Check column inputs and record Series names for the inference check.""" for index, column in enumerate(columns): if column is None: yield None diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index 98909c41d..d89a0c755 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -226,9 +226,9 @@ def _read_table( """ if self._table_name not in connector.get_table_names(): raise ValueError(f"Table {self._table_name!r} not found in database.") - col_infos = connector.get_column_info(self._table_name) require_source_column_names( - [info.name for info in col_infos], self._system_tag_columns + [info.name for info in connector.get_column_info(self._table_name)], + self._system_tag_columns, ) batches: list[pa.RecordBatch] = [] for batch in connector.iter_batches(self._query): @@ -237,8 +237,9 @@ def _read_table( if not batches: raise ValueError(f"Table {self._table_name!r} is empty.") table: pa.Table = pa.Table.from_batches(batches) - # Apply database-defined nullability: the connector's get_column_info - # returns the authoritative nullable flag per column from the DB schema. + # Read database-defined nullability after the scan, as the schema can + # change between the preflight name check and the scan. + col_infos = connector.get_column_info(self._table_name) if col_infos: db_nullable = {ci.name: ci.nullable for ci in col_infos} db_schema = pa.schema( diff --git a/tests/test_core/data_function/test_result_token_column_type.py b/tests/test_core/data_function/test_result_token_column_type.py index e7158cc78..f96a3d002 100644 --- a/tests/test_core/data_function/test_result_token_column_type.py +++ b/tests/test_core/data_function/test_result_token_column_type.py @@ -110,6 +110,18 @@ def test_the_declared_token_column_is_a_nullable_large_string() -> None: assert RESULT_TOKEN_COLUMN.python_type is str +def test_record_data_refuses_reserved_output_names(tmp_path: Path) -> None: + """A manual cache write leaves no record if it has reserved output keys.""" + function = _function(_database("memory", tmp_path), ("total", "label")) + input_data = Data({"x": 3, "y": 4}) + with pytest.raises(InputValidationError, match="'_bad'.*'_tag_fake'.*reserved"): + function.record_data( + input_data, Data({"total": 7, "label": "3+4", "_bad": 1, "_tag_fake": 2}) + ) + assert _stored_rows(function) == 0 + assert function.get_cached_output_for_data(input_data) is None + + @pytest.mark.parametrize("backend", BACKENDS) @pytest.mark.parametrize("keys", KEY_ORDERS) @pytest.mark.parametrize("tokens", LIST_TOKENS, ids=repr) diff --git a/tests/test_core/function_pod/test_cached_function_pod_job.py b/tests/test_core/function_pod/test_cached_function_pod_job.py index ed3005250..90704243e 100644 --- a/tests/test_core/function_pod/test_cached_function_pod_job.py +++ b/tests/test_core/function_pod/test_cached_function_pod_job.py @@ -221,13 +221,13 @@ def test_pod_cache_refuses_reserved_output_keys( ) match = "'_foo'.*'_tag_fake'.*reserved" if path == "lookup": - with pytest.raises(errors.InputValidationError, match=match): + with pytest.raises(errors.OrcapodDatabaseReadError, match=match): _ = cached.lookup_cached_data(inputs[0]) elif path.startswith("job-"): job = PipelineJob(name="reject_reserved", database=InMemoryArrowDatabase()) with job: _ = cached(source, label="add") - with pytest.warns(errors.RowFailuresWarning, match=match): + with pytest.raises(errors.OrcapodDatabaseReadError, match=match): _ = job.run(orchestrator=ORCHESTRATORS[path.removeprefix("job-")]()) records = job.nodes["add"].get_all_records() assert records is None or records.num_rows == 0 @@ -252,7 +252,7 @@ def miss_first_lookup(*args: Any, **kwargs: Any): async def consume() -> None: _ = [row async for row in stream.async_iter_data()] - with pytest.raises(errors.InputValidationError, match=match): + with pytest.raises(errors.OrcapodDatabaseReadError, match=match): if path.endswith("-async"): asyncio.run(consume()) else: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index fd90b87dc..085ca0f86 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -240,16 +240,22 @@ def test_dict_source_refuses_reserved_fields_omitted_from_schema( class _UnreadableRows(Collection[dict[str, int]]): + """Fail if the source reads past the row that exposes a reserved name.""" + def __init__(self, first: dict[str, int] | None = None) -> None: + """Keep an optional first row for the source to inspect.""" self.first = first def __contains__(self, value: object) -> bool: + """Check membership without advancing the iterator.""" return value == self.first def __len__(self) -> int: + """Count the optional first row and the unreadable row.""" return 2 if self.first is not None else 1 def __iter__(self) -> Iterator[dict[str, int]]: + """Yield the known row, then fail on the next read.""" if self.first is not None: yield self.first raise AssertionError("the source read past a reserved name") @@ -846,6 +852,34 @@ def iter_batches(self, query, params=None, batch_size=1000): ) +def test_database_refresh_uses_nullability_observed_by_the_scan() -> None: + """Reject a column change visible when the connector scans the table.""" + + class Connector(_Connector): + change_at_scan = False + + def iter_batches( + self, query: str, params: Any = None, batch_size: int = 1000 + ) -> Iterator[pa.RecordBatch]: + """Expose the new schema at scan time.""" + if self.change_at_scan: + index = self.table.schema.get_field_index("extra") + self.table = self.table.set_column( + index, + self.table.schema.field(index).with_nullable(False), + self.table.column(index), + ) + yield from self.table.to_batches() + + connector = Connector(_table(pa.field("extra", pa.int64()), [3, 4])) + source = DBTableSource(connector, "rows", tag_columns=TAGS, source_id="rows") + before = source.as_table() + connector.change_at_scan = True + with pytest.raises(ValueError, match="changed its columns"): + source.check_for_new_data() + assert source.as_table().equals(before, check_metadata=True) + + @pytest.mark.parametrize("metadata", ["absent", "partial"]) @pytest.mark.parametrize("refresh", [False, True], ids=["construction", "refresh"]) def test_database_refuses_reserved_batch_names_with_incomplete_metadata( @@ -1835,6 +1869,7 @@ class DumpOverride(_SerializedFrameModel): calls: ClassVar[list[int]] = [] def model_dump(self, **kwargs: Any) -> dict[str, Any]: + """Record each serialization while preserving the declared fields.""" self.calls.append(self.k) return {**super().model_dump(**kwargs), "k": self.k + 10} @@ -1886,22 +1921,12 @@ def model_dump(self, **kwargs: Any) -> dict[str, Any]: source = PollingSource( _Poll(None, data), tags, source_id="poll", record_id_columns=key ) - if path == "poll-sync": - assert source.as_table().to_pylist() == expected - else: - - async def read() -> list[dict[str, Any]]: - async with contextlib.aclosing(source.async_iter_data()) as rows: - return [ - {**tag.as_dict(), **data.as_dict()} - for tag, data in [await anext(rows) for _ in expected] - ] - - assert asyncio.run(read()) == expected + assert _read_frame_poll(source, path, len(expected)) == expected assert DumpOverride.calls == expected_dump_calls @pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) +@pytest.mark.parametrize("path", ["frame", "poll-sync", "poll-async"]) @pytest.mark.parametrize( "tail", [ @@ -1915,18 +1940,26 @@ async def read() -> list[dict[str, Any]]: ], ids=lambda tail: type(tail).__name__, ) -def test_dataframe_source_accepts_polars_positional_tails( - tail: object, iterator: bool +def test_frame_sources_accept_polars_positional_tails( + tail: object, iterator: bool, path: str ) -> None: + """A namedtuple supplies column names for a compatible positional row.""" + class Reading(NamedTuple): k: int x: int rows: list[Any] = [Reading(1, 2), tail] - source = DataFrameSource( - iter(rows) if iterator else rows, ["k"], tag_only_columns=True - ) - assert source.as_table().to_pylist() == [{"k": 1, "x": 2}, {"k": 3, "x": 4}] + batch = iter(rows) if iterator else rows + if path == "frame": + source = DataFrameSource(batch, ["k"], tag_only_columns=True) + actual = source.as_table().to_pylist() + else: + poll = PollingSource( + _Poll(None, batch), ["k"], source_id="poll", record_id_columns="k" + ) + actual = _read_frame_poll(poll, path, 2) + assert actual == [{"k": 1, "x": 2}, {"k": 3, "x": 4}] @pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) @@ -2054,15 +2087,18 @@ class ReverseModel(BaseModel): def _read_frame_poll( poll: PollingSource[int], path: str, count: int ) -> list[dict[str, Any]]: + """Read a sync snapshot or collect and close a bounded async poll.""" if path == "poll-sync": return poll.as_table().to_pylist() async def read() -> list[dict[str, Any]]: + """Close the stream after collecting the expected rows or timing out.""" async with contextlib.aclosing(poll.async_iter_data()) as rows: - return [ - {**tag.as_dict(), **data.as_dict()} - for tag, data in [await anext(rows) for _ in range(count)] - ] + async with asyncio.timeout(5): + return [ + {**tag.as_dict(), **data.as_dict()} + for tag, data in [await anext(rows) for _ in range(count)] + ] return asyncio.run(read()) From fff89bb8cf6956d1698dcf5ef959653393a098a1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 16:36:58 -0800 Subject: [PATCH 17/21] fix(schema)!: reserve leading underscores at user column boundaries --- changelog.d/ITL-1165.md | 15 ++++++------- docs/concepts/provenance.md | 9 +++----- docs/concepts/sources.md | 4 ++++ src/orcapod/core/nodes/source_node.py | 10 +++++++++ src/orcapod/core/operators/add_tags.py | 1 - src/orcapod/core/operators/index.py | 1 - src/orcapod/core/operators/mappers.py | 3 --- src/orcapod/core/operators/pick.py | 1 - src/orcapod/core/operators/tag_by.py | 1 - src/orcapod/core/sources/derived_source.py | 6 +----- src/orcapod/core/sources/stream_builder.py | 2 +- .../core/streams/arrow_table_stream.py | 8 ++++--- src/orcapod/pipeline/serialization.py | 8 +++++-- src/orcapod/utils/schema_utils.py | 4 ++-- .../operators/test_async_sync_equivalence.py | 6 +++--- .../operators/test_mappers_strict.py | 2 +- tests/test_core/operators/test_pick_index.py | 12 ++++++----- tests/test_core/streams/test_streams.py | 17 +++++++++++++++ .../test_result_reuse_itl_1503.py | 21 +++++++++++++------ tests/test_pipeline/test_serialization.py | 18 ++++++++++++++++ 20 files changed, 99 insertions(+), 50 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index b4a1ac126..f362d0ba2 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -1,14 +1,11 @@ ### Breaking changes and migration -- Column names that begin with `_` are reserved. Sources refuse these columns instead - of silently dropping them. Rename your own columns or drop reserved columns before - building the source. When reading a table that Orcapod wrote, drop its system columns - first. The `system_tag_columns` option retains its existing validation. -- Operator output and rename targets and function pod output keys must use names that - do not begin with `_`. A saved configuration with a reserved function pod output key - is refused when the pod is rebuilt, including when the original callable is - unavailable and loading would normally use a proxy. Rename the output key and update - its downstream references in the pipeline before saving a new configuration. +- Names beginning with `_` are reserved for Orcapod. This applies to user tags and + data columns in sources, declared schemas and raw Arrow streams, function pod + outputs, operator outputs and renames, and derived tag copies. Loading a saved + configuration with a reserved user column name raises an error. Rename these + columns and update downstream references before saving a new configuration. + Use `stream.as_table()` to export user-facing columns for a new source. - Named Python rows returned to `PollingSource` need the same field names in every non-null named row. A leading namedtuple supplies names for positional rows of the same width. For sparse mappings, include missing keys diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 3db253ff3..88705ed0c 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -153,12 +153,9 @@ columns (`stream.as_table(columns={"source": True})`). not valid: the missing inner list would have to be a list, `[[], ["a"]]` or `[[null], ["a"]]`. -Orcapod's sources, operators and functions always keep these rules. They matter when you -build a table with `_source_*` columns by hand and hand it to `ArrowTableStream`: a list -token over a value that is not a list, a list of another kind (a fixed-size list of tokens -needs a fixed-size list of values of the same size), more list levels in the token than in -the value, a token that is not text, or a missing list of tokens at any level is refused with -`InputValidationError`, which names the token column, its data column and both types. +Use the `source_info` argument when supplying your own tokens to `ArrowTableStream`. +Orcapod checks that the token types and nesting match the data columns. An +`InputValidationError` identifies the token column, its data column and both types. One case reaches ordinary pipelines. A `Batch` of single values and a source that already holds lists of them have the same values but different tokens: a list of tokens (one per diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 111b2c9ee..a3709eb79 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -20,6 +20,10 @@ dependencies -- it sits at the root of the computational graph. Key properties: ### Concrete source types +Names beginning with `_` are reserved for Orcapod. Rename or drop any such columns +before passing data or a schema to a source. If you have the original stream, +`stream.as_table()` gives you the user-facing columns for a new source. + All sources follow the same pattern: convert input data to a PyArrow Table, then pass it through `SourceStreamBuilder` which handles enrichment (provenance columns, system tags, hashing) and produces the final immutable stream. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7b0f8d9ac..6b8cf9317 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -74,6 +74,7 @@ arrow_schema_identity, compute_schema_hash, declared_arrow_schema, + require_names_not_system, ) if TYPE_CHECKING: @@ -563,6 +564,15 @@ def __init__( *, _inherited_types: bool = False, ) -> None: + tag_names = ( + tag_schema.names if isinstance(tag_schema, pa.Schema) else tag_schema.keys() + ) + data_names = ( + data_schema.names + if isinstance(data_schema, pa.Schema) + else data_schema.keys() + ) + require_names_not_system((*tag_names, *data_names)) super().__init__(label=label, data_context=data_context, config=config) if isinstance(tag_schema, pa.Schema) or isinstance(data_schema, pa.Schema): # A slot declared in Arrow holds exactly those types (ITL-640). diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 4d49c51f8..a436f9b34 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -134,7 +134,6 @@ def __init__(self, tags: Mapping[str, TagConstant], **kwargs: Any): raise TypeError(f"add_tags: tag names must be strings, got {not_strings!r}") if "" in tags: raise ValueError("add_tags: a tag name must not be empty") - schema_utils.require_names_not_meta(list(tags)) schema_utils.require_names_not_system(list(tags)) schema_utils.require_names_without_separator(list(tags)) # In name order: the order the tags are given in is not kept (ITL-1269). diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index 9fc5beb47..c60085c93 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -65,7 +65,6 @@ def __init__( self.column = column self.i = i if out is not None: - schema_utils.require_names_not_meta([out]) schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index d4d4186ec..0cb772460 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -105,7 +105,6 @@ def __init__( ): # A data column never gets a meta column's name (ITL-1080): refused here, # so no path (sync, async or the prediction) can produce one. - schema_utils.require_names_not_meta(name_map.values()) schema_utils.require_names_not_system(name_map.values()) schema_utils.require_names_without_separator(name_map.values()) self.name_map = dict(name_map) @@ -383,7 +382,6 @@ def __init__( ): # A tag never gets a meta column's name (ITL-1080): refused here, so no # path (sync, async or the prediction) can produce one. - schema_utils.require_names_not_meta(name_map.values()) schema_utils.require_names_not_system(name_map.values()) schema_utils.require_names_without_separator(name_map.values()) self.name_map = dict(name_map) @@ -678,7 +676,6 @@ def __init__( ): # No column gets a meta column's name (ITL-1080): refused here, so no # path (sync, async or the prediction) can produce one. - schema_utils.require_names_not_meta(name_map.values()) schema_utils.require_names_not_system(name_map.values()) schema_utils.require_names_without_separator(name_map.values()) self.name_map = dict(name_map) diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 8ac043ae9..b88533f05 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -67,7 +67,6 @@ def __init__( self.column = column self.key = key if out is not None: - schema_utils.require_names_not_meta([out]) schema_utils.require_names_not_system([out]) schema_utils.require_names_without_separator([out]) self.out = out diff --git a/src/orcapod/core/operators/tag_by.py b/src/orcapod/core/operators/tag_by.py index 2e6b431b6..f52a36bd2 100644 --- a/src/orcapod/core/operators/tag_by.py +++ b/src/orcapod/core/operators/tag_by.py @@ -81,7 +81,6 @@ class TagBy(UnaryOperator): def __init__(self, columns: str | Iterable[str], **kwargs: Any) -> None: names = _tag_by_names(columns) - schema_utils.require_names_not_meta(names) schema_utils.require_names_not_system(names) schema_utils.require_names_without_separator(names) self.columns: tuple[str, ...] = names diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index b84febe6e..8e1c5a182 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -82,6 +82,7 @@ def validate_tags_as_data( name is already a column, is used twice, or starts with the prefix reserved for system columns. """ + schema_utils.require_names_not_system(tags_as_data.values()) seen: set[str] = set() for tag, name in tags_as_data.items(): if tag not in tag_keys: @@ -100,11 +101,6 @@ def validate_tags_as_data( f"tags_as_data: the name {name!r} is given to more than one tag. " "Each copy needs its own name." ) - if name.startswith(constants.DATAGRAM_PREFIX): - raise InputValidationError( - f"tags_as_data: cannot copy tag {tag!r} to {name!r}: names starting " - f"with {constants.DATAGRAM_PREFIX!r} are reserved for system columns." - ) seen.add(name) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 2a6a5e3dc..374cb980b 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -808,7 +808,7 @@ def build( ) # 1. Refuse reserved names before any system columns could be dropped. - schema_utils.require_names_not_meta(tag_columns_tuple) + require_source_column_names(tag_columns_tuple) table = arrow_utils.drop_system_columns(table) require_custom_system_tags(table, system_tag_columns_tuple) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index d3ffaff3a..5e1f522bb 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -78,7 +78,7 @@ def __init__( """Wrap ``table`` as a stream. Args: - table: The rows: tag, data, system-tag and source-info columns. + table: The user tag and data columns. tag_columns: The user tag columns. system_tag_columns: Columns to rename into system tags. source_info: Source-info tokens to add, by column. @@ -104,6 +104,10 @@ def __init__( Also if a system-tag column is not a string, contains null values, or lacks its matching source-id or record-id column. """ + if not _system_tags_are_derived: + schema_utils.require_names_not_system( + (*table.column_names, *tag_columns, *data_tags, *(source_info or ())) + ) super().__init__(**kwargs) self._producer = producer @@ -162,8 +166,6 @@ def __init__( prefix_info = {constants.SOURCE_PREFIX: source_info} - # A tag never has a meta column's name (ITL-1080). - schema_utils.require_names_not_meta(tag_columns) # determine tag columns first and then exclude any source info self._tag_columns = tuple(c for c in tag_columns if c in table.column_names) self._system_tag_columns = tuple( diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 1f2394bc9..3793f077a 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -25,6 +25,7 @@ ) from orcapod.semantic_types._schema_conversion import arrow_schema_for_types +from orcapod.utils.schema_utils import require_names_not_system if TYPE_CHECKING: import pyarrow as pa @@ -1434,6 +1435,9 @@ def deserialize_output_schema( such as an unregistered logical type, or a saved nullable column name is not a saved column. The message names the column and its saved type string. """ + tag_columns = output_schema.get("tag", {}) + data_columns = output_schema.get("data", {}) + require_names_not_system((*tag_columns, *data_columns)) saved_nullable: dict[str, list[str]] | None = output_schema.get("nullable") def restore(columns: dict[str, str], nullable: list[str] | None) -> Schema: @@ -1465,11 +1469,11 @@ def restore(columns: dict[str, str], nullable: list[str] | None) -> Schema: return ( restore( - output_schema.get("tag", {}), + tag_columns, None if saved_nullable is None else saved_nullable["tag"], ), restore( - output_schema.get("data", {}), + data_columns, None if saved_nullable is None else saved_nullable["data"], ), ) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index b469d98bb..89319b994 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -1247,8 +1247,8 @@ def require_names_not_system(names: Collection[str]) -> None: if reserved: columns = ", ".join(repr(name) for name in reserved) raise InputValidationError( - f"Column names {columns} start with {prefix!r}, which is reserved " - "for system columns. A tag or data column needs another name." + f"Column names {columns} start with {prefix!r}. Names beginning with " + f"{prefix!r} are reserved for Orcapod. Use another column name." ) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index b320186c4..0dedd10e1 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -2886,7 +2886,7 @@ def _table_with_meta_named_column() -> pa.Table: def test_a_stream_refuses_a_tag_named_with_the_meta_prefix() -> None: - with pytest.raises(InputValidationError, match="'__g'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__g'.*reserved for Orcapod"): _ = ArrowTableStream(_table_with_meta_named_column(), tag_columns=["k", "__g"]) @@ -2903,7 +2903,7 @@ def test_a_source_refuses_a_tag_named_with_the_meta_prefix() -> None: def test_map_tags_refuses_a_meta_named_target() -> None: """Refused when built, so neither path nor the prediction can produce one.""" - with pytest.raises(InputValidationError, match="'__t'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__t'.*reserved for Orcapod"): _ = MapTags({"ta": "__t"}) @@ -2998,7 +2998,7 @@ def test_map_tags_dropping_every_tag_agrees_on_both_paths() -> None: def test_map_data_refuses_a_meta_named_target() -> None: """A data column never gets a meta column's name: refused when built.""" - with pytest.raises(InputValidationError, match="'__x'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__x'.*reserved for Orcapod"): _ = MapData({"i8": "__x"}) diff --git a/tests/test_core/operators/test_mappers_strict.py b/tests/test_core/operators/test_mappers_strict.py index a9c3555fe..b909dc229 100644 --- a/tests/test_core/operators/test_mappers_strict.py +++ b/tests/test_core/operators/test_mappers_strict.py @@ -376,7 +376,7 @@ def test_map_columns_refuses_leaving_no_data_column() -> None: def test_map_columns_refuses_a_meta_named_target() -> None: - with pytest.raises(InputValidationError, match="'__x'.*reserved for meta"): + with pytest.raises(InputValidationError, match="'__x'.*reserved for Orcapod"): MapColumns({"age": "__x"}) diff --git a/tests/test_core/operators/test_pick_index.py b/tests/test_core/operators/test_pick_index.py index 3f990bb46..71499dd72 100644 --- a/tests/test_core/operators/test_pick_index.py +++ b/tests/test_core/operators/test_pick_index.py @@ -32,7 +32,9 @@ ["_", "_foo", "_tag_y", "_tag::y", "_source_y", "_content_hash", "_context_key"], ) def test_operators_refuse_reserved_column_names(build, name: str) -> None: - with pytest.raises(InputValidationError, match=escape(repr(name))): + with pytest.raises( + InputValidationError, match=rf"{escape(repr(name))}.*reserved for Orcapod" + ): build(name) @@ -92,9 +94,9 @@ def test_pick_out_collision_raises(dict_stream): def test_pick_out_with_the_meta_prefix_raises(): - """``__`` is reserved for meta columns, which no operator carries (ITL-1080): an + """``__`` is reserved for Orcapod, which no operator carries (ITL-1080): an ``out`` named with it would be dropped on every path, so it is refused at once.""" - with pytest.raises(InputValidationError, match="reserved for meta columns"): + with pytest.raises(InputValidationError, match="reserved for Orcapod"): Pick("scores", "speed", out="__speed") @@ -267,9 +269,9 @@ def test_index_out_collision_raises(): def test_index_out_with_the_meta_prefix_raises(): - """``__`` is reserved for meta columns, which no operator carries (ITL-1080): an + """``__`` is reserved for Orcapod, which no operator carries (ITL-1080): an ``out`` named with it would be dropped on every path, so it is refused at once.""" - with pytest.raises(InputValidationError, match="reserved for meta columns"): + with pytest.raises(InputValidationError, match="reserved for Orcapod"): Index("items", 0, out="__first") diff --git a/tests/test_core/streams/test_streams.py b/tests/test_core/streams/test_streams.py index 14b3b137b..509b907dd 100644 --- a/tests/test_core/streams/test_streams.py +++ b/tests/test_core/streams/test_streams.py @@ -12,6 +12,7 @@ from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import StreamBase +from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols.pod import PodProtocol from orcapod.protocols.core_protocols.streams import StreamProtocol from orcapod.types import Schema @@ -21,6 +22,22 @@ # --------------------------------------------------------------------------- +@pytest.mark.parametrize("reverse", [False, True]) +def test_raw_stream_refuses_all_reserved_columns(reverse: bool) -> None: + fields = [ + ("tag", [1]), + ("_private", [2]), + ("_source_value", ["token"]), + ("value", [3]), + ] + if reverse: + fields.reverse() + with pytest.raises( + InputValidationError, match="'_private'.*'_source_value'.*reserved for Orcapod" + ): + ArrowTableStream(pa.table(dict(fields)), tag_columns=["tag"]) + + def make_table_stream( tag_columns: list[str] | None = None, n_rows: int = 3, diff --git a/tests/test_pipeline/test_result_reuse_itl_1503.py b/tests/test_pipeline/test_result_reuse_itl_1503.py index 4714891e2..61e829a4c 100644 --- a/tests/test_pipeline/test_result_reuse_itl_1503.py +++ b/tests/test_pipeline/test_result_reuse_itl_1503.py @@ -38,7 +38,11 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import OrcapodDatabaseReadError, TypeIdentityError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + TypeIdentityError, +) from orcapod.pipeline.observer import NoOpObserver from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.system_constants import constants @@ -241,7 +245,16 @@ def test_persistent_hit_in_ephemeral_mode( ) -> None: """The persistent result is used: no call, no write, recorded as persistent.""" counted = _Counted() - source = _input({"a": 1, "b": 2, "c": 3}, marker=marker, arrangement=arrangement) + inputs = {"a": 1, "b": 2, "c": 3} + if marker: + # The raw stream refuses the column before either execution path can run. + with pytest.raises( + InputValidationError, match=rf"{OLD_MARKER!r}.*reserved for Orcapod" + ): + _input(inputs, marker=True, arrangement=arrangement) + return + + source = _input(inputs, arrangement=arrangement) persistent, ephemeral = InMemoryArrowDatabase(), InMemoryArrowDatabase() stored = _seed(persistent, counted, source, {"a", "b", "c"}) @@ -266,10 +279,6 @@ def test_persistent_hit_in_ephemeral_mode( key: {"result_id": stored[key], "is_ephemeral": False, "computed": False} for key in "abc" } - if marker: - # A user tag with the old marker's name is an ordinary tag. - assert all(tag.as_dict()[OLD_MARKER] is True for tag, _ in rows) - assert set(node.keys()[0]) == {"key", "group", OLD_MARKER} @PATHS diff --git a/tests/test_pipeline/test_serialization.py b/tests/test_pipeline/test_serialization.py index 0cc9ac3a0..4fdd910ba 100644 --- a/tests/test_pipeline/test_serialization.py +++ b/tests/test_pipeline/test_serialization.py @@ -14,6 +14,7 @@ from orcapod.core.operators import Join from orcapod.core.sources import ArrowTableSource from orcapod.databases.in_memory_databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError from orcapod.pipeline import Pipeline from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.serialization import PIPELINE_FORMAT_VERSION @@ -78,6 +79,23 @@ def schema(*names: str) -> Schema: return build +def test_load_refuses_reserved_user_columns_in_saved_schema(spec_pipeline) -> None: + pipeline, tmp_path = spec_pipeline + path = tmp_path / "pipeline.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + joiner = next(node for node in saved["nodes"].values() if node["label"] == "joiner") + schema = joiner["output_schema"] + schema["data"]["_score"] = schema["data"].pop("score") + schema["tag"]["_key"] = schema["tag"].pop("key") + path.write_text(json.dumps(saved)) + + with pytest.raises( + InputValidationError, match="'_key'.*'_score'.*reserved for Orcapod" + ): + Pipeline.load(path) + + def test_saved_pipeline_accepts_old_default_hashing_settings( hashing_settings_pipeline, tmp_path ) -> None: From 9b89eabf7b12154b12c2474d140d10a528d3f198 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 17:31:20 -0800 Subject: [PATCH 18/21] test(datagrams): use the internal route for metadata fixtures --- tests/test_core/datagrams/test_rows_of_table.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/test_core/datagrams/test_rows_of_table.py b/tests/test_core/datagrams/test_rows_of_table.py index 68d39bd24..3ed97986c 100644 --- a/tests/test_core/datagrams/test_rows_of_table.py +++ b/tests/test_core/datagrams/test_rows_of_table.py @@ -404,9 +404,9 @@ def _grouped() -> Any: return _joined().group_by(["g"]) -def _raw_stream_without_tags() -> Any: - """A raw stream with no tag column, a meta column and a column with no values.""" - return ArrowTableStream( +def _stream_without_tags() -> Any: + """An internal stream with no tags, a meta column and a column with no values.""" + return ArrowTableStream._from_derived_table( pa.table( { "x": pa.array([1, 2, 3], pa.int32()), @@ -436,7 +436,7 @@ def _raw_stream_in_two_chunks() -> Any: "source_in_another_arrangement": _source_in_another_arrangement, "joined": _joined, "grouped": _grouped, - "raw_stream_without_tags": _raw_stream_without_tags, + "stream_without_tags": _stream_without_tags, "raw_stream_in_two_chunks": _raw_stream_in_two_chunks, } @@ -487,13 +487,13 @@ def test_a_streams_rows_are_the_constructors(name: str) -> None: @pytest.mark.parametrize( - "name", [name for name in STREAMS if name != "raw_stream_without_tags"] + "name", [name for name in STREAMS if name != "stream_without_tags"] ) def test_a_streams_rows_rebuild_its_table(name: str) -> None: """The rows' own tables, put side by side, are the stream's table. - Not for the raw stream with a meta column: a row's data holds that column as meta, - the stream as a column like any other. + The constructor comparison covers the metadata case, where each row's data + exposes the column as metadata. """ stream = STREAMS[name]() columns = {"system_tags": True, "source": True} From e244d8d148a81a73cd209fd36f03240e47876178 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 17:51:17 -0800 Subject: [PATCH 19/21] fix(schema): keep the reserved column diagnostic internal --- src/orcapod/core/sources/stream_builder.py | 3 +-- src/orcapod/errors.py | 4 ---- src/orcapod/pipeline/graph.py | 2 +- src/orcapod/pipeline/job.py | 2 +- src/orcapod/pipeline/serialization.py | 3 +-- src/orcapod/utils/schema_utils.py | 6 +++++- 6 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 6d6841c7f..74e104683 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -27,7 +27,6 @@ from orcapod.errors import ( InputValidationError, RepeatedDictKeyError, - ReservedColumnNameError, RowIdentifierError, ) from orcapod.logical_types.canonical_form import ( @@ -38,7 +37,7 @@ from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils -from orcapod.utils.schema_utils import compute_schema_hash +from orcapod.utils.schema_utils import ReservedColumnNameError, compute_schema_hash if TYPE_CHECKING: from polars._typing import ( diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 638c6e989..91a77a590 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -9,10 +9,6 @@ class InputValidationError(Exception): """ -class ReservedColumnNameError(InputValidationError): - """A user column is named in Orcapod's reserved namespace.""" - - class RowIdentifierError(InputValidationError, ValueError): """A source's rows cannot be identified by the given key columns (ITL-1154). diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 38dd2ba62..9c6304cbf 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -16,11 +16,11 @@ ) from orcapod.side_effects import SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker -from orcapod.errors import ReservedColumnNameError from orcapod.pipeline.base import AbstractPipelineBase from orcapod.pipeline.dag import OrcaDAG from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule +from orcapod.utils.schema_utils import ReservedColumnNameError if TYPE_CHECKING: import networkx as nx diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index bfca23b29..909fa27ee 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -32,7 +32,6 @@ OrcapodDatabaseError, OrcapodDatabaseReadError, OrcapodDatabaseWriteError, - ReservedColumnNameError, UnboundSourceError, ) from orcapod.pipeline.base import AbstractPipelineBase @@ -72,6 +71,7 @@ commit_best_effort, database_write_path, ) +from orcapod.utils.schema_utils import ReservedColumnNameError if TYPE_CHECKING: from collections.abc import Mapping diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 2fb490a62..71d9dc394 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -11,7 +11,6 @@ from functools import partial from typing import TYPE_CHECKING, Any, TypeAlias, cast -from orcapod.errors import ReservedColumnNameError from orcapod.types import Schema from orcapod.logical_types.canonical_form import ( declaration_form_field, @@ -26,7 +25,7 @@ ) from orcapod.semantic_types._schema_conversion import arrow_schema_for_types -from orcapod.utils.schema_utils import require_names_not_system +from orcapod.utils.schema_utils import ReservedColumnNameError, require_names_not_system if TYPE_CHECKING: import pyarrow as pa diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 83f50d49a..07d5c1c67 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -9,7 +9,7 @@ import pyarrow as pa -from orcapod.errors import InputValidationError, ReservedColumnNameError +from orcapod.errors import InputValidationError from orcapod.types import ContentHash, Schema, SchemaLike from orcapod.utils.output_containers import EXCLUDED_OUTPUT_CONTAINERS @@ -1190,6 +1190,10 @@ def schema_hash_rejected_columns_error( ) +class ReservedColumnNameError(InputValidationError): + """A user column is named in Orcapod's reserved namespace.""" + + def reserved_system_names(names: Iterable[str]) -> set[str]: """Return the names in Orcapod's reserved column namespace.""" from orcapod.system_constants import constants From aaaabba52c1d4b86693c9f2a2506818bab6915ec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 19:24:53 -0800 Subject: [PATCH 20/21] fix(sources): preserve source reads under reserved name validation --- changelog.d/ITL-1165.md | 10 +- docs/concepts/sources.md | 9 - docs/dev/design_issues/ITL-1165-RN1.md | 9 +- src/orcapod/core/sources/data_frame_source.py | 452 +----------------- src/orcapod/core/sources/db_table_source.py | 8 +- src/orcapod/core/sources/list_source.py | 4 - src/orcapod/core/sources/polling_source.py | 3 +- .../sources/test_source_arrow_validation.py | 386 ++------------- 8 files changed, 57 insertions(+), 824 deletions(-) diff --git a/changelog.d/ITL-1165.md b/changelog.d/ITL-1165.md index f362d0ba2..f44970878 100644 --- a/changelog.d/ITL-1165.md +++ b/changelog.d/ITL-1165.md @@ -6,12 +6,6 @@ configuration with a reserved user column name raises an error. Rename these columns and update downstream references before saving a new configuration. Use `stream.as_table()` to export user-facing columns for a new source. -- Named Python rows returned to `PollingSource` need the same - field names in every non-null named row. A leading namedtuple supplies names - for positional rows of the same width. For sparse mappings, include missing keys - with `None` where appropriate. If typed rows would move a value to another column - or lose precision, pass mappings with the intended names and a type that can - represent all values in the column. ### Fixed @@ -25,7 +19,7 @@ - Raw Arrow and polling sources report reserved column names before validating their Arrow types. - `DataFrameSource` checks the column names of input frames and of the frame inferred - from Python data. `PollingSource` checks batch names before frame conversion. - List sources check names in each callback result before requesting more tags. + from Python data. `PollingSource` checks the inferred columns of Python batches. + List sources check user names in each callback result before requesting more tags. Dictionary sources check declared names before reading and each row from a custom collection before asking for the next. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index e34e7e7d5..baf93a2a6 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -386,15 +386,6 @@ dictionary-encoded columns themselves is future work (ITL-1277). `DataFrameSource` uses Polars to infer the columns of Python inputs and checks the resulting column names for reserved names. -Named Python rows returned to `PollingSource` must supply the same fields. -For sparse mappings, include every key and use `None` for missing values. A namedtuple -can supply the column names for positional rows of the same width. Different model or -dataclass classes can share a batch when conversion keeps each field in its named -column and preserves its value. For batches mixing model or dataclass classes, a -value-loss error identifies the affected column. Use a common type that can represent -all values in that column exactly. Mapping rows use Polars' type inference, which -can round values when a column mixes integers and floats. - ### A bare list of key/value structs is a dict A `dict[K, V]` column is stored as a list of structs with the two fields `key` and `value`, diff --git a/docs/dev/design_issues/ITL-1165-RN1.md b/docs/dev/design_issues/ITL-1165-RN1.md index ac8f23a87..9727988e6 100644 --- a/docs/dev/design_issues/ITL-1165-RN1.md +++ b/docs/dev/design_issues/ITL-1165-RN1.md @@ -35,11 +35,10 @@ operator's records feed a derived source. Manual function result cache writes also check output keys, and an invalid cached result fails the run as a stored-table read error. `DataFrameSource` checks the names on incoming frames and on the frame Polars infers -from Python inputs. Polling checks batch names before conversion. Polling batches keep -matching named layouts when conversion preserves the values and reject a mixed typed -input if conversion loses a value. List sources validate callback tags before discarding -metadata or asking for further tags. DictSource checks declared schemas before consuming -rows and checks each row of a custom collection before advancing it. A saved operator schema +from Python inputs. Polling checks the columns Polars infers from Python batches. List +sources validate callback user tags before asking for further tags. DictSource checks +declared schemas before consuming rows and each row of a custom collection before advancing +it. A saved operator schema identifies legacy user names even when a mixed table alone cannot distinguish them from system tags. SpiralDB validates the pinned snapshot's column names for historical reads. diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 66253a587..b573a847d 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -1,31 +1,14 @@ from __future__ import annotations import logging -import math -from collections.abc import ( - Callable, - Collection, - Iterable, - Iterator, - Mapping, - Sequence, - Sized, -) -from dataclasses import fields, is_dataclass -from enum import Enum -from itertools import chain, repeat -from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, cast +from collections.abc import Collection +from typing import TYPE_CHECKING, Any, ClassVar, cast -import numpy as np -import pandas as pd import polars as pl import pyarrow as pa -from pydantic import BaseModel -from typing_extensions import override from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.base import RootSource -from orcapod.errors import InputValidationError from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, @@ -35,7 +18,7 @@ require_supported_nullable_types, ) from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import _normalize_column_list, reserved_system_names +from orcapod.utils.schema_utils import _normalize_column_list from orcapod.semantic_types._schema_conversion import arrow_table_for_rows @@ -45,435 +28,6 @@ logger = logging.getLogger(__name__) -class _FrameRow(NamedTuple): - """A row and its layout before Polars infers any columns.""" - - value: Any - names: tuple[str, ...] - kind: Literal["mapping", "model", "dataclass", "namedtuple", "series", "positional"] - additional_names: tuple[str, ...] = () - - @property - def exposed_names(self) -> tuple[str, ...]: - """Return declared and other field names exposed by the row.""" - return (*self.names, *self.additional_names) - - -class _FrameModelRow(BaseModel): - """Present the original Pydantic layout and check any dump Polars uses. - - Polars reads declared field values directly for flat models and calls - `model_dump` when it unpacks nested models. Forward both paths so validation - keeps Polars' original type inference and does not run a serializer twice. - """ - - __slots__: ClassVar[tuple[str, ...]] = ( - "_original", - "_names", - "_dumped_fields", - ) - if TYPE_CHECKING: - _original: BaseModel - _names: set[str] - _dumped_fields: dict[str, object] | None - - @classmethod - def from_model( - cls, - value: BaseModel, - names: tuple[str, ...], - ) -> _FrameModelRow: - """Wrap a model that has already been constructed and validated.""" - row = cls.model_construct() - object.__setattr__(row, "_original", value) - object.__setattr__(row, "_names", set(names)) - object.__setattr__(row, "_dumped_fields", None) - return row - - @override - def __getattribute__(self, name: str) -> Any: - """Expose the original class and field dictionary to Polars.""" - if name in ("__class__", "__dict__"): - return getattr(self._original, name) - return super().__getattribute__(name) - - def __getattr__(self, name: str) -> Any: - """Read remaining attributes from the original model.""" - return getattr(self._original, name) - - @override - def model_dump(self, **kwargs: object) -> dict[str, object]: - """Validate the serialized field names before they reach inference.""" - dump = cast("Callable[..., object]", self._original.model_dump) - values = dump(**kwargs) - if not isinstance(values, dict): - raise InputValidationError( - "A serialized model row must return a dict with string field names." - ) - fields = cast("dict[object, object]", values) - names = {name for name in fields if isinstance(name, str)} - if len(names) != len(fields): - raise InputValidationError( - "A serialized model row needs string field names." - ) - require_source_column_names(names) - if names != self._names: - raise InputValidationError( - f"Serialized model row has different fields. Missing " - f"{sorted(self._names - names)!r}, extra " - f"{sorted(names - self._names)!r}. Use a mapping." - ) - result = cast("dict[str, object]", fields) - object.__setattr__(self, "_dumped_fields", result) - return result - - def _frame_fields(self) -> Mapping[str, object]: - """Return the fields Polars read, including any serializer changes.""" - if self._dumped_fields is not None: - return self._dumped_fields - return vars(self._original) - - -def _describe_model_row(value: BaseModel) -> _FrameRow: - """Read the model's field names without running its serialization code.""" - model = type(value) - declared = model.model_fields - computed = model.model_computed_fields - if not isinstance(computed, Mapping): - # Older Pydantic releases exposed this on the instance. - computed = value.model_computed_fields - exposed = ( - set(computed) - | {info.alias for info in computed.values() if info.alias is not None} - | set(value.model_extra or ()) - | set(value.__pydantic_extra__ or ()) - | value.model_fields_set - | vars(value).keys() - ) - aliases = { - field.serialization_alias - for name, field in declared.items() - if model.model_config.get("serialize_by_alias") - and field.serialization_alias is not None - and field.serialization_alias != name - } - if not all(isinstance(name, str) for name in exposed): - raise InputValidationError("needs string field names.") - if aliases & declared.keys(): - require_source_column_names(aliases) - raise InputValidationError( - f"has serialization aliases {sorted(aliases)!r} that rename existing " - "model fields. Use a mapping." - ) - return _FrameRow( - value, - tuple(declared), - "model", - tuple(sorted((exposed - declared.keys()) | aliases)), - ) - - -def _describe_frame_row(value: Any) -> _FrameRow | None: - """Read top-level field names while preserving typed row values.""" - if value is None: - return None - if isinstance(value, Mapping): - names = tuple(value) - if not all(isinstance(name, str) for name in names): - raise InputValidationError("needs string field names.") - return _FrameRow( - value if isinstance(value, dict) else dict(value), names, "mapping" - ) - if isinstance(value, BaseModel): - return _describe_model_row(value) - if is_dataclass(value) and not isinstance(value, type): - return _FrameRow( - value, tuple(field.name for field in fields(value)), "dataclass" - ) - if isinstance(value, Sequence): - names = getattr(value, "_fields", None) - if isinstance(names, tuple) and all(isinstance(name, str) for name in names): - return _FrameRow(value, names, "namedtuple") - if isinstance(value, (pd.Series, pd.Index, pl.Series)): - name = str(value.name) if value.name is not None else "" - return _FrameRow(value, (name,) if name else (), "series") - return _FrameRow(value, (), "positional") - - -def _describe_frame_rows(values: Iterable[Any]) -> Iterator[_FrameRow | None]: - """Attach the input row's index to an error from its descriptor.""" - for index, value in enumerate(values): - try: - yield _describe_frame_row(value) - except InputValidationError as exc: - raise InputValidationError(f"Source row {index} {exc}") from exc - - -def _checked_frame_rows(rows: Iterable[_FrameRow | None]) -> Iterator[_FrameRow | None]: - """Check every named layout before yielding the row to Polars.""" - first: _FrameRow | None = None - expected: set[str] = set() - for index, row in enumerate(rows): - if row is not None: - try: - require_source_column_names(row.exposed_names) - except InputValidationError as exc: - raise InputValidationError(f"Source row {index}. {exc}") from exc - names = set(row.exposed_names) - if first is None: - first, expected = row, names - positional_tail = ( - first.kind == "namedtuple" - and row.kind == "positional" - and isinstance(row.value, (Sequence, np.ndarray)) - and not isinstance(row.value, str) - and ( - not isinstance(row.value, np.ndarray) - or (row.value.ndim == 1 and row.value.dtype.names is None) - ) - and len(row.value) == len(first.names) - ) - if positional_tail: - yield row - continue - if names != expected: - raise InputValidationError( - f"Source row {index} has different field names. " - f"Missing {sorted(expected - names)!r}, extra {sorted(names - expected)!r}. " - "Use the same field names in every row. For mappings, add missing " - "fields with None where appropriate and remove unintended fields." - ) - if row.kind != first.kind or ( - row.kind == "namedtuple" and row.names != first.names - ): - raise InputValidationError( - f"Source row {index} has a different layout " - f"({type(row.value).__name__} fields {row.names!r}). " - f"Use the same row layout ({type(first.value).__name__} fields " - f"{first.names!r}) or use mappings throughout." - ) - yield row - - -def _same_frame_value(supplied: Any, converted: Any) -> bool: - """Compare converted values without rounding mixed numeric inputs.""" - if supplied is converted: - return True - if isinstance(supplied, np.generic): - supplied = supplied.item() - if isinstance(supplied, Enum): - supplied = supplied.value - if is_dataclass(supplied) and not isinstance(supplied, type): - supplied = { - field.name: getattr(supplied, field.name) for field in fields(supplied) - } - if isinstance(supplied, BaseModel): - supplied = vars(supplied) - if isinstance(supplied, Mapping) and isinstance(converted, Mapping): - return all( - _same_frame_value(value, converted.get(name)) and name in converted - for name, value in supplied.items() - ) and all( - name in supplied or value is None for name, value in converted.items() - ) - if isinstance(supplied, (list, tuple, np.ndarray)) and isinstance(converted, list): - return len(supplied) == len(converted) and all( - _same_frame_value(left, right) for left, right in zip(supplied, converted) - ) - if isinstance(supplied, float): - if math.isnan(supplied): - return isinstance(converted, float) and math.isnan(converted) - if supplied == 0 and math.copysign(1, supplied) < 0: - return ( - isinstance(converted, float) - and math.copysign(1, converted) < 0 - and converted == 0 - ) - equal = supplied == converted - return isinstance(equal, (bool, np.bool_)) and bool(equal) - - -def _require_exact_mixed_rows( - frame: pl.DataFrame, - rows: list[tuple[int, _FrameRow, Any]], -) -> None: - """Check a mixed batch against the values each input column supplied.""" - _, first, _ = rows[0] - if all(type(row.value) is type(first.value) for _, row, _ in rows): - return - names = frame.columns - values = [ - column.to_list() if column.dtype == pl.Object else column.to_arrow().to_pylist() - for column in frame - ] - for (index, row, value), converted in zip(rows, zip(*values), strict=True): - if isinstance(value, _FrameModelRow): - supplied = value._frame_fields() - elif row.kind == "dataclass": - supplied = {name: getattr(value, name) for name in row.names} - else: - supplied = dict(zip(first.names, value, strict=True)) - for name, item in zip(names, converted, strict=True): - if _same_frame_value(supplied[name], item): - continue - if row.kind == "dataclass" and row.names != first.names: - raise InputValidationError( - f"Source row {index} has a different layout ({row.names!r}) " - f"from the first row ({first.names!r}), and conversion changed " - f"column {name!r}. Use mappings for these rows." - ) - raise InputValidationError( - f"Source row {index} column {name!r} could not be converted " - "without losing its value. Use values that convert exactly to one type." - ) - - -def _require_materialized_row_names(rows: Sequence[_FrameRow | None]) -> None: - """Report all reserved names and the first row exposing one.""" - names = {name for row in rows if row is not None for name in row.exposed_names} - try: - require_source_column_names(names) - except InputValidationError as exc: - reserved = reserved_system_names(names) - first = next( - index - for index, row in enumerate(rows) - if row is not None and not reserved.isdisjoint(row.exposed_names) - ) - raise InputValidationError(f"Source row {first}. {exc}") from exc - - -def _frame_from_rows(data: Iterable[Any], *, materialized: bool) -> pl.DataFrame: - """Use the regular Polars conversion after checking row or column names.""" - rows = _describe_frame_rows(data) - if materialized: - described = list(rows) - _require_materialized_row_names(described) - rows = iter(described) - - leading_nulls = 0 - for first in rows: - if first is not None: - break - leading_nulls += 1 - else: - return pl.DataFrame([None] * leading_nulls) - - all_rows = chain(repeat(None, leading_nulls), (first,), rows) - if first.kind == "series" or (materialized and isinstance(first.value, np.ndarray)): - return _frame_from_columns(all_rows, materialized=materialized) - - checked = _checked_frame_rows(all_rows) - if first.kind in ("mapping", "positional"): - values = (row.value if row is not None else None for row in checked) - return pl.DataFrame(list(values) if materialized else values) - - null_positions: set[int] = set() - typed_rows: list[tuple[int, _FrameRow, Any]] = [] - - def typed_values() -> Iterator[Any]: - """Track null positions and the typed rows supplied to Polars.""" - for index, row in enumerate(checked): - if row is None: - null_positions.add(index) - continue - value = row.value - if isinstance(value, BaseModel): - value = _FrameModelRow.from_model(row.value, row.exposed_names) - typed_rows.append((index, row, value)) - yield value - - typed = typed_values() - frame = pl.DataFrame(list(typed) if materialized else typed) - if first.kind == "model": - expected = set(first.exposed_names) - if set(frame.columns) != expected: - raise InputValidationError( - f"Source row {leading_nulls} exposes model fields {sorted(expected)!r}, " - f"but Polars returned {frame.columns!r}. Use a mapping." - ) - elif tuple(frame.columns) != first.names: - raise InputValidationError( - f"Source row {leading_nulls} declares fields {first.names!r}, " - f"but Polars returned {frame.columns!r}. Use mappings for these rows." - ) - _require_exact_mixed_rows(frame, typed_rows) - if null_positions: - indices = iter(range(frame.height)) - positions = [ - None if index in null_positions else next(indices) - for index in range(frame.height + len(null_positions)) - ] - frame = frame.select( - pl.all().gather(pl.Series(positions, dtype=pl.get_index_type())) - ) - return frame - - -def _frame_from_columns( - columns: Iterable[_FrameRow | None], - *, - materialized: bool, -) -> pl.DataFrame: - """Check named columns and refuse named rows in a column-oriented sequence.""" - named_series: dict[int, str] = {} - - def checked_columns() -> Iterator[Any]: - """Check column inputs and record Series names for the inference check.""" - for index, column in enumerate(columns): - if column is None: - yield None - continue - if not materialized: - require_source_column_names(column.exposed_names) - if column.kind == "series" and column.names: - named_series[index] = column.names[0] - elif column.kind not in ("positional", "series"): - raise InputValidationError( - f"Source row {index} declares fields {column.names!r} in a " - "column-oriented sequence. Pass named rows separately or use named columns." - ) - yield column.value - - values = checked_columns() - frame = pl.DataFrame(list(values) if materialized else values) - for index, name in named_series.items(): - if index >= frame.width or name != frame.columns[index]: - raise InputValidationError( - f"Input column {index} is named {name!r}, but Polars " - f"returned columns {frame.columns!r}. Use named columns." - ) - return frame - - -def source_dataframe(data: FrameInitTypes) -> pl.DataFrame: - """Convert a polling batch, validating layouts before Polars infers columns. - - Args: - data: Tabular or column input, or Python rows with a consistent named layout. - - Returns: - The validated input converted with Polars' normal inference. - """ - if isinstance(data, pd.DataFrame): - require_source_column_names([str(name) for name in data.columns]) - elif isinstance(data, (pa.Table, pa.RecordBatch)): - require_source_column_names(data.schema.names) - elif isinstance(data, np.ndarray): - require_source_column_names(data.dtype.names or ()) - elif isinstance(data, Mapping): - require_source_column_names(data.keys()) - elif isinstance(data, Sequence): - return _frame_from_rows(data, materialized=True) - elif ( - isinstance(data, Iterable) - and not isinstance(data, Sized) - and not hasattr(data, "__arrow_c_stream__") - ): - return _frame_from_rows(data, materialized=False) - return pl.DataFrame(data) - - class DataFrameSource(RootSource): """A source backed by a Polars DataFrame or other Polars-compatible data. diff --git a/src/orcapod/core/sources/db_table_source.py b/src/orcapod/core/sources/db_table_source.py index d2a9a67e7..98c556701 100644 --- a/src/orcapod/core/sources/db_table_source.py +++ b/src/orcapod/core/sources/db_table_source.py @@ -223,9 +223,8 @@ def _read_table( """ if self._table_name not in connector.get_table_names(): raise ValueError(f"Table {self._table_name!r} not found in database.") - require_source_column_names( - [info.name for info in connector.get_column_info(self._table_name)], - ) + col_infos = connector.get_column_info(self._table_name) + require_source_column_names([info.name for info in col_infos]) batches: list[pa.RecordBatch] = [] for batch in connector.iter_batches(self._query): require_source_column_names(batch.schema.names) @@ -234,9 +233,6 @@ def _read_table( raise ValueError(f"Table {self._table_name!r} is empty.") table: pa.Table = pa.Table.from_batches(batches) require_live_logical_types(table.schema) - # Read database-defined nullability after the scan, as the schema can - # change between the preflight name check and the scan. - col_infos = connector.get_column_info(self._table_name) if col_infos: db_nullable = {ci.name: ci.nullable for ci in col_infos} db_schema = pa.schema( diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 6df668914..30a27e85c 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -126,10 +126,6 @@ def __init__( tag_fields = tag_function(element, idx) if idx == 0 and float32_columns: first_tag = tag_fields - if isinstance(tag_fields, TagProtocol): - require_source_column_names( - tag_fields.keys(columns={"meta": True, "system_tags": True}) - ) if hasattr(tag_fields, "as_dict"): tag_fields = tag_fields.as_dict() row = dict(tag_fields) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index c7630a617..fcd15779a 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -24,7 +24,6 @@ from orcapod.core.identity_chains import refuse_identity_io from orcapod.core.sources.base import RootSource -from orcapod.core.sources.data_frame_source import source_dataframe from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, @@ -925,7 +924,7 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: input_schema = None if arrow_frame is not None: data, input_schema = arrow_frame - df = source_dataframe(data) + df = pl.DataFrame(data) if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index bc7b70224..f4a287387 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -379,18 +379,6 @@ def build() -> CSVSource: build() -def test_polling_stops_at_first_reserved_series_in_iterator() -> None: - def columns() -> Iterator[pl.Series]: - yield pl.Series("k", [1, 2]) - yield pl.Series("_foo", [3, 4]) - pytest.fail("reserved columns must stop iteration") - - with pytest.raises(InputValidationError, match="'_foo'.*drop them first"): - PollingSource( - _Poll(None, columns()), ["k"], source_id="poll", record_id_columns="k" - ).as_table() - - @pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) def test_dataframe_source_uses_inferred_positional_column_names( as_iterator: bool, @@ -404,25 +392,6 @@ def test_dataframe_source_uses_inferred_positional_column_names( assert source.as_table().to_pylist() == expected.to_dicts() -@pytest.mark.parametrize("as_iterator", [False, True], ids=["sequence", "iterator"]) -def test_polling_adds_row_context_to_field_name_error( - as_iterator: bool, -) -> None: - rows: list[Any] = [{"k": 1, "g": "a", "x": 3, "y": 5}, {1: 2}] - with pytest.raises( - InputValidationError, match=r"Source row 1.*needs string field names" - ) as info: - PollingSource( - _Poll(None, iter(rows) if as_iterator else rows), - TAGS, - source_id="poll", - record_id_columns="k", - ).as_table() - cause = info.value.__cause__ - assert isinstance(cause, InputValidationError) - assert str(cause) == "needs string field names." - - def _late_reserved_rows(reverse: bool) -> list[dict[str, int]]: rows = [{"g": 0, "k": i, "x": i + 1, "y": i + 2} for i in range(1002)] names = ("_foo", "_source_x") @@ -465,19 +434,6 @@ def rows() -> Iterator[dict[str, int]]: assert source.source_id == expected.source_id -def test_polling_stops_after_the_first_invalid_iterator_row() -> None: - def rows() -> Iterator[dict[str, int]]: - yield {"k": 1, "x": 2, "_foo": 3, "_source_x": 4} - pytest.fail("reserved fields must stop iteration") - - with pytest.raises( - InputValidationError, match="'_foo'.*'_source_x'.*drop them first" - ): - PollingSource( - _Poll(None, rows()), ["k"], source_id="poll", record_id_columns="k" - ).as_table() - - @dataclass class _FrameRow: k: int @@ -490,29 +446,6 @@ class _EquivalentFrameRow: x: int -@dataclass -class _ReservedFrameRow: - k: int - _foo: int - - -@dataclass -class _ExtendedFrameRow(_FrameRow): - _foo: int - - -@dataclass -class _RenamedFrameRow: - k: int - y: int - - -@dataclass -class _ReorderedFrameRow: - x: int - k: int - - @dataclass class _NestedFrameValue: value: int @@ -564,13 +497,6 @@ class _ReorderedTypedFrameModel(BaseModel): k: int -class _FrameModel(BaseModel): - model_config = ConfigDict(extra="allow") - - k: int - x: int - - class _PlainFrameModel(BaseModel): k: int x: int @@ -585,13 +511,6 @@ class _AliasedFrameModel(_PlainFrameModel): x: int = Field(serialization_alias="value") -class _ReservedComputedFrameModel(_PlainFrameModel): - @computed_field # type: ignore[prop-decorator] - @property - def _foo(self) -> int: - return 12345 - - class _ComputedFrameModel(_PlainFrameModel): @computed_field # type: ignore[prop-decorator] @property @@ -620,106 +539,6 @@ def total(self) -> int: return self.k + self.x.x -def _model_with_explicit_attribute() -> _PlainFrameModel: - row = _PlainFrameModel(k=2, x=4) - object.__setattr__(row, "_raw", 12345) - return row - - -FRAME_ROW_CASES = [ - pytest.param( - [None] - + [{"k": i, "x": i + 2} for i in range(101)] - + [{"k": 101, "x": 102, "_foo": 12345}], - "'_foo'.*drop them first", - id="leading-null", - ), - pytest.param( - [_FrameRow(i, i + 2) for i in range(101)] + [_ReservedFrameRow(101, 12345)], - "'_foo'.*drop them first", - id="dataclass-replacement", - ), - pytest.param( - [_FrameRow(i, i + 2) for i in range(101)] - + [_ExtendedFrameRow(101, 102, 12345)], - "'_foo'.*drop them first", - id="dataclass-extension", - ), - pytest.param( - [_FrameModel(k=i, x=i + 2) for i in range(101)] - + [_FrameModel.model_validate({"k": 101, "x": 102, "_foo": 12345})], - "'_foo'.*drop them first", - id="pydantic-extra", - ), - pytest.param( - [_ReservedComputedFrameModel(k=1, x=2)], - r"row 0.*'_foo'.*drop them first", - id="pydantic-reserved-computed", - ), - pytest.param( - [ - _PlainFrameModel(k=1, x=2), - _PlainFrameModel(k=2, x=4).model_copy(update={"_foo": 3}), - ], - r"row 1.*'_foo'.*drop them first", - id="pydantic-reserved-undeclared", - ), - pytest.param( - [_PlainFrameModel(k=1, x=2), _model_with_explicit_attribute()], - r"row 1.*'_raw'.*drop them first", - id="pydantic-explicit-instance-attribute", - ), - pytest.param( - [_ComputedFrameModel(k=1, x=2)], - r"row 0.*'total'.*mapping", - id="pydantic-ordinary-computed", - ), - pytest.param( - [_PlainFrameModel(k=1, x=2).model_copy(update={"total": 3})], - r"row 0.*'total'.*mapping", - id="pydantic-ordinary-undeclared", - ), - pytest.param( - [_AliasedFrameModel(k=1, x=2)], - r"row 0.*'value'.*mapping", - id="pydantic-discarded-alias", - ), - pytest.param( - [ - _SerializedFrameModel(k=i, x=_PlainFrameModel(k=i, x=i + 2)) - for i in range(102) - ], - r"'_foo'.*drop them first", - id="pydantic-dynamic-serialization", - ), - pytest.param( - [_FrameRow(i, i + 2) for i in range(101)] + [_RenamedFrameRow(101, 12345)], - r"row 101.*field names.*'x'.*'y'.*same field names", - id="different-legal-fields", - ), - pytest.param( - [{"k": 1, "g": 2, "x": 3, "y": 4}, {"g": 5, "k": 6, "y": 7, "z": 8}], - r"row 1.*Missing \['x'\], extra \['z'\].*same field names.*None", - id="sparse-mapping", - ), - pytest.param( - [_FrameRow(1, 2), _ReorderedFrameRow(4, 3)], - r"row 1.*layout.*'k'.*'x'", - id="reordered-typed-fields", - ), - pytest.param( - [_FrameModel.model_validate({"k": 1, "x": 2, "extra": 3})], - r"row 0.*'extra'.*mapping", - id="legal-model-extra", - ), - pytest.param( - [{"k": 1, "x": 2}, (3, 4)], - r"row 1.*field names.*'k'.*'x'", - id="mixed-named-and-positional-input", - ), -] - - @pytest.mark.parametrize( ("row_type", "x_values", "arrow_type"), [ @@ -848,6 +667,17 @@ def tags(value: int, index: int) -> dict[str, int]: ListSource("value", [10, 20], tag_function=tags) +def test_list_source_accepts_a_tag_from_a_source() -> None: + origin = ArrowTableSource( + pa.table({"k": [1], "g": [2], "x": [3], "y": [4]}), + tag_columns=TAGS, + tag_only_columns=True, + ) + tag = next(iter(origin.iter_data()))[0] + source = ListSource("value", [10], tag_function=lambda *_: tag) + assert source.as_table().to_pylist() == [{"g": 2, "k": 1, "value": 10}] + + def test_rereading_an_orcapod_table_requires_dropping_system_columns() -> None: source = DictSource( [ @@ -892,32 +722,28 @@ def iter_batches(self, query, params=None, batch_size=1000): ) -def test_database_refresh_uses_nullability_observed_by_the_scan() -> None: - """Reject a column change visible when the connector scans the table.""" - +def test_database_reads_column_metadata_once_per_scan() -> None: class Connector(_Connector): - change_at_scan = False + metadata_reads = 0 - def iter_batches( - self, query: str, params: Any = None, batch_size: int = 1000 - ) -> Iterator[pa.RecordBatch]: - """Expose the new schema at scan time.""" - if self.change_at_scan: - index = self.table.schema.get_field_index("extra") - self.table = self.table.set_column( - index, - self.table.schema.field(index).with_nullable(False), - self.table.column(index), - ) - yield from self.table.to_batches() + def get_column_info(self, table_name: str) -> list[ColumnInfo]: + self.metadata_reads += 1 + return [ + ColumnInfo(info.name, info.arrow_type, nullable=False) + if info.name == "extra" + else info + for info in super().get_column_info(table_name) + ] connector = Connector(_table(pa.field("extra", pa.int64()), [3, 4])) - source = DBTableSource(connector, "rows", tag_columns=TAGS, source_id="rows") - before = source.as_table() - connector.change_at_scan = True - with pytest.raises(ValueError, match="changed its columns"): - source.check_for_new_data() - assert source.as_table().equals(before, check_metadata=True) + source = DBTableSource( + connector, "rows", tag_columns=TAGS, tag_only_columns=True, source_id="rows" + ) + assert connector.metadata_reads == 1 + assert not source.as_table().schema.field("extra").nullable + assert not source.check_for_new_data() + assert connector.metadata_reads == 2 + assert not source.as_table().schema.field("extra").nullable @pytest.mark.parametrize("metadata", ["absent", "partial"]) @@ -1479,35 +1305,13 @@ async def close(self) -> None: """There is no connection to close.""" -@pytest.mark.parametrize("rows, message", FRAME_ROW_CASES) -@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) -@pytest.mark.parametrize("use_iterator", [False, True], ids=["sequence", "iterator"]) -def test_polling_checks_named_row_shapes( - rows: list[Any], message: str, use_async: bool, use_iterator: bool -) -> None: - source = PollingSource( - _Poll(None, iter(rows) if use_iterator else rows), - ["k"], - source_id="poll", - record_id_columns="k", - ) - - async def read_first() -> None: - async with contextlib.aclosing(source.async_iter_data()) as records: - await anext(records, None) - - with pytest.raises(InputValidationError, match=message): - if use_async: - asyncio.run(read_first()) - else: - source.as_table() - - @pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("as_frame", [False, True], ids=["rows", "frame"]) def test_polling_refuses_reserved_frame_names_before_preprocessing( - use_async: bool, + use_async: bool, as_frame: bool ) -> None: - batch = pl.DataFrame({"k": [1, 2], "x": [None, None], "_foo": [3, 4]}) + rows = [{"k": 1, "x": None, "_foo": 3}, {"k": 2, "x": None, "_foo": 4}] + batch = pl.DataFrame(rows) if as_frame else rows source = PollingSource( _Poll(None, batch), ["k"], source_id="poll", record_id_columns="k" ) @@ -1523,33 +1327,6 @@ async def read_first() -> None: source.as_table() -@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) -@pytest.mark.parametrize("reverse", [False, True], ids=["foo-first", "source-first"]) -@pytest.mark.parametrize("as_tag", [False, True], ids=["data", "tag"]) -def test_polling_checks_raw_fields_beyond_polars_inference( - use_async: bool, reverse: bool, as_tag: bool -) -> None: - tags = (*TAGS, "_foo") if as_tag else TAGS - source = PollingSource( - _Poll(None, _late_reserved_rows(reverse)), - tags, - source_id="poll", - record_id_columns="k", - ) - - async def read_first() -> None: - async with contextlib.aclosing(source.async_iter_data()) as rows: - await anext(rows) - - with pytest.raises( - InputValidationError, match="'_foo'.*'_source_x'.*drop them first" - ): - if use_async: - asyncio.run(read_first()) - else: - source.check_for_new_data() - - @pytest.mark.parametrize("declare", [True, False], ids=["schema", "batch"]) @pytest.mark.parametrize("as_tag", [True, False], ids=["tag", "data"]) def test_polling_refuses_reserved_schema_and_batch_columns( @@ -2549,41 +2326,20 @@ async def read() -> list[dict[str, Any]]: return asyncio.run(read()) -@pytest.mark.parametrize("kind", ["dataclass", "model"]) -@pytest.mark.parametrize("value", [4.9, 4.0], ids=["lossy", "exact"]) -@pytest.mark.parametrize("iterator", [False, True], ids=["sequence", "iterator"]) @pytest.mark.parametrize("path", ["poll-sync", "poll-async"]) -def test_polling_refuses_lossy_mixed_typed_values( - kind: str, value: float, iterator: bool, path: str -) -> None: - @dataclass - class FloatRow: - k: int - x: float - - class FloatModel(BaseModel): - k: int - x: float - - rows = ( - [_FrameRow(1, 2), FloatRow(3, value)] - if kind == "dataclass" - else [_PlainFrameModel(k=1, x=2), FloatModel(k=3, x=value)] - ) - data = iter(rows) if iterator else rows - expected = [{"k": 1, "x": 2}, {"k": 3, "x": 4}] - - def read() -> list[dict[str, Any]]: - poll = PollingSource( - _Poll(None, data), ["k"], source_id="poll", record_id_columns="k" - ) - return _read_frame_poll(poll, path, 2) - - if value == 4.0: - assert read() == expected +@pytest.mark.parametrize("kind", ["sparse", "computed", "aliased"]) +def test_polling_keeps_polars_column_layout(kind: str, path: str) -> None: + if kind == "sparse": + batch = [{"k": 1, "x": 3}, {"k": 2}] + expected = [{"k": 1, "x": 3}, {"k": 2, "x": None}] else: - with pytest.raises(InputValidationError, match=r"column 'x'.*without losing"): - read() + model = _ComputedFrameModel if kind == "computed" else _AliasedFrameModel + batch = [model(k=1, x=3), model(k=2, x=4)] + expected = [{"k": 1, "x": 3}, {"k": 2, "x": 4}] + source = PollingSource( + _Poll(None, batch), ["k"], source_id="poll", record_id_columns="k" + ) + assert _read_frame_poll(source, path, 2) == expected @pytest.mark.parametrize("view", ["operator-replay", "operator-records", "derived"]) @@ -2653,58 +2409,6 @@ def test_cached_source_refuses_reserved_stored_user_columns() -> None: cached.as_table() -@pytest.mark.parametrize("path", ["poll-sync", "poll-async"]) -@pytest.mark.parametrize( - ("kind", "field"), - [("namedtuple", "_1"), ("namedtuple", "label"), ("series", "_hidden")], -) -def test_polling_numpy_first_batch_refuses_names_that_would_be_lost( - path: str, kind: str, field: str -) -> None: - from collections import namedtuple - - import numpy as np - - column: Any - if kind == "series": - column = pl.Series(field, [3, 4]) - elif field == "_1": - row = namedtuple("ReservedRecord", ["label", "_hidden"], rename=True) - column = row(3, 4) - else: - row = namedtuple("OrdinaryRecord", ["label", "value"]) - column = row(3, 4) - batch = [np.array([1, 2]), column] - - with pytest.raises(InputValidationError, match=escape(repr(field))): - source = PollingSource( - _Poll(None, batch), - ["column_0"], - source_id="poll", - record_id_columns="column_0", - ) - _read_frame_poll(source, path, 2) - - -@pytest.mark.parametrize("system_field", ["_tag_fake", "_tag::fake"]) -def test_list_source_checks_callback_tag_before_projection(system_field: str) -> None: - from orcapod.core.datagrams import Tag - - def tag(value: int, index: int) -> Tag: - return Tag({"label": index, system_field: value, "__meta": value}) - - with pytest.raises(InputValidationError) as exc: - ListSource("value", [1, 2], tag_function=tag, expected_tag_keys=["label"]) - assert repr(system_field) in str(exc.value) - assert "'__meta'" in str(exc.value) - assert "drop them first" in str(exc.value) - - valid = ListSource( - "value", [3], tag_function=lambda _, index: Tag({"label": index}) - ) - assert valid.as_table().to_pylist() == [{"label": 0, "value": 3}] - - def test_dataframe_source_checks_declared_names_before_reading_input() -> None: def unreadable() -> Iterator[dict[str, int]]: yield from () From 2455fc91c6b229c3f1e5b33297e73a253f99442d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 21:13:13 -0800 Subject: [PATCH 21/21] fix(spiraldb): reject key-only historical snapshots --- .../core/sources/spiraldb_table_source.py | 22 ++++--------------- .../sources/test_source_arrow_validation.py | 11 +++------- .../sources/test_spiraldb_lookups.py | 16 ++++++-------- .../test_spiraldb_table_source_streaming.py | 14 +++++++----- 4 files changed, 23 insertions(+), 40 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index ec8155c2a..ca1f243e2 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -65,8 +65,8 @@ SourceStreamBuilder, key_column_type_allowed, normalize_record_id_columns, - require_source_column_names, require_live_logical_types, + require_source_column_names, require_supported_nullable_types, row_identifiers, ) @@ -405,13 +405,6 @@ def __init__( # record), also a given older one, so a read makes no metadata call. schema = table.arrow_schema(asof=asof) require_source_column_names(schema.names) - if asof is not None and set(schema.names) == set(primary_key): - # Before the first write SpiralDB exposes only the keys. Keep the - # empty result's data columns from the current schema. - schema = arrow_utils.drop_system_columns( - table.arrow_schema().empty_table() - ).schema - require_source_column_names(schema.names) require_supported_nullable_types(schema) # One version for every read of this source object. A given version is # used as it is; a table that was never written has no version to pin. @@ -910,7 +903,7 @@ def check_for_new_data(self) -> bool: try: moved = self._check_table() # Every refusal is held: TableSchemaError and a missing table are - # ValueErrors, a reserved column name an InputValidationError. + # ValueErrors, a reserved system-tag column an InputValidationError. except (ValueError, InputValidationError) as exc: self._refusal = exc raise @@ -935,17 +928,10 @@ def _check_table(self) -> bool: raw_schema = table.arrow_schema(asof=given) require_source_column_names(raw_schema.names) schema = arrow_utils.drop_system_columns(raw_schema.empty_table()).schema - # A snapshot before the first write exposes only the keys. Its output - # template has data columns, but the check compares the pinned schemas. - expected = ( - self._table_schema - if given is None - else self._handle.arrow_schema(asof=given) - ) - if not schema.equals(expected, check_metadata=True): + if not schema.equals(self._table_schema, check_metadata=True): raise ValueError( f"SpiralDB table {self._qualified!r}: " - f"{_schema_difference(schema, expected)}. Build the " + f"{_schema_difference(schema, self._table_schema)}. Build the " "source again to read it as it is now." ) if given is not None: diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 2aa021c1f..156f6f6b0 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -2006,7 +2006,7 @@ def test_spiral_validates_reserved_null_in_an_empty_scan_batch( def test_spiral_validates_reserved_names_at_the_pinned_version(tmp_path: Path) -> None: - """Columns added later cannot block an older SpiralDB snapshot.""" + """Build validates the pinned schema, regardless of the current schema.""" rows = pa.table({"k": ["a"], "x": [1]}) with fake_spiral_sdk.install(tmp_path): project = fake_spiral_sdk.ExternalProject("project") @@ -2015,20 +2015,15 @@ def test_spiral_validates_reserved_names_at_the_pinned_version(tmp_path: Path) - ) external.write(rows) before = external.last_modified_at() - external.write(pa.table({"k": ["b"], "x": [2], "_tag_extra": [3]})) + external.write(pa.table({"k": ["b"], "x": [2], "_extra": [3]})) after = external.last_modified_at() historical = SpiralDBTableSource( "project", "rows", asof=before, tag_only_columns=True ) assert historical.as_table().to_pylist() == [{"k": "a", "x": 1}] - empty = SpiralDBTableSource("project", "rows", asof=0, tag_only_columns=True) - assert empty.as_table().column_names == ["k", "x"] - assert empty.as_table().num_rows == 0 for version in (None, after): - with pytest.raises( - InputValidationError, match="'_tag_extra'.*drop them first" - ): + with pytest.raises(InputValidationError, match="'_extra'.*drop them first"): SpiralDBTableSource( "project", "rows", asof=version, tag_only_columns=True ) diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 46231741c..7d67e07a9 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -761,28 +761,26 @@ def slow(self: SpiralDBTableSource) -> bool: assert most == 1 -def test_a_check_refusing_a_reserved_system_tag_column_is_held_by_every_read( - calls: collections.Counter[str], +@pytest.mark.parametrize("reserved", ["_tag_source_id::x", "_extra"]) +def test_a_check_refusing_a_reserved_column_is_held_by_every_read( + calls: collections.Counter[str], reserved: str ) -> None: - """CodeRabbit on #675: a check that refuses because the table now has a column in - the system-tag namespace (an ``InputValidationError``, not a ``ValueError``) is - held like every other refusal: every later read refuses with it, before - scanning, until a check accepts the table again.""" + """A check that refuses a newly added reserved column also blocks later reads.""" source = _source("plain") layout = _ARRANGED["layout"] - reserved = "_tag_source_id::x" table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") widened = _rows(layout, [0, 1, 2]).append_column( pa.field(reserved, pa.large_string()), pa.array(["r"] * 3, pa.large_string()) ) table.write(widened) table.record(widened.schema) - with pytest.raises(InputValidationError, match="reserved for Orcapod"): + with pytest.raises(InputValidationError, match="reserved for Orcapod") as refusal: source.check_for_new_data() calls.clear() for read in _bare_reads(source).values(): - with pytest.raises(InputValidationError, match="reserved for Orcapod"): + with pytest.raises(InputValidationError, match="reserved for Orcapod") as held: read() + assert held.value is refusal.value assert calls == {} diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index dd0296eec..6a920cc12 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -310,11 +310,15 @@ def test_a_given_version_is_used(self, project): assert source.to_config()["asof"] == 1 def test_a_given_version_zero_is_used(self, project): - """Version zero remains pinned for the empty read and subsequent check.""" - source = SpiralDBTableSource(_PROJECT, "event", asof=0, tag_only_columns=True) - assert source.pinned_version == 0 - assert source.check_for_new_data() is False - assert source.as_table().num_rows == 0 + """An ``asof`` of ``0`` is used, not taken as unset. + + The source is built from the version it reads (CodeRabbit on #675), and + version 0 is the table before its first write: key columns only, so the + source is refused for having no data column. Taken as unset, it would + read the latest version and be built. + """ + with pytest.raises(ValueError, match="No data columns"): + SpiralDBTableSource(_PROJECT, "event", asof=0, tag_only_columns=True) class TestRowCap: