diff --git a/.zed/rules b/.zed/rules index beb76d466..47691fb2e 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1419,6 +1419,15 @@ data. The rules: - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). +- Data context v1 gives nested fields produced from Python declarations implicit nullability + (developer, November 28, 2026, ITL-445/ITL-842). For example, `list[int]` and + `list[int | None]` give the same Arrow type. Sources, datagrams and function inputs can + carry a nested null where the codec supports it. A function checks nested values against + each declared output type, using the explicit `output_schema` for that output when + specified and the return annotation otherwise. A plain `T` at any depth refuses `None`. + Top-level flags distinguish T from T | None. An explicit nested Arrow flag is + kept as declared and enters the Arrow schema hash. Strict checking of Python input + annotations at nested positions is a later opt-in (ITL-1584). - normalize_to_large_types changes layouts only: every nested field (list items, struct children, map keys and items) keeps its name, nullability and metadata, so it never changes a schema or value hash. Never rebuild a nested type as pa.large_list(element_type), which diff --git a/CLAUDE.md b/CLAUDE.md index 23d483749..29205c0e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1467,6 +1467,15 @@ data. The rules: - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). +- Data context v1 gives nested fields produced from Python declarations implicit nullability + (developer, November 28, 2026, ITL-445/ITL-842). For example, `list[int]` and + `list[int | None]` give the same Arrow type. Sources, datagrams and function inputs can + carry a nested null where the codec supports it. A function checks nested values against + each declared output type, using the explicit `output_schema` for that output when + specified and the return annotation otherwise. A plain `T` at any depth refuses `None`. + Top-level flags distinguish T from T | None. An explicit nested Arrow flag is + kept as declared and enters the Arrow schema hash. Strict checking of Python input + annotations at nested positions is a later opt-in (ITL-1584). - `normalize_to_large_types` changes layouts only: every nested field (list items, struct children, map keys and items) keeps its name, nullability and metadata, so it never changes a schema or value hash. Never rebuild a nested type as `pa.large_list(element_type)`, which diff --git a/changelog.d/ITL-445.md b/changelog.d/ITL-445.md new file mode 100644 index 000000000..d8d8939fd --- /dev/null +++ b/changelog.d/ITL-445.md @@ -0,0 +1,7 @@ +### Changed + +- Documented implicit nullability for nested fields produced from Python declarations in data context v1. Explicit Arrow flags still distinguish schemas for joins and slot binding, and a refusal now names the differing nested field and explains how to match the flags. + +### Fixed + +- A function pod output declared as `set[T]` must be a `set` instance. Previously accepted non-set iterables, such as lists and `frozenset` instances, now raise an output type error even when their elements are valid. Set elements must match the declared element type. For example, `set[int]` rejects `None` as an element, while `set[int | None]` accepts it. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 3a758b6fe..03d09578f 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -209,10 +209,11 @@ untouched. ## Return values must match the declared type Each value the function returns is checked against its declared output type before it is -stored or hashed. A `float` returned for an output declared `int` is rejected; it is not -truncated. The `OutputTypeError` names the function, the output, the declared type and the -type of the value (never the value itself, which stays on the error's `value` attribute), -and says what to return instead: +stored or hashed. An explicit `output_schema` supplies the type for each output it declares. +For any other output, the type comes from the return annotation. Returning a `float` +for an output declared `int` raises `OutputTypeError`. The error names the function, +the output, the declared type and the type of the value. The value itself stays on the +error's `value` attribute. The error also says what to return instead. ```python from orcapod.errors import OutputTypeError @@ -1322,7 +1323,22 @@ for tag, data in count_rows.pod(readings): ### A `None` inside a container -A `None` inside a list, a set, a dict value or a class field is accepted where its type is +In data context v1, top-level `T` and `T | None` are distinct. Inside a column, Python +declarations produce nullable Arrow fields. For example, `list[int]` and +`list[int | None]` produce the same Arrow type. A function with a `list[int]` parameter +can receive a list containing `None` from a source or datagram. An explicit Arrow +non-null item flag is preserved by the source. + +The declared output type constrains values at every depth. For example, a pod with +`-> list[int]` that returns `[1, None]` raises `OutputTypeError` naming the nested +position. If its explicit `output_schema` declares that output as `list[int | None]`, +the pod stores the list with the missing item. A declared `set[int]` similarly rejects +`{None}`, while `set[int | None]` accepts it. Fixed and heterogeneous tuples are +unsupported as a single pod output. A tuple annotation can describe several separate +outputs. + +When the position admits `None`, it can be stored and read in a list, a set, a dict +value or a class field where its type is a scalar (`int`, `float`, `str`, `bool`, `bytes`, `datetime`, ...) or a class of your own (a dataclass, an `orcapod.dataclass` or a pydantic model): `list[int | None]`, `dict[str, float | None]`, `list[MyData | None]` and a field `x: int | None` store and read diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 4043c7ffe..05f70d013 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -132,6 +132,14 @@ your own, refuses a column whose type is or holds one, naming it (a stream's ide Arrow schema hash, which cannot hold them). Cast a list view to the large list of the same items, and expand a run-end-encoded column with `pyarrow.compute.run_end_decode`. +Top-level `T` and `T | None` describe different column fields. Python declarations +leave nested Arrow fields nullable in data context v1, so `list[int]` and +`list[int | None]` use one Arrow type. A source can carry null items in either case +for supported types. If you supply an Arrow schema, Orcapod keeps its nested flags. +For example, `pa.large_list(pa.field("item", pa.int64(), nullable=False))` declares +required items. That field has a different Arrow schema identity from the default +nullable item. Use matching nested flags when joining sources or binding a slot. + Dictionary-encoded columns are not currently supported in Orcapod, tags and data alike. A column whose Arrow type is a `dictionary`, or holds one inside it (a list of dictionary values, a struct with a dictionary field), is refused with `InputValidationError` when the source or diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 40c13de07..60409af1d 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -66,6 +66,12 @@ print(dict(tag_schema)) # {'subject_id': } print(dict(data_schema)) # {'age': , 'weight': } ``` +The Python schema distinguishes a nullable whole column as `T | None`. A Python +container annotation leaves nested fields nullable in the Arrow schema in data +context v1. For example, `list[int]` can describe a column whose items include +`None`. Inspect `as_table().schema` for explicit nested Arrow flags, which streams +preserve and include in their Arrow identity. + ### `keys()` Returns column names as `(tag_keys, data_keys)`: diff --git a/docs/concepts/your-own-data-types.md b/docs/concepts/your-own-data-types.md index f535c0e33..87f903309 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -38,6 +38,13 @@ although a pod can observe them. Changing one of them keeps the type and its sto results. If such a change alters what a pod computes, bump the pod's version, as you would for any change to its code. +In data context v1, field annotations in either kind of class produce nullable +Arrow struct children. A class annotation still determines what a function pod +can return. For example, a returned object with `None` in an `int` field raises +`OutputTypeError` naming the field. Annotate it as `int | None` to return missing +values deliberately. Pydantic's own validation still applies whenever it +constructs a model. + ## `op.dataclass` in a notebook `op.dataclass` is used like `dataclasses.dataclass` and returns a real dataclass. Define diff --git a/docs/dev/design_issues/ITL-445-NN1.md b/docs/dev/design_issues/ITL-445-NN1.md new file mode 100644 index 000000000..91da7231f --- /dev/null +++ b/docs/dev/design_issues/ITL-445-NN1.md @@ -0,0 +1,26 @@ +## Arrow types and schema validation + +### NN1 — Implicit nullability for nested Python fields in data context v1 +**Status:** resolved +**Severity:** medium +**Issue:** ITL-445, ITL-842 + +Python container and user-class declarations have been producing nullable nested +Arrow fields even when a child is annotated with plain `T`. Giving the same +column an explicit Arrow schema with a non-null child has always been possible. +That Arrow flag distinguishes schemas, while the Python column hints can appear +identical in diagnostics. + +**Decision (developer, November 28, 2026):** Keep implicit nullability for nested +fields produced from Python declarations in data context v1. Keep every +explicit Arrow flag and the boundary rule for whole columns. Enforce declared +function output types at supported nested positions. Use the explicit +`output_schema` for each output it declares and the return annotation for +the other outputs. A strict nested input policy is a future opt-in under ITL-1584. + +**Fix:** Documented the input, output and storage rules. The shared function +output checker now rejects null items in a required set element position. +Joins and slot binding identify a nested flag mismatch and describe how to +match the two declarations. For a shared data-tag in a multi-input Join, the +diagnostic compares the two inputs that supplied its conflicting types. +Existing schemas, hash labels and golden values stay the same. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 4c9a4af72..1a35f6f37 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1738,6 +1738,15 @@ The same walker gives the form of every other place a schema is compared or save slot made from that source have one Python schema, one Arrow schema and one pipeline hash. +Python declarations produce implicitly nullable nested fields in data context v1. +For example, `list[int]` and `list[int | None]` convert to the same Arrow type +and yield the same Arrow schema hash for that column. An explicit Arrow field +flag is preserved and hashed at every depth, including in a list item or struct +child. A column's top-level nullable flag also enters the hash. Function output +validation uses each declared output type independently of these storage flags. +The type comes from the explicit `output_schema` for that output, or from the +return annotation when the schema supplies no type for it. + What a schema must therefore agree on to be one identity: - **A bind** accepts a source whose Arrow types equal the slot's, as this hash compares them, diff --git a/docs/tutorial/coming-from-pandas-or-polars.md b/docs/tutorial/coming-from-pandas-or-polars.md index 90ac0f764..13161309d 100644 --- a/docs/tutorial/coming-from-pandas-or-polars.md +++ b/docs/tutorial/coming-from-pandas-or-polars.md @@ -191,6 +191,34 @@ print(rates.keys()) ).select(unit_keys + ["rate_hz"]) ``` +## List columns + +A dataframe list column can supply a `list[int]` parameter even when some of its +items are null. A missing item is passed to the function as `None`. This is +separate from the nullability of the whole column and from the return annotation. + +```python +from orcapod.sources import DataFrameSource + + +@function_pod(output_keys="total") +def total_present(counts: list[int]) -> int: + return sum(count for count in counts if count is not None) + + +list_frame = pl_units.head(1).select( + "unit", pl.concat_list("n_spikes", pl.lit(None, dtype=pl.Int64)).alias("counts") +) +for frame in (list_frame, pd.DataFrame(list_frame.to_dicts())): + source = DataFrameSource(frame, tag_columns=["unit"], tag_only_columns=True) + print(source.output_schema()[1]["counts"] == list[int]) + print(total_present.pod(source).as_table()["total"].to_pylist() == pl_units["n_spikes"].head(1).to_list()) +# True +# True +# True +# True +``` + ## Group `group_by` keeps the named tags and gathers each group's `rate_hz` values into a list diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..5b69d510d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1084,6 +1084,17 @@ def _fit(self, source: "StreamProtocol") -> tuple[Schema, Schema, frozenset[str] elif _is_narrower(declared[name], given[name]): narrower.add(name) else: + if compare_arrow: + issue = self._arrow_type_issue( + role, + name, + slot_arrow[role], + source_arrow[role], + nested_only=True, + ) + if issue is not None: + issues.append(issue) + continue issues.append( f"{role} column {name!r} is declared " f"{_type_text(declared[name])} but the source has " @@ -1146,6 +1157,8 @@ def _arrow_type_issue( name: str, slot_schema: "pa.Schema", source_schema: "pa.Schema", + *, + nested_only: bool = False, ) -> str | None: """Compare one column's Arrow type in the slot and in *source* (ITL-640). @@ -1161,6 +1174,8 @@ def _arrow_type_issue( name: The column name. slot_schema: The slot's Arrow schema of that role. source_schema: The source's Arrow schema of that role. + nested_only: Diagnose a nested flag mismatch only. A caller that + already has a Python type error uses this mode. Returns: The issue text, or ``None`` when the types agree. @@ -1172,15 +1187,28 @@ def _arrow_type_issue( if declared.nullable and not given.nullable: given = given.with_nullable(True) hasher = self.data_context.arrow_hasher - if hasher.hash_schema(pa.schema([declared])) == hasher.hash_schema( - pa.schema([given]) - ): + if not nested_only and hasher.hash_schema( + pa.schema([declared]) + ) == hasher.hash_schema(pa.schema([given])): return None issue = ( f"{role} column {name!r} has the Arrow type {_arrow_field_text(declared)} " f"in the slot but {_arrow_field_text(source_schema.field(name))} in the " "source" ) + if declared.nullable == given.nullable: + paths = arrow_utils.nested_nullability_differences( + declared.type, given.type + ) + if paths: + fields = ", ".join(repr(f"{name}.{path}") for path in paths) + return ( + f"{issue}. The Arrow types differ in the nullability of nested " + f"field {fields}. Declare the same nested flags on the slot and " + "source or drop the explicit non-null declaration." + ) + if nested_only: + return None if self._given_arrow_schemas is None: python_type = (self._tag_schema if role == "tag" else self._data_schema)[ name diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index f4baa10f3..32e940c56 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -4,8 +4,12 @@ from abc import abstractmethod from collections.abc import Collection, Sequence from dataclasses import dataclass +from itertools import combinations from typing import TYPE_CHECKING, Any, get_args +import pyarrow as pa + + from orcapod.core.operators.meta_columns import ( without_input_meta, without_meta_fields, @@ -25,8 +29,6 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol @@ -88,6 +90,7 @@ def require_shared_arrow_type( """ shared = arrow_utils.shared_arrow_type(left_type, right_type) if shared is None: + _require_matching_nested_flags(operator, name, left_type, right_type) left_description = arrow_utils.describe_arrow_type(left_type) right_description = arrow_utils.describe_arrow_type(right_type) raise InputValidationError( @@ -99,6 +102,65 @@ def require_shared_arrow_type( return shared +def _require_matching_nested_flags( + operator: str, column: str, left_type: pa.DataType, right_type: pa.DataType +) -> None: + """Name a join's conflicting nested fields and how to make the flags agree.""" + paths = arrow_utils.nested_nullability_differences(left_type, right_type) + if paths: + fields = ", ".join(repr(f"{column}.{path}") for path in paths) + left_description = _describe_with_storage(left_type) + right_description = _describe_with_storage(right_type) + raise InputValidationError( + f"{operator} inputs disagree on the Arrow type of column {column!r}: " + f"{left_description} in one input and {right_description} in the other. " + f"The types differ in the nullability of nested field {fields}. Declare the same " + "nested flags on both inputs or drop the explicit non-null declaration." + ) + + +def _describe_with_storage(arrow_type: pa.DataType) -> str: + """Describe a type so that its nested flags can be read. + + An extension type's text does not show its storage, where its nested flags + are, so the storage type is added. + """ + description = arrow_utils.describe_arrow_type(arrow_type) + if isinstance(arrow_type, pa.BaseExtensionType): + return f"{description} stored as {arrow_type.storage_type}" + return description + + +def explain_nested_join_conflict( + operator: str, + *streams: StreamProtocol, + include_data: bool = False, + column: str | None = None, +) -> None: + """Diagnose nested flags when Python schema validation already failed. + + Synthesized struct classes can differ even when their Python annotations + look alike. Only examine typed Arrow schemas on the error path. + When validation has identified the conflicting column, examine only it. + """ + from orcapod.core.streams.base import typed_arrow_schemas + + try: + schemas = [typed_arrow_schemas(stream) for stream in streams] + except (TypeError, ValueError, InputValidationError): + return # Keep the original validation error if the Arrow schema is unavailable. + roles = 2 if include_data else 1 + for a, b in combinations(schemas, 2): + for left, right in zip(a[:roles], b[:roles], strict=True): + shared = set(left.names) & set(right.names) + if column is not None: + shared &= {column} + for name in sorted(shared): + _require_matching_nested_flags( + operator, name, left.field(name).type, right.field(name).type + ) + + def require_matchable_key(operator: str, name: str, arrow_type: pa.DataType) -> None: """Raise if a join key's type has no rule for matching rows in Polars. diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 06cdcfd26..d9f199509 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -22,6 +22,7 @@ NonZeroInputOperator, require_matchable_key, require_shared_arrow_type, + explain_nested_join_conflict, require_tag_data_roles_agree, ) from orcapod.core.data_tags import ( @@ -206,6 +207,8 @@ def validate_nonzero_inputs(self, *streams: StreamProtocol) -> None: try: self.output_schema(*streams) except Exception as e: + if isinstance(e, TypeError): + explain_nested_join_conflict("Join", *streams) raise InputValidationError(f"Input streams are not compatible: {e}") from e def order_input_streams(self, *streams: StreamProtocol) -> list[StreamProtocol]: @@ -285,6 +288,7 @@ def _joined_user_schemas(self, *streams: StreamProtocol) -> tuple[Schema, Schema tag_schema, data_schema = stream.output_schema() data_schema = without_meta_fields(data_schema) data_tags = set(data_tag_names(tag_schema, data_schema)) + data_tag_sources = dict.fromkeys(data_tags, stream) for other_stream in ordered_streams[1:]: other_tag_schema, other_data_schema = other_stream.output_schema() other_data_schema = without_meta_fields(other_data_schema) @@ -318,6 +322,13 @@ def _joined_user_schemas(self, *streams: StreamProtocol) -> tuple[Schema, Schema ) for name in sorted(merged): if data_schema[name] != other_data_schema[name]: + explain_nested_join_conflict( + "Join", + data_tag_sources[name], + other_stream, + include_data=True, + column=name, + ) raise InputValidationError( f"{type(self).__name__}: data-tag {name!r} has type " f"{data_schema[name]} in one input and " @@ -325,6 +336,8 @@ def _joined_user_schemas(self, *streams: StreamProtocol) -> tuple[Schema, Schema ) tag_schema = schema_utils.union_schemas(tag_schema, other_tag_schema) data_schema = schema_utils.union_schemas(data_schema, other_data_schema) + for name in other_data_tags: + data_tag_sources.setdefault(name, other_stream) data_tags |= other_data_tags check_namespaces(tag_schema, data_schema, data_tags) return tag_schema, data_schema diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 88abafc5a..8e49d0728 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -9,6 +9,7 @@ BinaryOperator, require_matchable_key, require_shared_arrow_type, + explain_nested_join_conflict, require_tag_data_roles_agree, ) from orcapod.core.operators.join import ( @@ -188,6 +189,9 @@ def validate_binary_inputs( left_type = left_data_schema[key] right_type = right_data_schema[key] if left_type != right_type: + explain_nested_join_conflict( + "MergeJoin", left_stream, right_stream, include_data=True + ) raise InputValidationError( f"Colliding data column '{key}' has incompatible types: " f"{left_type} (left) vs {right_type} (right). " @@ -199,6 +203,8 @@ def validate_binary_inputs( except InputValidationError: raise except Exception as e: + if isinstance(e, TypeError): + explain_nested_join_conflict("MergeJoin", left_stream, right_stream) raise InputValidationError( f"Input streams are not compatible for merge join: {e}" ) from e diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index 18d28ea52..d19971bc4 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -17,6 +17,7 @@ BinaryOperator, require_matchable_key, require_shared_arrow_type, + explain_nested_join_conflict, ) from orcapod.core.operators.key_nullability import reconcile_key_nullability from orcapod.core.operators.match_keys import frozen_scalar @@ -312,6 +313,8 @@ def validate_binary_inputs( try: common_keys = self._checked_match_keys(left_stream, right_stream) except Exception as e: + if isinstance(e, TypeError): + explain_nested_join_conflict("SemiJoin", left_stream, right_stream) raise InputValidationError( f"Input streams are not compatible for semi-join: {e}" ) from e diff --git a/src/orcapod/semantic_types/output_conformance.py b/src/orcapod/semantic_types/output_conformance.py index 4cffaae05..1bd1d531e 100644 --- a/src/orcapod/semantic_types/output_conformance.py +++ b/src/orcapod/semantic_types/output_conformance.py @@ -209,6 +209,16 @@ def check(self, value: object, declared: object) -> Nonconformance | None: if mismatch: return _at(mismatch, f"[{index}]") return None + if origin is set: + if not isinstance(value, set): + return Nonconformance( + "", declared, value, "Return a set instead: set(value)" + ) + for item in value: + mismatch = self.check(item, args[0]) + if mismatch: + return _at(mismatch, "[*]") + return None if origin is dict: if not isinstance(value, dict): return Nonconformance( diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c49d1f429..57b5115a5 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -386,6 +386,83 @@ def shared_arrow_type( return None +def nested_nullability_differences( + left_type: pa.DataType, right_type: pa.DataType +) -> tuple[str, ...]: + """Find relative child paths when nested nullability is the only difference. + + Compare large-normalized containers. Type widths, struct field names and + order, list length, map ordering, and logical identifiers still distinguish + types. For matching logical identifiers, compare the declared storage types + recursively. + + Args: + left_type: The first declared Arrow type. + right_type: The second declared Arrow type. + + Returns: + Paths to the differing fields, or an empty tuple if the types agree or + have any difference beyond nested nullability. + """ + from orcapod.logical_types.canonical_form import ( + EXTENSION_METADATA_KEY, + EXTENSION_NAME_KEY, + ) + from orcapod.logical_types.identifier import arrow_type_identifier + + paths: list[str] = [] + + def compare(left: pa.DataType, right: pa.DataType, prefix: str) -> bool: + if isinstance(left, pa.ExtensionType) and isinstance(right, pa.ExtensionType): + if arrow_type_identifier(left) != arrow_type_identifier(right): + return False + return compare(left.storage_type, right.storage_type, prefix) + if left.id != right.id or left.num_fields != right.num_fields: + return False + if ( + isinstance(left, pa.FixedSizeListType) + and isinstance(right, pa.FixedSizeListType) + and left.list_size != right.list_size + ): + return False + if ( + isinstance(left, pa.MapType) + and isinstance(right, pa.MapType) + and left.keys_sorted != right.keys_sorted + ): + return False + if not isinstance( + left, + ( + pa.StructType, + pa.ListType, + pa.LargeListType, + pa.FixedSizeListType, + pa.MapType, + ), + ): + return shared_arrow_type(left, right) is not None + for index in range(left.num_fields): + a, b = left.field(index), right.field(index) + if isinstance(left, pa.StructType) and a.name != b.name: + return False + if any( + (a.metadata or {}).get(key) != (b.metadata or {}).get(key) + for key in (EXTENSION_NAME_KEY, EXTENSION_METADATA_KEY) + ): + return False + path = f"{prefix}{a.name}" + if not compare(a.type, b.type, f"{path}."): + return False + if a.nullable != b.nullable: + paths.append(path) + return True + + left = normalize_to_large_types(left_type, keep_null=True) + right = normalize_to_large_types(right_type, keep_null=True) + return tuple(paths) if compare(left, right, "") else () + + def normalize_table_to_large_types( table: "pa.Table", *, keep_null: bool = False ) -> "pa.Table": diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 419a7b9cc..0ca064757 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -205,7 +205,9 @@ def extract_function_schemas_with_container( output_typespec: Optional type specification for return values. Can be either: - A dict mapping output keys to types (TypeSpec) - A sequence of types that will be mapped to output_keys in order - These types override any inferred types from the function's return annotation. + For each specified output, this is the declared type used for validation, + including nested values. Otherwise the declared type comes from the return + annotation. Returns: A tuple containing: diff --git a/tests/test_core/function_pod/test_nested_output_nullability.py b/tests/test_core/function_pod/test_nested_output_nullability.py new file mode 100644 index 000000000..9833223ea --- /dev/null +++ b/tests/test_core/function_pod/test_nested_output_nullability.py @@ -0,0 +1,228 @@ +"""Python output annotations constrain nullable Arrow children.""" + +import asyncio +from dataclasses import dataclass +from pathlib import Path +from threading import Lock +from typing import Any + +import pytest +from pydantic import BaseModel + +from orcapod import PipelineJob, dataclass as structural_dataclass, function_pod +from orcapod.core.datagrams import Data +from orcapod.core.executors import LocalPythonFunctionExecutor +from orcapod.core.executors.capture_wrapper import make_capture_wrapper +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import OutputTypeError, RowFailuresWarning +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator + +from .test_output_conformance import _CrashRecorder, make_pod, make_source + + +@dataclass +class Required: + count: int + + +@dataclass +class Optional: + count: int | None + + +class RequiredModel(BaseModel): + count: int + + +class OptionalModel(BaseModel): + count: int | None + + +@structural_dataclass +class RequiredStructural: + count: int + + +@structural_dataclass +class OptionalStructural: + count: int | None + + +class _SerializedCaptureExecutor(LocalPythonFunctionExecutor): + """Round-trip the Ray worker's capture closure and response without a cluster.""" + + _capture_lock = Lock() + + def execute_callable( + self, fn, kwargs, executor_options=None, *, logger=None + ) -> Any: + from ray import cloudpickle + + worker, function, arguments = cloudpickle.loads( + cloudpickle.dumps((make_capture_wrapper(), fn, kwargs)) + ) + # The real workers capture in separate processes. Serialize capture here + # because the wrapper redirects process-wide file descriptors. + with self._capture_lock: + raw, *_ = cloudpickle.loads(cloudpickle.dumps(worker(function, arguments))) + return raw + + async def async_execute_callable( + self, fn, kwargs, executor_options=None, *, logger=None + ) -> Any: + return await asyncio.to_thread(self.execute_callable, fn, kwargs) + + +CASES = [ + pytest.param(list[int], [None], list[int | None], [None], "[0]", id="list"), + pytest.param(set[int], {None}, set[int | None], {None}, "[*]", id="set"), + pytest.param( + dict[str, int], + {None: 1}, + dict[str | None, int], + {None: 1}, + ".keys()", + id="dict-key", + ), + pytest.param( + dict[str, int], + {"a": None}, + dict[str, int | None], + {"a": None}, + "[*]", + id="dict-value", + ), + pytest.param( + Required, + Required(None), # pyright: ignore[reportArgumentType] # Test the invalid return. + Optional, + Optional(None), + ".count", + id="dataclass", + ), + pytest.param( + RequiredModel, + RequiredModel.model_construct(count=None), + OptionalModel, + OptionalModel(count=None), + ".count", + id="pydantic", + ), + pytest.param( + RequiredStructural, + RequiredStructural(None), # pyright: ignore[reportArgumentType] # Test the invalid return. + OptionalStructural, + OptionalStructural(None), + ".count", + id="structural", + ), + pytest.param( + list[Required], + [Required(None)], # pyright: ignore[reportArgumentType] # Test the invalid return. + list[Optional], + [Optional(None)], + "[0].count", + id="nested", + ), + pytest.param( + list[Path], [None], list[Path] | None, None, "[0]", id="logical-element" + ), +] + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("route", ["direct", "local", "capture"]) +@pytest.mark.parametrize( + ("required", "invalid", "optional", "valid", "position"), CASES +) +def test_nested_output_nullability( + required, invalid, optional, valid, position, route, asynchronous +): + """Reject a nested None at the annotated position and store its supported Optional form.""" + bad = make_pod(required, invalid, name="bad", async_function=asynchronous) + good = make_pod(optional, valid, name="good", async_function=asynchronous) + if route != "direct": + executor = ( + LocalPythonFunctionExecutor() + if route == "local" + else _SerializedCaptureExecutor() + ) + bad.pod.executor = good.pod.executor = executor + + input_data = Data({"x": 1}, python_schema={"x": int}) + + def call(pod): + function = pod.pod.data_function + if route == "direct": + return ( + asyncio.run(function.direct_async_call(input_data)) + if asynchronous + else function.direct_call(input_data) + ) + return ( + asyncio.run(function.async_call(input_data)) + if asynchronous + else function.call(input_data) + ) + + with pytest.raises(OutputTypeError) as info: + call(bad) + assert f"{position} is NoneType" in str(info.value) + assert call(good).as_dict() == {"y": valid} + + if route != "direct": + observer = _CrashRecorder() + job = PipelineJob(name="nested_outputs", database=InMemoryArrowDatabase()) + with job: + source = make_source() + bad.pod(source, label="bad") + good.pod(source, label="good") + orchestrator = ( + AsyncPipelineOrchestrator() if asynchronous else SyncPipelineOrchestrator() + ) + with pytest.warns(RowFailuresWarning): + job.run(orchestrator=orchestrator, observer=observer) + assert job.nodes["bad"].as_table().num_rows == 0 + assert job.nodes["good"].as_table().num_rows == 1 + [error] = observer.crashes + assert isinstance(error, OutputTypeError) + assert f"{position} is NoneType" in str(error) + + +@pytest.mark.parametrize( + "annotation", + [tuple[int, int], tuple[int, int | None], tuple[int, str], tuple[int | None, str]], +) +def test_tuple_is_not_a_single_pod_output_type(annotation): + """Tuple layouts in Arrow do not imply support for a single tuple output.""" + with pytest.raises(ValueError, match="Unsupported annotation"): + make_pod(annotation, (1, None)) + + +def test_explicit_output_schema_overrides_nested_return_annotation() -> None: + def produce(x: int) -> list[int]: + return [None] * x # pyright: ignore[reportReturnType] # Exercise the conflicting annotation. + + explicit = function_pod( + output_keys="returned", output_schema={"returned": list[int | None]} + )(produce) + annotated = function_pod(output_keys="returned")(produce) + + assert explicit.pod(make_source()).as_table()["returned"].to_pylist() == [[None]] + with pytest.raises(OutputTypeError, match=r"\[0\] is NoneType"): + _ = annotated.pod(make_source()).as_table() + + +def test_optional_logical_item_is_refused_at_construction(): + """The return checker must not silently bypass the ITL-1144 codec guard.""" + with pytest.raises(ValueError, match=r"Column 'y'.*ITL-1144"): + make_pod(list[Path | None], [None]) + + +@pytest.mark.parametrize("value", [[1], frozenset({1}), [None]]) +def test_an_iterable_cannot_bypass_set_output_validation(value): + """An iterable that Arrow can encode as a set is still the wrong output type.""" + pod = make_pod(set[int], value) + data = Data({"x": 1}, python_schema={"x": int}) + with pytest.raises(OutputTypeError, match="Return a set"): + pod.pod.data_function.direct_call(data) diff --git a/tests/test_core/operators/test_nested_nullability_diagnostic.py b/tests/test_core/operators/test_nested_nullability_diagnostic.py new file mode 100644 index 000000000..32f11e104 --- /dev/null +++ b/tests/test_core/operators/test_nested_nullability_diagnostic.py @@ -0,0 +1,271 @@ +"""Shared Arrow columns with different child flags need an actionable error.""" + +import asyncio +from itertools import combinations +from typing import Any +from unittest.mock import Mock + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, SourceNode +from orcapod.channels import Channel +from orcapod.errors import InputValidationError, SourceSpecMismatchError +from orcapod.operators import Join, MapData, MergeJoin, SemiJoin +from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +from orcapod.sources import ArrowTableSource +from orcapod.utils.arrow_utils import nested_nullability_differences + + +class _ListExtension(pa.ExtensionType): + """An extension whose identifier is independent of its list storage flags.""" + + def __init__(self, storage_type: pa.DataType, metadata: bytes = b"") -> None: + self._metadata = metadata + super().__init__(storage_type, "test.nested_nullability_list") + + def __arrow_ext_serialize__(self) -> bytes: + return self._metadata + + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_ListExtension": + return cls(storage_type, serialized) + + +def _extension_list(nullable: bool, metadata: bytes = b"") -> _ListExtension: + return _ListExtension( + pa.large_list(pa.field("item", pa.int64(), nullable=nullable)), metadata + ) + + +def _source( + name: str, + data_name: str, + *, + nullable: bool, + shape: str = "struct-item", + scalar: pa.DataType = pa.int64(), + data_tag: bool = False, +): + item: pa.Field[Any] = ( + pa.field("item", pa.struct([pa.field("code", scalar, nullable=nullable)])) + if shape == "struct-item" + else pa.field("item", scalar, nullable=nullable) + ) + key = pa.large_list(item) + value = [{"code": 1}] if shape == "struct-item" else [1] + keys: pa.Array[Any] = pa.array([value], type=key) + if shape == "extension-list": + keys = pa.ExtensionArray.from_storage(_ListExtension(key), keys) + table = pa.table({"k": keys, data_name: pa.array([2], type=pa.int64())}) + return ArrowTableSource( + table, + tag_columns=["k"], + tag_only_columns=not data_tag, + # ArrowTableSource infers data-tags from tag_only_columns. + source_id=name, + ) + + +async def _execute( + operator: Join | MergeJoin | SemiJoin, *streams: ArrowTableSource +) -> None: + """Feed the async row path with the same explicit Arrow schemas.""" + operator.validate_inputs(*streams) + inputs = [Channel[tuple[TagProtocol, DataProtocol]](buffer_size=4) for _ in streams] + output = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=4) + for stream, channel in zip(streams, inputs, strict=True): + for row in stream.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + await operator.async_execute( + [channel.reader for channel in inputs], + output.writer, + input_pipeline_hashes=[stream.pipeline_hash() for stream in streams], + ) + + +def _assert_remedy(message: str, field: str) -> None: + """Both repairs must be available in the error.""" + assert f"nullability of nested field {field!r}" in message + assert "declare the same nested flags" in message.lower() + assert "drop the explicit non-null declaration" in message + + +def _assert_names_both_types(message: str, shape: str) -> None: + """The error names the column and both input types, each with its flags.""" + child = "struct" if shape == "struct-item" else "int64{}" + nullable = f"large_list" + non_null = f"large_list" + assert "column 'k'" in message + if shape == "extension-list": + # An extension type's own text hides its storage, where the flag is. + nullable, non_null = f"stored as {nullable}", f"stored as {non_null}" + assert f"{nullable} in " in message + assert f"{non_null} in " in message + assert " in one input and " in message + + +@pytest.mark.parametrize("operator_class", [Join, MergeJoin, SemiJoin]) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("shape", ["list", "struct-item", "extension-list"]) +def test_joins_name_the_nested_flag(operator_class, asynchronous, shape): + """A nested-only mismatch gets the same remedy on both paths.""" + left = _source("a", "v", nullable=True, shape=shape) + right = _source("b", "w", nullable=False, shape=shape) + operator = operator_class() + with pytest.raises((InputValidationError, ExceptionGroup)) as error: + if asynchronous: + asyncio.run(_execute(operator, left, right)) + else: + operator(left, right).as_table() + value = error.value + if isinstance(value, ExceptionGroup): + [value] = value.exceptions + assert isinstance(value, InputValidationError) + _assert_remedy(str(value), "k.item.code" if shape == "struct-item" else "k.item") + _assert_names_both_types(str(value), shape) + + +def test_another_type_difference_keeps_the_generic_message(): + """Do not suggest changing flags alone when a scalar width differs.""" + left = _source("a", "v", nullable=True) + right = _source("b", "w", nullable=False, scalar=pa.int8()) + with pytest.raises(InputValidationError, match="not compatible") as error: + Join()(left, right).as_table() + assert "drop the explicit non-null declaration" not in str(error.value) + + +def test_join_names_nested_flag_in_shared_data_tag(): + """A merged data-tag type mismatch gets the same nested-field remedy.""" + left = _source("a", "v", nullable=True, shape="struct-item", data_tag=True) + right = _source("b", "w", nullable=False, shape="struct-item", data_tag=True) + with pytest.raises(InputValidationError) as error: + Join()(left, right).as_table() + _assert_remedy(str(error.value), "k.item.code") + _assert_names_both_types(str(error.value), "struct-item") + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("reverse_inputs", [False, True], ids=["forward", "reverse"]) +@pytest.mark.parametrize( + ("arity", "pair"), + [(arity, pair) for arity in (3, 4) for pair in combinations(range(arity), 2)], +) +def test_join_names_nested_flag_in_any_data_tag_pair( + monkeypatch: pytest.MonkeyPatch, + arity: int, + pair: tuple[int, int], + reverse_inputs: bool, + asynchronous: bool, +) -> None: + """Join diagnoses the conflicting data-tag at any two canonical positions.""" + streams: list[ArrowTableSource] = [] + for position in range(arity): + columns: dict[str, pa.Array[Any]] = { + "batch": pa.array([1]), + "group": pa.array([2]), + f"value_{position}": pa.array([3]), + } + tags = ["batch", "group"] + if position in pair: + item = pa.struct( + [pa.field("code", pa.int64(), nullable=position == pair[0])] + ) + columns["k"] = pa.array([[{"code": 1}]], type=pa.large_list(item)) + tags.append("k") + if reverse_inputs: + columns = dict(reversed(list(columns.items()))) + tags.reverse() + streams.append( + ArrowTableSource( + pa.Table.from_arrays(list(columns.values()), names=list(columns)), + tag_columns=tags, + tag_only_columns=["batch"], + source_id=f"input_{position}", + ) + ) + + # Assign the real hashes by rank so the pair occupies the specified + # positions while Join still sorts the inputs itself. + hashes = sorted( + (stream.pipeline_hash() for stream in streams), key=lambda h: h.to_hex() + ) + for stream, pipeline_hash in zip(streams, hashes, strict=True): + monkeypatch.setattr(stream, "pipeline_hash", Mock(return_value=pipeline_hash)) + if reverse_inputs: + streams.reverse() + + operator = Join() + with pytest.raises(InputValidationError) as error: + if asynchronous: + asyncio.run(_execute(operator, *streams)) + else: + _ = operator(*streams).as_table() + _assert_remedy(str(error.value), "k.item.code") + _assert_names_both_types(str(error.value), "struct-item") + + +def test_a_flag_and_a_logical_identifier_are_two_differences(): + """Logical identifiers in Arrow field metadata can also distinguish types.""" + left = pa.struct( + [ + pa.field( + "value", pa.large_string(), metadata={b"ARROW:extension:name": b"path"} + ) + ] + ) + right = pa.struct( + [ + pa.field( + "value", + pa.large_string(), + nullable=False, + metadata={b"ARROW:extension:name": b"file"}, + ) + ] + ) + assert nested_nullability_differences(left, right) == () + + +def test_an_extension_flag_and_different_serialized_metadata_are_two_differences(): + """Extension storage is comparable only when its full identifier agrees.""" + assert ( + nested_nullability_differences( + _extension_list(True, b"first"), _extension_list(False, b"second") + ) + == () + ) + + +def test_an_extension_flag_and_a_storage_layout_are_two_differences(): + """Changing flags alone cannot reconcile a storage layout mismatch.""" + left = _ListExtension(pa.list_(pa.int64())) + assert nested_nullability_differences(left, _extension_list(False)) == () + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("shape", ["list", "struct-item", "extension-list"]) +def test_slot_binding_names_the_nested_flag(asynchronous, shape): + """Both job routes reject this declaration at their shared binding boundary.""" + slot = SourceNode.from_stream( + _source("a", "v", nullable=True, shape=shape), name="src" + ) + other = _source("b", "v", nullable=False, shape=shape) + with PipelineJob(name="nested_flags") as job: + MapData({"v": "out"})(slot, label="op") + + async def bind_and_run(): + job.bind(sources={"src": other}) + await job.run_async() + + with pytest.raises(SourceSpecMismatchError) as error: + if asynchronous: + asyncio.run(bind_and_run()) + else: + job.bind(sources={"src": other}) + _assert_remedy( + str(error.value), "k.item.code" if shape == "struct-item" else "k.item" + ) diff --git a/tests/test_semantic_types/test_nested_none_guard.py b/tests/test_semantic_types/test_nested_none_guard.py index b6ea9409b..7e185c37d 100644 --- a/tests/test_semantic_types/test_nested_none_guard.py +++ b/tests/test_semantic_types/test_nested_none_guard.py @@ -159,6 +159,21 @@ def test_round_trips(self, annotation: Any, value: Any) -> None: assert read_hash == written_hash +def test_plain_list_input_keeps_implicit_nullable_items() -> None: + """Both Python annotations describe the same Arrow schema and admit input nulls.""" + plain = _source([None, 1], list[int]) + optional = _source([None, 1], list[int | None]) + assert plain.as_table().schema == optional.as_table().schema + assert plain.pipeline_hash() == optional.pipeline_hash() + assert _read_v(plain) == _read_v(optional) + + @op.function_pod(output_keys="count") + def count_missing(v: list[int]) -> int: + return sum(value is None for value in v) + + assert count_missing.pod(plain).as_table()["count"].to_pylist() == [1] + + class TestRaisedAtRead: """A stored None the read cannot restore raises instead of a wrong value."""