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
23 changes: 23 additions & 0 deletions changelog.d/ITL-907.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
### Breaking changes and migration

- A source refuses a dict column that holds one key twice in a cell, before presenting it
(`RepeatedDictKeyError`, an `InputValidationError`, naming the column and the key). To
Orcapod a bare Arrow list of `struct<key, value>` is a `dict[K, V]`, so this applies to
any such column of a table built outside Orcapod, at any depth. Remove the repeated
entries before building the source, or, if the column is meant as a list of pairs, give
the struct's fields other names. Every source kind applies the check to the rows it
presents, also to rows read back from a cache (`CachedSource`), from a job node's
store (`DerivedSource`) and from a SpiralDB table. Python values are checked as they
are stored: distinct Python keys that store as one key (for example, two floats narrowed
to the same `float32`) are refused as well. No stored value, path or hash changes (ITL-907).
Native lists and sets keep their declared element type. The check follows that type
into any user-class fields that hold dicts.

### Fixed

- A stored dict with a repeated key is no longer read as a Python `dict` that silently lost
an entry. `as_dict()`, `iter_data()` and a function pod taking the column raise
`RepeatedDictKeyError`, also for a stream built from an Arrow table of your own, which
is not scanned when it is built. Two keys are the same key exactly when a Python `dict`
would keep one of them: `0.0` and `-0.0` are, two nulls are, two NaN keys are not
(ITL-907).
2 changes: 2 additions & 0 deletions docs/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ These exceptions and warnings report problems identifying, binding, or reading s

::: orcapod.errors.RowIdentifierError

::: orcapod.errors.RepeatedDictKeyError

::: orcapod.errors.SourceTooLargeError

::: orcapod.errors.UnboundSourceError
Expand Down
56 changes: 56 additions & 0 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,62 @@ categorical column) is not a dictionary column: it is a library value, stored an
(see [Arrays and other library values](arrays.md)), and is accepted. Supporting
dictionary-encoded columns themselves is future work (ITL-1277).

### A bare list of key/value structs is a dict

A `dict[K, V]` column is stored as a list of structs with the two fields `key` and `value`,
and Orcapod reads a bare Arrow list of that shape (a list, large list or fixed-size list of
`struct<key, value>`, the fields in either order) as a `dict[K, V]`. Native lists and
sets of dataclasses follow their element's declared type, including classes with fields
named `key` and `value`. A dict holds each key once. An Arrow table built
outside Orcapod can hold a cell with one key twice; read as a Python `dict` it would lose an
entry. A source refuses such a column before presenting its rows, with
`RepeatedDictKeyError` (an `InputValidationError`) naming the column and key. It checks
dicts nested in lists, sets, dict values, structs and user-class fields. Polling and SpiralDB sources
check each batch. Cached and derived sources also check the stored rows they present.

Two keys are repeated when a Python `dict` would keep one of them. For example, `0.0`
and `-0.0` are one key, two `date64` values of the same day read as one `date`, and
two NaN keys stay distinct. A raw `ArrowTableStream` retains the original rows in
`as_table()`. Reading a repeated key as a `dict` with `as_dict()` or a function pod raises
the same error. Remove the repeated entries first, or, if the column is meant as a list of
pairs, give the struct's fields other names.

```python
import pyarrow as pa

from orcapod.errors import RepeatedDictKeyError
from orcapod.sources import ArrowTableSource

counts_type = pa.large_list(
pa.struct([("key", pa.large_string()), ("value", pa.int64())])
)
counts = pa.table(
{
"session": ["s1", "s2"],
"counts": pa.array(
[
[{"key": "left", "value": 3}, {"key": "right", "value": 5}],
[{"key": "left", "value": 1}, {"key": "left", "value": 4}],
],
counts_type,
),
}
)
try:
ArrowTableSource(counts, tag_columns=["session"], tag_only_columns=True)
except RepeatedDictKeyError as exc:
print(exc.column, exc.key)
# counts left

source = ArrowTableSource(
counts.slice(0, 1), tag_columns=["session"], tag_only_columns=True
)
print(source.output_schema()[1])
# Schema({'counts': dict[str, int] | None})
print([data.as_dict() for _, data in source.iter_data()])
# [{'counts': {'left': 3, 'right': 5}}]
```

### A CSV file's types: `schema=`

A CSV file holds text only, so `CSVSource` infers each column's type from the file, and
Expand Down
21 changes: 21 additions & 0 deletions docs/dev/design_issues/ITL-907-DK1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
## `src/orcapod/semantic_types/universal_converter.py`

### DK1 — A stored dict with a repeated key was read as a dict that lost an entry
**Status:** resolved
**Severity:** critical
**Issue:** ITL-907

A `dict[K, V]` column is stored as a list of key/value structs. A table built outside
Orcapod can hold a cell with one key twice (`[{key: 'a', value: 1}, {key: 'a', value: 2}]`).
`ArrowTableSource` accepted it; the table and its hash held both entries, while `as_dict()`
returned `{'a': 2}` and a function pod reading the column received a dict that had silently
lost an entry. An explicit storage type can also cause distinct Python keys to store as one key.

