diff --git a/changelog.d/ITL-1371.md b/changelog.d/ITL-1371.md new file mode 100644 index 000000000..5c26a0566 --- /dev/null +++ b/changelog.d/ITL-1371.md @@ -0,0 +1,23 @@ +### 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, whatever + `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, 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-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index 40c7d996b..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). +(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/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md new file mode 100644 index 000000000..62dd996d0 --- /dev/null +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -0,0 +1,107 @@ +## `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`, 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; 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; 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 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, 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 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 +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, 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 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 +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. 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. 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). + +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, 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 +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/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..1559c82c4 --- /dev/null +++ b/docs/dev/scripts/itl_1371_logical_identity_appends.py @@ -0,0 +1,180 @@ +"""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) -> Any: + """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: dict[str, Any] = {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": + # 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: Any = pa.map_( + pa.field("key", pa.large_string(), nullable=False), # pyright: ignore[reportArgumentType] + field.with_name("value"), # pyright: ignore[reportArgumentType] + ) + from_arrays: Any = pa.MapArray.from_arrays + arr = 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 9819e3cfb..1fc8911b3 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/__init__.py b/src/orcapod/databases/__init__.py index be4c9dd7b..3894cb5a0 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -3,10 +3,10 @@ from .extension_aware_database import ExtensionAwareDatabase from .in_memory_databases import InMemoryArrowDatabase from .noop_database import NoOpArrowDatabase +from .postgresql_connector import PostgreSQLConnector from .spiraldb_connector import SpiralDBConnector from .spiraldb_nullability import read_nullability_record, write_nullability_record from .sqlite_connector import SQLiteConnector -from .postgresql_connector import PostgreSQLConnector __all__ = [ "ConnectorArrowDatabase", diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 761486310..93dc6731e 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, in_held_column_order, ) from orcapod.errors import ( @@ -33,12 +34,12 @@ UnstorableColumnError, UnstorableTableNameError, ) +from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol from orcapod.utils.arrow_utils import ( normalize_schema_to_large_types, normalize_table_to_large_types, normalize_to_large_types, ) -from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -442,8 +443,13 @@ 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). + # 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.schema) + 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())) @@ -519,8 +525,34 @@ 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, ...], schema: pa.Schema + self, + record_path: tuple[str, ...], + records: pa.Table, + held: list[pa.Schema] | None, + *, + identity_only: bool = False, ) -> None: """Refuse rows whose columns would not read back as written (ITL-1334). @@ -529,27 +561,21 @@ 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 + that, so it can run before the rows are reordered by name. 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) - 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, 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 cbf6e2831..72ba31ee8 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -16,19 +16,6 @@ matching_rows, rows_at, ) -from orcapod.databases.utils import ( - appended_field_change, - coerce_record_id, - in_held_column_order, - metadata_bytes, -) -from orcapod.errors import ( - InputValidationError, - OrcapodDatabaseReadError, - TableListingNotSupportedError, - TypeIdentityError, - UnstorableColumnError, -) from orcapod.databases.delta_arrow_types import ( ARROW_TYPE_KEY, first_column_out_of_stored_range, @@ -46,6 +33,25 @@ is_cloud_uri, parse_base_path, ) +from orcapod.databases.utils import ( + LIST_ITEM, + MAP_ITEM, + MAP_KEY, + IdentityNode, + appended_field_change, + coerce_record_id, + identity_node, + identity_refusal, + in_held_column_order, + metadata_bytes, +) +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + TableListingNotSupportedError, + TypeIdentityError, + UnstorableColumnError, +) from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -632,6 +638,142 @@ def _non_null_violation( return None +def _delta_identity_node( + 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). + + 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: 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, by_name.get(f.name)), + ) + for f in delta_type.fields + ) + elif isinstance(delta_type, ArrayType): + 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, + _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]) + 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 _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 and the column's + recorded Arrow type; no data is read.""" + return [ + ( + f.name, + _delta_identity_node( + f.type, f.metadata, _recorded_field(f.name, f.metadata) + ), + ) + for f in delta_table.schema().fields + ] + + def _append_refusal( delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: @@ -640,6 +782,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 @@ -655,6 +799,9 @@ def _append_refusal( Returns: ``(column, reason)``, or ``None`` when the rows can be appended. """ + identity = identity_refusal(_stored_identities(delta_table), rows) + if identity is not None: + return identity held = _held_columns(delta_table) for field in rows.schema: if field.name in held: @@ -890,8 +1037,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( @@ -1731,6 +1884,82 @@ 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 + 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. + rows: The rows to append, as given. + + Returns: + The error message, or ``None``. + """ + found = None + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + 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: + 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 ) -> None: @@ -1742,7 +1971,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. + 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. @@ -1751,15 +1981,25 @@ def _refuse_changed_attributes( Raises: InputValidationError: For the first such column, naming it and the path. """ - held: list[dict[str, pa.Field[Any]]] = [] 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}) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: delta_table = None + 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: + # 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: @@ -1876,12 +2116,22 @@ 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 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: + # 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 ) diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 3c78dd1e0..29cf9746d 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -9,6 +9,7 @@ from orcapod.databases.utils import ( coerce_record_id, first_changed_column, + first_logical_identity_change, in_held_column_order, ) from orcapod.errors import InputValidationError @@ -17,6 +18,7 @@ if TYPE_CHECKING: import pyarrow as pa import pyarrow.compute as pc + from orcapod.pipeline.serialization import DatabaseRegistry else: pa = LazyModule("pyarrow") @@ -258,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). @@ -270,14 +290,6 @@ 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 - ] changed = 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 17018eb43..98089bf60 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -4,7 +4,8 @@ import re from collections.abc import Iterable, Mapping, Sequence -from typing import TYPE_CHECKING, Any, cast +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, TypeVar, cast from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -16,6 +17,9 @@ else: pa = LazyModule("pyarrow") +H = TypeVar("H") +G = TypeVar("G") + def coerce_record_id(record_id: str | bytes) -> bytes: """Encode ``record_id`` to bytes if it is a ``str``. @@ -203,6 +207,362 @@ def first_changed_column( return None +_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 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; 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 + identifier: RawIdentifier | None + claims: bool = True + children: "tuple[tuple[str, 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) + name = as_bytes.get(_EXTENSION_NAME) + if name is None: + return None + return name, as_bytes.get(_EXTENSION_METADATA, b"") + + +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 (``__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. + """ + try: + capsule = pa.field("x", arrow_type).__arrow_c_schema__() + except pa.ArrowNotImplementedError: + return None + 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. + + 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. 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 + it, when what it holds is the field itself). + + Returns: + The field's ``IdentityNode``; every part known. + """ + arrow_type = arrow_field.type + 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): + 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( + known=True, identifier=identifier, children=_children_of(storage) + ) + + +def _children_of(arrow_type: Any) -> "tuple[tuple[str, IdentityNode], ...]": + t = pa.types + if t.is_dictionary(arrow_type): + return _children_of(arrow_type.value_type) + if isinstance(arrow_type, pa.BaseExtensionType): + return ((f"{_ROLE}", identity_node(pa.field("storage", arrow_type))),) + if t.is_map(arrow_type): + return ( + (MAP_KEY, identity_node(arrow_type.key_field)), + (MAP_ITEM, identity_node(arrow_type.item_field)), + ) + 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 ((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) + + +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 + try: + return repr(f"{name.decode()};{metadata.hex()}") + except UnicodeDecodeError: + return f"{name!r};{metadata.hex()}" + + +def matched_pairs( + 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 + 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[H]] = {} + for label, place in held: + by_label.setdefault(label, []).append(place) + seen: dict[str, int] = {} + pairs: list[tuple[str, H, G]] = [] + 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( + 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 (``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 + ``matched_pairs`` says. + + 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 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, held_child, child in matched_pairs(held.children, incoming.children): + found = logical_identity_change( + held_child, child, f"{path}{label.replace(_ROLE, '')}" + ) + if found is not None: + return found + return None + + +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), 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. + + 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)] + seen = set(nodes) + for chunk in column.chunks: + 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 identity_refusal( + held: "Sequence[tuple[str, IdentityNode]]", given: "pa.Table | pa.Schema" +) -> tuple[str, str] | None: + """The first column of ``given`` known to carry another logical type identifier + than the one held in its place (``logical_identity_change``). + + 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 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``. + """ + 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_append_by_name.py b/tests/test_databases/test_append_by_name.py index 4fe75ba5d..3143463f7 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -37,7 +37,6 @@ from orcapod.databases.utils import in_held_column_order from orcapod.errors import ( InputValidationError, - OrcapodDatabaseReadError, UnstorableColumnError, ) from tests.test_databases.type_matrix import open_database @@ -786,7 +785,9 @@ def test_two_logical_types_over_one_storage_type_are_not_reordered( ) -> None: """Through the extension-aware wrapper, a column of one logical type held and a permuted append of another logical type over the same storage type: not taken - for one, so refused as on main, never read back as the held logical type.""" + for one, and refused before anything is buffered as another logical type + identifier, naming both (ITL-1371; on main it was refused later, or, committed + to Delta, taken by name and left the table unreadable).""" from tests.test_databases.test_extension_aware_database import ( _make_converter_with_type, ) @@ -813,24 +814,10 @@ def rows(n: int, pair: Any, order: list[str]) -> pa.Table: ) second = ExtensionAwareDatabase(inner, two[0]) permuted = rows(2, two, ["text", "b", "rid", "a"]) - # Main's verdict, measured on main 321284ae, the same here. - if backend == "in-memory" and not stored: - with pytest.raises(pa.ArrowInvalid): - second.add_records(PATH, permuted, record_id_column="rid") - elif backend == "in-memory": + with pytest.raises(InputValidationError) as refused: second.add_records(PATH, permuted, record_id_column="rid") - with pytest.raises(pa.ArrowInvalid): - second.flush() - elif not stored: - with pytest.raises(ValueError, match="Schema mismatch"): - second.add_records(PATH, permuted, record_id_column="rid") - else: - # Pre-existing on main and equal here (ITL-1371's family): Delta takes the - # rows by name and the stored table can no longer be read as one type. - second.add_records(PATH, permuted, record_id_column="rid", flush=True) - with pytest.raises(OrcapodDatabaseReadError): - inner.get_all_records(PATH, record_id_column="rid") - return + assert "'test.itl1367.other;'" in str(refused.value) + assert "'test.itl1367.held;'" in str(refused.value) inner.flush() stored_rows = inner.get_all_records(PATH, record_id_column="rid") assert stored_rows is not 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..982767cb3 --- /dev/null +++ b/tests/test_databases/test_logical_identity_appends.py @@ -0,0 +1,2387 @@ +"""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 re +import itertools +from collections.abc import Iterator +from pathlib import Path +from typing import Any, cast + +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 ( + IdentityNode, + first_logical_identity_change, + metadata_bytes, + identity_node, + logical_identity_change, +) +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 +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) -> Any: + """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: 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] = { + "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[Any]", Any]: + 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[Any]", Any]: + 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" + # 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: 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( + 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 _abstains(kind: str, state: str, depth: str) -> bool: + """Whether the identity rule cannot know the held identifier, and so abstains: + a Delta list item or map key or item, which the Delta log keeps no metadata for + (ITL-1372). There the database's other checks decide, exactly as on main.""" + return kind == "Delta" and state != "pending" and depth in ("list", "map value") + + +def _main_accepts(kind: str, state: str, form: str, depth: str) -> bool: + """Where the rule abstains, main accepts a map of extension values whatever the + identifier (Delta wrote it as plain storage, ITL-1372; pinned below).""" + return ( + _abstains(kind, state, depth) and form == "extension" and depth == "map value" + ) + + +KINDS = ("in-memory", "Delta", "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 + if not _main_accepts(*case) +] + +SAME_CASES = [ + pytest.param(*case, id="-".join(case)) + for case in BASE + # Main refuses a second list of extension values for its item's name (ITL-1372). + if not (_abstains(case[0], case[1], case[3]) and case[2:] == ("extension", "list")) +] + + +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().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") + 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 + 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) + + +@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 + + +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 + ) + # 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") +] + + +@pytest.mark.parametrize("via", ["direct", "wrapper"]) +@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: + 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="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("state", ["committed", "reopened"]) +def test_delta_list_and_map_of_extension_values_decide_as_on_main( + tmp_path: Path, state: str +) -> None: + """Pins the behaviour of ITL-1372; revisit there. + + Delta writes a list item or map item of an extension type as plain storage, and + its log keeps no metadata there, so the identity rule cannot know the stored + identifier and abstains: main's checks decide. A second list is refused for its + item's name (``item`` given, ``element`` stored); a second map is accepted with any + identifier, and every row reads back as plain storage. A same-type append to the + pending batch is accepted. + """ + for depth in ("list", "map value"): + root = tmp_path / depth.replace(" ", "_") + with _store("Delta", root) as store: + db = store.db + db.add_records( + PATH, _rows(HELD, "extension", depth, [b"1"]), record_id_column="id" + ) + db.add_records( + PATH, _rows(HELD, "extension", depth, [b"22"]), record_id_column="id" + ) + db.flush() + if state == "reopened": + store.reopen() + other = _rows(("itl1371.b", b"m"), "extension", depth, [b"333"]) + if depth == "list": + with pytest.raises(InputValidationError, match="is named 'item'"): + store.db.add_records(PATH, other, record_id_column="id") + assert store.stored().num_rows == 2 + continue + store.db.add_records(PATH, other, record_id_column="id") + stored = store.stored() + assert stored.num_rows == 3 + item = stored.schema.field("x").type.item_field + assert identity_node(item).identifier is None # read back plain + + +def test_the_reproducer_through_the_wrapper(tmp_path: Path) -> None: + """ITL-1371 as reported: annotated, aligned columns, through the wrapper over Delta.""" + inner = DeltaTableDatabase(tmp_path / "delta") + 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 _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 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 _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 _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[Any]": + key = pa.field( + "key", + pa.large_string(), + nullable=False, + metadata={NAME: identifier[0].encode(), META: identifier[1]}, + ) + item = pa.field("value", pa.int64()) + return pa.field("x", pa.map_(key, item)) # pyright: ignore[reportArgumentType] # pyarrow takes key/item fields + + 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 ") + + +def _struct_rows(form: str, unit: bytes, ids: list[bytes]) -> pa.Table: + """``x: struct``, ``v`` of logical type ``HELD`` with ``{unit: }`` beside + its identifier.""" + field, array = _leaf(HELD, form, [i.decode() for i in ids]) + field = field.with_metadata({**dict(field.metadata or {}), b"unit": unit}) + struct = pa.StructArray.from_arrays([array], fields=[field]) + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), struct], + schema=pa.schema( + [pa.field("id", pa.large_binary()), pa.field("x", struct.type)] + ), + ) + + +@pytest.mark.parametrize( + ("form", "state"), + [ + ("annotated", "pending"), + ("annotated", "committed"), + ("annotated", "reopened"), + # Committed, a struct child of an extension type with metadata of its own is + # refused even for the same type, as on main: the held view drops the child's + # own metadata (reported with ITL-1372). + ("extension", "pending"), + ], +) +def test_delta_other_nested_metadata_beside_an_identifier_is_still_refused( + tmp_path: Path, form: str, state: str +) -> None: + """The identity rule finds the same identifier on the struct child; the ITL-1334 + comparison of nested field metadata, which is main's, still refuses the child's + other non-extension metadata.""" + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, + _struct_rows(form, b"m", [b"1"]), + record_id_column="id", + flush=state != "pending", + ) + if state == "reopened": + store.reopen() + store.db.add_records( + PATH, _struct_rows(form, b"m", [b"22"]), record_id_column="id" + ) + with pytest.raises(InputValidationError, match="x.v has other field metadata"): + store.db.add_records( + PATH, _struct_rows(form, b"s", [b"333"]), record_id_column="id" + ) + ids = store.stored().sort_by("id").column("id").to_pylist() + assert ids == [b"1", b"22"] + + +# --------------------------------------------------------------------------- +# Review round 1 (PR 492) +# --------------------------------------------------------------------------- + + +def _struct_of(field: "pa.Field[Any]", array: Any, ids: list[bytes]) -> pa.Table: + struct = pa.StructArray.from_arrays([array], fields=[field.with_name("v")]) + return pa.Table.from_arrays( + [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 + 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: + """A dictionary is an encoding: its values' identifier stands where it stands. A + pending batch is compared as given (another identifier refused). Delta decodes a + dictionary column and stores its values as plain values, losing the identifier + (pre-existing, ITL-1372): over that loss the rule cannot know the stored + identifier, so a dictionary written again is accepted and its rows stored as on + main (plain values).""" + with _store("Delta", tmp_path) as store: + store.db.add_records( + PATH, _container_rows("dictionary", b"m", [b"1"]), record_id_column="id" + ) + with pytest.raises(InputValidationError, match="x is of logical type"): + store.db.add_records( + PATH, + _container_rows("dictionary", b"n", [b"22"]), + record_id_column="id", + ) + store.db.flush() + store.reopen() + store.db.add_records( + PATH, _container_rows("dictionary", b"m", [b"333"]), record_id_column="id" + ) + stored = store.stored().sort_by("id") + assert stored.column("id").to_pylist() == [b"1", b"333"] + assert stored.column("x").to_pylist() == ["1", "333"] + assert identity_node(stored.schema.field("x")).identifier is None + + +def _dictionary_layout( + ids: list[bytes], meta: bytes, *, encoded: bool, nested: bool, form: str +) -> pa.Table: + """``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, + _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 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"]) +@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); 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(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()), + 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"a", [b"1"]), + record_id_column="id", + flush=state == "committed", + ) + 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 "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") + 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], + ) + + +@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") + + +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_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, + _container_rows("list_view", b"m", [b"1"]), + record_id_column="id", + flush=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 + 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", + ) + + +@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 + + +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"]) +@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], + schema=pa.schema([pa.field("id", pa.large_binary()), field]), + ) + + 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, + _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 + + +@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. The order is the same with either duplicate setting: the identity rule + reads the Delta log only and runs first, so another identifier is refused with + the same ``InputValidationError`` naming both, before anything is decoded. Only + when it passes does the duplicate scan run, and a read failure there propagates + as it is (a read failure fails the run whatever the error policy): the same + identifier with ``skip_duplicates`` raises ``OrcapodDatabaseReadError``. Without + it nothing reads the stored ids or decodes the recorded types before the rows + are queued but the field-metadata check (ITL-1334), which decodes the stored + struct's recorded type: the registered reader's own ``ValueError`` is raised, as + on main (that decode is not wrapped as a read failure; pre-existing).""" + + class Current(pa.ExtensionType): + def __init__(self) -> None: + super().__init__(pa.large_string(), "itl1371.current") + + def __arrow_ext_serialize__(self) -> bytes: + return b"new" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + raise ValueError("itl1371.current cannot read this metadata") + + def rows(ids: list[bytes], name: bytes, meta: bytes) -> pa.Table: + field = pa.field("v", pa.large_string(), metadata={NAME: name, META: meta}) + values = pa.array([i.decode() for i in ids], pa.large_string()) + return _struct_of(field, values, ids) + + db = DeltaTableDatabase(tmp_path / "delta") + db.add_records( + PATH, + rows([b"1"], b"itl1371.current", b"old"), + record_id_column="id", + flush=True, + ) + pa.register_extension_type(cast(Any, Current())) + 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 + + 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") + + +@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("skip_duplicates", [False, True]) +@pytest.mark.parametrize("state", ["pending", "committed"]) +@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 + (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)] + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), pa.chunked_array(chunks)], + names=["id", "x"], + ) + + 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", + flush=state == "committed", + ) + 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", + ] + with pytest.raises( + InputValidationError, match="'itl1371.a;6e', the stored column's 'itl1371.a;6d'" + ): + 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", + 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 + + +@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"] + + +# --------------------------------------------------------------------------- +# 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 (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"m"], [b"1", b"22"]), + record_id_column="id", + flush=state == "committed", + ) + 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 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, given, record_id_column="id", skip_duplicates=skip + ) + store.db.add_records( + 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", + ] + + +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) + + +# --------------------------------------------------------------------------- +# 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") + + +# --------------------------------------------------------------------------- +# 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", + ] + + +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 diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index a3c298224..12882654a 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 identity_node from orcapod.utils.arrow_utils import normalize_to_large_types KEPT = "KEPT" @@ -812,9 +813,28 @@ 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 = identity_node(field).identifier + assert identifier is not None + 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) + 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 +845,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 +1043,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.