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

- Delta stores a logical (Arrow extension) type only as a whole top-level
column. It refuses nested extensions and fields carrying Arrow extension
metadata within another type, including within a top-level extension's
own storage. The refusal applies whether or not the logical type is
registered and also covers some previously accepted struct layouts.
Use the corresponding Orcapod container or class type to keep the logical
type: it stores its children as Arrow storage inside one top-level logical
column. Alternatively, use plain Arrow storage without extension annotations
or keep the raw Arrow column in an `InMemoryArrowDatabase`.

### Fixed

- Delta names affected columns and their nested paths before buffering rows.
This prevents nested logical type loss, unreadable tables, and identical
appends that fail after an apparently successful first write.
18 changes: 18 additions & 0 deletions docs/dev/design_issues/ITL-1372-LI2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
## `src/orcapod/databases/` — appending another logical type

### LI2 — Delta lost logical types or refused identical appends for nested extension columns
**Status:** resolved
**Severity:** critical
**Issue:** ITL-1372

Delta could lose a nested Arrow extension's identifier or store a field as a
different type. Some nested forms accepted a first write and then refused an
identical append. Others committed a table a fresh handle could not read.
The problems also occurred inside the storage of an extension type.

**Fix:** Delta accepts a logical type only as a whole top-level column. It
checks the schema and nested annotations on individual chunks before buffering.
The check walks extension storage and refuses both actual and annotated nested
types regardless of registration, with the column and nested path. Orcapod's
logical containers and user classes keep child values in plain Arrow storage
within one top-level extension, so they do not need nested Arrow extensions.
21 changes: 19 additions & 2 deletions docs/reference/database-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,16 @@ it, with an error naming the column, before anything of the table is written: no
it back as another type. The page is generated from a test that writes and reads each
type through each database, so it cannot drift from the code. The rows are
representative, not every Arrow type: dictionary-encoded columns are refused by every
stream before they reach a database, and union, run-end-encoded and list-view types are
not covered.
stream before they reach a database (the dictionary row uses a raw Arrow table), and
union, run-end-encoded and list-view types are not covered.

Delta supports logical types only as whole top-level columns. A logical type nested
in another Arrow type, including inside an extension's storage, is refused before
buffering. The rule covers both extension arrays and fields with Arrow extension
metadata, regardless of registration. Arrow's storage interchange cannot reliably
preserve a nested extension. Use the corresponding Orcapod container or class type
to keep the logical type: it stores its children in Arrow storage form within one
top-level logical column.

What a cell says:

Expand Down Expand Up @@ -255,6 +263,15 @@ fields is not covered: a struct whose fields are in another order is another typ
| `int64 not null` | kept | kept | kept | kept (by rule) |
| `string not null` | kept | kept | kept | kept (by rule) |

## Nested extension type

| Type | in-memory | Delta | SQLite | PostgreSQL |
|---|---|---|---|---|
| `extension type in struct child` | kept | refused | refused | refused |
| `extension type in list item` | kept | refused | refused | refused |
| `extension type in map value` | kept | refused | refused | refused |
| `extension type in dictionary values` | kept | refused | refused | refused |

## Orcapod logical type

| Type | in-memory | Delta | SQLite | PostgreSQL |
Expand Down
8 changes: 5 additions & 3 deletions src/orcapod/databases/delta_arrow_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@
merged column: ``merged_type``); a fixed-size list is rebuilt from the list Delta gives
back (a null row comes back with no items, which a cast cannot fill), refusing a row of
another length; a ``float16`` is checked to hold exactly the ``float32`` value read; and a
fixed-size binary to hold values of its width. A column whose type has an extension
(logical) type anywhere is left as it is: its type is restored from its extension
metadata.
fixed-size binary to hold values of its width. A column containing a Python Arrow
extension type bypasses type recording. Supported top-level extension columns are
restored from their extension metadata. ``DeltaTableDatabase.require_storable``
refuses nested extensions and annotations, including those within the storage of a
top-level extension (ITL-1372).

A table written before this existed has no recorded type and reads back with Delta's
types; such a database must be rebuilt.
Expand Down
90 changes: 87 additions & 3 deletions src/orcapod/databases/delta_lake_databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import sys
import uuid
from collections import defaultdict
from collections.abc import Callable, Collection, Mapping
from collections.abc import Callable, Collection, Iterable, Mapping
from contextlib import AbstractContextManager
from dataclasses import dataclass
from pathlib import Path
Expand Down Expand Up @@ -1427,6 +1427,55 @@ def _holds_null_type(arrow_type: pa.DataType) -> bool:
)


