Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -1419,6 +1419,15 @@ data. The rules:
- The type converter keys synthesized struct classes by the large-normalized struct, so
struct<b: string> and struct<b: large_string> 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
Expand Down
9 changes: 9 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,15 @@ data. The rules:
- The type converter keys synthesized struct classes by the large-normalized struct, so
`struct<b: string>` and `struct<b: large_string>` 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
Expand Down
7 changes: 7 additions & 0 deletions changelog.d/ITL-445.md
Original file line number Diff line number Diff line change
@@ -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.
26 changes: 21 additions & 5 deletions docs/concepts/function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions docs/concepts/streams.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ print(dict(tag_schema)) # {'subject_id': <class 'str'>}
print(dict(data_schema)) # {'age': <class 'int'>, 'weight': <class 'float'>}
```

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)`:
Expand Down
7 changes: 7 additions & 0 deletions docs/concepts/your-own-data-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions docs/dev/design_issues/ITL-445-NN1.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 9 additions & 0 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
28 changes: 28 additions & 0 deletions docs/tutorial/coming-from-pandas-or-polars.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 31 additions & 3 deletions src/orcapod/core/nodes/source_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down Expand Up @@ -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).

Expand All @@ -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.
Expand All @@ -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
Expand Down
66 changes: 64 additions & 2 deletions src/orcapod/core/operators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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


Expand Down Expand Up @@ -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(
Expand All @@ -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.

Expand Down
Loading
Loading