**Fix:** Both refusals (developer, November 28, 2026). Which Arrow type is a dict has one
definition for bare Arrow types, `UniversalTypeConverter.dict_entry_fields`. Sources
follow declared logical types through native containers and user-class fields and check
dicts at the table-to-stream boundary (`source_stream`). That covers eager tables,
polling and SpiralDB batches, and cached or derived rows. The check uses Arrow values
when storage equality matches Python equality, and decoded keys otherwise. The Python
dict reader also refuses repeats on raw streams. Both raise `RepeatedDictKeyError`
with the key and column. Stored layouts and hashes are unchanged.
10 changes: 4 additions & 6 deletions src/orcapod/core/sources/cached_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,14 @@
from orcapod.core.sources.source_ids import parse_source_id
from orcapod.core.sources.stream_builder import (
require_supported_nullable_types,
source_stream,
validate_source_table,
)
from orcapod.errors import (
CachedSourceIdMismatchError,
InputValidationError,
UnstorableColumnError,
)
from orcapod.core.streams.arrow_table_stream import (
ArrowTableStream,
stream_from_derived_table,
)
from orcapod.core.streams.base import (
typed_arrow_schemas,
check_head_size,
Expand Down Expand Up @@ -61,7 +58,7 @@
from orcapod.utils import schema_utils

if TYPE_CHECKING:
from orcapod.protocols.core_protocols import StreamProtocol
from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.protocols.database_protocols import DatabaseRegistryProtocol
from orcapod.protocols.hashing_protocols import SemanticHasherProtocol
from orcapod.types import ContentHash
Expand Down Expand Up @@ -704,8 +701,9 @@ def _build_merged_stream(self) -> ArrowTableStream:

tag_keys = self._source.keys()[0]
# Cached rows are this source's: give them its data context, not the default.
return stream_from_derived_table(
return source_stream(
Comment thread
eywalker marked this conversation as resolved.
Resolved
all_records,
self.data_context.type_converter,
tag_columns=tag_keys,
data_context=self.data_context,
data_tags=stream_data_tags(self._source),
Expand Down
43 changes: 21 additions & 22 deletions src/orcapod/core/sources/derived_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,11 @@
from orcapod.core.sources.reload import same_rows
from orcapod.core.sources.source_ids import hash_source_name
from orcapod.core.sources.stream_builder import (
require_supported_nullable_types,
validate_source_table,
SourceStreamBuilder,
normalize_record_id_columns,
)
from orcapod.core.streams.arrow_table_stream import (
ArrowTableStream,
stream_from_derived_table,
require_supported_nullable_types,
source_stream,
validate_source_table,
)
from orcapod.core.streams.view import (
ViewStatus,
Expand All @@ -50,6 +47,7 @@
from orcapod.utils.provisional import provisional_class_name

if TYPE_CHECKING:
from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.core.nodes.function_node import FunctionJobNode
from orcapod.core.nodes.operator_node import OperatorJobNode
from orcapod.protocols.core_protocols import StreamProtocol
Expand Down Expand Up @@ -702,9 +700,9 @@ def _get_stream(self) -> ArrowTableStream:
# earlier read (ITL-1331), as a provisional operator's stream does.
self._require_origin_bindings()
self._note_provisional_identity_use()
if self._cached_stream is not None:
return self._cached_stream
if self._tags_as_data is not None:
if self._cached_stream is not None:
return self._cached_stream
self._origin_seen = self._origin.last_modified
stream, has_rows = self._build_derived_stream(self._tags_as_data)
if has_rows:
Expand All @@ -713,14 +711,14 @@ def _get_stream(self) -> ArrowTableStream:
self._cached_stream = stream
return stream

if self._cached_table is None:
self._origin_seen = self._origin.last_modified
records = self._origin_records()
if records is None:
self._cached_table = self._empty_origin_table()
else:
self._cached_table = records
return self._stream_over(self._cached_table)
seen = self._origin.last_modified
records = self._origin_records()
table = self._empty_origin_table() if records is None else records
stream = self._stream_over(table)
self._origin_seen = seen
self._cached_table = table
self._cached_stream = stream
return stream

def _held_rows(self) -> "pa.Table | None":
"""The rows this source holds from its origin, or ``None`` before a read."""
Expand Down Expand Up @@ -777,10 +775,13 @@ def check_for_new_data(self) -> bool:
# The stored rows' ids may not be theirs to keep in another order: order
# counts unless a record_id_columns were given (never assume).
unchanged = same_rows(held, read, ordered=not self._record_id_columns)
self._origin_seen = seen
if unchanged:
self._origin_seen = seen
return False
stream = self._stream_over(read)
self._origin_seen = seen
self._cached_table = read
self._cached_stream = stream
self._update_modified_time()
return True

Expand Down Expand Up @@ -812,13 +813,10 @@ def head(
self._note_provisional_identity_use()
config = ColumnConfig.handle_config(columns, all_info=all_info)
origin_kind = "held" if isinstance(self._origin, RootSource) else "stored"
if self._tags_as_data is not None and self._cached_stream is not None:
if self._cached_stream is not None:
return self._cached_stream.head(n, columns=config).for_stream(
self, origin=origin_kind
)
if self._tags_as_data is None and self._cached_table is not None:
stream = self._stream_over(self._cached_table)
return stream.head(n, columns=config).for_stream(self, origin=origin_kind)
if isinstance(self._origin, RootSource):
origin_head = self._origin.head(n)
if (
Expand Down Expand Up @@ -883,8 +881,9 @@ def _stream_over(self, table: "pa.Table") -> ArrowTableStream:
"""Return this source's stream over the origin rows ``table``."""
if self._tags_as_data is not None:
return self._derive_from(table, self._tags_as_data)
return stream_from_derived_table(
return source_stream(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
validate_source_table(table),
self.data_context.type_converter,
tag_columns=self._origin.keys()[0],
data_tags=self._data_tags(),
)
Expand Down
Loading
Loading