def _nested_logical_type_path(
field: "pa.Field[Any]", *, top_level: bool = False
) -> str | None:
"""Find the first nested logical type, without consulting Arrow's registry.

Args:
field: A column or a field within its type.
top_level: Whether this field may itself carry a logical type.

Returns:
A relative path to the first unsupported field, or ``None``.
"""
arrow_type = field.type
metadata = field.metadata or {}
annotation = any(key in metadata for key in _EXTENSION_KEYS)
if isinstance(arrow_type, pa.BaseExtensionType) or annotation:
if not top_level:
return ""
storage = (
arrow_type.storage_type
if isinstance(arrow_type, pa.BaseExtensionType)
else arrow_type
)
path = _nested_logical_type_path(pa.field("storage", storage))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return None if path is None else f"<storage>{path}"

t = pa.types
if t.is_dictionary(arrow_type):
children = (("<dictionary values>", pa.field("values", arrow_type.value_type)),)
elif t.is_map(arrow_type):
children = ((".key", arrow_type.key_field), (".value", arrow_type.item_field))
elif (
t.is_list(arrow_type)
or t.is_large_list(arrow_type)
or t.is_fixed_size_list(arrow_type)
or t.is_list_view(arrow_type)
or t.is_large_list_view(arrow_type)
):
children = (("[]", arrow_type.value_field),)
else:
fields = (arrow_type.field(i) for i in range(arrow_type.num_fields))
children = ((f".{child.name}", child) for child in fields)
for step, child in children:
path = _nested_logical_type_path(child)
if path is not None:
return step + path
return None


def _unmergeable_name_reason(name: str) -> str | None:
"""Say why Delta cannot commit to a table with a column named ``name``, or ``None``.

Expand Down Expand Up @@ -2428,8 +2477,9 @@ def require_storable(self, schema: pa.Schema) -> None:
names are case-insensitive (ITL-1403).

Raises:
UnstorableColumnError: For the first column Delta cannot hold, naming the
column, its Arrow type and Delta's reason.
UnstorableColumnError: Naming every column with an unsupported nested
extension type, or the first otherwise unstorable column, with
its Arrow type and Delta's reason.
"""
position = _case_clash_position(schema.names)
if position is not None:
Expand All @@ -2443,6 +2493,7 @@ def require_storable(self, schema: pa.Schema) -> None:
arrow_type=schema.field(position).type,
reason=_case_reason(*clash),
)
self._require_top_level_logical_types(schema)
for field in schema:
reason = delta_unstorable_reason(field)
if reason is not None:
Expand All @@ -2453,6 +2504,31 @@ def require_storable(self, schema: pa.Schema) -> None:
reason=reason,
)

def _require_top_level_logical_types(
self, fields: "Iterable[pa.Field[Any]]"
) -> None:
"""Name each column whose logical type is nested within another type."""
unsupported = {}
for field in fields:
path = _nested_logical_type_path(field, top_level=True)
if path is not None:
unsupported.setdefault(field.name, (field.type, f"{field.name}{path}"))
if unsupported:
column, (arrow_type, _) = next(iter(unsupported.items()))
paths = ", ".join(repr(path) for _, path in unsupported.values())
raise UnstorableColumnError(
database_kind=type(self).__name__,
column=column,
arrow_type=arrow_type,
reason=(
f"the Delta store does not support a logical type nested in another "
f"type yet. Nested paths: {paths}. Arrow storage cannot reliably "
"preserve these nested logical types. Use the corresponding Orcapod "
"container or class type, which stores its children as Arrow storage "
"within one top-level logical column, or use plain Arrow storage"
),
)

def _refuse_case_clash_with_pending(
self, record_path: tuple[str, ...], schema: pa.Schema
) -> None:
Expand Down Expand Up @@ -2857,6 +2933,14 @@ def add_records(
if records.num_rows == 0:
return

# Arrow type equality can overlook nested field metadata in extension
# storage and dictionary values. Check every chunk before any casts.
self._require_top_level_logical_types(
field.with_type(chunk.type)
for index, field in enumerate(records.schema)
for chunk in records.column(index).chunks
)

# Convert view types up front so the whole write path (group_by dedup,
# filters, storage) avoids string_view's missing kernels (ENG-601).
records = arrow_utils.normalize_table_view_types(records)
Expand Down
Loading
Loading