From 0612479afb400208ac2a82ac80e1ca354f20692a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 18:40:28 -0800 Subject: [PATCH 1/4] fix(databases): refuse unsupported nested Delta extension types --- changelog.d/ITL-1372.md | 15 + docs/dev/design_issues/ITL-1372-LI2.md | 20 + docs/reference/database-types.md | 13 +- src/orcapod/databases/delta_arrow_types.py | 8 +- src/orcapod/databases/delta_lake_databases.py | 99 ++++- .../test_delta_nested_extension_types.py | 278 ++++++++++++ .../test_logical_identity_appends.py | 409 ++++-------------- tests/test_databases/type_matrix.py | 72 ++- 8 files changed, 582 insertions(+), 332 deletions(-) create mode 100644 changelog.d/ITL-1372.md create mode 100644 docs/dev/design_issues/ITL-1372-LI2.md create mode 100644 tests/test_databases/test_delta_nested_extension_types.py diff --git a/changelog.d/ITL-1372.md b/changelog.d/ITL-1372.md new file mode 100644 index 000000000..48224a0aa --- /dev/null +++ b/changelog.d/ITL-1372.md @@ -0,0 +1,15 @@ +### Breaking changes and migration + +- Delta now refuses raw Arrow columns with extension types in a list item or its + descendants, directly in a map key or value, or within dictionary values. It + also refuses fields beneath a list or map that supply a logical type through + `ARROW:extension:*` metadata, including unregistered identifiers previously + accepted. Registering those identifiers could make an identical second write + fail. Remove the annotations and store the affected values in their plain + Arrow storage form, or use an `InMemoryArrowDatabase` to keep the logical type. + +### Fixed + +- Delta names the columns with unsupported nested extension types before + buffering rows. This prevents writes that lose the logical type and lists + of structs whose renamed item field prevents an identical append. 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..a750ba902 --- /dev/null +++ b/docs/dev/design_issues/ITL-1372-LI2.md @@ -0,0 +1,20 @@ +## `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 store an extension array in a list item, map key or value, or +dictionary values as plain Arrow storage. A list of structs could keep the +struct child's identifier but rename the list item, causing an identical +append to fail. With extension metadata on storage fields beneath lists or +maps, an identical append could fail once the extension was registered. + +**Fix:** Delta checks the incoming schema before buffering. It refuses Arrow +extension types anywhere within list items or dictionary values, or directly +as map keys or values. It refuses storage fields carrying an extension +annotation anywhere beneath a list or map, regardless of registration. It +names the affected columns and points to plain storage or the in-memory +database. Arrow extension types on struct children, including under another +struct or a struct-valued map item, keep their existing write and read paths. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index a60973db0..fc06ac8f9 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -12,8 +12,8 @@ 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. What a cell says: @@ -255,6 +255,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 | kept | 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..1a632d6a7 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 extension fields are restored from +their extension metadata. ``DeltaTableDatabase.require_storable`` refuses nested +extension types and annotations that would be lost or prevent an identical append +(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 c88b322d8..415877f57 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1372,6 +1372,77 @@ def _holds_null_type(arrow_type: pa.DataType) -> bool: ) +def _unsupported_nested_extension( + field: "pa.Field[Any]", + *, + extension_slot: str | None = None, + annotation_slot: str | None = None, +) -> str | None: + """Describe a nested logical type Delta cannot keep (ITL-1372). + + Args: + field: The column or nested field to check. + extension_slot: An enclosing list item or dictionary value, where no + Arrow extension type is supported, even through a struct. + annotation_slot: An enclosing list item or map key or value, where + a stored annotation can restore as a different field once registered. + + Returns: + A description of the unsupported type and nesting, or ``None``. + """ + arrow_type = field.type + if isinstance(arrow_type, pa.BaseExtensionType): + if extension_slot is not None: + return f"an Arrow extension type in {extension_slot}" + return None + if annotation_slot is not None and b"ARROW:extension:name" in ( + field.metadata or {} + ): + return f"an extension type supplied as annotated storage in {annotation_slot}" + + t = pa.types + if ( + t.is_list(arrow_type) + or t.is_large_list(arrow_type) + or t.is_fixed_size_list(arrow_type) + ): + return _unsupported_nested_extension( + arrow_type.value_field, + extension_slot=extension_slot or "a list item", + annotation_slot=annotation_slot or "a list item", + ) + if t.is_dictionary(arrow_type): + return _unsupported_nested_extension( + field.with_type(arrow_type.value_type), + extension_slot=extension_slot or "dictionary values", + annotation_slot=annotation_slot, + ) + if t.is_map(arrow_type): + for child, slot in ( + (arrow_type.key_field, "a map key"), + (arrow_type.item_field, "a map value"), + ): + if isinstance(child.type, pa.BaseExtensionType): + return f"an Arrow extension type in {extension_slot or slot}" + reason = _unsupported_nested_extension( + child, + extension_slot=extension_slot, + annotation_slot=annotation_slot or slot, + ) + if reason is not None: + return reason + return None + for i in range(arrow_type.num_fields): + reason = _unsupported_nested_extension( + arrow_type.field(i), + extension_slot=extension_slot, + annotation_slot=annotation_slot, + ) + if reason is not None: + return reason + 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``. @@ -2322,8 +2393,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: @@ -2337,6 +2409,29 @@ def require_storable(self, schema: pa.Schema) -> None: arrow_type=schema.field(position).type, reason=_case_reason(*clash), ) + unsupported = [ + (field, reason) + for field in schema + if (reason := _unsupported_nested_extension(field)) is not None + ] + if unsupported: + (field, reason), *others = unsupported + details = [f"Delta cannot reliably round-trip {reason}"] + details.extend( + f"Column {other.name!r} of Arrow type {other.type} has {why}" + for other, why in others + ) + details.append( + "Store the affected columns in their storage form" + if others + else "Store the column in its storage form" + ) + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=field.name, + arrow_type=field.type, + reason=". ".join(details), + ) for field in schema: reason = delta_unstorable_reason(field) if reason is not None: 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..b0348857e --- /dev/null +++ b/tests/test_databases/test_delta_nested_extension_types.py @@ -0,0 +1,278 @@ +"""Delta keeps or refuses nested Arrow extension types before queuing (ITL-1372).""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod.databases import ( + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, +) +from orcapod.errors import UnstorableColumnError +from orcapod.logical_types.registry import LogicalTypeRegistry +from orcapod.semantic_types.universal_converter import UniversalTypeConverter + +PATH = ("t",) + + +class _Unit(pa.ExtensionType): + """A logical type over large strings.""" + + def __init__(self) -> None: + super().__init__(pa.large_string(), "itl1372.unit") + + def __arrow_ext_serialize__(self) -> bytes: + return b"{}" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> _Unit: + return cls() + + +@pytest.fixture +def unit() -> Any: + """An Arrow extension type registered for the lifetime of one test.""" + extension = _Unit() + pa.register_extension_type(cast(Any, extension)) + try: + yield extension + finally: + pa.unregister_extension_type(extension.extension_name) + + +def _nested(kind: str, values: Any) -> Any: + """Build one occurrence of `values` per row, nested in the given container.""" + offsets = range(len(values) + 1) + if kind == "list": + return pa.ListArray.from_arrays(pa.array(offsets, pa.int32()), values) + if kind == "large list": + return pa.LargeListArray.from_arrays(pa.array(offsets, pa.int64()), values) + if kind == "fixed-size list": + return pa.FixedSizeListArray.from_arrays(values, 1) + if kind == "list of structs": + return _nested("large list", _nested("struct", values)) + if kind == "struct of lists": + return _nested("struct", _nested("large list", values)) + if kind == "struct of dictionaries": + return _nested("struct", _nested("dictionary", values)) + if kind == "dictionary of structs": + return _nested("dictionary", _nested("struct", values)) + if kind == "struct of structs": + return _nested("struct", _nested("struct", values)) + if kind == "struct": + return pa.StructArray.from_arrays([values], names=["v"]) + if kind == "dictionary": + return pa.DictionaryArray.from_arrays( + pa.array(range(len(values)), pa.int32()), values + ) + ordinary = pa.array([f"k{i}" for i in range(len(values))], pa.large_string()) + from_arrays: Any = pa.MapArray.from_arrays + if kind == "map key": + return from_arrays(pa.array(offsets, pa.int32()), values, ordinary) + assert kind == "map value" + return from_arrays(pa.array(offsets, pa.int32()), ordinary, values) + + +REFUSED = [ + ("list", "list item"), + ("large list", "list item"), + ("fixed-size list", "list item"), + ("map key", "map key"), + ("map value", "map value"), + ("dictionary", "dictionary values"), + ("list of structs", "list item"), + ("struct of lists", "list item"), + ("struct of dictionaries", "dictionary values"), + ("dictionary of structs", "dictionary values"), +] + + +@pytest.mark.parametrize(("kind", "why"), REFUSED) +@pytest.mark.parametrize("wrap", [False, True], ids=["direct", "wrapper"]) +def test_nested_extension_is_refused_before_queueing( + tmp_path: Path, unit: Any, kind: str, why: str, wrap: bool +) -> None: + """Both write entry points reject the same column before it reaches the queue.""" + delta = DeltaTableDatabase(tmp_path) + db = ( + ExtensionAwareDatabase( + delta, UniversalTypeConverter(logical_type_registry=LogicalTypeRegistry()) + ) + if wrap + else delta + ) + values = unit.wrap_array(pa.array(["a"], pa.large_string())) + table = pa.table({"measurement": _nested(kind, values)}) + rows = table.append_column("id", pa.array([b"1"], pa.large_binary())) + with pytest.raises(UnstorableColumnError, match=why) as first: + db.add_records(PATH, rows, record_id_column="id") + db.flush() + assert db.get_all_records(PATH) is None + assert not (tmp_path / "t" / "_delta_log").exists() + + with pytest.raises(UnstorableColumnError, match=why) as second: + db.add_record(PATH, b"2", table) + assert str(first.value) == str(second.value) + assert first.value.column == "measurement" + assert first.value.arrow_type == table.schema.field("measurement").type + message = str(first.value) + assert "storage form" in message + assert "InMemoryArrowDatabase" in message + assert "docs/reference/database-types.md" in message + db.flush() + assert db.get_all_records(PATH) is None + assert not (tmp_path / "t" / "_delta_log").exists() + + +@pytest.mark.parametrize("order", [("samples", "units"), ("units", "samples")]) +def test_delta_names_both_unstorable_columns( + tmp_path: Path, unit: Any, order: tuple[str, str] +) -> None: + """All columns with unsupported extensions are named in either input order.""" + values = unit.wrap_array(pa.array(["a"], pa.large_string())) + columns = { + "samples": _nested("list", values), + "units": _nested("map value", values), + } + table = pa.table({name: columns[name] for name in order}) + rows = table.append_column("id", pa.array([b"1"], pa.large_binary())) + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError) as refused: + db.add_records(PATH, rows, record_id_column="id") + message = str(refused.value) + assert "'samples'" in message and "list item" in message + assert "'units'" in message and "map value" in message + db.flush() + assert db.get_all_records(PATH) is None + + +@pytest.mark.parametrize("kind", [*dict(REFUSED), "struct", "struct of structs"]) +def test_memory_keeps_nested_extensions(unit: Any, kind: str) -> None: + """In-memory preserves both writes, including the extension type.""" + values = unit.wrap_array(pa.array(["a"], pa.large_string())) + table = pa.table({"x": _nested(kind, values)}) + db = InMemoryArrowDatabase() + for rid in (b"1", b"2"): + db.add_record(PATH, rid, table) + db.flush() + stored = db.get_all_records(PATH) + assert stored is not None + assert stored.select(["x"]).equals( + pa.concat_tables([table, table]), check_metadata=True + ) + + +@pytest.mark.parametrize("kind", ["struct", "struct of structs"]) +def test_delta_keeps_extension_in_struct(tmp_path: Path, unit: Any, kind: str) -> None: + """Struct children keep their type and an identical second append succeeds.""" + values = unit.wrap_array(pa.array(["a"], pa.large_string())) + table = pa.table({"x": _nested(kind, values)}) + db = DeltaTableDatabase(tmp_path) + for rid in (b"1", b"2"): + db.add_record(PATH, rid, table) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert stored is not None + expected = table if rid == b"1" else pa.concat_tables([table, table]) + assert stored.select(["x"]).equals(expected, check_metadata=True) + + code = """ +import sys + +import pyarrow as pa + +from orcapod.databases import DeltaTableDatabase + +table = DeltaTableDatabase(sys.argv[1]).get_all_records(("t",)) +child = table.schema.field("x").type.field("v") +if sys.argv[2] == "struct of structs": + child = child.type.field("v") +assert child.type == pa.large_string(), child +assert child.metadata == { + b"ARROW:extension:name": b"itl1372.unit", + b"ARROW:extension:metadata": b"{}", +}, child.metadata +""" + subprocess.run([sys.executable, "-c", code, str(tmp_path), kind], check=True) + + +def test_delta_keeps_ordinary_struct_child_metadata_on_append(tmp_path: Path) -> None: + """An identical second write preserves ordinary metadata on a struct child.""" + field = pa.field("v", pa.large_string(), metadata={b"unit": b"m"}) + array = pa.StructArray.from_arrays([pa.array(["a"], field.type)], fields=[field]) + table = pa.table({"x": array}) + db = DeltaTableDatabase(tmp_path) + for rid in (b"1", b"2"): + db.add_record(PATH, rid, table) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert stored is not None + assert stored.select(["x"]).equals( + pa.concat_tables([table, table]), check_metadata=True + ) + + +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +@pytest.mark.parametrize( + "kind", ["list", "map value", "list of structs", "map of structs"] +) +def test_delta_refuses_annotated_storage_under_list_or_map( + tmp_path: Path, unit: Any, kind: str, registered: bool +) -> None: + """The refusal is independent of registry state and applies through a struct.""" + metadata = { + b"ARROW:extension:name": b"itl1372.unit" if registered else b"itl1372.missing", + b"ARROW:extension:metadata": b"{}", + } + field = pa.field("v", pa.large_string(), metadata=metadata) + values: Any = pa.array(["a"], field.type) + if kind.endswith("of structs"): + values = pa.StructArray.from_arrays([values], fields=[field]) + field = pa.field("v", values.type) + if kind.startswith("list"): + array = pa.LargeListArray.from_arrays( + pa.array([0, 1], pa.int64()), + values, + type=pa.large_list(field.with_name("item")), + ) + else: + from_arrays: Any = pa.MapArray.from_arrays + map_type = pa.map_(pa.large_string(), field.with_name("value")) # pyright: ignore[reportArgumentType] + array = from_arrays( + pa.array([0, 1], pa.int32()), + pa.array(["key"], pa.large_string()), + values, + type=map_type, + ) + db = DeltaTableDatabase(tmp_path) + errors = [] + for rid in (b"1", b"2"): + with pytest.raises(UnstorableColumnError, match="annotated storage") as refused: + db.add_record(PATH, rid, pa.table({"measurement": array})) + errors.append(str(refused.value)) + db.flush() + assert db.get_all_records(PATH) is None + assert errors[0] == errors[1] + + +def test_delta_keeps_extension_in_struct_under_map(tmp_path: Path, unit: Any) -> None: + """A map's struct child keeps its type and accepts identical appends.""" + values = unit.wrap_array(pa.array(["a"], pa.large_string())) + table = pa.table({"x": _nested("map value", _nested("struct", values))}) + db = DeltaTableDatabase(tmp_path) + for rid in (b"1", b"2"): + db.add_record(PATH, rid, table) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert stored is not None + expected = table if rid == b"1" else pa.concat_tables([table, table]) + assert stored.select(["x"]).equals(expected, check_metadata=True) diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index a37606b8e..4344214b1 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 in ("top", "struct")) ] 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 in ("top", "struct")) ] @@ -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") @@ -560,59 +498,46 @@ def _readable_type() -> Any: return ext_class -def _annotated_nested(meta: bytes, depth: str, ids: list[bytes]) -> pa.Table: +def _annotated_struct(meta: bytes, 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 - ) - 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)]), + return _struct_of( + field, pa.array([i.decode() for i in ids], pa.large_string()), ids ) -@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 +def test_delta_registered_struct_child_decides_by_raw_bytes( + tmp_path: Path, 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). + """Delta's log keeps the raw identifier bytes for an annotated struct child. + + A change from old to new is refused naming both identifiers. For identical + writes, the ordinary field check compares the given annotation against the + restored extension type and refuses the append. """ _readable_type() with _store("Delta", tmp_path) as store: store.db.add_records( PATH, - _annotated_nested(held, depth, [b"1"]), + _annotated_struct(held, [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" + PATH, _annotated_struct(given, [b"22"]), record_id_column="id" ) message = str(refused.value) - if depth == "struct" and held != given: + if 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 "x.v has other field metadata" in message assert store.stored().column("id").to_pylist() == [b"1"] @@ -739,34 +664,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 +686,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, @@ -1294,8 +1190,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,30 +1249,37 @@ 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]) @@ -1660,44 +1569,31 @@ 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, ids: list[bytes]) -> pa.Table: + """A map value whose struct child carries the given extension identifier.""" + field, leaf = _leaf(("itl1371.a", meta), "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 +def test_delta_struct_children_beneath_maps_are_compared( + tmp_path: Path, 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" + """The map value keeps no metadata, but its struct child's identifier is kept.""" with _store("Delta", tmp_path) as store: store.db.add_records( PATH, - _struct_beneath(shape, form, b"m", [b"1", b"22"]), + _map_of_structs(b"m", [b"1", b"22"]), record_id_column="id", flush=True, ) @@ -1705,11 +1601,11 @@ def test_delta_struct_children_beneath_lists_and_maps_are_compared( 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") + InputValidationError, match=r"x\.item\.v is of logical type" ): store.db.add_records( PATH, - _struct_beneath(shape, form, b"n", ids), + _map_of_structs(b"n", ids), record_id_column="id", skip_duplicates=skip, ) @@ -1948,7 +1844,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,46 +1852,38 @@ 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, + PATH, _map_of_structs(b"m", [b"1"]), record_id_column="id", flush=True + ) + incoming = _map_of_structs(b"n", [b"1", b"22"]) + pa.register_extension_type( + cast(Any, _failing_reader(TypeIdentityError, readable=b"n")()) ) - 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" ) 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: @@ -2154,113 +2042,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..16b23d4be 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,8 @@ 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. What a cell says: From 2430f1ee8aafe306a1599806f988a87ddc06eb6e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 19:38:32 -0800 Subject: [PATCH 2/4] fix(databases): refuse lossy nested extension layouts in Delta --- changelog.d/ITL-1372.md | 11 +- docs/dev/design_issues/ITL-1372-LI2.md | 18 +- docs/reference/database-types.md | 5 + src/orcapod/databases/delta_lake_databases.py | 78 +++- .../test_delta_nested_extension_types.py | 152 +++++++- .../test_logical_identity_appends.py | 352 ++++++------------ tests/test_databases/type_matrix.py | 5 + .../test_delta_refusals_in_jobs.py | 48 +++ 8 files changed, 403 insertions(+), 266 deletions(-) diff --git a/changelog.d/ITL-1372.md b/changelog.d/ITL-1372.md index 48224a0aa..794b5e816 100644 --- a/changelog.d/ITL-1372.md +++ b/changelog.d/ITL-1372.md @@ -2,14 +2,17 @@ - Delta now refuses raw Arrow columns with extension types in a list item or its descendants, directly in a map key or value, or within dictionary values. It - also refuses fields beneath a list or map that supply a logical type through + also refuses nested fields that supply a logical type through `ARROW:extension:*` metadata, including unregistered identifiers previously accepted. Registering those identifiers could make an identical second write - fail. Remove the annotations and store the affected values in their plain - Arrow storage form, or use an `InMemoryArrowDatabase` to keep the logical type. + fail. An actual nested extension field with its own metadata or in a column + that needs type recording is also refused. Use plain Arrow storage without + extension annotations, or use an `InMemoryArrowDatabase` to keep the logical type. ### Fixed - Delta names the columns with unsupported nested extension types before buffering rows. This prevents writes that lose the logical type and lists - of structs whose renamed item field prevents an identical append. + of structs whose renamed item field prevents an identical append. It also + prevents a sibling such as `uint16` from making a column with a nested extension + unreadable. diff --git a/docs/dev/design_issues/ITL-1372-LI2.md b/docs/dev/design_issues/ITL-1372-LI2.md index a750ba902..6f6637bdb 100644 --- a/docs/dev/design_issues/ITL-1372-LI2.md +++ b/docs/dev/design_issues/ITL-1372-LI2.md @@ -8,13 +8,17 @@ Delta could store an extension array in a list item, map key or value, or dictionary values as plain Arrow storage. A list of structs could keep the struct child's identifier but rename the list item, causing an identical -append to fail. With extension metadata on storage fields beneath lists or -maps, an identical append could fail once the extension was registered. +append to fail. With extension metadata on nested storage fields, an identical +append could fail once the extension was registered. An actual extension field +with ordinary metadata also refused an identical append. A sibling requiring +type recording could change type or make the stored column unreadable, since +the extension bypasses type recording for the whole column. **Fix:** Delta checks the incoming schema before buffering. It refuses Arrow extension types anywhere within list items or dictionary values, or directly -as map keys or values. It refuses storage fields carrying an extension -annotation anywhere beneath a list or map, regardless of registration. It -names the affected columns and points to plain storage or the in-memory -database. Arrow extension types on struct children, including under another -struct or a struct-valued map item, keep their existing write and read paths. +as map keys or values. It refuses nested storage fields carrying an extension +annotation regardless of registration, actual nested extension fields with +other metadata, and nested extension columns that require type recording. +It names the affected columns and points to plain storage or the in-memory +database. Supported struct children, including under another struct or a +struct-valued map item, keep their existing write and read paths. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index fc06ac8f9..96136be5c 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -15,6 +15,11 @@ representative, not every Arrow type: dictionary-encoded columns are refused by 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 accepts an Arrow extension array on a struct child when the column can round-trip +without recording its type and the extension field has no extra field metadata. +An extension field supplied as annotated storage is refused at nested positions so the +write verdict stays the same whether or not Arrow has registered the identifier. + What a cell says: - **kept**: read back exactly: the Arrow type with the name, nullability and metadata of diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 415877f57..0b8b2c506 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -28,6 +28,7 @@ ) from orcapod.databases.delta_arrow_types import ( ARROW_TYPE_KEY, + _has_extension_type, # pyright: ignore[reportPrivateUsage] first_column_out_of_stored_range, from_delta_layout, merged_type, @@ -1384,8 +1385,8 @@ def _unsupported_nested_extension( field: The column or nested field to check. extension_slot: An enclosing list item or dictionary value, where no Arrow extension type is supported, even through a struct. - annotation_slot: An enclosing list item or map key or value, where - a stored annotation can restore as a different field once registered. + annotation_slot: The nested position. A stored annotation at any nested + position can restore as a different field once registered. Returns: A description of the unsupported type and nesting, or ``None``. @@ -1394,6 +1395,8 @@ def _unsupported_nested_extension( if isinstance(arrow_type, pa.BaseExtensionType): if extension_slot is not None: return f"an Arrow extension type in {extension_slot}" + if annotation_slot is not None and field.metadata: + return f"an Arrow extension field with field metadata in {annotation_slot}" return None if annotation_slot is not None and b"ARROW:extension:name" in ( field.metadata or {} @@ -1436,13 +1439,80 @@ def _unsupported_nested_extension( reason = _unsupported_nested_extension( arrow_type.field(i), extension_slot=extension_slot, - annotation_slot=annotation_slot, + annotation_slot=annotation_slot or "a struct field", ) if reason is not None: return reason return None +_UNRECORDED_EXTENSION_SCALARS = frozenset( + { + pa.bool_(), + pa.int8(), + pa.int16(), + pa.int32(), + pa.int64(), + pa.float32(), + pa.float64(), + pa.string(), + pa.large_string(), + pa.binary(), + pa.large_binary(), + pa.date32(), + } +) + + +def _unrecorded_extension_part(arrow_type: pa.DataType) -> str | None: + """Describe a part of an extension column that needs Delta type recording. + + A Python extension disables recording for its whole column. Keep only the + scalar types verified to round-trip without a record, and struct fields and + ordinary maps over those types. Apply the same rule to extension storage. + + Args: + arrow_type: The composite column's type, or a type inside it. + + Returns: + The first unsupported part, or ``None`` for a supported layout. + """ + if isinstance(arrow_type, pa.BaseExtensionType): + storage = arrow_type.storage_type + if storage != arrow_utils.normalize_to_large_types(storage, keep_null=True): + return f"extension storage type {storage} that Delta would widen" + return _unrecorded_extension_part(storage) + if pa.types.is_struct(arrow_type): + fields = list(arrow_type) + elif pa.types.is_map(arrow_type): + fields = [arrow_type.key_field, arrow_type.item_field] + if arrow_type.keys_sorted or any(field.metadata for field in fields): + return "a map with sorted keys or key/value field metadata" + elif arrow_type in _UNRECORDED_EXTENSION_SCALARS: + return None + else: + return f"the Arrow type {arrow_type}" + for field in fields: + part = _unrecorded_extension_part(field.type) + if part is not None: + return part + return None + + +def _nested_extension_reason(field: "pa.Field[Any]") -> str | None: + """Describe the first unsupported logical type or layout in a column.""" + reason = _unsupported_nested_extension(field) + if reason is not None: + return reason + if not isinstance(field.type, pa.BaseExtensionType) and _has_extension_type( + field.type + ): + part = _unrecorded_extension_part(field.type) + if part is not None: + return f"a nested extension that disables type recording with {part}" + 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``. @@ -2412,7 +2482,7 @@ def require_storable(self, schema: pa.Schema) -> None: unsupported = [ (field, reason) for field in schema - if (reason := _unsupported_nested_extension(field)) is not None + if (reason := _nested_extension_reason(field)) is not None ] if unsupported: (field, reason), *others = unsupported diff --git a/tests/test_databases/test_delta_nested_extension_types.py b/tests/test_databases/test_delta_nested_extension_types.py index b0348857e..a9a335fa9 100644 --- a/tests/test_databases/test_delta_nested_extension_types.py +++ b/tests/test_databases/test_delta_nested_extension_types.py @@ -25,8 +25,12 @@ class _Unit(pa.ExtensionType): """A logical type over large strings.""" - def __init__(self) -> None: - super().__init__(pa.large_string(), "itl1372.unit") + def __init__( + self, name: str = "itl1372.unit", storage_type: pa.DataType | None = None + ) -> None: + super().__init__( + pa.large_string() if storage_type is None else storage_type, name + ) def __arrow_ext_serialize__(self) -> bytes: return b"{}" @@ -264,15 +268,153 @@ def test_delta_refuses_annotated_storage_under_list_or_map( assert errors[0] == errors[1] -def test_delta_keeps_extension_in_struct_under_map(tmp_path: Path, unit: Any) -> None: +@pytest.mark.parametrize("slot", ["map key", "map value"]) +def test_delta_keeps_extension_in_struct_under_map( + tmp_path: Path, unit: Any, slot: str +) -> None: """A map's struct child keeps its type and accepts identical appends.""" values = unit.wrap_array(pa.array(["a"], pa.large_string())) - table = pa.table({"x": _nested("map value", _nested("struct", values))}) - db = DeltaTableDatabase(tmp_path) + table = pa.table({"x": _nested(slot, _nested("struct", values))}) for rid in (b"1", b"2"): + db = DeltaTableDatabase(tmp_path) db.add_record(PATH, rid, table) db.flush() stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) assert stored is not None expected = table if rid == b"1" else pa.concat_tables([table, table]) assert stored.select(["x"]).equals(expected, check_metadata=True) + + +@pytest.mark.parametrize("container", ["struct", "map key", "map value"]) +@pytest.mark.parametrize("sibling", ["uint16", "high uint16", "list"]) +def test_delta_refuses_extension_struct_with_lossy_sibling( + tmp_path: Path, unit: Any, container: str, sibling: str +) -> None: + """An extension disables type recording for its entire column.""" + extension = unit.wrap_array(pa.array(["a"], pa.large_string())) + other = ( + pa.array([["s"]], pa.large_list(pa.large_string())) + if sibling == "list" + else pa.array([65535 if sibling == "high uint16" else 1], pa.uint16()) + ) + struct = pa.StructArray.from_arrays([extension, other], names=["v", "sibling"]) + values = struct if container == "struct" else _nested(container, struct) + db = DeltaTableDatabase(tmp_path) + table = pa.table({"measurement": values}) + errors = [] + for rid in (b"1", b"2"): + with pytest.raises(UnstorableColumnError, match="type recording") as refused: + db.add_record(PATH, rid, table) + assert refused.value.column == "measurement" + errors.append(str(refused.value)) + db.flush() + assert DeltaTableDatabase(tmp_path).get_all_records(PATH) is None + assert not (tmp_path / "t" / "_delta_log").exists() + assert errors[0] == errors[1] + + +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +@pytest.mark.parametrize("form", ["extension", "annotated"]) +def test_delta_refuses_struct_extension_with_field_metadata( + tmp_path: Path, unit: Any, registered: bool, form: str +) -> None: + """Both writes refuse even if Arrow has no registered reader for the identifier.""" + if not registered: + unit = _Unit("itl1372.unregistered") + storage = pa.array(["a"], pa.large_string()) + if form == "annotated": + metadata = { + b"ARROW:extension:name": unit.extension_name.encode(), + b"ARROW:extension:metadata": b"{}", + } + values = storage + else: + metadata = {b"units": b"metres"} + values = unit.wrap_array(storage) + field = pa.field("v", values.type, metadata=metadata) + table = pa.table( + {"measurement": pa.StructArray.from_arrays([values], fields=[field])} + ) + db = DeltaTableDatabase(tmp_path) + for rid in (b"1", b"2"): + with pytest.raises( + UnstorableColumnError, match="annotated storage|field metadata" + ) as refused: + db.add_record(PATH, rid, table) + assert refused.value.column == "measurement" + db.flush() + assert DeltaTableDatabase(tmp_path).get_all_records(PATH) is None + + +@pytest.mark.parametrize( + ("arrow_type", "value"), + [ + (pa.bool_(), True), + (pa.int8(), -8), + (pa.int16(), -16), + (pa.int32(), -32), + (pa.int64(), -64), + (pa.float32(), 1.25), + (pa.float64(), -1.25), + (pa.string(), "s"), + (pa.large_string(), "s"), + (pa.binary(), b"s"), + (pa.large_binary(), b"s"), + (pa.date32(), 1), + (pa.struct([("n", pa.int64())]), {"n": 1}), + (pa.map_(pa.large_string(), pa.int64()), [("n", 1)]), + ], + ids=str, +) +def test_delta_keeps_proven_sibling_layouts( + tmp_path: Path, unit: Any, arrow_type: pa.DataType, value: Any +) -> None: + """A supported sibling keeps its value and type through both writes.""" + from orcapod.utils.arrow_utils import normalize_to_large_types + + extension = unit.wrap_array(pa.array(["a"], pa.large_string())) + original = pa.array([value], arrow_type) + normalized = pa.array([value], normalize_to_large_types(arrow_type)) + tables = [ + pa.table( + { + "x": _nested( + "map value", + pa.StructArray.from_arrays( + [extension, sibling], names=["v", "sibling"] + ), + ) + } + ) + for sibling in (original, normalized) + ] + table, expected = tables + for count in (1, 2): + db = DeltaTableDatabase(tmp_path) + db.add_record(PATH, str(count).encode(), table, flush=True) + actual = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert actual is not None + assert actual.select(["x"]).equals( + pa.concat_tables([expected] * count), check_metadata=True + ) + + +@pytest.mark.parametrize( + ("storage_type", "value"), [(pa.string(), "a"), (pa.binary(), b"a")], ids=str +) +def test_delta_refuses_nested_extension_storage_that_would_be_widened( + tmp_path: Path, storage_type: pa.DataType, value: Any +) -> None: + """Delta normalizes small text and binary when comparing an identical append.""" + extension = _Unit("itl1372.small-storage", storage_type) + values = extension.wrap_array(pa.array([value], storage_type)) + table = pa.table({"measurement": _nested("map value", _nested("struct", values))}) + db = DeltaTableDatabase(tmp_path) + for rid in (b"1", b"2"): + with pytest.raises(UnstorableColumnError, match="type recording") as refused: + db.add_record(PATH, rid, table) + assert refused.value.column == "measurement" + 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 4344214b1..6ca555380 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -194,7 +194,10 @@ def _through(db: Any, via: str) -> Any: (kind, state, form, depth) for kind, state, form, depth in itertools.product(KINDS, STATES, FORMS, DEPTHS) if (kind == "in-memory" and state != "reopened") - or (kind == "Delta" and depth in ("top", "struct")) + or ( + kind == "Delta" + and (depth == "top" or (depth == "struct" and form == "extension")) + ) ] REFUSED_CASES = [ @@ -268,7 +271,11 @@ 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 kind == "in-memory" or (state == "pending" and depth in ("top", "struct")) + if kind == "in-memory" + or ( + state == "pending" + and (depth == "top" or (depth == "struct" and form == "extension")) + ) ] @@ -386,63 +393,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( @@ -453,96 +403,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 = extension.wrap_array(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_struct(meta: bytes, ids: list[bytes]) -> pa.Table: - field = pa.field( - "v", pa.large_string(), metadata={NAME: b"itl1371.readable", META: meta} +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 _struct_of( - field, pa.array([i.decode() for i in ids], pa.large_string()), ids + _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( - ("held", "given"), [(b"old", b"new"), (b"old", b"old"), (b"new", b"new")] -) -def test_delta_registered_struct_child_decides_by_raw_bytes( - tmp_path: Path, held: bytes, given: bytes -) -> None: - """Delta's log keeps the raw identifier bytes for an annotated struct child. - - A change from old to new is refused naming both identifiers. For identical - writes, the ordinary field check compares the given annotation against the - restored extension type and refuses the append. - """ - _readable_type() - with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, - _annotated_struct(held, [b"1"]), - record_id_column="id", - flush=True, - ) - store.reopen() - with pytest.raises(InputValidationError) as refused: - store.db.add_records( - PATH, _annotated_struct(given, [b"22"]), record_id_column="id" + different = _wrapped(b"n", ["2"]) + 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 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 "x.v 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: @@ -718,45 +659,6 @@ def test_delta_annotated_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", @@ -1099,7 +1001,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", "struct", [b"1"]), record_id_column="id", flush=True, ) @@ -1115,7 +1017,7 @@ def undecodable(_: Any) -> Any: ): store.db.add_records( PATH, - _rows(("itl1371.b", b"m"), "annotated", "struct", [b"22"]), + _rows(("itl1371.b", b"m"), "extension", "struct", [b"22"]), record_id_column="id", ) @@ -1286,64 +1188,24 @@ def test_delta_extension_after_a_legacy_dictionary_first_write( 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(("itl1371.b", b"n"), "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 'itl1371.b;6e'" 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"]) @@ -1639,16 +1501,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"]), @@ -1890,25 +1749,26 @@ def test_delta_identity_beneath_map_comes_before_an_undecodable_child( 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), diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 16b23d4be..d8cc2fe06 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1062,6 +1062,11 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: 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 accepts an Arrow extension array on a struct child when the column can round-trip +without recording its type and the extension field has no extra field metadata. +An extension field supplied as annotated storage is refused at nested positions so the +write verdict stays the same whether or not Arrow has registered the identifier. + What a cell says: - **kept**: read back exactly: the Arrow type with the name, nullability and metadata of diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py index 6387cb5bb..f942afa77 100644 --- a/tests/test_pipeline/test_delta_refusals_in_jobs.py +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -120,3 +120,51 @@ 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 "annotated storage in a list item" in cause.reason + database.flush() + assert database.list_table_paths() == [] From 1cfd0d85a3abee962d29ed51eb34610dac08dd40 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 20:32:47 -0800 Subject: [PATCH 3/4] fix(databases): require whole-column logical types in Delta --- changelog.d/ITL-1372.md | 25 +- docs/dev/design_issues/ITL-1372-LI2.md | 26 +- docs/reference/database-types.md | 13 +- src/orcapod/databases/delta_arrow_types.py | 8 +- src/orcapod/databases/delta_lake_databases.py | 217 ++---- .../test_delta_nested_extension_types.py | 665 +++++++++--------- .../test_logical_identity_appends.py | 104 +-- tests/test_databases/type_matrix.py | 11 +- .../test_delta_refusals_in_jobs.py | 107 ++- 9 files changed, 567 insertions(+), 609 deletions(-) diff --git a/changelog.d/ITL-1372.md b/changelog.d/ITL-1372.md index 794b5e816..23e159051 100644 --- a/changelog.d/ITL-1372.md +++ b/changelog.d/ITL-1372.md @@ -1,18 +1,17 @@ ### Breaking changes and migration -- Delta now refuses raw Arrow columns with extension types in a list item or its - descendants, directly in a map key or value, or within dictionary values. It - also refuses nested fields that supply a logical type through - `ARROW:extension:*` metadata, including unregistered identifiers previously - accepted. Registering those identifiers could make an identical second write - fail. An actual nested extension field with its own metadata or in a column - that needs type recording is also refused. Use plain Arrow storage without - extension annotations, or use an `InMemoryArrowDatabase` to keep the logical type. +- 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 the columns with unsupported nested extension types before - buffering rows. This prevents writes that lose the logical type and lists - of structs whose renamed item field prevents an identical append. It also - prevents a sibling such as `uint16` from making a column with a nested extension - unreadable. +- 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 index 6f6637bdb..fb702b1ef 100644 --- a/docs/dev/design_issues/ITL-1372-LI2.md +++ b/docs/dev/design_issues/ITL-1372-LI2.md @@ -5,20 +5,14 @@ **Severity:** critical **Issue:** ITL-1372 -Delta could store an extension array in a list item, map key or value, or -dictionary values as plain Arrow storage. A list of structs could keep the -struct child's identifier but rename the list item, causing an identical -append to fail. With extension metadata on nested storage fields, an identical -append could fail once the extension was registered. An actual extension field -with ordinary metadata also refused an identical append. A sibling requiring -type recording could change type or make the stored column unreadable, since -the extension bypasses type recording for the whole column. +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 checks the incoming schema before buffering. It refuses Arrow -extension types anywhere within list items or dictionary values, or directly -as map keys or values. It refuses nested storage fields carrying an extension -annotation regardless of registration, actual nested extension fields with -other metadata, and nested extension columns that require type recording. -It names the affected columns and points to plain storage or the in-memory -database. Supported struct children, including under another struct or a -struct-valued map item, keep their existing write and read paths. +**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 96136be5c..acba19b4c 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -15,10 +15,13 @@ representative, not every Arrow type: dictionary-encoded columns are refused by 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 accepts an Arrow extension array on a struct child when the column can round-trip -without recording its type and the extension field has no extra field metadata. -An extension field supplied as annotated storage is refused at nested positions so the -write verdict stays the same whether or not Arrow has registered the identifier. +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: @@ -264,7 +267,7 @@ fields is not covered: a struct whose fields are in another order is another typ | Type | in-memory | Delta | SQLite | PostgreSQL | |---|---|---|---|---| -| `extension type in struct child` | kept | kept | refused | refused | +| `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 | diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index 1a632d6a7..18233139c 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -42,10 +42,10 @@ 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 containing a Python Arrow -extension type bypasses type recording. Supported extension fields are restored from -their extension metadata. ``DeltaTableDatabase.require_storable`` refuses nested -extension types and annotations that would be lost or prevent an identical append -(ITL-1372). +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 0b8b2c506..d68082950 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -8,7 +8,7 @@ import time 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 @@ -28,7 +28,6 @@ ) from orcapod.databases.delta_arrow_types import ( ARROW_TYPE_KEY, - _has_extension_type, # pyright: ignore[reportPrivateUsage] first_column_out_of_stored_range, from_delta_layout, merged_type, @@ -1373,143 +1372,53 @@ def _holds_null_type(arrow_type: pa.DataType) -> bool: ) -def _unsupported_nested_extension( - field: "pa.Field[Any]", - *, - extension_slot: str | None = None, - annotation_slot: str | None = None, +def _nested_logical_type_path( + field: "pa.Field[Any]", *, top_level: bool = False ) -> str | None: - """Describe a nested logical type Delta cannot keep (ITL-1372). + """Find the first nested logical type, without consulting Arrow's registry. Args: - field: The column or nested field to check. - extension_slot: An enclosing list item or dictionary value, where no - Arrow extension type is supported, even through a struct. - annotation_slot: The nested position. A stored annotation at any nested - position can restore as a different field once registered. + field: A column or a field within its type. + top_level: Whether this field may itself carry a logical type. Returns: - A description of the unsupported type and nesting, or ``None``. + A relative path to the first unsupported field, or ``None``. """ arrow_type = field.type - if isinstance(arrow_type, pa.BaseExtensionType): - if extension_slot is not None: - return f"an Arrow extension type in {extension_slot}" - if annotation_slot is not None and field.metadata: - return f"an Arrow extension field with field metadata in {annotation_slot}" - return None - if annotation_slot is not None and b"ARROW:extension:name" in ( - field.metadata or {} - ): - return f"an extension type supplied as annotated storage in {annotation_slot}" + annotation = any( + key.startswith(b"ARROW:extension:") for key in (field.metadata or {}) + ) + 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 ( + 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) ): - return _unsupported_nested_extension( - arrow_type.value_field, - extension_slot=extension_slot or "a list item", - annotation_slot=annotation_slot or "a list item", - ) - if t.is_dictionary(arrow_type): - return _unsupported_nested_extension( - field.with_type(arrow_type.value_type), - extension_slot=extension_slot or "dictionary values", - annotation_slot=annotation_slot, - ) - if t.is_map(arrow_type): - for child, slot in ( - (arrow_type.key_field, "a map key"), - (arrow_type.item_field, "a map value"), - ): - if isinstance(child.type, pa.BaseExtensionType): - return f"an Arrow extension type in {extension_slot or slot}" - reason = _unsupported_nested_extension( - child, - extension_slot=extension_slot, - annotation_slot=annotation_slot or slot, - ) - if reason is not None: - return reason - return None - for i in range(arrow_type.num_fields): - reason = _unsupported_nested_extension( - arrow_type.field(i), - extension_slot=extension_slot, - annotation_slot=annotation_slot or "a struct field", - ) - if reason is not None: - return reason - return None - - -_UNRECORDED_EXTENSION_SCALARS = frozenset( - { - pa.bool_(), - pa.int8(), - pa.int16(), - pa.int32(), - pa.int64(), - pa.float32(), - pa.float64(), - pa.string(), - pa.large_string(), - pa.binary(), - pa.large_binary(), - pa.date32(), - } -) - - -def _unrecorded_extension_part(arrow_type: pa.DataType) -> str | None: - """Describe a part of an extension column that needs Delta type recording. - - A Python extension disables recording for its whole column. Keep only the - scalar types verified to round-trip without a record, and struct fields and - ordinary maps over those types. Apply the same rule to extension storage. - - Args: - arrow_type: The composite column's type, or a type inside it. - - Returns: - The first unsupported part, or ``None`` for a supported layout. - """ - if isinstance(arrow_type, pa.BaseExtensionType): - storage = arrow_type.storage_type - if storage != arrow_utils.normalize_to_large_types(storage, keep_null=True): - return f"extension storage type {storage} that Delta would widen" - return _unrecorded_extension_part(storage) - if pa.types.is_struct(arrow_type): - fields = list(arrow_type) - elif pa.types.is_map(arrow_type): - fields = [arrow_type.key_field, arrow_type.item_field] - if arrow_type.keys_sorted or any(field.metadata for field in fields): - return "a map with sorted keys or key/value field metadata" - elif arrow_type in _UNRECORDED_EXTENSION_SCALARS: - return None + children = (("[]", arrow_type.value_field),) else: - return f"the Arrow type {arrow_type}" - for field in fields: - part = _unrecorded_extension_part(field.type) - if part is not None: - return part - return None - - -def _nested_extension_reason(field: "pa.Field[Any]") -> str | None: - """Describe the first unsupported logical type or layout in a column.""" - reason = _unsupported_nested_extension(field) - if reason is not None: - return reason - if not isinstance(field.type, pa.BaseExtensionType) and _has_extension_type( - field.type - ): - part = _unrecorded_extension_part(field.type) - if part is not None: - return f"a nested extension that disables type recording with {part}" + 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 @@ -2479,29 +2388,7 @@ def require_storable(self, schema: pa.Schema) -> None: arrow_type=schema.field(position).type, reason=_case_reason(*clash), ) - unsupported = [ - (field, reason) - for field in schema - if (reason := _nested_extension_reason(field)) is not None - ] - if unsupported: - (field, reason), *others = unsupported - details = [f"Delta cannot reliably round-trip {reason}"] - details.extend( - f"Column {other.name!r} of Arrow type {other.type} has {why}" - for other, why in others - ) - details.append( - "Store the affected columns in their storage form" - if others - else "Store the column in its storage form" - ) - raise UnstorableColumnError( - database_kind=type(self).__name__, - column=field.name, - arrow_type=field.type, - reason=". ".join(details), - ) + self._require_top_level_logical_types(schema) for field in schema: reason = delta_unstorable_reason(field) if reason is not None: @@ -2512,6 +2399,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: @@ -2916,6 +2828,15 @@ def add_records( if records.num_rows == 0: return + # A chunk can carry nested field metadata different from the table schema. + # Check those original types before any casts normalize them to the schema. + 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 + if not chunk.type.equals(field.type, check_metadata=True) + ) + # 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 index a9a335fa9..c4b82d23e 100644 --- a/tests/test_databases/test_delta_nested_extension_types.py +++ b/tests/test_databases/test_delta_nested_extension_types.py @@ -1,420 +1,381 @@ -"""Delta keeps or refuses nested Arrow extension types before queuing (ITL-1372).""" +"""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 pydantic import BaseModel -from orcapod.databases import ( - DeltaTableDatabase, - ExtensionAwareDatabase, - InMemoryArrowDatabase, -) +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 logical type over large strings.""" + """A small Arrow extension with a caller-supplied storage type.""" - def __init__( - self, name: str = "itl1372.unit", storage_type: pa.DataType | None = None - ) -> None: - super().__init__( - pa.large_string() if storage_type is None else storage_type, name - ) + def __init__(self, name: str, storage: pa.DataType) -> None: + super().__init__(storage, name) def __arrow_ext_serialize__(self) -> bytes: - return b"{}" + return self.extension_name.encode() @classmethod - def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> _Unit: - return cls() + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> _Unit: + return cls(serialized.decode(), storage_type) -@pytest.fixture -def unit() -> Any: - """An Arrow extension type registered for the lifetime of one test.""" - extension = _Unit() - pa.register_extension_type(cast(Any, extension)) +@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 extension + yield finally: - pa.unregister_extension_type(extension.extension_name) - - -def _nested(kind: str, values: Any) -> Any: - """Build one occurrence of `values` per row, nested in the given container.""" - offsets = range(len(values) + 1) - if kind == "list": - return pa.ListArray.from_arrays(pa.array(offsets, pa.int32()), values) - if kind == "large list": - return pa.LargeListArray.from_arrays(pa.array(offsets, pa.int64()), values) - if kind == "fixed-size list": - return pa.FixedSizeListArray.from_arrays(values, 1) - if kind == "list of structs": - return _nested("large list", _nested("struct", values)) - if kind == "struct of lists": - return _nested("struct", _nested("large list", values)) - if kind == "struct of dictionaries": - return _nested("struct", _nested("dictionary", values)) - if kind == "dictionary of structs": - return _nested("dictionary", _nested("struct", values)) - if kind == "struct of structs": - return _nested("struct", _nested("struct", values)) - if kind == "struct": - return pa.StructArray.from_arrays([values], names=["v"]) - if kind == "dictionary": - return pa.DictionaryArray.from_arrays( - pa.array(range(len(values)), pa.int32()), values + 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")) ) - ordinary = pa.array([f"k{i}" for i in range(len(values))], pa.large_string()) - from_arrays: Any = pa.MapArray.from_arrays - if kind == "map key": - return from_arrays(pa.array(offsets, pa.int32()), values, ordinary) - assert kind == "map value" - return from_arrays(pa.array(offsets, pa.int32()), ordinary, values) - - -REFUSED = [ - ("list", "list item"), - ("large list", "list item"), - ("fixed-size list", "list item"), - ("map key", "map key"), - ("map value", "map value"), - ("dictionary", "dictionary values"), - ("list of structs", "list item"), - ("struct of lists", "list item"), - ("struct of dictionaries", "dictionary values"), - ("dictionary of structs", "dictionary values"), -] - - -@pytest.mark.parametrize(("kind", "why"), REFUSED) -@pytest.mark.parametrize("wrap", [False, True], ids=["direct", "wrapper"]) -def test_nested_extension_is_refused_before_queueing( - tmp_path: Path, unit: Any, kind: str, why: str, wrap: bool + 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: - """Both write entry points reject the same column before it reaches the queue.""" - delta = DeltaTableDatabase(tmp_path) - db = ( - ExtensionAwareDatabase( + """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()) ) - if wrap - else delta + 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 ) - values = unit.wrap_array(pa.array(["a"], pa.large_string())) - table = pa.table({"measurement": _nested(kind, values)}) - rows = table.append_column("id", pa.array([b"1"], pa.large_binary())) - with pytest.raises(UnstorableColumnError, match=why) as first: - db.add_records(PATH, rows, record_id_column="id") - db.flush() - assert db.get_all_records(PATH) is None - assert not (tmp_path / "t" / "_delta_log").exists() - - with pytest.raises(UnstorableColumnError, match=why) as second: - db.add_record(PATH, b"2", table) - assert str(first.value) == str(second.value) - assert first.value.column == "measurement" - assert first.value.arrow_type == table.schema.field("measurement").type - message = str(first.value) - assert "storage form" in message - assert "InMemoryArrowDatabase" in message - assert "docs/reference/database-types.md" in message - db.flush() - assert db.get_all_records(PATH) is None - assert not (tmp_path / "t" / "_delta_log").exists() + _, 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, unit: Any, order: tuple[str, str] + tmp_path: Path, order: tuple[str, str] ) -> None: - """All columns with unsupported extensions are named in either input order.""" - values = unit.wrap_array(pa.array(["a"], pa.large_string())) + """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": _nested("list", values), - "units": _nested("map value", values), + "samples": _nest("list", field, values)[1], + "units": _nest("map value", field, values)[1], } - table = pa.table({name: columns[name] for name in order}) - rows = table.append_column("id", pa.array([b"1"], pa.large_binary())) + 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 refused: - db.add_records(PATH, rows, record_id_column="id") - message = str(refused.value) - assert "'samples'" in message and "list item" in message - assert "'units'" in message and "map value" in message + 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("kind", [*dict(REFUSED), "struct", "struct of structs"]) -def test_memory_keeps_nested_extensions(unit: Any, kind: str) -> None: - """In-memory preserves both writes, including the extension type.""" - values = unit.wrap_array(pa.array(["a"], pa.large_string())) - table = pa.table({"x": _nested(kind, values)}) - db = InMemoryArrowDatabase() - for rid in (b"1", b"2"): - db.add_record(PATH, rid, table) - db.flush() - stored = db.get_all_records(PATH) - assert stored is not None - assert stored.select(["x"]).equals( - pa.concat_tables([table, table]), check_metadata=True - ) - - -@pytest.mark.parametrize("kind", ["struct", "struct of structs"]) -def test_delta_keeps_extension_in_struct(tmp_path: Path, unit: Any, kind: str) -> None: - """Struct children keep their type and an identical second append succeeds.""" - values = unit.wrap_array(pa.array(["a"], pa.large_string())) - table = pa.table({"x": _nested(kind, values)}) - db = DeltaTableDatabase(tmp_path) - for rid in (b"1", b"2"): - db.add_record(PATH, rid, table) - db.flush() - stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) - assert stored is not None - expected = table if rid == b"1" else pa.concat_tables([table, table]) - assert stored.select(["x"]).equals(expected, check_metadata=True) - - code = """ -import sys - -import pyarrow as pa - -from orcapod.databases import DeltaTableDatabase - -table = DeltaTableDatabase(sys.argv[1]).get_all_records(("t",)) -child = table.schema.field("x").type.field("v") -if sys.argv[2] == "struct of structs": - child = child.type.field("v") -assert child.type == pa.large_string(), child -assert child.metadata == { - b"ARROW:extension:name": b"itl1372.unit", - b"ARROW:extension:metadata": b"{}", -}, child.metadata -""" - subprocess.run([sys.executable, "-c", code, str(tmp_path), kind], check=True) - - -def test_delta_keeps_ordinary_struct_child_metadata_on_append(tmp_path: Path) -> None: - """An identical second write preserves ordinary metadata on a struct child.""" - field = pa.field("v", pa.large_string(), metadata={b"unit": b"m"}) - array = pa.StructArray.from_arrays([pa.array(["a"], field.type)], fields=[field]) - table = pa.table({"x": array}) - db = DeltaTableDatabase(tmp_path) - for rid in (b"1", b"2"): - db.add_record(PATH, rid, table) - db.flush() - stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) - assert stored is not None - assert stored.select(["x"]).equals( - pa.concat_tables([table, table]), check_metadata=True - ) - - +@pytest.mark.parametrize("annotated", [False, True], ids=["actual", "annotated"]) @pytest.mark.parametrize( "registered", [False, True], ids=["unregistered", "registered"] ) @pytest.mark.parametrize( - "kind", ["list", "map value", "list of structs", "map of structs"] + "metadata", [False, True], ids=["no metadata", "ordinary metadata"] ) -def test_delta_refuses_annotated_storage_under_list_or_map( - tmp_path: Path, unit: Any, kind: str, registered: bool +def test_delta_keeps_top_level_scalar_extension( + tmp_path: Path, annotated: bool, registered: bool, metadata: bool ) -> None: - """The refusal is independent of registry state and applies through a struct.""" - metadata = { - b"ARROW:extension:name": b"itl1372.unit" if registered else b"itl1372.missing", - b"ARROW:extension:metadata": b"{}", - } - field = pa.field("v", pa.large_string(), metadata=metadata) - values: Any = pa.array(["a"], field.type) - if kind.endswith("of structs"): - values = pa.StructArray.from_arrays([values], fields=[field]) - field = pa.field("v", values.type) - if kind.startswith("list"): - array = pa.LargeListArray.from_arrays( - pa.array([0, 1], pa.int64()), - values, - type=pa.large_list(field.with_name("item")), + """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)]) ) - else: - from_arrays: Any = pa.MapArray.from_arrays - map_type = pa.map_(pa.large_string(), field.with_name("value")) # pyright: ignore[reportArgumentType] - array = from_arrays( - pa.array([0, 1], pa.int32()), - pa.array(["key"], pa.large_string()), - values, - type=map_type, - ) - db = DeltaTableDatabase(tmp_path) - errors = [] - for rid in (b"1", b"2"): - with pytest.raises(UnstorableColumnError, match="annotated storage") as refused: - db.add_record(PATH, rid, pa.table({"measurement": array})) - errors.append(str(refused.value)) - db.flush() - assert db.get_all_records(PATH) is None - assert errors[0] == errors[1] - - -@pytest.mark.parametrize("slot", ["map key", "map value"]) -def test_delta_keeps_extension_in_struct_under_map( - tmp_path: Path, unit: Any, slot: str -) -> None: - """A map's struct child keeps its type and accepts identical appends.""" - values = unit.wrap_array(pa.array(["a"], pa.large_string())) - table = pa.table({"x": _nested(slot, _nested("struct", values))}) - for rid in (b"1", b"2"): - db = DeltaTableDatabase(tmp_path) - db.add_record(PATH, rid, table) - db.flush() - stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) - assert stored is not None - expected = table if rid == b"1" else pa.concat_tables([table, table]) - assert stored.select(["x"]).equals(expected, check_metadata=True) - - -@pytest.mark.parametrize("container", ["struct", "map key", "map value"]) -@pytest.mark.parametrize("sibling", ["uint16", "high uint16", "list"]) -def test_delta_refuses_extension_struct_with_lossy_sibling( - tmp_path: Path, unit: Any, container: str, sibling: str -) -> None: - """An extension disables type recording for its entire column.""" - extension = unit.wrap_array(pa.array(["a"], pa.large_string())) - other = ( - pa.array([["s"]], pa.large_list(pa.large_string())) - if sibling == "list" - else pa.array([65535 if sibling == "high uint16" else 1], pa.uint16()) - ) - struct = pa.StructArray.from_arrays([extension, other], names=["v", "sibling"]) - values = struct if container == "struct" else _nested(container, struct) - db = DeltaTableDatabase(tmp_path) - table = pa.table({"measurement": values}) - errors = [] - for rid in (b"1", b"2"): - with pytest.raises(UnstorableColumnError, match="type recording") as refused: - db.add_record(PATH, rid, table) - assert refused.value.column == "measurement" - errors.append(str(refused.value)) - db.flush() - assert DeltaTableDatabase(tmp_path).get_all_records(PATH) is None - assert not (tmp_path / "t" / "_delta_log").exists() - assert errors[0] == errors[1] + 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 -@pytest.mark.parametrize( - "registered", [False, True], ids=["unregistered", "registered"] -) -@pytest.mark.parametrize("form", ["extension", "annotated"]) -def test_delta_refuses_struct_extension_with_field_metadata( - tmp_path: Path, unit: Any, registered: bool, form: str -) -> None: - """Both writes refuse even if Arrow has no registered reader for the identifier.""" - if not registered: - unit = _Unit("itl1372.unregistered") - storage = pa.array(["a"], pa.large_string()) - if form == "annotated": - metadata = { - b"ARROW:extension:name": unit.extension_name.encode(), - b"ARROW:extension:metadata": b"{}", - } - values = storage - else: - metadata = {b"units": b"metres"} - values = unit.wrap_array(storage) - field = pa.field("v", values.type, metadata=metadata) - table = pa.table( - {"measurement": pa.StructArray.from_arrays([values], fields=[field])} - ) - db = DeltaTableDatabase(tmp_path) - for rid in (b"1", b"2"): - with pytest.raises( - UnstorableColumnError, match="annotated storage|field metadata" - ) as refused: - db.add_record(PATH, rid, table) - assert refused.value.column == "measurement" - db.flush() - assert DeltaTableDatabase(tmp_path).get_all_records(PATH) is None + +class _WithUUID(BaseModel): + """A Pydantic model with a logical field.""" + + value: UUID @pytest.mark.parametrize( - ("arrow_type", "value"), + ("python_type", "value"), [ - (pa.bool_(), True), - (pa.int8(), -8), - (pa.int16(), -16), - (pa.int32(), -32), - (pa.int64(), -64), - (pa.float32(), 1.25), - (pa.float64(), -1.25), - (pa.string(), "s"), - (pa.large_string(), "s"), - (pa.binary(), b"s"), - (pa.large_binary(), b"s"), - (pa.date32(), 1), - (pa.struct([("n", pa.int64())]), {"n": 1}), - (pa.map_(pa.large_string(), pa.int64()), [("n", 1)]), + (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=str, + ids=["scalar", "list", "set", "dataclass", "pydantic", "list of dataclasses"], ) -def test_delta_keeps_proven_sibling_layouts( - tmp_path: Path, unit: Any, arrow_type: pa.DataType, value: Any +def test_delta_keeps_orcapod_logical_columns( + tmp_path: Path, python_type: Any, value: Any ) -> None: - """A supported sibling keeps its value and type through both writes.""" - from orcapod.utils.arrow_utils import normalize_to_large_types - - extension = unit.wrap_array(pa.array(["a"], pa.large_string())) - original = pa.array([value], arrow_type) - normalized = pa.array([value], normalize_to_large_types(arrow_type)) - tables = [ - pa.table( - { - "x": _nested( - "map value", - pa.StructArray.from_arrays( - [extension, sibling], names=["v", "sibling"] - ), - ) - } - ) - for sibling in (original, normalized) - ] - table, expected = tables + """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): - db = DeltaTableDatabase(tmp_path) - db.add_record(PATH, str(count).encode(), table, flush=True) - actual = DeltaTableDatabase(tmp_path).get_all_records(PATH) - assert actual is not None - assert actual.select(["x"]).equals( - pa.concat_tables([expected] * count), check_metadata=True + 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 ) -@pytest.mark.parametrize( - ("storage_type", "value"), [(pa.string(), "a"), (pa.binary(), b"a")], ids=str -) -def test_delta_refuses_nested_extension_storage_that_would_be_widened( - tmp_path: Path, storage_type: pa.DataType, value: Any -) -> None: - """Delta normalizes small text and binary when comparing an identical append.""" - extension = _Unit("itl1372.small-storage", storage_type) - values = extension.wrap_array(pa.array([value], storage_type)) - table = pa.table({"measurement": _nested("map value", _nested("struct", values))}) +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 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) - for rid in (b"1", b"2"): - with pytest.raises(UnstorableColumnError, match="type recording") as refused: - db.add_record(PATH, rid, table) - assert refused.value.column == "measurement" + 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 6ca555380..fd28ee20b 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -194,10 +194,7 @@ def _through(db: Any, via: str) -> Any: (kind, state, form, depth) for kind, state, form, depth in itertools.product(KINDS, STATES, FORMS, DEPTHS) if (kind == "in-memory" and state != "reopened") - or ( - kind == "Delta" - and (depth == "top" or (depth == "struct" and form == "extension")) - ) + or (kind == "Delta" and depth == "top") ] REFUSED_CASES = [ @@ -271,11 +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 kind == "in-memory" - or ( - state == "pending" - and (depth == "top" or (depth == "struct" and form == "extension")) - ) + if kind == "in-memory" or (state == "pending" and depth == "top") ] @@ -426,7 +419,7 @@ def test_delta_reads_an_older_annotated_struct_child(tmp_path: Path) -> None: pa.register_extension_type(extension) try: db = DeltaTableDatabase(tmp_path) - new = extension.wrap_array(pa.array(["2"], pa.large_string())) + new = pa.array(["2"], pa.large_string()) with pytest.raises( InputValidationError, match="the stored column's 'itl1371.readable;6f6c64'" ): @@ -470,7 +463,7 @@ def test_delta_legacy_record_keeps_dictionary_child_identifier(tmp_path: Path) - assert identity_node(child).identifier == (b"itl1371.a", b"m") assert stored.column("x").to_pylist() == [{"v": "1", "u": 65535}] - different = _wrapped(b"n", ["2"]) + 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'" @@ -660,23 +653,16 @@ def test_delta_annotated_dictionary_of_the_stored_type_is_accepted( @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) @@ -1001,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, "extension", "struct", [b"1"]), + _rows(HELD, "extension", "top", [b"1"]), record_id_column="id", flush=True, ) @@ -1013,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"), "extension", "struct", [b"22"]), + _rows(("itl1371.b", b"m"), "extension", "top", [b"22"]), record_id_column="id", ) @@ -1191,7 +1177,7 @@ def test_delta_identity_is_refused_before_an_undecodable_stored_type( """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(("itl1371.b", b"n"), "extension", "struct", [b"2"]) + incoming = _rows(None, "extension", "struct", [b"2"]) pa.register_extension_type(cast(Any, _failing_reader(ValueError)())) try: db = DeltaTableDatabase(tmp_path) @@ -1200,7 +1186,7 @@ def test_delta_identity_is_refused_before_an_undecodable_stored_type( PATH, incoming, record_id_column="id", skip_duplicates=skip_duplicates ) message = str(refused.value) - assert "x.v is of logical type 'itl1371.b;6e'" in message + 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") @@ -1431,9 +1417,10 @@ def test_duplicate_only_append_of_the_same_identifier_is_a_no_op( # --------------------------------------------------------------------------- -def _map_of_structs(meta: bytes, ids: list[bytes]) -> pa.Table: +def _map_of_structs(meta: bytes | None, ids: list[bytes]) -> pa.Table: """A map value whose struct child carries the given extension identifier.""" - field, leaf = _leaf(("itl1371.a", meta), "extension", [i.decode() for i in ids]) + 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) keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) @@ -1447,35 +1434,24 @@ def _map_of_structs(meta: bytes, ids: list[bytes]) -> pa.Table: ) -@pytest.mark.parametrize("state", ["committed", "reopened"]) -def test_delta_struct_children_beneath_maps_are_compared( - tmp_path: Path, state: str -) -> None: - """The map value keeps no metadata, but its struct child's identifier is kept.""" - with _store("Delta", tmp_path) as store: - store.db.add_records( - PATH, - _map_of_structs(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=r"x\.item\.v is of logical type" - ): - store.db.add_records( - PATH, - _map_of_structs(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: @@ -1730,16 +1706,12 @@ def test_delta_identity_beneath_map_comes_before_an_undecodable_child( from orcapod.errors import TypeIdentityError root = tmp_path / "delta" - DeltaTableDatabase(root).add_records( - PATH, _map_of_structs(b"m", [b"1"]), record_id_column="id", flush=True - ) - incoming = _map_of_structs(b"n", [b"1", b"22"]) - pa.register_extension_type( - cast(Any, _failing_reader(TypeIdentityError, readable=b"n")()) - ) + _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: with pytest.raises( - InputValidationError, match=r"x\.item\.v is of logical type" + InputValidationError, match=r"x\.item\.v is of logical type no logical type" ) as refused: DeltaTableDatabase(root).add_records( PATH, incoming, record_id_column="id", skip_duplicates=skip_duplicates diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index d8cc2fe06..ef47aba82 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1062,10 +1062,13 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: 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 accepts an Arrow extension array on a struct child when the column can round-trip -without recording its type and the extension field has no extra field metadata. -An extension field supplied as annotated storage is refused at nested positions so the -write verdict stays the same whether or not Arrow has registered the identifier. +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 f942afa77..311ebd3bc 100644 --- a/tests/test_pipeline/test_delta_refusals_in_jobs.py +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -165,6 +165,111 @@ def test_annotated_list_reaches_delta_operator_log( cause = error.value.__cause__ assert isinstance(cause, UnstorableColumnError) assert cause.column == "extra" - assert "annotated storage in a list item" in cause.reason + 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) From d7e258ef274099525cd4766c7e7f242eab0510d1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 23:52:16 -0800 Subject: [PATCH 4/4] fix(databases): inspect every Delta chunk for logical annotations --- src/orcapod/databases/delta_lake_databases.py | 10 +- .../test_delta_nested_extension_types.py | 131 ++++++++++++++++++ 2 files changed, 135 insertions(+), 6 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index d68082950..4efeb628b 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1385,9 +1385,8 @@ def _nested_logical_type_path( A relative path to the first unsupported field, or ``None``. """ arrow_type = field.type - annotation = any( - key.startswith(b"ARROW:extension:") for key in (field.metadata or {}) - ) + 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 "" @@ -2828,13 +2827,12 @@ def add_records( if records.num_rows == 0: return - # A chunk can carry nested field metadata different from the table schema. - # Check those original types before any casts normalize them to the schema. + # 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 - if not chunk.type.equals(field.type, check_metadata=True) ) # Convert view types up front so the whole write path (group_by dedup, diff --git a/tests/test_databases/test_delta_nested_extension_types.py b/tests/test_databases/test_delta_nested_extension_types.py index c4b82d23e..48f705389 100644 --- a/tests/test_databases/test_delta_nested_extension_types.py +++ b/tests/test_databases/test_delta_nested_extension_types.py @@ -13,6 +13,7 @@ import pyarrow as pa import pytest +from deltalake import DeltaTable from pydantic import BaseModel from orcapod import dataclass @@ -369,6 +370,136 @@ def test_delta_refuses_annotation_in_later_chunk(tmp_path: Path) -> None: 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())