Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
ab21bea
fix(logical_types): order a set of a scalar-stored logical type canon…
eywalker Nov 28, 2026
7328143
Merge remote-tracking branch 'origin/main' into eywalker/itl-922-a-se…
eywalker Nov 28, 2026
faa29d9
fix(logical_types)!: canonically order stored sets of user-class valu…
eywalker Nov 28, 2026
4b5f375
fix(logical_types): order logical sets after Arrow coercion
eywalker Nov 28, 2026
216aeea
fix(logical_types): canonicalize nested stored sets and batch column …
eywalker Nov 28, 2026
8eee15e
perf(logical_types): batch stored set sorting and rank list keys nati…
eywalker Nov 28, 2026
c9daaa5
perf(logical_types): batch canonical ordering for struct sets
eywalker Nov 28, 2026
e91dedb
perf(logical_types): isolate and batch struct-set storage
eywalker Nov 28, 2026
a44f381
fix(logical_types): restore direct set decoding and speed small writes
eywalker Nov 28, 2026
b522c55
fix(logical_types): restore schema overrides and wrapped set iteration
eywalker Nov 28, 2026
3c67c76
fix(logical_types): honor explicit Arrow set schemas
eywalker Nov 28, 2026
32a7c0a
test(logical_types): reuse default Arrow extensions in native writes
eywalker Nov 28, 2026
c9236ff
perf(logical_types): resolve explicit writer dispatch by type
eywalker Nov 28, 2026
a422250
chore: merge origin/main into ITL-922
eywalker Nov 28, 2026
98d89f5
test(logical_types): use a concrete schema for registration
eywalker Nov 28, 2026
ef72f45
fix(logical_types): skip projected-away set columns
eywalker Nov 28, 2026
c27a08b
fix(logical-types): honor empty projections and retain batch ordering
eywalker Nov 28, 2026
8956cff
chore: merge origin/main into ITL-922
eywalker Nov 28, 2026
11c5afc
chore: merge origin/main into ITL-922
eywalker Nov 29, 2026
14434e0
fix(logical-types): preserve set validation across conversion paths
eywalker Nov 29, 2026
c59f893
fix(logical-types): preserve values in set projections
eywalker Nov 29, 2026
6ab9b67
fix(logical-types): restore reviewed set conversion behavior
eywalker Nov 29, 2026
4a0bd48
chore: merge origin/main into ITL-922
eywalker Nov 29, 2026
39faca3
fix(typing): record Arrow date scalar stub omission
eywalker Nov 29, 2026
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
6 changes: 6 additions & 0 deletions .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,12 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension
identifier is the container kind plus the element's identifier; the type hash treats them
like any generic alias (origin and arguments). A change to how they are stored or hashed is
a data context (global hash version) change, not a logical type change.
- Sets of struct-stored logical types use `logical_set_storage` after
coercion to the declared Arrow type (ITL-922). Compare structs by declared field order
and lists by item order, recursively. Class comparators have no effect. A NaN at any
depth, duplicate storage values or incomparable values raise `CanonicalOrderError`.
Other logical sets keep their native sort. Sets of user-defined scalar-stored types
also reject NaNs and duplicate storage values after coercion. The caller adds the column.
- `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611):
`ListLogicalType` over an `ArrowElement`, extension name `set[<large Arrow type text>]`
(`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer,
Expand Down
6 changes: 6 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,12 @@ A logical type's identifier is its Arrow extension name plus its Arrow extension
identifier is the container kind plus the element's identifier; the type hash treats them
like any generic alias (origin and arguments). A change to how they are stored or hashed is
a data context (global hash version) change, not a logical type change.
- Sets of struct-stored logical types use `logical_set_storage` after
coercion to the declared Arrow type (ITL-922). Compare structs by declared field order
and lists by item order, recursively. Class comparators have no effect. A NaN at any
depth, duplicate storage values or incomparable values raise `CanonicalOrderError`.
Other logical sets keep their native sort. Sets of user-defined scalar-stored types
also reject NaNs and duplicate storage values after coercion. The caller adds the column.
- `set[T]` of a primitive is a native container too (developer, November 14, 2026, ITL-611):
`ListLogicalType` over an `ArrowElement`, extension name `set[<large Arrow type text>]`
(`set[int64]`), metadata `{"category": "set", "element_kind": "arrow"}` (developer,
Expand Down
25 changes: 25 additions & 0 deletions changelog.d/ITL-922.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
### Breaking changes and migration

- Rebuilding rows with a `set[T]` of user-class values can change their hashes
(ITL-922). The elements now sort by their stored fields in declared order.
For example, a numeric field with `2` sorts before `10`. Orcapod recomputes
cached results whose input hashes change when the data is rebuilt.

### Fixed

- Sets of struct-stored logical types are ordered after Arrow coerces each element
to the declared storage type (ITL-922). The sort descends into nested structs
and lists, with `None` first. Nested dict keys and set items are ordered after
coercion too. A NaN at any depth, incomparable values, or two keys or elements
with equal storage raise `CanonicalOrderError` naming the column.
- Sets of user-defined scalar-stored types keep their native sort and reject
NaNs or duplicate storage values after Arrow coercion.
- Table conversion batches struct sets in columns, including sets nested in
lists and user classes. Nested dictionary keys, set items, and list comparison
keys use Arrow or Polars kernels.
- Direct structural-dictionary conversion round-trips sets of logical values,
including struct fields with their own logical decoders.
- Explicit Arrow schema overrides use the requested field types and compare only
the fields stored in the target schema. A logical set column omitted by the
override is skipped, including for an empty projection. Function iteration
validates wrapped sets without sorting each output.
1 change: 1 addition & 0 deletions docs/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ These exceptions and warnings report invalid inputs, schemas, or values.
::: orcapod.errors.RecursiveTypeError

::: orcapod.errors.CanonicalOrderError
::: orcapod.errors.LogicalSetCanonicalOrderError

::: orcapod.errors.UnsupportedValueError

Expand Down
6 changes: 6 additions & 0 deletions docs/concepts/your-own-data-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ can return. For example, a returned object with `None` in an `int` field raises
values deliberately. Pydantic's own validation still applies whenever it
constructs a model.

A `set[T]` of user-class instances is stored in declared field order. Orcapod compares
the stored field values, descending into nested classes and lists and placing `None`
first. A class's own comparison methods have no effect on storage order. Unorderable
values, NaNs anywhere in an element, and distinct elements that store the same fields
raise `CanonicalOrderError`. See [canonical set order](../reference/hashing.md#1e-dict-and-set-values-canonical-order).

## `op.dataclass` in a notebook

`op.dataclass` is used like `dataclasses.dataclass` and returns a real dataclass. Define
Expand Down
36 changes: 36 additions & 0 deletions docs/dev/design_issues/ITL-922-DO2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
## `src/orcapod/semantic_types/canonical_order.py` — dict and set values in canonical order

### DO2 — Sets of logical elements used representation text as a fallback order
**Status:** resolved
**Severity:** medium
**Issue:** ITL-922

Struct storage fell back to representation-text order, which put a field with
`10` before `2`. NaNs and distinct instances with equal declared fields could
enter storage. A scalar-stored logical type could also admit NaNs and equal
storage values.

**Fix:** Apply canonical order to struct-stored elements after Arrow coercion.
Sort the struct fields in declared order and use a lexicographic key for each
list field. Sort nested dict keys and set items in their own declared storage
types before comparing the enclosing elements. Check adjacent sorted values
for duplicates within each set. Multi-row table conversion encodes and sorts
each set column in one pass, including sets nested in lists and user classes.
Small sets with flat exact keys compare the coerced Arrow values without
constructing a sort table. Direct structural-dictionary reads pass Python
storage values to each logical decoder.
Function iteration checks the coerced storage keys for NaNs and duplicates
without sorting the row, including when a list or class wraps the set.
Function table assembly carries the typed source-info columns directly from
the rows so it can encode and order the payload once per column.
An explicit Arrow schema override compares its retained fields in the user
class's declared order after coercing them to their target Arrow types.
Columns omitted by an Arrow schema override are skipped during checked-set
writes, including when the override has no fields.
Explicit native writes reuse converters by Python type, even when Arrow
schema metadata changes between writes.
Sets of other logical types keep their native sort. For user-defined scalar
storage, one Arrow pass per table column rejects NaNs and duplicate stored
values. The same ordering rules apply to classes rebuilt from metadata.
The conversion boundary supplies the column name. Rebuilding sets of user
classes can change affected row hashes.
31 changes: 21 additions & 10 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -1074,14 +1074,24 @@ orders for equal hashed inputs; reconstructing user-class instances is outside t
| `str` | Unicode code point, never locale |
| `bytes` | unsigned bytewise |
| `date`, `datetime`, `time`, `timedelta` | natural order; datetimes by instant (they are timezone aware after conversion) |

A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`) has no order
and raises `CanonicalOrderError` (a `ValueError`) naming the column, as do keys or elements
that cannot be compared and two keys or elements that convert to the same stored value
(decided November 12, 2026). A
dict or set whose nested unordered containers are all already in this order is stored
byte-for-byte as before this rule existed,
so its hash did not change.
| Struct set element (such as a user class) | field by field in declared order |
| List inside a set element | item by item, with a shorter prefix first |

Struct fields and list items follow the same rules recursively, including `None` first.
For a set of struct-stored logical values, Orcapod coerces each element to its declared Arrow
type before comparing it. Python class comparators such as those generated by
`@dataclass(order=True)` do not participate. Nested dict keys and set items are also
ordered in their declared storage types. Two keys or items that coerce to the same
stored value are refused before they can collapse on read.

A NaN key or element (a Python `float`, a NumPy floating scalar or a `Decimal`),
including a NaN anywhere inside a set element, has no order
and raises `CanonicalOrderError` (a `ValueError`) naming the column for primitive containers
and struct-stored sets. Those containers also reject incomparable values and duplicate
storage keys. Sets of scalar-stored logical types keep their native sort. For user-defined
scalar types, Arrow validation also rejects NaNs and duplicate storage values.
For user-class sets written with the old representation-text order, rebuilding the data
can change row hashes and cause affected cached results to be recomputed (ITL-922).

**Signed zero.** In a table Orcapod builds, `-0.0` hashes as `0.0` wherever it appears: in
a plain `float` column and as a dict key or set element alike, as Python compares them
Expand All @@ -1107,8 +1117,9 @@ canonical JSON text (ITL-942); that order is never stored and never seen. The tw
different on purpose (JSON text puts `10` before `2`; storage order is numeric) and neither
is defined in terms of the other: changing the hasher's order would move semantic hashes
of affected inputs, and changing storage order would move row hashes and what a pod reads back.
`set[T]` of a logical type (`set[Path]`, `set[UUID]`) is ordered by `ListLogicalType`, not
by this rule.
`ListLogicalType` applies the canonical storage rule to sets of struct-stored logical
types. Sets of scalar-stored logical types keep their native sort, which can produce a
different stored order and row hash from canonical ordering.

**The set's identity is part of the row hash** (ITL-611). A set of a primitive is stored
under its native container type, and the Arrow hasher hashes an extension column's
Expand Down
51 changes: 41 additions & 10 deletions src/orcapod/core/data_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
context_result_path,
)
from orcapod.errors import (
LogicalSetCanonicalOrderError,
NoOutputsDeclaredError,
OutputContainerTypeError,
OutputTypeError,
Expand All @@ -48,10 +49,12 @@
PythonFunctionReturnCheckProtocol,
)
from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol
from orcapod.semantic_types.output_conformance import (
check_conformance,
normalize_output_numbers,
)
from orcapod.semantic_types.universal_converter import UniversalTypeConverter
from orcapod.types import ContentHash, DataValue, Schema, SchemaLike
from orcapod.utils import schema_utils
from orcapod.utils.canonical_type_names import stabilize_type_names
Expand Down Expand Up @@ -817,6 +820,9 @@ def output_source_info(
return {column: f"{source}::{result_id}::{column}" for column in columns}


_OutputTableConverter = Callable[[list[dict[str, Any]], SchemaLike], pa.Table | None]


class PythonDataFunction(DataFunctionBase[PythonFunctionExecutorProtocol]):
@property
def data_function_type_id(self) -> str:
Expand Down Expand Up @@ -897,6 +903,9 @@ def __init__(
self._function_name = function_name
# (output key, conversion) pairs already reported with ValueConversionWarning.
self._reported_conversions: set[tuple[str, str]] = set()
self._output_table_converter: (
tuple[TypeConverterProtocol, _OutputTableConverter] | None
) = None

super().__init__(
label=label,
Expand Down Expand Up @@ -1149,28 +1158,50 @@ def _executor_return_options(self) -> dict[str, object] | None:
return self._executor.return_container_options(self._return_container)
return None

def _resolve_output_table_converter(
self, converter: TypeConverterProtocol
) -> _OutputTableConverter:
"""Use eager set validation when the standard writer owns storage."""
writer = converter.python_dicts_to_arrow_table
if (
isinstance(converter, UniversalTypeConverter)
and getattr(writer, "__func__", None)
is UniversalTypeConverter.python_dicts_to_arrow_table
):
validate = converter._eager_set_output_validator(self.output_data_schema)
if validate is not None:
return validate
return writer

def write(rows: list[dict[str, Any]], schema: SchemaLike) -> pa.Table:
return writer(rows, python_schema=schema)

return write

def _convert_outputs(
self, output_data: dict[str, DataValue], output_schema: Schema
) -> pa.Table:
"""Convert checked outputs to a one-row Arrow table with the declared types.
) -> None:
"""Check that outputs can be stored with their declared Arrow types.

Args:
output_data: The parsed outputs, already checked against ``output_schema``.
output_schema: The declared output types.

Returns:
The one-row table, typed by the declared schema.

Raises:
LogicalSetCanonicalOrderError: If an output's logical set has no canonical
storage order. The converter names the column.
OutputTypeError: If an output cannot be converted, for example an integer
out of range for its declared width, a ``datetime`` without a time zone
or one with a part below one microsecond; it names that output.
out of range for its declared width or a datetime without a time zone.
"""
converter = self.data_context.type_converter
try:
return converter.python_dicts_to_arrow_table(
[output_data], python_schema=output_schema
)
cached = self._output_table_converter
if cached is None or cached[0] is not converter:
cached = (converter, self._resolve_output_table_converter(converter))
self._output_table_converter = cached
cached[1]([output_data], output_schema)
except LogicalSetCanonicalOrderError:
raise
except Exception as exc:
# Find the output that fails on its own, so the error can name it.
for key, value in output_data.items():
Expand Down
45 changes: 30 additions & 15 deletions src/orcapod/core/function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol
from orcapod.semantic_types import infer_python_schema_from_pylist_data
from orcapod.semantic_types.universal_converter import UniversalTypeConverter
from orcapod.system_constants import constants
from orcapod.types import (
ColumnConfig,
Expand Down Expand Up @@ -1218,7 +1219,7 @@ def _token_rows(rows: "Sequence[pa.Table]") -> pa.Table:
tables.append(
pa.Table.from_arrays(
[
columns[name] if name in columns else pa.nulls(row.num_rows, kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type
columns[name] if name in columns else pa.nulls(1, kind) # pyright: ignore[reportCallIssue, reportArgumentType] # pyarrow takes any type; the stubs say an extension type
for name, kind in types.items()
],
schema=schema,
Expand Down Expand Up @@ -1660,15 +1661,21 @@ def _table_from_pairs(
# Tags are passed through untouched: each row's own Arrow table keeps
# the input's tag types, a logical type included (ITL-928).
tag_tables.append(tag.as_table(columns={"system_tags": True}))
# So are the source-info tokens: each row's own token columns, with
# the types the row carries, never converted from their Python
# values (ITL-1491).
row_table = data.as_table(columns={"source": True})
token_tables.append(
row_table.select(
[n for n in row_table.column_names if n.startswith(source_prefix)]
# Keep the declared token fields (ITL-1491) without building a
# payload table for each row. Encode the payload column-wide below.
if isinstance(data, Data):
token_tables.append(data._source_info_for_transport()) # pyright: ignore[reportPrivateUsage] # transport keeps the row's declaration
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
else:
row_table = data.as_table(columns={"source": True})
token_tables.append(
row_table.select(
[
n
for n in row_table.column_names
if n.startswith(source_prefix)
]
)
)
)
row = data.as_dict(all_info=True)
all_data.append(
{
Expand All @@ -1688,13 +1695,21 @@ def _table_from_pairs(
# typed from their values.
python_schema = dict(infer_python_schema_from_pylist_data(all_data))
python_schema.update(self.output_schema()[1])
struct_data = converter.python_dicts_to_struct_dicts(
all_data, python_schema=python_schema
)
all_tags_as_tables = arrow_utils.concat_tables_by_name(tag_tables)
all_data_as_tables: pa.Table = pa.Table.from_pylist(
struct_data, schema=data_schema
)
assert data_schema is not None
if isinstance(converter, UniversalTypeConverter) and (
checked_columns := converter._explicit_checked_columns(
python_schema, data_schema
)
):
all_data_as_tables = converter._storage_table(
all_data, python_schema, data_schema, checked_columns
)
else:
struct_data = converter.python_dicts_to_struct_dicts(
all_data, python_schema=python_schema
)
all_data_as_tables = pa.Table.from_pylist(struct_data, schema=data_schema)
return arrow_utils.hstack_tables(
all_tags_as_tables, all_data_as_tables, _token_rows(token_tables)
)
Expand Down
4 changes: 4 additions & 0 deletions src/orcapod/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ class CanonicalOrderError(ValueError):
"""


class LogicalSetCanonicalOrderError(CanonicalOrderError):
"""Raised when the Arrow storage of a logical set has no canonical order."""


class UnsupportedValueError(ValueError):
"""A value cannot be stored by the logical type of its column.

Expand Down
Loading
Loading