diff --git a/changelog.d/ITL-1372.md b/changelog.d/ITL-1372.md new file mode 100644 index 000000000..23e159051 --- /dev/null +++ b/changelog.d/ITL-1372.md @@ -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. diff --git a/docs/dev/design_issues/ITL-1372-LI2.md b/docs/dev/design_issues/ITL-1372-LI2.md new file mode 100644 index 000000000..fb702b1ef --- /dev/null +++ b/docs/dev/design_issues/ITL-1372-LI2.md @@ -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. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index a60973db0..acba19b4c 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -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: @@ -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 | diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index f9c624886..18233139c 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -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. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 9e2877228..e9373b91e 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -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 @@ -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)) + return None if path is None else f"{path}" + + t = pa.types + if t.is_dictionary(arrow_type): + children = (("", 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``. @@ -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: @@ -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: @@ -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: @@ -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) diff --git a/tests/test_databases/test_delta_nested_extension_types.py b/tests/test_databases/test_delta_nested_extension_types.py new file mode 100644 index 000000000..48f705389 --- /dev/null +++ b/tests/test_databases/test_delta_nested_extension_types.py @@ -0,0 +1,512 @@ +"""Delta accepts a logical type only as a whole top-level column (ITL-1372).""" + +from __future__ import annotations + +import re +import subprocess +import sys +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any, cast +from uuid import UUID + +import pyarrow as pa +import pytest +from deltalake import DeltaTable +from pydantic import BaseModel + +from orcapod import dataclass +from orcapod.contexts import get_default_context +from orcapod.databases import DeltaTableDatabase, ExtensionAwareDatabase +from orcapod.errors import UnstorableColumnError +from orcapod.logical_types.registry import LogicalTypeRegistry +from orcapod.semantic_types.universal_converter import UniversalTypeConverter + +PATH = ("t",) +NAME = b"ARROW:extension:name" +META = b"ARROW:extension:metadata" + + +class _Unit(pa.ExtensionType): + """A small Arrow extension with a caller-supplied storage type.""" + + def __init__(self, name: str, storage: pa.DataType) -> None: + super().__init__(storage, name) + + def __arrow_ext_serialize__(self) -> bytes: + return self.extension_name.encode() + + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> _Unit: + return cls(serialized.decode(), storage_type) + + +@contextmanager +def _register(extension: _Unit, registered: bool) -> Iterator[None]: + """Register the extension only when the test calls for a warm reader.""" + if registered: + pa.register_extension_type(cast(Any, extension)) + try: + yield + finally: + if registered: + pa.unregister_extension_type(extension.extension_name) + + +def _annotation(extension: _Unit) -> dict[bytes | str, bytes | str]: + """The storage form's extension identifier.""" + return { + NAME: extension.extension_name.encode(), + META: extension.__arrow_ext_serialize__(), + } + + +def _nest(container: str, field: Any, array: Any) -> tuple[Any, Any]: + """Wrap one row in a container, keeping any annotation on the nested field.""" + if container == "struct": + array = pa.StructArray.from_arrays([array], fields=[field.with_name("v")]) + elif container == "list": + array = pa.ListArray.from_arrays( + pa.array([0, 1], pa.int32()), array, type=pa.list_(field.with_name("item")) + ) + elif container == "large list": + array = pa.LargeListArray.from_arrays( + pa.array([0, 1], pa.int64()), + array, + type=pa.large_list(field.with_name("item")), + ) + elif container == "fixed list": + from_fixed_arrays: Any = pa.FixedSizeListArray.from_arrays + array = from_fixed_arrays(array, type=pa.list_(field.with_name("item"), 1)) + elif container == "list view": + from_arrays: Any = pa.ListViewArray.from_arrays + array = from_arrays( + pa.array([0], pa.int32()), + pa.array([1], pa.int32()), + array, + type=pa.list_view(field.with_name("item")), + ) + elif container == "dictionary": + # Dictionary values have no Field of their own to carry an annotation. + array = pa.DictionaryArray.from_arrays(pa.array([0], pa.int8()), array) + else: + assert container in ("map key", "map value") + from_arrays: Any = pa.MapArray.from_arrays + plain = pa.array(["k"], pa.large_string()) + plain_field = pa.field("key", plain.type, nullable=False) + if container == "map key": + key, value = array, plain + key_field, value_field = ( + field.with_name("key").with_nullable(False), + plain_field.with_name("value"), + ) + else: + key, value = plain, array + key_field, value_field = plain_field, field.with_name("value") + map_type = pa.map_(key_field, value_field) # pyright: ignore[reportArgumentType] # Arrow accepts Fields + array = from_arrays(pa.array([0, 1], pa.int32()), key, value, type=map_type) + return pa.field("measurement", array.type), array + + +@pytest.mark.parametrize( + ("containers", "path"), + [ + (("struct",), ".v"), + (("struct", "struct"), ".v.v"), + (("list",), "[]"), + (("large list", "struct"), ".v[]"), + (("fixed list", "struct"), ".v[]"), + (("list view",), "[]"), + (("map key",), ".key"), + (("map value",), ".value"), + (("struct", "map value"), ".value.v"), + (("struct", "dictionary"), ".v"), + ], +) +@pytest.mark.parametrize("annotated", [False, True], ids=["actual", "annotated"]) +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +def test_delta_refuses_nested_logical_types( + tmp_path: Path, + containers: tuple[str, ...], + path: str, + annotated: bool, + registered: bool, +) -> None: + """The public write APIs refuse the same nested position before queuing.""" + extension = _Unit("itl1372.unit", pa.large_string()) + storage = pa.array(["a"], extension.storage_type) + array: Any = storage if annotated else extension.wrap_array(storage) + field: Any = pa.field( + "measurement", + array.type, + metadata=_annotation(extension) if annotated else None, + ) + for container in containers: + field, array = _nest(container, field, array) + table = pa.Table.from_arrays([array], schema=pa.schema([field])) + records = table.append_column("id", pa.array([b"1"], pa.large_binary())) + with _register(extension, registered): + delta = DeltaTableDatabase(tmp_path) + wrapped = ExtensionAwareDatabase( + delta, UniversalTypeConverter(logical_type_registry=LogicalTypeRegistry()) + ) + with pytest.raises( + UnstorableColumnError, match=re.escape("measurement" + path) + ) as first: + delta.add_records(PATH, records, record_id_column="id") + delta.flush() + assert delta.get_all_records(PATH) is None + with pytest.raises( + UnstorableColumnError, match="logical type nested in another type" + ) as second: + wrapped.add_record(PATH, b"2", table) + assert str(first.value) == str(second.value) + assert first.value.column == "measurement" + assert "Orcapod container or class type" in str(first.value) + delta.flush() + assert not (tmp_path / "t" / "_delta_log").exists() + + +@pytest.mark.parametrize("inner_annotated", [False, True], ids=["actual", "annotated"]) +@pytest.mark.parametrize("outer_annotated", [False, True], ids=["actual", "annotated"]) +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +def test_delta_refuses_nested_type_in_top_level_extension_storage( + tmp_path: Path, inner_annotated: bool, outer_annotated: bool, registered: bool +) -> None: + """A top-level extension cannot hide another extension in its storage.""" + inner = _Unit("itl1372.inner", pa.large_string()) + scalar = pa.array(["a"], inner.storage_type) + item = scalar if inner_annotated else inner.wrap_array(scalar) + child = pa.field( + "value", item.type, metadata=_annotation(inner) if inner_annotated else None + ) + _, storage = _nest("map value", child, item) + outer = _Unit("itl1372.outer", storage.type) + values = storage if outer_annotated else outer.wrap_array(storage) + field = pa.field( + "measurement", + values.type, + metadata=_annotation(outer) if outer_annotated else None, + ) + table = pa.Table.from_arrays([values], schema=pa.schema([field])) + with _register(inner, registered), _register(outer, registered): + db = DeltaTableDatabase(tmp_path) + for rid in (b"1", b"2"): + with pytest.raises( + UnstorableColumnError, match=r"measurement\.value" + ): + db.add_record(PATH, rid, table) + db.flush() + assert db.get_all_records(PATH) is None + + +@pytest.mark.parametrize("order", [("samples", "units"), ("units", "samples")]) +def test_delta_names_both_unstorable_columns( + tmp_path: Path, order: tuple[str, str] +) -> None: + """An error names both columns and their paths in either schema order.""" + extension = _Unit("itl1372.multi", pa.large_string()) + values = extension.wrap_array(pa.array(["a"], extension.storage_type)) + field = pa.field("x", values.type) + columns = { + "samples": _nest("list", field, values)[1], + "units": _nest("map value", field, values)[1], + } + table = pa.table( + { + "id": pa.array([b"1"], pa.large_binary()), + **{key: columns[key] for key in order}, + } + ) + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError) as error: + db.add_records(PATH, table, record_id_column="id") + assert "samples[]" in str(error.value) + assert "units.value" in str(error.value) + db.flush() + assert db.get_all_records(PATH) is None + + +@pytest.mark.parametrize("annotated", [False, True], ids=["actual", "annotated"]) +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +@pytest.mark.parametrize( + "metadata", [False, True], ids=["no metadata", "ordinary metadata"] +) +def test_delta_keeps_top_level_scalar_extension( + tmp_path: Path, annotated: bool, registered: bool, metadata: bool +) -> None: + """Both writes preserve the whole-column extension and its ordinary metadata.""" + extension = _Unit("itl1372.scalar", pa.large_string()) + storage = pa.array(["a"], extension.storage_type) + actual = extension.wrap_array(storage) + ordinary = {b"units": b"metres"} if metadata else {} + + def table(array: Any, is_annotated: bool) -> pa.Table: + md = {**ordinary, **(_annotation(extension) if is_annotated else {})} + return pa.Table.from_arrays( + [array], schema=pa.schema([pa.field("x", array.type, metadata=md or None)]) + ) + + given = table(storage, True) if annotated else table(actual, False) + expected = table(actual, False) if registered else table(storage, True) + with _register(extension, registered): + for count in (1, 2): + DeltaTableDatabase(tmp_path).add_record( + PATH, str(count).encode(), given, flush=True + ) + read = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert read is not None + assert read.select(["x"]).equals( + pa.concat_tables([expected] * count), check_metadata=True + ) + + +@dataclass +class _WithPath: + """A structural dataclass with a logical field.""" + + value: Path + + +class _WithUUID(BaseModel): + """A Pydantic model with a logical field.""" + + value: UUID + + +@pytest.mark.parametrize( + ("python_type", "value"), + [ + (Path, Path("/a")), + (list[Path], [Path("/a")]), + (set[Path], {Path("/a")}), + (_WithPath, _WithPath(Path("/a"))), + (_WithUUID, _WithUUID(value=UUID(int=1))), + (list[_WithPath], [_WithPath(Path("/a"))]), + ], + ids=["scalar", "list", "set", "dataclass", "pydantic", "list of dataclasses"], +) +def test_delta_keeps_orcapod_logical_columns( + tmp_path: Path, python_type: Any, value: Any +) -> None: + """The warm and cold reads recover the original logical types and values.""" + converter = get_default_context().type_converter + table = converter.python_dicts_to_arrow_table( + [{"x": value}], python_schema={"x": python_type} + ) + field = table.schema.field("x") + assert isinstance(field.type, pa.ExtensionType) + assert field.type.extension_name + field = field.with_metadata({b"units": b"metres"}) + table = pa.Table.from_arrays([table.column("x")], schema=pa.schema([field])) + code = """ +import sys + +import pyarrow as pa + +from orcapod.contexts import get_default_context +from orcapod.databases import DeltaTableDatabase, ExtensionAwareDatabase +from orcapod.databases.utils import identity_node +from tests.test_databases.test_delta_nested_extension_types import _WithPath, _WithUUID + +db = ExtensionAwareDatabase(DeltaTableDatabase(sys.argv[1]), get_default_context().type_converter) +actual = db.get_all_records(("t",)).select(["x"]) +with pa.ipc.open_file(sys.argv[2]) as reader: + expected = reader.read_all() +given, recovered = expected.column("x").combine_chunks(), actual.column("x").combine_chunks() +assert given.type == recovered.type +assert given.storage.equals(recovered.storage) +assert actual.equals(expected) +actual_field, expected_field = actual.schema.field("x"), expected.schema.field("x") +assert identity_node(actual_field).identifier == identity_node(expected_field).identifier +ordinary = {k: v for k, v in actual_field.metadata.items() if not k.startswith(b"ARROW:extension:")} +assert ordinary == expected_field.metadata +""" + for count in (1, 2): + DeltaTableDatabase(tmp_path).add_record( + PATH, str(count).encode(), table, flush=True + ) + warm = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert warm is not None + expected = pa.concat_tables([table] * count) + assert warm.select(["x"]).equals(expected, check_metadata=True) + expected_file = tmp_path / "expected.arrow" + with pa.ipc.new_file(str(expected_file), expected.schema) as writer: + writer.write_table(expected) + subprocess.run( + [sys.executable, "-c", code, str(tmp_path), str(expected_file)], check=True + ) + + +def test_delta_refuses_annotation_in_later_chunk(tmp_path: Path) -> None: + """A child annotation in a later chunk can differ from the table schema.""" + extension = _Unit("itl1372.later", pa.large_string()) + values = pa.array(["a"], extension.storage_type) + field = pa.field("v", values.type) + plain = pa.StructArray.from_arrays([values], fields=[field]) + annotated = pa.StructArray.from_arrays( + [values], fields=[field.with_metadata(_annotation(extension))] + ) + x = pa.chunked_array([plain, annotated]) + table = pa.Table.from_arrays( + [pa.array([b"1", b"2"], pa.large_binary()), x], names=["id", "x"] + ) + assert not table.schema.field("x").type.field("v").metadata + assert x.chunk(1).type.field("v").metadata + + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match=r"x\.v"): + db.add_records(PATH, table, record_id_column="id") + db.flush() + assert db.get_all_records(PATH) is None + + +def _struct_chunks_with_later_annotation() -> tuple[pa.StructArray, pa.StructArray]: + """Return two struct chunks with a logical annotation only in the second.""" + inner = _Unit("itl1372.chunk_inner", pa.large_string()) + field = pa.field("path", inner.storage_type) + plain = pa.StructArray.from_arrays( + [pa.array(["ordinary"], field.type)], fields=[field] + ) + annotated = pa.StructArray.from_arrays( + [pa.array(["marked"], field.type)], + fields=[field.with_metadata(_annotation(inner))], + ) + return plain, annotated + + +@pytest.mark.parametrize("wrapped", [False, True], ids=["direct", "wrapped"]) +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +@pytest.mark.parametrize("append", [False, True], ids=["create", "append"]) +def test_delta_refuses_later_chunk_annotation_in_extension_storage( + tmp_path: Path, wrapped: bool, registered: bool, append: bool +) -> None: + """Arrow type equality hides child metadata in a later extension chunk.""" + plain, annotated = _struct_chunks_with_later_annotation() + outer = _Unit("itl1372.chunk_outer", plain.type) + clean = outer.wrap_array(plain) + marked = _Unit(outer.extension_name, annotated.type).wrap_array(annotated) + chunks = pa.chunked_array([clean, marked]) + records = pa.Table.from_arrays( + [pa.array([b"1", b"2"], pa.large_binary()), chunks], names=["id", "measurement"] + ) + schema_type = records.schema.field("measurement").type + later_type = records.column("measurement").chunk(1).type + assert isinstance(schema_type, pa.BaseExtensionType) + assert isinstance(later_type, pa.BaseExtensionType) + assert schema_type.storage_type.field(0).metadata is None + metadata = later_type.storage_type.field(0).metadata or {} + assert metadata[NAME] == b"itl1372.chunk_inner" + assert later_type.equals(schema_type, check_metadata=True) + + with _register(outer, registered): + delta = DeltaTableDatabase(tmp_path) + db = ( + ExtensionAwareDatabase( + delta, + UniversalTypeConverter(logical_type_registry=LogicalTypeRegistry()), + ) + if wrapped + else delta + ) + table_dir = tmp_path / PATH[0] + version = None + if append: + db.add_record( + PATH, b"existing", pa.table({"measurement": clean}), flush=True + ) + version = DeltaTable(str(table_dir)).version() + with pytest.raises(UnstorableColumnError, match=r"measurement\.path"): + db.add_records(PATH, records, record_id_column="id") + db.flush() + reopened = DeltaTableDatabase(tmp_path).get_all_records(PATH) + if version is not None: + assert DeltaTable(str(table_dir)).version() == version + assert reopened is not None + assert reopened.num_rows == 1 + else: + assert not (table_dir / "_delta_log").exists() + assert reopened is None + + +def test_delta_refuses_later_chunk_annotation_in_dictionary_values( + tmp_path: Path, +) -> None: + """The nested annotation is refused before Delta attempts to store the dictionary.""" + plain, annotated = _struct_chunks_with_later_annotation() + indices = pa.array([0], pa.int8()) + chunks = pa.chunked_array( + [pa.DictionaryArray.from_arrays(indices, chunk) for chunk in (plain, annotated)] + ) + records = pa.Table.from_arrays( + [pa.array([b"1", b"2"], pa.large_binary()), chunks], names=["id", "measurement"] + ) + schema_type = records.schema.field("measurement").type + later_type = records.column("measurement").chunk(1).type + assert isinstance(schema_type, pa.DictionaryType) + assert isinstance(later_type, pa.DictionaryType) + assert schema_type.value_type.field(0).metadata is None + metadata = later_type.value_type.field(0).metadata or {} + assert metadata[NAME] == b"itl1372.chunk_inner" + assert later_type.equals(schema_type, check_metadata=True) + + db = DeltaTableDatabase(tmp_path) + with pytest.raises( + UnstorableColumnError, match=r"measurement\.path" + ): + db.add_records(PATH, records, record_id_column="id", flush=True) + db.flush() + assert not (tmp_path / PATH[0] / "_delta_log").exists() + + +@pytest.mark.parametrize("nested", [False, True], ids=["top-level", "nested"]) +@pytest.mark.parametrize( + "key", [b"ARROW:extension:review-marker", b"review-marker"], ids=["prefix", "plain"] +) +def test_delta_preserves_ordinary_field_metadata( + tmp_path: Path, nested: bool, key: bytes +) -> None: + """Creation and identical appends preserve ordinary field metadata verbatim.""" + values = pa.array(["text"], pa.large_string()) + field = pa.field("v", values.type, metadata={key: b"keep"}) + if nested: + table = pa.table( + {"measure": pa.StructArray.from_arrays([values], fields=[field])} + ) + else: + table = pa.Table.from_arrays( + [values], schema=pa.schema([field.with_name("measure")]) + ) + + for count in (1, 2): + DeltaTableDatabase(tmp_path).add_record( + PATH, str(count).encode(), table, flush=True + ) + read = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert read is not None + assert read.select(["measure"]).equals( + pa.concat_tables([table] * count), check_metadata=True + ) + + +def test_delta_refuses_nested_extension_metadata_without_a_name(tmp_path: Path) -> None: + """The blanket rule covers incomplete as well as complete extension annotations.""" + values = pa.array(["a"], pa.large_string()) + field = pa.field("v", values.type, metadata={META: b"{}"}) + column = pa.StructArray.from_arrays([values], fields=[field]) + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match=r"x\.v"): + db.add_record(PATH, b"1", pa.table({"x": column})) + db.flush() + assert db.get_all_records(PATH) is None diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index a37606b8e..fd28ee20b 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -35,7 +35,11 @@ identity_node, logical_identity_change, ) -from orcapod.errors import InputValidationError, OrcapodDatabaseReadError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) from orcapod.logical_types.identifier import LogicalTypeIdentifier from orcapod.logical_types.registry import make_arrow_extension_type from orcapod.logical_types.registry import LogicalTypeRegistry @@ -181,26 +185,6 @@ def _through(db: Any, via: str) -> Any: return ExtensionAwareDatabase(db, converter) -def _supported(kind: str, form: str, depth: str) -> bool: - """Whether ``kind`` stores the column at all (the type matrix): both do.""" - return True - - -def _abstains(kind: str, state: str, depth: str) -> bool: - """Whether the identity rule cannot know the held identifier, and so abstains: - a Delta list item or map key or item, which the Delta log keeps no metadata for - (ITL-1372). There the database's other checks decide, exactly as on main.""" - return kind == "Delta" and state != "pending" and depth in ("list", "map value") - - -def _main_accepts(kind: str, state: str, form: str, depth: str) -> bool: - """Where the rule abstains, main accepts a map of extension values whatever the - identifier (Delta wrote it as plain storage, ITL-1372; pinned below).""" - return ( - _abstains(kind, state, depth) and form == "extension" and depth == "map value" - ) - - KINDS = ("in-memory", "Delta") STATES = ("pending", "committed", "reopened") FORMS = ("extension", "annotated") @@ -209,23 +193,17 @@ def _main_accepts(kind: str, state: str, form: str, depth: str) -> bool: BASE = [ (kind, state, form, depth) for kind, state, form, depth in itertools.product(KINDS, STATES, FORMS, DEPTHS) - if _supported(kind, form, depth) - and not (kind == "in-memory" and state == "reopened") + if (kind == "in-memory" and state != "reopened") + or (kind == "Delta" and depth == "top") ] REFUSED_CASES = [ pytest.param(*case, change, id=f"{'-'.join(case)}-{change}") for case in BASE for change in CHANGES - if not _main_accepts(*case) ] -SAME_CASES = [ - pytest.param(*case, id="-".join(case)) - for case in BASE - # Main refuses a second list of extension values for its item's name (ITL-1372). - if not (_abstains(case[0], case[1], case[3]) and case[2:] == ("extension", "list")) -] +SAME_CASES = [pytest.param(*case, id="-".join(case)) for case in BASE] def _write_held(store: _Store, via: str, state: str, form: str, depth: str) -> None: @@ -262,12 +240,11 @@ def test_another_identifier_is_refused( message = str(refused.value) assert "column 'x'" in message assert "othing was written" in message - if not _abstains(kind, state, depth): - assert repr(_text(HELD)) in message - identifier = CHANGES[change] - assert ( - repr(_text(identifier)) if identifier is not None else "no logical type" - ) in message + assert repr(_text(HELD)) in message + identifier = CHANGES[change] + assert ( + repr(_text(identifier)) if identifier is not None else "no logical type" + ) in message # Nothing was buffered, and the held rows are unchanged. _assert_only_held_rows(store) @@ -291,7 +268,7 @@ def test_same_identifier_is_accepted( ) # A stored Delta column with no identifier and no recorded type: the rule # abstains (test_delta_logical_type_over_a_plain_column). - if not (kind == "Delta" and state == "committed") + if kind == "in-memory" or (state == "pending" and depth == "top") ] @@ -314,45 +291,6 @@ def test_a_logical_type_over_a_plain_column_is_refused( assert store.stored().column("id").to_pylist() == [b"1"] -@pytest.mark.parametrize("state", ["committed", "reopened"]) -def test_delta_list_and_map_of_extension_values_decide_as_on_main( - tmp_path: Path, state: str -) -> None: - """Pins the behaviour of ITL-1372; revisit there. - - Delta writes a list item or map item of an extension type as plain storage, and - its log keeps no metadata there, so the identity rule cannot know the stored - identifier and abstains: main's checks decide. A second list is refused for its - item's name (``item`` given, ``element`` stored); a second map is accepted with any - identifier, and every row reads back as plain storage. A same-type append to the - pending batch is accepted. - """ - for depth in ("list", "map value"): - root = tmp_path / depth.replace(" ", "_") - with _store("Delta", root) as store: - db = store.db - db.add_records( - PATH, _rows(HELD, "extension", depth, [b"1"]), record_id_column="id" - ) - db.add_records( - PATH, _rows(HELD, "extension", depth, [b"22"]), record_id_column="id" - ) - db.flush() - if state == "reopened": - store.reopen() - other = _rows(("itl1371.b", b"m"), "extension", depth, [b"333"]) - if depth == "list": - with pytest.raises(InputValidationError, match="is named 'item'"): - store.db.add_records(PATH, other, record_id_column="id") - assert store.stored().num_rows == 2 - continue - store.db.add_records(PATH, other, record_id_column="id") - stored = store.stored() - assert stored.num_rows == 3 - item = stored.schema.field("x").type.item_field - assert identity_node(item).identifier is None # read back plain - - def test_the_reproducer_through_the_wrapper(tmp_path: Path) -> None: """ITL-1371 as reported: annotated, aligned columns, through the wrapper over Delta.""" inner = DeltaTableDatabase(tmp_path / "delta") @@ -448,63 +386,6 @@ def map_field(identifier: tuple[str, bytes]) -> "pa.Field[Any]": assert reason is not None and reason.startswith("x.key ") -def _struct_rows(form: str, unit: bytes, ids: list[bytes]) -> pa.Table: - """``x: struct``, ``v`` of logical type ``HELD`` with ``{unit: }`` beside - its identifier.""" - field, array = _leaf(HELD, form, [i.decode() for i in ids]) - field = field.with_metadata({**dict(field.metadata or {}), b"unit": unit}) - struct = pa.StructArray.from_arrays([array], fields=[field]) - return pa.Table.from_arrays( - [pa.array(ids, pa.large_binary()), struct], - schema=pa.schema( - [pa.field("id", pa.large_binary()), pa.field("x", struct.type)] - ), - ) - - -@pytest.mark.parametrize( - ("form", "state"), - [ - ("annotated", "pending"), - ("annotated", "committed"), - ("annotated", "reopened"), - # Committed, a struct child of an extension type with metadata of its own is - # refused even for the same type, as on main: the held view drops the child's - # own metadata (reported with ITL-1372). - ("extension", "pending"), - ], -) -def test_delta_other_nested_metadata_beside_an_identifier_is_still_refused( - tmp_path: Path, form: str, state: str -) -> None: - """The identity rule finds the same identifier on the struct child; the ITL-1334 - comparison of nested field metadata, which is main's, still refuses the child's - other non-extension metadata.""" - with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, - _struct_rows(form, b"m", [b"1"]), - record_id_column="id", - flush=state != "pending", - ) - if state == "reopened": - store.reopen() - store.db.add_records( - PATH, _struct_rows(form, b"m", [b"22"]), record_id_column="id" - ) - with pytest.raises(InputValidationError, match="x.v has other field metadata"): - store.db.add_records( - PATH, _struct_rows(form, b"s", [b"333"]), record_id_column="id" - ) - ids = store.stored().sort_by("id").column("id").to_pylist() - assert ids == [b"1", b"22"] - - -# --------------------------------------------------------------------------- -# Review round 1 (PR 492) -# --------------------------------------------------------------------------- - - def _struct_of(field: "pa.Field[Any]", array: Any, ids: list[bytes]) -> pa.Table: struct = pa.StructArray.from_arrays([array], fields=[field.with_name("v")]) return pa.Table.from_arrays( @@ -515,109 +396,87 @@ def _struct_of(field: "pa.Field[Any]", array: Any, ids: list[bytes]) -> pa.Table ) -@pytest.mark.parametrize("state", ["committed", "reopened"]) -@pytest.mark.parametrize( - ("first", "second"), [("extension", "annotated"), ("annotated", "extension")] -) -def test_delta_struct_child_representation_change_is_refused_as_on_main( - tmp_path: Path, first: str, second: str, state: str -) -> None: - """The same identifier in the other representation on a struct child is refused, - as on main, and nothing about the stored rows changes: their identifier reads - back, and no recorded type is written.""" +def _write_legacy(root: Path, rows: pa.Table) -> None: + """Seed a Delta log in the layout used before ITL-1372's write preflight.""" import deltalake - with _store("Delta", tmp_path) as store: - field, array = _leaf(HELD, first, ["1"]) - store.db.add_records( - PATH, _struct_of(field, array, [b"1"]), record_id_column="id", flush=True - ) - log_before = deltalake.DeltaTable(str(tmp_path / "delta" / "t")).schema() - if state == "reopened": - store.reopen() - field, array = _leaf(HELD, second, ["22"]) - with pytest.raises(InputValidationError, match="x.v has other field metadata"): - store.db.add_records( - PATH, _struct_of(field, array, [b"22"]), record_id_column="id" - ) - stored = store.stored() - assert stored.column("id").to_pylist() == [b"1"] - child = stored.schema.field("x").type.field("v") - assert identity_node(child).identifier == (HELD[0].encode(), HELD[1]) - log_after = deltalake.DeltaTable(str(tmp_path / "delta" / "t")).schema() - assert log_after.fields[1].metadata == log_before.fields[1].metadata + from orcapod.databases.delta_arrow_types import to_delta_layout + records = rows.rename_columns(["__record_id", "x"]) + deltalake.write_deltalake(str(root / "t"), to_delta_layout(records)) -def _readable_type() -> Any: - """A registered logical type that writes ``b"new"`` and also reads ``b"old"``.""" - ext_class: Any = make_arrow_extension_type( + +def test_delta_reads_an_older_annotated_struct_child(tmp_path: Path) -> None: + """Physical identifier bytes on an old struct protect its existing rows.""" + extension_class: Any = make_arrow_extension_type( "itl1371.readable", pa.large_string(), b"new", also_reads=(b"old",) ) + extension = extension_class() + field = pa.field( + "v", pa.large_string(), metadata={NAME: b"itl1371.readable", META: b"old"} + ) + _write_legacy(tmp_path, _struct_of(field, pa.array(["1"], field.type), [b"1"])) + pa.register_extension_type(extension) try: - pa.register_extension_type(ext_class()) - except pa.ArrowKeyError: - pass # registered by an earlier test in this process - return ext_class + db = DeltaTableDatabase(tmp_path) + new = pa.array(["2"], pa.large_string()) + with pytest.raises( + InputValidationError, match="the stored column's 'itl1371.readable;6f6c64'" + ): + db.add_records( + PATH, + _struct_of(pa.field("v", new.type), new, [b"2"]), + record_id_column="id", + ) + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.column("id").to_pylist() == [b"1"] + assert stored.column("x").to_pylist() == [{"v": "1"}] + finally: + pa.unregister_extension_type(extension.extension_name) -def _annotated_nested(meta: bytes, depth: str, ids: list[bytes]) -> pa.Table: - field = pa.field( - "v", pa.large_string(), metadata={NAME: b"itl1371.readable", META: meta} - ) - array = pa.array([i.decode() for i in ids], pa.large_string()) - if depth == "struct": - return _struct_of(field, array, ids) - list_type = pa.large_list(field.with_name("item")) - lists = pa.LargeListArray.from_arrays( - pa.array(range(len(ids) + 1), pa.int64()), array, type=list_type +def test_delta_legacy_record_keeps_dictionary_child_identifier(tmp_path: Path) -> None: + """Verify the read and identity fallback when only the recorded type has the identifier.""" + import deltalake + from deltalake.schema import StructType + + held = _wrapped(b"m", ["1"]) + dictionary = pa.DictionaryArray.from_arrays(pa.array([0], pa.int8()), held) + struct = pa.StructArray.from_arrays( + [dictionary, pa.array([65535], pa.uint16())], names=["v", "u"] ) - return pa.Table.from_arrays( - [pa.array(ids, pa.large_binary()), lists], - schema=pa.schema([pa.field("id", pa.large_binary()), pa.field("x", list_type)]), + _write_legacy( + tmp_path, pa.table({"id": pa.array([b"1"], pa.large_binary()), "x": struct}) ) + log = deltalake.DeltaTable(str(tmp_path / "t")) + field = log.schema().fields[1] + physical = field.type + assert isinstance(physical, StructType) + assert physical.fields[0].metadata == {} + assert "orcapod:arrow_type" in field.metadata + db = DeltaTableDatabase(tmp_path) + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + child = stored.schema.field("x").type.field("v") + assert identity_node(child).identifier == (b"itl1371.a", b"m") + assert stored.column("x").to_pylist() == [{"v": "1", "u": 65535}] - -@pytest.mark.parametrize("depth", ["struct", "list"]) -@pytest.mark.parametrize( - ("held", "given"), [(b"old", b"new"), (b"old", b"old"), (b"new", b"new")] -) -def test_delta_registered_nested_type_decides_by_raw_bytes( - tmp_path: Path, depth: str, held: bytes, given: bytes -) -> None: - """A registered logical type nested in a Delta column with a recorded type. - - The identity rule decides by the raw stored bytes, which the Delta log keeps for - a struct child: ``old`` then ``new`` is refused naming both. It cannot know them - for a list item (the log keeps none, and the recorded type is read through the - registry, which gives ``new`` for ``old``), so it abstains there. Every case is - refused, as on main: main's field-metadata check compares the given annotation - with the recorded type as the registry reads it, an extension type, so it refuses - even an identical second append (pre-existing; reported with ITL-1372). - """ - _readable_type() - with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, - _annotated_nested(held, depth, [b"1"]), - record_id_column="id", - flush=True, - ) - store.reopen() - with pytest.raises(InputValidationError) as refused: - store.db.add_records( - PATH, _annotated_nested(given, depth, [b"22"]), record_id_column="id" + different = pa.array(["2"], pa.large_string()) + for ids, skip in (([b"2"], False), ([b"1"], True)): + with pytest.raises( + InputValidationError, match="the stored column's 'itl1371.a;6d'" + ): + db.add_records( + PATH, + _struct_of(pa.field("v", different.type), different, ids), + record_id_column="id", + skip_duplicates=skip, ) - message = str(refused.value) - if depth == "struct" and held != given: - assert f"x.v is of logical type {_raw_text(given)}" in message - assert f"the stored column's {_raw_text(held)}" in message - else: - assert "has other field metadata" in message - assert store.stored().column("id").to_pylist() == [b"1"] - - -def _raw_text(meta: bytes) -> str: - return repr(f"itl1371.readable;{meta.hex()}") + db.flush() + after = db.get_all_records(PATH, record_id_column="id") + assert after is not None and after.equals(stored, check_metadata=True) def _wrapped(meta: bytes, values: list[str]) -> Any: @@ -739,34 +598,6 @@ def _identifiers(node: IdentityNode) -> list[Any]: return found -def test_delta_dictionary_of_extension_values(tmp_path: Path) -> None: - """A dictionary is an encoding: its values' identifier stands where it stands. A - pending batch is compared as given (another identifier refused). Delta decodes a - dictionary column and stores its values as plain values, losing the identifier - (pre-existing, ITL-1372): over that loss the rule cannot know the stored - identifier, so a dictionary written again is accepted and its rows stored as on - main (plain values).""" - with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, _container_rows("dictionary", b"m", [b"1"]), record_id_column="id" - ) - with pytest.raises(InputValidationError, match="x is of logical type"): - store.db.add_records( - PATH, - _container_rows("dictionary", b"n", [b"22"]), - record_id_column="id", - ) - store.db.flush() - store.reopen() - store.db.add_records( - PATH, _container_rows("dictionary", b"m", [b"333"]), record_id_column="id" - ) - stored = store.stored().sort_by("id") - assert stored.column("id").to_pylist() == [b"1", b"333"] - assert stored.column("x").to_pylist() == ["1", "333"] - assert identity_node(stored.schema.field("x")).identifier is None - - def _dictionary_layout( ids: list[bytes], meta: bytes, *, encoded: bool, nested: bool, form: str ) -> pa.Table: @@ -789,13 +620,12 @@ def _dictionary_layout( ) -@pytest.mark.parametrize("form", FORMS) @pytest.mark.parametrize("state", ["committed", "reopened"]) -def test_delta_dictionary_of_the_stored_type_is_accepted( - tmp_path: Path, state: str, form: str +def test_delta_annotated_dictionary_of_the_stored_type_is_accepted( + tmp_path: Path, state: str ) -> None: - """A committed extension column, then a dictionary of that exact type: the same - identifier, accepted as on main, and every row reads back with it.""" + """A dictionary of storage values with the held column's annotation keeps it.""" + form = "annotated" with _store("Delta", tmp_path) as store: store.db.add_records( PATH, @@ -822,63 +652,17 @@ def test_delta_dictionary_of_the_stored_type_is_accepted( ) -@pytest.mark.parametrize("state", ["committed", "reopened"]) -def test_delta_dictionary_of_structs_with_another_child_identifier_is_refused( - tmp_path: Path, state: str -) -> None: - """A committed struct whose child is annotated ``m``, then a dictionary of structs - whose child is annotated ``n``: the log's raw bytes and the given ones differ, - refused; the stored rows keep ``m``. The same child identifier is accepted.""" - with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, - _dictionary_layout( - [b"1"], b"m", encoded=False, nested=True, form="annotated" - ), - record_id_column="id", - flush=True, - ) - if state == "reopened": - store.reopen() - with pytest.raises(InputValidationError, match="x.v is of logical type"): - store.db.add_records( - PATH, - _dictionary_layout( - [b"2"], b"n", encoded=True, nested=True, form="annotated" - ), - record_id_column="id", - ) - store.db.add_records( - PATH, - _dictionary_layout( - [b"3"], b"m", encoded=True, nested=True, form="annotated" - ), - record_id_column="id", - ) - stored = store.stored().sort_by("id") - assert stored.column("id").to_pylist() == [b"1", b"3"] - child = stored.schema.field("x").type.field("v") - assert identity_node(child).identifier == (b"itl1371.a", b"m") - - @pytest.mark.parametrize("state", ["pending", "committed", "reopened"]) -@pytest.mark.parametrize( - "metadata", - [ - {b"orcapod:arrow_type": b"a"}, # an ordinary key with that name, nested - {META: b"a"}, # extension metadata without a name: no identifier - ], - ids=["arrow_type key", "lone extension metadata"], -) def test_other_nested_metadata_without_an_identifier_is_still_refused( - tmp_path: Path, metadata: dict[bytes, bytes], state: str + tmp_path: Path, state: str ) -> None: """Nested metadata other than a complete identifier stays with ITL-1334's comparison: a change is refused, as on main.""" def rows(value: bytes, ids: list[bytes]) -> pa.Table: - key = next(iter(metadata)) - field = pa.field("v", pa.large_string(), metadata={key: value}) + field = pa.field( + "v", pa.large_string(), metadata={b"orcapod:arrow_type": value} + ) array = pa.array([i.decode() for i in ids], pa.large_string()) return _struct_of(field, array, ids) @@ -1203,7 +987,7 @@ def test_delta_identity_is_checked_before_recorded_types_are_decoded( with _store("Delta", tmp_path) as store: store.db.add_records( PATH, - _rows(HELD, "annotated", "struct", [b"1"]), + _rows(HELD, "extension", "top", [b"1"]), record_id_column="id", flush=True, ) @@ -1215,11 +999,11 @@ def undecodable(_: Any) -> Any: monkeypatch.setattr(delta_module, "_held_columns", undecodable) with pytest.raises( - InputValidationError, match="x.v is of logical type 'itl1371.b" + InputValidationError, match="x is of logical type 'itl1371.b" ): store.db.add_records( PATH, - _rows(("itl1371.b", b"m"), "annotated", "struct", [b"22"]), + _rows(("itl1371.b", b"m"), "extension", "top", [b"22"]), record_id_column="id", ) @@ -1294,8 +1078,14 @@ def rows(ids: list[bytes], identifier: bool) -> pa.Table: ) if state == "reopened": store.reopen() - with pytest.raises(InputValidationError, match="stored column's no logical"): - store.db.add_records(PATH, rows([b"22"], True), record_id_column="id") + if encoded and form == "extension": + with pytest.raises(UnstorableColumnError, match="dictionary values"): + store.db.add_records(PATH, rows([b"22"], True), record_id_column="id") + else: + with pytest.raises( + InputValidationError, match="stored column's no logical" + ): + store.db.add_records(PATH, rows([b"22"], True), record_id_column="id") assert store.stored().column("id").to_pylist() == [b"1"] @@ -1347,94 +1137,61 @@ def test_delta_logical_type_over_a_plain_column(tmp_path: Path, state: str) -> N @pytest.mark.parametrize("state", ["committed", "reopened"]) -def test_delta_extension_after_a_dictionary_first_write( +def test_delta_extension_after_a_legacy_dictionary_first_write( tmp_path: Path, state: str ) -> None: - """Delta writes a first dictionary of extension values as plain values with no - identifier and no recorded type (ITL-1372): the same type appended again, as a - plain extension column or as a dictionary, is accepted, as on main.""" + """A legacy dictionary of extension values was stored as plain text.""" + import deltalake + + root = tmp_path / "delta" + # Model the old log, which had neither an extension identifier nor a recorded type. + plain = pa.table( + { + "__record_id": pa.array([b"1"], pa.large_binary()), + "x": pa.array(["1"], pa.large_string()), + } + ) + deltalake.write_deltalake(str(root / "t"), plain) with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, - _container_rows("dictionary", b"m", [b"1"]), - record_id_column="id", - flush=True, - ) + assert store.stored().column("x").to_pylist() == ["1"] if state == "reopened": store.reopen() - plain = pa.table( + extension = pa.table( {"id": pa.array([b"22"], pa.large_binary()), "x": _wrapped(b"m", ["22"])} ) - store.db.add_records(PATH, plain, record_id_column="id", flush=True) - store.db.add_records( - PATH, _container_rows("dictionary", b"m", [b"333"]), record_id_column="id" - ) + store.db.add_records(PATH, extension, record_id_column="id", flush=True) + with pytest.raises(UnstorableColumnError, match="dictionary values"): + store.db.add_records( + PATH, + _container_rows("dictionary", b"m", [b"333"]), + record_id_column="id", + ) stored = store.stored().sort_by("id") - assert stored.column("id").to_pylist() == [b"1", b"22", b"333"] + assert stored.column("id").to_pylist() == [b"1", b"22"] @pytest.mark.parametrize("skip_duplicates", [False, True]) def test_delta_identity_is_refused_before_an_undecodable_stored_type( tmp_path: Path, skip_duplicates: bool ) -> None: - """A stored struct child annotated with an identifier the registered type cannot - read. The order is the same with either duplicate setting: the identity rule - reads the Delta log only and runs first, so another identifier is refused with - the same ``InputValidationError`` naming both, before anything is decoded. Only - when it passes does the duplicate scan run, and a read failure there propagates - as it is (a read failure fails the run whatever the error policy): the same - identifier with ``skip_duplicates`` raises ``OrcapodDatabaseReadError``. Without - it nothing reads the stored ids or decodes the recorded types before the rows - are queued but the field-metadata check (ITL-1334), which decodes the stored - struct's recorded type: the registered reader's own ``ValueError`` is raised, as - on main (that decode is not wrapped as a read failure; pre-existing).""" - - class Current(pa.ExtensionType): - def __init__(self) -> None: - super().__init__(pa.large_string(), "itl1371.current") - - def __arrow_ext_serialize__(self) -> bytes: - return b"new" - - @classmethod - def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: - raise ValueError("itl1371.current cannot read this metadata") - - def rows(ids: list[bytes], name: bytes, meta: bytes) -> pa.Table: - field = pa.field("v", pa.large_string(), metadata={NAME: name, META: meta}) - values = pa.array([i.decode() for i in ids], pa.large_string()) - return _struct_of(field, values, ids) - - db = DeltaTableDatabase(tmp_path / "delta") - db.add_records( - PATH, - rows([b"1"], b"itl1371.current", b"old"), - record_id_column="id", - flush=True, - ) - pa.register_extension_type(cast(Any, Current())) + """The legacy log exposes its raw identifier even if Arrow cannot read the rows.""" + field = pa.field("v", pa.large_string(), metadata={NAME: b"itl1371.a", META: b"m"}) + _write_legacy(tmp_path, _struct_of(field, pa.array(["1"], field.type), [b"1"])) + incoming = _rows(None, "extension", "struct", [b"2"]) + pa.register_extension_type(cast(Any, _failing_reader(ValueError)())) try: + db = DeltaTableDatabase(tmp_path) with pytest.raises(InputValidationError) as refused: - DeltaTableDatabase(tmp_path / "delta").add_records( - PATH, - rows([b"22", b"333"], b"itl1371.other", b"new"), - record_id_column="id", - skip_duplicates=skip_duplicates, + db.add_records( + PATH, incoming, record_id_column="id", skip_duplicates=skip_duplicates ) message = str(refused.value) - assert "x.v is of logical type 'itl1371.other;6e6577'" in message - assert "the stored column's 'itl1371.current;6f6c64'" in message - - same = rows([b"22", b"333"], b"itl1371.current", b"old") - db = DeltaTableDatabase(tmp_path / "delta") - if skip_duplicates: - with pytest.raises(OrcapodDatabaseReadError): - db.add_records(PATH, same, record_id_column="id", skip_duplicates=True) - else: - with pytest.raises(ValueError, match="cannot read this metadata"): - db.add_records(PATH, same, record_id_column="id") + assert "x.v is of logical type no logical type" in message + assert "the stored column's 'itl1371.a;6d'" in message + with pytest.raises(OrcapodDatabaseReadError): + db.get_all_records(PATH, record_id_column="id") finally: - pa.unregister_extension_type("itl1371.current") + pa.unregister_extension_type("itl1371.a") @pytest.mark.parametrize("state", ["pending", "committed"]) @@ -1660,64 +1417,41 @@ def test_duplicate_only_append_of_the_same_identifier_is_a_no_op( # --------------------------------------------------------------------------- -def _struct_beneath(shape: str, form: str, meta: bytes, ids: list[bytes]) -> pa.Table: - """``x``: a struct whose child ``v`` carries ``itl1371.a;`` (extension or - annotated), as a list item (``list``) or a map item (``map``).""" - field, leaf = _leaf(("itl1371.a", meta), form, [i.decode() for i in ids]) +def _map_of_structs(meta: bytes | None, ids: list[bytes]) -> pa.Table: + """A map value whose struct child carries the given extension identifier.""" + identifier = None if meta is None else ("itl1371.a", meta) + field, leaf = _leaf(identifier, "extension", [i.decode() for i in ids]) struct = pa.StructArray.from_arrays([leaf], fields=[field]) n = len(ids) - if shape == "list": - list_type = pa.large_list(pa.field("item", struct.type)) - x: Any = pa.LargeListArray.from_arrays( - pa.array(range(n + 1), pa.int64()), struct, type=list_type - ) - else: - map_type: Any = pa.map_( - pa.field("key", pa.large_string(), nullable=False), # pyright: ignore[reportArgumentType] - pa.field("value", struct.type), # pyright: ignore[reportArgumentType] - ) - keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) - offsets: Any = pa.array(range(n + 1), pa.int32()) - from_arrays: Any = pa.MapArray.from_arrays - x = from_arrays(offsets, keys, struct, type=map_type) - return pa.table({"id": pa.array(ids, pa.large_binary()), "x": x}) + keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) + offsets: Any = pa.array(range(n + 1), pa.int32()) + from_arrays: Any = pa.MapArray.from_arrays + return pa.table( + { + "id": pa.array(ids, pa.large_binary()), + "x": from_arrays(offsets, keys, struct), + } + ) -@pytest.mark.parametrize("state", ["committed", "reopened"]) -@pytest.mark.parametrize("form", FORMS) -@pytest.mark.parametrize("shape", ["list", "map"]) -def test_delta_struct_children_beneath_lists_and_maps_are_compared( - tmp_path: Path, shape: str, form: str, state: str -) -> None: - """A list item or map item keeps no metadata in the Delta log, but the children - of a struct beneath it do: the walk goes through the unknown item to them, so - another identifier there is refused, with fresh ids and duplicate-only, and the - same identifier is accepted.""" - path = "x[].v" if shape == "list" else "x.item.v" - with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, - _struct_beneath(shape, form, b"m", [b"1", b"22"]), - record_id_column="id", - flush=True, - ) - if state == "reopened": - store.reopen() - for ids, skip in (([b"333"], False), ([b"1", b"22"], True)): - with pytest.raises( - InputValidationError, match=re.escape(f"{path} is of logical type") - ): - store.db.add_records( - PATH, - _struct_beneath(shape, form, b"n", ids), - record_id_column="id", - skip_duplicates=skip, - ) - stored = store.stored() - assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ - b"1", - b"22", - ] +def test_delta_legacy_struct_children_beneath_maps_are_compared(tmp_path: Path) -> None: + """An extension-free append cannot overwrite a legacy map child's identifier.""" + _write_legacy(tmp_path, _map_of_structs(b"m", [b"1", b"22"])) + db = DeltaTableDatabase(tmp_path) + for ids, skip in (([b"333"], False), ([b"1", b"22"], True)): + with pytest.raises( + InputValidationError, match=r"x\.item\.v is of logical type no logical type" + ): + db.add_records( + PATH, + _map_of_structs(None, ids), + record_id_column="id", + skip_duplicates=skip, + ) + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [b"1", b"22"] def _late_chunk_rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: @@ -1743,16 +1477,13 @@ def _late_chunk_rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: @pytest.mark.parametrize("state", ["pending", "committed"]) -@pytest.mark.parametrize("kind", KINDS) -def test_a_later_chunk_annotation_is_compared( - tmp_path: Path, kind: str, state: str -) -> None: +def test_a_later_chunk_annotation_is_compared(tmp_path: Path, state: str) -> None: """Arrow keeps a nested field's annotation per chunk: a later chunk of another annotated identifier is refused, with fresh ids (either duplicate setting) and - duplicate-only (every id already held, ``skip_duplicates``), in every database; + duplicate-only (every id already held, ``skip_duplicates``), in memory; chunks of the same identifier are accepted, and the same identifier duplicate-only is a no-op (round 4, finding 2; round 5, finding 3).""" - with _store(kind, tmp_path) as store: + with _store("in-memory", tmp_path) as store: store.db.add_records( PATH, _late_chunk_rows([b"m", b"m"], [b"1", b"22"]), @@ -1948,7 +1679,7 @@ def rows(ext: Any, ids: list[bytes]) -> pa.Table: # --------------------------------------------------------------------------- -def _failing_reader(error: type[Exception]) -> Any: +def _failing_reader(error: type[Exception], *, readable: bytes | None = None) -> Any: """A registered ``itl1371.a`` whose reader cannot read stored metadata.""" class Failing(pa.ExtensionType): @@ -1956,71 +1687,60 @@ def __init__(self) -> None: super().__init__(pa.large_string(), "itl1371.a") def __arrow_ext_serialize__(self) -> bytes: - return b"current" + return b"current" if readable is None else readable @classmethod def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + if serialized == readable: + return cls() raise error("itl1371.a cannot read this metadata") return Failing @pytest.mark.parametrize("skip_duplicates", [False, True]) -@pytest.mark.parametrize("shape", ["list", "map"]) -def test_delta_identity_beneath_lists_and_maps_comes_before_an_undecodable_child( - tmp_path: Path, shape: str, skip_duplicates: bool +def test_delta_identity_beneath_map_comes_before_an_undecodable_child( + tmp_path: Path, skip_duplicates: bool ) -> None: - """A struct child beneath a list or map whose stored identifier the registered - reader cannot read: another identifier is refused naming both, from the log, - before any decode, with either duplicate setting (round 4, finding 1). The rows - are annotated: an extension type the registered reader cannot write is refused - as unstorable before the rule (a stated limit).""" - form = "annotated" + """Delta compares a map's struct child's identifier before decoding it.""" from orcapod.errors import TypeIdentityError root = tmp_path / "delta" - DeltaTableDatabase(root).add_records( - PATH, - _struct_beneath(shape, form, b"m", [b"1"]), - record_id_column="id", - flush=True, - ) + _write_legacy(root, _map_of_structs(b"m", [b"1"])) + incoming = _map_of_structs(None, [b"1", b"22"]) pa.register_extension_type(cast(Any, _failing_reader(TypeIdentityError)())) try: - path = "x[].v" if shape == "list" else "x.item.v" with pytest.raises( - InputValidationError, match=re.escape(f"{path} is of logical type") + InputValidationError, match=r"x\.item\.v is of logical type no logical type" ) as refused: DeltaTableDatabase(root).add_records( - PATH, - _struct_beneath(shape, form, b"n", [b"1", b"22"]), - record_id_column="id", - skip_duplicates=skip_duplicates, + PATH, incoming, record_id_column="id", skip_duplicates=skip_duplicates ) assert "the stored column's 'itl1371.a;6d'" in str(refused.value) finally: pa.unregister_extension_type("itl1371.a") -def test_delta_duplicate_scan_type_identity_error_propagates_as_itself( +def test_delta_legacy_read_type_identity_error_propagates_as_itself( tmp_path: Path, ) -> None: - """Pins main's ITL-881 carve-out (round 4, finding 6): the same identifier with - ``skip_duplicates``, over a stored child the registered reader refuses with - ``TypeIdentityError``: the duplicate scan's decode raises it as itself, not as - ``OrcapodDatabaseReadError``, in every ``schema_handling`` mode.""" + """A legacy annotated field still propagates a reader's TypeIdentityError.""" from orcapod.errors import TypeIdentityError - root = tmp_path / "delta" - rows = _rows(HELD, "annotated", "struct", [b"1"]) - DeltaTableDatabase(root).add_records(PATH, rows, record_id_column="id", flush=True) + _write_legacy( + tmp_path, _rows(HELD, "annotated", "struct", [b"1"]).select(["id", "x"]) + ) pa.register_extension_type(cast(Any, _failing_reader(TypeIdentityError)())) try: + db = DeltaTableDatabase(tmp_path) + with pytest.raises(TypeIdentityError): + db.get_all_records(PATH, record_id_column="id") + ids = pa.table({"id": pa.array([b"1"], pa.large_binary())}) for mode in ("error", "merge", "coerce"): with pytest.raises(TypeIdentityError): - DeltaTableDatabase(root).add_records( + db.add_records( PATH, - rows, + ids, record_id_column="id", skip_duplicates=True, schema_handling=cast(Any, mode), @@ -2154,113 +1874,6 @@ def test_delta_flush_refuses_after_another_writer_changed_the_identifier( # --------------------------------------------------------------------------- -class _DictExt(pa.ExtensionType): - def __init__(self, meta: bytes) -> None: - self._meta = meta - super().__init__(pa.large_string(), "itl1371.dict") - - def __arrow_ext_serialize__(self) -> bytes: - return self._meta - - @classmethod - def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: - return cls(serialized) - - -def _dictionary_child_rows(shape: str, meta: bytes, ids: list[bytes]) -> pa.Table: - """``x``: ``struct>, u: uint16>`` under a - recorded container (``list-list``, ``map-list``, ``fixed``, ``map``) or alone - (``struct``). Delta writes ``v`` as plain text with no metadata in the log; the - column's recorded Arrow type keeps ``v``'s identifier.""" - n = len(ids) - values = _DictExt(meta).wrap_array( - pa.array([f"s{i}" for i in range(n)], pa.large_string()) - ) - v = pa.DictionaryArray.from_arrays(pa.array(range(n), pa.int8()), values) - struct = pa.StructArray.from_arrays( - [v, pa.array(range(n), pa.uint16())], names=["v", "u"] - ) - offsets = pa.array(range(n + 1), pa.int64()) - keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) - map_offsets: Any = pa.array(range(n + 1), pa.int32()) - map_from: Any = pa.MapArray.from_arrays - x: Any - if shape == "struct": - x = struct - elif shape == "fixed": - x = pa.FixedSizeListArray.from_arrays(struct, 1) - elif shape == "map": - x = map_from(map_offsets, keys, struct) - else: - inner = pa.LargeListArray.from_arrays(offsets, struct) - x = ( - pa.LargeListArray.from_arrays(offsets, inner) - if shape == "list-list" - else map_from(map_offsets, keys, inner) - ) - return pa.table({"id": pa.array(ids, pa.large_binary()), "x": x}) - - -DICTIONARY_CHILD_PATHS = { - "list-list": "x[][].v", - "map-list": "x.item[].v", - "fixed": "x[].v", - "map": "x.item.v", - "struct": "x.v", -} - - -@pytest.mark.parametrize("shape", list(DICTIONARY_CHILD_PATHS)) -def test_delta_recorded_type_decides_a_child_the_log_keeps_plain( - tmp_path: Path, shape: str -) -> None: - """A dictionary child is written as plain text with no metadata in the Delta log; - the column's recorded Arrow type keeps its identifier. The stored side is read - from the physical field's own annotation, else from the recorded type at that - place, else not known: missing physical metadata alone never proves 'no logical - type'. So the identical duplicate-only batch is a no-op and the same identifier - with fresh ids keeps main's verdict (main's field-metadata check refuses it), while - another identifier is refused naming both (round 5, finding 1).""" - root = tmp_path / "delta" - DeltaTableDatabase(root).add_records( - PATH, - _dictionary_child_rows(shape, b"old", [b"1", b"22"]), - record_id_column="id", - flush=True, - ) - path = DICTIONARY_CHILD_PATHS[shape] - # The identical batch, duplicate-only: a no-op, as on main. - DeltaTableDatabase(root).add_records( - PATH, - _dictionary_child_rows(shape, b"old", [b"1", b"22"]), - record_id_column="id", - skip_duplicates=True, - flush=True, - ) - # The same identifier, fresh ids: main's field-metadata check refuses it (the - # identity rule does not). - with pytest.raises( - InputValidationError, match=re.escape(f"{path} has other field metadata") - ): - DeltaTableDatabase(root).add_records( - PATH, _dictionary_child_rows(shape, b"old", [b"333"]), record_id_column="id" - ) - # Another identifier, fresh or duplicate-only: refused naming both. - for ids, skip in (([b"333"], False), ([b"1", b"22"], True)): - with pytest.raises(InputValidationError) as refused: - DeltaTableDatabase(root).add_records( - PATH, - _dictionary_child_rows(shape, b"new", ids), - record_id_column="id", - skip_duplicates=skip, - ) - assert f"{path} is of logical type 'itl1371.dict;6e6577'" in str(refused.value) - assert "the stored column's 'itl1371.dict;6f6c64'" in str(refused.value) - stored = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="id") - assert stored is not None - assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [b"1", b"22"] - - def test_delta_handle_after_delete_and_recreate_reads_the_new_tables_ids( tmp_path: Path, ) -> None: diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 614e9900e..ef47aba82 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -18,12 +18,10 @@ - ``SILENT``: anything else (another type, other values, an error that does not name the column, a failed read). The test fails on any silent cell. -The databases: in-memory, Delta Lake (local directory), the connector database over -SQLite, over PostgreSQL and over SpiralDB. No PostgreSQL server and no SpiralDB is used: -the PostgreSQL cell comes from the connector's own storability rule +The databases: in-memory, Delta Lake (local directory), and the connector database over +SQLite and PostgreSQL. The PostgreSQL cell comes from the connector's own storability rule (``unstorable_column_reason`` and ``validate_records``, over a mocked connection), so it -is ``KEPT BY RULE`` or ``REFUSED``, never a measured read; the SpiralDB cell is measured -through the disk fake (``tests/test_databases/fake_spiral_sdk.py``). No database tells tag +is ``KEPT BY RULE`` or ``REFUSED``, never a measured read. No database tells tag columns from data columns: the connector databases tell only the record-id key, which Orcapod always writes as ``large_binary``. """ @@ -100,7 +98,13 @@ class Row: label: str group: str build: Callable[ - [Path], tuple["pa.Field[Any]", "pa.Field[Any]", list[Any], list[Any]] + [Path], + tuple[ + "pa.Field[Any]", + "pa.Field[Any]", + "list[Any] | pa.Array[Any]", + "list[Any] | pa.Array[Any]", + ], ] provisional: bool = False @@ -229,6 +233,42 @@ def _upaths(root: Path) -> list[Any]: return [UPath(f"memory://matrix/{i}") for i in range(3)] +def _nested_extension(container: str) -> Callable[[Path], tuple[Any, Any, Any, Any]]: + """Build Arrow arrays nesting the registered Path type in both columns.""" + + def wrap(values: Any, mask: Any) -> Any: + if container == "struct child": + return pa.StructArray.from_arrays([values], names=["p"], mask=mask) + if container == "list item": + return pa.LargeListArray.from_arrays( + pa.array([0, 1, 2, 3], pa.int64()), values, mask=mask + ) + if container == "map value": + from_arrays: Any = pa.MapArray.from_arrays + return from_arrays( + pa.array([0, 1, 2, 3], pa.int32()), + pa.array(["a", "b", "c"], pa.large_string()), + values, + mask=mask, + ) + assert container == "dictionary values" + indices = pa.array([0, None if mask is not None else 1, 2], pa.int32()) + return pa.DictionaryArray.from_arrays(indices, values) + + def build(_root: Path) -> tuple[Any, Any, Any, Any]: + extension: Any = get_default_context().type_converter.python_type_to_arrow_type( + Path + ) + values = extension.wrap_array( + pa.array(["/a", "/b", "/c"], type=extension.storage_type) + ) + x = wrap(values, None) + y = wrap(values, pa.array([False, True, False])) + return pa.field("x", x.type), pa.field("y", y.type), x, y + + return build + + ROWS: tuple[Row, ...] = ( *( Row(str(t), "integer", _plain(t, [1, 2, 100])) @@ -482,6 +522,14 @@ def _upaths(root: Path) -> list[Any]: "nullability", _plain(pa.string(), ["a", "b", "c"], nullable=False), ), + *( + Row( + f"extension type in {place}", + "nested extension type", + _nested_extension(place), + ) + for place in ("struct child", "list item", "map value", "dictionary values") + ), Row("File", "Orcapod logical type", _logical(orcapod.File, _files)), Row("Directory", "Orcapod logical type", _logical(orcapod.Directory, _directories)), Row( @@ -854,9 +902,11 @@ def _attribute_changes(rows: pa.Table) -> list[tuple[str, pa.Table]]: changed = _nested_changed(field.type) if changed is None: return out - # Built from the values: the append must be refused, so they are never read. - column = pa.array(nested.column(index).to_pylist(), changed) - nested = nested.set_column(index, field.with_type(changed), column) + # Only the schema changes. Keep the original arrays, including extension + # children that Arrow cannot rebuild from Python values. + nested = nested.set_column( + index, field.with_type(changed), nested.column(index) + ) out.append(("nested field metadata", nested)) return out @@ -1009,8 +1059,16 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: 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: diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py index ead2185f7..4b5420c00 100644 --- a/tests/test_pipeline/test_delta_refusals_in_jobs.py +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -21,6 +21,7 @@ from orcapod.databases import DeltaTableDatabase from orcapod.errors import ( InputValidationError, + OrcapodDatabaseWriteError, UnstorableColumnError, ) from orcapod.types import CacheMode @@ -109,3 +110,156 @@ def test_a_function_with_output_keys_differing_in_case_stops( _pair.pod(_source([1, 2], [1, 2]), label="fn") _run(job, use_async) assert not (tmp_path / "itl1403").exists() + + +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_annotated_list_reaches_delta_operator_log( + tmp_path: Path, use_async: bool, registered: bool +) -> None: + """A tagged Arrow source carries annotated storage to the logging operator.""" + from orcapod.contexts import get_default_context + + path_type: Any = get_default_context().type_converter.python_type_to_arrow_type( + Path + ) + metadata = { + b"ARROW:extension:name": ( + path_type.extension_name.encode() if registered else b"itl1372.missing" + ), + b"ARROW:extension:metadata": path_type.__arrow_ext_serialize__(), + } + item = pa.field("item", path_type.storage_type, metadata=metadata) + extra = pa.LargeListArray.from_arrays( + pa.array([0, 1, 2], pa.int64()), + pa.array(["/one", "/two"], item.type), + type=pa.large_list(item), + ) + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [10, 20], "extra": extra}), + tag_columns=["k"], + tag_only_columns=True, + record_id_columns=["k"], + source_id="input", + infer_nullable=True, + ) + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1372", database=database) + with job: + source.map_data({"x": "z"}, label="renamed") + job.nodes["renamed"].attach_databases(database, cache_mode=CacheMode.LOG) + with pytest.raises(OrcapodDatabaseWriteError) as error: + _run(job, use_async) + cause = error.value.__cause__ + assert isinstance(cause, UnstorableColumnError) + assert cause.column == "extra" + assert "logical type nested in another type" in cause.reason + assert "extra[]" in cause.reason + database.flush() + assert database.list_table_paths() == [] + + +def test_nested_logical_function_output_is_refused_at_declaration( + tmp_path: Path, +) -> None: + """A Python dict with logical values is refused before Delta gets a schema.""" + from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError + + def nested(v: int) -> dict[str, Path]: + return {"path": Path(str(v))} + + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1372", database=database) + with ( + job, + pytest.raises( + NestedTypeNotStorableError, match=r"Column 'payload'.*orcapod.path" + ), + ): + function_pod(output_keys="payload")(nested).pod( + _source([1], [2]), label="nested" + ) + database.flush() + assert database.list_table_paths() == [] + + +class _NestedStorageResult(str): + """A function result whose custom logical type declares annotated storage.""" + + +def test_delta_refuses_nested_logical_storage_in_function_output( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A custom logical output that reaches Delta is refused when attaching the store.""" + from orcapod.contexts import create_registry, get_default_context + from orcapod.logical_types.base_logical_type import BaseLogicalType + from orcapod.logical_types.registry import ( + make_arrow_extension_type, + make_polars_extension_type, + ) + from orcapod.semantic_types.universal_converter import UniversalTypeConverter + + label = "itl1372.nested-output" + storage = pa.struct( + [ + pa.field( + "leaf", + pa.large_string(), + metadata={ + b"ARROW:extension:name": b"itl1372.nested-leaf", + b"ARROW:extension:metadata": b"{}", + }, + ) + ] + ) + arrow_extension: Any = make_arrow_extension_type(label, storage, b"{}") + polars_extension: Any = make_polars_extension_type( + label, pa.struct([("leaf", pa.large_string())]) + ) + + class LogicalResult(BaseLogicalType): + logical_type_name = label + python_type = _NestedStorageResult + + def get_arrow_extension_type(self) -> pa.ExtensionType: + return arrow_extension() + + def get_polars_extension_type(self) -> Any: + return polars_extension() + + def python_to_storage( + self, value: _NestedStorageResult, converter: Any + ) -> dict[str, str]: + return {"leaf": str(value)} + + def storage_to_python( + self, storage_value: dict[str, str], converter: Any + ) -> _NestedStorageResult: + return _NestedStorageResult(storage_value["leaf"]) + + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type(LogicalResult()) + monkeypatch.setattr(get_default_context(), "type_converter", converter) + + @function_pod(output_keys="payload") + def nested(v: int | None) -> _NestedStorageResult: + return _NestedStorageResult(str(v)) + + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1372", database=database) + try: + with pytest.raises( + UnstorableColumnError, match=r"payload\.leaf" + ) as error: + with job: + nested.pod(_source([1], [2]), label="nested") + job.run() + assert error.value.column == "payload" + assert error.value.node_label == "nested" + database.flush() + assert database.list_table_paths() == [] + finally: + pa.unregister_extension_type(label)