From 7fe0970e4d4c0d01cae499067b52d5006ea1bfe5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:33:45 -0800 Subject: [PATCH 01/14] fix(databases): refuse an append of another logical type identifier (ITL-1371) An appended column with the stored or pending column's storage type but another logical type identifier (another extension name, other extension metadata, or a logical type against none) was accepted in several cases and read back as the stored type: a Delta column in the annotated form, extension arrays whose types differ only in metadata (pyarrow's equality ignores it), a committed Delta column appended as extension arrays. One rule, databases/utils.logical_identity_change, compares the identifier of every column and nested field in either form; the in-memory, connector and Delta databases apply it before buffering (Delta also at flush). Delta's held column keeps the extension annotations its log keeps on struct children. The type matrix appends each logical type under another extension name. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1371.md | 14 + docs/dev/design_issues/ITL-1371-LI1.md | 46 ++ .../itl_1371_logical_identity_appends.py | 176 +++++++ docs/reference/database-types.md | 6 +- .../databases/connector_arrow_database.py | 6 +- src/orcapod/databases/delta_lake_databases.py | 128 +++++- src/orcapod/databases/in_memory_databases.py | 11 +- src/orcapod/databases/utils.py | 149 ++++++ .../test_logical_identity_appends.py | 433 ++++++++++++++++++ tests/test_databases/type_matrix.py | 38 +- 10 files changed, 993 insertions(+), 14 deletions(-) create mode 100644 changelog.d/ITL-1371.md create mode 100644 docs/dev/design_issues/ITL-1371-LI1.md create mode 100644 docs/dev/scripts/itl_1371_logical_identity_appends.py create mode 100644 tests/test_databases/test_logical_identity_appends.py diff --git a/changelog.d/ITL-1371.md b/changelog.d/ITL-1371.md new file mode 100644 index 000000000..8fdda3d7d --- /dev/null +++ b/changelog.d/ITL-1371.md @@ -0,0 +1,14 @@ +### Fixed + +- **An append of another logical type is refused:** every database (in-memory, Delta Lake, + and the connector databases, directly and through `ExtensionAwareDatabase`) refuses rows + whose column, or a field nested in it (a struct child, a list item, a map key or item), + has the stored or pending column's storage type but another logical type identifier: + another extension name, the same name with other extension metadata, or a logical type + where the stored column has none, and the reverse. It raises `InputValidationError` + naming the column and both identifiers before anything is written. Before, such rows were + accepted in several cases (a Delta column in the annotated form, extension arrays whose + types differ only in their metadata) and read back as the stored type. An append with + the same identifier is accepted as before. A second append of a list or map of an + extension type to a committed Delta table, which Delta had stored as plain storage + (ITL-1372), is now refused too. (ITL-1371) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md new file mode 100644 index 000000000..05b933274 --- /dev/null +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -0,0 +1,46 @@ +## `src/orcapod/databases/` — appending another logical type + +### LI1 — An append of another logical type over the same storage type was accepted and read back as the stored type +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1371 + +A table holds one logical type per column and per nested field. An append that gave a +column the same storage type but another logical type identifier (another extension name, +the same name with other extension metadata, or a logical type where the stored column has +none, and the reverse) was accepted in several places, and every appended row then read back +as the stored type, a type it was never written as: + +- `DeltaTableDatabase`, a top-level column in the annotated form (storage type with + `ARROW:extension:name` / `ARROW:extension:metadata` field metadata, the form + `ExtensionAwareDatabase` passes on and a stored column reads back in): `_column_change` + left a logical column's extension keys out of its metadata comparison and relied on the + type check, which compares storage types only. This is the case reported. +- Extension arrays (in-memory and Delta, at every depth): pyarrow's equality of two Python + extension types ignores their serialized metadata, so two types with one name and other + metadata compare equal; the ITL-1334 checks (`appended_field_change`) treat an extension + type as a leaf and left it to that equality. +- `DeltaTableDatabase`, a committed table: the held column is the storage type with the + annotation, while the rows given are extension arrays, and the same short cut applied. + +**Fix:** one rule, `databases/utils.logical_identity_change` (with +`first_logical_identity_change` and `field_logical_identifier`), compares the logical type +identifier of every column and nested field (struct children by name, list items, map keys +and items, an extension's storage) in either form, by identifier, never by Arrow type +equality. In-memory and connector databases apply it in `add_records` before the ITL-1334 +check, Delta in `_column_change`, at add time and again at flush. A refusal raises +`InputValidationError` naming the column, the path and both identifiers' text, before +anything is buffered; an append with the same identifier is accepted as before. Columns are +matched by name, so the order of the given columns plays no part. Delta's held column now +carries the extension annotations the Delta log keeps on struct children +(`_with_extension_annotations`), so a struct of an extension type can still be appended to. +As in the other Delta checks, the rule runs after `skip_duplicates` has dropped the rows +already stored: an append that writes nothing is not refused. The database type matrix +appends each logical type again under another extension name, which every database refuses. + +A consequence of ITL-1372 (Delta writes a list item or a map value of an extension type as +plain storage on the first write): a second append of the same nested extension type to a +committed Delta table was accepted on main and stored as plain storage; it is now refused, +because the held column has no logical type. The first write is still accepted and still +loses the type until ITL-1372. `test_delta_nested_extension_second_append_is_refused` pins +this. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`. diff --git a/docs/dev/scripts/itl_1371_logical_identity_appends.py b/docs/dev/scripts/itl_1371_logical_identity_appends.py new file mode 100644 index 000000000..728df8ab9 --- /dev/null +++ b/docs/dev/scripts/itl_1371_logical_identity_appends.py @@ -0,0 +1,176 @@ +"""Which appends of another logical type identifier each database accepts (ITL-1371). + +usage: PYTHONPATH=. uv run python docs/dev/scripts/itl_1371_logical_identity_appends.py + +A table holds a column ``x`` of logical type ``probe.a`` (metadata ``m``), at the top +level, as a struct child, as a list item or as a map item; a second batch appends ``x`` +with the same storage type and the same, or another, identifier, either as a real Arrow +extension array or as the annotated physical form (storage type with +``ARROW:extension:name`` / ``ARROW:extension:metadata`` field metadata), against the +pending batch, the committed table, and (Delta, SpiralDB fake) a reopened database. +Prints ``accepted`` or ``refused: `` per case. +""" + +from __future__ import annotations + +import itertools +import os +import sys +import tempfile +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase +from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.sqlite_connector import SQLiteConnector + +NAME = b"ARROW:extension:name" +META = b"ARROW:extension:metadata" + + +def _probe_class(name: str) -> type: + """An extension type named ``name`` whose metadata is any bytes.""" + + class Probe(pa.ExtensionType): + def __init__(self, meta: bytes) -> None: + self._meta = meta + super().__init__(pa.large_string(), name) + + def __arrow_ext_serialize__(self) -> bytes: + return self._meta + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized) + + return Probe + + +PROBES = {name: _probe_class(name) for name in ("probe.a", "probe.b")} + + +IDENTIFIERS = { + "same": ("probe.a", b"m"), + "other name": ("probe.b", b"m"), + "other metadata": ("probe.a", b"n"), + "plain": None, +} + + +def leaf(identifier: tuple[str, bytes] | None, form: str, values: list[str]): + """The leaf field and array of ``x``.""" + storage = pa.array(values, pa.large_string()) + if identifier is None: + return pa.field("v", pa.large_string()), storage + if form == "extension": + ext = PROBES[identifier[0]](identifier[1]) + return pa.field("v", ext), pa.ExtensionArray.from_storage(ext, storage) + meta = {NAME: identifier[0].encode(), META: identifier[1]} + return pa.field("v", pa.large_string(), metadata=meta), storage + + +def column(identifier, form: str, depth: str, values: list[str]): + field, array = leaf(identifier, form, values) + n = len(values) + if depth == "top": + return field.with_name("x"), array + if depth == "struct": + arr = pa.StructArray.from_arrays([array], fields=[field]) + return pa.field("x", arr.type), arr + if depth == "list": + offsets = pa.array(list(range(n + 1)), pa.int64()) + typ = pa.large_list(field.with_name("item")) + arr = pa.LargeListArray.from_arrays(offsets, array, type=typ) + return pa.field("x", typ), arr + if depth == "map value": + offsets = pa.array(list(range(n + 1)), pa.int32()) + keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) + typ = pa.map_( + pa.field("key", pa.large_string(), nullable=False), field.with_name("value") + ) + arr = pa.MapArray.from_arrays(offsets, keys, array, type=typ) + return pa.field("x", typ), arr + raise AssertionError(depth) + + +def table(identifier, form, depth, ids: list[bytes]): + field, arr = column(identifier, form, depth, [i.decode() for i in ids]) + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), arr], + schema=pa.schema([pa.field("id", pa.large_binary()), field]), + ) + + +def open_db(kind: str, root: Path): + if kind == "in-memory": + return InMemoryArrowDatabase() + if kind == "Delta": + return DeltaTableDatabase(root / "delta") + if kind == "SQLite": + return ConnectorArrowDatabase(SQLiteConnector(str(root / "s.db"))) + if kind == "SpiralDB": + return ConnectorArrowDatabase(SpiralDBConnector("p")) + raise AssertionError(kind) + + +def case(kind, state, form, depth, change, root: Path) -> str: + path = ("t",) + db = open_db(kind, root) + base = IDENTIFIERS["same"] + try: + db.add_records( + path, + table(base, form, depth, [b"1"]), + record_id_column="id", + flush=state != "pending", + ) + except Exception as e: # noqa: BLE001 + return f"first write refused: {type(e).__name__}" + if state == "reopened": + db = open_db(kind, root) + incoming = table(IDENTIFIERS[change], form, depth, [b"2"]) + try: + db.add_records(path, incoming, record_id_column="id") + db.flush() + except Exception as e: # noqa: BLE001 + return f"refused: {type(e).__name__}: {(str(e).splitlines() or [''])[0][:110]}" + return "accepted" + + +def main() -> None: + warnings.simplefilter("ignore") + kinds = ["in-memory", "Delta", "SQLite", "SpiralDB"] + with tempfile.TemporaryDirectory() as tmp: + from tests.test_databases import fake_pyspiral + + with fake_pyspiral.install(Path(tmp) / "spiral"): + fake_pyspiral.FakeSpiral().project("p") + for i, (kind, state, form, depth, change) in enumerate( + itertools.product( + kinds, + ("pending", "committed", "reopened"), + ("extension", "annotated"), + ("top", "struct", "list", "map value"), + IDENTIFIERS, + ) + ): + if state == "reopened" and kind == "in-memory": + continue + root = Path(tmp) / str(i) + root.mkdir() + if kind == "SpiralDB": + fake_pyspiral.FakeSpiral().project("p") + print( + f"{kind:9} {state:9} {form:9} {depth:9} {change:14} " + f"{case(kind, state, form, depth, change, root)}" + ) + + +if __name__ == "__main__": + main() + sys.stdout.flush() + os._exit(0) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 1b668112e..9016c325e 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -39,8 +39,10 @@ How it is measured: a table holding two columns of the type (the second nullable null row) is written with `add_records` and flushed. The same type is then appended as slices of a larger table (three rows over two chunks, then the null row alone), and the same columns with other field metadata (the column's own, and a nested field's) are -appended, which every database must refuse, naming the column. Every batch written is read -back with `get_all_records`. +appended, which every database must refuse, naming the column; for a logical type, so are +the same values under another logical type identifier (another extension name over the +same storage), which would otherwise read back as the stored type. Every batch written is +read back with `get_all_records`. The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which models what SpiralDB does to a column (no SpiralDB is used). No database tells tag columns from data columns, so a type is kept or refused the same way in either role. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index e17ebeada..68b05bf49 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -26,6 +26,7 @@ from orcapod.databases.utils import ( coerce_record_id, first_changed_column, + first_logical_identity_change, ) from orcapod.errors import ( InputValidationError, @@ -484,7 +485,10 @@ def _refuse_changed_columns( self._stored_schemas[table_name] = stored if stored is not None: held.append(stored) - changed = first_changed_column(held, schema) + # A column of another logical type would read back as the held one (ITL-1371). + changed = first_logical_identity_change(held, schema) or first_changed_column( + held, schema + ) if changed is not None: raise InputValidationError( f"Cannot append to the table at {record_path!r}: column " diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 827d78ea5..14923b5e2 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -18,6 +18,7 @@ ) from orcapod.databases.utils import ( appended_field_change, + logical_identity_change, coerce_record_id, metadata_bytes, ) @@ -561,8 +562,10 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: The column's own field metadata and its nested field tree must be the held ones (``appended_field_change``): the table holds one type per column, so either side's rows would read back with the other's. A struct may evolve, within - ``_evolution_change``. A logical column's type is its extension's, which the type - check compares; its own field metadata is compared here. Nullability is not + ``_evolution_change``. A logical column's identifier (extension name and + metadata, at every depth, as an extension type or a field annotation) must be the + held one (``logical_identity_change``, ITL-1371); its storage type is compared by + the type check, its other field metadata here. Nullability is not compared: the append check and Delta decide it, and whether a change is refused belongs to the nullability audit (ITL-842). @@ -574,13 +577,29 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: Returns: The reason, naming the path, or ``None``. """ + # The logical type identifier first, at every depth, in either form: the + # metadata comparison below leaves a logical column's extension name and + # metadata out, and the type check compares storage types only (ITL-1371). + identity = logical_identity_change(held, field) + if identity is not None: + return identity if _is_logical(field) or _is_logical(held): if _metadata(held.metadata) == _metadata(field.metadata): return None return f"{field.name} has other field metadata than the stored column" return appended_field_change( - held.with_metadata(cast(Any, _metadata(held.metadata))), - field.with_metadata(cast(Any, _metadata(field.metadata))), + pa.field( + held.name, + _without_extension_annotations(held.type), + nullable=held.nullable, + metadata=cast(Any, _metadata(held.metadata)) or None, + ), + pa.field( + field.name, + _without_extension_annotations(field.type), + nullable=field.nullable, + metadata=cast(Any, _metadata(field.metadata)) or None, + ), ) or _evolution_change( arrow_utils.normalize_to_large_types(held.type, keep_null=True), arrow_utils.normalize_to_large_types(field.type, keep_null=True), @@ -588,9 +607,103 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: ) +def _with_extension_annotations(arrow_type: Any, delta_type: Any) -> Any: + """``arrow_type`` (a stored type without nested metadata) with the + ``ARROW:extension:*`` annotation the Delta log keeps on each nested field + (ITL-1371): a nested logical type's identifier is part of what the column holds. + + Struct children are matched by name, a list's item and a map's key and item + followed; no other metadata is restored. + + Args: + arrow_type: The stored Arrow type of a column, or of a nested field. + delta_type: The same column's ``deltalake.schema`` type. + + Returns: + ``arrow_type`` with the nested annotations. + """ + from deltalake.schema import ArrayType, MapType, StructType + + def annotated(field: "pa.Field[Any]", delta_field_type: Any, metadata: Any) -> Any: + keys = { + k: v for k, v in metadata_bytes(metadata).items() if k in _EXTENSION_KEYS + } + inner = _with_extension_annotations(field.type, delta_field_type) + return field.with_type(inner).with_metadata( + cast(Any, {**metadata_bytes(field.metadata), **keys}) or None + ) + + t = pa.types + if isinstance(delta_type, StructType) and t.is_struct(arrow_type): + by_name = {f.name: f for f in delta_type.fields} + return pa.struct( + [ + annotated(f, by_name[f.name].type, by_name[f.name].metadata) + if f.name in by_name + else f + for f in arrow_type + ] + ) + if isinstance(delta_type, ArrayType) and ( + t.is_list(arrow_type) or t.is_large_list(arrow_type) + ): + # Delta keeps no metadata on a list's element. + item = _with_extension_annotations( + arrow_type.value_type, delta_type.element_type + ) + value_field = arrow_type.value_field.with_type(item) + if t.is_large_list(arrow_type): + return pa.large_list(value_field) + return pa.list_(value_field) + if isinstance(delta_type, MapType) and t.is_map(arrow_type): + return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields + arrow_type.key_field.with_type( + _with_extension_annotations(arrow_type.key_type, delta_type.key_type) + ), + arrow_type.item_field.with_type( + _with_extension_annotations(arrow_type.item_type, delta_type.value_type) + ), + keys_sorted=arrow_type.keys_sorted, + ) + return arrow_type + + +def _without_extension_annotations(arrow_type: Any) -> Any: + """``arrow_type`` with the ``ARROW:extension:*`` keys removed from the metadata of + every nested field: the identifier they hold is compared by + ``logical_identity_change``, the rest of the metadata by ``appended_field_change`` + (ITL-1371).""" + + def bare(field: "pa.Field[Any]") -> "pa.Field[Any]": + metadata = _metadata(field.metadata) + return field.with_type( + _without_extension_annotations(field.type) + ).with_metadata(cast(Any, metadata) or None) + + t = pa.types + if isinstance(arrow_type, pa.BaseExtensionType): + return arrow_type + if t.is_struct(arrow_type): + return pa.struct([bare(f) for f in arrow_type]) + if t.is_large_list(arrow_type): + return pa.large_list(bare(arrow_type.value_field)) + if t.is_list(arrow_type): + return pa.list_(bare(arrow_type.value_field)) + if t.is_fixed_size_list(arrow_type): + return pa.list_(bare(arrow_type.value_field), arrow_type.list_size) + if t.is_map(arrow_type): + return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields + bare(arrow_type.key_field), + bare(arrow_type.item_field), + keys_sorted=arrow_type.keys_sorted, + ) + return arrow_type + + def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any]"]: """Each stored column as the table holds it: its recorded type, else its stored - type, with its field metadata as stored. Read from the log; no data is read.""" + type with the nested logical type annotations the log keeps, with its field + metadata as stored. Read from the log; no data is read.""" stored = _stored_arrow_schema(delta_table) fields: dict[str, pa.Field[Any]] = {} for delta_field in delta_table.schema().fields: @@ -599,7 +712,10 @@ def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any] delta_field.name, record if record is not None - else stored.field(stored.get_field_index(delta_field.name)).type, + else _with_extension_annotations( + stored.field(stored.get_field_index(delta_field.name)).type, + delta_field.type, + ), nullable=delta_field.nullable, metadata=cast(Any, metadata_bytes(delta_field.metadata)) or None, ) diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 92fca521a..ba2e8a2a4 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -6,7 +6,11 @@ from typing import TYPE_CHECKING, Any, cast from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows -from orcapod.databases.utils import coerce_record_id, first_changed_column +from orcapod.databases.utils import ( + coerce_record_id, + first_changed_column, + first_logical_identity_change, +) from orcapod.errors import InputValidationError from orcapod.utils.lazy_module import LazyModule @@ -264,7 +268,10 @@ def add_records( ) if table is not None ] - changed = first_changed_column(held, records.schema) + # A column of another logical type would read back as the held one (ITL-1371). + changed = first_logical_identity_change( + held, records.schema + ) or first_changed_column(held, records.schema) if changed is not None: raise InputValidationError( f"Cannot append to the table at {record_path!r}: column " diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 8cd9f0018..ae67e7dc0 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -6,6 +6,10 @@ from collections.abc import Iterable, Mapping from typing import TYPE_CHECKING, Any, cast +from orcapod.logical_types.identifier import ( + LogicalTypeIdentifier, + arrow_type_identifier, +) from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -201,3 +205,148 @@ def first_changed_column( if reason is not None: return field.name, reason return None + + +_EXTENSION_NAME = b"ARROW:extension:name" +_EXTENSION_METADATA = b"ARROW:extension:metadata" + + +def field_logical_identifier(field: "pa.Field[Any]") -> LogicalTypeIdentifier | None: + """The logical type identifier a field carries, in either form (ITL-1371). + + A logical column reaches a database as an Arrow extension type, or as its storage + type annotated with the extension name and metadata in the field metadata (the + form a stored column is read back in, and the form ``ExtensionAwareDatabase`` + passes on). Both forms carry one identifier. + + Args: + field: A column or nested field. + + Returns: + The identifier (extension name and metadata), or ``None`` for a field of no + logical type. + """ + if isinstance(field.type, pa.ExtensionType): + return arrow_type_identifier(field.type) + if isinstance(field.type, pa.BaseExtensionType): + # An extension type defined in Arrow's C++ library (``arrow.uuid``, + # ``arrow.fixed_shape_tensor``) has no ``__arrow_ext_serialize__``: its name + # and metadata are read from its C data interface export, as field metadata + # (arro3, which ``deltalake`` depends on). + from arro3.core import Field as Arro3Field + + exported = metadata_bytes( + Arro3Field.from_arrow(pa.field(field.name, field.type)).metadata + ) + return LogicalTypeIdentifier( + exported[_EXTENSION_NAME].decode(), exported.get(_EXTENSION_METADATA, b"") + ) + metadata = metadata_bytes(field.metadata) + name = metadata.get(_EXTENSION_NAME) + if name is None: + return None + return LogicalTypeIdentifier(name.decode(), metadata.get(_EXTENSION_METADATA, b"")) + + +def _identifier_text(identifier: LogicalTypeIdentifier | None) -> str: + return "no logical type" if identifier is None else repr(identifier.text) + + +def logical_identity_change( + held: "pa.Field[Any]", incoming: "pa.Field[Any]" +) -> str | None: + """Say why rows of ``incoming`` would be read back as another logical type than + they were written as, appended to a column a database holds as ``held`` + (ITL-1371). + + A table holds one logical type per column and per nested field, so the appended + column must carry, at every depth, the logical type identifier the held column + carries (``field_logical_identifier``: extension name and metadata, as an + extension type or as a field annotation; none counts as an identifier too). The + walk follows struct children by name, the items of every list kind, a map's key + and item, and an extension type's storage. Whatever else differs (a type, a + nested field's name or other metadata) is left to the other append checks. + + The comparison is by identifier, never by Arrow type equality: pyarrow's + equality of two Python extension types ignores their serialized metadata. + + Args: + held: The column as the database holds it (stored or pending). + incoming: The column of the rows to append. + + Returns: + The reason, naming the path (``x``, ``x.a``, ``x[]``, ``x.key``) and both + identifiers' text, or ``None``. + """ + return _identity_change(held, incoming, incoming.name) + + +def _identity_change( + held: "pa.Field[Any]", incoming: "pa.Field[Any]", path: str +) -> str | None: + held_id = field_logical_identifier(held) + incoming_id = field_logical_identifier(incoming) + if held_id != incoming_id: + return ( + f"{path} is of logical type {_identifier_text(incoming_id)}, the stored " + f"column's {_identifier_text(held_id)}" + ) + return _nested_identity_change(_storage(held.type), _storage(incoming.type), path) + + +def _storage(arrow_type: Any) -> Any: + while isinstance(arrow_type, pa.BaseExtensionType): + arrow_type = arrow_type.storage_type + return arrow_type + + +def _nested_identity_change(held: Any, incoming: Any, path: str) -> str | None: + t = pa.types + if t.is_struct(held) and t.is_struct(incoming): + known = {f.name: f for f in held} + for field in incoming: + if field.name in known: + found = _identity_change( + known[field.name], field, f"{path}.{field.name}" + ) + if found is not None: + return found + return None + if t.is_map(held) and t.is_map(incoming): + return _identity_change( + held.key_field, incoming.key_field, f"{path}.key" + ) or _identity_change(held.item_field, incoming.item_field, f"{path}.item") + lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) + if any(k(held) for k in lists) and any(k(incoming) for k in lists): + # cast: the type guards above narrow the types in the stubs' terms. + return _identity_change( + cast(Any, held).value_field, cast(Any, incoming).value_field, f"{path}[]" + ) + return None + + +def first_logical_identity_change( + held: "Iterable[pa.Schema]", schema: "pa.Schema" +) -> tuple[str, str] | None: + """The first column of ``schema`` that carries another logical type identifier + than a column of that name the database holds (``logical_identity_change``). + + Columns are matched by name; the order of either schema plays no part. + + Args: + held: The schemas the database holds for the table (stored, pending). + schema: The schema of the rows to append, as given. + + Returns: + The column's name and the reason, or ``None``. + """ + held = list(held) + for field in schema: + for given in held: + index = given.get_field_index(field.name) + if index < 0: + continue + reason = logical_identity_change(given.field(index), field) + if reason is not None: + return field.name, reason + return None diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py new file mode 100644 index 000000000..29c4b9ca1 --- /dev/null +++ b/tests/test_databases/test_logical_identity_appends.py @@ -0,0 +1,433 @@ +"""An append of another logical type identifier is refused (ITL-1371). + +A table holds one logical type per column and per nested field. A column appended +with the same storage type but another logical type identifier (another extension +name, the same name with other extension metadata, or a logical type where the held +column has none, and the reverse) would read back as the held type, so every database +refuses it before anything is buffered, naming the column and both identifiers. The +identifier arrives in two forms: an Arrow extension type, or its storage type +annotated with ``ARROW:extension:name`` / ``ARROW:extension:metadata`` (the form a +stored column reads back in, and the one ``ExtensionAwareDatabase`` passes on). +""" + +from __future__ import annotations + +import contextlib +import itertools +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import ( + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, +) +from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase +from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.utils import ( + field_logical_identifier, + first_logical_identity_change, + logical_identity_change, +) +from orcapod.errors import InputValidationError +from orcapod.logical_types.identifier import LogicalTypeIdentifier +from orcapod.logical_types.registry import LogicalTypeRegistry +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from tests.test_databases import fake_pyspiral + +NAME = b"ARROW:extension:name" +META = b"ARROW:extension:metadata" +PATH = ("t",) + + +def _extension_class(name: str) -> type[pa.ExtensionType]: + """An extension type named ``name`` over ``large_string``, any metadata bytes.""" + + class _Ext(pa.ExtensionType): + def __init__(self, meta: bytes) -> None: + self._meta = meta + super().__init__(pa.large_string(), name) + + def __arrow_ext_serialize__(self) -> bytes: + return self._meta + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized) + + return _Ext + + +EXTENSIONS = {name: _extension_class(name) for name in ("itl1371.a", "itl1371.b")} + +HELD = ("itl1371.a", b"m") +CHANGES: dict[str, tuple[str, bytes] | None] = { + "other name": ("itl1371.b", b"m"), + "other metadata": ("itl1371.a", b"n"), + "no logical type": None, +} + + +def _text(identifier: tuple[str, bytes]) -> str: + return LogicalTypeIdentifier(*identifier).text + + +def _leaf( + identifier: tuple[str, bytes] | None, form: str, values: list[str] +) -> tuple[pa.Field, pa.Array]: + storage = pa.array(values, pa.large_string()) + if identifier is None: + return pa.field("v", pa.large_string()), storage + if form == "extension": + ext = EXTENSIONS[identifier[0]](identifier[1]) + return pa.field("v", ext), pa.ExtensionArray.from_storage(ext, storage) + metadata = {NAME: identifier[0].encode(), META: identifier[1]} + return pa.field("v", pa.large_string(), metadata=metadata), storage + + +def _column( + identifier: tuple[str, bytes] | None, form: str, depth: str, values: list[str] +) -> tuple[pa.Field, pa.Array]: + field, array = _leaf(identifier, form, values) + n = len(values) + if depth == "top": + return field.with_name("x"), array + if depth == "struct": + struct = pa.StructArray.from_arrays([array], fields=[field]) + return pa.field("x", struct.type), struct + if depth == "list": + list_type = pa.large_list(field.with_name("item")) + offsets = pa.array(range(n + 1), pa.int64()) + return pa.field("x", list_type), pa.LargeListArray.from_arrays( + offsets, array, type=list_type + ) + assert depth == "map value" + map_type = pa.map_( + pa.field("key", pa.large_string(), nullable=False), field.with_name("value") + ) + keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) + offsets = pa.array(range(n + 1), pa.int32()) + return pa.field("x", map_type), pa.MapArray.from_arrays( + offsets, keys, array, type=map_type + ) + + +def _rows( + identifier: tuple[str, bytes] | None, form: str, depth: str, ids: list[bytes] +) -> pa.Table: + """Rows ``ids`` with a data column ``a`` before and ``x`` after the record id.""" + field, array = _column(identifier, form, depth, [i.decode() for i in ids]) + return pa.Table.from_arrays( + [ + pa.array([len(i) for i in ids], pa.int64()), + pa.array(ids, pa.large_binary()), + array, + ], + schema=pa.schema( + [pa.field("a", pa.int64()), pa.field("id", pa.large_binary()), field] + ), + ) + + +# --------------------------------------------------------------------------- +# Databases +# --------------------------------------------------------------------------- + + +class _Store: + """One database of a kind over one root: ``db`` (the same instance, so a pending + batch stays pending) until ``reopen`` opens it again over the same files.""" + + def __init__(self, open_db: Any) -> None: + self._open = open_db + self.db = open_db() + + def reopen(self) -> None: + self.db = self._open() + + def stored(self) -> pa.Table: + """Flush and read every row back.""" + self.db.flush() + table = self.db.get_all_records(PATH, record_id_column="id") + assert table is not None + return table + + +@contextlib.contextmanager +def _store(kind: str, root: Path) -> Iterator[_Store]: + """A ``_Store`` of database ``kind`` over ``root``.""" + if kind == "in-memory": + yield _Store(InMemoryArrowDatabase) + elif kind == "Delta": + yield _Store(lambda: DeltaTableDatabase(root / "delta")) + else: + assert kind == "SpiralDB" + with fake_pyspiral.install(root / "spiral"): + fake_pyspiral.FakeSpiral().project("p") + yield _Store(lambda: ConnectorArrowDatabase(SpiralDBConnector("p"))) + + +def _through(db: Any, via: str) -> Any: + if via == "direct": + return db + converter = UniversalTypeConverter(logical_type_registry=LogicalTypeRegistry()) + return ExtensionAwareDatabase(db, converter) + + +def _supported(kind: str, form: str, depth: str) -> bool: + """Whether ``kind`` stores the column at all (the type matrix): SpiralDB keeps an + annotated top-level column only here; it refuses extension types, and the fake + refuses these nested forms.""" + if kind == "SpiralDB": + return form == "annotated" and depth == "top" + return True + + +def _loses_nested_extension(kind: str, state: str, form: str, depth: str) -> bool: + """Delta writes a list item or map value of an extension type as plain storage + (ITL-1372): a committed table no longer holds the identifier, so only refusals + are asserted there. (A struct child keeps its annotation in the Delta log.)""" + return ( + kind == "Delta" + and form == "extension" + and depth in ("list", "map value") + and state != "pending" + ) + + +KINDS = ("in-memory", "Delta", "SpiralDB") +STATES = ("pending", "committed", "reopened") +FORMS = ("extension", "annotated") +DEPTHS = ("top", "struct", "list", "map value") + +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") +] + +REFUSED_CASES = [ + pytest.param(*case, change, id=f"{'-'.join(case)}-{change}") + for case in BASE + for change in CHANGES + # A plain column over a Delta column that lost its nested type (ITL-1372) is not + # another identifier: the held column is plain too. + if not (_loses_nested_extension(*case) and CHANGES[change] is None) +] + +SAME_CASES = [ + pytest.param(*case, id="-".join(case)) + for case in BASE + if not _loses_nested_extension(*case) # pinned by the ITL-1372 test below +] + + +def _write_held(store: _Store, via: str, state: str, form: str, depth: str) -> None: + held = _rows(HELD, form, depth, [b"1", b"22"]) + _through(store.db, via).add_records( + PATH, held, record_id_column="id", flush=state != "pending" + ) + if state == "reopened": + store.reopen() + + +def _assert_only_held_rows(store: _Store) -> None: + """The two held rows, as written, and nothing of the refused append.""" + stored = store.stored() + assert stored.column("id").to_pylist() == [b"1", b"22"] + assert stored.column("a").to_pylist() == [1, 2] + x = stored.column("x") + values = x.combine_chunks() + if isinstance(values, pa.ExtensionArray): + values = values.storage + assert len(values) == 2 + + +@pytest.mark.parametrize("via", ["direct", "wrapper"]) +@pytest.mark.parametrize(("kind", "state", "form", "depth", "change"), REFUSED_CASES) +def test_another_identifier_is_refused( + tmp_path: Path, kind: str, state: str, form: str, depth: str, change: str, via: str +) -> None: + with _store(kind, tmp_path) as store: + _write_held(store, via, state, form, depth) + incoming = _rows(CHANGES[change], form, depth, [b"333", b"4444"]) + with pytest.raises(InputValidationError) as refused: + _through(store.db, via).add_records(PATH, incoming, record_id_column="id") + message = str(refused.value) + assert "column 'x'" in message + assert "othing was written" in message + lost = _loses_nested_extension(kind, state, form, depth) + assert (repr(_text(HELD)) if not lost else "no logical type") 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) + + +@pytest.mark.parametrize("via", ["direct", "wrapper"]) +@pytest.mark.parametrize(("kind", "state", "form", "depth"), SAME_CASES) +def test_same_identifier_is_accepted( + tmp_path: Path, kind: str, state: str, form: str, depth: str, via: str +) -> None: + with _store(kind, tmp_path) as store: + _write_held(store, via, state, form, depth) + same = _rows(HELD, form, depth, [b"333"]) + _through(store.db, via).add_records(PATH, same, record_id_column="id") + assert store.stored().num_rows == 3 + + +@pytest.mark.parametrize("via", ["direct", "wrapper"]) +@pytest.mark.parametrize("form", FORMS) +@pytest.mark.parametrize("depth", DEPTHS) +@pytest.mark.parametrize("state", ["pending", "committed"]) +@pytest.mark.parametrize("kind", ["in-memory", "Delta"]) +def test_a_logical_type_over_a_plain_column_is_refused( + tmp_path: Path, kind: str, state: str, form: str, depth: str, via: str +) -> None: + with _store(kind, tmp_path) as store: + _through(store.db, via).add_records( + PATH, + _rows(None, form, depth, [b"1"]), + record_id_column="id", + flush=state == "committed", + ) + with pytest.raises( + InputValidationError, match="the stored column's no logical" + ): + _through(store.db, via).add_records( + PATH, _rows(HELD, form, depth, [b"22"]), record_id_column="id" + ) + assert store.stored().column("id").to_pylist() == [b"1"] + + +@pytest.mark.parametrize("depth", ["list", "map value"]) +def test_delta_nested_extension_second_append_is_refused( + tmp_path: Path, depth: str +) -> None: + """Pins a consequence of ITL-1372; revisit there. + + Delta writes a list item or map value of an extension type as plain storage on + the first write: the first write is accepted and reads back plain. On main a + second append of the same type to the committed table was accepted and stored as + plain storage too (the map; the list was refused for its item's name); it is now + refused, because the held column has no logical type. A same-type append to the + pending batch is still accepted. + """ + db = DeltaTableDatabase(tmp_path / "delta") + 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() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.num_rows == 2 + leaf = stored.schema.field("x").type + leaf_field = leaf.value_field if depth == "list" else leaf.item_field + assert field_logical_identifier(leaf_field) is None # read back plain + with pytest.raises(InputValidationError) as refused: + db.add_records( + PATH, _rows(HELD, "extension", depth, [b"333"]), record_id_column="id" + ) + assert f"of logical type {_text(HELD)!r}, the stored column's no logical type" in ( + str(refused.value) + ) + db.flush() + after = db.get_all_records(PATH, record_id_column="id") + assert after is not None and after.num_rows == 2 + + +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") + wrapper = ExtensionAwareDatabase( + inner, UniversalTypeConverter(logical_type_registry=LogicalTypeRegistry()) + ) + wrapper.add_records( + PATH, _rows(HELD, "annotated", "top", [b"1"]), record_id_column="id", flush=True + ) + other = ("itl1371.b", b"m") + with pytest.raises(InputValidationError) as refused: + wrapper.add_records( + PATH, + _rows(other, "annotated", "top", [b"22"]), + record_id_column="id", + flush=True, + ) + assert repr(_text(other)) in str(refused.value) + assert repr(_text(HELD)) in str(refused.value) + stored = inner.get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.column("id").to_pylist() == [b"1"] + + +# --------------------------------------------------------------------------- +# The rule itself +# --------------------------------------------------------------------------- + + +def test_identifier_is_read_from_either_form() -> None: + ext = EXTENSIONS["itl1371.a"](b"m") + annotated = pa.field( + "x", pa.large_string(), metadata={NAME: b"itl1371.a", META: b"m"} + ) + assert field_logical_identifier(pa.field("x", ext)) == LogicalTypeIdentifier( + "itl1371.a", b"m" + ) + assert field_logical_identifier(annotated) == LogicalTypeIdentifier( + "itl1371.a", b"m" + ) + assert field_logical_identifier(pa.field("x", pa.large_string())) is None + # The two forms of one identifier are one identifier. + assert logical_identity_change(annotated, pa.field("x", ext)) is None + + +def test_pyarrow_equality_does_not_decide() -> None: + """pyarrow's equality of two Python extension types ignores their metadata.""" + m, n = EXTENSIONS["itl1371.a"](b"m"), EXTENSIONS["itl1371.a"](b"n") + assert m == n # what the rule must not rely on + assert logical_identity_change(pa.field("x", m), pa.field("x", n)) is not None + + +@pytest.mark.parametrize( + ("depth", "path"), + [("top", "x"), ("struct", "x.v"), ("list", "x[]"), ("map value", "x.item")], +) +def test_reason_names_the_path(depth: str, path: str) -> None: + held = _rows(HELD, "annotated", depth, [b"1"]).schema + incoming = _rows(("itl1371.b", b"m"), "extension", depth, [b"1"]).schema + found = first_logical_identity_change([held], incoming) + assert found is not None + assert found[0] == "x" + assert found[1].startswith(f"{path} is of logical type") + + +def test_columns_are_matched_by_name_in_any_order() -> None: + held = _rows(HELD, "annotated", "top", [b"1"]).schema + incoming = _rows(("itl1371.b", b"m"), "annotated", "top", [b"1"]).schema + reordered = pa.schema([incoming.field(n) for n in ("x", "id", "a")]) + assert first_logical_identity_change([held], incoming) == ( + first_logical_identity_change([held], reordered) + ) + same = pa.schema([held.field(n) for n in ("x", "a", "id")]) + assert first_logical_identity_change([held], same) is None + + +def test_map_key_identifier_is_compared() -> None: + def map_field(identifier: tuple[str, bytes]) -> pa.Field: + key = pa.field( + "key", + pa.large_string(), + nullable=False, + metadata={NAME: identifier[0].encode(), META: identifier[1]}, + ) + return pa.field("x", pa.map_(key, pa.field("value", pa.int64()))) + + assert logical_identity_change(map_field(HELD), map_field(HELD)) is None + reason = logical_identity_change(map_field(HELD), map_field(("itl1371.a", b"n"))) + assert reason is not None and reason.startswith("x.key ") diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index ce00684e8..dd63a471a 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -53,6 +53,7 @@ SpiralDBConnector, ) from orcapod.databases.delta_arrow_types import _is_recorded # pyright: ignore[reportPrivateUsage] +from orcapod.databases.utils import field_logical_identifier from orcapod.utils.arrow_utils import normalize_to_large_types KEPT = "KEPT" @@ -812,9 +813,29 @@ def _nested_changed(arrow_type: Any) -> Any: return None +def _other_identifier(field: "pa.Field[Any]", column: Any) -> tuple[Any, Any]: + """A logical column as the same storage annotated with another extension name + (the column's, suffixed) and the same metadata: another logical type identifier + (ITL-1371). Not the same name with other metadata: a registered type's + unreadable metadata is refused before the append is compared.""" + ext = cast("pa.BaseExtensionType", field.type) + identifier = field_logical_identifier(field) + assert identifier is not None + metadata = { + b"ARROW:extension:name": f"{identifier.name}.other".encode(), + b"ARROW:extension:metadata": identifier.metadata, + } + storage = pa.chunked_array( + [chunk.storage for chunk in column.chunks], type=ext.storage_type + ) + return pa.field(field.name, ext.storage_type, field.nullable, metadata), storage + + def _attribute_changes(rows: pa.Table) -> list[tuple[str, pa.Table]]: """``rows`` (new ids) with other field attributes on ``x`` and ``y``: the columns' - own metadata, then, for a nested type, its first nested field's metadata.""" + own metadata; for a logical type, another identifier (another extension name); + for a nested type, its first nested field's + metadata.""" ids = pa.array([b"c1", b"c2", b"c3"], pa.large_binary()) rows = rows.set_column(0, rows.schema.field("id"), ids) out = [] @@ -825,6 +846,15 @@ def _attribute_changes(rows: pa.Table) -> list[tuple[str, pa.Table]]: index, _with_changed_metadata(own.schema.field(name)), own.column(index) ) out.append(("column metadata", own)) + if isinstance(rows.schema.field("x").type, pa.BaseExtensionType): + other = rows + for name in ("x", "y"): + index = other.schema.get_field_index(name) + field, column = _other_identifier( + other.schema.field(name), other.column(index) + ) + other = other.set_column(index, field, column) + out.append(("logical type identifier", other)) nested = rows for name in ("x", "y"): index = nested.schema.get_field_index(name) @@ -1014,8 +1044,10 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: null row) is written with `add_records` and flushed. The same type is then appended as slices of a larger table (three rows over two chunks, then the null row alone), and the same columns with other field metadata (the column's own, and a nested field's) are -appended, which every database must refuse, naming the column. Every batch written is read -back with `get_all_records`. +appended, which every database must refuse, naming the column; for a logical type, so are +the same values under another logical type identifier (another extension name over the +same storage), which would otherwise read back as the stored type. Every batch written is +read back with `get_all_records`. The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which models what SpiralDB does to a column (no SpiralDB is used). No database tells tag columns from data columns, so a type is kept or refused the same way in either role. From 11052fab81150e8e0443aca49ec006a896dfb661 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:41:35 -0800 Subject: [PATCH 02/14] test(databases): nested metadata beside an identifier is still refused; type fixes (ITL-1371) Pin that Delta's ITL-1334 comparison, which now leaves nested extension keys to the identity rule, still refuses a struct child of the same logical type with other non-extension metadata. Fix basedpyright errors in the new code. Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 4 +- .../itl_1371_logical_identity_appends.py | 16 ++-- src/orcapod/databases/delta_lake_databases.py | 4 +- .../test_logical_identity_appends.py | 83 ++++++++++++++++--- tests/test_databases/type_matrix.py | 5 +- 5 files changed, 87 insertions(+), 25 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 05b933274..fc0997ca9 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -33,7 +33,9 @@ check, Delta in `_column_change`, at add time and again at flush. A refusal rais anything is buffered; an append with the same identifier is accepted as before. Columns are matched by name, so the order of the given columns plays no part. Delta's held column now carries the extension annotations the Delta log keeps on struct children -(`_with_extension_annotations`), so a struct of an extension type can still be appended to. +(`_with_extension_annotations`), so a struct of an extension type can still be appended to, +and Delta's ITL-1334 comparison leaves the nested extension keys to the new rule +(`_without_extension_annotations`); every other nested metadata key is compared as before. As in the other Delta checks, the rule runs after `skip_duplicates` has dropped the rows already stored: an append that writes nothing is not refused. The database type matrix appends each logical type again under another extension name, which every database refuses. diff --git a/docs/dev/scripts/itl_1371_logical_identity_appends.py b/docs/dev/scripts/itl_1371_logical_identity_appends.py index 728df8ab9..1559c82c4 100644 --- a/docs/dev/scripts/itl_1371_logical_identity_appends.py +++ b/docs/dev/scripts/itl_1371_logical_identity_appends.py @@ -32,7 +32,7 @@ META = b"ARROW:extension:metadata" -def _probe_class(name: str) -> type: +def _probe_class(name: str) -> Any: """An extension type named ``name`` whose metadata is any bytes.""" class Probe(pa.ExtensionType): @@ -50,7 +50,7 @@ def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: return Probe -PROBES = {name: _probe_class(name) for name in ("probe.a", "probe.b")} +PROBES: dict[str, Any] = {name: _probe_class(name) for name in ("probe.a", "probe.b")} IDENTIFIERS = { @@ -87,12 +87,16 @@ def column(identifier, form: str, depth: str, values: list[str]): arr = pa.LargeListArray.from_arrays(offsets, array, type=typ) return pa.field("x", typ), arr if depth == "map value": - offsets = pa.array(list(range(n + 1)), pa.int32()) + # The stubs type pa.map_'s arguments as types and from_arrays' offsets as + # int64; pyarrow takes key and item fields, and int32 offsets for a map. + offsets: Any = pa.array(list(range(n + 1)), pa.int32()) keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) - typ = pa.map_( - pa.field("key", pa.large_string(), nullable=False), field.with_name("value") + typ: Any = pa.map_( + pa.field("key", pa.large_string(), nullable=False), # pyright: ignore[reportArgumentType] + field.with_name("value"), # pyright: ignore[reportArgumentType] ) - arr = pa.MapArray.from_arrays(offsets, keys, array, type=typ) + from_arrays: Any = pa.MapArray.from_arrays + arr = from_arrays(offsets, keys, array, type=typ) return pa.field("x", typ), arr raise AssertionError(depth) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 14923b5e2..dd9355f8d 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -630,7 +630,7 @@ def annotated(field: "pa.Field[Any]", delta_field_type: Any, metadata: Any) -> A } inner = _with_extension_annotations(field.type, delta_field_type) return field.with_type(inner).with_metadata( - cast(Any, {**metadata_bytes(field.metadata), **keys}) or None + cast(Any, {**metadata_bytes(field.metadata), **keys}) ) t = pa.types @@ -678,7 +678,7 @@ def bare(field: "pa.Field[Any]") -> "pa.Field[Any]": metadata = _metadata(field.metadata) return field.with_type( _without_extension_annotations(field.type) - ).with_metadata(cast(Any, metadata) or None) + ).with_metadata(cast(Any, metadata)) t = pa.types if isinstance(arrow_type, pa.BaseExtensionType): diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 29c4b9ca1..fb653d92c 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -44,7 +44,7 @@ PATH = ("t",) -def _extension_class(name: str) -> type[pa.ExtensionType]: +def _extension_class(name: str) -> Any: """An extension type named ``name`` over ``large_string``, any metadata bytes.""" class _Ext(pa.ExtensionType): @@ -62,7 +62,9 @@ def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: return _Ext -EXTENSIONS = {name: _extension_class(name) for name in ("itl1371.a", "itl1371.b")} +EXTENSIONS: dict[str, Any] = { + name: _extension_class(name) for name in ("itl1371.a", "itl1371.b") +} HELD = ("itl1371.a", b"m") CHANGES: dict[str, tuple[str, bytes] | None] = { @@ -78,7 +80,7 @@ def _text(identifier: tuple[str, bytes]) -> str: def _leaf( identifier: tuple[str, bytes] | None, form: str, values: list[str] -) -> tuple[pa.Field, pa.Array]: +) -> tuple["pa.Field[Any]", Any]: storage = pa.array(values, pa.large_string()) if identifier is None: return pa.field("v", pa.large_string()), storage @@ -91,7 +93,7 @@ def _leaf( def _column( identifier: tuple[str, bytes] | None, form: str, depth: str, values: list[str] -) -> tuple[pa.Field, pa.Array]: +) -> tuple["pa.Field[Any]", Any]: field, array = _leaf(identifier, form, values) n = len(values) if depth == "top": @@ -106,14 +108,16 @@ def _column( offsets, array, type=list_type ) assert depth == "map value" - map_type = pa.map_( - pa.field("key", pa.large_string(), nullable=False), field.with_name("value") + # The stubs type pa.map_'s arguments as types and from_arrays' offsets as int64; + # pyarrow takes key and item fields, and int32 offsets for a map. + map_type: Any = pa.map_( + pa.field("key", pa.large_string(), nullable=False), # pyright: ignore[reportArgumentType] + field.with_name("value"), # pyright: ignore[reportArgumentType] ) keys = pa.array([f"k{i}" for i in range(n)], pa.large_string()) - offsets = pa.array(range(n + 1), pa.int32()) - return pa.field("x", map_type), pa.MapArray.from_arrays( - offsets, keys, array, type=map_type - ) + offsets: Any = pa.array(range(n + 1), pa.int32()) + from_arrays: Any = pa.MapArray.from_arrays + return pa.field("x", map_type), from_arrays(offsets, keys, array, type=map_type) def _rows( @@ -238,7 +242,7 @@ def _write_held(store: _Store, via: str, state: str, form: str, depth: str) -> N def _assert_only_held_rows(store: _Store) -> None: """The two held rows, as written, and nothing of the refused append.""" - stored = store.stored() + stored = store.stored().sort_by("id") assert stored.column("id").to_pylist() == [b"1", b"22"] assert stored.column("a").to_pylist() == [1, 2] x = stored.column("x") @@ -419,15 +423,68 @@ def test_columns_are_matched_by_name_in_any_order() -> None: def test_map_key_identifier_is_compared() -> None: - def map_field(identifier: tuple[str, bytes]) -> pa.Field: + def map_field(identifier: tuple[str, bytes]) -> "pa.Field[Any]": key = pa.field( "key", pa.large_string(), nullable=False, metadata={NAME: identifier[0].encode(), META: identifier[1]}, ) - return pa.field("x", pa.map_(key, pa.field("value", pa.int64()))) + item = pa.field("value", pa.int64()) + return pa.field("x", pa.map_(key, item)) # pyright: ignore[reportArgumentType] # pyarrow takes key/item fields assert logical_identity_change(map_field(HELD), map_field(HELD)) is None reason = logical_identity_change(map_field(HELD), map_field(("itl1371.a", b"n"))) 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: + """Delta leaves the nested extension keys to the identity rule and compares the + rest of a nested field's metadata as before (ITL-1334): a struct child of the + same logical type with other non-extension metadata is refused.""" + 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"] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index dd63a471a..603e11f43 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -825,9 +825,8 @@ def _other_identifier(field: "pa.Field[Any]", column: Any) -> tuple[Any, Any]: b"ARROW:extension:name": f"{identifier.name}.other".encode(), b"ARROW:extension:metadata": identifier.metadata, } - storage = pa.chunked_array( - [chunk.storage for chunk in column.chunks], type=ext.storage_type - ) + chunked: Any = pa.chunked_array # the stubs type ``type=`` as None + storage = chunked([chunk.storage for chunk in column.chunks], type=ext.storage_type) return pa.field(field.name, ext.storage_type, field.nullable, metadata), storage From 004f86b6c876c49e4ec81219060ce56d7eedc320 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 15:10:16 -0800 Subject: [PATCH 03/14] fix(databases): the identity rule refuses only a known different identifier (ITL-1371) Review round 1 of PR 492. The identity rule now adds a refusal only where it knows, from raw stored bytes, that two identifiers differ, and abstains elsewhere, so every other verdict is main's: - Delta's ITL-1334 comparison and held view are back to main (no nested extension keys stripped, no annotations restored): a representation change on a struct child is refused as on main and the stored rows keep their type. - The stored Delta side comes from the Delta log (column and struct children, byte for byte); list items and map keys/items, which the log does not keep and the recorded type rewrites through the registry, abstain. - Identifiers are compared as bytes, decoded only to word an error. - The walk enumerates the children of every nested Arrow type (list views, unions, dictionary values, run-end encoded) and unwraps one extension level at a time. - An untyped null claims no type, as Delta's null rule says. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1371.md | 7 +- docs/dev/design_issues/ITL-1371-LI1.md | 53 +- src/orcapod/databases/delta_lake_databases.py | 213 ++++---- src/orcapod/databases/utils.py | 248 +++++---- .../test_logical_identity_appends.py | 506 +++++++++++++++--- tests/test_databases/type_matrix.py | 8 +- 6 files changed, 716 insertions(+), 319 deletions(-) diff --git a/changelog.d/ITL-1371.md b/changelog.d/ITL-1371.md index 8fdda3d7d..b789f9faf 100644 --- a/changelog.d/ITL-1371.md +++ b/changelog.d/ITL-1371.md @@ -9,6 +9,7 @@ naming the column and both identifiers before anything is written. Before, such rows were accepted in several cases (a Delta column in the annotated form, extension arrays whose types differ only in their metadata) and read back as the stored type. An append with - the same identifier is accepted as before. A second append of a list or map of an - extension type to a committed Delta table, which Delta had stored as plain storage - (ITL-1372), is now refused too. (ITL-1371) + the same identifier is decided as before; identifiers are compared as stored bytes. A + list item or map key or item of a stored Delta table, whose identifier Delta does not + keep (ITL-1372), is decided as before. + (ITL-1371) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index fc0997ca9..81e80eea0 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -23,26 +23,35 @@ as the stored type, a type it was never written as: - `DeltaTableDatabase`, a committed table: the held column is the storage type with the annotation, while the rows given are extension arrays, and the same short cut applied. -**Fix:** one rule, `databases/utils.logical_identity_change` (with -`first_logical_identity_change` and `field_logical_identifier`), compares the logical type -identifier of every column and nested field (struct children by name, list items, map keys -and items, an extension's storage) in either form, by identifier, never by Arrow type -equality. In-memory and connector databases apply it in `add_records` before the ITL-1334 -check, Delta in `_column_change`, at add time and again at flush. A refusal raises -`InputValidationError` naming the column, the path and both identifiers' text, before -anything is buffered; an append with the same identifier is accepted as before. Columns are -matched by name, so the order of the given columns plays no part. Delta's held column now -carries the extension annotations the Delta log keeps on struct children -(`_with_extension_annotations`), so a struct of an extension type can still be appended to, -and Delta's ITL-1334 comparison leaves the nested extension keys to the new rule -(`_without_extension_annotations`); every other nested metadata key is compared as before. -As in the other Delta checks, the rule runs after `skip_duplicates` has dropped the rows -already stored: an append that writes nothing is not refused. The database type matrix -appends each logical type again under another extension name, which every database refuses. +**Fix:** one rule, `databases/utils.logical_identity_change`, over `IdentityNode`s +(`identity_node` for a field as given, `first_logical_identity_change` for schemas): at every +column and nested place (struct children by name, list items of every kind including list +views, map keys and items, union members, dictionary values, run-end encoded children, and +an extension type held directly as another's storage, one extension level at a time), the +raw identifier bytes (an extension type's name and serialized metadata, or the +`ARROW:extension:*` annotation; never decoded to decide, never Arrow type equality) must be +the held ones; no logical type is an identifier too. -A consequence of ITL-1372 (Delta writes a list item or a map value of an extension type as -plain storage on the first write): a second append of the same nested extension type to a -committed Delta table was accepted on main and stored as plain storage; it is now refused, -because the held column has no logical type. The first write is still accepted and still -loses the type until ITL-1372. `test_delta_nested_extension_second_append_is_refused` pins -this. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`. +The rule only ADDS a refusal where it KNOWS the identifiers differ: from the fields as given +(in-memory, a pending batch, a connector's stored schema) and, for a stored Delta table, from +the Delta log, which keeps the field metadata of a column and of each struct child byte for +byte (`_delta_identity_node`). Where the held identifier is not reliably known (a Delta list +item, map key or item: the log keeps no metadata there, and the recorded type is read +through the Arrow registry, which may rewrite the metadata) and where a side is an untyped +null (`pa.null()`, which holds no value and claims no type), it abstains, and the database's +other checks decide exactly as before. A place only one side has (struct evolution, another +kind of type) is left to those checks too. The ITL-1334 comparison is unchanged and runs after +it. In-memory and connector databases apply it in `add_records`, Delta in +`_refuse_changed_attributes` (pending and stored) and again at flush (`_append_refusal`). +A refusal raises `InputValidationError` naming the column, the path and both identifiers' +text, before anything is buffered. As in the other Delta checks, the rule runs after +`skip_duplicates` has dropped the rows already stored: an append that writes nothing is not +refused. The database type matrix appends each logical type again under another extension +name, which every database refuses. + +So the only appends whose verdict differs from main are those with a known different +identifier. Where Delta stored a nested extension type as plain storage (a list item or map +value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with +any identifier, a second list refused for its item's name). Also pre-existing (ITL-1372): +Delta refuses any second append of a registered logical type nested in a column with a +recorded type, even the identical one. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index dd9355f8d..114cd8d0e 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -17,9 +17,12 @@ rows_at, ) from orcapod.databases.utils import ( + UNKNOWN, + IdentityNode, appended_field_change, - logical_identity_change, coerce_record_id, + identity_node, + logical_identity_change, metadata_bytes, ) from orcapod.errors import ( @@ -562,10 +565,8 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: The column's own field metadata and its nested field tree must be the held ones (``appended_field_change``): the table holds one type per column, so either side's rows would read back with the other's. A struct may evolve, within - ``_evolution_change``. A logical column's identifier (extension name and - metadata, at every depth, as an extension type or a field annotation) must be the - held one (``logical_identity_change``, ITL-1371); its storage type is compared by - the type check, its other field metadata here. Nullability is not + ``_evolution_change``. A logical column's type is its extension's, which the type + check compares; its own field metadata is compared here. Nullability is not compared: the append check and Delta decide it, and whether a change is refused belongs to the nullability audit (ITL-842). @@ -577,29 +578,13 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: Returns: The reason, naming the path, or ``None``. """ - # The logical type identifier first, at every depth, in either form: the - # metadata comparison below leaves a logical column's extension name and - # metadata out, and the type check compares storage types only (ITL-1371). - identity = logical_identity_change(held, field) - if identity is not None: - return identity if _is_logical(field) or _is_logical(held): if _metadata(held.metadata) == _metadata(field.metadata): return None return f"{field.name} has other field metadata than the stored column" return appended_field_change( - pa.field( - held.name, - _without_extension_annotations(held.type), - nullable=held.nullable, - metadata=cast(Any, _metadata(held.metadata)) or None, - ), - pa.field( - field.name, - _without_extension_annotations(field.type), - nullable=field.nullable, - metadata=cast(Any, _metadata(field.metadata)) or None, - ), + held.with_metadata(cast(Any, _metadata(held.metadata))), + field.with_metadata(cast(Any, _metadata(field.metadata))), ) or _evolution_change( arrow_utils.normalize_to_large_types(held.type, keep_null=True), arrow_utils.normalize_to_large_types(field.type, keep_null=True), @@ -607,103 +592,9 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: ) -def _with_extension_annotations(arrow_type: Any, delta_type: Any) -> Any: - """``arrow_type`` (a stored type without nested metadata) with the - ``ARROW:extension:*`` annotation the Delta log keeps on each nested field - (ITL-1371): a nested logical type's identifier is part of what the column holds. - - Struct children are matched by name, a list's item and a map's key and item - followed; no other metadata is restored. - - Args: - arrow_type: The stored Arrow type of a column, or of a nested field. - delta_type: The same column's ``deltalake.schema`` type. - - Returns: - ``arrow_type`` with the nested annotations. - """ - from deltalake.schema import ArrayType, MapType, StructType - - def annotated(field: "pa.Field[Any]", delta_field_type: Any, metadata: Any) -> Any: - keys = { - k: v for k, v in metadata_bytes(metadata).items() if k in _EXTENSION_KEYS - } - inner = _with_extension_annotations(field.type, delta_field_type) - return field.with_type(inner).with_metadata( - cast(Any, {**metadata_bytes(field.metadata), **keys}) - ) - - t = pa.types - if isinstance(delta_type, StructType) and t.is_struct(arrow_type): - by_name = {f.name: f for f in delta_type.fields} - return pa.struct( - [ - annotated(f, by_name[f.name].type, by_name[f.name].metadata) - if f.name in by_name - else f - for f in arrow_type - ] - ) - if isinstance(delta_type, ArrayType) and ( - t.is_list(arrow_type) or t.is_large_list(arrow_type) - ): - # Delta keeps no metadata on a list's element. - item = _with_extension_annotations( - arrow_type.value_type, delta_type.element_type - ) - value_field = arrow_type.value_field.with_type(item) - if t.is_large_list(arrow_type): - return pa.large_list(value_field) - return pa.list_(value_field) - if isinstance(delta_type, MapType) and t.is_map(arrow_type): - return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields - arrow_type.key_field.with_type( - _with_extension_annotations(arrow_type.key_type, delta_type.key_type) - ), - arrow_type.item_field.with_type( - _with_extension_annotations(arrow_type.item_type, delta_type.value_type) - ), - keys_sorted=arrow_type.keys_sorted, - ) - return arrow_type - - -def _without_extension_annotations(arrow_type: Any) -> Any: - """``arrow_type`` with the ``ARROW:extension:*`` keys removed from the metadata of - every nested field: the identifier they hold is compared by - ``logical_identity_change``, the rest of the metadata by ``appended_field_change`` - (ITL-1371).""" - - def bare(field: "pa.Field[Any]") -> "pa.Field[Any]": - metadata = _metadata(field.metadata) - return field.with_type( - _without_extension_annotations(field.type) - ).with_metadata(cast(Any, metadata)) - - t = pa.types - if isinstance(arrow_type, pa.BaseExtensionType): - return arrow_type - if t.is_struct(arrow_type): - return pa.struct([bare(f) for f in arrow_type]) - if t.is_large_list(arrow_type): - return pa.large_list(bare(arrow_type.value_field)) - if t.is_list(arrow_type): - return pa.list_(bare(arrow_type.value_field)) - if t.is_fixed_size_list(arrow_type): - return pa.list_(bare(arrow_type.value_field), arrow_type.list_size) - if t.is_map(arrow_type): - return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields - bare(arrow_type.key_field), - bare(arrow_type.item_field), - keys_sorted=arrow_type.keys_sorted, - ) - return arrow_type - - def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any]"]: """Each stored column as the table holds it: its recorded type, else its stored - type with the nested logical type annotations the log keeps, with its field - metadata as stored. Read from the log; no data is read.""" + type, with its field metadata as stored. Read from the log; no data is read.""" stored = _stored_arrow_schema(delta_table) fields: dict[str, pa.Field[Any]] = {} for delta_field in delta_table.schema().fields: @@ -712,10 +603,7 @@ def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any] delta_field.name, record if record is not None - else _with_extension_annotations( - stored.field(stored.get_field_index(delta_field.name)).type, - delta_field.type, - ), + else stored.field(stored.get_field_index(delta_field.name)).type, nullable=delta_field.nullable, metadata=cast(Any, metadata_bytes(delta_field.metadata)) or None, ) @@ -747,6 +635,64 @@ def _non_null_violation( return None +def _delta_identity_node(delta_type: Any, metadata: Any) -> IdentityNode: + """What the Delta log reliably says of a stored column's logical type + identifiers, at every depth (ITL-1371). + + The log keeps the field metadata written with the column and with each struct + child, byte for byte, so the identifier there is known. A list item and a map key + or item keep no metadata in the log (ITL-1372), and the column's recorded type is + read through the Arrow registry, which may give an identifier other than the one + stored: there the identifier is not known, and the identity rule abstains. + + Args: + delta_type: A ``deltalake.schema`` type from the log. + metadata: Its field's metadata, as the log gives it. + + Returns: + The ``IdentityNode`` of the stored field. + """ + from deltalake.schema import ArrayType, MapType, StructType + + children: dict[str, IdentityNode] = {} + if isinstance(delta_type, StructType): + children = { + f".{f.name}": _delta_identity_node(f.type, f.metadata) + for f in delta_type.fields + } + elif isinstance(delta_type, ArrayType): + children = {"[]": UNKNOWN} + elif isinstance(delta_type, MapType): + children = {".key": UNKNOWN, ".item": UNKNOWN} + as_bytes = metadata_bytes(metadata) + name = as_bytes.get(_EXTENSION_KEYS[0]) + identifier = None if name is None else (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) + return IdentityNode(known=True, identifier=identifier, children=children) + + +def _identity_refusal( + held: Mapping[str, IdentityNode], schema: pa.Schema +) -> tuple[str, str] | None: + """The first column of ``schema`` whose logical type identifier is known to + differ from the held one (``logical_identity_change``, ITL-1371).""" + for field in schema: + if field.name in held: + change = logical_identity_change( + held[field.name], identity_node(field), field.name + ) + if change is not None: + return field.name, change + return None + + +def _stored_identities(delta_table: deltalake.DeltaTable) -> dict[str, IdentityNode]: + """Each stored column's ``_delta_identity_node``, from the log; no data is read.""" + return { + f.name: _delta_identity_node(f.type, f.metadata) + for f in delta_table.schema().fields + } + + def _append_refusal( delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: @@ -755,6 +701,8 @@ def _append_refusal( One rule for what an append is refused for, checked before the rows are buffered and again at flush against the version then loaded: + - a logical type identifier known, from the Delta log, to differ from the stored + one (``logical_identity_change``, ITL-1371); - a column change (``_column_change``): other field attributes, a struct that adds a non-nullable field or one inside a map, or omits a non-nullable one; - a column stored as non-nullable that the rows omit or hold a null in (Delta @@ -770,6 +718,9 @@ def _append_refusal( Returns: ``(column, reason)``, or ``None`` when the rows can be appended. """ + identity = _identity_refusal(_stored_identities(delta_table), rows.schema) + if identity is not None: + return identity held = _held_columns(delta_table) for field in rows.schema: if field.name in held: @@ -1857,7 +1808,10 @@ def _refuse_changed_attributes( attributes: the rows would then be stored, and read back, with another column's attributes. So the field tree of each column (``_column_change``) is compared as given, against the pending batch and the stored table, in every - mode, as an append without schema handling is. + mode, as an append without schema handling is. Before it, a logical type + identifier known to differ from the held one is refused + (``logical_identity_change``, ITL-1371; the stored side as the Delta log + gives it, ``_delta_identity_node``). Args: record_path: The table the rows are for. @@ -1867,15 +1821,28 @@ def _refuse_changed_attributes( InputValidationError: For the first such column, naming it and the path. """ held: list[dict[str, pa.Field[Any]]] = [] + identities: list[dict[str, IdentityNode]] = [] pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: held.append({f.name: f for f in pending.schema}) + identities.append({f.name: identity_node(f) for f in pending.schema}) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: delta_table = None if delta_table is not None: held.append(_held_columns(delta_table)) + identities.append(_stored_identities(delta_table)) + # A known different logical type identifier first (ITL-1371). + for given_identities in identities: + identity = _identity_refusal(given_identities, schema) + if identity is not None: + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: column {identity[0]!r}: " + f"{identity[1]}. The stored rows are unchanged and nothing was " + "written." + ) for given in held: for field in schema: if field.name not in given: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index ae67e7dc0..cb95a87fd 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -4,12 +4,10 @@ import re from collections.abc import Iterable, Mapping +import dataclasses +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast -from orcapod.logical_types.identifier import ( - LogicalTypeIdentifier, - arrow_type_identifier, -) from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -210,118 +208,169 @@ def first_changed_column( _EXTENSION_NAME = b"ARROW:extension:name" _EXTENSION_METADATA = b"ARROW:extension:metadata" +# A logical type identifier as stored: the extension name and metadata, as bytes. +# Compared as bytes only; decoded only to word an error. +RawIdentifier = tuple[bytes, bytes] + + +@dataclass(frozen=True) +class IdentityNode: + """What a database knows of the logical type identifier at one place in a column + (ITL-1371): the column itself, or a nested field. + + Attributes: + known: Whether ``identifier`` is reliably known. A held column read back + through something that may rewrite or drop an identifier (a Delta list + item, map key or item; see ``delta_identity_node``) is not known, and the + rule abstains there. + identifier: The raw identifier, or ``None`` for no logical type. + claims: ``False`` for an untyped null (``pa.null()``) part: it holds no value + and claims no type, so it is never another identifier. + children: The nested places, by path label (``.name`` for a struct child, + ``[]`` for a list item, ``.key`` and ``.item`` for a map, ``|name`` for a + union member, ``{values}`` for dictionary values, ```` for an + extension type held directly as another's storage, ``.name`` for the + other children of a nested type). + """ -def field_logical_identifier(field: "pa.Field[Any]") -> LogicalTypeIdentifier | None: - """The logical type identifier a field carries, in either form (ITL-1371). + known: bool + identifier: RawIdentifier | None + claims: bool = True + children: "dict[str, IdentityNode]" = dataclasses.field(default_factory=dict) - A logical column reaches a database as an Arrow extension type, or as its storage - type annotated with the extension name and metadata in the field metadata (the - form a stored column is read back in, and the form ``ExtensionAwareDatabase`` - passes on). Both forms carry one identifier. - Args: - field: A column or nested field. +UNKNOWN = IdentityNode(known=False, identifier=None) - Returns: - The identifier (extension name and metadata), or ``None`` for a field of no - logical type. - """ - if isinstance(field.type, pa.ExtensionType): - return arrow_type_identifier(field.type) - if isinstance(field.type, pa.BaseExtensionType): - # An extension type defined in Arrow's C++ library (``arrow.uuid``, - # ``arrow.fixed_shape_tensor``) has no ``__arrow_ext_serialize__``: its name - # and metadata are read from its C data interface export, as field metadata - # (arro3, which ``deltalake`` depends on). - from arro3.core import Field as Arro3Field - - exported = metadata_bytes( - Arro3Field.from_arrow(pa.field(field.name, field.type)).metadata - ) - return LogicalTypeIdentifier( - exported[_EXTENSION_NAME].decode(), exported.get(_EXTENSION_METADATA, b"") - ) - metadata = metadata_bytes(field.metadata) - name = metadata.get(_EXTENSION_NAME) + +def _annotation(metadata: Mapping[Any, Any] | None) -> RawIdentifier | None: + as_bytes = metadata_bytes(metadata) + name = as_bytes.get(_EXTENSION_NAME) if name is None: return None - return LogicalTypeIdentifier(name.decode(), metadata.get(_EXTENSION_METADATA, b"")) + return name, as_bytes.get(_EXTENSION_METADATA, b"") -def _identifier_text(identifier: LogicalTypeIdentifier | None) -> str: - return "no logical type" if identifier is None else repr(identifier.text) +def _extension_identifier(arrow_type: Any) -> RawIdentifier: + """The raw identifier of an Arrow extension type.""" + if isinstance(arrow_type, pa.ExtensionType): + return ( + arrow_type.extension_name.encode(), + arrow_type.__arrow_ext_serialize__(), + ) + # An extension type defined in Arrow's C++ library (``arrow.uuid``, + # ``arrow.fixed_shape_tensor``) has no ``__arrow_ext_serialize__``: its name and + # metadata are read from its C data interface export, as field metadata (arro3, + # which ``deltalake`` depends on). + from arro3.core import Field as Arro3Field + exported = _annotation(Arro3Field.from_arrow(pa.field("x", arrow_type)).metadata) + assert exported is not None # an extension type exports its name + return exported -def logical_identity_change( - held: "pa.Field[Any]", incoming: "pa.Field[Any]" -) -> str | None: - """Say why rows of ``incoming`` would be read back as another logical type than - they were written as, appended to a column a database holds as ``held`` - (ITL-1371). - A table holds one logical type per column and per nested field, so the appended - column must carry, at every depth, the logical type identifier the held column - carries (``field_logical_identifier``: extension name and metadata, as an - extension type or as a field annotation; none counts as an identifier too). The - walk follows struct children by name, the items of every list kind, a map's key - and item, and an extension type's storage. Whatever else differs (a type, a - nested field's name or other metadata) is left to the other append checks. +def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: + """The identifiers an Arrow field carries, at every depth, in either form. - The comparison is by identifier, never by Arrow type equality: pyarrow's - equality of two Python extension types ignores their serialized metadata. + A logical type reaches a database as an Arrow extension type, or as its storage + type annotated with ``ARROW:extension:name`` / ``ARROW:extension:metadata`` (the + form a stored column reads back in, and the one ``ExtensionAwareDatabase`` + passes on). Each level is one identifier: an annotation names the field's own + type as storage; an extension type is unwrapped one level, and an extension + type found as storage is a level of its own. The children of every nested Arrow + type are enumerated from the type itself, so no container is a leaf. Args: - held: The column as the database holds it (stored or pending). - incoming: The column of the rows to append. + arrow_field: A column, or a nested field, as given (or as a database holds + it, when what it holds is the field itself). Returns: - The reason, naming the path (``x``, ``x.a``, ``x[]``, ``x.key``) and both - identifiers' text, or ``None``. + The field's ``IdentityNode``; every part known. """ - return _identity_change(held, incoming, incoming.name) + arrow_type = arrow_field.type + if pa.types.is_null(arrow_type): + return IdentityNode(known=True, identifier=None, claims=False) + identifier = _annotation(arrow_field.metadata) + if identifier is not None: + storage = arrow_type + elif isinstance(arrow_type, pa.BaseExtensionType): + identifier = _extension_identifier(arrow_type) + storage = arrow_type.storage_type + else: + storage = arrow_type + return IdentityNode( + known=True, identifier=identifier, children=_children_of(storage) + ) -def _identity_change( - held: "pa.Field[Any]", incoming: "pa.Field[Any]", path: str -) -> str | None: - held_id = field_logical_identifier(held) - incoming_id = field_logical_identifier(incoming) - if held_id != incoming_id: - return ( - f"{path} is of logical type {_identifier_text(incoming_id)}, the stored " - f"column's {_identifier_text(held_id)}" - ) - return _nested_identity_change(_storage(held.type), _storage(incoming.type), path) +def _children_of(arrow_type: Any) -> dict[str, IdentityNode]: + t = pa.types + if isinstance(arrow_type, pa.BaseExtensionType): + return {"": identity_node(pa.field("storage", arrow_type))} + if t.is_dictionary(arrow_type): + return {"{values}": identity_node(pa.field("values", arrow_type.value_type))} + if t.is_map(arrow_type): + return { + ".key": identity_node(arrow_type.key_field), + ".item": identity_node(arrow_type.item_field), + } + if t.is_struct(arrow_type): + return {f".{child.name}": identity_node(child) for child in arrow_type} + if ( + 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 {"[]": identity_node(arrow_type.value_field)} + prefix = "|" if t.is_union(arrow_type) else "." + children = (arrow_type.field(i) for i in range(arrow_type.num_fields)) + return {f"{prefix}{child.name}": identity_node(child) for child in children} + + +def _identifier_text(identifier: RawIdentifier | None) -> str: + if identifier is None: + return "no logical type" + name, metadata = identifier + return repr(f"{name.decode('utf-8', 'replace')};{metadata.hex()}") -def _storage(arrow_type: Any) -> Any: - while isinstance(arrow_type, pa.BaseExtensionType): - arrow_type = arrow_type.storage_type - return arrow_type +def logical_identity_change( + held: IdentityNode, incoming: IdentityNode, path: str +) -> str | None: + """Say why rows of ``incoming`` would be read back as another logical type than + they were written as, appended where a database holds ``held`` (ITL-1371). + A table holds one logical type per column and per nested field, so at every place + both sides have, the appended identifier must be the held one; no logical type is + an identifier too. The rule refuses only where it knows: wherever the held + identifier is not reliably known, or a side is an untyped null, it abstains at + that place, and a place only one side has (struct evolution, another kind of + type) is left to the database's other append checks. It compares raw bytes, + never Arrow type equality: pyarrow's equality of two instances of one Python + extension class ignores their serialized metadata. -def _nested_identity_change(held: Any, incoming: Any, path: str) -> str | None: - t = pa.types - if t.is_struct(held) and t.is_struct(incoming): - known = {f.name: f for f in held} - for field in incoming: - if field.name in known: - found = _identity_change( - known[field.name], field, f"{path}.{field.name}" - ) - if found is not None: - return found + Args: + held: What the database holds (stored or pending). + incoming: The rows to append, as given (``identity_node``). + path: The column name, or the path of the nested place. + + Returns: + The reason, naming the path and both identifiers' text, or ``None``. + """ + if not (held.claims and incoming.claims): return None - if t.is_map(held) and t.is_map(incoming): - return _identity_change( - held.key_field, incoming.key_field, f"{path}.key" - ) or _identity_change(held.item_field, incoming.item_field, f"{path}.item") - lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) - if any(k(held) for k in lists) and any(k(incoming) for k in lists): - # cast: the type guards above narrow the types in the stubs' terms. - return _identity_change( - cast(Any, held).value_field, cast(Any, incoming).value_field, f"{path}[]" + if held.known and incoming.known and held.identifier != incoming.identifier: + return ( + f"{path} is of logical type {_identifier_text(incoming.identifier)}, the " + f"stored column's {_identifier_text(held.identifier)}" ) + for label, child in incoming.children.items(): + held_child = held.children.get(label) + if held_child is not None: + found = logical_identity_change(held_child, child, f"{path}{label}") + if found is not None: + return found return None @@ -329,9 +378,11 @@ def first_logical_identity_change( held: "Iterable[pa.Schema]", schema: "pa.Schema" ) -> tuple[str, str] | None: """The first column of ``schema`` that carries another logical type identifier - than a column of that name the database holds (``logical_identity_change``). + than a column of that name the database holds, as given (``identity_node``). - Columns are matched by name; the order of either schema plays no part. + For a database that holds what it was given (in-memory, a pending batch, a + connector's stored schema). Columns are matched by name; the order of either + schema plays no part. Args: held: The schemas the database holds for the table (stored, pending). @@ -341,12 +392,15 @@ def first_logical_identity_change( The column's name and the reason, or ``None``. """ held = list(held) - for field in schema: + for given_field in schema: + incoming = identity_node(given_field) for given in held: - index = given.get_field_index(field.name) + index = given.get_field_index(given_field.name) if index < 0: continue - reason = logical_identity_change(given.field(index), field) + reason = logical_identity_change( + identity_node(given.field(index)), incoming, given_field.name + ) if reason is not None: - return field.name, reason + return given_field.name, reason return None diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index fb653d92c..161d99614 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -16,7 +16,7 @@ import itertools from collections.abc import Iterator from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest @@ -29,12 +29,13 @@ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.utils import ( - field_logical_identifier, first_logical_identity_change, + identity_node, logical_identity_change, ) from orcapod.errors import InputValidationError from orcapod.logical_types.identifier import LogicalTypeIdentifier +from orcapod.logical_types.registry import make_arrow_extension_type from orcapod.logical_types.registry import LogicalTypeRegistry from orcapod.semantic_types.universal_converter import UniversalTypeConverter from tests.test_databases import fake_pyspiral @@ -191,15 +192,18 @@ def _supported(kind: str, form: str, depth: str) -> bool: return True -def _loses_nested_extension(kind: str, state: str, form: str, depth: str) -> bool: - """Delta writes a list item or map value of an extension type as plain storage - (ITL-1372): a committed table no longer holds the identifier, so only refusals - are asserted there. (A struct child keeps its annotation in the Delta log.)""" +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 ( - kind == "Delta" - and form == "extension" - and depth in ("list", "map value") - and state != "pending" + _abstains(kind, state, depth) and form == "extension" and depth == "map value" ) @@ -219,15 +223,14 @@ def _loses_nested_extension(kind: str, state: str, form: str, depth: str) -> boo pytest.param(*case, change, id=f"{'-'.join(case)}-{change}") for case in BASE for change in CHANGES - # A plain column over a Delta column that lost its nested type (ITL-1372) is not - # another identifier: the held column is plain too. - if not (_loses_nested_extension(*case) and CHANGES[change] is None) + if not _main_accepts(*case) ] SAME_CASES = [ pytest.param(*case, id="-".join(case)) for case in BASE - if not _loses_nested_extension(*case) # pinned by the ITL-1372 test below + # 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")) ] @@ -265,12 +268,12 @@ def test_another_identifier_is_refused( message = str(refused.value) assert "column 'x'" in message assert "othing was written" in message - lost = _loses_nested_extension(kind, state, form, depth) - assert (repr(_text(HELD)) if not lost else "no logical type") in message - identifier = CHANGES[change] - assert ( - repr(_text(identifier)) if identifier is not None else "no logical type" - ) 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 # Nothing was buffered, and the held rows are unchanged. _assert_only_held_rows(store) @@ -287,11 +290,19 @@ def test_same_identifier_is_accepted( assert store.stored().num_rows == 3 +LOGICAL_OVER_PLAIN = [ + pytest.param(kind, state, form, depth, id=f"{kind}-{state}-{form}-{depth}") + for kind, state, form, depth in itertools.product( + ("in-memory", "Delta"), ("pending", "committed"), FORMS, DEPTHS + ) + # The rule abstains at a stored Delta list or map item; main accepts extension + # values there. + if not (_abstains(kind, state, depth) and form == "extension") +] + + @pytest.mark.parametrize("via", ["direct", "wrapper"]) -@pytest.mark.parametrize("form", FORMS) -@pytest.mark.parametrize("depth", DEPTHS) -@pytest.mark.parametrize("state", ["pending", "committed"]) -@pytest.mark.parametrize("kind", ["in-memory", "Delta"]) +@pytest.mark.parametrize(("kind", "state", "form", "depth"), LOGICAL_OVER_PLAIN) def test_a_logical_type_over_a_plain_column_is_refused( tmp_path: Path, kind: str, state: str, form: str, depth: str, via: str ) -> None: @@ -302,49 +313,51 @@ def test_a_logical_type_over_a_plain_column_is_refused( record_id_column="id", flush=state == "committed", ) - with pytest.raises( - InputValidationError, match="the stored column's no logical" - ): + match = None if _abstains(kind, state, depth) else "stored column's no logical" + with pytest.raises(InputValidationError, match=match): _through(store.db, via).add_records( PATH, _rows(HELD, form, depth, [b"22"]), record_id_column="id" ) assert store.stored().column("id").to_pylist() == [b"1"] -@pytest.mark.parametrize("depth", ["list", "map value"]) -def test_delta_nested_extension_second_append_is_refused( - tmp_path: Path, depth: str +@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 a consequence of ITL-1372; revisit there. - - Delta writes a list item or map value of an extension type as plain storage on - the first write: the first write is accepted and reads back plain. On main a - second append of the same type to the committed table was accepted and stored as - plain storage too (the map; the list was refused for its item's name); it is now - refused, because the held column has no logical type. A same-type append to the - pending batch is still accepted. + """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. """ - db = DeltaTableDatabase(tmp_path / "delta") - 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() - stored = db.get_all_records(PATH, record_id_column="id") - assert stored is not None and stored.num_rows == 2 - leaf = stored.schema.field("x").type - leaf_field = leaf.value_field if depth == "list" else leaf.item_field - assert field_logical_identifier(leaf_field) is None # read back plain - with pytest.raises(InputValidationError) as refused: - db.add_records( - PATH, _rows(HELD, "extension", depth, [b"333"]), record_id_column="id" - ) - assert f"of logical type {_text(HELD)!r}, the stored column's no logical type" in ( - str(refused.value) - ) - db.flush() - after = db.get_all_records(PATH, record_id_column="id") - assert after is not None and after.num_rows == 2 + 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: @@ -375,27 +388,31 @@ def test_the_reproducer_through_the_wrapper(tmp_path: Path) -> None: # --------------------------------------------------------------------------- +def _change(held: "pa.Field[Any]", incoming: "pa.Field[Any]") -> str | None: + return logical_identity_change( + identity_node(held), identity_node(incoming), incoming.name + ) + + def test_identifier_is_read_from_either_form() -> None: ext = EXTENSIONS["itl1371.a"](b"m") annotated = pa.field( "x", pa.large_string(), metadata={NAME: b"itl1371.a", META: b"m"} ) - assert field_logical_identifier(pa.field("x", ext)) == LogicalTypeIdentifier( - "itl1371.a", b"m" - ) - assert field_logical_identifier(annotated) == LogicalTypeIdentifier( - "itl1371.a", b"m" - ) - assert field_logical_identifier(pa.field("x", pa.large_string())) is None + assert identity_node(pa.field("x", ext)).identifier == (b"itl1371.a", b"m") + assert identity_node(annotated).identifier == (b"itl1371.a", b"m") + assert identity_node(pa.field("x", pa.large_string())).identifier is None # The two forms of one identifier are one identifier. - assert logical_identity_change(annotated, pa.field("x", ext)) is None + assert _change(annotated, pa.field("x", ext)) is None + # Arrow's own extension types too. + assert identity_node(pa.field("x", pa.uuid())).identifier == (b"arrow.uuid", b"") def test_pyarrow_equality_does_not_decide() -> None: """pyarrow's equality of two Python extension types ignores their metadata.""" m, n = EXTENSIONS["itl1371.a"](b"m"), EXTENSIONS["itl1371.a"](b"n") assert m == n # what the rule must not rely on - assert logical_identity_change(pa.field("x", m), pa.field("x", n)) is not None + assert _change(pa.field("x", m), pa.field("x", n)) is not None @pytest.mark.parametrize( @@ -433,8 +450,8 @@ def map_field(identifier: tuple[str, bytes]) -> "pa.Field[Any]": item = pa.field("value", pa.int64()) return pa.field("x", pa.map_(key, item)) # pyright: ignore[reportArgumentType] # pyarrow takes key/item fields - assert logical_identity_change(map_field(HELD), map_field(HELD)) is None - reason = logical_identity_change(map_field(HELD), map_field(("itl1371.a", b"n"))) + assert _change(map_field(HELD), map_field(HELD)) is None + reason = _change(map_field(HELD), map_field(("itl1371.a", b"n"))) assert reason is not None and reason.startswith("x.key ") @@ -488,3 +505,352 @@ def test_delta_other_nested_metadata_beside_an_identifier_is_still_refused( ) 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( + [pa.array(ids, pa.large_binary()), struct], + schema=pa.schema( + [pa.field("id", pa.large_binary()), pa.field("x", struct.type)] + ), + ) + + +@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.""" + 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 + + +def _readable_type() -> Any: + """A registered logical type that writes ``b"new"`` and also reads ``b"old"``.""" + ext_class: Any = make_arrow_extension_type( + "itl1371.readable", pa.large_string(), b"new", also_reads=(b"old",) + ) + try: + pa.register_extension_type(ext_class()) + except pa.ArrowKeyError: + pass # registered by an earlier test in this process + return ext_class + + +def _annotated_nested(meta: bytes, depth: str, ids: list[bytes]) -> pa.Table: + field = pa.field( + "v", pa.large_string(), metadata={NAME: b"itl1371.readable", META: meta} + ) + array = pa.array([i.decode() for i in ids], pa.large_string()) + if depth == "struct": + return _struct_of(field, array, ids) + list_type = pa.large_list(field.with_name("item")) + lists = pa.LargeListArray.from_arrays( + pa.array(range(len(ids) + 1), pa.int64()), array, type=list_type + ) + 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)]), + ) + + +@pytest.mark.parametrize("depth", ["struct", "list"]) +@pytest.mark.parametrize( + ("held", "given"), [(b"old", b"new"), (b"old", b"old"), (b"new", b"new")] +) +def test_delta_registered_nested_type_decides_by_raw_bytes( + tmp_path: Path, depth: str, held: bytes, given: bytes +) -> None: + """A registered logical type nested in a Delta column with a recorded type. + + The identity rule decides by the raw stored bytes, which the Delta log keeps for + a struct child: ``old`` then ``new`` is refused naming both. It cannot know them + for a list item (the log keeps none, and the recorded type is read through the + registry, which gives ``new`` for ``old``), so it abstains there. Every case is + refused, as on main: main's field-metadata check compares the given annotation + with the recorded type as the registry reads it, an extension type, so it refuses + even an identical second append (pre-existing; reported with ITL-1372). + """ + _readable_type() + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, + _annotated_nested(held, depth, [b"1"]), + record_id_column="id", + flush=True, + ) + store.reopen() + with pytest.raises(InputValidationError) as refused: + store.db.add_records( + PATH, _annotated_nested(given, depth, [b"22"]), record_id_column="id" + ) + message = str(refused.value) + if depth == "struct" and held != given: + assert f"x.v is of logical type {_raw_text(given)}" in message + assert f"the stored column's {_raw_text(held)}" in message + else: + assert "has other field metadata" in message + assert store.stored().column("id").to_pylist() == [b"1"] + + +def _raw_text(meta: bytes) -> str: + return repr(f"itl1371.readable;{meta.hex()}") + + +def _wrapped(meta: bytes, values: list[str]) -> Any: + ext = EXTENSIONS["itl1371.a"](meta) + return ext.wrap_array(pa.array(values, pa.large_string())) + + +# The stubs know only some of these constructors' signatures. +_LIST_VIEW: Any = pa.ListViewArray +_LARGE_LIST_VIEW: Any = pa.LargeListViewArray + +CONTAINERS: dict[str, Any] = { + "list_view": lambda a: _LIST_VIEW.from_arrays( + pa.array(range(len(a)), pa.int32()), pa.array([1] * len(a), pa.int32()), a + ), + "large_list_view": lambda a: _LARGE_LIST_VIEW.from_arrays( + pa.array(range(len(a)), pa.int64()), pa.array([1] * len(a), pa.int64()), a + ), + "sparse union": lambda a: pa.UnionArray.from_sparse( + pa.array([0] * len(a), pa.int8()), [a], ["v"] + ), + "dense union": lambda a: pa.UnionArray.from_dense( + pa.array([0] * len(a), pa.int8()), + pa.array(range(len(a)), pa.int32()), + [a], + ["v"], + ), + "dictionary": lambda a: pa.DictionaryArray.from_arrays( + pa.array(range(len(a)), pa.int8()), a + ), + # Run-end encoded extension values cannot be combined by pyarrow; the values are + # a struct whose child carries the identifier as an annotation. + "run-end encoded": lambda a: pa.RunEndEncodedArray.from_arrays( + pa.array(range(1, len(a) + 1), pa.int16()), + pa.StructArray.from_arrays( + [a.storage], + fields=[ + pa.field( + "v", + pa.large_string(), + metadata={ + NAME: a.type.extension_name.encode(), + META: a.type.__arrow_ext_serialize__(), + }, + ) + ], + ), + ), +} + + +def _outer_class() -> Any: + """An extension type whose storage is directly another extension type.""" + + class _Outer(pa.ExtensionType): + def __init__(self, storage: Any) -> None: + super().__init__(storage, "itl1371.outer") + + def __arrow_ext_serialize__(self) -> bytes: + return b"outer" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(storage_type) + + return _Outer + + +_OUTER = _outer_class() +CONTAINERS["extension in extension"] = lambda a: _OUTER(a.type).wrap_array(a) + + +def _container_rows(container: str, meta: bytes, ids: list[bytes]) -> pa.Table: + column = CONTAINERS[container](_wrapped(meta, [i.decode() for i in ids])) + return pa.table({"id": pa.array(ids, pa.large_binary()), "x": column}) + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +@pytest.mark.parametrize("container", list(CONTAINERS)) +def test_every_container_is_walked(tmp_path: Path, container: str, state: str) -> None: + """An identifier under any nested Arrow type is compared (in-memory, which keeps + them all): the same identifier is appended and reads back, another is refused.""" + db = InMemoryArrowDatabase() + db.add_records( + PATH, + _container_rows(container, b"m", [b"1"]), + record_id_column="id", + flush=state == "committed", + ) + held_ids = [b"1"] + if container != "dictionary": + # (pyarrow cannot unify two dictionaries of extension values at the flush.) + db.add_records( + PATH, _container_rows(container, b"m", [b"22"]), record_id_column="id" + ) + held_ids.append(b"22") + with pytest.raises(InputValidationError, match="itl1371.a;6e"): + db.add_records( + PATH, _container_rows(container, b"n", [b"333"]), record_id_column="id" + ) + 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())) == held_ids + assert ( + stored.schema.field("x").type + == _container_rows(container, b"m", [b"1"]).schema.field("x").type + ) + + +def test_delta_dictionary_of_extension_values(tmp_path: Path) -> None: + """Delta decodes a dictionary column and stores its values as plain storage: a + pending batch is compared as given (another identifier refused); once stored, the + log names no identifier for the values, so the rule abstains and main's verdict + stands (accepted, read back as 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\\{values\\}"): + store.db.add_records( + PATH, + _container_rows("dictionary", b"n", [b"22"]), + record_id_column="id", + ) + store.db.flush() + store.db.add_records( + PATH, _container_rows("dictionary", b"n", [b"333"]), record_id_column="id" + ) + stored = store.stored() + assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ + b"1", + b"333", + ] + assert identity_node(stored.schema.field("x")).identifier is None + + +@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 +) -> 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}) + array = pa.array([i.decode() for i in ids], pa.large_string()) + return _struct_of(field, array, ids) + + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, rows(b"a", [b"1"]), record_id_column="id", flush=state != "pending" + ) + if state == "reopened": + store.reopen() + with pytest.raises(InputValidationError, match="x.v has other field metadata"): + store.db.add_records(PATH, rows(b"b", [b"22"]), record_id_column="id") + assert store.stored().column("id").to_pylist() == [b"1"] + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +def test_identifiers_are_compared_as_bytes(state: str) -> None: + """An extension name that is not UTF-8: identical bytes are one identifier (the + second append is accepted, as on main); other bytes are refused, the error + naming the name with replacement characters.""" + + def rows(meta: bytes, ids: list[bytes]) -> pa.Table: + field = pa.field("x", pa.large_string(), metadata={NAME: b"\xff", META: meta}) + return pa.Table.from_arrays( + [ + pa.array(ids, pa.large_binary()), + pa.array(["v"] * len(ids), pa.large_string()), + ], + schema=pa.schema([pa.field("id", pa.large_binary()), field]), + ) + + db = InMemoryArrowDatabase() + db.add_records( + PATH, rows(b"a", [b"1"]), record_id_column="id", flush=state == "committed" + ) + db.add_records(PATH, rows(b"a", [b"22"]), record_id_column="id") + with pytest.raises(InputValidationError, match="\ufffd;62"): + db.add_records(PATH, rows(b"b", [b"333"]), record_id_column="id") + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.num_rows == 2 + + +@pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) +@pytest.mark.parametrize("state", ["committed", "reopened"]) +def test_delta_untyped_null_over_a_logical_column( + tmp_path: Path, state: str, schema_handling: str +) -> None: + """An untyped null column holds no value and claims no type: it is resolved to the + held type and stored as a null, as on main, in every schema handling mode.""" + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, + _rows(HELD, "annotated", "top", [b"1"]), + record_id_column="id", + flush=True, + ) + if state == "reopened": + store.reopen() + nulls = pa.table( + { + "a": pa.array([1], pa.int64()), + "id": pa.array([b"22"], pa.large_binary()), + "x": pa.nulls(1), + } + ) + store.db.add_records( + PATH, nulls, record_id_column="id", schema_handling=schema_handling + ) + stored = store.stored().sort_by("id") + assert stored.column("x").to_pylist() == ["1", None] + assert identity_node(stored.schema.field("x")).identifier == ( + HELD[0].encode(), + HELD[1], + ) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 603e11f43..a9d098308 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -53,7 +53,7 @@ SpiralDBConnector, ) from orcapod.databases.delta_arrow_types import _is_recorded # pyright: ignore[reportPrivateUsage] -from orcapod.databases.utils import field_logical_identifier +from orcapod.databases.utils import identity_node from orcapod.utils.arrow_utils import normalize_to_large_types KEPT = "KEPT" @@ -819,11 +819,11 @@ def _other_identifier(field: "pa.Field[Any]", column: Any) -> tuple[Any, Any]: (ITL-1371). Not the same name with other metadata: a registered type's unreadable metadata is refused before the append is compared.""" ext = cast("pa.BaseExtensionType", field.type) - identifier = field_logical_identifier(field) + identifier = identity_node(field).identifier assert identifier is not None metadata = { - b"ARROW:extension:name": f"{identifier.name}.other".encode(), - b"ARROW:extension:metadata": identifier.metadata, + b"ARROW:extension:name": identifier[0] + b".other", + b"ARROW:extension:metadata": identifier[1], } chunked: Any = pa.chunked_array # the stubs type ``type=`` as None storage = chunked([chunk.storage for chunk in column.chunks], type=ext.storage_type) From e940c72b19f1cf71228bd91ffbe27dd28f574d47 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:01:20 -0800 Subject: [PATCH 04/14] fix(databases): identity rule looks through dictionaries, pairs repeated names (ITL-1371) Review round 2 of PR 492: - A dictionary is an encoding: its values stand where it stands, so a dictionary of the stored type is accepted and a dictionary of structs with another child identifier is refused. - Places pair by name, or by occurrence where a name repeats among siblings or columns; never by name alone. - An extension type's bytes are those Arrow holds (its C data interface export), not its serializer called again; the serializer only for an extension whose storage is another extension, which Arrow cannot export. - Only a bare null claims no type; an annotated null claims its annotation. - A name that is not UTF-8 is shown in hex in the error. Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 19 +- src/orcapod/databases/delta_lake_databases.py | 46 +-- src/orcapod/databases/utils.py | 178 +++++++---- .../test_logical_identity_appends.py | 290 ++++++++++++++++-- 4 files changed, 420 insertions(+), 113 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 81e80eea0..1c936ef4f 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -27,10 +27,16 @@ as the stored type, a type it was never written as: (`identity_node` for a field as given, `first_logical_identity_change` for schemas): at every column and nested place (struct children by name, list items of every kind including list views, map keys and items, union members, dictionary values, run-end encoded children, and -an extension type held directly as another's storage, one extension level at a time), the -raw identifier bytes (an extension type's name and serialized metadata, or the -`ARROW:extension:*` annotation; never decoded to decide, never Arrow type equality) must be -the held ones; no logical type is an identifier too. +an extension type held directly as another's storage, one extension level at a time; a +dictionary is an encoding, so its values stand where it stands), the raw identifier bytes +must be the held ones; no logical type is an identifier too. The bytes are those Arrow holds +(an extension type's C data interface export, never its serializer called again; the +serializer only for an extension type whose storage is another extension type, which Arrow +cannot export) or the `ARROW:extension:*` annotation; never decoded to decide (a name that +is not UTF-8 is shown in hex), never Arrow type equality. Places pair by name, or by +occurrence where a name repeats among siblings (Arrow allows two struct children, union +members or columns of one name), never by name alone. Only a bare `pa.null()` claims no +type; an annotated null claims its annotation. The rule only ADDS a refusal where it KNOWS the identifiers differ: from the fields as given (in-memory, a pending batch, a connector's stored schema) and, for a stored Delta table, from @@ -52,6 +58,9 @@ name, which every database refuses. So the only appends whose verdict differs from main are those with a known different identifier. Where Delta stored a nested extension type as plain storage (a list item or map value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with -any identifier, a second list refused for its item's name). Also pre-existing (ITL-1372): +any identifier, a second list refused for its item's name). Delta stores a dictionary of +extension values as plain values with no identifier in the log (as on main), so a logical +append to such a column, even another dictionary of the same type, is refused as one over +any plain column. Also pre-existing (ITL-1372): Delta refuses any second append of a registered logical type nested in a column with a recorded type, even the identical one. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 114cd8d0e..37268e48a 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -4,7 +4,7 @@ import os import sys from collections import defaultdict -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast @@ -23,6 +23,7 @@ coerce_record_id, identity_node, logical_identity_change, + matched_pairs, metadata_bytes, ) from orcapod.errors import ( @@ -654,16 +655,16 @@ def _delta_identity_node(delta_type: Any, metadata: Any) -> IdentityNode: """ from deltalake.schema import ArrayType, MapType, StructType - children: dict[str, IdentityNode] = {} + children: tuple[tuple[str, IdentityNode], ...] = () if isinstance(delta_type, StructType): - children = { - f".{f.name}": _delta_identity_node(f.type, f.metadata) + children = tuple( + (f".{f.name}", _delta_identity_node(f.type, f.metadata)) for f in delta_type.fields - } + ) elif isinstance(delta_type, ArrayType): - children = {"[]": UNKNOWN} + children = (("[]", UNKNOWN),) elif isinstance(delta_type, MapType): - children = {".key": UNKNOWN, ".item": UNKNOWN} + children = ((".key", UNKNOWN), (".item", UNKNOWN)) as_bytes = metadata_bytes(metadata) name = as_bytes.get(_EXTENSION_KEYS[0]) identifier = None if name is None else (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) @@ -671,26 +672,27 @@ def _delta_identity_node(delta_type: Any, metadata: Any) -> IdentityNode: def _identity_refusal( - held: Mapping[str, IdentityNode], schema: pa.Schema + held: "Sequence[tuple[str, IdentityNode]]", schema: pa.Schema ) -> tuple[str, str] | None: """The first column of ``schema`` whose logical type identifier is known to - differ from the held one (``logical_identity_change``, ITL-1371).""" - for field in schema: - if field.name in held: - change = logical_identity_change( - held[field.name], identity_node(field), field.name - ) - if change is not None: - return field.name, change + differ from the held one (``logical_identity_change``, ITL-1371); columns pair + as ``matched_pairs`` says (by name, or by occurrence where a name repeats).""" + given = [(f.name, identity_node(f)) for f in schema] + for name, held_node, node in matched_pairs(held, given): + change = logical_identity_change(held_node, node, name) + if change is not None: + return name, change return None -def _stored_identities(delta_table: deltalake.DeltaTable) -> dict[str, IdentityNode]: +def _stored_identities( + delta_table: deltalake.DeltaTable, +) -> list[tuple[str, IdentityNode]]: """Each stored column's ``_delta_identity_node``, from the log; no data is read.""" - return { - f.name: _delta_identity_node(f.type, f.metadata) + return [ + (f.name, _delta_identity_node(f.type, f.metadata)) for f in delta_table.schema().fields - } + ] def _append_refusal( @@ -1821,11 +1823,11 @@ def _refuse_changed_attributes( InputValidationError: For the first such column, naming it and the path. """ held: list[dict[str, pa.Field[Any]]] = [] - identities: list[dict[str, IdentityNode]] = [] + identities: list[list[tuple[str, IdentityNode]]] = [] pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: held.append({f.name: f for f in pending.schema}) - identities.append({f.name: identity_node(f) for f in pending.schema}) + identities.append([(f.name, identity_node(f)) for f in pending.schema]) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index cb95a87fd..6c95619b7 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -3,10 +3,9 @@ from __future__ import annotations import re -from collections.abc import Iterable, Mapping -import dataclasses +from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any, TypeVar, cast from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -18,6 +17,8 @@ else: pa = LazyModule("pyarrow") +T = TypeVar("T") + def coerce_record_id(record_id: str | bytes) -> bytes: """Encode ``record_id`` to bytes if it is a ``str``. @@ -221,22 +222,24 @@ class IdentityNode: Attributes: known: Whether ``identifier`` is reliably known. A held column read back through something that may rewrite or drop an identifier (a Delta list - item, map key or item; see ``delta_identity_node``) is not known, and the - rule abstains there. + item, map key or item; see ``_delta_identity_node``) is not known, and + the rule abstains there. identifier: The raw identifier, or ``None`` for no logical type. - claims: ``False`` for an untyped null (``pa.null()``) part: it holds no value - and claims no type, so it is never another identifier. - children: The nested places, by path label (``.name`` for a struct child, - ``[]`` for a list item, ``.key`` and ``.item`` for a map, ``|name`` for a - union member, ``{values}`` for dictionary values, ```` for an - extension type held directly as another's storage, ``.name`` for the - other children of a nested type). + claims: ``False`` for a bare untyped null (``pa.null()`` with no + annotation): it holds no value and claims no type, so it is never + another identifier. + children: The nested places, in order, each with its label (``.name`` for a + struct child, ``[]`` for a list item, ``.key`` and ``.item`` for a map, + ``|name`` for a union member, ```` for an extension type held + directly as another's storage, ``.name`` for the other children of a + nested type). Labels may repeat: Arrow allows two struct children or + union members of one name. """ known: bool identifier: RawIdentifier | None claims: bool = True - children: "dict[str, IdentityNode]" = dataclasses.field(default_factory=dict) + children: "tuple[tuple[str, IdentityNode], ...]" = () UNKNOWN = IdentityNode(known=False, identifier=None) @@ -251,21 +254,28 @@ def _annotation(metadata: Mapping[Any, Any] | None) -> RawIdentifier | None: def _extension_identifier(arrow_type: Any) -> RawIdentifier: - """The raw identifier of an Arrow extension type.""" - if isinstance(arrow_type, pa.ExtensionType): - return ( - arrow_type.extension_name.encode(), - arrow_type.__arrow_ext_serialize__(), - ) - # An extension type defined in Arrow's C++ library (``arrow.uuid``, - # ``arrow.fixed_shape_tensor``) has no ``__arrow_ext_serialize__``: its name and - # metadata are read from its C data interface export, as field metadata (arro3, - # which ``deltalake`` depends on). + """The raw identifier an Arrow extension type holds. + + Read from the type's C data interface export, where Arrow writes the extension + name and the serialized metadata it holds (arro3, which ``deltalake`` depends + on), never by calling ``__arrow_ext_serialize__`` again: a Python extension + type's serializer may give other bytes than the ones Arrow took when the type + was made, and the export is also the only way to read the bytes of an extension + type defined in Arrow's C++ library (``arrow.uuid``). Arrow cannot export an + extension type whose storage is itself an extension type; for that one, and + only that one, the Python serializer is asked. + """ from arro3.core import Field as Arro3Field - exported = _annotation(Arro3Field.from_arrow(pa.field("x", arrow_type)).metadata) - assert exported is not None # an extension type exports its name - return exported + try: + exported = Arro3Field.from_arrow(pa.field("x", arrow_type)).metadata + except pa.ArrowNotImplementedError: + if not isinstance(arrow_type, pa.ExtensionType): + raise + return arrow_type.extension_name.encode(), arrow_type.__arrow_ext_serialize__() + identifier = _annotation(exported) + assert identifier is not None # an extension type exports its name + return identifier def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: @@ -276,8 +286,9 @@ def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: form a stored column reads back in, and the one ``ExtensionAwareDatabase`` passes on). Each level is one identifier: an annotation names the field's own type as storage; an extension type is unwrapped one level, and an extension - type found as storage is a level of its own. The children of every nested Arrow - type are enumerated from the type itself, so no container is a leaf. + type found as storage is a level of its own. A dictionary is an encoding, not a + type: its values stand where it stands. The children of every nested Arrow type + are enumerated from the type itself, so no container is a leaf. Args: arrow_field: A column, or a nested field, as given (or as a database holds @@ -287,9 +298,14 @@ def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: The field's ``IdentityNode``; every part known. """ arrow_type = arrow_field.type - if pa.types.is_null(arrow_type): - return IdentityNode(known=True, identifier=None, claims=False) + if pa.types.is_dictionary(arrow_type): + return identity_node(arrow_field.with_type(arrow_type.value_type)) identifier = _annotation(arrow_field.metadata) + if pa.types.is_null(arrow_type): + # A bare null claims nothing; an annotated one claims its annotation. + return IdentityNode( + known=True, identifier=identifier, claims=identifier is not None + ) if identifier is not None: storage = arrow_type elif isinstance(arrow_type, pa.BaseExtensionType): @@ -302,19 +318,17 @@ def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: ) -def _children_of(arrow_type: Any) -> dict[str, IdentityNode]: +def _children_of(arrow_type: Any) -> "tuple[tuple[str, IdentityNode], ...]": t = pa.types - if isinstance(arrow_type, pa.BaseExtensionType): - return {"": identity_node(pa.field("storage", arrow_type))} if t.is_dictionary(arrow_type): - return {"{values}": identity_node(pa.field("values", arrow_type.value_type))} + return _children_of(arrow_type.value_type) + if isinstance(arrow_type, pa.BaseExtensionType): + return (("", identity_node(pa.field("storage", arrow_type))),) if t.is_map(arrow_type): - return { - ".key": identity_node(arrow_type.key_field), - ".item": identity_node(arrow_type.item_field), - } - if t.is_struct(arrow_type): - return {f".{child.name}": identity_node(child) for child in arrow_type} + return ( + (".key", identity_node(arrow_type.key_field)), + (".item", identity_node(arrow_type.item_field)), + ) if ( t.is_list(arrow_type) or t.is_large_list(arrow_type) @@ -322,17 +336,56 @@ def _children_of(arrow_type: Any) -> dict[str, IdentityNode]: or t.is_list_view(arrow_type) or t.is_large_list_view(arrow_type) ): - return {"[]": identity_node(arrow_type.value_field)} + return (("[]", identity_node(arrow_type.value_field)),) prefix = "|" if t.is_union(arrow_type) else "." children = (arrow_type.field(i) for i in range(arrow_type.num_fields)) - return {f"{prefix}{child.name}": identity_node(child) for child in children} + return tuple((f"{prefix}{child.name}", identity_node(child)) for child in children) + + +def _name_text(name: bytes) -> str: + try: + return name.decode() + except UnicodeDecodeError: + return f"0x{name.hex()}" # not text: shown as its bytes def _identifier_text(identifier: RawIdentifier | None) -> str: if identifier is None: return "no logical type" name, metadata = identifier - return repr(f"{name.decode('utf-8', 'replace')};{metadata.hex()}") + return repr(f"{_name_text(name)};{metadata.hex()}") + + +def matched_pairs( + held: "Sequence[tuple[str, T]]", incoming: "Sequence[tuple[str, T]]" +) -> "list[tuple[str, T, T]]": + """Pair the labelled places of two sides (ITL-1371). + + A label that occurs once on each side pairs by label. Where a label repeats on + either side (Arrow allows two struct children, union members or columns of one + name), its places pair by occurrence: the k-th with the k-th. Never by label + alone, so a repeated place is never overwritten by another of its name. A place + without a partner is left out. + + Args: + held: The held side's places, in order, with their labels. + incoming: The given side's places, in order, with their labels. + + Returns: + ``(label, held place, given place)`` for every pair, in the given order. + """ + by_label: dict[str, list[T]] = {} + for label, place in held: + by_label.setdefault(label, []).append(place) + seen: dict[str, int] = {} + pairs: list[tuple[str, T, T]] = [] + for label, place in incoming: + k = seen.get(label, 0) + seen[label] = k + 1 + candidates = by_label.get(label, []) + if k < len(candidates): + pairs.append((label, candidates[k], place)) + return pairs def logical_identity_change( @@ -344,11 +397,12 @@ def logical_identity_change( A table holds one logical type per column and per nested field, so at every place both sides have, the appended identifier must be the held one; no logical type is an identifier too. The rule refuses only where it knows: wherever the held - identifier is not reliably known, or a side is an untyped null, it abstains at - that place, and a place only one side has (struct evolution, another kind of + identifier is not reliably known, or a side is a bare untyped null, it abstains + at that place, and a place only one side has (struct evolution, another kind of type) is left to the database's other append checks. It compares raw bytes, never Arrow type equality: pyarrow's equality of two instances of one Python - extension class ignores their serialized metadata. + extension class ignores their serialized metadata. Places pair as + ``matched_pairs`` says. Args: held: What the database holds (stored or pending). @@ -365,12 +419,10 @@ def logical_identity_change( f"{path} is of logical type {_identifier_text(incoming.identifier)}, the " f"stored column's {_identifier_text(held.identifier)}" ) - for label, child in incoming.children.items(): - held_child = held.children.get(label) - if held_child is not None: - found = logical_identity_change(held_child, child, f"{path}{label}") - if found is not None: - return found + for label, held_child, child in matched_pairs(held.children, incoming.children): + found = logical_identity_change(held_child, child, f"{path}{label}") + if found is not None: + return found return None @@ -378,11 +430,12 @@ def first_logical_identity_change( held: "Iterable[pa.Schema]", schema: "pa.Schema" ) -> tuple[str, str] | None: """The first column of ``schema`` that carries another logical type identifier - than a column of that name the database holds, as given (``identity_node``). + than the column the database holds in its place, as given (``identity_node``). For a database that holds what it was given (in-memory, a pending batch, a - connector's stored schema). Columns are matched by name; the order of either - schema plays no part. + connector's stored schema). Columns pair as ``matched_pairs`` says: by name, or + by occurrence where a name repeats; the order of columns of distinct names plays + no part. Args: held: The schemas the database holds for the table (stored, pending). @@ -391,16 +444,13 @@ def first_logical_identity_change( Returns: The column's name and the reason, or ``None``. """ - held = list(held) - for given_field in schema: - incoming = identity_node(given_field) - for given in held: - index = given.get_field_index(given_field.name) - if index < 0: - continue + incoming = [(f.name, f) for f in schema] + for given in held: + pairs = matched_pairs([(f.name, f) for f in given], incoming) + for name, held_field, given_field in pairs: reason = logical_identity_change( - identity_node(given.field(index)), incoming, given_field.name + identity_node(held_field), identity_node(given_field), name ) if reason is not None: - return given_field.name, reason + return name, reason return None diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 161d99614..da499fe1e 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -30,6 +30,7 @@ from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.utils import ( first_logical_identity_change, + metadata_bytes, identity_node, logical_identity_change, ) @@ -484,9 +485,9 @@ def _struct_rows(form: str, unit: bytes, ids: list[bytes]) -> pa.Table: def test_delta_other_nested_metadata_beside_an_identifier_is_still_refused( tmp_path: Path, form: str, state: str ) -> None: - """Delta leaves the nested extension keys to the identity rule and compares the - rest of a nested field's metadata as before (ITL-1334): a struct child of the - same logical type with other non-extension metadata is refused.""" + """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, @@ -736,30 +737,125 @@ def test_every_container_is_walked(tmp_path: Path, container: str, state: str) - def test_delta_dictionary_of_extension_values(tmp_path: Path) -> None: - """Delta decodes a dictionary column and stores its values as plain storage: a - pending batch is compared as given (another identifier refused); once stored, the - log names no identifier for the values, so the rule abstains and main's verdict - stands (accepted, read back as plain values).""" + """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 storage, with no identifier in + the log (as on main), so the stored column holds no logical type and a logical + append to it is refused, as over any plain column.""" 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\\{values\\}"): + 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() + with pytest.raises(InputValidationError, match="stored column's no logical"): + store.db.add_records( + PATH, + _container_rows("dictionary", b"m", [b"333"]), + record_id_column="id", + ) + stored = store.stored() + assert stored.column("id").to_pylist() == [b"1"] + 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: + """``x``: an identifier ``itl1371.a;`` (extension or annotated), directly + or as the child ``v`` of a struct, dictionary-encoded or not.""" + field: Any + array: Any + field, array = _leaf(("itl1371.a", meta), form, [i.decode() for i in ids]) + if nested: + array = pa.StructArray.from_arrays([array], fields=[field]) + field = pa.field("x", array.type) + if encoded: + array = pa.DictionaryArray.from_arrays( + pa.array(range(len(ids)), pa.int8()), array + ) + field = field.with_type(array.type) + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), array], + schema=pa.schema([pa.field("id", pa.large_binary()), field.with_name("x")]), + ) + + +@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 +) -> 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.""" + with _store("Delta", tmp_path) as store: store.db.add_records( - PATH, _container_rows("dictionary", b"n", [b"333"]), record_id_column="id" + PATH, + _dictionary_layout( + [b"1", b"2"], b"m", encoded=False, nested=False, form=form + ), + record_id_column="id", + flush=True, + ) + if state == "reopened": + store.reopen() + store.db.add_records( + PATH, + _dictionary_layout( + [b"3", b"4"], b"m", encoded=True, nested=False, form=form + ), + record_id_column="id", ) stored = store.stored() - assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ - b"1", - b"333", - ] - assert identity_node(stored.schema.field("x")).identifier is None + assert stored.num_rows == 4 + assert identity_node(stored.schema.field("x")).identifier == ( + b"itl1371.a", + b"m", + ) + + +@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"]) @@ -797,11 +893,12 @@ def rows(value: bytes, ids: list[bytes]) -> pa.Table: @pytest.mark.parametrize("state", ["pending", "committed"]) def test_identifiers_are_compared_as_bytes(state: str) -> None: """An extension name that is not UTF-8: identical bytes are one identifier (the - second append is accepted, as on main); other bytes are refused, the error - naming the name with replacement characters.""" + second append is accepted, as on main); another name or other metadata is + refused, the error showing a name that is not text as its bytes in hex, so two + such names read apart.""" - def rows(meta: bytes, ids: list[bytes]) -> pa.Table: - field = pa.field("x", pa.large_string(), metadata={NAME: b"\xff", META: meta}) + def rows(name: bytes, meta: bytes, ids: list[bytes]) -> pa.Table: + field = pa.field("x", pa.large_string(), metadata={NAME: name, META: meta}) return pa.Table.from_arrays( [ pa.array(ids, pa.large_binary()), @@ -812,11 +909,17 @@ def rows(meta: bytes, ids: list[bytes]) -> pa.Table: db = InMemoryArrowDatabase() db.add_records( - PATH, rows(b"a", [b"1"]), record_id_column="id", flush=state == "committed" + PATH, + rows(b"\xff", b"a", [b"1"]), + record_id_column="id", + flush=state == "committed", ) - db.add_records(PATH, rows(b"a", [b"22"]), record_id_column="id") - with pytest.raises(InputValidationError, match="\ufffd;62"): - db.add_records(PATH, rows(b"b", [b"333"]), record_id_column="id") + db.add_records(PATH, rows(b"\xff", b"a", [b"22"]), record_id_column="id") + with pytest.raises(InputValidationError) as refused: + db.add_records(PATH, rows(b"\xfe", b"a", [b"333"]), record_id_column="id") + assert "'0xfe;61', the stored column's '0xff;61'" in str(refused.value) + with pytest.raises(InputValidationError, match="'0xff;62'"): + db.add_records(PATH, rows(b"\xff", b"b", [b"4444"]), record_id_column="id") db.flush() stored = db.get_all_records(PATH, record_id_column="id") assert stored is not None and stored.num_rows == 2 @@ -854,3 +957,146 @@ def test_delta_untyped_null_over_a_logical_column( HELD[0].encode(), HELD[1], ) + + +@pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) +@pytest.mark.parametrize("state", ["committed", "reopened"]) +def test_delta_annotated_null_of_another_identifier_is_refused( + tmp_path: Path, state: str, schema_handling: str +) -> None: + """Only a bare null claims no type: a null column annotated with another + identifier is a known different identifier, refused in every mode.""" + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, + _rows(HELD, "annotated", "top", [b"1"]), + record_id_column="id", + flush=True, + ) + if state == "reopened": + store.reopen() + other = pa.field("x", pa.null(), metadata={NAME: b"itl1371.a", META: b"n"}) + nulls = pa.Table.from_arrays( + [ + pa.array([1], pa.int64()), + pa.array([b"22"], pa.large_binary()), + pa.nulls(1), + ], + schema=pa.schema( + [pa.field("a", pa.int64()), pa.field("id", pa.large_binary()), other] + ), + ) + with pytest.raises(InputValidationError, match="'itl1371.a;6e'"): + store.db.add_records( + PATH, nulls, record_id_column="id", schema_handling=schema_handling + ) + assert store.stored().column("id").to_pylist() == [b"1"] + + +# The stubs type ``type_codes`` as an array; pyarrow takes a list. +_TYPE_CODES: Any = [7, 9] + + +def _duplicates(shape: str, first_meta: bytes, ids: list[bytes]) -> pa.Table: + """Two places named ``dup`` of different identifiers (``first_meta`` and + ``fixed``), as struct children, sparse or dense union members, or two top-level + columns; only the first one's metadata varies.""" + n = len(ids) + + def ext(meta: bytes, values: list[str | None]) -> Any: + return EXTENSIONS["itl1371.a"](meta).wrap_array( + pa.array(values, pa.large_string()) + ) + + idcol = pa.array(ids, pa.large_binary()) + if shape == "struct": + x = pa.StructArray.from_arrays( + [ext(first_meta, ["v"] * n), ext(b"fixed", ["w"] * n)], names=["dup", "dup"] + ) + return pa.Table.from_arrays([idcol, x], names=["id", "x"]) + if shape == "columns": + return pa.Table.from_arrays( + [idcol, ext(first_meta, ["v"] * n), ext(b"fixed", ["w"] * n)], + names=["id", "dup", "dup"], + ) + codes = pa.array([7] * n, pa.int8()) + if shape == "sparse union": + x = pa.UnionArray.from_sparse( + codes, + [ext(first_meta, ["v"] * n), ext(b"fixed", [None] * n)], + ["dup", "dup"], + type_codes=_TYPE_CODES, + ) + else: + x = pa.UnionArray.from_dense( + codes, + pa.array(range(n), pa.int32()), + [ext(first_meta, ["v"] * n), ext(b"fixed", ["w"])], + ["dup", "dup"], + type_codes=_TYPE_CODES, + ) + return pa.Table.from_arrays([idcol, x], names=["id", "x"]) + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +@pytest.mark.parametrize("shape", ["struct", "sparse union", "dense union", "columns"]) +def test_repeated_names_pair_by_occurrence(shape: str, state: str) -> None: + """Arrow allows two struct children, union members or columns of one name. They + pair by occurrence, never by name alone: a change to the FIRST of two places + named ``dup`` is refused; the same identifiers are accepted.""" + db = InMemoryArrowDatabase() + db.add_records( + PATH, + _duplicates(shape, b"a", [b"1"]), + record_id_column="id", + flush=state == "committed", + ) + db.add_records(PATH, _duplicates(shape, b"a", [b"22"]), record_id_column="id") + with pytest.raises( + InputValidationError, match="'itl1371.a;62', the stored column's 'itl1371.a;61'" + ): + db.add_records(PATH, _duplicates(shape, b"b", [b"333"]), record_id_column="id") + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.num_rows == 2 + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +def test_the_bytes_arrow_holds_decide_not_the_serializer(state: str) -> None: + """A third-party extension type whose serializer's state changes after its array + was built: Arrow holds the bytes taken when the type was made (its C data + interface export), and those decide, as on main for the same bytes.""" + from arro3.core import Field as Arro3Field + + class Mutable(pa.ExtensionType): + def __init__(self, payload: bytes) -> None: + self.payload = payload + super().__init__(pa.large_string(), "itl1371.mutable") + + def __arrow_ext_serialize__(self) -> bytes: + return self.payload + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized) + + def rows(ext: Any, rid: bytes) -> pa.Table: + x = ext.wrap_array(pa.array(["v"], pa.large_string())) + return pa.table({"id": pa.array([rid], pa.large_binary()), "x": x}) + + first, second = Mutable(b"original"), Mutable(b"original") + held, given = rows(first, b"1"), rows(second, b"22") + second.payload = b"changed" # the callback now differs; Arrow's bytes do not + exported = Arro3Field.from_arrow(given.schema.field("x")).metadata + assert metadata_bytes(exported)[META] == b"original" + db = InMemoryArrowDatabase() + db.add_records(PATH, held, record_id_column="id", flush=state == "committed") + db.add_records(PATH, given, record_id_column="id") + + third, fourth = Mutable(b"first"), Mutable(b"second") + held, given = rows(third, b"1"), rows(fourth, b"22") + fourth.payload = b"first" # the callback now agrees; Arrow's bytes do not + db = InMemoryArrowDatabase() + db.add_records(PATH, held, record_id_column="id", flush=state == "committed") + with pytest.raises(InputValidationError, match="'itl1371.mutable;7365636f6e64'"): + db.add_records(PATH, given, record_id_column="id") From 2e3a128f4abc105d8ad381181c65f294852eabac Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:05:53 -0800 Subject: [PATCH 05/14] fix(databases): abstain on a dictionary over a stored place with no identifier (ITL-1371) Delta stores a dictionary of extension values as plain values, losing the identifier (ITL-1372), so a stored place without one is not known when a dictionary-encoded place is given over it: the identifier comparison abstains there, and a dictionary written again is accepted as on main. Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 7 +++--- src/orcapod/databases/utils.py | 24 +++++++++++++++---- .../test_logical_identity_appends.py | 22 ++++++++--------- 3 files changed, 35 insertions(+), 18 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 1c936ef4f..2cc9e8d31 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -59,8 +59,9 @@ So the only appends whose verdict differs from main are those with a known diffe identifier. Where Delta stored a nested extension type as plain storage (a list item or map value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with any identifier, a second list refused for its item's name). Delta stores a dictionary of -extension values as plain values with no identifier in the log (as on main), so a logical -append to such a column, even another dictionary of the same type, is refused as one over -any plain column. Also pre-existing (ITL-1372): +extension values as plain values with no identifier in the log, losing the type +(pre-existing, as on main; ITL-1372): a dictionary-encoded place given over a stored place +with no identifier is therefore not compared, and a dictionary written again is accepted as +on main. Also pre-existing (ITL-1372): Delta refuses any second append of a registered logical type nested in a column with a recorded type, even the identical one. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`. diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 6c95619b7..35d4437c6 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -2,6 +2,7 @@ from __future__ import annotations +import dataclasses import re from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass @@ -234,11 +235,14 @@ class IdentityNode: directly as another's storage, ``.name`` for the other children of a nested type). Labels may repeat: Arrow allows two struct children or union members of one name. + encoded: Whether the place is dictionary-encoded as given (its values stand + where it stands). """ known: bool identifier: RawIdentifier | None claims: bool = True + encoded: bool = False children: "tuple[tuple[str, IdentityNode], ...]" = () @@ -299,7 +303,8 @@ def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: """ arrow_type = arrow_field.type if pa.types.is_dictionary(arrow_type): - return identity_node(arrow_field.with_type(arrow_type.value_type)) + values = identity_node(arrow_field.with_type(arrow_type.value_type)) + return dataclasses.replace(values, encoded=True) identifier = _annotation(arrow_field.metadata) if pa.types.is_null(arrow_type): # A bare null claims nothing; an annotated one claims its annotation. @@ -397,8 +402,10 @@ def logical_identity_change( A table holds one logical type per column and per nested field, so at every place both sides have, the appended identifier must be the held one; no logical type is an identifier too. The rule refuses only where it knows: wherever the held - identifier is not reliably known, or a side is a bare untyped null, it abstains - at that place, and a place only one side has (struct evolution, another kind of + identifier is not reliably known, where a dictionary-encoded place is given over + a held place with no identifier (Delta stores a dictionary of extension values + plain, losing it), or where a side is a bare untyped null, it abstains at that + place, and a place only one side has (struct evolution, another kind of type) is left to the database's other append checks. It compares raw bytes, never Arrow type equality: pyarrow's equality of two instances of one Python extension class ignores their serialized metadata. Places pair as @@ -414,7 +421,16 @@ def logical_identity_change( """ if not (held.claims and incoming.claims): return None - if held.known and incoming.known and held.identifier != incoming.identifier: + # A dictionary-encoded place over a stored place with no identifier: Delta stores + # a dictionary of extension values as plain values, losing the identifier + # (ITL-1372), so "none" there is not known; the identifier comparison abstains. + unknown_loss = incoming.encoded and held.identifier is None + if ( + held.known + and incoming.known + and not unknown_loss + and held.identifier != incoming.identifier + ): return ( f"{path} is of logical type {_identifier_text(incoming.identifier)}, the " f"stored column's {_identifier_text(held.identifier)}" diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index da499fe1e..e13cec4c4 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -739,9 +739,10 @@ def test_every_container_is_walked(tmp_path: Path, container: str, state: str) - 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 storage, with no identifier in - the log (as on main), so the stored column holds no logical type and a logical - append to it is refused, as over any plain column.""" + 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" @@ -753,14 +754,13 @@ def test_delta_dictionary_of_extension_values(tmp_path: Path) -> None: record_id_column="id", ) store.db.flush() - with pytest.raises(InputValidationError, match="stored column's no logical"): - store.db.add_records( - PATH, - _container_rows("dictionary", b"m", [b"333"]), - record_id_column="id", - ) - stored = store.stored() - assert stored.column("id").to_pylist() == [b"1"] + 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 From c7e99cb118916ae4b10d3c177726853eb7dd1134 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:44:29 -0800 Subject: [PATCH 06/14] fix(databases): address CodeRabbit review of the identity rule (ITL-1371) - The dictionary exception applies to a stored Delta place only: where a database holds the given schema, a dictionary of extension values over a plain column is a known different identifier. - An extension level Arrow cannot export (an extension type over another) is not compared, instead of asking its serializer; its storage still is. - Delta checks the identity from the log before decoding recorded types. - In memory, a duplicate-only append with skip_duplicates is not refused for another identifier, as in Delta. - The container test asserts the read-back identifiers as raw bytes. Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 14 +- src/orcapod/databases/delta_lake_databases.py | 20 ++- src/orcapod/databases/in_memory_databases.py | 17 ++- src/orcapod/databases/utils.py | 35 +++-- .../test_logical_identity_appends.py | 144 +++++++++++++++++- 5 files changed, 202 insertions(+), 28 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 2cc9e8d31..9eee4e3c5 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -30,9 +30,9 @@ views, map keys and items, union members, dictionary values, run-end encoded chi an extension type held directly as another's storage, one extension level at a time; a dictionary is an encoding, so its values stand where it stands), the raw identifier bytes must be the held ones; no logical type is an identifier too. The bytes are those Arrow holds -(an extension type's C data interface export, never its serializer called again; the -serializer only for an extension type whose storage is another extension type, which Arrow -cannot export) or the `ARROW:extension:*` annotation; never decoded to decide (a name that +(an extension type's C data interface export, never its serializer called again; for an +extension type whose storage is another extension type, which Arrow cannot export, that +level is not known and not compared, its storage still is) or the `ARROW:extension:*` annotation; never decoded to decide (a name that is not UTF-8 is shown in hex), never Arrow type equality. Places pair by name, or by occurrence where a name repeats among siblings (Arrow allows two struct children, union members or columns of one name), never by name alone. Only a bare `pa.null()` claims no @@ -52,7 +52,8 @@ it. In-memory and connector databases apply it in `add_records`, Delta in A refusal raises `InputValidationError` naming the column, the path and both identifiers' text, before anything is buffered. As in the other Delta checks, the rule runs after `skip_duplicates` has dropped the rows already stored: an append that writes nothing is not -refused. The database type matrix appends each logical type again under another extension +refused, in Delta and in memory. In Delta it reads the log only and runs before any recorded +type is decoded. The database type matrix appends each logical type again under another extension name, which every database refuses. So the only appends whose verdict differs from main are those with a known different @@ -60,8 +61,9 @@ identifier. Where Delta stored a nested extension type as plain storage (a list value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with any identifier, a second list refused for its item's name). Delta stores a dictionary of extension values as plain values with no identifier in the log, losing the type -(pre-existing, as on main; ITL-1372): a dictionary-encoded place given over a stored place -with no identifier is therefore not compared, and a dictionary written again is accepted as +(pre-existing, as on main; ITL-1372): a dictionary-encoded place given over a stored Delta +place with no identifier is therefore not compared (only Delta's: where a database holds the +given schema, that is a known difference), and a dictionary written again is accepted as on main. Also pre-existing (ITL-1372): Delta refuses any second append of a registered logical type nested in a column with a recorded type, even the identical one. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 37268e48a..bfedea5fb 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -668,7 +668,14 @@ def _delta_identity_node(delta_type: Any, metadata: Any) -> IdentityNode: as_bytes = metadata_bytes(metadata) name = as_bytes.get(_EXTENSION_KEYS[0]) identifier = None if name is None else (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) - return IdentityNode(known=True, identifier=identifier, children=children) + # Delta stores a dictionary of extension values as plain values, losing the + # identifier (ITL-1372): a place with none may be such a loss. + return IdentityNode( + known=True, + identifier=identifier, + children=children, + drops_dictionary_identifier=True, + ) def _identity_refusal( @@ -1822,20 +1829,18 @@ def _refuse_changed_attributes( Raises: InputValidationError: For the first such column, naming it and the path. """ - held: list[dict[str, pa.Field[Any]]] = [] identities: list[list[tuple[str, IdentityNode]]] = [] pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: - held.append({f.name: f for f in pending.schema}) identities.append([(f.name, identity_node(f)) for f in pending.schema]) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: delta_table = None if delta_table is not None: - held.append(_held_columns(delta_table)) identities.append(_stored_identities(delta_table)) - # A known different logical type identifier first (ITL-1371). + # A known different logical type identifier first (ITL-1371), from the log + # alone: before any recorded type is decoded, so the error names it. for given_identities in identities: identity = _identity_refusal(given_identities, schema) if identity is not None: @@ -1845,6 +1850,11 @@ def _refuse_changed_attributes( f"{identity[1]}. The stored rows are unchanged and nothing was " "written." ) + held: list[dict[str, pa.Field[Any]]] = [] + if pending is not None: + held.append({f.name: f for f in pending.schema}) + if delta_table is not None: + held.append(_held_columns(delta_table)) for given in held: for field in schema: if field.name not in given: diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index ba2e8a2a4..40f4629d8 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -268,9 +268,20 @@ def add_records( ) if table is not None ] - # A column of another logical type would read back as the held one (ITL-1371). - changed = first_logical_identity_change( - held, records.schema + # A column of another logical type would read back as the held one + # (ITL-1371). An append that writes nothing (every row a duplicate, with + # skip_duplicates) is not refused for it, as in Delta. + writes_nothing = ( + skip_duplicates + and self._filter_existing_records( + record_key, self._deduplicate_within_table(records) + ).num_rows + == 0 + ) + changed = ( + None + if writes_nothing + else first_logical_identity_change(held, records.schema) ) or first_changed_column(held, records.schema) if changed is not None: raise InputValidationError( diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 35d4437c6..b6a7cb90e 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -237,12 +237,17 @@ class IdentityNode: union members of one name. encoded: Whether the place is dictionary-encoded as given (its values stand where it stands). + drops_dictionary_identifier: Whether the held place is in storage that + writes a dictionary of extension values as plain values, losing the + identifier (a stored Delta place): there "no identifier" is not known + against a dictionary-encoded place. """ known: bool identifier: RawIdentifier | None claims: bool = True encoded: bool = False + drops_dictionary_identifier: bool = False children: "tuple[tuple[str, IdentityNode], ...]" = () @@ -257,7 +262,7 @@ def _annotation(metadata: Mapping[Any, Any] | None) -> RawIdentifier | None: return name, as_bytes.get(_EXTENSION_METADATA, b"") -def _extension_identifier(arrow_type: Any) -> RawIdentifier: +def _extension_identifier(arrow_type: Any) -> RawIdentifier | None: """The raw identifier an Arrow extension type holds. Read from the type's C data interface export, where Arrow writes the extension @@ -265,18 +270,19 @@ def _extension_identifier(arrow_type: Any) -> RawIdentifier: on), never by calling ``__arrow_ext_serialize__`` again: a Python extension type's serializer may give other bytes than the ones Arrow took when the type was made, and the export is also the only way to read the bytes of an extension - type defined in Arrow's C++ library (``arrow.uuid``). Arrow cannot export an - extension type whose storage is itself an extension type; for that one, and - only that one, the Python serializer is asked. + type defined in Arrow's C++ library (``arrow.uuid``). + + Returns: + The identifier, or ``None`` when Arrow cannot export the type (an extension + type whose storage is itself an extension type): the bytes Arrow holds are + then out of reach, and the serializer is not asked in their place. """ from arro3.core import Field as Arro3Field try: exported = Arro3Field.from_arrow(pa.field("x", arrow_type)).metadata except pa.ArrowNotImplementedError: - if not isinstance(arrow_type, pa.ExtensionType): - raise - return arrow_type.extension_name.encode(), arrow_type.__arrow_ext_serialize__() + return None identifier = _annotation(exported) assert identifier is not None # an extension type exports its name return identifier @@ -316,6 +322,11 @@ def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: elif isinstance(arrow_type, pa.BaseExtensionType): identifier = _extension_identifier(arrow_type) storage = arrow_type.storage_type + if identifier is None: + # Not exportable: this level's bytes are not known; its storage is. + return IdentityNode( + known=False, identifier=None, children=_children_of(storage) + ) else: storage = arrow_type return IdentityNode( @@ -403,8 +414,8 @@ def logical_identity_change( both sides have, the appended identifier must be the held one; no logical type is an identifier too. The rule refuses only where it knows: wherever the held identifier is not reliably known, where a dictionary-encoded place is given over - a held place with no identifier (Delta stores a dictionary of extension values - plain, losing it), or where a side is a bare untyped null, it abstains at that + a stored Delta place with no identifier (Delta stores a dictionary of extension + values plain, losing it), or where a side is a bare untyped null, it abstains at that place, and a place only one side has (struct evolution, another kind of type) is left to the database's other append checks. It compares raw bytes, never Arrow type equality: pyarrow's equality of two instances of one Python @@ -424,7 +435,11 @@ def logical_identity_change( # A dictionary-encoded place over a stored place with no identifier: Delta stores # a dictionary of extension values as plain values, losing the identifier # (ITL-1372), so "none" there is not known; the identifier comparison abstains. - unknown_loss = incoming.encoded and held.identifier is None + unknown_loss = ( + incoming.encoded + and held.identifier is None + and held.drops_dictionary_identifier + ) if ( held.known and incoming.known diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index e13cec4c4..a1375878c 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -29,6 +29,7 @@ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.utils import ( + IdentityNode, first_logical_identity_change, metadata_bytes, identity_node, @@ -730,10 +731,21 @@ def test_every_container_is_walked(tmp_path: Path, container: str, state: str) - 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())) == held_ids - assert ( - stored.schema.field("x").type - == _container_rows(container, b"m", [b"1"]).schema.field("x").type - ) + expected = _container_rows(container, b"m", [b"1"]).schema.field("x") + # The layout, by Arrow type equality, and the identifiers, as raw bytes: type + # equality alone would also hold for another payload. + assert stored.schema.field("x").type == expected.type + read_back = identity_node(stored.schema.field("x")) + assert read_back == identity_node(expected) + assert (b"itl1371.a", b"m") in _identifiers(read_back) + + +def _identifiers(node: IdentityNode) -> list[Any]: + """Every identifier a node and its children carry, depth first.""" + found = [node.identifier] if node.identifier is not None else [] + for _, child in node.children: + found.extend(_identifiers(child)) + return found def test_delta_dictionary_of_extension_values(tmp_path: Path) -> None: @@ -1100,3 +1112,127 @@ def rows(ext: Any, rid: bytes) -> pa.Table: db.add_records(PATH, held, record_id_column="id", flush=state == "committed") with pytest.raises(InputValidationError, match="'itl1371.mutable;7365636f6e64'"): db.add_records(PATH, given, record_id_column="id") + + +def test_an_unexportable_extension_level_is_not_compared() -> None: + """Arrow cannot export an extension type whose storage is another extension type, + so the bytes it holds for that outer level are out of reach: the outer level is + not compared (its serializer, which may have changed, is not asked), and its + storage still is.""" + + class MutableOuter(pa.ExtensionType): + def __init__(self, storage: Any, payload: bytes) -> None: + self.payload = payload + super().__init__(storage, "itl1371.mutable_outer") + + def __arrow_ext_serialize__(self) -> bytes: + return self.payload + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(storage_type, serialized) + + def rows(inner_meta: bytes, outer: bytes, rid: bytes) -> tuple[Any, pa.Table]: + inner = _wrapped(inner_meta, ["v"]) + outer_type = MutableOuter(inner.type, outer) + x = outer_type.wrap_array(inner) + return outer_type, pa.table({"id": pa.array([rid], pa.large_binary()), "x": x}) + + db = InMemoryArrowDatabase() + _, held = rows(b"m", b"o", b"1") + db.add_records(PATH, held, record_id_column="id", flush=True) + # The outer serializer changed after its type was made: not asked, accepted. + outer_type, same = rows(b"m", b"o", b"22") + outer_type.payload = b"changed" + db.add_records(PATH, same, record_id_column="id") + # Another inner identifier is still refused. + _, other_inner = rows(b"n", b"o", b"333") + with pytest.raises(InputValidationError, match="x is of logical type"): + db.add_records(PATH, other_inner, record_id_column="id") + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.num_rows == 2 + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +def test_a_dictionary_over_a_plain_held_column_is_refused_outside_delta( + state: str, +) -> None: + """The dictionary exception is Delta's alone (its storage loses a dictionary's + identifier): where the database holds the given schema, a dictionary of + extension values over a plain column is a known different identifier.""" + db = InMemoryArrowDatabase() + plain = pa.table( + { + "id": pa.array([b"1"], pa.large_binary()), + "x": pa.array(["v"], pa.large_string()), + } + ) + db.add_records(PATH, plain, record_id_column="id", flush=state == "committed") + with pytest.raises(InputValidationError, match="stored column's no logical"): + db.add_records( + PATH, _container_rows("dictionary", b"m", [b"22"]), record_id_column="id" + ) + + +def test_in_memory_duplicate_only_append_is_not_refused() -> None: + """With ``skip_duplicates``, an append whose every row is already stored writes + nothing and is not refused for another identifier, as in Delta; one with a new + row is.""" + db = InMemoryArrowDatabase() + db.add_records( + PATH, + _container_rows("list_view", b"m", [b"1"]), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _container_rows("list_view", b"n", [b"1"]), + record_id_column="id", + skip_duplicates=True, + ) + with pytest.raises(InputValidationError, match="itl1371.a;6e"): + db.add_records( + PATH, + _container_rows("list_view", b"n", [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + 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 (b"itl1371.a", b"m") in _identifiers(identity_node(stored.schema.field("x"))) + + +def test_delta_identity_is_checked_before_recorded_types_are_decoded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The identity rule reads the Delta log only, and runs before the stored + recorded types are decoded: a decode that would fail does not hide the + identifier the error names.""" + import orcapod.databases.delta_lake_databases as delta_module + + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, + _rows(HELD, "annotated", "struct", [b"1"]), + record_id_column="id", + flush=True, + ) + + def undecodable(_: Any) -> Any: + raise RuntimeError( + "recorded types are not decoded before the identity rule" + ) + + monkeypatch.setattr(delta_module, "_held_columns", undecodable) + with pytest.raises( + InputValidationError, match="x.v is of logical type 'itl1371.b" + ): + store.db.add_records( + PATH, + _rows(("itl1371.b", b"m"), "annotated", "struct", [b"22"]), + record_id_column="id", + ) From 06369af8b193cffb1cea1563ea7edeafa17ce728 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:47:16 -0800 Subject: [PATCH 07/14] fix(databases): read extension identifiers from Arrow's export as raw bytes (ITL-1371) arro3 refuses field metadata that is not UTF-8, so an extension type whose serialized metadata is not text could not be compared. Read the exported ArrowSchema's metadata directly, as the C data interface lays it out, as bytes; arro3 is no longer used. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/utils.py | 58 +++++++++++++++---- .../test_logical_identity_appends.py | 25 ++++++++ 2 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index b6a7cb90e..89608e254 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -265,29 +265,67 @@ def _annotation(metadata: Mapping[Any, Any] | None) -> RawIdentifier | None: def _extension_identifier(arrow_type: Any) -> RawIdentifier | None: """The raw identifier an Arrow extension type holds. - Read from the type's C data interface export, where Arrow writes the extension - name and the serialized metadata it holds (arro3, which ``deltalake`` depends - on), never by calling ``__arrow_ext_serialize__`` again: a Python extension - type's serializer may give other bytes than the ones Arrow took when the type - was made, and the export is also the only way to read the bytes of an extension - type defined in Arrow's C++ library (``arrow.uuid``). + Read from the type's C data interface export (``__arrow_c_schema__``), where + Arrow writes the extension name and the serialized metadata it holds, as bytes + (``_exported_metadata``), never by calling ``__arrow_ext_serialize__`` again: a + Python extension type's serializer may give other bytes than the ones Arrow took + when the type was made, and the export is also the only way to read the bytes of + an extension type defined in Arrow's C++ library (``arrow.uuid``). Returns: The identifier, or ``None`` when Arrow cannot export the type (an extension type whose storage is itself an extension type): the bytes Arrow holds are then out of reach, and the serializer is not asked in their place. """ - from arro3.core import Field as Arro3Field - try: - exported = Arro3Field.from_arrow(pa.field("x", arrow_type)).metadata + capsule = pa.field("x", arrow_type).__arrow_c_schema__() except pa.ArrowNotImplementedError: return None - identifier = _annotation(exported) + identifier = _annotation(_exported_metadata(capsule)) assert identifier is not None # an extension type exports its name return identifier +def _exported_metadata(capsule: Any) -> dict[bytes, bytes]: + """The metadata of an exported ``ArrowSchema``, as raw bytes. + + Read as the Arrow C data interface lays it out (a stable ABI): the struct's + third member is the metadata, a 32-bit count, then for each pair a 32-bit + length and the key bytes, a 32-bit length and the value bytes, native byte + order. Keys and values are bytes: no text decoding, so metadata that is not + UTF-8 is read as it is. The capsule releases the schema when it is collected. + """ + import ctypes + import struct + + get_pointer = ctypes.pythonapi.PyCapsule_GetPointer + get_pointer.restype = ctypes.c_void_p + get_pointer.argtypes = [ctypes.py_object, ctypes.c_char_p] + schema = get_pointer(capsule, b"arrow_schema") + # struct ArrowSchema { const char* format; const char* name; + # const char* metadata; ... } + metadata_pointer = ctypes.c_void_p.from_address( + schema + 2 * ctypes.sizeof(ctypes.c_void_p) + ).value + if not metadata_pointer: + return {} + + def read(offset: int, size: int) -> bytes: + return ctypes.string_at(metadata_pointer + offset, size) + + count = struct.unpack("=i", read(0, 4))[0] + offset = 4 + pairs: dict[bytes, bytes] = {} + for _ in range(count): + key_length = struct.unpack("=i", read(offset, 4))[0] + key = read(offset + 4, key_length) + offset += 4 + key_length + value_length = struct.unpack("=i", read(offset, 4))[0] + pairs[key] = read(offset + 4, value_length) + offset += 4 + value_length + return pairs + + def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: """The identifiers an Arrow field carries, at every depth, in either form. diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index a1375878c..31895d489 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1236,3 +1236,28 @@ def undecodable(_: Any) -> Any: _rows(("itl1371.b", b"m"), "annotated", "struct", [b"22"]), record_id_column="id", ) + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +def test_extension_metadata_that_is_not_text(state: str) -> None: + """An extension type's serialized metadata is bytes, read from Arrow's export as + they are (none of it decoded): the same bytes are accepted, other bytes refused.""" + db = InMemoryArrowDatabase() + db.add_records( + PATH, + _container_rows("list_view", b"\xff\xfe", [b"1"]), + record_id_column="id", + flush=state == "committed", + ) + db.add_records( + PATH, _container_rows("list_view", b"\xff\xfe", [b"22"]), record_id_column="id" + ) + with pytest.raises(InputValidationError, match="'itl1371.a;fffd', the stored"): + db.add_records( + PATH, + _container_rows("list_view", b"\xff\xfd", [b"333"]), + record_id_column="id", + ) + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.num_rows == 2 From 288b82735a9137b5473ad53b9a71c52ad069494b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 17:06:34 -0800 Subject: [PATCH 08/14] fix(databases): one abstention for a missing Delta identifier; chunks; decode order (ITL-1371) Review round 3 of PR 492: - A stored Delta place with no identifier is unknown unless the log records the column's Arrow type (Delta writes a dictionary of extension values plain, with neither): the rule abstains there whatever the given encoding; with a record, another identifier is refused, dictionary-encoded or not. Replaces the dictionary-specific flags. - Delta finds the identity refusal from the log before anything decodes a stored type, the duplicate scan included, with either skip_duplicates. - In memory, the duplicate test reads record ids only, so the ordinary check keeps its priority and no temporary column is added. - A name that is not UTF-8 is shown as a bytes literal. - Each chunk's exported identifier of a given column is compared. Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 36 ++- .../databases/connector_arrow_database.py | 8 +- src/orcapod/databases/delta_lake_databases.py | 132 +++++---- src/orcapod/databases/in_memory_databases.py | 26 +- src/orcapod/databases/utils.py | 151 ++++++---- .../test_logical_identity_appends.py | 258 +++++++++++++++++- 6 files changed, 459 insertions(+), 152 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 9eee4e3c5..401a9e3ae 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -32,8 +32,11 @@ dictionary is an encoding, so its values stand where it stands), the raw identif must be the held ones; no logical type is an identifier too. The bytes are those Arrow holds (an extension type's C data interface export, never its serializer called again; for an extension type whose storage is another extension type, which Arrow cannot export, that -level is not known and not compared, its storage still is) or the `ARROW:extension:*` annotation; never decoded to decide (a name that -is not UTF-8 is shown in hex), never Arrow type equality. Places pair by name, or by +level is not known and not compared, its storage still is) or the `ARROW:extension:*` +annotation; never decoded to decide (a name that is not UTF-8 is shown as a bytes literal, +`b'\xff'`, a form no text name takes), never Arrow type equality. A given column's field and +each of its chunks are compared (pyarrow lets the chunks of one Python extension class carry +other serialized metadata). Places pair by name, or by occurrence where a name repeats among siblings (Arrow allows two struct children, union members or columns of one name), never by name alone. Only a bare `pa.null()` claims no type; an annotated null claims its annotation. @@ -41,29 +44,32 @@ type; an annotated null claims its annotation. The rule only ADDS a refusal where it KNOWS the identifiers differ: from the fields as given (in-memory, a pending batch, a connector's stored schema) and, for a stored Delta table, from the Delta log, which keeps the field metadata of a column and of each struct child byte for -byte (`_delta_identity_node`). Where the held identifier is not reliably known (a Delta list -item, map key or item: the log keeps no metadata there, and the recorded type is read -through the Arrow registry, which may rewrite the metadata) and where a side is an untyped +byte (`_delta_identity_node`). Where the held identifier is not reliably known it abstains: +a Delta list item, map key or item (the log keeps no metadata there, and the recorded type +is read through the Arrow registry, which may rewrite the metadata), and, the one condition +for a missing identifier, a stored Delta place with no identifier in a column whose log +records no Arrow type (`orcapod:arrow_type`): Delta writes a dictionary of extension values as +plain values with no identifier and no record (pre-existing, ITL-1372), so there the absence +proves nothing, whatever the given encoding; with a record, the column is known to hold no +logical type and another identifier is refused, dictionary-encoded or not. Also where a side is an untyped null (`pa.null()`, which holds no value and claims no type), it abstains, and the database's other checks decide exactly as before. A place only one side has (struct evolution, another kind of type) is left to those checks too. The ITL-1334 comparison is unchanged and runs after -it. In-memory and connector databases apply it in `add_records`, Delta in -`_refuse_changed_attributes` (pending and stored) and again at flush (`_append_refusal`). +it. In-memory and connector databases apply it in `add_records`, Delta in `add_records` +(`_identity_refusal`, pending and stored) and again at flush (`_append_refusal`). A refusal raises `InputValidationError` naming the column, the path and both identifiers' text, before anything is buffered. As in the other Delta checks, the rule runs after `skip_duplicates` has dropped the rows already stored: an append that writes nothing is not -refused, in Delta and in memory. In Delta it reads the log only and runs before any recorded -type is decoded. The database type matrix appends each logical type again under another extension +refused, in Delta and in memory (in memory by its record ids only; main's ordinary +check keeps its priority). In Delta it reads the log only and is found before anything +decodes a stored type (the duplicate scan, the held columns), with either duplicate setting. The database type matrix appends each logical type again under another extension name, which every database refuses. So the only appends whose verdict differs from main are those with a known different identifier. Where Delta stored a nested extension type as plain storage (a list item or map value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with -any identifier, a second list refused for its item's name). Delta stores a dictionary of -extension values as plain values with no identifier in the log, losing the type -(pre-existing, as on main; ITL-1372): a dictionary-encoded place given over a stored Delta -place with no identifier is therefore not compared (only Delta's: where a database holds the -given schema, that is a known difference), and a dictionary written again is accepted as -on main. Also pre-existing (ITL-1372): +any identifier, a second list refused for its item's name); a column Delta wrote from a +dictionary of extension values takes the same type again, as a dictionary or not, as on +main. Also pre-existing (ITL-1372): Delta refuses any second append of a registered logical type nested in a column with a recorded type, even the identical one. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 24c7f6868..6c9e20b15 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -444,7 +444,7 @@ def add_records( # put in the held order, so the connector always receives the stored order # (ITL-1367). records = in_held_column_order(records, self._held_column_order(record_path)) - self._refuse_changed_columns(record_path, records.schema) + self._refuse_changed_columns(record_path, records) records = self._deduplicate_within_table(records) input_ids = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) @@ -521,7 +521,7 @@ def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": ] def _refuse_changed_columns( - self, record_path: tuple[str, ...], schema: pa.Schema + self, record_path: tuple[str, ...], records: pa.Table ) -> None: """Refuse rows whose columns would not read back as written (ITL-1334). @@ -551,8 +551,8 @@ def _refuse_changed_columns( if stored is not None: held.append(stored) # A column of another logical type would read back as the held one (ITL-1371). - changed = first_logical_identity_change(held, schema) or first_changed_column( - held, schema + changed = first_logical_identity_change(held, records) or first_changed_column( + held, records.schema ) if changed is not None: raise InputValidationError( diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 1929fe857..230b07c61 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -4,7 +4,7 @@ import os import sys from collections import defaultdict -from collections.abc import Callable, Collection, Mapping, Sequence +from collections.abc import Callable, Collection, Mapping from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast @@ -39,9 +39,8 @@ appended_field_change, coerce_record_id, identity_node, + identity_refusal, in_held_column_order, - logical_identity_change, - matched_pairs, metadata_bytes, ) from orcapod.errors import ( @@ -637,19 +636,26 @@ def _non_null_violation( return None -def _delta_identity_node(delta_type: Any, metadata: Any) -> IdentityNode: +def _delta_identity_node( + delta_type: Any, metadata: Any, recorded: bool +) -> IdentityNode: """What the Delta log reliably says of a stored column's logical type identifiers, at every depth (ITL-1371). The log keeps the field metadata written with the column and with each struct - child, byte for byte, so the identifier there is known. A list item and a map key - or item keep no metadata in the log (ITL-1372), and the column's recorded type is - read through the Arrow registry, which may give an identifier other than the one - stored: there the identifier is not known, and the identity rule abstains. + child, byte for byte, so an identifier there is known. "No identifier" is known + only when the column's Arrow type is recorded (``ARROW_TYPE_KEY``): a column + written from a dictionary of extension values is stored as plain values, losing + the identifier, and records no type (ITL-1372), so without a record the absence + proves nothing and the identity rule abstains. A list item and a map key or item + keep no metadata in the log (ITL-1372), and the column's recorded type is read + through the Arrow registry, which may give an identifier other than the one + stored: there the identifier is never known. Args: delta_type: A ``deltalake.schema`` type from the log. metadata: Its field's metadata, as the log gives it. + recorded: Whether the column records its Arrow type. Returns: The ``IdentityNode`` of the stored field. @@ -659,7 +665,7 @@ def _delta_identity_node(delta_type: Any, metadata: Any) -> IdentityNode: children: tuple[tuple[str, IdentityNode], ...] = () if isinstance(delta_type, StructType): children = tuple( - (f".{f.name}", _delta_identity_node(f.type, f.metadata)) + (f".{f.name}", _delta_identity_node(f.type, f.metadata, recorded)) for f in delta_type.fields ) elif isinstance(delta_type, ArrayType): @@ -669,36 +675,25 @@ def _delta_identity_node(delta_type: Any, metadata: Any) -> IdentityNode: as_bytes = metadata_bytes(metadata) name = as_bytes.get(_EXTENSION_KEYS[0]) identifier = None if name is None else (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) - # Delta stores a dictionary of extension values as plain values, losing the - # identifier (ITL-1372): a place with none may be such a loss. return IdentityNode( - known=True, + known=identifier is not None or recorded, identifier=identifier, children=children, - drops_dictionary_identifier=True, ) -def _identity_refusal( - held: "Sequence[tuple[str, IdentityNode]]", schema: pa.Schema -) -> tuple[str, str] | None: - """The first column of ``schema`` whose logical type identifier is known to - differ from the held one (``logical_identity_change``, ITL-1371); columns pair - as ``matched_pairs`` says (by name, or by occurrence where a name repeats).""" - given = [(f.name, identity_node(f)) for f in schema] - for name, held_node, node in matched_pairs(held, given): - change = logical_identity_change(held_node, node, name) - if change is not None: - return name, change - return None - - def _stored_identities( delta_table: deltalake.DeltaTable, ) -> list[tuple[str, IdentityNode]]: - """Each stored column's ``_delta_identity_node``, from the log; no data is read.""" + """Each stored column's ``_delta_identity_node``, from the log; no data is read + and no type is decoded.""" return [ - (f.name, _delta_identity_node(f.type, f.metadata)) + ( + f.name, + _delta_identity_node( + f.type, f.metadata, ARROW_TYPE_KEY in metadata_bytes(f.metadata) + ), + ) for f in delta_table.schema().fields ] @@ -728,7 +723,7 @@ def _append_refusal( Returns: ``(column, reason)``, or ``None`` when the rows can be appended. """ - identity = _identity_refusal(_stored_identities(delta_table), rows.schema) + identity = identity_refusal(_stored_identities(delta_table), rows) if identity is not None: return identity held = _held_columns(delta_table) @@ -1807,6 +1802,44 @@ def _refuse_declared_nulls( "unchanged and nothing was written." ) + def _identity_refusal( + self, record_path: tuple[str, ...], rows: pa.Table + ) -> str | None: + """Why ``rows`` cannot be appended for a logical type identifier known to + differ from the held one (``identity_refusal``, ITL-1371), or ``None``. + + Held is the pending batch, as given, and the stored table as its Delta log + gives it (``_stored_identities``): no stored type is decoded, so the + comparison comes before anything that decodes one (the duplicate scan, the + held columns' recorded types) and its error names the identifiers. + + Args: + record_path: The table the rows are for. + rows: The rows to append, as given. + + Returns: + The error message, or ``None``. + """ + held: list[list[tuple[str, IdentityNode]]] = [] + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + held.append([(f.name, identity_node(f)) for f in pending.schema]) + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + delta_table = None + if delta_table is not None: + held.append(_stored_identities(delta_table)) + for given in held: + found = identity_refusal(given, rows) + if found is not None: + return ( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: column {found[0]!r}: " + f"{found[1]}. The stored rows are unchanged and nothing was written." + ) + return None + def _refuse_changed_attributes( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1818,10 +1851,8 @@ def _refuse_changed_attributes( attributes: the rows would then be stored, and read back, with another column's attributes. So the field tree of each column (``_column_change``) is compared as given, against the pending batch and the stored table, in every - mode, as an append without schema handling is. Before it, a logical type - identifier known to differ from the held one is refused - (``logical_identity_change``, ITL-1371; the stored side as the Delta log - gives it, ``_delta_identity_node``). + mode, as an append without schema handling is. (A logical type identifier is + compared before, by ``_identity_refusal``.) Args: record_path: The table the rows are for. @@ -1830,27 +1861,11 @@ def _refuse_changed_attributes( Raises: InputValidationError: For the first such column, naming it and the path. """ - identities: list[list[tuple[str, IdentityNode]]] = [] pending = self._pending_batches.get(self._get_record_key(record_path)) - if pending is not None: - identities.append([(f.name, identity_node(f)) for f in pending.schema]) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: delta_table = None - if delta_table is not None: - identities.append(_stored_identities(delta_table)) - # A known different logical type identifier first (ITL-1371), from the log - # alone: before any recorded type is decoded, so the error names it. - for given_identities in identities: - identity = _identity_refusal(given_identities, schema) - if identity is not None: - raise InputValidationError( - f"Cannot append to the stored table " - f"{self._get_table_uri(record_path)!r}: column {identity[0]!r}: " - f"{identity[1]}. The stored rows are unchanged and nothing was " - "written." - ) held: list[dict[str, pa.Field[Any]]] = [] if pending is not None: held.append({f.name: f for f in pending.schema}) @@ -1971,15 +1986,24 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) self._refuse_untyped_null_columns(record_path, records.schema) + # A logical type identifier known to differ from the held one (ITL-1371), + # found from the Delta log before anything decodes a stored type; raised + # once the duplicate scan shows the append writes something. + identity = self._identity_refusal(record_path, records) # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) # Step 3: Handle conflicts based on skip_duplicates setting if skip_duplicates: - filtered_table = self._filter_existing_records( - record_path, deduplicated_table - ) + try: + filtered_table = self._filter_existing_records( + record_path, deduplicated_table + ) + except OrcapodDatabaseReadError as error: + if identity is not None: + raise InputValidationError(identity) from error + raise if filtered_table.num_rows == 0: logger.debug("All records were duplicates, nothing to insert") return None @@ -1987,6 +2011,8 @@ def add_records( # Check for conflicts - insert never allows duplicates when skip_duplicates=False # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table + if identity is not None: + raise InputValidationError(identity) # Columns match by name within a pending batch: rows with the pending # batch's columns in another order, each field equal, are put in its order diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 30f9bf823..bd9d4c475 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -281,20 +281,18 @@ def add_records( if table is not None ] # A column of another logical type would read back as the held one - # (ITL-1371). An append that writes nothing (every row a duplicate, with - # skip_duplicates) is not refused for it, as in Delta. - writes_nothing = ( - skip_duplicates - and self._filter_existing_records( - record_key, self._deduplicate_within_table(records) - ).num_rows - == 0 - ) - changed = ( - None - if writes_nothing - else first_logical_identity_change(held, records.schema) - ) or first_changed_column(held, records.schema) + # (ITL-1371); refused before the other checks, so the error names the + # identifiers. An append that writes nothing (with skip_duplicates, every + # record id already held) is not refused for it, as in Delta; the ordinary + # check below keeps main's place and priority. + identity = first_logical_identity_change(held, records) + if identity is not None and skip_duplicates: + given_ids = set(records[self.RECORD_ID_COLUMN].to_pylist()) + held_ids = self._pending_record_ids[record_key] + committed = self._committed_id_index(record_key) + if all(i in held_ids or i in committed for i in given_ids): + identity = None + changed = identity or first_changed_column(held, records.schema) if changed is not None: raise InputValidationError( f"Cannot append to the table at {record_path!r}: column " diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 5dc2d871f..45b91e470 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -2,7 +2,6 @@ from __future__ import annotations -import dataclasses import re from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass @@ -18,7 +17,8 @@ else: pa = LazyModule("pyarrow") -T = TypeVar("T") +H = TypeVar("H") +G = TypeVar("G") def coerce_record_id(record_id: str | bytes) -> bytes: @@ -235,19 +235,11 @@ class IdentityNode: directly as another's storage, ``.name`` for the other children of a nested type). Labels may repeat: Arrow allows two struct children or union members of one name. - encoded: Whether the place is dictionary-encoded as given (its values stand - where it stands). - drops_dictionary_identifier: Whether the held place is in storage that - writes a dictionary of extension values as plain values, losing the - identifier (a stored Delta place): there "no identifier" is not known - against a dictionary-encoded place. """ known: bool identifier: RawIdentifier | None claims: bool = True - encoded: bool = False - drops_dictionary_identifier: bool = False children: "tuple[tuple[str, IdentityNode], ...]" = () @@ -347,8 +339,7 @@ def identity_node(arrow_field: "pa.Field[Any]") -> IdentityNode: """ arrow_type = arrow_field.type if pa.types.is_dictionary(arrow_type): - values = identity_node(arrow_field.with_type(arrow_type.value_type)) - return dataclasses.replace(values, encoded=True) + return identity_node(arrow_field.with_type(arrow_type.value_type)) identifier = _annotation(arrow_field.metadata) if pa.types.is_null(arrow_type): # A bare null claims nothing; an annotated one claims its annotation. @@ -396,23 +387,23 @@ def _children_of(arrow_type: Any) -> "tuple[tuple[str, IdentityNode], ...]": return tuple((f"{prefix}{child.name}", identity_node(child)) for child in children) -def _name_text(name: bytes) -> str: - try: - return name.decode() - except UnicodeDecodeError: - return f"0x{name.hex()}" # not text: shown as its bytes - - def _identifier_text(identifier: RawIdentifier | None) -> str: + """An identifier as the error shows it: ``';'`` (a quoted + text) when the name is text; a name that is not UTF-8 as a bytes literal, + ``b'\\xff';``, which no text can be shown as, so two names never + read alike.""" if identifier is None: return "no logical type" name, metadata = identifier - return repr(f"{_name_text(name)};{metadata.hex()}") + try: + return repr(f"{name.decode()};{metadata.hex()}") + except UnicodeDecodeError: + return f"{name!r};{metadata.hex()}" def matched_pairs( - held: "Sequence[tuple[str, T]]", incoming: "Sequence[tuple[str, T]]" -) -> "list[tuple[str, T, T]]": + held: "Sequence[tuple[str, H]]", incoming: "Sequence[tuple[str, G]]" +) -> "list[tuple[str, H, G]]": """Pair the labelled places of two sides (ITL-1371). A label that occurs once on each side pairs by label. Where a label repeats on @@ -428,11 +419,11 @@ def matched_pairs( Returns: ``(label, held place, given place)`` for every pair, in the given order. """ - by_label: dict[str, list[T]] = {} + by_label: dict[str, list[H]] = {} for label, place in held: by_label.setdefault(label, []).append(place) seen: dict[str, int] = {} - pairs: list[tuple[str, T, T]] = [] + pairs: list[tuple[str, H, G]] = [] for label, place in incoming: k = seen.get(label, 0) seen[label] = k + 1 @@ -451,10 +442,8 @@ def logical_identity_change( A table holds one logical type per column and per nested field, so at every place both sides have, the appended identifier must be the held one; no logical type is an identifier too. The rule refuses only where it knows: wherever the held - identifier is not reliably known, where a dictionary-encoded place is given over - a stored Delta place with no identifier (Delta stores a dictionary of extension - values plain, losing it), or where a side is a bare untyped null, it abstains at that - place, and a place only one side has (struct evolution, another kind of + identifier is not reliably known (``IdentityNode.known``), or a side is a bare + untyped null, it abstains at that place, and a place only one side has (struct evolution, another kind of type) is left to the database's other append checks. It compares raw bytes, never Arrow type equality: pyarrow's equality of two instances of one Python extension class ignores their serialized metadata. Places pair as @@ -470,20 +459,7 @@ def logical_identity_change( """ if not (held.claims and incoming.claims): return None - # A dictionary-encoded place over a stored place with no identifier: Delta stores - # a dictionary of extension values as plain values, losing the identifier - # (ITL-1372), so "none" there is not known; the identifier comparison abstains. - unknown_loss = ( - incoming.encoded - and held.identifier is None - and held.drops_dictionary_identifier - ) - if ( - held.known - and incoming.known - and not unknown_loss - and held.identifier != incoming.identifier - ): + if held.known and incoming.known and held.identifier != incoming.identifier: return ( f"{path} is of logical type {_identifier_text(incoming.identifier)}, the " f"stored column's {_identifier_text(held.identifier)}" @@ -495,36 +471,93 @@ def logical_identity_change( return None -def first_logical_identity_change( - held: "Iterable[pa.Schema]", schema: "pa.Schema" +def given_identities( + given: "pa.Table | pa.Schema", +) -> "list[tuple[str, list[IdentityNode]]]": + """The identifiers the rows to append carry, column by column (ITL-1371). + + A column's field, and, for a table, each of its chunks: pyarrow lets the chunks of + one column hold instances of one Python extension class with other serialized + metadata (it compares them by class), so each chunk's own exported identifier is + read too, and every one of them must be the held one. + + Args: + given: The rows to append, or only their schema. + + Returns: + ``(column name, identity nodes)`` in column order; the field's node first. + """ + if isinstance(given, pa.Schema): + return [(f.name, [identity_node(f)]) for f in given] + out: list[tuple[str, list[IdentityNode]]] = [] + for field, column in zip(given.schema, given.columns): + nodes = [identity_node(field)] + for chunk in column.chunks: + if _has_extension_part(chunk.type): + node = identity_node(field.with_type(chunk.type)) + if node not in nodes: + nodes.append(node) + out.append((field.name, nodes)) + return out + + +def _has_extension_part(arrow_type: Any) -> bool: + if isinstance(arrow_type, pa.BaseExtensionType): + return True + if pa.types.is_dictionary(arrow_type): + return _has_extension_part(arrow_type.value_type) + return any( + _has_extension_part(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + +def identity_refusal( + held: "Sequence[tuple[str, IdentityNode]]", given: "pa.Table | pa.Schema" ) -> tuple[str, str] | None: - """The first column of ``schema`` that carries another logical type identifier - than the column the database holds in its place, as given (``identity_node``). + """The first column of ``given`` known to carry another logical type identifier + than the one held in its place (``logical_identity_change``). - For a database that holds what it was given (in-memory, a pending batch, a - connector's stored schema). Columns pair as ``matched_pairs`` says: by name, or - by occurrence where a name repeats; the order of columns of distinct names plays - no part. + Columns pair as ``matched_pairs`` says: by name, or by occurrence where a name + repeats; the order of columns of distinct names plays no part. Args: - held: The schemas the database holds for the table (stored, pending). - schema: The schema of the rows to append, as given. + held: The held columns, in order, with what is known of their identifiers. + given: The rows to append (``given_identities``), or their schema. Returns: The column's name and the reason, or ``None``. """ - incoming = [(f.name, f) for f in schema] - for given in held: - pairs = matched_pairs([(f.name, f) for f in given], incoming) - for name, held_field, given_field in pairs: - reason = logical_identity_change( - identity_node(held_field), identity_node(given_field), name - ) + for name, held_node, nodes in matched_pairs(held, given_identities(given)): + for node in nodes: + reason = logical_identity_change(held_node, node, name) if reason is not None: return name, reason return None +def first_logical_identity_change( + held: "Iterable[pa.Schema]", given: "pa.Table | pa.Schema" +) -> tuple[str, str] | None: + """The first column of ``given`` that carries another logical type identifier + than the column the database holds in its place (``identity_refusal``), for a + database that holds what it was given (in-memory, a pending batch, a connector's + stored schema): every held identifier is known. + + Args: + held: The schemas the database holds for the table (stored, pending). + given: The rows to append, or their schema. + + Returns: + The column's name and the reason, or ``None``. + """ + for schema in held: + found = identity_refusal([(f.name, identity_node(f)) for f in schema], given) + if found is not None: + return found + return None + + def in_held_column_order( records: "pa.Table", held: "Sequence[pa.Field[Any]] | None" ) -> "pa.Table": diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 31895d489..6cffc06bc 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -13,6 +13,7 @@ from __future__ import annotations import contextlib +import re import itertools from collections.abc import Iterator from pathlib import Path @@ -297,9 +298,9 @@ def test_same_identifier_is_accepted( for kind, state, form, depth in itertools.product( ("in-memory", "Delta"), ("pending", "committed"), FORMS, DEPTHS ) - # The rule abstains at a stored Delta list or map item; main accepts extension - # values there. - if not (_abstains(kind, state, depth) and form == "extension") + # 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") ] @@ -315,8 +316,7 @@ def test_a_logical_type_over_a_plain_column_is_refused( record_id_column="id", flush=state == "committed", ) - match = None if _abstains(kind, state, depth) else "stored column's no logical" - with pytest.raises(InputValidationError, match=match): + with pytest.raises(InputValidationError, match="stored column's no logical"): _through(store.db, via).add_records( PATH, _rows(HELD, form, depth, [b"22"]), record_id_column="id" ) @@ -929,8 +929,8 @@ def rows(name: bytes, meta: bytes, ids: list[bytes]) -> pa.Table: db.add_records(PATH, rows(b"\xff", b"a", [b"22"]), record_id_column="id") with pytest.raises(InputValidationError) as refused: db.add_records(PATH, rows(b"\xfe", b"a", [b"333"]), record_id_column="id") - assert "'0xfe;61', the stored column's '0xff;61'" in str(refused.value) - with pytest.raises(InputValidationError, match="'0xff;62'"): + assert "b'\\xfe';61, the stored column's b'\\xff';61" in str(refused.value) + with pytest.raises(InputValidationError, match=re.escape("b'\\xff';62")): db.add_records(PATH, rows(b"\xff", b"b", [b"4444"]), record_id_column="id") db.flush() stored = db.get_all_records(PATH, record_id_column="id") @@ -1261,3 +1261,247 @@ def test_extension_metadata_that_is_not_text(state: str) -> None: db.flush() stored = db.get_all_records(PATH, record_id_column="id") assert stored is not None and stored.num_rows == 2 + + +@pytest.mark.parametrize("state", ["committed", "reopened"]) +def test_delta_logical_type_over_a_plain_column(tmp_path: Path, state: str) -> None: + """A stored Delta column with no identifier is known to hold no logical type only + when the log records its Arrow type: then another identifier is refused, + dictionary-encoded or not. Without a record (a plain text column, or one Delta + wrote from a dictionary of extension values, losing its identifier: ITL-1372) the + absence proves nothing and the rule abstains, so main's checks decide: an + extension column is accepted, as on main.""" + uint16 = pa.uint16() + + def recorded_rows(ids: list[bytes], identifier: bool, encoded: bool) -> pa.Table: + values: Any = pa.array(range(len(ids)), uint16) + if identifier: + values = _UINT16(b"e").wrap_array(values) + if encoded: + values = pa.DictionaryArray.from_arrays( + pa.array(range(len(ids)), pa.int8()), values + ) + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), values], names=["id", "x"] + ) + + for encoded in (False, True): + root = tmp_path / f"recorded-{encoded}" + with _store("Delta", root) as store: + store.db.add_records( + PATH, + recorded_rows([b"1"], False, False), + record_id_column="id", + flush=True, + ) + if state == "reopened": + store.reopen() + with pytest.raises( + InputValidationError, match="stored column's no logical" + ): + store.db.add_records( + PATH, recorded_rows([b"22"], True, encoded), record_id_column="id" + ) + assert store.stored().column("id").to_pylist() == [b"1"] + + with _store("Delta", tmp_path / "unrecorded") as store: + store.db.add_records( + PATH, + _rows(None, "extension", "top", [b"1"]), + record_id_column="id", + flush=True, + ) + if state == "reopened": + store.reopen() + store.db.add_records( + PATH, _rows(HELD, "extension", "top", [b"22"]), record_id_column="id" + ) + assert store.stored().num_rows == 2 + + +def _uint16_type() -> Any: + class _UInt16(pa.ExtensionType): + def __init__(self, meta: bytes) -> None: + self._meta = meta + super().__init__(pa.uint16(), "itl1371.uint16") + + def __arrow_ext_serialize__(self) -> bytes: + return self._meta + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized) + + return _UInt16 + + +_UINT16 = _uint16_type() + + +@pytest.mark.parametrize("state", ["committed", "reopened"]) +def test_delta_extension_after_a_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.""" + 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, + ) + if state == "reopened": + store.reopen() + plain = 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" + ) + stored = store.stored().sort_by("id") + assert stored.column("id").to_pylist() == [b"1", b"22", b"333"] + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_identity_is_refused_before_an_undecodable_stored_type( + tmp_path: Path, skip_duplicates: bool +) -> None: + """A stored struct child annotated with an identifier the registered type cannot + read: every path that would decode the stored types (the duplicate scan, the + held columns) comes after the identity rule, which reads the Delta log only, so + another identifier is refused naming both, with either duplicate setting.""" + + 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())) + try: + 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, + ) + 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 + finally: + pa.unregister_extension_type("itl1371.current") + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +@pytest.mark.parametrize( + "ids", [[b"1", b"2"], [b"1", b"3"]], ids=["duplicates", "one new"] +) +def test_in_memory_ordinary_refusal_keeps_its_priority( + state: str, ids: list[bytes] +) -> None: + """With skip_duplicates, the duplicate test of the identity rule reads record ids + only (no deduplication, no temporary column): an ordinary field-metadata change + is refused as on main, even with a user column named ``__row_index``.""" + db = InMemoryArrowDatabase() + + def rows(row_ids: list[bytes], unit: bytes) -> pa.Table: + field = pa.field("x", pa.large_string(), metadata={b"unit": unit}) + return pa.Table.from_arrays( + [ + pa.array(row_ids, pa.large_binary()), + pa.array(["v"] * len(row_ids), pa.large_string()), + ], + schema=pa.schema([pa.field("id", pa.large_binary()), field]), + ) + + db.add_records( + PATH, + rows([b"1", b"2"], b"a"), + record_id_column="id", + flush=state == "committed", + ) + changed = rows(ids, b"b").append_column("__row_index", pa.array([0, 1])) + with pytest.raises(InputValidationError, match="x has other field metadata"): + db.add_records(PATH, changed, record_id_column="id", skip_duplicates=True) + + +def test_an_opaque_name_never_reads_as_a_text_name() -> None: + """A name that is not UTF-8 is shown as a bytes literal, a form no text name + takes: ``b'\\xff'`` and the text ``0xff`` read apart.""" + + def rows(name: bytes, ids: list[bytes]) -> pa.Table: + field = pa.field("x", pa.large_string(), metadata={NAME: name}) + return pa.Table.from_arrays( + [ + pa.array(ids, pa.large_binary()), + pa.array(["v"] * len(ids), pa.large_string()), + ], + schema=pa.schema([pa.field("id", pa.large_binary()), field]), + ) + + db = InMemoryArrowDatabase() + db.add_records(PATH, rows(b"\xff", [b"1"]), record_id_column="id", flush=True) + with pytest.raises(InputValidationError) as refused: + db.add_records(PATH, rows(b"0xff", [b"22"]), record_id_column="id") + assert "'0xff;', the stored column's b'\\xff';" in str(refused.value) + with pytest.raises(InputValidationError) as refused: + db.add_records(PATH, rows(b"b'\\xff'", [b"22"]), record_id_column="id") + assert "\"b'\\\\xff';\", the stored column's b'\\xff';" in str(refused.value) + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +def test_every_chunk_identifier_is_compared(state: str) -> None: + """pyarrow lets the chunks of one column hold one Python extension class with + other serialized metadata: each chunk's own identifier is compared, so a later + chunk of another identifier is refused; chunks of the same bytes are accepted.""" + + def rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: + chunks = [_wrapped(meta, [i.decode()]) for meta, i in zip(metas, ids)] + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), pa.chunked_array(chunks)], + names=["id", "x"], + ) + + db = InMemoryArrowDatabase() + db.add_records( + PATH, rows([b"m"], [b"1"]), record_id_column="id", flush=state == "committed" + ) + db.add_records(PATH, rows([b"m", b"m"], [b"2", b"3"]), record_id_column="id") + mixed = rows([b"m", b"n"], [b"4", b"5"]) + assert [c.type.__arrow_ext_serialize__() for c in mixed.column("x").chunks] == [ + b"m", + b"n", + ] + with pytest.raises( + InputValidationError, match="'itl1371.a;6e', the stored column's 'itl1371.a;6d'" + ): + db.add_records(PATH, mixed, record_id_column="id") + 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"2", + b"3", + ] From f5cf3c20f867edaa6ea988a5582bf05e9ca32ef8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:04:32 -0800 Subject: [PATCH 09/14] fix(databases): address CodeRabbit review of bc2b49ec (ITL-1371) - A read failure of the duplicate scan is raised as it is (a read failure fails the run whatever the error policy), with the identity refusal noted. - Delta's attribute check compares identities on the table it loads, before decoding its recorded types. - In memory, a null record id is never taken for a stored one. - Places pair only within one role: a map's key never pairs with a struct field named key. - The MERGE source carries the identifier bytes Arrow holds, not the serializer asked again. - Chunk identities are deduplicated with a set. Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1367-CO1.md | 4 +- src/orcapod/databases/delta_lake_databases.py | 31 +++++- src/orcapod/databases/in_memory_databases.py | 5 +- src/orcapod/databases/utils.py | 33 ++++-- .../test_logical_identity_appends.py | 101 ++++++++++++++++-- 5 files changed, 152 insertions(+), 22 deletions(-) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index a1b86d80b..dc2b40648 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -63,7 +63,9 @@ table between the flush's check and its write (a DDL in that window) is not seen of `a` to `A` then stores the value under `A`, since SQLite resolves names without case, as on main. Through `ExtensionAwareDatabase`, rows of another logical type over the same storage type in the SAME column order are accepted and read back as the held logical type -(ITL-1371, which now refuses them, in either column order). +(ITL-1371 now refuses them, in either column order, wherever the held identifier is known: +not over a Delta column with no identifier and no recorded Arrow type, such as one written +from a dictionary of extension values, where the identity rule abstains; ITL-1372). Not covered: the order of a struct's fields (a struct with its fields in another order is another type here, and the fake keeps struct children as written): ITL-1368. A canonical diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 230b07c61..7049c7120 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -34,6 +34,9 @@ parse_base_path, ) from orcapod.databases.utils import ( + LIST_ITEM, + MAP_ITEM, + MAP_KEY, UNKNOWN, IdentityNode, appended_field_change, @@ -669,9 +672,9 @@ def _delta_identity_node( for f in delta_type.fields ) elif isinstance(delta_type, ArrayType): - children = (("[]", UNKNOWN),) + children = ((LIST_ITEM, UNKNOWN),) elif isinstance(delta_type, MapType): - children = ((".key", UNKNOWN), (".item", UNKNOWN)) + children = ((MAP_KEY, UNKNOWN), (MAP_ITEM, UNKNOWN)) as_bytes = metadata_bytes(metadata) name = as_bytes.get(_EXTENSION_KEYS[0]) identifier = None if name is None else (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) @@ -961,8 +964,14 @@ def _merge_source_in_stored_layout( # would be dropped from the table (ITL-1334). metadata = dict(field.metadata or {}) if isinstance(field.type, pa.ExtensionType): - metadata[b"ARROW:extension:name"] = field.type.extension_name.encode() - metadata[b"ARROW:extension:metadata"] = field.type.__arrow_ext_serialize__() + # The bytes Arrow holds, the ones the identity rule compared (ITL-1371), + # not the serializer asked again, which may answer otherwise. + identifier = identity_node(field).identifier or ( + field.type.extension_name.encode(), + field.type.__arrow_ext_serialize__(), + ) + metadata[b"ARROW:extension:name"] = identifier[0] + metadata[b"ARROW:extension:metadata"] = identifier[1] batch = batch.set_column( index, pa.field( @@ -1870,6 +1879,16 @@ def _refuse_changed_attributes( if pending is not None: held.append({f.name: f for f in pending.schema}) if delta_table is not None: + # The identity rule on this very table, from its log, before its recorded + # types are decoded: the table loaded here may not be the one + # ``_identity_refusal`` saw (it could not load one), ITL-1371. + found = identity_refusal(_stored_identities(delta_table), schema) + if found is not None: + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: column {found[0]!r}: " + f"{found[1]}. The stored rows are unchanged and nothing was written." + ) held.append(_held_columns(delta_table)) for given in held: for field in schema: @@ -2001,8 +2020,10 @@ def add_records( record_path, deduplicated_table ) except OrcapodDatabaseReadError as error: + # A read failure fails the run whatever the error policy: it is + # raised as it is, naming the identifiers it kept from refusing. if identity is not None: - raise InputValidationError(identity) from error + error.add_note(f"Also refused: {identity}") raise if filtered_table.num_rows == 0: logger.debug("All records were duplicates, nothing to insert") diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index bd9d4c475..eea2257e5 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -290,7 +290,10 @@ def add_records( given_ids = set(records[self.RECORD_ID_COLUMN].to_pylist()) held_ids = self._pending_record_ids[record_key] committed = self._committed_id_index(record_key) - if all(i in held_ids or i in committed for i in given_ids): + # As _filter_existing_records: a null id is never a committed record. + if all( + i in held_ids or (i is not None and i in committed) for i in given_ids + ): identity = None changed = identity or first_changed_column(held, records.schema) if changed is not None: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 45b91e470..99bb413cd 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -233,8 +233,9 @@ class IdentityNode: struct child, ``[]`` for a list item, ``.key`` and ``.item`` for a map, ``|name`` for a union member, ```` for an extension type held directly as another's storage, ``.name`` for the other children of a - nested type). Labels may repeat: Arrow allows two struct children or - union members of one name. + nested type; every label but a struct child's starts with ``_ROLE``, so + places pair only within one role). Labels may repeat: Arrow allows two + struct children or union members of one name. """ known: bool @@ -245,6 +246,14 @@ class IdentityNode: UNKNOWN = IdentityNode(known=False, identifier=None) +# Child labels pair places of one role: a struct field is labelled ``.``; a +# place of any other role carries ``_ROLE`` first, so a map's key, say, never pairs +# with a struct field named ``key``. Messages show labels without it. +_ROLE = "\x00" +MAP_KEY = f"{_ROLE}.key" +MAP_ITEM = f"{_ROLE}.item" +LIST_ITEM = f"{_ROLE}[]" + def _annotation(metadata: Mapping[Any, Any] | None) -> RawIdentifier | None: as_bytes = metadata_bytes(metadata) @@ -368,11 +377,11 @@ def _children_of(arrow_type: Any) -> "tuple[tuple[str, IdentityNode], ...]": if t.is_dictionary(arrow_type): return _children_of(arrow_type.value_type) if isinstance(arrow_type, pa.BaseExtensionType): - return (("", identity_node(pa.field("storage", arrow_type))),) + return ((f"{_ROLE}", identity_node(pa.field("storage", arrow_type))),) if t.is_map(arrow_type): return ( - (".key", identity_node(arrow_type.key_field)), - (".item", identity_node(arrow_type.item_field)), + (MAP_KEY, identity_node(arrow_type.key_field)), + (MAP_ITEM, identity_node(arrow_type.item_field)), ) if ( t.is_list(arrow_type) @@ -381,8 +390,10 @@ def _children_of(arrow_type: Any) -> "tuple[tuple[str, IdentityNode], ...]": or t.is_list_view(arrow_type) or t.is_large_list_view(arrow_type) ): - return (("[]", identity_node(arrow_type.value_field)),) - prefix = "|" if t.is_union(arrow_type) else "." + return ((LIST_ITEM, identity_node(arrow_type.value_field)),) + if t.is_struct(arrow_type): + return tuple((f".{child.name}", identity_node(child)) for child in arrow_type) + prefix = f"{_ROLE}|" if t.is_union(arrow_type) else f"{_ROLE}." children = (arrow_type.field(i) for i in range(arrow_type.num_fields)) return tuple((f"{prefix}{child.name}", identity_node(child)) for child in children) @@ -465,7 +476,9 @@ def logical_identity_change( f"stored column's {_identifier_text(held.identifier)}" ) for label, held_child, child in matched_pairs(held.children, incoming.children): - found = logical_identity_change(held_child, child, f"{path}{label}") + found = logical_identity_change( + held_child, child, f"{path}{label.replace(_ROLE, '')}" + ) if found is not None: return found return None @@ -492,10 +505,12 @@ def given_identities( out: list[tuple[str, list[IdentityNode]]] = [] for field, column in zip(given.schema, given.columns): nodes = [identity_node(field)] + seen = set(nodes) for chunk in column.chunks: if _has_extension_part(chunk.type): node = identity_node(field.with_type(chunk.type)) - if node not in nodes: + if node not in seen: + seen.add(node) nodes.append(node) out.append((field.name, nodes)) return out diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 6cffc06bc..afae9e9f5 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -36,7 +36,7 @@ identity_node, logical_identity_change, ) -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, OrcapodDatabaseReadError from orcapod.logical_types.identifier import LogicalTypeIdentifier from orcapod.logical_types.registry import make_arrow_extension_type from orcapod.logical_types.registry import LogicalTypeRegistry @@ -1370,9 +1370,12 @@ 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: every path that would decode the stored types (the duplicate scan, the - held columns) comes after the identity rule, which reads the Delta log only, so - another identifier is refused naming both, with either duplicate setting.""" + read: the identity rule reads the Delta log only and comes before every path that + decodes the stored types (the duplicate scan, the held columns), so another + identifier is refused naming both. With ``skip_duplicates`` the duplicate scan + must read the stored ids, which decodes: that read failure is raised as it is (a + read failure fails the run whatever the error policy), with the identity refusal + noted on it.""" class Current(pa.ExtensionType): def __init__(self) -> None: @@ -1399,14 +1402,19 @@ def rows(ids: list[bytes], name: bytes, meta: bytes) -> pa.Table: ) pa.register_extension_type(cast(Any, Current())) try: - with pytest.raises(InputValidationError) as refused: + expected = OrcapodDatabaseReadError if skip_duplicates else InputValidationError + with pytest.raises(expected) 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, ) - message = str(refused.value) + message = ( + "\n".join([str(refused.value), *refused.value.__notes__]) + if (skip_duplicates) + else 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 finally: @@ -1505,3 +1513,84 @@ def rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: b"2", b"3", ] + + +def test_a_null_record_id_is_never_taken_for_a_stored_one() -> None: + """The duplicate test reads record ids as ``_filter_existing_records`` does: a + null id is never a stored record, so an append of null ids with another + identifier is refused even when a null id is committed.""" + + def rows(meta: bytes, ids: list[bytes | None]) -> pa.Table: + return pa.table( + { + "id": pa.array(ids, pa.large_binary()), + "x": _wrapped(meta, ["v"] * len(ids)), + } + ) + + db = InMemoryArrowDatabase() + db.add_records(PATH, rows(b"m", [None]), record_id_column="id", flush=True) + with pytest.raises(InputValidationError, match="itl1371.a;6e"): + db.add_records( + PATH, rows(b"n", [None]), record_id_column="id", skip_duplicates=True + ) + + +def test_a_map_and_a_struct_do_not_pair_their_places() -> None: + """Places pair only within one role: a map's key never pairs with a struct field + named ``key``, so a held map and a given struct of other key identifiers are not + reported as a logical type change at ``x.key`` (their kinds differ; that is the + database's other checks' to say).""" + + def annotated(meta: bytes, name: str = "key") -> "pa.Field[Any]": + return pa.field( + name, + pa.large_string(), + nullable=False, + metadata={NAME: b"itl1371.a", META: meta}, + ) + + item = pa.field("item", pa.int64()) + map_field = pa.field("x", pa.map_(annotated(b"m"), item)) # pyright: ignore[reportArgumentType] # pyarrow takes key/item fields + struct_field = pa.field("x", pa.struct([annotated(b"n"), item])) + assert _change(map_field, struct_field) is None + other_map = pa.field("x", pa.map_(annotated(b"n"), item)) # pyright: ignore[reportArgumentType] # pyarrow takes key/item fields + reason = _change(map_field, other_map) + assert reason is not None and reason.startswith("x.key is of logical type") + + +def test_delta_merge_source_keeps_the_held_identifier_bytes(tmp_path: Path) -> None: + """A list-typed extension column appended to a stored table goes to the MERGE (a + batch with an id already stored) in the stored layout with its identifier: the bytes Arrow holds (the ones the + identity rule compared), not its serializer asked again, which may answer + otherwise. The stored identifier stays the one written.""" + import deltalake + + class ListExt(pa.ExtensionType): + def __init__(self, payload: bytes) -> None: + self.payload = payload + super().__init__(pa.large_list(pa.large_string()), "itl1371.lists") + + def __arrow_ext_serialize__(self) -> bytes: + return self.payload + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized) + + def rows(ext: Any, ids: list[bytes]) -> pa.Table: + storage = pa.array([["v"]] * len(ids), pa.large_list(pa.large_string())) + return pa.table( + {"id": pa.array(ids, pa.large_binary()), "x": ext.wrap_array(storage)} + ) + + db = DeltaTableDatabase(tmp_path / "delta") + db.add_records(PATH, rows(ListExt(b"m"), [b"1"]), record_id_column="id", flush=True) + second = ListExt(b"m") + given = rows(second, [b"1", b"22"]) + second.payload = b"changed" # the serializer now answers otherwise + db.add_records(PATH, given, record_id_column="id", flush=True) + stored = deltalake.DeltaTable(str(tmp_path / "delta" / "t")).schema().fields[1] + assert metadata_bytes(stored.metadata)[META] == b"m" + stored_rows = db.get_all_records(PATH, record_id_column="id") + assert stored_rows is not None and stored_rows.num_rows == 2 From 1fa8b21baf06a9b06b021d7422ffa7dbb8b2ad66 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:09:26 -0800 Subject: [PATCH 10/14] fix(databases): the identity refusal comes first, whatever skip_duplicates (ITL-1371) One rule in every database and one order in both duplicate settings: the identity check (in Delta, from the log, before anything decodes) runs first and refuses a known different identifier, duplicate-only or not; only then does the duplicate scan run, and a read failure there propagates as a read failure. On main a duplicate-only append of another identifier was a silent no-op; it is now refused (nothing was or is written). A duplicate-only append of the same identifier stays a no-op. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1371.md | 4 +- docs/dev/design_issues/ITL-1371-LI1.md | 13 +-- src/orcapod/databases/delta_lake_databases.py | 27 +++--- src/orcapod/databases/in_memory_databases.py | 15 +--- .../test_logical_identity_appends.py | 88 ++++++++++++------- 5 files changed, 83 insertions(+), 64 deletions(-) diff --git a/changelog.d/ITL-1371.md b/changelog.d/ITL-1371.md index b789f9faf..51f63ddc9 100644 --- a/changelog.d/ITL-1371.md +++ b/changelog.d/ITL-1371.md @@ -6,7 +6,9 @@ has the stored or pending column's storage type but another logical type identifier: another extension name, the same name with other extension metadata, or a logical type where the stored column has none, and the reverse. It raises `InputValidationError` - naming the column and both identifiers before anything is written. Before, such rows were + naming the column and both identifiers before anything is written, whatever + `skip_duplicates` (an append of only rows already stored, which wrote nothing and raised + nothing before, is refused too). Before, such rows were accepted in several cases (a Delta column in the annotated form, extension arrays whose types differ only in their metadata) and read back as the stored type. An append with the same identifier is decided as before; identifiers are compared as stored bytes. A diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 401a9e3ae..239a9b896 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -58,11 +58,14 @@ kind of type) is left to those checks too. The ITL-1334 comparison is unchanged it. In-memory and connector databases apply it in `add_records`, Delta in `add_records` (`_identity_refusal`, pending and stored) and again at flush (`_append_refusal`). A refusal raises `InputValidationError` naming the column, the path and both identifiers' -text, before anything is buffered. As in the other Delta checks, the rule runs after -`skip_duplicates` has dropped the rows already stored: an append that writes nothing is not -refused, in Delta and in memory (in memory by its record ids only; main's ordinary -check keeps its priority). In Delta it reads the log only and is found before anything -decodes a stored type (the duplicate scan, the held columns), with either duplicate setting. The database type matrix appends each logical type again under another extension +text, before anything is buffered, whatever `skip_duplicates`: an append whose column carries +a known different identifier is refused, duplicate-only or not (on main a duplicate-only +append with `skip_duplicates` was a silent no-op; nothing was or is written), while a +duplicate-only append of the same identifier stays a no-op. The order is the same with +either setting: in Delta the rule reads the log only and runs first, before anything decodes +a stored type (the duplicate scan, the held columns), so no read failure can come before it; +only when it passes or abstains does the duplicate scan run, and a read failure there +propagates as a read failure. The database type matrix appends each logical type again under another extension name, which every database refuses. So the only appends whose verdict differs from main are those with a known different diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 7049c7120..a90f8405e 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2005,26 +2005,25 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) self._refuse_untyped_null_columns(record_path, records.schema) - # A logical type identifier known to differ from the held one (ITL-1371), - # found from the Delta log before anything decodes a stored type; raised - # once the duplicate scan shows the append writes something. + # A logical type identifier known to differ from the held one is refused + # first (ITL-1371), whatever skip_duplicates: found from the Delta log, before + # anything decodes a stored type (the duplicate scan below does), so no read + # failure can come before it. A whole-input condition, outside the row error + # policy. identity = self._identity_refusal(record_path, records) + if identity is not None: + raise InputValidationError(identity) # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) # Step 3: Handle conflicts based on skip_duplicates setting if skip_duplicates: - try: - filtered_table = self._filter_existing_records( - record_path, deduplicated_table - ) - except OrcapodDatabaseReadError as error: - # A read failure fails the run whatever the error policy: it is - # raised as it is, naming the identifiers it kept from refusing. - if identity is not None: - error.add_note(f"Also refused: {identity}") - raise + # A read failure here propagates as it is: it fails the run whatever + # the error policy. + filtered_table = self._filter_existing_records( + record_path, deduplicated_table + ) if filtered_table.num_rows == 0: logger.debug("All records were duplicates, nothing to insert") return None @@ -2032,8 +2031,6 @@ def add_records( # Check for conflicts - insert never allows duplicates when skip_duplicates=False # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table - if identity is not None: - raise InputValidationError(identity) # Columns match by name within a pending batch: rows with the pending # batch's columns in another order, each field equal, are put in its order diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index eea2257e5..61ae0fa7a 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -281,20 +281,9 @@ def add_records( if table is not None ] # A column of another logical type would read back as the held one - # (ITL-1371); refused before the other checks, so the error names the - # identifiers. An append that writes nothing (with skip_duplicates, every - # record id already held) is not refused for it, as in Delta; the ordinary - # check below keeps main's place and priority. + # (ITL-1371): refused first, so the error names the identifiers, whatever + # skip_duplicates (as in every database). identity = first_logical_identity_change(held, records) - if identity is not None and skip_duplicates: - given_ids = set(records[self.RECORD_ID_COLUMN].to_pylist()) - held_ids = self._pending_record_ids[record_key] - committed = self._committed_id_index(record_key) - # As _filter_existing_records: a null id is never a committed record. - if all( - i in held_ids or (i is not None and i in committed) for i in given_ids - ): - identity = None changed = identity or first_changed_column(held, records.schema) if changed is not None: raise InputValidationError( diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index afae9e9f5..4b04c182f 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1175,10 +1175,10 @@ def test_a_dictionary_over_a_plain_held_column_is_refused_outside_delta( ) -def test_in_memory_duplicate_only_append_is_not_refused() -> None: - """With ``skip_duplicates``, an append whose every row is already stored writes - nothing and is not refused for another identifier, as in Delta; one with a new - row is.""" +def test_in_memory_duplicate_only_append_of_another_identifier_is_refused() -> None: + """One rule in every database: a known different identifier is refused whatever + ``skip_duplicates``, duplicate-only or not (on main, a duplicate-only append was a + silent no-op; nothing was or is written).""" db = InMemoryArrowDatabase() db.add_records( PATH, @@ -1186,19 +1186,14 @@ def test_in_memory_duplicate_only_append_is_not_refused() -> None: record_id_column="id", flush=True, ) - db.add_records( - PATH, - _container_rows("list_view", b"n", [b"1"]), - record_id_column="id", - skip_duplicates=True, - ) - with pytest.raises(InputValidationError, match="itl1371.a;6e"): - db.add_records( - PATH, - _container_rows("list_view", b"n", [b"1", b"22"]), - record_id_column="id", - skip_duplicates=True, - ) + for ids in ([b"1"], [b"1", b"22"]): + with pytest.raises(InputValidationError, match="itl1371.a;6e"): + db.add_records( + PATH, + _container_rows("list_view", b"n", ids), + record_id_column="id", + skip_duplicates=True, + ) db.flush() stored = db.get_all_records(PATH, record_id_column="id") assert stored is not None @@ -1370,12 +1365,16 @@ 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 identity rule reads the Delta log only and comes before every path that - decodes the stored types (the duplicate scan, the held columns), so another - identifier is refused naming both. With ``skip_duplicates`` the duplicate scan - must read the stored ids, which decodes: that read failure is raised as it is (a - read failure fails the run whatever the error policy), with the identity refusal - noted on it.""" + 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: @@ -1402,21 +1401,25 @@ def rows(ids: list[bytes], name: bytes, meta: bytes) -> pa.Table: ) pa.register_extension_type(cast(Any, Current())) try: - expected = OrcapodDatabaseReadError if skip_duplicates else InputValidationError - with pytest.raises(expected) as refused: + 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, ) - message = ( - "\n".join([str(refused.value), *refused.value.__notes__]) - if (skip_duplicates) - else str(refused.value) - ) + 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") finally: pa.unregister_extension_type("itl1371.current") @@ -1594,3 +1597,28 @@ def rows(ext: Any, ids: list[bytes]) -> pa.Table: assert metadata_bytes(stored.metadata)[META] == b"m" stored_rows = db.get_all_records(PATH, record_id_column="id") assert stored_rows is not None and stored_rows.num_rows == 2 + + +@pytest.mark.parametrize("state", ["pending", "committed"]) +@pytest.mark.parametrize("kind", KINDS) +def test_duplicate_only_append_of_the_same_identifier_is_a_no_op( + tmp_path: Path, kind: str, state: str +) -> None: + """With ``skip_duplicates``, an append whose every row is already held, with the + same identifier, writes nothing and raises nothing, as on main, in every + database.""" + with _store(kind, tmp_path) as store: + store.db.add_records( + PATH, + _rows(HELD, "annotated", "top", [b"1", b"22"]), + record_id_column="id", + flush=state == "committed", + ) + store.db.add_records( + PATH, + _rows(HELD, "annotated", "top", [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + stored = store.stored().sort_by("id") + assert stored.column("id").to_pylist() == [b"1", b"22"] From a1ea3b8ddee4be9f16fe9b756f4b4d6f4a6b7dea Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:31:14 -0800 Subject: [PATCH 11/14] fix(databases): identity walk through Delta lists and maps; every chunk; fresh refusals (ITL-1371) Review round 4 of PR 492: - The Delta log walk goes through a list item or map key/item (its own identifier not kept) to the struct children beneath it, whose identifiers the log keeps. - Every chunk of a given column is read, for both forms: a later chunk's nested annotation is compared too. - Delta decides every identity refusal on the freshly loaded version; an accept reads the held handle (no extra read per append) and is rechecked at flush. - In memory and in connector databases the raw identity check runs before the reorder by name, which may call an extension's serializer. - The design entry, changelog and PR body state the limits: the MERGE source bytes, TypeIdentityError from the duplicate scan, zero-row and unwritable appends, the stale-handle and connector cache behaviour. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1371.md | 11 +- docs/dev/design_issues/ITL-1371-LI1.md | 20 ++ .../databases/connector_arrow_database.py | 19 +- src/orcapod/databases/delta_lake_databases.py | 85 ++++-- src/orcapod/databases/in_memory_databases.py | 32 +- src/orcapod/databases/utils.py | 26 +- .../test_logical_identity_appends.py | 275 ++++++++++++++++++ 7 files changed, 411 insertions(+), 57 deletions(-) diff --git a/changelog.d/ITL-1371.md b/changelog.d/ITL-1371.md index 51f63ddc9..c7cf97aaa 100644 --- a/changelog.d/ITL-1371.md +++ b/changelog.d/ITL-1371.md @@ -7,11 +7,14 @@ another extension name, the same name with other extension metadata, or a logical type where the stored column has none, and the reverse. It raises `InputValidationError` naming the column and both identifiers before anything is written, whatever - `skip_duplicates` (an append of only rows already stored, which wrote nothing and raised - nothing before, is refused too). Before, such rows were + `skip_duplicates`: an append of only rows already stored is refused too (before, Delta + wrote nothing and raised nothing for it; the in-memory and connector databases already + refused it when the change showed in the field annotation). Before, such rows were accepted in several cases (a Delta column in the annotated form, extension arrays whose types differ only in their metadata) and read back as the stored type. An append with the same identifier is decided as before; identifiers are compared as stored bytes. A - list item or map key or item of a stored Delta table, whose identifier Delta does not - keep (ITL-1372), is decided as before. + list item or map key or item of a stored Delta table, whose own identifier Delta does + not keep (ITL-1372), is decided as before; a struct's children beneath it are compared. Delta's MERGE now writes the identifier bytes Arrow + holds, not what the extension's serializer answers when asked again. A zero-row append, + and an encoding the database cannot write, keep their verdict. (ITL-1371) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 239a9b896..29022c945 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -68,6 +68,26 @@ only when it passes or abstains does the duplicate scan run, and a read failure propagates as a read failure. The database type matrix appends each logical type again under another extension name, which every database refuses. +Delta decides every refusal on the version stored now: a difference found on the handle it +holds (loaded at its last load or flush) is compared again on the table loaded afresh, so a +held handle never refuses what a reopened one accepts; accepting reads the held handle (no +extra read per append), and an accept is checked again at flush, against the version then +loaded, before anything is written. The one remaining difference writes nothing either way: +a duplicate-only append of the identifier a stale version holds is a no-op on the held +handle, where a reopened handle refuses it. A connector database compares against the +stored schema it caches for the ITL-1334 check (`_stored_schemas`), as main's check does, so +a table replaced by another connection is seen as main sees it (pre-existing). + +Limits and differences from main, stated: Delta's MERGE source (a batch with an id already +stored) now carries the identifier bytes Arrow holds, not the serializer asked again, so for +an extension whose serializer changes after its type was made, or raises, the stored form +(and, for a raising serializer, the verdict: main failed the commit) differs from main in +that one case. A decode failure of the duplicate scan that is a `TypeIdentityError` +propagates as itself (main's ITL-881 carve-out), not as `OrcapodDatabaseReadError`. A +zero-row append, and an encoding the database cannot write (refused as unstorable before the +rule: metadata that is not UTF-8 in Delta, any field metadata in SQLite), are outside the +identity rule and keep main's verdict. + So the only appends whose verdict differs from main are those with a known different identifier. Where Delta stored a nested extension type as plain storage (a list item or map value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6c9e20b15..c1d3dc410 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -443,6 +443,9 @@ def add_records( # Columns match by name: rows with the held columns in another order are # put in the held order, so the connector always receives the stored order # (ITL-1367). + # A column of another logical type is refused first, on the raw identifier + # bytes, before the reorder compares types (ITL-1371). + self._refuse_changed_columns(record_path, records, identity_only=True) records = in_held_column_order(records, self._held_column_order(record_path)) self._refuse_changed_columns(record_path, records) @@ -521,7 +524,11 @@ def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": ] def _refuse_changed_columns( - self, record_path: tuple[str, ...], records: pa.Table + self, + record_path: tuple[str, ...], + records: pa.Table, + *, + identity_only: bool = False, ) -> None: """Refuse rows whose columns would not read back as written (ITL-1334). @@ -533,6 +540,10 @@ def _refuse_changed_columns( is checked. The stored table's schema is read once per table (``_read_stored_schema``): an append the check accepts does not change it. + A column of another logical type identifier is refused first + (``first_logical_identity_change``, ITL-1371); ``identity_only`` checks only + that, so it can run before the rows are reordered by name. + Raises: InputValidationError: For the first such column, naming it and the path. """ @@ -551,9 +562,9 @@ def _refuse_changed_columns( if stored is not None: held.append(stored) # A column of another logical type would read back as the held one (ITL-1371). - changed = first_logical_identity_change(held, records) or first_changed_column( - held, records.schema - ) + changed = first_logical_identity_change(held, records) + if changed is None and not identity_only: + changed = first_changed_column(held, records.schema) if changed is not None: raise InputValidationError( f"Cannot append to the table at {record_path!r}: column " diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index a90f8405e..b7056fd8c 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -37,7 +37,6 @@ LIST_ITEM, MAP_ITEM, MAP_KEY, - UNKNOWN, IdentityNode, appended_field_change, coerce_record_id, @@ -653,7 +652,8 @@ def _delta_identity_node( proves nothing and the identity rule abstains. A list item and a map key or item keep no metadata in the log (ITL-1372), and the column's recorded type is read through the Arrow registry, which may give an identifier other than the one - stored: there the identifier is never known. + stored: there the identifier is never known, while the children of a struct + beneath it are (``_unknown_place``). Args: delta_type: A ``deltalake.schema`` type from the log. @@ -672,9 +672,12 @@ def _delta_identity_node( for f in delta_type.fields ) elif isinstance(delta_type, ArrayType): - children = ((LIST_ITEM, UNKNOWN),) + children = ((LIST_ITEM, _unknown_place(delta_type.element_type, recorded)),) elif isinstance(delta_type, MapType): - children = ((MAP_KEY, UNKNOWN), (MAP_ITEM, UNKNOWN)) + children = ( + (MAP_KEY, _unknown_place(delta_type.key_type, recorded)), + (MAP_ITEM, _unknown_place(delta_type.value_type, recorded)), + ) as_bytes = metadata_bytes(metadata) name = as_bytes.get(_EXTENSION_KEYS[0]) identifier = None if name is None else (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) @@ -685,6 +688,15 @@ def _delta_identity_node( ) +def _unknown_place(delta_type: Any, recorded: bool) -> IdentityNode: + """A list item or map key or item as the Delta log gives it: its own identifier + is not known (the log keeps no metadata there, ITL-1372), but a struct beneath it + keeps its children's metadata in the log, byte for byte, so the walk goes on + through it to them.""" + place = _delta_identity_node(delta_type, None, recorded) + return IdentityNode(known=False, identifier=None, children=place.children) + + def _stored_identities( delta_table: deltalake.DeltaTable, ) -> list[tuple[str, IdentityNode]]: @@ -1829,25 +1841,62 @@ def _identity_refusal( Returns: The error message, or ``None``. """ - held: list[list[tuple[str, IdentityNode]]] = [] + found = None pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: - held.append([(f.name, identity_node(f)) for f in pending.schema]) + found = identity_refusal( + [(f.name, identity_node(f)) for f in pending.schema], rows + ) + if found is None: + found = self._stored_identity_refusal(record_path, rows) + if found is None: + return None + return ( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: column {found[0]!r}: " + f"{found[1]}. The stored rows are unchanged and nothing was written." + ) + + def _stored_identity_refusal( + self, record_path: tuple[str, ...], rows: pa.Table + ) -> tuple[str, str] | None: + """``identity_refusal`` against the stored table, every refusal decided on + its freshly loaded version (ITL-1371). + + The handle this instance holds is the one loaded at its last load or flush, + and accepting reads it as it is (no extra read per append: function nodes + append row by row). A refusal is never decided on it: when it shows a + difference, the table is loaded again and compared once more, so a held + handle never refuses what a reopened one accepts. An accept on a stale handle + is checked again at flush, against the version then loaded, before anything + is written; the one append it can leave different from a reopened handle + writes nothing either way (a duplicate-only append of the identifier the + stale version holds: a no-op here, refused there). + + Args: + record_path: The table the rows are for. + rows: The rows to append, as given. + + Returns: + The column and the reason, or ``None``. + """ try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: - delta_table = None - if delta_table is not None: - held.append(_stored_identities(delta_table)) - for given in held: - found = identity_refusal(given, rows) - if found is not None: - return ( - f"Cannot append to the stored table " - f"{self._get_table_uri(record_path)!r}: column {found[0]!r}: " - f"{found[1]}. The stored rows are unchanged and nothing was written." - ) - return None + return None + if delta_table is None: + return None + if identity_refusal(_stored_identities(delta_table), rows) is None: + return None + # Decide the refusal on the version stored now. + self._delta_table_cache.pop(self._get_record_key(record_path), None) + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + return None + if delta_table is None: + return None + return identity_refusal(_stored_identities(delta_table), rows) def _refuse_changed_attributes( self, record_path: tuple[str, ...], schema: pa.Schema diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 61ae0fa7a..29cf9746d 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -260,6 +260,24 @@ def add_records( ) record_key = self._get_record_key(record_path) + held = [ + table.schema + for table in ( + self._tables.get(record_key), + self._pending_batches.get(record_key), + ) + if table is not None + ] + # A column of another logical type would read back as the held one + # (ITL-1371): refused first, on the raw identifier bytes, before the + # reorder below compares types (which may call an extension's serializer), + # whatever skip_duplicates (as in every database). + identity = first_logical_identity_change(held, records) + if identity is not None: + raise InputValidationError( + f"Cannot append to the table at {record_path!r}: column " + f"{identity[0]!r}: {identity[1]}. Nothing was written." + ) # Columns match by name: rows with the held columns in another order are # put in the held order, the pending batch's, else the stored table's # (ITL-1367). @@ -272,19 +290,7 @@ def add_records( ) # The table holds one type per column: rows whose field metadata or nested # field attributes differ would read back with the held ones (ITL-1334). - held = [ - table.schema - for table in ( - self._tables.get(record_key), - self._pending_batches.get(record_key), - ) - if table is not None - ] - # A column of another logical type would read back as the held one - # (ITL-1371): refused first, so the error names the identifiers, whatever - # skip_duplicates (as in every database). - identity = first_logical_identity_change(held, records) - changed = identity or first_changed_column(held, records.schema) + changed = first_changed_column(held, records.schema) if changed is not None: raise InputValidationError( f"Cannot append to the table at {record_path!r}: column " diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 99bb413cd..98089bf60 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -491,8 +491,10 @@ def given_identities( A column's field, and, for a table, each of its chunks: pyarrow lets the chunks of one column hold instances of one Python extension class with other serialized - metadata (it compares them by class), so each chunk's own exported identifier is - read too, and every one of them must be the held one. + metadata (it compares them by class), and nested fields with other field + metadata, an annotation included (it compares types without it), so every + chunk's own type is read too, in both forms, and every one of them must be the + held one. Args: given: The rows to append, or only their schema. @@ -507,26 +509,14 @@ def given_identities( nodes = [identity_node(field)] seen = set(nodes) for chunk in column.chunks: - if _has_extension_part(chunk.type): - node = identity_node(field.with_type(chunk.type)) - if node not in seen: - seen.add(node) - nodes.append(node) + node = identity_node(field.with_type(chunk.type)) + if node not in seen: + seen.add(node) + nodes.append(node) out.append((field.name, nodes)) return out -def _has_extension_part(arrow_type: Any) -> bool: - if isinstance(arrow_type, pa.BaseExtensionType): - return True - if pa.types.is_dictionary(arrow_type): - return _has_extension_part(arrow_type.value_type) - return any( - _has_extension_part(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) - ) - - def identity_refusal( held: "Sequence[tuple[str, IdentityNode]]", given: "pa.Table | pa.Schema" ) -> tuple[str, str] | None: diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 4b04c182f..a74b71889 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1622,3 +1622,278 @@ def test_duplicate_only_append_of_the_same_identifier_is_a_no_op( ) stored = store.stored().sort_by("id") assert stored.column("id").to_pylist() == [b"1", b"22"] + + +# --------------------------------------------------------------------------- +# Review round 4 (PR 492) +# --------------------------------------------------------------------------- + + +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]) + 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}) + + +@pytest.mark.parametrize("state", ["committed", "reopened"]) +@pytest.mark.parametrize("form", FORMS) +@pytest.mark.parametrize("shape", ["list", "map"]) +def test_delta_struct_children_beneath_lists_and_maps_are_compared( + tmp_path: Path, shape: str, form: str, state: str +) -> None: + """A list item or map item keeps no metadata in the Delta log, but the children + of a struct beneath it do: the walk goes through the unknown item to them, so + another identifier there is refused, with fresh ids and duplicate-only, and the + same identifier is accepted.""" + path = "x[].v" if shape == "list" else "x.item.v" + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, + _struct_beneath(shape, form, b"m", [b"1", b"22"]), + record_id_column="id", + flush=True, + ) + if state == "reopened": + store.reopen() + for ids, skip in (([b"333"], False), ([b"1", b"22"], True)): + with pytest.raises( + InputValidationError, match=re.escape(f"{path} is of logical type") + ): + store.db.add_records( + PATH, + _struct_beneath(shape, form, b"n", ids), + record_id_column="id", + skip_duplicates=skip, + ) + stored = store.stored() + assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ + b"1", + b"22", + ] + + +def _late_chunk_rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: + """``x: struct``, one chunk per id, ``v`` annotated ``itl1371.a;`` in its + own chunk: the column's field carries the first chunk's annotation only.""" + chunks = [] + for meta, i in zip(metas, ids): + field = pa.field( + "v", pa.large_string(), metadata={NAME: b"itl1371.a", META: meta} + ) + chunks.append( + pa.StructArray.from_arrays( + [pa.array([i.decode()], pa.large_string())], fields=[field] + ) + ) + column = pa.chunked_array(chunks) + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), column], + schema=pa.schema( + [pa.field("id", pa.large_binary()), pa.field("x", chunks[0].type)] + ), + ) + + +@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: + """Arrow keeps a nested field's annotation per chunk: a later chunk of another + annotated identifier is refused, with fresh ids and duplicate-only, in every + database; chunks of the same identifier are accepted.""" + with _store(kind, tmp_path) as store: + store.db.add_records( + PATH, + _late_chunk_rows([b"m"], [b"1"]), + record_id_column="id", + flush=state == "committed", + ) + mixed = _late_chunk_rows([b"m", b"n"], [b"1", b"22"]) + assert [c.type.field("v").metadata[META] for c in mixed.column("x").chunks] == [ + b"m", + b"n", + ] + for skip in (False, True): + with pytest.raises(InputValidationError, match="x.v is of logical type"): + store.db.add_records( + PATH, mixed, record_id_column="id", skip_duplicates=skip + ) + store.db.add_records( + PATH, _late_chunk_rows([b"m", b"m"], [b"22", b"333"]), record_id_column="id" + ) + stored = store.stored() + assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ + b"1", + b"22", + b"333", + ] + + +def _annotated_top(meta: bytes, ids: list[bytes]) -> pa.Table: + field = pa.field("x", pa.large_string(), metadata={NAME: b"itl1371.a", META: meta}) + return pa.Table.from_arrays( + [ + pa.array(ids, pa.large_binary()), + pa.array(["v"] * len(ids), pa.large_string()), + ], + schema=pa.schema([pa.field("id", pa.large_binary()), field]), + ) + + +def test_delta_refusals_are_decided_on_the_table_stored_now(tmp_path: Path) -> None: + """A handle kept open while the table is replaced (same ids, another identifier): + every refusal is decided on the version stored now, so the held handle never + refuses what a reopened one accepts. A fresh-id append the stale handle accepts is + refused at flush, against the version then loaded, before anything is written. + The one remaining difference writes nothing either way: a duplicate-only append + of the identifier the stale version holds is a no-op on the held handle, where a + reopened handle refuses it.""" + import deltalake + + root = tmp_path / "delta" + held = DeltaTableDatabase(root) + held.add_records( + PATH, _annotated_top(b"m", [b"1", b"22"]), record_id_column="id", flush=True + ) + replacement = _annotated_top(b"n", [b"1", b"22"]).rename_columns( + ["__record_id", "x"] + ) + deltalake.write_deltalake( + str(root / "t"), replacement, mode="overwrite", schema_mode="overwrite" + ) + reopened = DeltaTableDatabase(root) + + # The identifier stored now, duplicate-only: accepted (a no-op) by both handles; + # the held handle's stale log differs, so it decides on the version stored now. + for db in (held, reopened): + db.add_records( + PATH, + _annotated_top(b"n", [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + # The replaced identifier, duplicate-only, on a reopened handle: refused. + with pytest.raises( + InputValidationError, match="the stored column's 'itl1371.a;6e'" + ): + reopened.add_records( + PATH, + _annotated_top(b"m", [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + + # A fresh handle opened before a second replacement, back to ``m``. + stale_handle = DeltaTableDatabase(root) + stale_handle.get_all_records(PATH, record_id_column="id") # loads the ``n`` version + deltalake.write_deltalake( + str(root / "t"), + _annotated_top(b"m", [b"1", b"22"]).rename_columns(["__record_id", "x"]), + mode="overwrite", + schema_mode="overwrite", + ) + # Duplicate-only ``n`` on the stale handle: a no-op (writes nothing); a reopened + # handle refuses it. + stale_handle.add_records( + PATH, + _annotated_top(b"n", [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + with pytest.raises(InputValidationError): + DeltaTableDatabase(root).add_records( + PATH, + _annotated_top(b"n", [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + # Duplicate-only ``m`` (stored now) on the stale handle: its stale log says ``n``, + # the refusal is decided on the version stored now, ``m``: accepted, a no-op. + stale_handle.add_records( + PATH, + _annotated_top(b"m", [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + # A fresh id of ``n`` on a stale handle that accepts it: refused at flush. + other_stale = DeltaTableDatabase(root) + other_stale.get_all_records(PATH, record_id_column="id") + deltalake.write_deltalake( + str(root / "t"), + _annotated_top(b"n", [b"1", b"22"]).rename_columns(["__record_id", "x"]), + mode="overwrite", + schema_mode="overwrite", + ) + other_stale.add_records(PATH, _annotated_top(b"m", [b"333"]), record_id_column="id") + with pytest.raises( + InputValidationError, match="the stored column's 'itl1371.a;6e'" + ): + other_stale.flush() + final = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="id") + assert final is not None + assert sorted(cast(list[bytes], final.column("id").to_pylist())) == [b"1", b"22"] + + +@pytest.mark.parametrize("kind", ["in-memory", "Delta"]) +def test_the_identity_is_refused_before_the_reorder_calls_a_serializer( + tmp_path: Path, kind: str +) -> None: + """The rows are reordered by name (ITL-1367) after the identity rule, which reads + the bytes Arrow holds: a permuted batch of another identifier whose serializer + raises when asked again is refused naming both identifiers.""" + + class Raising(pa.ExtensionType): + def __init__(self, payload: bytes | None) -> None: + self.payload = payload + super().__init__(pa.large_string(), "itl1371.raising") + + def __arrow_ext_serialize__(self) -> bytes: + if self.payload is None: + raise RuntimeError("serializer asked again") + return self.payload + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized) + + def rows(ext: Any, ids: list[bytes]) -> pa.Table: + x = ext.wrap_array(pa.array(["v"] * len(ids), pa.large_string())) + return pa.table( + { + "id": pa.array(ids, pa.large_binary()), + "x": x, + "z": pa.array(range(len(ids)), pa.int64()), + } + ) + + with _store(kind, tmp_path) as store: + store.db.add_records( + PATH, rows(Raising(b"old"), [b"1", b"22"]), record_id_column="id" + ) + incoming = Raising(b"new") + permuted = rows(incoming, [b"1", b"22"]).select(["z", "id", "x"]) + incoming.payload = None + with pytest.raises(InputValidationError) as refused: + store.db.add_records( + PATH, permuted, record_id_column="id", skip_duplicates=True + ) + assert "'itl1371.raising;6e6577'" in str(refused.value) + assert "'itl1371.raising;6f6c64'" in str(refused.value) From 1c790dfb203d620a9beb759364d46ad5784c91d3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:38:50 -0800 Subject: [PATCH 12/14] test(databases): every review finding of ITL-1371 pinned by a test Developer requirement: each Codex and CodeRabbit finding has a test. Adds parametrized tests for the recorded plain types, chunk identifiers in Delta, an undecodable child beneath lists and maps, and pins for the stated limits: the MERGE source with a changed or raising serializer, TypeIdentityError from the duplicate scan, zero-row and unwritable appends, the connector's cached schema and the flush-time recheck after another writer. Co-Authored-By: Claude Opus 5.5 --- .../test_logical_identity_appends.py | 412 +++++++++++++++--- 1 file changed, 351 insertions(+), 61 deletions(-) diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index a74b71889..d98c9bf26 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1258,47 +1258,88 @@ def test_extension_metadata_that_is_not_text(state: str) -> None: assert stored is not None and stored.num_rows == 2 +RECORDED_STORAGES = { + "uint16": (pa.uint16(), lambda n: list(range(n))), + "fixed_size_binary": (pa.binary(4), lambda n: [b"%04d" % i for i in range(n)]), +} + + @pytest.mark.parametrize("state", ["committed", "reopened"]) -def test_delta_logical_type_over_a_plain_column(tmp_path: Path, state: str) -> None: - """A stored Delta column with no identifier is known to hold no logical type only - when the log records its Arrow type: then another identifier is refused, - dictionary-encoded or not. Without a record (a plain text column, or one Delta - wrote from a dictionary of extension values, losing its identifier: ITL-1372) the - absence proves nothing and the rule abstains, so main's checks decide: an - extension column is accepted, as on main.""" - uint16 = pa.uint16() - - def recorded_rows(ids: list[bytes], identifier: bool, encoded: bool) -> pa.Table: - values: Any = pa.array(range(len(ids)), uint16) - if identifier: - values = _UINT16(b"e").wrap_array(values) - if encoded: +@pytest.mark.parametrize("encoded", [False, True], ids=["plain", "dictionary"]) +@pytest.mark.parametrize("form", FORMS) +@pytest.mark.parametrize("storage", list(RECORDED_STORAGES)) +def test_delta_logical_type_over_a_recorded_plain_column( + tmp_path: Path, storage: str, form: str, encoded: bool, state: str +) -> None: + """A stored Delta column whose log records its Arrow type (``uint16``, fixed-size + binary) and carries no identifier is known to hold no logical type: another + identifier is refused, as an extension type or an annotation, dictionary-encoded + or not (round 3, finding 1).""" + arrow_type, values_of = RECORDED_STORAGES[storage] + + def rows(ids: list[bytes], identifier: bool) -> pa.Table: + values: Any = pa.array(values_of(len(ids)), arrow_type) + field = pa.field("x", arrow_type) + if identifier and form == "extension": + values = _ext_over(arrow_type)(b"e").wrap_array(values) + field = pa.field("x", values.type) + elif identifier: + field = pa.field( + "x", arrow_type, metadata={NAME: b"itl1371.over", META: b"e"} + ) + if encoded and identifier: values = pa.DictionaryArray.from_arrays( pa.array(range(len(ids)), pa.int8()), values ) + field = field.with_type(values.type) return pa.Table.from_arrays( - [pa.array(ids, pa.large_binary()), values], names=["id", "x"] + [pa.array(ids, pa.large_binary()), values], + schema=pa.schema([pa.field("id", pa.large_binary()), field]), ) - for encoded in (False, True): - root = tmp_path / f"recorded-{encoded}" - with _store("Delta", root) as store: - store.db.add_records( - PATH, - recorded_rows([b"1"], False, False), - record_id_column="id", - flush=True, - ) - if state == "reopened": - store.reopen() - with pytest.raises( - InputValidationError, match="stored column's no logical" - ): - store.db.add_records( - PATH, recorded_rows([b"22"], True, encoded), record_id_column="id" - ) - assert store.stored().column("id").to_pylist() == [b"1"] + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, rows([b"1"], False), record_id_column="id", flush=True + ) + 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") + assert store.stored().column("id").to_pylist() == [b"1"] + + +_EXT_OVER: dict[str, Any] = {} + + +def _ext_over(storage: Any) -> Any: + """An extension class named ``itl1371.over`` over ``storage``, one per storage.""" + key = str(storage) + if key not in _EXT_OVER: + + class _Over(pa.ExtensionType): + def __init__(self, meta: bytes) -> None: + self._meta = meta + super().__init__(storage, "itl1371.over") + + def __arrow_ext_serialize__(self) -> bytes: + return self._meta + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: Any, serialized: bytes + ) -> Any: + return cls(serialized) + + _EXT_OVER[key] = _Over + return _EXT_OVER[key] + + +@pytest.mark.parametrize("state", ["committed", "reopened"]) +def test_delta_logical_type_over_a_plain_column(tmp_path: Path, state: str) -> None: + """Without a recorded Arrow type (a plain text column, or one Delta wrote from a + dictionary of extension values, losing its identifier: ITL-1372) a stored column + with no identifier proves nothing and the rule abstains, so main's checks decide: + an extension column is accepted, as on main (round 3, findings 1 and 5).""" with _store("Delta", tmp_path / "unrecorded") as store: store.db.add_records( PATH, @@ -1314,25 +1355,6 @@ def recorded_rows(ids: list[bytes], identifier: bool, encoded: bool) -> pa.Table assert store.stored().num_rows == 2 -def _uint16_type() -> Any: - class _UInt16(pa.ExtensionType): - def __init__(self, meta: bytes) -> None: - self._meta = meta - super().__init__(pa.uint16(), "itl1371.uint16") - - def __arrow_ext_serialize__(self) -> bytes: - return self._meta - - @classmethod - def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: - return cls(serialized) - - return _UInt16 - - -_UINT16 = _uint16_type() - - @pytest.mark.parametrize("state", ["committed", "reopened"]) def test_delta_extension_after_a_dictionary_first_write( tmp_path: Path, state: str @@ -1481,11 +1503,16 @@ def rows(name: bytes, ids: list[bytes]) -> pa.Table: assert "\"b'\\\\xff';\", the stored column's b'\\xff';" in str(refused.value) +@pytest.mark.parametrize("skip_duplicates", [False, True]) @pytest.mark.parametrize("state", ["pending", "committed"]) -def test_every_chunk_identifier_is_compared(state: str) -> None: +@pytest.mark.parametrize("kind", ["in-memory", "Delta"]) +def test_every_chunk_identifier_is_compared( + tmp_path: Path, kind: str, state: str, skip_duplicates: bool +) -> None: """pyarrow lets the chunks of one column hold one Python extension class with other serialized metadata: each chunk's own identifier is compared, so a later - chunk of another identifier is refused; chunks of the same bytes are accepted.""" + chunk of another identifier is refused; chunks of the same bytes are accepted + (round 3, finding 6).""" def rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: chunks = [_wrapped(meta, [i.decode()]) for meta, i in zip(metas, ids)] @@ -1494,12 +1521,22 @@ def rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: names=["id", "x"], ) - db = InMemoryArrowDatabase() + with _store(kind, tmp_path) as store: + _check_chunk_identifiers(store, rows, state, skip_duplicates) + + +def _check_chunk_identifiers( + store: _Store, rows: Any, state: str, skip_duplicates: bool +) -> None: + db = store.db db.add_records( PATH, rows([b"m"], [b"1"]), record_id_column="id", flush=state == "committed" ) - db.add_records(PATH, rows([b"m", b"m"], [b"2", b"3"]), record_id_column="id") - mixed = rows([b"m", b"n"], [b"4", b"5"]) + db.add_records( + PATH, rows([b"m", b"m"], [b"2", b"3"]), record_id_column="id", flush=True + ) + ids = [b"2", b"3"] if skip_duplicates else [b"4", b"5"] + mixed = rows([b"m", b"n"], ids) assert [c.type.__arrow_ext_serialize__() for c in mixed.column("x").chunks] == [ b"m", b"n", @@ -1507,10 +1544,10 @@ def rows(metas: list[bytes], ids: list[bytes]) -> pa.Table: with pytest.raises( InputValidationError, match="'itl1371.a;6e', the stored column's 'itl1371.a;6d'" ): - db.add_records(PATH, mixed, record_id_column="id") - db.flush() - stored = db.get_all_records(PATH, record_id_column="id") - assert stored is not None + db.add_records( + PATH, mixed, record_id_column="id", skip_duplicates=skip_duplicates + ) + stored = store.stored() assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ b"1", b"2", @@ -1897,3 +1934,256 @@ def rows(ext: Any, ids: list[bytes]) -> pa.Table: ) assert "'itl1371.raising;6e6577'" in str(refused.value) assert "'itl1371.raising;6f6c64'" in str(refused.value) + + +# --------------------------------------------------------------------------- +# Every review finding pinned (developer, 2026-11-22): round 4 limits and the +# declined CodeRabbit item +# --------------------------------------------------------------------------- + + +def _failing_reader(error: type[Exception]) -> Any: + """A registered ``itl1371.a`` whose reader cannot read stored metadata.""" + + class Failing(pa.ExtensionType): + def __init__(self) -> None: + super().__init__(pa.large_string(), "itl1371.a") + + def __arrow_ext_serialize__(self) -> bytes: + return b"current" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + 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 +) -> 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" + 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, + ) + 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") + ) 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, + ) + assert "the stored column's 'itl1371.a;6d'" in str(refused.value) + finally: + pa.unregister_extension_type("itl1371.a") + + +def test_delta_duplicate_scan_type_identity_error_propagates_as_itself( + 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.""" + 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) + pa.register_extension_type(cast(Any, _failing_reader(TypeIdentityError)())) + try: + for mode in ("error", "merge", "coerce"): + with pytest.raises(TypeIdentityError): + DeltaTableDatabase(root).add_records( + PATH, + rows, + record_id_column="id", + skip_duplicates=True, + schema_handling=cast(Any, mode), + ) + finally: + pa.unregister_extension_type("itl1371.a") + + +@pytest.mark.parametrize("schema_evolution", [False, True]) +@pytest.mark.parametrize("serializer", ["changed", "raising"]) +def test_delta_merge_source_with_a_changed_or_raising_serializer( + tmp_path: Path, serializer: str, schema_evolution: bool +) -> None: + """Pins the stated difference from main (round 4, finding 5): the MERGE source + carries the identifier bytes Arrow holds. With a serializer that changed after + its type was made, the stored identifier stays the held one (main rewrote it); + with one that raises, the commit goes through under the held bytes (main failed + it).""" + import deltalake + + class ListExt(pa.ExtensionType): + def __init__(self, payload: bytes | None) -> None: + self.payload = payload + super().__init__(pa.large_list(pa.large_string()), "itl1371.lists") + + def __arrow_ext_serialize__(self) -> bytes: + if self.payload is None: + raise RuntimeError("serializer asked again") + return self.payload + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized) + + def rows(ext: Any, ids: list[bytes]) -> pa.Table: + storage = pa.array([["v"]] * len(ids), pa.large_list(pa.large_string())) + return pa.table( + {"id": pa.array(ids, pa.large_binary()), "x": ext.wrap_array(storage)} + ) + + db = DeltaTableDatabase(tmp_path / "delta", allow_schema_evolution=schema_evolution) + db.add_records(PATH, rows(ListExt(b"m"), [b"1"]), record_id_column="id", flush=True) + second = ListExt(b"m") + given = rows(second, [b"1", b"22"]) + second.payload = b"changed" if serializer == "changed" else None + db.add_records(PATH, given, record_id_column="id", flush=True) + stored = deltalake.DeltaTable(str(tmp_path / "delta" / "t")).schema().fields[1] + assert metadata_bytes(stored.metadata)[META] == b"m" + ids = deltalake.DeltaTable(str(tmp_path / "delta" / "t")).to_pyarrow_table() + assert sorted(cast(list[bytes], ids["__record_id"].to_pylist())) == [b"1", b"22"] + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("kind", KINDS) +def test_a_zero_row_append_is_outside_the_rule( + tmp_path: Path, kind: str, skip_duplicates: bool +) -> None: + """Pins a stated limit (round 4, finding 7): a zero-row append writes nothing and + returns before the rule, whatever identifier it carries, as on main.""" + with _store(kind, tmp_path) as store: + store.db.add_records( + PATH, _annotated_top(b"m", [b"1"]), record_id_column="id", flush=True + ) + store.db.add_records( + PATH, + _annotated_top(b"n", []), + record_id_column="id", + skip_duplicates=skip_duplicates, + ) + assert store.stored().column("id").to_pylist() == [b"1"] + + +def test_an_unwritable_encoding_is_refused_before_the_rule(tmp_path: Path) -> None: + """Pins a stated limit (round 4, finding 7): a column the database cannot write is + refused by its own check before the identity rule, as on main: Delta refuses + metadata that is not UTF-8 as unstorable; SQLite refuses any field metadata.""" + from orcapod.databases.sqlite_connector import SQLiteConnector + from orcapod.errors import UnstorableColumnError + + delta = DeltaTableDatabase(tmp_path / "delta") + delta.add_records( + PATH, _annotated_top(b"m", [b"1"]), record_id_column="id", flush=True + ) + with pytest.raises(UnstorableColumnError): + delta.add_records(PATH, _annotated_top(b"\xff", [b"22"]), record_id_column="id") + + sqlite = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) + plain = pa.table( + { + "id": pa.array([b"1"], pa.large_binary()), + "x": pa.array(["v"], pa.large_string()), + } + ) + sqlite.add_records(PATH, plain, record_id_column="id", flush=True) + with pytest.raises(ValueError, match="does not preserve Arrow metadata"): + sqlite.add_records(PATH, _annotated_top(b"n", [b"22"]), record_id_column="id") + + +def test_connector_compares_against_its_cached_stored_schema(tmp_path: Path) -> None: + """Pins the connector's behaviour, as main's (round 4, finding 3): it compares + against the stored schema it caches for the ITL-1334 check, so after another + connection replaces the table (same ids, another identifier), the original + handle still refuses by the replaced identifier and a new handle by the one + stored now.""" + with fake_pyspiral.install(tmp_path / "spiral"): + fake_pyspiral.FakeSpiral().project("p") + held = ConnectorArrowDatabase(SpiralDBConnector("p")) + held.add_records( + PATH, _annotated_top(b"m", [b"1"]), record_id_column="id", flush=True + ) + held.add_records( # reads and caches the stored schema + PATH, + _annotated_top(b"m", [b"1"]), + record_id_column="id", + skip_duplicates=True, + ) + connector = SpiralDBConnector("p") + fake_pyspiral.FakeSpiral().project("p").drop_table( + connector._table_id("t") # pyright: ignore[reportPrivateUsage] # the fake's id of the table + ) + fresh = ConnectorArrowDatabase(connector) + fresh.add_records( + PATH, _annotated_top(b"n", [b"1"]), record_id_column="id", flush=True + ) + with pytest.raises( + InputValidationError, match="the stored column's 'itl1371.a;6d'" + ): + held.add_records( + PATH, + _annotated_top(b"n", [b"1"]), + record_id_column="id", + skip_duplicates=True, + ) + with pytest.raises( + InputValidationError, match="the stored column's 'itl1371.a;6e'" + ): + ConnectorArrowDatabase(SpiralDBConnector("p")).add_records( + PATH, + _annotated_top(b"m", [b"1"]), + record_id_column="id", + skip_duplicates=True, + ) + + +def test_delta_flush_refuses_after_another_writer_changed_the_identifier( + tmp_path: Path, +) -> None: + """Pins the declined CodeRabbit item (flush-time recheck, 11052fab): rows queued + with ``skip_duplicates``, then another writer stores the same ids under another + identifier: the flush, which compares against the version it loads, refuses + the queued rows (they were duplicates the MERGE would not insert; nothing is + lost and the stored rows are the other writer's).""" + import deltalake + + root = tmp_path / "delta" + writer = DeltaTableDatabase(root) + writer.add_records( + PATH, _annotated_top(b"m", [b"1"]), record_id_column="id", skip_duplicates=True + ) + deltalake.write_deltalake( + str(root / "t"), + _annotated_top(b"n", [b"1"]).rename_columns(["__record_id", "x"]), + mode="overwrite", + schema_mode="overwrite", + ) + with pytest.raises( + InputValidationError, match="the stored column's 'itl1371.a;6e'" + ): + writer.flush() + stored = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.column("id").to_pylist() == [b"1"] + assert identity_node(stored.schema.field("x")).identifier == (b"itl1371.a", b"n") From 6eab211eb52b1f4b0dec467d98ac315a79cdfafe Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:52:12 -0800 Subject: [PATCH 13/14] fix(databases): a stored Delta place's identifier comes from its annotation, else its record (ITL-1371) Review round 5 of PR 492: missing physical metadata in the Delta log does not prove a place is plain. A stored place's identifier is known from its own annotation, else from the same place in the column's recorded Arrow type (its annotation, or none where the recorded place is plain), else it is unknown and the rule abstains. A dictionary child under a recorded container (list of list, map of list, fixed-size list, map, top-level struct) appended again with the same identifier keeps main's verdict. The design entry and PR body name the pre-existing delete-and-recreate limit (ITL-1413); the same-identifier statements are conditional on the MERGE exception; the per-chunk test covers a real duplicate-only append. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1371.md | 13 +- docs/dev/design_issues/ITL-1371-LI1.md | 37 ++-- src/orcapod/databases/delta_lake_databases.py | 123 +++++++++--- .../test_logical_identity_appends.py | 189 +++++++++++++++++- 4 files changed, 303 insertions(+), 59 deletions(-) diff --git a/changelog.d/ITL-1371.md b/changelog.d/ITL-1371.md index c7cf97aaa..5c26a0566 100644 --- a/changelog.d/ITL-1371.md +++ b/changelog.d/ITL-1371.md @@ -12,9 +12,12 @@ refused it when the change showed in the field annotation). Before, such rows were accepted in several cases (a Delta column in the annotated form, extension arrays whose types differ only in their metadata) and read back as the stored type. An append with - the same identifier is decided as before; identifiers are compared as stored bytes. A - list item or map key or item of a stored Delta table, whose own identifier Delta does - not keep (ITL-1372), is decided as before; a struct's children beneath it are compared. Delta's MERGE now writes the identifier bytes Arrow - holds, not what the extension's serializer answers when asked again. A zero-row append, - and an encoding the database cannot write, keep their verdict. + the same identifier is decided as before, except at Delta's MERGE (a batch with an id + already stored), which now writes the identifier bytes Arrow holds, not what the + extension's serializer answers when asked again: with a serializer that changed or + raises, the stored form (and, for a raising one, the verdict) differs. Identifiers are + compared as stored bytes. A place of a stored Delta table whose identifier neither the log + nor the column's recorded type gives (a list item or map item of extension values, + ITL-1372) is decided as before. A zero-row append, and an encoding the database cannot + write, keep their verdict. (ITL-1371) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 29022c945..b5decd173 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -35,23 +35,27 @@ extension type whose storage is another extension type, which Arrow cannot expor level is not known and not compared, its storage still is) or the `ARROW:extension:*` annotation; never decoded to decide (a name that is not UTF-8 is shown as a bytes literal, `b'\xff'`, a form no text name takes), never Arrow type equality. A given column's field and -each of its chunks are compared (pyarrow lets the chunks of one Python extension class carry -other serialized metadata). Places pair by name, or by +each of its chunks are compared, a zero-length chunk too (pyarrow lets the chunks of one +column carry other extension metadata and other nested annotations). Places pair by name, or by occurrence where a name repeats among siblings (Arrow allows two struct children, union members or columns of one name), never by name alone. Only a bare `pa.null()` claims no type; an annotated null claims its annotation. The rule only ADDS a refusal where it KNOWS the identifiers differ: from the fields as given (in-memory, a pending batch, a connector's stored schema) and, for a stored Delta table, from -the Delta log, which keeps the field metadata of a column and of each struct child byte for -byte (`_delta_identity_node`). Where the held identifier is not reliably known it abstains: -a Delta list item, map key or item (the log keeps no metadata there, and the recorded type -is read through the Arrow registry, which may rewrite the metadata), and, the one condition -for a missing identifier, a stored Delta place with no identifier in a column whose log -records no Arrow type (`orcapod:arrow_type`): Delta writes a dictionary of extension values as -plain values with no identifier and no record (pre-existing, ITL-1372), so there the absence -proves nothing, whatever the given encoding; with a record, the column is known to hold no -logical type and another identifier is refused, dictionary-encoded or not. Also where a side is an untyped +the Delta log and the column's recorded Arrow type (`_delta_identity_node`). A stored Delta +place's identifier is known from, in this order: the physical field's own annotation (the log +keeps the field metadata of a column and of each struct child byte for byte); else the place +inside the column's recorded Arrow type (`orcapod:arrow_type`): its annotation there, or no +logical type where the recorded place is plain; else it is unknown and the rule abstains. +Missing physical metadata alone never proves "no logical type": a list item or map key or +item keeps none in the log (ITL-1372), a dictionary child is written as plain values (its +identifier stays in the record), and a column written from a dictionary of extension values +records no type at all (pre-existing, ITL-1372), so there the absence proves nothing, +whatever the given encoding; where the record says plain, another identifier is refused, +dictionary-encoded or not. A recorded place the Arrow registry reads back as an extension +type is unknown too (the registry may give other bytes than the ones stored), and so is a +record that cannot be read. Also where a side is an untyped null (`pa.null()`, which holds no value and claims no type), it abstains, and the database's other checks decide exactly as before. A place only one side has (struct evolution, another kind of type) is left to those checks too. The ITL-1334 comparison is unchanged and runs after @@ -72,9 +76,12 @@ Delta decides every refusal on the version stored now: a difference found on the holds (loaded at its last load or flush) is compared again on the table loaded afresh, so a held handle never refuses what a reopened one accepts; accepting reads the held handle (no extra read per append), and an accept is checked again at flush, against the version then -loaded, before anything is written. The one remaining difference writes nothing either way: +loaded, before anything is written. Two differences remain. One writes nothing either way: a duplicate-only append of the identifier a stale version holds is a no-op on the held -handle, where a reopened handle refuses it. A connector database compares against the +handle, where a reopened handle refuses it. The other is pre-existing, as on main +(ITL-1413): when the table is deleted and recreated at the same path and Delta version, the +held handle's duplicate scan reuses the old version's cached ids, so an old id is skipped as +a duplicate and a new one can be written twice. A connector database compares against the stored schema it caches for the ITL-1334 check (`_stored_schemas`), as main's check does, so a table replaced by another connection is seen as main sees it (pre-existing). @@ -88,8 +95,8 @@ zero-row append, and an encoding the database cannot write (refused as unstorabl rule: metadata that is not UTF-8 in Delta, any field metadata in SQLite), are outside the identity rule and keep main's verdict. -So the only appends whose verdict differs from main are those with a known different -identifier. Where Delta stored a nested extension type as plain storage (a list item or map +So, apart from the stated MERGE case, the only appends whose verdict differs from main are +those with a known different identifier. Where Delta stored a nested extension type as plain storage (a list item or map value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with any identifier, a second list refused for its item's name); a column Delta wrote from a dictionary of extension values takes the same type again, as a dictionary or not, as on diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index b7056fd8c..c4058c809 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -639,74 +639,135 @@ def _non_null_violation( def _delta_identity_node( - delta_type: Any, metadata: Any, recorded: bool + delta_type: Any, metadata: Any, recorded: "pa.Field[Any] | None" ) -> IdentityNode: """What the Delta log reliably says of a stored column's logical type identifiers, at every depth (ITL-1371). - The log keeps the field metadata written with the column and with each struct - child, byte for byte, so an identifier there is known. "No identifier" is known - only when the column's Arrow type is recorded (``ARROW_TYPE_KEY``): a column - written from a dictionary of extension values is stored as plain values, losing - the identifier, and records no type (ITL-1372), so without a record the absence - proves nothing and the identity rule abstains. A list item and a map key or item - keep no metadata in the log (ITL-1372), and the column's recorded type is read - through the Arrow registry, which may give an identifier other than the one - stored: there the identifier is never known, while the children of a struct - beneath it are (``_unknown_place``). + A place's identifier is known from, in this order: the physical field's own + annotation (the log keeps the field metadata written with the column and with + each struct child, byte for byte); else the place inside the column's recorded + Arrow type (``ARROW_TYPE_KEY``), when the column records one: its annotation + there, or no logical type when the recorded place is plain; else it is unknown + and the identity rule abstains. Missing physical metadata alone proves nothing: + a list item or map key or item keeps none in the log (ITL-1372), a dictionary + child is written as plain values, and a column written from a dictionary of + extension values records no type. A recorded place that the Arrow registry read + back as an extension type is unknown too: the registry may give other bytes than + the ones stored. Args: delta_type: A ``deltalake.schema`` type from the log. metadata: Its field's metadata, as the log gives it. - recorded: Whether the column records its Arrow type. + recorded: The same place in the column's recorded Arrow type, or ``None`` + when the column records none (or the record has no such place). Returns: The ``IdentityNode`` of the stored field. """ from deltalake.schema import ArrayType, MapType, StructType + recorded_type = _recorded_storage(recorded) children: tuple[tuple[str, IdentityNode], ...] = () if isinstance(delta_type, StructType): + by_name = ( + {f.name: f for f in recorded_type} + if recorded_type is not None and pa.types.is_struct(recorded_type) + else {} + ) children = tuple( - (f".{f.name}", _delta_identity_node(f.type, f.metadata, recorded)) + ( + f".{f.name}", + _delta_identity_node(f.type, f.metadata, by_name.get(f.name)), + ) for f in delta_type.fields ) elif isinstance(delta_type, ArrayType): - children = ((LIST_ITEM, _unknown_place(delta_type.element_type, recorded)),) + item = ( + recorded_type.value_field + if recorded_type is not None + and ( + pa.types.is_list(recorded_type) + or pa.types.is_large_list(recorded_type) + or pa.types.is_fixed_size_list(recorded_type) + ) + else None + ) + children = ( + (LIST_ITEM, _delta_identity_node(delta_type.element_type, None, item)), + ) elif isinstance(delta_type, MapType): + is_map = recorded_type is not None and pa.types.is_map(recorded_type) children = ( - (MAP_KEY, _unknown_place(delta_type.key_type, recorded)), - (MAP_ITEM, _unknown_place(delta_type.value_type, recorded)), + ( + MAP_KEY, + _delta_identity_node( + delta_type.key_type, + None, + recorded_type.key_field if is_map else None, + ), + ), + ( + MAP_ITEM, + _delta_identity_node( + delta_type.value_type, + None, + recorded_type.item_field if is_map else None, + ), + ), ) as_bytes = metadata_bytes(metadata) name = as_bytes.get(_EXTENSION_KEYS[0]) - identifier = None if name is None else (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) - return IdentityNode( - known=identifier is not None or recorded, - identifier=identifier, - children=children, + if name is not None: + identifier = (name, as_bytes.get(_EXTENSION_KEYS[1], b"")) + return IdentityNode(known=True, identifier=identifier, children=children) + if recorded is None or isinstance(recorded.type, pa.BaseExtensionType): + return IdentityNode(known=False, identifier=None, children=children) + recorded_metadata = metadata_bytes(recorded.metadata) + recorded_name = recorded_metadata.get(_EXTENSION_KEYS[0]) + identifier = ( + None + if recorded_name is None + else (recorded_name, recorded_metadata.get(_EXTENSION_KEYS[1], b"")) ) + return IdentityNode(known=True, identifier=identifier, children=children) + + +def _recorded_storage(recorded: "pa.Field[Any] | None") -> Any: + """The recorded place's type to walk into: a dictionary's values (an encoding), + or ``None`` when there is no record or the place is an extension type (whose + children the registry has built).""" + if recorded is None: + return None + arrow_type = recorded.type + if pa.types.is_dictionary(arrow_type): + arrow_type = arrow_type.value_type + if isinstance(arrow_type, pa.BaseExtensionType): + return None + return arrow_type -def _unknown_place(delta_type: Any, recorded: bool) -> IdentityNode: - """A list item or map key or item as the Delta log gives it: its own identifier - is not known (the log keeps no metadata there, ITL-1372), but a struct beneath it - keeps its children's metadata in the log, byte for byte, so the walk goes on - through it to them.""" - place = _delta_identity_node(delta_type, None, recorded) - return IdentityNode(known=False, identifier=None, children=place.children) +def _recorded_field(name: str, metadata: Any) -> "pa.Field[Any] | None": + """The column's recorded Arrow type as a field, or ``None`` when it records none + or the record cannot be read (a registered reader that refuses its metadata): + then the record proves nothing.""" + try: + record = recorded_type(metadata) + except Exception: # noqa: BLE001 # an unreadable record proves nothing + return None + return None if record is None else pa.field(name, record) def _stored_identities( delta_table: deltalake.DeltaTable, ) -> list[tuple[str, IdentityNode]]: - """Each stored column's ``_delta_identity_node``, from the log; no data is read - and no type is decoded.""" + """Each stored column's ``_delta_identity_node``, from the log and the column's + recorded Arrow type; no data is read.""" return [ ( f.name, _delta_identity_node( - f.type, f.metadata, ARROW_TYPE_KEY in metadata_bytes(f.metadata) + f.type, f.metadata, _recorded_field(f.name, f.metadata) ), ) for f in delta_table.schema().fields diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index d98c9bf26..9796c0511 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1754,33 +1754,45 @@ def test_a_later_chunk_annotation_is_compared( tmp_path: Path, kind: str, state: str ) -> None: """Arrow keeps a nested field's annotation per chunk: a later chunk of another - annotated identifier is refused, with fresh ids and duplicate-only, in every - database; chunks of the same identifier are accepted.""" + annotated identifier is refused, with fresh ids (either duplicate setting) and + duplicate-only (every id already held, ``skip_duplicates``), in every database; + 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: store.db.add_records( PATH, - _late_chunk_rows([b"m"], [b"1"]), + _late_chunk_rows([b"m", b"m"], [b"1", b"22"]), record_id_column="id", flush=state == "committed", ) - mixed = _late_chunk_rows([b"m", b"n"], [b"1", b"22"]) - assert [c.type.field("v").metadata[META] for c in mixed.column("x").chunks] == [ + fresh = _late_chunk_rows([b"m", b"n"], [b"333", b"4444"]) + duplicate_only = _late_chunk_rows([b"m", b"n"], [b"1", b"22"]) + assert [c.type.field("v").metadata[META] for c in fresh.column("x").chunks] == [ b"m", b"n", ] - for skip in (False, True): + for given, skip in ((fresh, False), (fresh, True), (duplicate_only, True)): with pytest.raises(InputValidationError, match="x.v is of logical type"): store.db.add_records( - PATH, mixed, record_id_column="id", skip_duplicates=skip + PATH, given, record_id_column="id", skip_duplicates=skip ) store.db.add_records( - PATH, _late_chunk_rows([b"m", b"m"], [b"22", b"333"]), record_id_column="id" + PATH, + _late_chunk_rows([b"m", b"m"], [b"1", b"22"]), + record_id_column="id", + skip_duplicates=True, + ) + store.db.add_records( + PATH, + _late_chunk_rows([b"m", b"m"], [b"333", b"4444"]), + record_id_column="id", ) stored = store.stored() assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ b"1", b"22", b"333", + b"4444", ] @@ -2187,3 +2199,164 @@ def test_delta_flush_refuses_after_another_writer_changed_the_identifier( stored = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="id") assert stored is not None and stored.column("id").to_pylist() == [b"1"] assert identity_node(stored.schema.field("x")).identifier == (b"itl1371.a", b"n") + + +# --------------------------------------------------------------------------- +# Review round 5 (PR 492) +# --------------------------------------------------------------------------- + + +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_stale_handle_after_delete_and_recreate_reuses_its_ids( + tmp_path: Path, +) -> None: + """Pins a pre-existing limit, as on main (round 5, finding 2; ITL-1413): a held + handle whose table was deleted and recreated at the same path, at the same Delta + version, takes the new table's identifier on a reload but its duplicate scan + reuses the old version's cached ids, so a same-identifier append of an old id is + taken for a duplicate (nothing written) and one of a new id is written again.""" + import shutil + + import deltalake + + root = tmp_path / "delta" + held = DeltaTableDatabase(root) + held.add_records( + PATH, _annotated_top(b"m", [b"a", b"b"]), record_id_column="id", flush=True + ) + held.add_records( # caches the version-0 ids + PATH, _annotated_top(b"m", [b"a"]), record_id_column="id", skip_duplicates=True + ) + shutil.rmtree(root / "t") + deltalake.write_deltalake( + str(root / "t"), + _annotated_top(b"n", [b"c", b"d"]).rename_columns(["__record_id", "x"]), + ) + assert deltalake.DeltaTable(str(root / "t")).version() == 0 + held.add_records( + PATH, + _annotated_top(b"n", [b"a"]), + record_id_column="id", + skip_duplicates=True, + flush=True, + ) + held.add_records( + PATH, + _annotated_top(b"n", [b"c"]), + record_id_column="id", + skip_duplicates=True, + flush=True, + ) + 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"c", + b"c", + b"d", + ] From cacbe7e8ec992af5a7bb43b5ad51aff31625bf6d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 20:46:33 -0800 Subject: [PATCH 14/14] fix(databases): one table listing per connector append; order statement (ITL-1371) CodeRabbit on 6eab211e: - The connector gathers the held schemas once for the identity and the ordinary check: an append to a table not stored yet lists the backend's tables once, as on main (the PR had added a second listing). - The design note and _identity_refusal say the identity rule decodes the recorded types itself and comes before the duplicate scan and the ordinary held-column checks. - The pending variant of the chunk test keeps its held batch pending. Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 10 +++-- .../databases/connector_arrow_database.py | 45 ++++++++++++------- src/orcapod/databases/delta_lake_databases.py | 7 +-- .../test_logical_identity_appends.py | 27 ++++++++++- 4 files changed, 64 insertions(+), 25 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index b5decd173..62dd996d0 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -66,10 +66,12 @@ text, before anything is buffered, whatever `skip_duplicates`: an append whose c a known different identifier is refused, duplicate-only or not (on main a duplicate-only append with `skip_duplicates` was a silent no-op; nothing was or is written), while a duplicate-only append of the same identifier stays a no-op. The order is the same with -either setting: in Delta the rule reads the log only and runs first, before anything decodes -a stored type (the duplicate scan, the held columns), so no read failure can come before it; -only when it passes or abstains does the duplicate scan run, and a read failure there -propagates as a read failure. The database type matrix appends each logical type again under another extension +either setting: in Delta the rule reads the log and the columns' recorded Arrow types +(decoding a record is part of the rule: a record that cannot be decoded only makes its +places unknown, it raises nothing) and runs first, before the duplicate scan and the +ordinary held-column checks, so no read failure can come before it; only when it passes or +abstains does the duplicate scan run, and a read failure there propagates as a read +failure. The database type matrix appends each logical type again under another extension name, which every database refuses. Delta decides every refusal on the version stored now: a difference found on the handle it diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index c1d3dc410..93dc6731e 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -445,9 +445,11 @@ def add_records( # (ITL-1367). # A column of another logical type is refused first, on the raw identifier # bytes, before the reorder compares types (ITL-1371). - self._refuse_changed_columns(record_path, records, identity_only=True) + # The held schemas are gathered once for both checks (one table listing). + held = self._held_schemas(record_path) + self._refuse_changed_columns(record_path, records, held, identity_only=True) records = in_held_column_order(records, self._held_column_order(record_path)) - self._refuse_changed_columns(record_path, records) + self._refuse_changed_columns(record_path, records, held) records = self._deduplicate_within_table(records) input_ids = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) @@ -523,10 +525,32 @@ def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": for c in self._connector.get_column_info(table_name) ] + def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: + """The schemas held for the table, the pending batch's and the stored one's, + for ``_refuse_changed_columns``; ``None`` when the connector keeps no field + metadata. The stored table's schema is read once per table + (``_read_stored_schema``): an append the check accepts does not change it.""" + if not self.keeps_field_metadata: + return None + held: list[pa.Schema] = [] + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + held.append(pending.schema) + table_name = self._path_to_table_name(self._path_prefix + record_path) + stored = self._stored_schemas.get(table_name) + if stored is None and table_name in self._connector.get_table_names(): + stored = self._read_stored_schema(table_name) + if stored is not None: + self._stored_schemas[table_name] = stored + if stored is not None: + held.append(stored) + return held + def _refuse_changed_columns( self, record_path: tuple[str, ...], records: pa.Table, + held: list[pa.Schema] | None, *, identity_only: bool = False, ) -> None: @@ -537,8 +561,7 @@ def _refuse_changed_columns( held by the stored table and by a batch pending for it: otherwise one side's rows would read back with the other's. A connector that keeps no field metadata refuses metadata and nested types itself, so only one that keeps it - is checked. The stored table's schema is read once per table - (``_read_stored_schema``): an append the check accepts does not change it. + is checked (``held`` is ``None`` for one that keeps none). A column of another logical type identifier is refused first (``first_logical_identity_change``, ITL-1371); ``identity_only`` checks only @@ -547,20 +570,8 @@ def _refuse_changed_columns( Raises: InputValidationError: For the first such column, naming it and the path. """ - if not self.keeps_field_metadata: + if held is None: return - held: list[pa.Schema] = [] - pending = self._pending_batches.get(self._get_record_key(record_path)) - if pending is not None: - held.append(pending.schema) - table_name = self._path_to_table_name(self._path_prefix + record_path) - stored = self._stored_schemas.get(table_name) - if stored is None and table_name in self._connector.get_table_names(): - stored = self._read_stored_schema(table_name) - if stored is not None: - self._stored_schemas[table_name] = stored - if stored is not None: - held.append(stored) # A column of another logical type would read back as the held one (ITL-1371). changed = first_logical_identity_change(held, records) if changed is None and not identity_only: diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c4058c809..72ba31ee8 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1891,9 +1891,10 @@ def _identity_refusal( differ from the held one (``identity_refusal``, ITL-1371), or ``None``. Held is the pending batch, as given, and the stored table as its Delta log - gives it (``_stored_identities``): no stored type is decoded, so the - comparison comes before anything that decodes one (the duplicate scan, the - held columns' recorded types) and its error names the identifiers. + and its columns' recorded types give it (``_stored_identities``; a record + that cannot be decoded only makes its places unknown, it raises nothing), + so the comparison comes before the duplicate scan and the ordinary + held-column checks, and its error names the identifiers. Args: record_path: The table the rows are for. diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 9796c0511..982767cb3 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1533,7 +1533,10 @@ def _check_chunk_identifiers( PATH, rows([b"m"], [b"1"]), record_id_column="id", flush=state == "committed" ) db.add_records( - PATH, rows([b"m", b"m"], [b"2", b"3"]), record_id_column="id", flush=True + PATH, + rows([b"m", b"m"], [b"2", b"3"]), + record_id_column="id", + flush=state == "committed", ) ids = [b"2", b"3"] if skip_duplicates else [b"4", b"5"] mixed = rows([b"m", b"n"], ids) @@ -2360,3 +2363,25 @@ def test_delta_stale_handle_after_delete_and_recreate_reuses_its_ids( b"c", b"d", ] + + +def test_connector_lists_its_tables_once_per_append(tmp_path: Path) -> None: + """The identity check and the ordinary check share one gathering of the held + schemas: an append to a table not stored yet lists the backend's tables once, as + on main (CodeRabbit, 6eab211e).""" + with fake_pyspiral.install(tmp_path / "spiral"): + fake_pyspiral.FakeSpiral().project("p") + connector = SpiralDBConnector("p") + calls = {"n": 0} + listing = connector.get_table_names + + def counted() -> list[str]: + calls["n"] += 1 + return listing() + + connector.get_table_names = counted # pyright: ignore[reportAttributeAccessIssue] # counts the listings + db = ConnectorArrowDatabase(connector) + for ids in ([b"1"], [b"22"]): + calls["n"] = 0 + db.add_records(PATH, _annotated_top(b"m", ids), record_id_column="id") + assert calls["n"] == 1