From 04876f5507296039444391853ddbe165a61b4c22 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:30:18 -0800 Subject: [PATCH 1/7] fix(types): enforce set outputs and document nested nullability --- .zed/rules | 8 + CLAUDE.md | 8 + changelog.d/ITL-445.md | 7 + docs/concepts/function-pods.md | 16 +- docs/concepts/sources.md | 8 + docs/concepts/streams.md | 6 + docs/concepts/your-own-data-types.md | 7 + docs/dev/design_issues/ITL-445-NN1.md | 24 ++ docs/reference/hashing.md | 7 + docs/tutorial/coming-from-pandas-or-polars.md | 28 +++ src/orcapod/core/nodes/source_node.py | 34 ++- src/orcapod/core/operators/base.py | 39 ++++ src/orcapod/core/operators/join.py | 3 + src/orcapod/core/operators/merge_join.py | 6 + src/orcapod/core/operators/semijoin.py | 3 + .../semantic_types/output_conformance.py | 6 + src/orcapod/utils/arrow_utils.py | 61 ++++++ .../test_nested_output_nullability.py | 205 ++++++++++++++++++ .../test_nested_nullability_diagnostic.py | 110 ++++++++++ .../test_nested_none_guard.py | 15 ++ 20 files changed, 597 insertions(+), 4 deletions(-) create mode 100644 changelog.d/ITL-445.md create mode 100644 docs/dev/design_issues/ITL-445-NN1.md create mode 100644 tests/test_core/function_pod/test_nested_output_nullability.py create mode 100644 tests/test_core/operators/test_nested_nullability_diagnostic.py diff --git a/.zed/rules b/.zed/rules index bcfb8afbf..fc526540e 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1413,6 +1413,14 @@ 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's return annotation still + constrains nested values, and its output check refuses a None where the annotation says + plain T. 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 dd9e6450e..6ac6b2b89 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1461,6 +1461,14 @@ 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's return annotation still + constrains nested values, and its output check refuses a None where the annotation says + plain T. 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..4f9141222 --- /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 + +- Function pods now reject a returned `None` inside a set whose element annotation is non-optional, such as `set[int]`. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 9de222bca..1f995e12b 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -1317,7 +1317,21 @@ 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 return annotation constrains the values a function can return. A pod returning +`[1, None]` for `-> list[int]`, or `{None}` for `-> set[int]`, raises +`OutputTypeError` naming the nested position. Use `list[int | None]` or +`set[int | None]` when the function intentionally returns missing items. Fixed and +heterogeneous tuples are unsupported as a single pod output. A tuple annotation can +still 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 589c57427..f39491654 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..843f0bc12 --- /dev/null +++ b/docs/dev/design_issues/ITL-445-NN1.md @@ -0,0 +1,24 @@ +## 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 function +return annotations at supported nested positions. 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. Existing schemas, hash labels and golden values +stay the same. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e05ee87b3..0c1b23bca 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1729,6 +1729,13 @@ 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 the return annotation independently of these storage flags. + 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 c0fd0c320..4f9d96191 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -3,6 +3,7 @@ import asyncio from abc import abstractmethod from collections.abc import Collection, Sequence +from itertools import combinations from typing import TYPE_CHECKING, Any from orcapod.core.operators.meta_columns import ( @@ -55,6 +56,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( @@ -66,6 +68,43 @@ 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) + raise InputValidationError( + f"{operator} inputs disagree on column {column!r}: their Arrow types " + f"differ in the nullability of nested field {fields}. Declare the same " + "nested flags on both inputs or drop the explicit non-null declaration." + ) + + +def explain_nested_join_conflict( + operator: str, *streams: StreamProtocol, include_data: bool = False +) -> 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. + """ + 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): + for name in sorted(set(left.names) & set(right.names)): + _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..70ccdaa3c 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]: 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 d2a379f50..645fd0457 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 @@ -307,6 +308,8 @@ def validate_binary_inputs( ) 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..b3a5309ac 100644 --- a/src/orcapod/semantic_types/output_conformance.py +++ b/src/orcapod/semantic_types/output_conformance.py @@ -209,6 +209,12 @@ def check(self, value: object, declared: object) -> Nonconformance | None: if mismatch: return _at(mismatch, f"[{index}]") return None + if origin is set and isinstance(value, set): + 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..b989fd621 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -386,6 +386,67 @@ 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. Logical storage is opaque here. + + 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. + """ + paths: list[str] = [] + + def compare(left: pa.DataType, right: pa.DataType, prefix: str) -> bool: + 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 + 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/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..922ce3589 --- /dev/null +++ b/tests/test_core/function_pod/test_nested_output_nullability.py @@ -0,0 +1,205 @@ +"""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 +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_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]) 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..602f38e13 --- /dev/null +++ b/tests/test_core/operators/test_nested_nullability_diagnostic.py @@ -0,0 +1,110 @@ +"""Shared Arrow columns with different child flags need an actionable error.""" + +import asyncio +from typing import Any + +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.sources import ArrowTableSource + + +def _source( + name: str, + data_name: str, + *, + nullable: bool, + structured: bool = True, + scalar: pa.DataType = pa.int64(), +): + item: pa.Field[Any] = ( + pa.field("item", pa.struct([pa.field("code", scalar, nullable=nullable)])) + if structured + else pa.field("item", scalar, nullable=nullable) + ) + key = pa.large_list(item) + schema = pa.schema([pa.field("k", key), pa.field(data_name, pa.int64())]) + value = [{"code": 1}] if structured else [1] + table = pa.Table.from_pylist([{"k": value, data_name: 2}], schema=schema) + return ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id=name + ) + + +async def _execute(operator, left, right): + """Feed the async row path with the same explicit Arrow schemas.""" + operator.validate_inputs(left, right) + inputs = [Channel(buffer_size=4), Channel(buffer_size=4)] + output = Channel(buffer_size=4) + for stream, channel in zip((left, right), 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=[left.pipeline_hash(), right.pipeline_hash()], + ) + + +def _assert_remedy(message, field): + """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 + + +@pytest.mark.parametrize("operator_class", [Join, MergeJoin, SemiJoin]) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("structured", [False, True], ids=["list", "struct-item"]) +def test_joins_name_the_nested_flag(operator_class, asynchronous, structured): + """A nested-only mismatch gets the same remedy on both paths.""" + left = _source("a", "v", nullable=True, structured=structured) + right = _source("b", "w", nullable=False, structured=structured) + 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 structured else "k.item") + + +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) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("structured", [False, True], ids=["list", "struct-item"]) +def test_slot_binding_names_the_nested_flag(asynchronous, structured): + """Both job routes reject this declaration at their shared binding boundary.""" + slot = SourceNode.from_stream( + _source("a", "v", nullable=True, structured=structured), name="src" + ) + other = _source("b", "v", nullable=False, structured=structured) + 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 structured 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.""" From ba0e1dbd007ca2ee84533c2d354b517a9a6e3b53 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:32:39 -0800 Subject: [PATCH 2/7] fix(types): distinguish nested logical identifiers in diagnostics --- src/orcapod/core/operators/base.py | 4 ++-- src/orcapod/utils/arrow_utils.py | 10 ++++++++ .../test_nested_nullability_diagnostic.py | 23 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index 4f9d96191..62f1a1f09 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -76,8 +76,8 @@ def _require_matching_nested_flags( if paths: fields = ", ".join(repr(f"{column}.{path}") for path in paths) raise InputValidationError( - f"{operator} inputs disagree on column {column!r}: their Arrow types " - f"differ in the nullability of nested field {fields}. Declare the same " + f"{operator} inputs disagree on the Arrow type of column {column!r}. " + 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." ) diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index b989fd621..232d020ba 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -403,6 +403,11 @@ def nested_nullability_differences( 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, + ) + paths: list[str] = [] def compare(left: pa.DataType, right: pa.DataType, prefix: str) -> bool: @@ -435,6 +440,11 @@ def compare(left: pa.DataType, right: pa.DataType, prefix: str) -> bool: 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 diff --git a/tests/test_core/operators/test_nested_nullability_diagnostic.py b/tests/test_core/operators/test_nested_nullability_diagnostic.py index 602f38e13..4907438b2 100644 --- a/tests/test_core/operators/test_nested_nullability_diagnostic.py +++ b/tests/test_core/operators/test_nested_nullability_diagnostic.py @@ -11,6 +11,7 @@ from orcapod.errors import InputValidationError, SourceSpecMismatchError from orcapod.operators import Join, MapData, MergeJoin, SemiJoin from orcapod.sources import ArrowTableSource +from orcapod.utils.arrow_utils import nested_nullability_differences def _source( @@ -87,6 +88,28 @@ def test_another_type_difference_keeps_the_generic_message(): assert "drop the explicit non-null declaration" not in str(error.value) +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) == () + + @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize("structured", [False, True], ids=["list", "struct-item"]) def test_slot_binding_names_the_nested_flag(asynchronous, structured): From 8e59357221870db4f313b92c25a7b6ad6df6ec2f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:37:59 -0800 Subject: [PATCH 3/7] fix(types): prevent iterable bypass of set output checks --- changelog.d/ITL-445.md | 2 +- src/orcapod/semantic_types/output_conformance.py | 6 +++++- .../function_pod/test_nested_output_nullability.py | 8 ++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/changelog.d/ITL-445.md b/changelog.d/ITL-445.md index 4f9141222..b6e725608 100644 --- a/changelog.d/ITL-445.md +++ b/changelog.d/ITL-445.md @@ -4,4 +4,4 @@ ### Fixed -- Function pods now reject a returned `None` inside a set whose element annotation is non-optional, such as `set[int]`. +- Function pods now check set outputs against their declared type and reject a returned `None` when the element annotation is non-optional, such as `set[int]`. diff --git a/src/orcapod/semantic_types/output_conformance.py b/src/orcapod/semantic_types/output_conformance.py index b3a5309ac..1bd1d531e 100644 --- a/src/orcapod/semantic_types/output_conformance.py +++ b/src/orcapod/semantic_types/output_conformance.py @@ -209,7 +209,11 @@ def check(self, value: object, declared: object) -> Nonconformance | None: if mismatch: return _at(mismatch, f"[{index}]") return None - if origin is set and isinstance(value, set): + 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: diff --git a/tests/test_core/function_pod/test_nested_output_nullability.py b/tests/test_core/function_pod/test_nested_output_nullability.py index 922ce3589..bebd86e62 100644 --- a/tests/test_core/function_pod/test_nested_output_nullability.py +++ b/tests/test_core/function_pod/test_nested_output_nullability.py @@ -203,3 +203,11 @@ 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]) + + +def test_an_iterable_cannot_bypass_set_output_validation(): + """An iterable that Arrow can encode as a set is still the wrong output type.""" + pod = make_pod(set[int], [None]) + data = Data({"x": 1}, python_schema={"x": int}) + with pytest.raises(OutputTypeError, match="Return a set"): + pod.pod.data_function.direct_call(data) From 9712abce6f3e79bc1fcb20fb1616dcb7ad81cdcc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 20:13:17 -0800 Subject: [PATCH 4/7] fix(types): diagnose nested flags in extension storage --- changelog.d/ITL-445.md | 2 +- src/orcapod/utils/arrow_utils.py | 8 +- .../test_nested_output_nullability.py | 5 +- .../test_nested_nullability_diagnostic.py | 73 +++++++++++++++---- 4 files changed, 69 insertions(+), 19 deletions(-) diff --git a/changelog.d/ITL-445.md b/changelog.d/ITL-445.md index b6e725608..eaccf47a7 100644 --- a/changelog.d/ITL-445.md +++ b/changelog.d/ITL-445.md @@ -4,4 +4,4 @@ ### Fixed -- Function pods now check set outputs against their declared type and reject a returned `None` when the element annotation is non-optional, such as `set[int]`. +- A function pod annotated to return `set[T]` must return 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/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 232d020ba..57b5115a5 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -393,7 +393,8 @@ def nested_nullability_differences( Compare large-normalized containers. Type widths, struct field names and order, list length, map ordering, and logical identifiers still distinguish - types. Logical storage is opaque here. + types. For matching logical identifiers, compare the declared storage types + recursively. Args: left_type: The first declared Arrow type. @@ -407,10 +408,15 @@ def nested_nullability_differences( 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 ( diff --git a/tests/test_core/function_pod/test_nested_output_nullability.py b/tests/test_core/function_pod/test_nested_output_nullability.py index bebd86e62..9c2e207a1 100644 --- a/tests/test_core/function_pod/test_nested_output_nullability.py +++ b/tests/test_core/function_pod/test_nested_output_nullability.py @@ -205,9 +205,10 @@ def test_optional_logical_item_is_refused_at_construction(): make_pod(list[Path | None], [None]) -def test_an_iterable_cannot_bypass_set_output_validation(): +@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], [None]) + 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 index 4907438b2..591214b68 100644 --- a/tests/test_core/operators/test_nested_nullability_diagnostic.py +++ b/tests/test_core/operators/test_nested_nullability_diagnostic.py @@ -14,23 +14,48 @@ 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, - structured: bool = True, + shape: str = "struct-item", scalar: pa.DataType = pa.int64(), ): item: pa.Field[Any] = ( pa.field("item", pa.struct([pa.field("code", scalar, nullable=nullable)])) - if structured + if shape == "struct-item" else pa.field("item", scalar, nullable=nullable) ) key = pa.large_list(item) - schema = pa.schema([pa.field("k", key), pa.field(data_name, pa.int64())]) - value = [{"code": 1}] if structured else [1] - table = pa.Table.from_pylist([{"k": value, data_name: 2}], schema=schema) + 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=True, source_id=name ) @@ -61,11 +86,11 @@ def _assert_remedy(message, field): @pytest.mark.parametrize("operator_class", [Join, MergeJoin, SemiJoin]) @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) -@pytest.mark.parametrize("structured", [False, True], ids=["list", "struct-item"]) -def test_joins_name_the_nested_flag(operator_class, asynchronous, structured): +@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, structured=structured) - right = _source("b", "w", nullable=False, structured=structured) + 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: @@ -76,7 +101,7 @@ def test_joins_name_the_nested_flag(operator_class, asynchronous, structured): if isinstance(value, ExceptionGroup): [value] = value.exceptions assert isinstance(value, InputValidationError) - _assert_remedy(str(value), "k.item.code" if structured else "k.item") + _assert_remedy(str(value), "k.item.code" if shape == "struct-item" else "k.item") def test_another_type_difference_keeps_the_generic_message(): @@ -110,14 +135,30 @@ def test_a_flag_and_a_logical_identifier_are_two_differences(): 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("structured", [False, True], ids=["list", "struct-item"]) -def test_slot_binding_names_the_nested_flag(asynchronous, structured): +@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, structured=structured), name="src" + _source("a", "v", nullable=True, shape=shape), name="src" ) - other = _source("b", "v", nullable=False, structured=structured) + other = _source("b", "v", nullable=False, shape=shape) with PipelineJob(name="nested_flags") as job: MapData({"v": "out"})(slot, label="op") @@ -130,4 +171,6 @@ async def bind_and_run(): asyncio.run(bind_and_run()) else: job.bind(sources={"src": other}) - _assert_remedy(str(error.value), "k.item.code" if structured else "k.item") + _assert_remedy( + str(error.value), "k.item.code" if shape == "struct-item" else "k.item" + ) From cbf3ab7ecf55dfacdde1a5944f6671ab88e8d129 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 00:07:30 -0800 Subject: [PATCH 5/7] fix(join): diagnose nested flag conflicts across all inputs --- docs/dev/design_issues/ITL-445-NN1.md | 5 +- src/orcapod/core/operators/base.py | 11 ++- src/orcapod/core/operators/join.py | 9 ++- .../test_nested_nullability_diagnostic.py | 78 +++++++++++++++++-- 4 files changed, 91 insertions(+), 12 deletions(-) diff --git a/docs/dev/design_issues/ITL-445-NN1.md b/docs/dev/design_issues/ITL-445-NN1.md index 843f0bc12..9e9df5284 100644 --- a/docs/dev/design_issues/ITL-445-NN1.md +++ b/docs/dev/design_issues/ITL-445-NN1.md @@ -20,5 +20,6 @@ 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. Existing schemas, hash labels and golden values -stay the same. +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/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index e5876c92d..bdf182def 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -117,12 +117,16 @@ def _require_matching_nested_flags( def explain_nested_join_conflict( - operator: str, *streams: StreamProtocol, include_data: bool = False + 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 @@ -133,7 +137,10 @@ def explain_nested_join_conflict( 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): - for name in sorted(set(left.names) & set(right.names)): + 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 ) diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 35a9a27b3..d9f199509 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -288,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) @@ -322,7 +323,11 @@ 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", stream, other_stream, include_data=True + "Join", + data_tag_sources[name], + other_stream, + include_data=True, + column=name, ) raise InputValidationError( f"{type(self).__name__}: data-tag {name!r} has type " @@ -331,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/tests/test_core/operators/test_nested_nullability_diagnostic.py b/tests/test_core/operators/test_nested_nullability_diagnostic.py index e2035c3ea..771f49b62 100644 --- a/tests/test_core/operators/test_nested_nullability_diagnostic.py +++ b/tests/test_core/operators/test_nested_nullability_diagnostic.py @@ -1,7 +1,9 @@ """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 @@ -10,6 +12,7 @@ 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 @@ -66,23 +69,25 @@ def _source( ) -async def _execute(operator, left, right): +async def _execute( + operator: Join | MergeJoin | SemiJoin, *streams: ArrowTableSource +) -> None: """Feed the async row path with the same explicit Arrow schemas.""" - operator.validate_inputs(left, right) - inputs = [Channel(buffer_size=4), Channel(buffer_size=4)] - output = Channel(buffer_size=4) - for stream, channel in zip((left, right), inputs, strict=True): + 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=[left.pipeline_hash(), right.pipeline_hash()], + input_pipeline_hashes=[stream.pipeline_hash() for stream in streams], ) -def _assert_remedy(message, field): +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() @@ -127,6 +132,65 @@ def test_join_names_nested_flag_in_shared_data_tag(): _assert_remedy(str(error.value), "k.item.code") +@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") + + def test_a_flag_and_a_logical_identifier_are_two_differences(): """Logical identifiers in Arrow field metadata can also distinguish types.""" left = pa.struct( From f0b00a6b49eced84b940718cdc87da4025ef0b7f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 01:10:42 -0800 Subject: [PATCH 6/7] docs(function-pod): clarify nested output schema precedence --- .zed/rules | 7 +++--- CLAUDE.md | 7 +++--- changelog.d/ITL-445.md | 2 +- docs/concepts/function-pods.md | 22 ++++++++++--------- docs/dev/design_issues/ITL-445-NN1.md | 7 +++--- docs/reference/hashing.md | 4 +++- src/orcapod/utils/schema_utils.py | 4 +++- .../test_nested_output_nullability.py | 16 +++++++++++++- 8 files changed, 46 insertions(+), 23 deletions(-) diff --git a/.zed/rules b/.zed/rules index 2d796b026..f36f34e43 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1416,9 +1416,10 @@ data. The rules: - 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's return annotation still - constrains nested values, and its output check refuses a None where the annotation says - plain T. Top-level flags distinguish T from T | None. An explicit nested Arrow flag is + 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 diff --git a/CLAUDE.md b/CLAUDE.md index 1d27324bc..75cc86154 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1464,9 +1464,10 @@ data. The rules: - 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's return annotation still - constrains nested values, and its output check refuses a None where the annotation says - plain T. Top-level flags distinguish T from T | None. An explicit nested Arrow flag is + 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 diff --git a/changelog.d/ITL-445.md b/changelog.d/ITL-445.md index eaccf47a7..d8d8939fd 100644 --- a/changelog.d/ITL-445.md +++ b/changelog.d/ITL-445.md @@ -4,4 +4,4 @@ ### Fixed -- A function pod annotated to return `set[T]` must return 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. +- 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 7e634314c..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 @@ -1328,12 +1329,13 @@ declarations produce nullable Arrow fields. For example, `list[int]` and can receive a list containing `None` from a source or datagram. An explicit Arrow non-null item flag is preserved by the source. -The return annotation constrains the values a function can return. A pod returning -`[1, None]` for `-> list[int]`, or `{None}` for `-> set[int]`, raises -`OutputTypeError` naming the nested position. Use `list[int | None]` or -`set[int | None]` when the function intentionally returns missing items. Fixed and -heterogeneous tuples are unsupported as a single pod output. A tuple annotation can -still describe several separate outputs. +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 diff --git a/docs/dev/design_issues/ITL-445-NN1.md b/docs/dev/design_issues/ITL-445-NN1.md index 9e9df5284..91da7231f 100644 --- a/docs/dev/design_issues/ITL-445-NN1.md +++ b/docs/dev/design_issues/ITL-445-NN1.md @@ -13,9 +13,10 @@ 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 function -return annotations at supported nested positions. A strict nested input policy -is a future opt-in under ITL-1584. +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. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 66d6ab942..4aa000010 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1738,7 +1738,9 @@ 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 the return annotation independently of these storage flags. +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: 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 index 9c2e207a1..9833223ea 100644 --- a/tests/test_core/function_pod/test_nested_output_nullability.py +++ b/tests/test_core/function_pod/test_nested_output_nullability.py @@ -9,7 +9,7 @@ import pytest from pydantic import BaseModel -from orcapod import PipelineJob, dataclass as structural_dataclass +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 @@ -199,6 +199,20 @@ def test_tuple_is_not_a_single_pod_output_type(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"): From 3fe70de032d3af09d951f6984b5c3292d4f6d279 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:01:03 -0800 Subject: [PATCH 7/7] fix(operators): name both Arrow types in the nested-nullability join error The specialized error for inputs whose types differ only in a nested field's nullability named the column and the nested path but neither input type. It now names both, and an extension type also shows its storage, where the flag is. Co-Authored-By: Claude Fable 5.2 --- src/orcapod/core/operators/base.py | 21 ++++++++++++++++--- .../test_nested_nullability_diagnostic.py | 17 +++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index bdf182def..32e940c56 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -7,6 +7,8 @@ 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, @@ -27,8 +29,6 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: - import pyarrow as pa - from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol @@ -109,13 +109,28 @@ def _require_matching_nested_flags( 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"{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, diff --git a/tests/test_core/operators/test_nested_nullability_diagnostic.py b/tests/test_core/operators/test_nested_nullability_diagnostic.py index 771f49b62..32f11e104 100644 --- a/tests/test_core/operators/test_nested_nullability_diagnostic.py +++ b/tests/test_core/operators/test_nested_nullability_diagnostic.py @@ -94,6 +94,20 @@ def _assert_remedy(message: str, field: str) -> None: 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"]) @@ -112,6 +126,7 @@ def test_joins_name_the_nested_flag(operator_class, asynchronous, shape): [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(): @@ -130,6 +145,7 @@ def test_join_names_nested_flag_in_shared_data_tag(): 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"]) @@ -189,6 +205,7 @@ def test_join_names_nested_flag_in_any_data_tag_pair( 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():