From 8998df204d4b6ee22004bd8727f8b546b762d87d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:51:42 -0800 Subject: [PATCH 01/23] fix(databases): commit every Delta write to an existing table by MERGE, retried on a conflict (ITL-1377) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 318 ++++++++++-------- .../test_delta_committed_snapshot.py | 6 +- .../test_pipeline/test_job_batched_commits.py | 14 +- 3 files changed, 196 insertions(+), 142 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 827d78ea5..6266e6c50 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2,7 +2,9 @@ import logging import os +import random import sys +import time from collections import defaultdict from collections.abc import Callable, Collection, Mapping from dataclasses import dataclass @@ -70,6 +72,35 @@ # Directory that marks its parent directory as a Delta table. _DELTA_LOG_DIRECTORY = "_delta_log" +# How many times a flush tries to commit a table's pending rows when other writers +# keep committing first; after the last attempt it raises the last conflict +# (ITL-1377). +_COMMIT_ATTEMPTS = 10 + + +class _LostCommitRace(Exception): + """Another writer committed to the table first; load it again and retry. + + Attributes: + error: The error the lost commit raised, raised as itself when no attempt + is left. + """ + + def __init__(self, error: Exception) -> None: + super().__init__(str(error)) + self.error = error + + +def _sleep_before_retry(attempt: int) -> None: + """Wait a random time before attempt ``attempt + 1``, longer after each loss. + + Writers that lost to each other start again at different moments, so they do + not keep colliding. The wait only spaces attempts: what is committed is decided + against the table each attempt loads. + """ + time.sleep(random.uniform(0, min(0.5, 0.005 * 2**attempt))) + + # deltalake storage option -> where s3fs takes the same setting. _S3FS_OPTION_OF: dict[str, tuple[str, ...]] = { "aws_access_key_id": ("key",), @@ -2594,105 +2625,36 @@ def _flush_by_key(self, record_key: str) -> None: original_table = arrow_utils.normalize_table_view_types( pending_batch.combine_chunks() ) - # A column whose type Delta would not give back is written in its - # integer form with its type recorded (ITL-928). - combined_table = to_delta_layout(original_table) # Ensure parent directory exists (local only) if not self._is_cloud: - import os - os.makedirs(table_uri, exist_ok=True) - # Check if Delta table exists at this URI. Only TableNotFoundError - # means "absent": a table that exists but cannot be loaded must never - # be replaced by the mode="overwrite" write below (ITL-884). - from deltalake.exceptions import TableNotFoundError - - try: - delta_table = deltalake.DeltaTable( - table_uri, storage_options=self._storage_options or None - ) - except TableNotFoundError: - delta_table = None - except Exception as load_error: - raise OrcapodDatabaseReadError( - table_uri, abs_path_components - ) from load_error - - # Set when the rows were appended through ``delta_table``, which the - # writer then moves to the version it committed (ITL-1173). - appended = False - if delta_table is None: - # TODO: reconsider mode="overwrite" here - deltalake.write_deltalake( - table_uri, - combined_table, - mode="overwrite", - schema_mode="merge" if self.allow_schema_evolution else "overwrite", - storage_options=self._storage_options or None, - # Name the statistics columns once, at creation (ITL-1187). - configuration=statistics_configuration(combined_table.schema), - ) - base = _CommittedSnapshot(version=-1, ids=set()) - inserted_ids = self._non_null_ids(combined_table) - logger.debug( - f"Created new Delta table for {record_key} with {len(combined_table)} records" - ) - else: - # The add-time check, against the version just loaded: another - # writer may have committed since the rows were buffered (ITL-1334). - refusal = _append_refusal(delta_table, original_table) - if refusal is not None: - column, reason = refusal - raise InputValidationError( - f"Cannot append to the stored table {table_uri!r}: column " - f"{column!r}: {reason}. The stored rows are unchanged and " - "nothing was written." + # Every commit can fail because another writer committed first: a create + # finds the table created, a MERGE finds rows added since it loaded the + # table. Each attempt loads the table again and decides against what is + # committed then, so an id another writer committed meanwhile is never + # stored a second time (ITL-1377, ITL-1384). + attempt = 1 + while True: + try: + delta_table, base, inserted_ids = self._commit_once( + record_key, table_uri, abs_path_components, original_table ) - # Delta's MERGE matches struct fields by position: the rows are given - # the stored struct layout by name first, so an evolved struct (fields - # reordered, omitted or added) keeps every value under its name; and a - # recorded column's record describes the column after this append - # (ITL-1334). - combined_table = _with_merged_records( - delta_table, - original_table, - _conformed_to_stored(delta_table, combined_table, table_uri), - ) - base = self._snapshot_for_commit( - record_key, delta_table, table_uri, abs_path_components - ) - assert base.ids is not None - incoming_ids = self._non_null_ids(combined_table) - inserted_ids = incoming_ids - base.ids - if len(inserted_ids) == len(incoming_ids) and self._stores_as_is( - delta_table, combined_table - ): - # Every pending id is new in the version just loaded and the rows - # have the stored schema: append (ITL-919). A MERGE reads the whole - # stored table on each commit; it remains for every other batch. - # Written through the table just loaded: given a URI, the writer - # would load the table again (ITL-1173). - deltalake.write_deltalake( - delta_table, combined_table, mode="append" + break + except _LostCommitRace as lost: + # What this handle cached of the table describes a version + # another writer has moved past. + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + if attempt >= _COMMIT_ATTEMPTS: + raise lost.error + logger.debug( + f"Commit to {record_key} lost to another writer " + f"(attempt {attempt}); retrying" ) - appended = True - else: - # Some pending ids are stored already: insert only the others. - delta_table.merge( - source=_merge_source_in_stored_layout( - delta_table, combined_table - ), - predicate=f"target.{self.RECORD_ID_COLUMN} = source.{self.RECORD_ID_COLUMN}", - source_alias="source", - target_alias="target", - merge_schema=self.allow_schema_evolution, - ).when_not_matched_insert_all().execute() - - logger.debug( - f"Appended batch of {len(combined_table)} records to {record_key}" - ) + _sleep_before_retry(attempt) + attempt += 1 except InputValidationError as e: # The stored table refuses these rows (``_append_refusal``, @@ -2725,7 +2687,7 @@ def _flush_by_key(self, record_key: str) -> None: try: committed = ( delta_table - if appended and delta_table is not None + if delta_table is not None else deltalake.DeltaTable( table_uri, storage_options=self._storage_options or None ) @@ -2740,6 +2702,135 @@ def _flush_by_key(self, record_key: str) -> None: self._delta_table_cache.pop(record_key, None) self._snapshots.pop(record_key, None) + def _commit_once( + self, + record_key: str, + table_uri: str, + abs_path_components: tuple[str, ...], + original_table: pa.Table, + ) -> tuple[deltalake.DeltaTable | None, _CommittedSnapshot, set[bytes]]: + """Commit ``original_table`` to the table as it is now, in one attempt. + + A table that does not exist is created, and the create fails if another + writer created it first. Rows for an existing table are committed by a + MERGE that inserts only the ids the table does not hold: Delta refuses + that commit when another writer added rows after the table was loaded, + which a plain append never is (ITL-1377). + + Args: + record_key: The table's absolute record key. + table_uri: The table's location. + abs_path_components: The table's absolute path, for errors. + original_table: The pending rows, view types converted. + + Returns: + The table the rows were merged through (moved to the version it + committed), or ``None`` for a table this attempt created; the snapshot + of the version the commit built on; and the non-null ids it inserted. + + Raises: + _LostCommitRace: If another writer committed first; the caller loads + the table again and retries. + OrcapodDatabaseReadError: If the table exists but cannot be loaded, or + its stored ids cannot be read. + InputValidationError: If the stored table refuses the rows. + """ + from deltalake.exceptions import CommitFailedError, TableNotFoundError + + # A column whose type Delta would not give back is written in its integer + # form with its type recorded (ITL-928). + combined_table = to_delta_layout(original_table) + # Only TableNotFoundError means "absent": a table that exists but cannot be + # loaded is never created over (ITL-884). + try: + delta_table = deltalake.DeltaTable( + table_uri, storage_options=self._storage_options or None + ) + except TableNotFoundError: + delta_table = None + except Exception as load_error: + raise OrcapodDatabaseReadError( + table_uri, abs_path_components + ) from load_error + + if delta_table is None: + try: + # mode="error": a table another writer created after the load above + # is never replaced; this attempt fails instead (ITL-1384). + deltalake.write_deltalake( + table_uri, + combined_table, + mode="error", + storage_options=self._storage_options or None, + # Name the statistics columns once, at creation (ITL-1187). + configuration=statistics_configuration(combined_table.schema), + ) + except Exception as create_error: + if self._table_exists_at(table_uri): + raise _LostCommitRace(create_error) from create_error + raise + logger.debug( + f"Created new Delta table for {record_key} with {len(combined_table)} records" + ) + return ( + None, + _CommittedSnapshot(version=-1, ids=set()), + self._non_null_ids(combined_table), + ) + + # The add-time check, against the version just loaded: another writer may + # have committed since the rows were buffered (ITL-1334). + refusal = _append_refusal(delta_table, original_table) + if refusal is not None: + column, reason = refusal + raise InputValidationError( + f"Cannot append to the stored table {table_uri!r}: column " + f"{column!r}: {reason}. The stored rows are unchanged and " + "nothing was written." + ) + # Delta's MERGE matches struct fields by position: the rows are given the + # stored struct layout by name first, so an evolved struct (fields + # reordered, omitted or added) keeps every value under its name; and a + # recorded column's record describes the column after this append + # (ITL-1334). + combined_table = _with_merged_records( + delta_table, + original_table, + _conformed_to_stored(delta_table, combined_table, table_uri), + ) + base = self._snapshot_for_commit( + record_key, delta_table, table_uri, abs_path_components + ) + assert base.ids is not None + inserted_ids = self._non_null_ids(combined_table) - base.ids + try: + # Insert only the ids the table does not hold. Every commit to an + # existing table is this MERGE, also when every id is new: it is the + # commit Delta checks against rows another writer added meanwhile + # (ITL-1377). The table object moves to the version it committed, so + # it is not loaded again (ITL-1173). + delta_table.merge( + source=_merge_source_in_stored_layout(delta_table, combined_table), + predicate=f"target.{self.RECORD_ID_COLUMN} = source.{self.RECORD_ID_COLUMN}", + source_alias="source", + target_alias="target", + merge_schema=self.allow_schema_evolution, + ).when_not_matched_insert_all().execute() + except CommitFailedError as conflict: + raise _LostCommitRace(conflict) from conflict + logger.debug(f"Merged batch of {len(combined_table)} records to {record_key}") + return delta_table, base, inserted_ids + + def _table_exists_at(self, table_uri: str) -> bool: + """Whether a Delta table can be loaded at ``table_uri`` now.""" + try: + deltalake.DeltaTable( + table_uri, storage_options=self._storage_options or None + ) + except Exception: + return False + return True + def _rows_with_ids( self, rows: KeyIndex, @@ -2772,47 +2863,6 @@ def _rows_with_ids( positions = {p for r in set(record_ids) for p in id_index.get(r, ())} return rows_at(rows.table, sorted(positions)) - @staticmethod - def _stores_as_is(delta_table: deltalake.DeltaTable, batch: pa.Table) -> bool: - """Whether ``batch`` has exactly the stored schema once the Delta writer converts it. - - Only such a batch is appended: an append stores it unchanged, as the MERGE - would. A batch that needs a cast (a ``null``-typed column, a nullability - difference) or evolves the schema goes through the MERGE, which handles it. - - Args: - delta_table: The loaded stored table. - batch: The rows about to be committed. - - Returns: - Whether an append stores ``batch`` exactly as the MERGE would. - """ - # Delta stores a logical column as its storage type (ITL-984): compare that, - # or a batch with a logical list never equals the stored plain list. - schema = pa.schema( - [ - f.with_type(f.type.storage_type) - if isinstance(f.type, pa.ExtensionType) - else f - for f in batch.schema - ] - ) - try: - incoming = _as_delta_writer_stores(schema) - except Exception: - # A type Delta cannot store directly (null): leave it to the MERGE. - return False - # A changed recorded type must reach the log: the MERGE writes it (ITL-1334). - stored_records = { - f.name: recorded_type(f.metadata) for f in delta_table.schema().fields - } - if any( - recorded_type(f.metadata) != stored_records.get(f.name) - for f in batch.schema - ): - return False - return incoming.equals(_stored_arrow_schema(delta_table), check_metadata=False) - @classmethod def _non_null_ids(cls, table: pa.Table) -> set[bytes]: """Return the record ids of ``table``'s rows, nulls left out.""" diff --git a/tests/test_databases/test_delta_committed_snapshot.py b/tests/test_databases/test_delta_committed_snapshot.py index 99982b657..5ba5a1556 100644 --- a/tests/test_databases/test_delta_committed_snapshot.py +++ b/tests/test_databases/test_delta_committed_snapshot.py @@ -160,15 +160,15 @@ def _operations(path: Path) -> list[str]: return [str(entry["operation"]) for entry in reversed(history)] -def test_commits_with_new_ids_append(tmp_path: Path) -> None: - """Batches whose ids are all new are appended (no MERGE) and stored unchanged.""" +def test_commits_with_new_ids_are_merged_and_stored_unchanged(tmp_path: Path) -> None: + """Batches whose ids are all new are MERGEd too (ITL-1377) and stored unchanged.""" db = DeltaTableDatabase(tmp_path) for start in range(0, 9, 3): ids = [f"id{i}" for i in range(start, start + 3)] db.add_records(PATH, _rows(ids, list(range(start, start + 3)))) _ = db.get_records_with_column_value(PATH, {"g": b"g"}) # lookups as a job does db.flush() - assert _operations(tmp_path / "table") == ["WRITE", "WRITE", "WRITE"] + assert _operations(tmp_path / "table") == ["WRITE", "MERGE", "MERGE"] assert _values(DeltaTableDatabase(tmp_path).get_all_records(PATH)) == list(range(9)) diff --git a/tests/test_pipeline/test_job_batched_commits.py b/tests/test_pipeline/test_job_batched_commits.py index 8f9c864cc..c3f69ce10 100644 --- a/tests/test_pipeline/test_job_batched_commits.py +++ b/tests/test_pipeline/test_job_batched_commits.py @@ -4,7 +4,7 @@ pipeline records every N rows and when it finishes, instead of after every row. These tests check, on a ``DeltaTableDatabase`` whose table history counts commits: -- the commit count (one per N rows per table, appends only), +- the commit count (one per N rows per table: a create, then MERGEs; ITL-1377), - the option's validation, - that a node or cached pod used on its own still commits after every row, - a failed commit: ``OrcapodDatabaseWriteError`` naming the node and no row, earlier batches kept, @@ -118,14 +118,18 @@ def stored_rows(table: Path) -> int: def test_each_table_is_committed_once_per_batch( tmp_path: Path, orchestrator: str, n_rows: int, every: int | None, commits: int ) -> None: - """250 rows at 100 per commit (the default) give 3 commits per table, all appends.""" + """250 rows at 100 per commit (the default) give 3 commits per table. + + The first creates the table; every later one is a MERGE, the commit Delta checks + against rows another writer added meanwhile (ITL-1377). + """ job = build_job(DeltaTableDatabase(tmp_path), n_rows) if every is None: job.run(orchestrator=ORCHESTRATORS[orchestrator]()) else: job.run(orchestrator=ORCHESTRATORS[orchestrator](), commit_every_rows=every) for kind, table in table_dirs(tmp_path).items(): - assert operations(table) == ["WRITE"] * commits, kind + assert operations(table) == ["WRITE"] + ["MERGE"] * (commits - 1), kind assert stored_rows(table) == n_rows, kind assert job.nodes["dbl"].as_table().num_rows == n_rows @@ -148,7 +152,7 @@ def test_a_node_run_on_its_own_commits_every_row(tmp_path: Path) -> None: job = build_job(DeltaTableDatabase(tmp_path), 5) job.nodes["dbl"].run() result_table = table_dirs(tmp_path)["result"] - assert operations(result_table) == ["WRITE"] * 5 + assert operations(result_table) == ["WRITE"] + ["MERGE"] * 4 def test_a_cached_pod_used_on_its_own_commits_every_row(tmp_path: Path) -> None: @@ -166,7 +170,7 @@ def test_a_cached_pod_used_on_its_own_commits_every_row(tmp_path: Path) -> None: for tag, data in source.iter_data(): cached.process_data(tag, data) (table,) = {log.parent for log in tmp_path.rglob("_delta_log")} - assert operations(table) == ["WRITE"] * 4 + assert operations(table) == ["WRITE"] + ["MERGE"] * 3 class FailingCommits: From ede6a7069fd7cdd9538eabf81fd767cea03e390c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:57:52 -0800 Subject: [PATCH 02/23] fix(databases): refuse a Delta column name holding a backtick; test two writers committing one id (ITL-1377, ITL-1375, ITL-1384) Co-Authored-By: Claude Opus 5.5 --- docs/reference/database-types.md | 4 + src/orcapod/databases/delta_lake_databases.py | 35 +++ tests/test_databases/test_append_by_name.py | 48 ++-- .../test_delta_concurrent_writers.py | 255 ++++++++++++++++++ .../test_delta_statistics_columns.py | 56 +++- tests/test_databases/type_matrix.py | 4 + 6 files changed, 366 insertions(+), 36 deletions(-) create mode 100644 tests/test_databases/test_delta_concurrent_writers.py diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 9819e3cfb..a86b33325 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -66,6 +66,10 @@ Some refusals depend on the values or names as well as the type: field, so a map with such metadata is refused there. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. +- Delta refuses a column whose name holds a backtick, of any type: delta-rs cannot MERGE + such a table, and every commit to an existing Delta table is a MERGE. A table that + already holds such a column takes no further append. A backtick in a nested field's + name is kept. A table holds one type per column. An append whose columns differ from the held ones (stored, or still pending) in field metadata (the column's own, or a nested field's: a diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index e09c4c40f..59d4898ae 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -671,6 +671,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 stored column whose name delta-rs cannot MERGE (``_unmergeable_name_reason``, + ITL-1375); - 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 @@ -687,6 +689,11 @@ def _append_refusal( ``(column, reason)``, or ``None`` when the rows can be appended. """ held = _held_columns(delta_table) + # A table stored with such a column (before ITL-1375) takes no further commit. + for name in held: + reason = _unmergeable_name_reason(name) + if reason is not None: + return name, reason for field in rows.schema: if field.name in held: change = _column_change(held[field.name], field) @@ -843,6 +850,28 @@ def _holds_null_type(arrow_type: pa.DataType) -> bool: ) +def _unmergeable_name_reason(name: str) -> str | None: + """Say why Delta cannot commit to a table with a column named ``name``, or ``None``. + + delta-rs cannot MERGE a table with a top-level column whose name holds a backtick + (``Expected close delimiter``), and every commit to an existing table is a MERGE + (ITL-1377), so such a table would take only its first commit (ITL-1375). A + backtick in a nested field's name is merged as any other. + + Args: + name: A top-level column name. + + Returns: + The reason, or ``None`` when the name is accepted. + """ + if "`" in name: + return ( + "the name holds a backtick, and delta-rs cannot MERGE a table with such a " + "column; every commit to an existing Delta table is a MERGE" + ) + return None + + def delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: """Say why Delta cannot hold a column, even through a recorded type, or ``None``. @@ -858,10 +887,16 @@ def delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: Args: field: A column, as given to the database. + A top-level name holding a backtick is refused too (``_unmergeable_name_reason``, + ITL-1375). + Returns: Delta's reason (``Invalid data type for Delta Lake: Decimal256(40, 2)``), or ``None`` when Delta holds the column. """ + name_reason = _unmergeable_name_reason(field.name) + if name_reason is not None: + return name_reason if arrow_utils.holds_renamed_map(field.type): # The recorded type goes through Arrow IPC, which renames them (ITL-1334). return "a map's key and item fields read back as 'key' and 'value'" diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 4fe75ba5d..57d9ba0cb 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -521,7 +521,7 @@ def _race_rows(n: int, value: int, order: tuple[str, ...]) -> pa.Table: ("stale_order", "other_order"), [(("a", "b", "rid"), ("b", "rid", "a")), (("b", "rid", "a"), ("a", "b", "rid"))], ) -def test_a_reordered_append_is_committed_as_insert_if_missing_across_writers( +def test_a_reordered_append_is_stored_once_across_writers( tmp_path: Path, skip_duplicates: bool, stale_order: tuple[str, ...], @@ -529,9 +529,9 @@ def test_a_reordered_append_is_committed_as_insert_if_missing_across_writers( ) -> None: """Two handles append the same new record id with different values, each in another order than the stored table. The second commits after the first has - taken its snapshot of the stored ids. As on main (where rows in another order - than the stored table are committed by MERGE), the stale commit fails and the id - keeps one row: the reorder does not turn the commit into a blind append.""" + taken its snapshot of the stored ids. Every commit to an existing table is a + MERGE (ITL-1377): the stale commit fails, is retried against the table as it is + then, and leaves the id alone, so it keeps the first writer's row.""" stale, other = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) stale.add_records( PATH, _race_rows(1, 10, ("rid", "a", "b")), record_id_column="rid", flush=True @@ -549,16 +549,18 @@ def interleave(*args: Any) -> Any: ) return taken - with patch.object(stale, "_snapshot_for_commit", side_effect=interleave): - with pytest.raises(RuntimeError) as raised: - stale.add_records( - PATH, - _race_rows(2, 99, stale_order), - record_id_column="rid", - flush=True, - skip_duplicates=skip_duplicates, - ) - assert type(raised.value.__cause__).__name__ == "CommitFailedError" + with patch.object( + stale, "_snapshot_for_commit", side_effect=interleave + ) as snapshots: + stale.add_records( + PATH, + _race_rows(2, 99, stale_order), + record_id_column="rid", + flush=True, + skip_duplicates=skip_duplicates, + ) + # The first attempt lost to the other writer; the second committed nothing. + assert snapshots.call_count == 2 table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") assert table is not None assert sorted(table.select(["rid", "a"]).to_pylist(), key=str) == [ @@ -735,12 +737,13 @@ def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: @pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) @pytest.mark.parametrize("skip_duplicates", [False, True]) @pytest.mark.parametrize("race", [False, True], ids=["alone", "with another writer"]) -def test_a_refused_reordered_append_leaves_the_next_batch_on_mains_commit( +def test_a_refused_reordered_append_leaves_the_next_batch_committed( tmp_path: Path, schema_handling: str, skip_duplicates: bool, race: bool ) -> None: """A reordered append the ITL-1334 check refuses (other field metadata) queues - nothing, and leaves nothing behind: the next aligned batch is committed as on - main, by append, also when another writer commits an unrelated id meanwhile.""" + nothing, and leaves nothing behind: the next aligned batch is committed, by the + MERGE every commit to an existing table is (ITL-1377), also when another writer + commits an unrelated id meanwhile.""" from deltalake import DeltaTable db = DeltaTableDatabase(tmp_path) @@ -770,7 +773,7 @@ def interleave(*args: Any) -> Any: db.add_records(PATH, _abc(2), flush=True, **kwargs) else: db.add_records(PATH, _abc(2), flush=True, **kwargs) - assert DeltaTable(tmp_path / "t").history()[0]["operation"] == "WRITE" + assert DeltaTable(tmp_path / "t").history()[0]["operation"] == "MERGE" table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") assert table is not None expected = [1, 2, 3] if race else [1, 2] @@ -873,12 +876,13 @@ def test_a_delta_batch_queued_in_another_order_keeps_its_order( ] -def test_a_delta_table_created_again_in_another_order_takes_mains_commit( +def test_a_delta_table_created_again_in_another_order_takes_the_batch( tmp_path: Path, ) -> None: """A Delta table created again in another order while this handle holds the old - one: an aligned batch is committed by append as on main, also with another writer - committing an unrelated id meanwhile (no state of this PR forces a MERGE).""" + one: an aligned batch is committed by the MERGE every commit to an existing + table is (ITL-1377), also with another writer committing an unrelated id + meanwhile.""" import shutil from deltalake import DeltaTable, write_deltalake @@ -910,7 +914,7 @@ def interleave(*args: Any) -> Any: with patch.object(db, "_snapshot_for_commit", side_effect=interleave): db.flush() history = [entry["operation"] for entry in DeltaTable(tmp_path / "t").history()] - assert "MERGE" not in history + assert history == ["MERGE", "MERGE", "WRITE"] table = DeltaTableDatabase(tmp_path).get_all_records( PATH, record_id_column="__record_id" ) diff --git a/tests/test_databases/test_delta_concurrent_writers.py b/tests/test_databases/test_delta_concurrent_writers.py new file mode 100644 index 000000000..9d0ddef91 --- /dev/null +++ b/tests/test_databases/test_delta_concurrent_writers.py @@ -0,0 +1,255 @@ +"""Two writers committing the same new record id store it once (ITL-1377, ITL-1384). + +A ``DeltaTableDatabase`` decides which pending ids are new against the table version it +loads for a commit. Another writer can commit between that load and the commit. Every +commit to an existing table is therefore a MERGE, which Delta refuses when rows were +added after the load; the flush then loads the table again and retries. A create fails +when another writer created the table first, and is retried the same way. + +The interleavings are deterministic: the other writer commits inside the first writer's +flush, after it loaded the table (``_snapshot_for_commit``) or before it creates the +table (``deltalake.write_deltalake``). Two processes are checked as well. +""" + +from __future__ import annotations + +import multiprocessing +import sys +from pathlib import Path +from typing import Any, Literal +from unittest.mock import patch + +import deltalake +import pyarrow as pa +import pytest +from deltalake.exceptions import CommitFailedError + +from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases + +PATH = ("t",) + +SchemaHandling = Literal["error", "merge", "coerce"] + + +@pytest.fixture(autouse=True) +def _no_wait_between_attempts(monkeypatch: pytest.MonkeyPatch) -> None: + """The random wait before a retry only spaces attempts; tests skip it.""" + monkeypatch.setattr(delta_lake_databases, "_sleep_before_retry", lambda _: None) + + +def _records(n: int, value: int, *, reordered: bool = False) -> pa.Table: + """One row with record id ``bytes([n])``; ``reordered`` puts its columns in another order.""" + table = pa.table( + { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([value], pa.int64()), + "z": pa.array([100 + n], pa.int64()), + } + ) + return table.select(["z", "rid", "a"]) if reordered else table + + +def _stored(root: Path) -> list[tuple[bytes, int]]: + """Every stored ``(record id, a)``, read by a fresh database, sorted.""" + table = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="rid") + assert table is not None + return sorted(zip(table["rid"].to_pylist(), table["a"].to_pylist())) + + +def _operations(root: Path) -> list[str]: + """The table's commit operations, oldest first.""" + history = deltalake.DeltaTable(str(root / "t")).history() + return [str(entry["operation"]) for entry in reversed(history)] + + +def _commit_after_load( + one: DeltaTableDatabase, commit: Any, *, every_attempt: bool = False +) -> Any: + """Patch ``one`` so ``commit()`` runs after ``one`` loads the table for a commit.""" + real = one._snapshot_for_commit + done: list[bool] = [] + + def interleaved(*args: Any) -> Any: + loaded = real(*args) + if every_attempt or not done: + done.append(True) + commit() + return loaded + + return patch.object(one, "_snapshot_for_commit", side_effect=interleaved) + + +@pytest.mark.parametrize("flushed", [False, True], ids=["pending", "flushed"]) +@pytest.mark.parametrize("reordered", [False, True], ids=["same-order", "other-order"]) +@pytest.mark.parametrize("skip_duplicates", [True, False]) +@pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) +def test_an_id_another_writer_committed_meanwhile_is_stored_once( + tmp_path: Path, + schema_handling: SchemaHandling, + skip_duplicates: bool, + reordered: bool, + flushed: bool, +) -> None: + """The later writer retries, sees the id and leaves it: the first writer's row stays.""" + one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + one.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) + + def other_writer() -> None: + two.add_records( + PATH, + _records(2, 99, reordered=reordered), + record_id_column="rid", + skip_duplicates=skip_duplicates, + schema_handling=schema_handling, + flush=True, + ) + + with _commit_after_load(one, other_writer): + one.add_records( + PATH, + _records(2, 20), + record_id_column="rid", + skip_duplicates=skip_duplicates, + schema_handling=schema_handling, + flush=flushed, + ) + if not flushed: + one.flush() + + assert _stored(tmp_path) == [(b"\x01", 10), (b"\x02", 99)] + # The later writer's retry inserted nothing, so it committed nothing. + assert _operations(tmp_path) == ["WRITE", "MERGE"] + # Both handles answer from what is committed. + for db in (one, two): + row = db.get_record_by_id(PATH, b"\x02") + assert row is not None and row["a"].to_pylist() == [99] + + +@pytest.mark.parametrize("reordered", [False, True], ids=["same-order", "other-order"]) +def test_disjoint_ids_are_both_committed(tmp_path: Path, reordered: bool) -> None: + """A conflict over another id is retried, and both rows are stored.""" + one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + one.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) + + def other_writer() -> None: + two.add_records( + PATH, + _records(3, 30, reordered=reordered), + record_id_column="rid", + flush=True, + ) + + with _commit_after_load(one, other_writer): + one.add_records(PATH, _records(2, 20), record_id_column="rid", flush=True) + + assert _stored(tmp_path) == [(b"\x01", 10), (b"\x02", 20), (b"\x03", 30)] + assert _operations(tmp_path) == ["WRITE", "MERGE", "MERGE"] + row = one.get_record_by_id(PATH, b"\x03") + assert row is not None and row["a"].to_pylist() == [30] + + +@pytest.mark.parametrize("same_id", [True, False], ids=["same-id", "other-id"]) +def test_a_table_another_writer_created_meanwhile_keeps_its_rows( + tmp_path: Path, same_id: bool +) -> None: + """The later create fails and is retried as a MERGE; no committed row is lost (ITL-1384).""" + one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + real = deltalake.write_deltalake + created: list[bool] = [] + + def interleaved(*args: Any, **kwargs: Any) -> None: + if not created: + created.append(True) + two.add_records( + PATH, + _records(1 if same_id else 2, 99), + record_id_column="rid", + flush=True, + ) + real(*args, **kwargs) + + one.add_records(PATH, _records(1, 10), record_id_column="rid") + with patch.object(deltalake, "write_deltalake", side_effect=interleaved): + one.flush() + + if same_id: + assert _stored(tmp_path) == [(b"\x01", 99)] + assert _operations(tmp_path) == ["WRITE"] + else: + assert _stored(tmp_path) == [(b"\x01", 10), (b"\x02", 99)] + assert _operations(tmp_path) == ["WRITE", "MERGE"] + + +def test_a_writer_that_keeps_losing_stops_after_the_bound(tmp_path: Path) -> None: + """After ``_COMMIT_ATTEMPTS`` lost commits the flush raises main's error; rows stay queued.""" + one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + one.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) + others = iter(range(10, 10 + delta_lake_databases._COMMIT_ATTEMPTS)) + + def other_writer() -> None: + two.add_records( + PATH, _records(next(others), 0), record_id_column="rid", flush=True + ) + + one.add_records(PATH, _records(2, 20), record_id_column="rid") + with _commit_after_load(one, other_writer, every_attempt=True) as loads: + with pytest.raises(RuntimeError) as info: + one.flush() + assert isinstance(info.value.__cause__, CommitFailedError) + assert loads.call_count == delta_lake_databases._COMMIT_ATTEMPTS + # The batch is still queued, and the next flush commits it. + one.flush() + stored = _stored(tmp_path) + assert (b"\x02", 20) in stored + assert len(stored) == 2 + delta_lake_databases._COMMIT_ATTEMPTS + + +def test_a_writer_that_wins_after_losing_commits_within_the_bound( + tmp_path: Path, +) -> None: + """Losing every attempt but the last still commits.""" + one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + one.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) + losses = delta_lake_databases._COMMIT_ATTEMPTS - 1 + others = iter(range(10, 10 + losses)) + + def other_writer() -> None: + other = next(others, None) + if other is not None: + two.add_records( + PATH, _records(other, 0), record_id_column="rid", flush=True + ) + + one.add_records(PATH, _records(2, 20), record_id_column="rid") + with _commit_after_load(one, other_writer, every_attempt=True) as loads: + one.flush() + assert loads.call_count == delta_lake_databases._COMMIT_ATTEMPTS + assert (b"\x02", 20) in _stored(tmp_path) + + +def _write_ids(root: str, start: Any, ids: list[int], value: int) -> None: + """Commit each id in ``ids`` alone, once ``start`` lets every process go.""" + db = DeltaTableDatabase(root) + start.wait() + for n in ids: + db.add_records(PATH, _records(n, value), record_id_column="rid", flush=True) + + +@pytest.mark.skipif(sys.platform == "win32", reason="spawned writers on one table") +def test_writers_in_other_processes_store_each_id_once(tmp_path: Path) -> None: + """Three processes commit the same ids one at a time: each id is stored once.""" + context = multiprocessing.get_context("spawn") + start = context.Barrier(3) + ids = list(range(1, 13)) + processes = [ + context.Process(target=_write_ids, args=(str(tmp_path), start, ids, value)) + for value in (1, 2, 3) + ] + for process in processes: + process.start() + for process in processes: + process.join(timeout=120) + assert process.exitcode == 0 + stored = _stored(tmp_path) + assert [rid for rid, _ in stored] == [bytes([n]) for n in ids] diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index 87d368bd3..3f0504b68 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -20,6 +20,7 @@ import pytest from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InputValidationError, UnstorableColumnError from orcapod.databases.delta_statistics import ( NUM_INDEXED_COLUMNS_PROPERTY, STATS_COLUMNS_PROPERTY, @@ -376,24 +377,51 @@ def test_every_kind_is_written_without_warning( == _every_kind(range(0, 1)).select(compared).to_pylist() ) - def test_backtick_name_is_left_out_and_written( - self, tmp_path: Path, capfd: pytest.CaptureFixture[str] + def test_backtick_name_is_refused_before_anything_is_queued( + self, tmp_path: Path ) -> None: - """Create and append work; delta-rs cannot MERGE such a table either way.""" + """delta-rs cannot MERGE such a table, and every later commit is one (ITL-1375).""" db = DeltaTableDatabase(tmp_path) - - def table(ids: range) -> pa.Table: - return rows(ids).append_column("x`y", pa.array(list(ids), pa.int64())) - - capfd.readouterr() - db.add_records(PATH, table(range(0, 3)), flush=True) - db.add_records(PATH, table(range(3, 6)), flush=True) - assert stats_warnings(capfd) == [] - assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" - } + with pytest.raises(UnstorableColumnError) as info: + db.add_records( + PATH, + rows(range(0, 3)).append_column("x`y", pa.array([0, 1, 2], pa.int64())), + flush=True, + ) + assert info.value.column == "x`y" + assert "backtick" in info.value.reason + assert not (tmp_path / "t" / "_delta_log").exists() + # A backtick inside a nested field's name is merged as any other. + nested = pa.array([{"x`y": i} for i in range(3)]) + db.add_records(PATH, rows(range(0, 3)).append_column("s", nested), flush=True) + db.add_records( + PATH, + rows(range(3, 6)).append_column("s", pa.array([{"x`y": 3}] * 3)), + flush=True, + ) assert len(stored_ids(db)) == 6 + def test_a_stored_table_with_a_backtick_name_takes_no_append( + self, tmp_path: Path + ) -> None: + """A table written with such a column before ITL-1375 is refused, rows unchanged.""" + deltalake.write_deltalake( + str(tmp_path / "t"), + rows(range(0, 3)).append_column("x`y", pa.array([0, 1, 2], pa.int64())), + ) + db = DeltaTableDatabase(tmp_path) + # Rows holding the column are refused as new ones are (above); rows without + # it are refused by the stored table. + with pytest.raises(UnstorableColumnError): + db.add_records( + PATH, + rows(range(3, 6)).append_column("x`y", pa.array([3, 4, 5], pa.int64())), + ) + with pytest.raises(InputValidationError, match="backtick") as info: + db.add_records(PATH, rows(range(3, 6)), flush=True) + assert "'x`y'" in str(info.value) + assert len(stored_ids(db)) == 3 + def test_names_of_nested_parts_are_left_out_and_written( self, tmp_path: Path, capfd: pytest.CaptureFixture[str] ) -> None: diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index a3c298224..e16172c34 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1041,6 +1041,10 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: field, so a map with such metadata is refused there. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. +- Delta refuses a column whose name holds a backtick, of any type: delta-rs cannot MERGE + such a table, and every commit to an existing Delta table is a MERGE. A table that + already holds such a column takes no further append. A backtick in a nested field's + name is kept. A table holds one type per column. An append whose columns differ from the held ones (stored, or still pending) in field metadata (the column's own, or a nested field's: a From 558ddb30f2fe7dd5993e722d30d6d7bf27e1b15e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 17:17:45 -0800 Subject: [PATCH 03/23] fix(databases): bound a lost Delta commit's retries by 200 attempts, as measured under contention (ITL-1377) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 7 +++++-- .../test_delta_concurrent_writers.py | 17 +++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 59d4898ae..c73495578 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -75,8 +75,11 @@ # How many times a flush tries to commit a table's pending rows when other writers # keep committing first; after the last attempt it raises the last conflict -# (ITL-1377). -_COMMIT_ATTEMPTS = 10 +# (ITL-1377). A writer that lost waits until the others pause: measured with 4 +# processes each committing 200 batches back to back, one commit took 97 attempts. +# With the wait capped at 0.5 s (``_sleep_before_retry``), 200 attempts give up after +# about 100 s of losing. +_COMMIT_ATTEMPTS = 200 class _LostCommitRace(Exception): diff --git a/tests/test_databases/test_delta_concurrent_writers.py b/tests/test_databases/test_delta_concurrent_writers.py index 9d0ddef91..cea096315 100644 --- a/tests/test_databases/test_delta_concurrent_writers.py +++ b/tests/test_databases/test_delta_concurrent_writers.py @@ -32,10 +32,15 @@ SchemaHandling = Literal["error", "merge", "coerce"] +BOUND = 4 + + @pytest.fixture(autouse=True) def _no_wait_between_attempts(monkeypatch: pytest.MonkeyPatch) -> None: - """The random wait before a retry only spaces attempts; tests skip it.""" + """The random wait before a retry only spaces attempts; tests skip it, and use a + small bound so that reaching it takes a few commits.""" monkeypatch.setattr(delta_lake_databases, "_sleep_before_retry", lambda _: None) + monkeypatch.setattr(delta_lake_databases, "_COMMIT_ATTEMPTS", BOUND) def _records(n: int, value: int, *, reordered: bool = False) -> pa.Table: @@ -185,7 +190,7 @@ def test_a_writer_that_keeps_losing_stops_after_the_bound(tmp_path: Path) -> Non """After ``_COMMIT_ATTEMPTS`` lost commits the flush raises main's error; rows stay queued.""" one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) one.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) - others = iter(range(10, 10 + delta_lake_databases._COMMIT_ATTEMPTS)) + others = iter(range(10, 10 + BOUND)) def other_writer() -> None: two.add_records( @@ -197,12 +202,12 @@ def other_writer() -> None: with pytest.raises(RuntimeError) as info: one.flush() assert isinstance(info.value.__cause__, CommitFailedError) - assert loads.call_count == delta_lake_databases._COMMIT_ATTEMPTS + assert loads.call_count == BOUND # The batch is still queued, and the next flush commits it. one.flush() stored = _stored(tmp_path) assert (b"\x02", 20) in stored - assert len(stored) == 2 + delta_lake_databases._COMMIT_ATTEMPTS + assert len(stored) == 2 + BOUND def test_a_writer_that_wins_after_losing_commits_within_the_bound( @@ -211,7 +216,7 @@ def test_a_writer_that_wins_after_losing_commits_within_the_bound( """Losing every attempt but the last still commits.""" one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) one.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) - losses = delta_lake_databases._COMMIT_ATTEMPTS - 1 + losses = BOUND - 1 others = iter(range(10, 10 + losses)) def other_writer() -> None: @@ -224,7 +229,7 @@ def other_writer() -> None: one.add_records(PATH, _records(2, 20), record_id_column="rid") with _commit_after_load(one, other_writer, every_attempt=True) as loads: one.flush() - assert loads.call_count == delta_lake_databases._COMMIT_ATTEMPTS + assert loads.call_count == BOUND assert (b"\x02", 20) in _stored(tmp_path) From e218443a0993ad4422d72a43eedf385d3a1e6084 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 17:41:14 -0800 Subject: [PATCH 04/23] perf(databases): merge Delta commits without streaming the pending rows (ITL-1377) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c73495578..c76eafb81 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2862,6 +2862,13 @@ def _commit_once( source_alias="source", target_alias="target", merge_schema=self.allow_schema_evolution, + # The pending rows are in memory already. Not streaming them lets + # delta-rs read their id range first and plan the join with it: a + # one-row commit to a 10M-row table took 270 ms instead of 400 ms + # (ITL-1377). The id column has no file statistics (delta-rs keeps + # none for binary columns), so no file is skipped, and a concurrent + # commit of any id still makes this commit fail. + streamed_exec=False, ).when_not_matched_insert_all().execute() except CommitFailedError as conflict: raise _LostCommitRace(conflict) from conflict From 81d00aa19aa8625485fc246f4755ac9d8f6b2876 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 18:21:50 -0800 Subject: [PATCH 05/23] build(deps): require deltalake>=1.6.6; refuse on Delta what deltalake 1.5+ refuses (ITL-1403) deltalake 1.6.6 makes a Delta MERGE 2-8x faster than 1.0.2 (ITL-1377). It also refuses two kinds of table 1.0.2 took; DeltaTableDatabase now refuses them before anything is queued: - two columns, or two fields of one struct, whose names differ only in case (Delta column names are case-insensitive; refused from 1.5.1); - an append that would change a stored column's recorded Arrow type (a field added to a recorded struct) or a logical column's type: deltalake 1.5+ does not let a commit change a column's field metadata. The lock changes deltalake only. docs/dev/scripts/itl_1403 holds the interop check (every stored table kind, both directions) and the premise check (no job reaches the record refusal on Orcapod's own tables). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 24 ++ docs/dev/scripts/itl_1403/compare.py | 69 +++++ docs/dev/scripts/itl_1403/interop.py | 137 +++++++++ docs/dev/scripts/itl_1403/interop.sh | 17 ++ docs/dev/scripts/itl_1403/premise.py | 260 ++++++++++++++++++ docs/reference/database-types.md | 13 +- docs/troubleshooting.md | 19 -- docs/tutorial/00-setup.md | 3 - docs/tutorial/05-pipeline-job.md | 2 - pyproject.toml | 2 +- src/orcapod/databases/delta_lake_databases.py | 219 +++++++++++++-- tests/test_databases/test_append_by_name.py | 44 ++- .../test_delta_append_preflight.py | 17 +- .../test_delta_read_failures.py | 17 +- .../test_delta_statistics_columns.py | 17 +- .../test_delta_struct_evolution.py | 125 ++++++++- tests/test_databases/type_matrix.py | 13 +- uv.lock | 19 +- 18 files changed, 927 insertions(+), 90 deletions(-) create mode 100644 changelog.d/ITL-1403.md create mode 100644 docs/dev/scripts/itl_1403/compare.py create mode 100644 docs/dev/scripts/itl_1403/interop.py create mode 100755 docs/dev/scripts/itl_1403/interop.sh create mode 100644 docs/dev/scripts/itl_1403/premise.py diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md new file mode 100644 index 000000000..a8c732215 --- /dev/null +++ b/changelog.d/ITL-1403.md @@ -0,0 +1,24 @@ +### Changed + +- Orcapod now requires deltalake 1.6.6 or newer (was 1.0.2). A commit to a Delta table is + faster with it: a one-row MERGE into a 10-million-row table took about 110 ms instead + of about 380 ms, and into a 5 GB table about 1.2 s instead of about 2.6 s. Tables written + by either version are read and appended to by the other, with identical rows, for every + stored table kind. New tables keep Delta protocol 1/2, with no table features. deltalake + 1.6 no longer logs `Skipping column ... because it's a binary field`. +- `DeltaTableDatabase` refuses two columns, or two fields of one struct, whose names + differ only in case (`a` and `A`), before anything is queued + (`UnstorableColumnError`, or `InputValidationError` for a column added beside a held or + queued one). Delta column names are case-insensitive, and deltalake 1.5.1 and later + refuses such a table. The in-memory and connector databases still hold such names as + two columns. +- `DeltaTableDatabase` refuses an append that would change a stored column's recorded + Arrow type (`InputValidationError` naming the column, before anything is queued). This + covers a field added to a struct whose type is recorded: every list and map column, + and every struct holding an unsigned integer, a non-microsecond time type, `float16` + or a fixed-size type. It also covers another logical type over a stored logical + column's storage type. deltalake 1.5 and later does not let a commit change a column's + field metadata, and the record is field metadata. A struct column without a record + still gains fields, a field may still be omitted or reordered, and a new column may + still be added. No job reaches the refusal on the tables Orcapod's own nodes write: a + changed column type changes the table's path. diff --git a/docs/dev/scripts/itl_1403/compare.py b/docs/dev/scripts/itl_1403/compare.py new file mode 100644 index 000000000..1066018db --- /dev/null +++ b/docs/dev/scripts/itl_1403/compare.py @@ -0,0 +1,69 @@ +"""ITL-1403: compare interop dumps: same tables, schemas and rows (run-dependent columns left out). + +usage: python compare.py A.json B.json [C.json ...] (exit 1 when any differs from A) +""" + +from __future__ import annotations + +import json +import sys +from typing import Any + +# Values a run makes, not the data: write times, run ids, row ids drawn at random. +VOLATILE = {"__pod_ts", "executed_at", "pipeline_run_id", "__data_id"} + + +def rows(name: str, table: dict[str, Any]) -> list[str]: + out = [] + for row in table["rows"]: + values = {k: v for k, v in json.loads(row).items() if k not in VOLATILE} + text = json.dumps(values, sort_keys=True) + if "/_result/" in name: + # A result row's record id is a uuid7 drawn when it is stored; the + # source-info tokens of its outputs repeat it. + text = text.replace(values["__record_id"], "") + out.append(text) + return sorted(out) + + +def load(path: str) -> dict[str, Any]: + data = json.load(open(path)) + # Table paths hold no version; compare them as they are. + return data + + +def main() -> int: + first, *others = sys.argv[1:] + a = load(first) + status = 0 + for other in others: + before = status + status = 0 + b = load(other) + if set(a["tables"]) != set(b["tables"]): + print( + f"{other}: tables differ: {sorted(set(a['tables']) ^ set(b['tables']))}" + ) + status = 1 + continue + for name in sorted(a["tables"]): + x, y = a["tables"][name], b["tables"][name] + if x["schema"] != y["schema"]: + print( + f"{other}: {name}: schema differs\n {x['schema']}\n {y['schema']}" + ) + status = 1 + if rows(name, x) != rows(name, y): + print( + f"{other}: {name}: rows differ ({len(x['rows'])} vs {len(y['rows'])})" + ) + status = 1 + print( + f"{first} vs {other}: {'equal' if status == 0 else 'DIFFERENT'} ({len(a['tables'])} tables)" + ) + status = max(status, before) + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/dev/scripts/itl_1403/interop.py b/docs/dev/scripts/itl_1403/interop.py new file mode 100644 index 000000000..e3642071a --- /dev/null +++ b/docs/dev/scripts/itl_1403/interop.py @@ -0,0 +1,137 @@ +"""ITL-1403: a Delta store written by one deltalake version, read and appended by another. + +One job writes every stored table kind into a ``DeltaTableDatabase``: a function pod +(result and pipeline tables), an operator node that logs (a ``Join``: the operator cache), +a cached source and a side-effect pod (its log). ``run`` runs the job over the rows of a +generation (``first``: two rows per source; ``second``: two more), so a second run appends +to every table the first created. ``dump`` writes every stored table, read back through +``DeltaTableDatabase``, with its rows sorted, plus each table's Delta protocol, as JSON. + + interop.py run STORE first + interop.py run STORE second # B reads and appends to A's tables + interop.py dump STORE OUT.json + +``interop.sh`` runs both directions and a single-version control and compares the dumps. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + +import deltalake +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import DeltaTableDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +ROWS = { + "first": [("s1", 1), ("s2", 2)], + "second": [("s1", 1), ("s2", 2), ("s3", 3), ("s4", 4)], +} + + +def _source( + name: str, data: list[str], rows: list[tuple[str, int]] +) -> ArrowTableSource: + fields = [ + pa.field("z_tag", pa.large_string(), nullable=False), + pa.field("a_tag", pa.int64(), nullable=False), + *(pa.field(n, pa.float64(), nullable=False) for n in data), + ] + arrays = [ + pa.array([z for z, _ in rows], pa.large_string()), + pa.array([a for _, a in rows], pa.int64()), + *( + pa.array([float(a) * (k + 1) for _, a in rows], pa.float64()) + for k in range(len(data)) + ), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + source_id=name, + record_id_columns=["z_tag"], + ) + + +@function_pod(output_keys=["w_out", "c_out"]) +def compute(y: float, b: float) -> tuple[float, float]: + return y + b, y - b + + +def notify(ctx: Any, y: float, b: float) -> None: + return None + + +def run(store: Path, generation: str) -> None: + rows = ROWS[generation] + database = DeltaTableDatabase(store) + job = PipelineJob(name="itl1403", database=database) + cached = CachedSource(_source("left", ["y", "b"], rows), cache_database=database) + with job: + compute.pod(cached, label="fn") + Join()(cached, _source("right", ["x", "e"], rows), label="joined") + SideEffectPod(notify)(cached, label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + database.flush() + + +def _canonical(value: Any) -> Any: + if isinstance(value, bytes): + return value.hex() + if isinstance(value, dict): + return {k: _canonical(v) for k, v in value.items()} + if isinstance(value, list): + return [_canonical(v) for v in value] + return value + + +def dump(store: Path, out: Path) -> None: + database = DeltaTableDatabase(store) + tables: dict[str, Any] = {} + for path in sorted(database.list_table_paths()): + table = database.get_all_records(path, record_id_column="__record_id") + assert table is not None, path + rows = sorted( + ( + json.dumps(_canonical(row), sort_keys=True, default=str) + for row in table.to_pylist() + ) + ) + delta = deltalake.DeltaTable(str(store.joinpath(*path))) + protocol = delta.protocol() + tables["/".join(path)] = { + "schema": [f"{f.name}: {f.type}" for f in table.schema], + "rows": rows, + "protocol": { + "min_reader_version": protocol.min_reader_version, + "min_writer_version": protocol.min_writer_version, + "reader_features": protocol.reader_features, + "writer_features": protocol.writer_features, + }, + "operations": [h["operation"] for h in delta.history()][::-1], + } + out.write_text( + json.dumps({"deltalake": deltalake.__version__, "tables": tables}, indent=1) + ) + print(f"deltalake {deltalake.__version__}: {len(tables)} tables dumped to {out}") + + +if __name__ == "__main__": + if sys.argv[1] == "run": + run(Path(sys.argv[2]), sys.argv[3]) + print(f"deltalake {deltalake.__version__}: ran {sys.argv[3]} on {sys.argv[2]}") + else: + dump(Path(sys.argv[2]), Path(sys.argv[3])) diff --git a/docs/dev/scripts/itl_1403/interop.sh b/docs/dev/scripts/itl_1403/interop.sh new file mode 100755 index 000000000..adcb6f3a2 --- /dev/null +++ b/docs/dev/scripts/itl_1403/interop.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# ITL-1403: a store written by deltalake OLD, read and appended by NEW, the reverse, and a +# control written by OLD alone; every dump read by both versions; dumps compared. +# usage: interop.sh OLD_PYTHON NEW_PYTHON WORKDIR +set -euo pipefail +OLD="$1"; NEW="$2"; W="$3"; HERE="$(cd "$(dirname "$0")" && pwd)" +export RUST_LOG=off +rm -rf "$W"; mkdir -p "$W" +for case in old-new new-old old-old new-new; do + first=${case%-*}; second=${case#*-} + P1=$([ "$first" = old ] && echo "$OLD" || echo "$NEW"); P2=$([ "$second" = old ] && echo "$OLD" || echo "$NEW") + "$P1" "$HERE/interop.py" run "$W/$case" first + "$P2" "$HERE/interop.py" run "$W/$case" second + "$OLD" "$HERE/interop.py" dump "$W/$case" "$W/$case.read-by-old.json" + "$NEW" "$HERE/interop.py" dump "$W/$case" "$W/$case.read-by-new.json" +done +python3 "$HERE/compare.py" "$W/old-old.read-by-old.json" "$W"/*.json diff --git a/docs/dev/scripts/itl_1403/premise.py b/docs/dev/scripts/itl_1403/premise.py new file mode 100644 index 000000000..f923fcf4c --- /dev/null +++ b/docs/dev/scripts/itl_1403/premise.py @@ -0,0 +1,260 @@ +"""ITL-1403: can a job reach the refusal of a recorded type change on its own tables? + +The developer's premise: a table Orcapod's nodes write (function result, pipeline +records, operator cache, cached source, side-effect log) has its column definition fixed +by its path (a schema hash in the path), so no job can append rows whose recorded Arrow +type differs from the stored one. Each case below runs a job twice into one +``DeltaTableDatabase``, varying one thing between the runs, and reports whether the +second run was refused, and which stored tables it wrote: the same path (its rows had to +carry the same record) or a new one. + +Cases (each where the Python schema may be equal but the Arrow record could differ): + +- ``optional_fields``: a dataclass output whose instances leave an optional field + ``None`` in one run and set it in the other. +- ``list_item_nulls``: a ``list[int]`` output holding ``None`` items in one run only. +- ``class_gains_field``: a user class output gaining a field between the runs (the same + module and name, redefined). +- ``nullable_vs_not``: a source tag column ``T | None`` (nulls present) in one run, ``T`` + in the other. +- ``widths``: a source data column ``int32`` in one run, ``int64`` in the other. +- ``struct_gains_field``: a source data column, a struct with a recorded type + (``uint8``), gaining a field between the runs, through a cached source, a function + pod, an operator that logs and a side-effect pod. + +usage: uv run python docs/dev/scripts/itl_1403/premise.py WORKDIR +""" + +import os +import shutil +import subprocess +import sys +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import DeltaTableDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + + +@dataclass +class Point: + x: float + label: str | None + + +# The same module path and name in both runs; the second run (another process) has a +# field more. +_SHAPE_EXTRA = os.environ.get("ITL1403_SHAPE_EXTRA") == "1" + + +@dataclass +class Shape: + x: float + if _SHAPE_EXTRA: + y: float = 0.0 + + +def _shape(v: float) -> Shape: + return Shape(v, v) if _SHAPE_EXTRA else Shape(v) + + +@function_pod(output_keys=["s"]) +def to_shape(v: float) -> Shape: + return _shape(v) + + +def _source( + name: str, columns: dict[str, "pa.Array[Any]"], tags: list[str] +) -> ArrowTableSource: + schema = pa.schema( + [pa.field(n, a.type, nullable=a.null_count > 0) for n, a in columns.items()] + ) + return ArrowTableSource( + pa.Table.from_arrays(list(columns.values()), schema=schema), + tag_columns=tags, + tag_only_columns=True, + source_id=name, + record_id_columns=["k"], + ) + + +def _keys(n: int) -> "pa.Array[Any]": + return pa.array([f"k{i}" for i in range(n)], pa.large_string()) + + +def notify(ctx: Any, v: Any) -> None: + return None + + +def _job(store: Path, source: ArrowTableSource, pod: Any, data: str) -> None: + """Every stored table kind over ``source``: cached source, function pod, a logging + operator node and a side-effect pod.""" + database = DeltaTableDatabase(store) + job = PipelineJob(name="premise", database=database) + cached = CachedSource(source, cache_database=database) + other = _source( + "other", {"k": _keys(2), "w": pa.array([1.0, 2.0], pa.float64())}, ["k"] + ) + with job: + pod(cached, label="fn") + Join()(cached, other, label="joined") + SideEffectPod(notify)(cached.select_data_columns([data]), label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + database.flush() + + +def _tables(store: Path) -> set[str]: + return {"/".join(p) for p in DeltaTableDatabase(store).list_table_paths()} + + +@function_pod(output_keys=["out"]) +def identity_v(v: Any) -> Any: # replaced per case with a typed pod + return v + + +def _case(store: Path, first: Callable[[], None], second: Callable[[], None]) -> str: + shutil.rmtree(store, ignore_errors=True) + first() + before = _tables(store) + try: + second() + except Exception as e: # noqa: BLE001 + return f"REFUSED on the second run: {type(e).__name__}: {str(e)[:300]}" + after = _tables(store) + new = sorted(after - before) + return ( + f"no refusal; {len(before)} tables after run 1, {len(new)} new after run 2" + + "".join(f"\n new: {t[:110]}" for t in new) + ) + + +def main(work: Path) -> None: + results: dict[str, str] = {} + + # optional_fields + @function_pod(output_keys=["p"]) + def to_point(v: float) -> Point: + return Point(v, None if v < 10 else f"p{v}") + + def run_points(values: list[float]) -> Callable[[], None]: + src = _source("s", {"k": _keys(2), "v": pa.array(values, pa.float64())}, ["k"]) + return lambda: _job(work / "optional_fields", src, to_point.pod, "v") + + results["optional_fields"] = _case( + work / "optional_fields", run_points([1.0, 2.0]), run_points([11.0, 12.0]) + ) + + # list_item_nulls + @function_pod(output_keys=["items"]) + def to_items(v: float) -> list[int | None]: + return [int(v), None] if v > 10 else [int(v)] + + def run_items(values: list[float]) -> Callable[[], None]: + src = _source("s", {"k": _keys(2), "v": pa.array(values, pa.float64())}, ["k"]) + return lambda: _job(work / "list_item_nulls", src, to_items.pod, "v") + + results["list_item_nulls"] = _case( + work / "list_item_nulls", run_items([1.0, 2.0]), run_items([11.0, 12.0]) + ) + + # class_gains_field: each run in its own process (see ``Shape``). + def run_shape(extra: bool) -> Callable[[], None]: + def go() -> None: + subprocess.run( + [sys.executable, __file__, "shape", str(work / "class_gains_field")], + env={**os.environ, "ITL1403_SHAPE_EXTRA": "1" if extra else "0"}, + check=True, + ) + + return go + + results["class_gains_field"] = _case( + work / "class_gains_field", run_shape(False), run_shape(True) + ) + + # nullable_vs_not: a tag T | None (nulls present), then T. + @function_pod(output_keys=["d"]) + def double(v: float) -> float: + return 2 * v + + def run_tag(nullable: bool) -> Callable[[], None]: + t = pa.array([1, None] if nullable else [1, 2], pa.int64()) + src = ArrowTableSource( + pa.Table.from_arrays( + [_keys(2), t, pa.array([1.0, 2.0], pa.float64())], + schema=pa.schema( + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("t", pa.int64(), nullable=nullable), + pa.field("v", pa.float64(), nullable=False), + ] + ), + ), + tag_columns=["k", "t"], + tag_only_columns=True, + source_id="s", + record_id_columns=["k"], + ) + return lambda: _job(work / "nullable_vs_not", src, double.pod, "v") + + results["nullable_vs_not"] = _case( + work / "nullable_vs_not", run_tag(True), run_tag(False) + ) + + # widths: an int32 data column, then int64. + @function_pod(output_keys=["d"]) + def widen(v: int) -> int: + return v + 1 + + def run_width(width: pa.DataType) -> Callable[[], None]: + src = _source("s", {"k": _keys(2), "v": pa.array([1, 2], width)}, ["k"]) + return lambda: _job(work / "widths", src, widen.pod, "v") + + results["widths"] = _case( + work / "widths", run_width(pa.int32()), run_width(pa.int64()) + ) + + # struct_gains_field: a recorded struct data column (uint8 inside) gaining a field. + @function_pod(output_keys=["n"]) + def count(v: Any) -> int: + return 1 + + def run_struct(extra: bool) -> Callable[[], None]: + fields = [pa.field("a", pa.uint8())] + ( + [pa.field("b", pa.uint8())] if extra else [] + ) + values = [{"a": 1, "b": 2}, {"a": 3, "b": 4}] if extra else [{"a": 1}, {"a": 3}] + src = _source( + "s", {"k": _keys(2), "v": pa.array(values, pa.struct(fields))}, ["k"] + ) + return lambda: _job(work / "struct_gains_field", src, count.pod, "v") + + results["struct_gains_field"] = _case( + work / "struct_gains_field", run_struct(False), run_struct(True) + ) + + for name, outcome in results.items(): + print(f"{name}: {outcome}") + + +if __name__ == "__main__": + if sys.argv[1] == "shape": + store = Path(sys.argv[2]) + src = _source( + "s", {"k": _keys(2), "v": pa.array([1.0, 2.0], pa.float64())}, ["k"] + ) + _job(store, src, to_shape.pod, "v") + else: + main(Path(sys.argv[1])) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 9819e3cfb..88021bf30 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -79,10 +79,19 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map +included) cannot gain a field: the record is the column's field metadata, which Delta +(deltalake 1.5 and later) does not let a commit change, so such an append is refused, +naming the column, before anything is queued. A struct column without a record still +gains fields, and an append may still add a new column. Another logical type over a +stored logical column's storage type is refused the same way. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two -columns), never by position. Rows whose columns are the held table's columns in another +columns), never by position. Delta alone refuses two columns, or two fields of one +struct, whose names differ only in case: Delta column names are case-insensitive, so +such a table, or an append that would make one, is refused naming both, before anything +is queued. Rows whose columns are the held table's columns in another order, each field equal to the held one (the same type at every depth, the same logical type, the same field attributes), are put in the held order, whether the table was flushed in between or not. The in-memory database matches them to the rows still pending, diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6579a12e6..4d494707e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -302,25 +302,6 @@ a path to nothing. **Fix.** Delete output files and the database together, or bump the function's major version to regenerate them. -## Messages you can ignore - -- `WARN deltalake_core::writer::stats] Skipping column ... because it's a binary field.` - whenever a `DeltaTableDatabase` writes to a table that an earlier version of Orcapod - created: one line per binary column (record ids and hashes) per commit. The deltalake - library keeps no minimum and maximum statistics for binary columns and says so on every - write; nothing is wrong with the table. A table that `DeltaTableDatabase` creates now names - the columns it keeps statistics for (the `delta.dataSkippingStatsColumns` table property), - and writes to it log nothing. Orcapod never changes the property of an existing table. To - hide only this line for an older table, set `RUST_LOG` in the environment before Python - starts, keeping deltalake's other warnings: - - ``` - RUST_LOG="warn,deltalake_core::writer::stats=error" python my_pipeline.py - ``` - - deltalake reads `RUST_LOG` once, when it is first imported, so setting it later in the - same process (for example with `os.environ`) has no effect. - ## A script finishes its work but the process never exits **Symptom.** A Python script that used a Delta database prints all of its output and then hangs, diff --git a/docs/tutorial/00-setup.md b/docs/tutorial/00-setup.md index 6d2eebd92..7ab90205c 100644 --- a/docs/tutorial/00-setup.md +++ b/docs/tutorial/00-setup.md @@ -80,9 +80,6 @@ Depending on what else is installed, you may see these on your screen. They are - `UserWarning: Protobuf gencode version ... is exactly one major version older than the runtime version ...`, several times, when Orcapod is imported. -- `WARN deltalake_core::writer::stats] Skipping column ... because it's a binary field.`, - many times, whenever results are written to an on-disk database (from - [Part 5](05-pipeline-job.md) on). ## Get the dataset diff --git a/docs/tutorial/05-pipeline-job.md b/docs/tutorial/05-pipeline-job.md index 3291b904a..fb2d17fde 100644 --- a/docs/tutorial/05-pipeline-job.md +++ b/docs/tutorial/05-pipeline-job.md @@ -234,8 +234,6 @@ print(len(calls)) ``` This is a different, empty database, so everything was computed once more: 71 further calls. -(You will see many `WARN deltalake_core::writer::stats` lines while it writes. They are -harmless; see [Part 0](00-setup.md#messages-you-can-ignore).) Now do what a new Python session would do: make a new database object for the same directory, build the job, run it. diff --git a/pyproject.toml b/pyproject.toml index cd3e10a74..8913e2945 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ "polars>=1.36.0", "numpy>=1.26.4", "beartype>=0.21.0", - "deltalake>=1.0.2", + "deltalake>=1.6.6", "gitpython>=3.1.45", "universal-pathlib>=0.3.8", "starfix>=0.6.0,<0.7", diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index cbf6e2831..006725268 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -448,28 +448,100 @@ def _with_merged_records( own = original.schema.field(field.name).type if position < 0 or isinstance(own, pa.ExtensionType): continue - stored_record = stored_records.get(field.name) - incoming_record = recorded_type(field.metadata) - if stored_record is None and incoming_record is None: - continue - base = ( - stored_record - if stored_record is not None - else arrow_utils.normalize_to_large_types(stored.field(position).type) - ) - incoming = ( - incoming_record - if incoming_record is not None - else arrow_utils.normalize_to_large_types(own) + merged = _merged_record( + stored.field(position).type, stored_records.get(field.name), own, field ) + if merged is None: + continue written = written.set_column( - index, - with_recorded_type(field, merged_type(base, incoming)), - written.column(index), + index, with_recorded_type(field, merged), written.column(index) ) return written +def _merged_record( + stored_type: pa.DataType, + stored_record: pa.DataType | None, + own: pa.DataType, + written: "pa.Field[Any]", +) -> pa.DataType | None: + """The record a column has after an append, or ``None`` when it has none. + + A column recorded on either side (stored or incoming) is recorded as the merge of + its stored type (its record, else its stored type) and the incoming rows' type + (``merged_type``). + + Args: + stored_type: The column's type as Delta stores it. + stored_record: The column's stored record, or ``None``. + own: The incoming rows' own type for the column. + written: The incoming column as it is written (``to_delta_layout``). + + Returns: + The merged record, or ``None`` when neither side is recorded. + """ + incoming_record = recorded_type(written.metadata) + if stored_record is None and incoming_record is None: + return None + base = ( + stored_record + if stored_record is not None + else arrow_utils.normalize_to_large_types(stored_type) + ) + incoming = ( + incoming_record + if incoming_record is not None + else arrow_utils.normalize_to_large_types(own) + ) + return merged_type(base, incoming) + + +# Why Delta refuses names that differ only in case (ITL-1403). +_CASE_INSENSITIVE = ( + "Delta column names are case-insensitive, so a Delta table cannot hold both" +) + + +def _differ_only_in_case(names: list[str]) -> tuple[str, str] | None: + """The first two of ``names`` that differ only in case, or ``None``.""" + seen: dict[str, str] = {} + for name in names: + other = seen.setdefault(name.lower(), name) + if other != name: + return other, name + return None + + +def _nested_names_differing_in_case(arrow_type: pa.DataType) -> tuple[str, str] | None: + """Two field names of one struct inside ``arrow_type`` that differ only in case.""" + if isinstance(arrow_type, pa.ExtensionType): + return _nested_names_differing_in_case(arrow_type.storage_type) + if pa.types.is_struct(arrow_type): + found = _differ_only_in_case( + [arrow_type.field(i).name for i in range(arrow_type.num_fields)] + ) + if found is not None: + return found + for i in range(arrow_type.num_fields): + found = _nested_names_differing_in_case(arrow_type.field(i).type) + if found is not None: + return found + return None + + +def _case_reason(first: str, second: str, nested: bool = False) -> str: + where = "struct fields" if nested else "columns" + return f"{where} {first!r} and {second!r} differ only in case: {_CASE_INSENSITIVE}" + + +# Why a recorded column's record cannot change on Delta (ITL-1403). +_RECORD_CHANGE = ( + "the append would change the column's recorded Arrow type, and a recorded " + "column's type cannot change on a Delta table: deltalake refuses a commit that " + "changes a column's field metadata (deltalake 1.5 and later)" +) + + _EXTENSION_KEYS = (b"ARROW:extension:name", b"ARROW:extension:metadata") @@ -632,6 +704,74 @@ def _non_null_violation( return None +def _changed_record( + delta_table: deltalake.DeltaTable, rows: pa.Table +) -> tuple[str, str] | None: + """The first stored column whose record (or nested names) the append would change. + + deltalake (1.5 and later) refuses a commit that changes a column's field metadata, + and a recorded column's record is its field metadata: an append whose merged + record (``_merged_record``, what the commit would write) is not the stored one is + refused here, before anything is queued. An append that leaves the record as it + is, a column with no record on either side (a plain struct still evolves), and a + new column are not concerned. A struct evolution that would put two field names + differing only in case into one struct is refused too. + + Args: + delta_table: The loaded stored table. + rows: The rows to append, with their own types. + + Returns: + ``(column, reason)``, or ``None``. + """ + stored = _stored_arrow_schema(delta_table) + stored_metadata = {f.name: f.metadata for f in delta_table.schema().fields} + stored_records = { + name: recorded_type(metadata) for name, metadata in stored_metadata.items() + } + for field in rows.schema: + position = stored.get_field_index(field.name) + if position < 0: + continue + # A logical column's type is named in its field metadata: another logical + # type over the same storage type would change it. + stored_extension = stored_metadata[field.name].get("ARROW:extension:name") + incoming_extension = ( + field.type.extension_name + if isinstance(field.type, pa.ExtensionType) + else None + ) + if stored_extension != incoming_extension: + return field.name, ( + f"it is stored as logical type {stored_extension!r} and the rows hold " + f"{incoming_extension!r}: a column's field metadata cannot change on a " + "Delta table (deltalake 1.5 and later refuses such a commit)" + ) + if incoming_extension is not None: + continue + stored_type = stored.field(position).type + stored_record = stored_records.get(field.name) + merged = _merged_record( + stored_type, stored_record, field.type, written_field(field) + ) + if merged is not None and ( + stored_record is None + or not stored_record.equals(merged, check_metadata=True) + ): + return field.name, _RECORD_CHANGE + try: + evolved = merged_type( + arrow_utils.normalize_to_large_types(stored_type), + arrow_utils.normalize_to_large_types(field.type), + ) + except Exception: # noqa: BLE001 # a type change: the type check reports it + continue + nested = _nested_names_differing_in_case(evolved) + if nested is not None: + return field.name, _case_reason(*nested, nested=True) + return None + + def _append_refusal( delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: @@ -661,6 +801,13 @@ def _append_refusal( change = _column_change(held[field.name], field) if change is not None: return field.name, change + else: + clash = _differ_only_in_case([*held, field.name]) + if clash is not None: + return field.name, _case_reason(*clash) + changed = _changed_record(delta_table, rows) + if changed is not None: + return changed violation = _non_null_violation(held, rows) if violation is not None: name, omitted = violation @@ -831,6 +978,9 @@ def delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: Delta's reason (``Invalid data type for Delta Lake: Decimal256(40, 2)``), or ``None`` when Delta holds the column. """ + nested = _nested_names_differing_in_case(field.type) + if nested is not None: + return _case_reason(*nested, nested=True) if arrow_utils.holds_renamed_map(field.type): # The recorded type goes through Arrow IPC, which renames them (ITL-1334). return "a map's key and item fields read back as 'key' and 'value'" @@ -1626,10 +1776,21 @@ def require_storable(self, schema: pa.Schema) -> None: Args: schema: The Arrow schema of a table this database is to hold. + Two columns whose names differ only in case are refused too: Delta column + names are case-insensitive (ITL-1403). + Raises: UnstorableColumnError: For the first column Delta cannot hold, naming the column, its Arrow type and Delta's reason. """ + clash = _differ_only_in_case(schema.names) + if clash is not None: + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=clash[1], + arrow_type=schema.field(clash[1]).type, + reason=_case_reason(*clash), + ) for field in schema: reason = delta_unstorable_reason(field) if reason is not None: @@ -1640,6 +1801,31 @@ def require_storable(self, schema: pa.Schema) -> None: reason=reason, ) + def _refuse_case_clash_with_pending( + self, record_path: tuple[str, ...], schema: pa.Schema + ) -> None: + """Refuse a column whose name differs only in case from a queued one (ITL-1403). + + Checked before the schema handling, which would otherwise report the queued + and the new columns as a mismatch. A stored table's columns are checked by + ``_append_refusal``. + + Raises: + InputValidationError: Naming both columns. + """ + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is None: + return + queued = pending.schema.names + clash = _differ_only_in_case( + [*queued, *(n for n in schema.names if n not in queued)] + ) + if clash is not None: + raise InputValidationError( + f"Cannot add rows to {self._get_table_uri(record_path)!r}: column " + f"{clash[1]!r}: {_case_reason(*clash)}. Nothing was queued." + ) + def _refuse_unmergeable_append( self, record_path: tuple[str, ...], @@ -1875,6 +2061,7 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) + self._refuse_case_clash_with_pending(record_path, records.schema) self._refuse_untyped_null_columns(record_path, records.schema) # Step 2: Deduplicate within input table (keep last occurrence) diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 4fe75ba5d..ccacc5b7a 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 @@ -440,13 +439,13 @@ def test_the_step_leaves_anything_else_as_given( assert in_held_column_order(given, held) is given -@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +@pytest.mark.parametrize("database", ["in-memory"]) @pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) def test_names_differing_in_case_only_are_two_columns( tmp_path: Path, database: str, when: str ) -> None: - """The in-memory and Delta databases hold ``a`` and ``A`` apart; an append of them - in another order is matched by exact name.""" + """The in-memory database holds ``a`` and ``A`` apart; an append of them in another + order is matched by exact name. (Delta refuses them: below.)""" with open_database(database, tmp_path) as db: _add(db, _table_with_id(b"r1", [ID, "a", "A"]), flush=when == "after a flush") _add(db, _table_with_id(b"r2", ["A", ID, "a"])) @@ -459,6 +458,31 @@ def test_names_differing_in_case_only_are_two_columns( ] +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_delta_refuses_names_differing_only_in_case(tmp_path: Path, when: str) -> None: + """Delta column names are case-insensitive (deltalake 1.5.1 and later refuses + such a table): ``a`` and ``A`` in one table are refused before anything is + queued, in one batch and as a column added beside a held one (ITL-1403).""" + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match="differ only in case") as info: + _add(db, _table_with_id(b"r1", [ID, "a", "A"])) + assert info.value.column == "A" + _add(db, _table_with_id(b"r1", [ID, "a"]), flush=when == "after a flush") + with pytest.raises(InputValidationError, match="'a' and 'A' differ only in case"): + # ``merge``: a new column beside a pending batch is otherwise refused by the + # schema check before the name is looked at. + db.add_records( + PATH, + _table_with_id(b"r2", ["A", ID]), + record_id_column=ID, + schema_handling="merge", + ) + db.flush() + table = db.get_all_records(PATH, record_id_column=ID) + assert table is not None + assert table.select([ID, "a"]).to_pylist() == [{ID: b"r1", "a": 1}] + + def _table_with_id(rid: bytes, order: list[str]) -> pa.Table: columns = { ID: pa.array([rid], pa.large_binary()), @@ -825,12 +849,12 @@ def rows(n: int, pair: Any, order: list[str]) -> pa.Table: 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 + # Delta refuses another logical type where one is stored, before anything is + # queued: deltalake 1.5 and later refuses the commit (ITL-1403). Before, Delta + # took the rows and the table could no longer be read as one type + # (ITL-1371's family). + with pytest.raises(InputValidationError, match="logical type"): + second.add_records(PATH, permuted, record_id_column="rid", flush=True) 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_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index d37919f53..27327206c 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -304,7 +304,8 @@ def test_a_null_child_of_an_evolving_struct_appends( tmp_path: Path, appended: Any ) -> None: """Delta's MERGE panicked on a ``null`` child of a struct that gains a field - (pre-existing); the child is written as typed nulls of its stored type.""" + (pre-existing); the child is written as typed nulls of its stored type. Inside a + list (a recorded column) the evolution is refused instead (ITL-1403).""" stored_type = _struct(pa.field("a", I64)) in_list = pa.types.is_large_list(appended) db = DeltaTableDatabase(tmp_path) @@ -321,9 +322,21 @@ def test_a_null_child_of_an_evolving_struct_appends( flush=True, ) value = {"a": None, "b": 2} + if in_list: + # A list column is recorded, and its record would change: refused on Delta + # before anything is buffered (ITL-1403). + with pytest.raises(InputValidationError, match="recorded Arrow type"): + db.add_records( + PATH, + _rows([b"2"], x=(appended, [[value]])), + record_id_column="id", + flush=True, + ) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + return db.add_records( PATH, - _rows([b"2"], x=(appended, [[value]] if in_list else [value])), + _rows([b"2"], x=(appended, [value])), record_id_column="id", flush=True, ) diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 8948b9db8..842d37d1c 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -469,24 +469,23 @@ def test_new_struct_field(self, base: Path) -> None: {"a": 2, "b": 3}, ] - def test_new_struct_field_inside_a_list(self, base: Path) -> None: - """An append that adds a field to a struct inside a list column succeeds.""" + def test_new_struct_field_inside_a_list_is_refused(self, base: Path) -> None: + """An append that adds a field to a struct inside a list column would change + the list column's recorded type: refused before anything is buffered, the + stored rows unchanged (deltalake refuses such a commit; ITL-1403).""" db = DeltaTableDatabase(base_path=base) stored_type = pa.large_list(pa.struct([("a", pa.int64())])) append(db, rows([b"a"], pa.array([[{"a": 1}]], stored_type))) evolved = pa.large_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) - append(db, rows([b"b"], pa.array([[{"a": 2, "b": 3}]], evolved))) + with pytest.raises(InputValidationError, match="recorded Arrow type"): + append(db, rows([b"b"], pa.array([[{"a": 2, "b": 3}]], evolved))) back = DeltaTableDatabase(base_path=base).get_all_records( PATH, record_id_column="rid" ) assert back is not None - back = back.sort_by("rid") - assert back.schema.field("x").type == evolved - assert back.column("x").to_pylist() == [ - [{"a": 1, "b": None}], - [{"a": 2, "b": 3}], - ] + assert back.schema.field("x").type == stored_type + assert back.column("x").to_pylist() == [[{"a": 1}]] def test_missing_column(self, base): """An append that omits a stored column succeeds.""" diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index 87d368bd3..e13b369d8 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -449,14 +449,18 @@ def test_a_listed_column_prunes_files(self, tmp_path: Path) -> None: .read_all() ) text = "\n".join(str(row) for row in plan.to_pylist()) - assert "files_pruned=2, files_scanned=1" in text, text + # The scan is given only the file whose statistics can hold the value: the + # other two are pruned before it (deltalake 1.6 lists the files it scans). + assert text.count(".parquet") == 1, text + assert "file_groups={1 group:" in text, text class TestTablesCreatedElsewhere: def test_existing_table_without_the_property_is_unaltered( self, tmp_path: Path, capfd: pytest.CaptureFixture[str] ) -> None: - """A table created before ITL-1187 keeps no property and keeps warning.""" + """A table created before ITL-1187 keeps no property: delta-rs keeps statistics + for every column it can, and none for a binary one.""" deltalake.write_deltalake(str(tmp_path / "t"), rows(range(0, 10))) db = DeltaTableDatabase(tmp_path) capfd.readouterr() @@ -464,9 +468,14 @@ def test_existing_table_without_the_property_is_unaltered( db.add_records(PATH, rows(range(10, 20)), flush=True) db.add_records(PATH, rows(range(15, 30)), skip_duplicates=False, flush=True) - # The capture works: this table has no property, so delta-rs warns. - assert stats_warnings(capfd) != [] + # deltalake 1.6 no longer logs the binary-column warning (1.0.2 did); what + # the property was about stays: no min/max is kept for a binary column. assert configuration(tmp_path / "t") == {} + added = pa.table( + deltalake.DeltaTable(str(tmp_path / "t")).get_add_actions(flatten=True) + ) + assert "min.v" in added.column_names + assert not any(n.startswith("min.h") for n in added.column_names) assert stored_ids(db) == sorted(f"id{i}".encode() for i in range(30)) def test_plain_deltalake_appends_to_a_table_with_the_property( diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index 877b1b32f..f5cbe037b 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -3,9 +3,14 @@ Schema evolution is on by default: an append may add struct fields, omit some, or give them in another order. Delta's MERGE matches struct fields by position, so the rows are first given the stored struct layout by name (``_conformed_to_stored``), and a column -whose Arrow type is recorded has its record describe the merged column (``merged_type``), -which a read restores by name. Every read path, on a fresh database object, gives each -value under the name it was written with: never swapped, never dropped. +whose Arrow type is recorded keeps its record, which a read restores by name. Every read +path, on a fresh database object, gives each value under the name it was written with: +never swapped, never dropped. + +An append that would CHANGE a recorded column's record (a field added to a recorded +struct) is refused before anything is buffered: deltalake 1.5 and later refuses a commit +that changes a column's field metadata, and the record is field metadata (ITL-1403). A +struct with no record still gains fields, and a new column is still added. A ``null``-typed part with nothing stored at its path (a new struct field, the items of a new list) is refused naming the column and the path, before anything is buffered. @@ -88,19 +93,28 @@ def _rows(ids: list[bytes], **columns: tuple[list[Any], pa.DataType]) -> pa.Tabl [{"a": 3.0}], [{"a": 1.0, "b": 2}, {"a": 3.0, "b": None}], ), + "added, unrecorded": ( + _struct(("a", I64)), + [{"a": 1}], + _struct(("a", I64), ("c", I64)), + [{"a": 3, "c": 5}], + [{"a": 1, "c": None}, {"a": 3, "c": 5}], + ), +} + +# Appends that would change a recorded column's record: refused (ITL-1403). +RECORD_CHANGES: dict[str, tuple[Any, list[Any], Any, list[Any]]] = { "added, recorded": ( _struct(("a", F16)), [{"a": 1.0}], _struct(("a", F16), ("c", pa.list_(pa.int16(), 2))), [{"a": 3.0, "c": [5, 6]}], - [{"a": 1.0, "c": None}, {"a": 3.0, "c": [5, 6]}], ), "reordered and added, in a list": ( pa.large_list(_struct(("a", pa.uint8()), ("b", I64))), [[{"a": 1, "b": 2}]], pa.large_list(_struct(("c", I64), ("b", I64), ("a", pa.uint8()))), [[{"c": 9, "b": 4, "a": 3}]], - [[{"a": 1, "b": 2, "c": None}], [{"a": 3, "b": 4, "c": 9}]], ), } @@ -141,6 +155,61 @@ def test_an_evolved_struct_keeps_every_value_under_its_name( assert back.column(name).to_pylist() == expected, name +@pytest.mark.parametrize("flush", [True, False], ids=["flushed", "queued"]) +@pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) +def test_an_append_changing_a_recorded_type_is_refused_before_buffering( + tmp_path: pathlib.Path, case: str, flush: bool +) -> None: + first, first_values, appended, appended_values = RECORD_CHANGES[case] + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], k=([7], pa.int64()), x=(first_values, first)), + record_id_column="id", + flush=True, + ) + with pytest.raises( + InputValidationError, + match=r"column 'x': the append would change the column's recorded Arrow type", + ): + db.add_records( + PATH, + _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)), + record_id_column="id", + flush=flush, + ) + db.flush() # nothing was queued + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.column("id").to_pylist() == [b"1"] + assert back.column("x").to_pylist() == first_values + + +def test_a_new_column_is_still_added(tmp_path: pathlib.Path) -> None: + """A column the table does not hold changes no stored record: it is added.""" + recorded = _struct(("a", F16)) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=([{"a": 1.0}], recorded)), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _rows( + [b"2"], x=([{"a": 2.0}], recorded), z=([[1, 2]], pa.list_(pa.int16(), 2)) + ), + record_id_column="id", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + back = back.sort_by("id") + assert back.column("z").to_pylist() == [None, [1, 2]] + assert back.schema.field("z").type == pa.list_(pa.int16(), 2) + + def test_omitting_a_non_nullable_stored_field_is_refused( tmp_path: pathlib.Path, ) -> None: @@ -317,28 +386,31 @@ def test_adding_a_non_nullable_struct_field_is_refused( def test_adding_a_nullable_field_with_a_non_nullable_child_appends( tmp_path: pathlib.Path, ) -> None: - """The stored rows read the new field as null, so its child needs no value.""" + """The stored rows read the new field as null, so its child needs no value. + + An unrecorded struct (a recorded one cannot gain a field on Delta: ITL-1403). + """ added = pa.struct( - [pa.field("a", F16), pa.field("b", pa.struct([pa.field("c", F16, False)]))] + [pa.field("a", I64), pa.field("b", pa.struct([pa.field("c", I64, False)]))] ) db = DeltaTableDatabase(tmp_path) db.add_records( PATH, - _rows([b"1"], x=([{"a": 1.0}], _struct(("a", F16)))), + _rows([b"1"], x=([{"a": 1}], _struct(("a", I64)))), record_id_column="id", flush=True, ) db.add_records( PATH, - _rows([b"2"], x=([{"a": 2.0, "b": {"c": 3.0}}], added)), + _rows([b"2"], x=([{"a": 2, "b": {"c": 3}}], added)), record_id_column="id", flush=True, ) back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") assert back is not None assert back.sort_by("id").column("x").to_pylist() == [ - {"a": 1.0, "b": None}, - {"a": 2.0, "b": {"c": 3.0}}, + {"a": 1, "b": None}, + {"a": 2, "b": {"c": 3}}, ] @@ -458,3 +530,34 @@ def test_a_new_column_keeps_every_other_columns_type( for name in ("items", "u", "s", "p"): assert str(back.schema.field(name).type) == str(first.schema.field(name).type) assert back.sort_by("id").column("added").to_pylist() == [None, "a"] + + +def test_struct_fields_differing_only_in_case_are_refused( + tmp_path: pathlib.Path, +) -> None: + """Delta field names are case-insensitive at every depth (ITL-1403): a struct + holding ``x`` and ``X`` is refused, and so is an evolution that would add ``X`` + beside a stored ``x``, before anything is queued.""" + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match="'x' and 'X' differ only in case"): + db.add_records( + PATH, + _rows([b"1"], s=([{"x": 1, "X": 2}], _struct(("x", I64), ("X", I64)))), + record_id_column="id", + ) + db.add_records( + PATH, + _rows([b"1"], s=([{"x": 1}], _struct(("x", I64)))), + record_id_column="id", + flush=True, + ) + with pytest.raises(InputValidationError, match="'x' and 'X' differ only in case"): + db.add_records( + PATH, + _rows([b"2"], s=([{"X": 2}], _struct(("X", I64)))), + record_id_column="id", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.column("s").to_pylist() == [{"x": 1}] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index a3c298224..8adab576c 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1054,10 +1054,19 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map +included) cannot gain a field: the record is the column's field metadata, which Delta +(deltalake 1.5 and later) does not let a commit change, so such an append is refused, +naming the column, before anything is queued. A struct column without a record still +gains fields, and an append may still add a new column. Another logical type over a +stored logical column's storage type is refused the same way. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two -columns), never by position. Rows whose columns are the held table's columns in another +columns), never by position. Delta alone refuses two columns, or two fields of one +struct, whose names differ only in case: Delta column names are case-insensitive, so +such a table, or an append that would make one, is refused naming both, before anything +is queued. Rows whose columns are the held table's columns in another order, each field equal to the held one (the same type at every depth, the same logical type, the same field attributes), are put in the held order, whether the table was flushed in between or not. The in-memory database matches them to the rows still pending, diff --git a/uv.lock b/uv.lock index fe03d5d44..31a050573 100644 --- a/uv.lock +++ b/uv.lock @@ -793,20 +793,21 @@ wheels = [ [[package]] name = "deltalake" -version = "1.0.2" +version = "1.6.6" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "arro3-core" }, { name = "deprecated" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1e/c3/19cd8457243c41aa60562d28b66271ff958d896e3fd9373816d8fd781f1a/deltalake-1.0.2.tar.gz", hash = "sha256:fbe4cccde0af14c6e30b62cc3dd09e9a46777e8fd8e375ec809a6bf4edea756c", size = 5076074, upload-time = "2025-06-02T11:08:14.063Z" } +sdist = { url = "https://files.pythonhosted.org/packages/24/7e/817984d82cec757f6f3a3dbb84afcd85027e7ae02e0a354702c2127f6777/deltalake-1.6.6.tar.gz", hash = "sha256:91864d97adb429fa8b8748b4f68d69adab3d0417ffa9f100bdb85805890c997f", size = 5650031, upload-time = "2026-09-24T11:31:48.009Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/74/043f52f50cbda7f651d39465fb7c5a9e8880e9a332abbb4f64c4d0522306/deltalake-1.0.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e4f24cdbadaf8a4c32ae535a44b89d8bcafd5cb97897de33a4ec8609058a7d50", size = 41649942, upload-time = "2025-06-02T11:08:17.754Z" }, - { url = "https://files.pythonhosted.org/packages/f9/99/ced0f538deacdf0f1e78e28a14c30420d8df1c7d9ca30ff8f71a03a008a7/deltalake-1.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:43731c48657c16c1728c90270e5e7ae1f3fa1a5b6fb0cb0b55c88c5c8f23cc3f", size = 38590012, upload-time = "2025-06-02T11:09:07.48Z" }, - { url = "https://files.pythonhosted.org/packages/6f/f1/feee0df833eed13a27aafeedfac313c0b6bf7b0d712fa5892b1099a7a752/deltalake-1.0.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c921b47e4810a346650141dae30abc69564e57f26e00cce256f1837dd9c4b5fd", size = 40281750, upload-time = "2025-06-02T11:08:52.532Z" }, - { url = "https://files.pythonhosted.org/packages/dc/6f/4707d7511bd172f6c6504e87ea0bc43cdf7b5a4c85340ff61cee83170e37/deltalake-1.0.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59a3b403e5871d12920798d27f2b1e4b70f4e975381841066cb6733ccbc80071", size = 51273870, upload-time = "2025-06-02T11:08:10.194Z" }, - { url = "https://files.pythonhosted.org/packages/5c/2a/1dfc1f337f85d62141b4e70923b923d5faccbe666d4253b670c6d506d1bb/deltalake-1.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:67d3224ce7e569bbb6d5181f9ed2530b237a1cdc87f413e5ff0bc1227aab50d5", size = 40293966, upload-time = "2025-06-02T11:08:51.989Z" }, - { url = "https://files.pythonhosted.org/packages/78/a9/9014b804f947a505c21a6c0cbc87e2673cacb6cd82ac70be9a60f26a836b/deltalake-1.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:7a1606f535416d4a38ce554019f9fcad194aaec33d638328662b2de46af03059", size = 42567914, upload-time = "2025-06-02T11:23:49.313Z" }, + { url = "https://files.pythonhosted.org/packages/44/d5/fee90d565b32a166777a2c39ca7c77e1b8b8240a4ecfc9eeeabc2fb9fd63/deltalake-1.6.6-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:9b9883cc1236a44f62ed360abd1f39e564d892848b8a1aa5483871d12d23f74e", size = 50800766, upload-time = "2026-09-24T13:08:43.437Z" }, + { url = "https://files.pythonhosted.org/packages/bf/59/83e954337cb28173b5699a46f8350d8f76b15b20c6f055463b4d1ae343c0/deltalake-1.6.6-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:9e97c964ac768e104a58f147c3b41f281e9ed010825e02a3846d4a9c571a5d8a", size = 47072020, upload-time = "2026-09-24T12:58:11.229Z" }, + { url = "https://files.pythonhosted.org/packages/75/8f/07925ff4f54d8ce35f33961f27e224e3073b7286d9041b95f8e84549fe4a/deltalake-1.6.6-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:802db1ae734295c7b947bddd228b9e6b5df702846b085be91ad593840f72e36c", size = 52017042, upload-time = "2026-09-24T12:04:22.8Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e0/120f64cc7d3ccf4f28207e3bef566fcfcadab6887f8b18864eca16425d11/deltalake-1.6.6-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:25edf9373e6dd21f5db4792b1176a7b3e1780d2072e52e8d1433ba8f5e356c30", size = 50905121, upload-time = "2026-09-24T11:50:03.525Z" }, + { url = "https://files.pythonhosted.org/packages/23/46/35a59c6d24de9fdb3b68b41bc458ae9dc561a27b74e19d08137de1c8a695/deltalake-1.6.6-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:018e7b1d6a1098e365480cda810651b5570e38fad2236ea5f4a3e152457d8cc2", size = 50922944, upload-time = "2026-09-24T11:50:48.724Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ed/fd2cdf5edcea2ee90b75c5891f5a542b8564cf69bc92e174dab26b45819a/deltalake-1.6.6-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e2829c996dcf32bd6135e2eafe5b807f47ad40e84711c1453ee7b63f4548c034", size = 52029056, upload-time = "2026-09-24T12:03:08.689Z" }, + { url = "https://files.pythonhosted.org/packages/a4/a0/aa5d6643b85a9509b241e34df3b3e6720653279eb230e6025f7beee8eeb6/deltalake-1.6.6-cp310-abi3-win_amd64.whl", hash = "sha256:9a4d95a2c2ca70ef8b4f21e599850e2c21374bbde0fab3414388e5ef7d3f69e0", size = 55542042, upload-time = "2026-09-24T12:35:30.393Z" }, ] [[package]] @@ -2124,7 +2125,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "beartype", specifier = ">=0.21.0" }, - { name = "deltalake", specifier = ">=1.0.2" }, + { name = "deltalake", specifier = ">=1.6.6" }, { name = "gitpython", specifier = ">=3.1.45" }, { name = "ipywidgets", marker = "extra == 'all'", specifier = ">=8.1.7" }, { name = "ipywidgets", marker = "extra == 'ray'", specifier = ">=8.1.7" }, From 8b7c058c7d9625f8a0adf8aecfa799a7fe4e13df Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:02:01 -0800 Subject: [PATCH 06/23] docs(databases): several Delta writers, the commit cost, the design issue and changelog (ITL-1377) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1377.md | 21 ++++++++++++ docs/concepts/function-pods.md | 10 ++++++ docs/dev/design_issues/ITL-1377-CW1.md | 44 ++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 changelog.d/ITL-1377.md create mode 100644 docs/dev/design_issues/ITL-1377-CW1.md diff --git a/changelog.d/ITL-1377.md b/changelog.d/ITL-1377.md new file mode 100644 index 000000000..c144c54ea --- /dev/null +++ b/changelog.d/ITL-1377.md @@ -0,0 +1,21 @@ +### Changed + +- `DeltaTableDatabase` commits every write to an existing table as a MERGE (it appended a + batch of new ids before), so that a commit fails when another writer added rows after + the table was loaded. The flush then loads the table again and retries. A commit + re-reads the stored rows, so its cost grows with the table: commit in batches (a job + commits every 100 rows by default) rather than per row, above all to tables holding + large values. The stored rows, their values and types, and every hash, record id and + stored path are unchanged; only the order of the rows within one commit may differ. +- `DeltaTableDatabase` refuses a top-level column whose name holds a backtick + (`UnstorableColumnError`, before anything is queued), and an append to a table that + holds one: delta-rs cannot MERGE such a table. + +### Fixed + +- Two writers (two `DeltaTableDatabase` objects, or two processes) that committed the + same new record id to one Delta table both committed it, so the id was stored twice, + with `skip_duplicates` true or false. Now the later writer leaves the id the earlier + one stored: each id is stored once. Writers committing other ids all commit. +- Two writers creating the same Delta table at once could lose the earlier writer's + rows. The later create now fails and is retried as a MERGE. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 25460e959..c3d0d8215 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -860,6 +860,16 @@ object that has already loaded the table until its own next commit to that table a new `DeltaTableDatabase` object reads them at once. This was already the case before batching; only the re-reading per lookup is gone. +**Several writers.** Two jobs, or two processes, may write to the same +`DeltaTableDatabase` directory at once. Each record id is stored once. A commit to an +existing table is a Delta MERGE that inserts only the ids the table does not hold, and it +fails when another writer added rows after the table was loaded. The database then loads +the table again and retries, so the later writer finds the id stored and leaves it. That +MERGE reads the stored rows, so a commit takes longer as the table grows, and longer still +when the rows hold large values (arrays, images). Commit in batches (the default +`commit_every_rows=100` is fine). Avoid `commit_every_rows=1`, or a node run on its own, +against large tables. + [Pipelines and Jobs](pipeline-job.md) covers jobs in full: nodes, databases, pipeline blueprints, and saving and loading. diff --git a/docs/dev/design_issues/ITL-1377-CW1.md b/docs/dev/design_issues/ITL-1377-CW1.md new file mode 100644 index 000000000..8721b1467 --- /dev/null +++ b/docs/dev/design_issues/ITL-1377-CW1.md @@ -0,0 +1,44 @@ +## `src/orcapod/databases/delta_lake_databases.py` + +### CW1 — Two writers committing the same new record id to a Delta table both commit +**Status:** resolved +**Severity:** high +**Issue:** ITL-1377 + +`DeltaTableDatabase` decided which pending ids were new against the version it loaded for +a commit, and committed a batch of new ids by a plain WRITE (append). Another writer (a +second handle, or another process) could commit the same id between the load and the +append. A Delta append never conflicts with a concurrent append, so both commits +succeeded and the id was stored twice. This happened with `skip_duplicates` true and +false, in every `schema_handling` mode, and in any column order. Only a batch that took +the MERGE path (a stored id among its ids) was protected. Two writers creating a new +table at once had the same problem (ITL-1384): the later `mode="overwrite"` create +removed the earlier writer's rows. + +What deltalake offers was measured, not assumed: +- None of these makes an append conflict: `CommitProperties(max_commit_retries=0)`, + application transactions, an overwrite with a predicate on the binary id, or the + table-level options of `write_deltalake`. They all commit on top of the concurrent + commit. +- Only a MERGE fails (`CommitFailedError`) when another writer added rows after its load. + +**Fix:** every commit to an existing table is a MERGE that inserts only the ids the +table does not hold (`_commit_once`), with `streamed_exec=False`. +- **Retries.** On `CommitFailedError` the flush loads the table again, decides against + it and retries, at most `_COMMIT_ATTEMPTS` (200) times, with a random wait of at most + 0.5 s. After the last attempt it raises the conflict, as before. +- **Creating a table.** A new table is created with `mode="error"` and no commit retry, + so a create that lost the race fails and is retried as a MERGE. Without that, deltalake + 1.6 commits the losing create on top of the winner's. +- **Duplicates.** The later writer leaves an id the earlier one stored, and so stores + each id once. With `skip_duplicates=False` such an id is skipped without an error, as + an id already stored is today (ITL-1386). +- **Backticks.** delta-rs cannot MERGE a table with a top-level column whose name holds + a backtick, so such a column is refused (ITL-1375). + +**Cost.** delta-rs's insert-only MERGE reads every stored row in full: it is a full outer +join, and the binary id column has no file statistics, so no file is skipped. A commit +therefore costs time in proportion to the table's size. ITL-1403 (deltalake 1.6.6) made +that MERGE 2 to 8 times faster. ITL-1406 lists stored layouts that would let it skip +files. Commit in batches (a job's default of 100 rows per commit) rather than per row, +above all to tables holding large values. From c543f2a8c8ca163feef92b5f5640c2e168ff94e7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:26:37 -0800 Subject: [PATCH 07/23] fix(databases): refuse when added what deltalake 1.6 refuses at commit (ITL-1403 review) Review of PR 504 (seven findings, all reproduced): 1. A struct field differing in case from a QUEUED one is refused when added, on the merged pending and incoming type, at every depth. 2-3. The preflight computes the field metadata the commit would send, with the flush's own functions (to_delta_layout, _conformed_to_stored, _with_merged_records), and refuses a stored key given another value, as delta-rs try_merge_metadata does: the small-list record of an evolved struct, and a logical column's extension metadata (not only its name). 4. Delta folds case with Rust's to_lowercase; where Python's str.lower differs, the flush turns Delta's duplicate-name error into UnstorableColumnError once and drops the batch (every later flush would fail the same way). 5. An untyped null appended to a stored logical column claims no type: accepted. 6-7. Disclosed: an operator whose result type depends on its data now fails at the store (ITL-1410 will refuse it at the operator; kept in premise.py); a table written before deltalake 1.5.1 with 'a' and 'A' cannot be read on 1.6, and an append to it is refused when added, with nothing queued. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 60 ++++-- docs/dev/scripts/itl_1403/premise.py | 62 ++++++ docs/reference/database-types.md | 12 +- src/orcapod/databases/delta_lake_databases.py | 192 ++++++++++++++---- .../test_delta_refused_before_queueing.py | 178 ++++++++++++++++ tests/test_databases/type_matrix.py | 12 +- 6 files changed, 443 insertions(+), 73 deletions(-) create mode 100644 tests/test_databases/test_delta_refused_before_queueing.py diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index a8c732215..7c32c8d7f 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -1,24 +1,48 @@ +### Breaking changes and migration + +- A Delta table that holds two columns whose names differ only in case (`a` and `A`), + which `DeltaTableDatabase` stored before this release, can no longer be read with + deltalake 1.6 (`OrcapodDatabaseReadError`: Delta column names are case-insensitive). + An append to such a table is refused when the rows are added, naming the cause, with + nothing queued. Such a store is affected only if a table of it has two such names: + for example a function with output keys `a` and `A`, or a source with such columns. + Read it with Orcapod 0.3 (deltalake before 1.5.1) and write it again with distinct + names. + ### Changed - Orcapod now requires deltalake 1.6.6 or newer (was 1.0.2). A commit to a Delta table is faster with it: a one-row MERGE into a 10-million-row table took about 110 ms instead - of about 380 ms, and into a 5 GB table about 1.2 s instead of about 2.6 s. Tables written - by either version are read and appended to by the other, with identical rows, for every - stored table kind. New tables keep Delta protocol 1/2, with no table features. deltalake - 1.6 no longer logs `Skipping column ... because it's a binary field`. + of about 380 ms, and into a 5 GB table about 1.2 s instead of about 2.6 s. Every other + table written by either version is read and appended to by the other, with identical + rows, for every stored table kind. New tables keep Delta protocol 1/2, with no table + features. deltalake 1.6 no longer logs `Skipping column ... because it's a binary field`. - `DeltaTableDatabase` refuses two columns, or two fields of one struct, whose names differ only in case (`a` and `A`), before anything is queued - (`UnstorableColumnError`, or `InputValidationError` for a column added beside a held or - queued one). Delta column names are case-insensitive, and deltalake 1.5.1 and later - refuses such a table. The in-memory and connector databases still hold such names as - two columns. -- `DeltaTableDatabase` refuses an append that would change a stored column's recorded - Arrow type (`InputValidationError` naming the column, before anything is queued). This - covers a field added to a struct whose type is recorded: every list and map column, - and every struct holding an unsigned integer, a non-microsecond time type, `float16` - or a fixed-size type. It also covers another logical type over a stored logical - column's storage type. deltalake 1.5 and later does not let a commit change a column's - field metadata, and the record is field metadata. A struct column without a record - still gains fields, a field may still be omitted or reordered, and a new column may - still be added. No job reaches the refusal on the tables Orcapod's own nodes write: a - changed column type changes the table's path. + (`UnstorableColumnError`, or `InputValidationError` for a column or field added beside a + stored or queued one). Delta column names are case-insensitive, and deltalake 1.5.1 + and later refuses such a table. So a function job with output keys `a` and `A` now + stops at its first write, on the sync and the async path alike. Delta folds case as + Rust's `to_lowercase` does: for the few code points where Python's `str.lower` differs, + the refusal comes at the flush, once, as `UnstorableColumnError`, and the batch leaves + the queue. The in-memory and connector databases still hold such names as two columns. +- `DeltaTableDatabase` refuses an append that would change a stored column's field + metadata (`InputValidationError` naming the column, before anything is queued): + deltalake 1.5 and later refuses such a commit. Two cases: + - A column's recorded Arrow type: every list and map column, and every struct holding + an unsigned integer, a non-microsecond time type, `float16` or a fixed-size type. A + field added to such a struct changes it, in the small list form as in the large one, + and so does a change of nested nullability (a list's items becoming nullable). + - A logical column's identifier: another extension name, or the same name with other + extension metadata. + + Still accepted: a struct column without a record gaining fields, a field omitted or + reordered, a new column, and an untyped `null` column, which takes the stored type. + Tables Orcapod's own nodes write are not concerned: their column types are fixed by + their inputs' schemas, and a changed column type changes the table's path. The one + exception is an operator whose result type depends on its data rather than on its + input schemas, which is a bug of that operator. Example: a custom operator emitting + list items nullable only when a value exceeds 10, in an operator node that logs + (`CacheMode.LOG`). Such an operator now fails at the store when its result type + changes, instead of silently changing a table's recorded type (deltalake 1.0.2 stored + both). ITL-1410 is to refuse it earlier, at the operator. diff --git a/docs/dev/scripts/itl_1403/premise.py b/docs/dev/scripts/itl_1403/premise.py index f923fcf4c..8bed7b585 100644 --- a/docs/dev/scripts/itl_1403/premise.py +++ b/docs/dev/scripts/itl_1403/premise.py @@ -21,6 +21,15 @@ - ``struct_gains_field``: a source data column, a struct with a recorded type (``uint8``), gaining a field between the runs, through a cached source, a function pod, an operator that logs and a side-effect pod. +- ``operator_nested_nullability`` (the stated EXCEPTION, found by review): a custom + operator in a node that logs (``CacheMode.LOG``) whose result type depends on its + data, not on its input schemas: ``large_list`` with non-nullable items in one + run and nullable items in the next. Its declared and observed Python schemas are + equal and its cache path is the same, but the recorded type differs (nested + nullability is part of the record), so the second run fails at the store. On + deltalake 1.0.2 both runs were stored and the table's recorded type changed + silently. Such an operator is a bug of the operator (an operator's output schema is + fully determined by its inputs' schemas); ITL-1410 is to refuse it at the operator. usage: uv run python docs/dev/scripts/itl_1403/premise.py WORKDIR """ @@ -38,6 +47,8 @@ from orcapod import PipelineJob, function_pod from orcapod.core.operators import Join +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.sources import ArrowTableSource from orcapod.core.sources.cached_source import CachedSource from orcapod.databases import DeltaTableDatabase @@ -140,6 +151,50 @@ def _case(store: Path, first: Callable[[], None], second: Callable[[], None]) -> ) +class ShapeValues(UnaryOperator): + """Lists of one Python type whose items' Arrow nullability follows the values.""" + + def validate_unary_input(self, stream: Any) -> None: + pass + + def identity_structure(self) -> Any: + return ("itl1403-shape-values",) + + def unary_output_schema(self, stream: Any, **kwargs: Any) -> Any: + tags, _ = stream.output_schema(**kwargs) + values = pa.array([], type=pa.large_list(pa.field("item", pa.uint8()))) + _, data = ArrowTableStream(pa.table({"v": values})).output_schema(**kwargs) + return tags, data + + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns={"source": True, "system_tags": True}) + values = table["v"].to_pylist() + nullable = any(v > 10 for v in values) + shape = pa.large_list(pa.field("item", pa.uint8(), nullable=nullable)) + wrapped = pa.array([[v] for v in values], shape) + table = table.set_column(table.schema.get_field_index("v"), "v", wrapped) + return ArrowTableStream(table, tag_columns=stream.keys()[0]) + + +def _operator_job(store: Path, rerun: bool) -> None: + database = DeltaTableDatabase(store) + source = ArrowTableSource( + pa.table( + {"k": [3, 4] if rerun else [1, 2], "v": [11, 12] if rerun else [1, 2]} + ), + tag_columns=["k"], + tag_only_columns=True, + source_id="input", + record_id_columns=["k"], + ) + job = PipelineJob(name="premise-operator", database=database) + with job: + ShapeValues()(source, label="shape") + job.nodes["shape"].attach_databases(database, cache_mode=CacheMode.LOG) + job.run() + database.flush() + + def main(work: Path) -> None: results: dict[str, str] = {} @@ -245,6 +300,13 @@ def run_struct(extra: bool) -> Callable[[], None]: work / "struct_gains_field", run_struct(False), run_struct(True) ) + # The known exception: the second run is refused. + results["operator_nested_nullability (known exception)"] = _case( + work / "operator_nested_nullability", + lambda: _operator_job(work / "operator_nested_nullability", False), + lambda: _operator_job(work / "operator_nested_nullability", True), + ) + for name, outcome in results.items(): print(f"{name}: {outcome}") diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 88021bf30..e295ea606 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,11 +81,13 @@ would add a non-nullable struct field (the stored rows have no value for it) or struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field: the record is the column's field metadata, which Delta -(deltalake 1.5 and later) does not let a commit change, so such an append is refused, -naming the column, before anything is queued. A struct column without a record still -gains fields, and an append may still add a new column. Another logical type over a -stored logical column's storage type is refused the same way. +included) cannot gain a field, nor have a nested nullability change: the record is the +column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit +change, so such an append is refused, naming the column, before anything is queued. A +struct column without a record still gains fields, an append may still add a new column, +and an untyped `null` column takes the stored type. Another logical type over a stored +logical column (another extension name, or the same name with other extension metadata) +is refused the same way. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 006725268..3027e6558 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2,6 +2,7 @@ import logging import os +import re import sys from collections import defaultdict from collections.abc import Callable, Collection, Mapping @@ -41,6 +42,7 @@ written_field, ) from orcapod.databases.delta_statistics import statistics_configuration +from orcapod.logical_types.identifier import arrow_type_identifier from orcapod.databases.storage_utils import ( delta_to_pyarrow_dataset, is_cloud_uri, @@ -534,6 +536,21 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: return f"{where} {first!r} and {second!r} differ only in case: {_CASE_INSENSITIVE}" +# delta-rs reports two names equal under its case folding (Rust ``to_lowercase``). +_DUPLICATE_NAME = re.compile(r"Duplicate field name \(case-insensitive\): '([^']*)'") + + +def _duplicate_name_in(error: BaseException) -> str | None: + """The name delta-rs reports as a case-insensitive duplicate in ``error``'s chain.""" + seen: BaseException | None = error + while seen is not None: + match = _DUPLICATE_NAME.search(str(seen)) + if match is not None: + return match.group(1) + seen = seen.__cause__ or seen.__context__ + return None + + # Why a recorded column's record cannot change on Delta (ITL-1403). _RECORD_CHANGE = ( "the append would change the column's recorded Arrow type, and a recorded " @@ -704,18 +721,40 @@ def _non_null_violation( return None +def _metadata_sent(field: "pa.Field[Any]") -> dict[str, str]: + """The field metadata a commit sends to Delta for ``field``, as text. + + A logical column also carries its identifier as ``ARROW:extension:name`` and + ``ARROW:extension:metadata``, as the Arrow C interface hands it to delta-rs. + """ + sent = { + k.decode() if isinstance(k, bytes) else k: ( + v.decode(errors="replace") if isinstance(v, bytes) else v + ) + for k, v in (field.metadata or {}).items() + } + if isinstance(field.type, pa.ExtensionType): + identifier = arrow_type_identifier(field.type) + sent["ARROW:extension:name"] = identifier.name + sent["ARROW:extension:metadata"] = identifier.metadata.decode(errors="replace") + return sent + + def _changed_record( delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: - """The first stored column whose record (or nested names) the append would change. - - deltalake (1.5 and later) refuses a commit that changes a column's field metadata, - and a recorded column's record is its field metadata: an append whose merged - record (``_merged_record``, what the commit would write) is not the stored one is - refused here, before anything is queued. An append that leaves the record as it - is, a column with no record on either side (a plain struct still evolves), and a - new column are not concerned. A struct evolution that would put two field names - differing only in case into one struct is refused too. + """The first stored column whose field metadata (or nested names) the append changes. + + deltalake (1.5 and later) refuses a commit that gives a stored column's field + metadata key another value (delta-rs ``try_merge_metadata``). That metadata holds a + recorded column's record (``orcapod:arrow_type``) and a logical column's identifier + (``ARROW:extension:name`` and ``ARROW:extension:metadata``). The metadata the + commit would send is computed here by the functions the flush uses + (``to_delta_layout``, ``_conformed_to_stored``, ``_with_merged_records``), so the + rows are refused when they are added, never left to fail at every flush. A new key + is accepted, as Delta adds it; so is a bare ``null`` column, which sends no + metadata and takes the stored type. A struct evolution that would put two field + names differing only in case into one struct is refused too. Args: delta_table: The loaded stored table. @@ -725,43 +764,41 @@ def _changed_record( ``(column, reason)``, or ``None``. """ stored = _stored_arrow_schema(delta_table) - stored_metadata = {f.name: f.metadata for f in delta_table.schema().fields} - stored_records = { - name: recorded_type(metadata) for name, metadata in stored_metadata.items() - } + stored_metadata = {f.name: dict(f.metadata) for f in delta_table.schema().fields} + empty = rows.slice(0, 0) + # ``_conformed_to_stored`` refuses a struct the stored table cannot take, as the + # flush would (``InputValidationError``). + sent_schema = _with_merged_records( + delta_table, + empty, + _conformed_to_stored( + delta_table, to_delta_layout(empty), delta_table.table_uri + ), + ).schema for field in rows.schema: position = stored.get_field_index(field.name) - if position < 0: + if position < 0 or pa.types.is_null(field.type): continue - # A logical column's type is named in its field metadata: another logical - # type over the same storage type would change it. - stored_extension = stored_metadata[field.name].get("ARROW:extension:name") - incoming_extension = ( - field.type.extension_name - if isinstance(field.type, pa.ExtensionType) - else None - ) - if stored_extension != incoming_extension: - return field.name, ( - f"it is stored as logical type {stored_extension!r} and the rows hold " - f"{incoming_extension!r}: a column's field metadata cannot change on a " - "Delta table (deltalake 1.5 and later refuses such a commit)" - ) - if incoming_extension is not None: - continue - stored_type = stored.field(position).type - stored_record = stored_records.get(field.name) - merged = _merged_record( - stored_type, stored_record, field.type, written_field(field) - ) - if merged is not None and ( - stored_record is None - or not stored_record.equals(merged, check_metadata=True) - ): + held = stored_metadata[field.name] + sent = _metadata_sent(sent_schema.field(field.name)) + changed = sorted(k for k, v in sent.items() if k in held and held[k] != v) + if changed: + if any(k.startswith("ARROW:extension:") for k in changed): + return field.name, ( + "it is stored as logical type " + f"{held.get('ARROW:extension:name')!r} " + f"({held.get('ARROW:extension:metadata')!r}) and the rows hold " + f"{sent.get('ARROW:extension:name')!r} " + f"({sent.get('ARROW:extension:metadata')!r}): a column's field " + "metadata cannot change on a Delta table (deltalake 1.5 and later " + "refuses such a commit)" + ) return field.name, _RECORD_CHANGE + if isinstance(field.type, pa.ExtensionType): + continue try: evolved = merged_type( - arrow_utils.normalize_to_large_types(stored_type), + arrow_utils.normalize_to_large_types(stored.field(position).type), arrow_utils.normalize_to_large_types(field.type), ) except Exception: # noqa: BLE001 # a type change: the type check reports it @@ -1160,16 +1197,18 @@ def _database_error_to_raise(errors: list[Exception]) -> Exception | None: A ``OrcapodDatabaseReadError`` is preferred, because it is the error that fails a run whatever the orchestrator's ``error_policy``; failing that, an - ``InputValidationError`` from a refused append. + ``InputValidationError`` from a refused append, then an ``UnstorableColumnError`` + from a batch Delta refused for its column names (ITL-1403). Args: errors: The error of every batch that failed, in flush order. Returns: - The first ``OrcapodDatabaseReadError``, else the first ``InputValidationError``, or - ``None`` when no batch failed with a database error. + The first ``OrcapodDatabaseReadError``, else the first ``InputValidationError``, + else the first ``UnstorableColumnError``, or ``None`` when no batch failed with + a database error. """ - for kind in (OrcapodDatabaseReadError, InputValidationError): + for kind in (OrcapodDatabaseReadError, InputValidationError, UnstorableColumnError): chosen = next((e for e in errors if isinstance(e, kind)), None) if chosen is not None: return chosen @@ -1825,6 +1864,27 @@ def _refuse_case_clash_with_pending( f"Cannot add rows to {self._get_table_uri(record_path)!r}: column " f"{clash[1]!r}: {_case_reason(*clash)}. Nothing was queued." ) + # A struct queued and a struct added, merged as the flush would merge them, + # must not hold two field names differing only in case, at any depth. + for field in schema: + if field.name not in queued: + continue + try: + merged = merged_type( + arrow_utils.normalize_to_large_types( + pending.schema.field(field.name).type + ), + arrow_utils.normalize_to_large_types(field.type), + ) + except Exception: # noqa: BLE001 # a type change: the schema check reports it + continue + nested = _nested_names_differing_in_case(merged) + if nested is not None: + raise InputValidationError( + f"Cannot add rows to {self._get_table_uri(record_path)!r}: column " + f"{field.name!r}: {_case_reason(*nested, nested=True)}, once " + "merged with the rows queued. Nothing was queued." + ) def _refuse_unmergeable_append( self, @@ -1878,7 +1938,20 @@ def _refuse_unmergeable_append( if refusal is None: try: delta_table = self._get_delta_table(record_path) - except OrcapodDatabaseReadError: + except OrcapodDatabaseReadError as unreadable: + duplicate = _duplicate_name_in(unreadable) + if duplicate is not None: + # Written before deltalake 1.5.1, which no longer reads it: every + # flush would fail the same way, so nothing is queued (ITL-1403). + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: it holds columns whose " + f"names differ only in case (one is {duplicate!r}), which " + "deltalake 1.5.1 and later cannot read: " + f"{_CASE_INSENSITIVE} of them. Nothing was queued. Rebuild the " + "table with distinct names, using a deltalake version before " + "1.5.1 to read it." + ) from unreadable delta_table = None if delta_table is not None: refusal = _append_refusal(delta_table, records) @@ -2713,6 +2786,9 @@ def flush(self) -> None: InputValidationError: If no batch failed with ``OrcapodDatabaseReadError`` but a batch was refused by its stored table (dropped from the queue, above). Other failed batches are added to it as notes. + UnstorableColumnError: If neither of the above, but Delta refused a batch + for two names equal under its case folding (dropped from the queue: + every later flush would refuse it too; ITL-1403). RuntimeError: If batches failed with other errors only, naming the failed batches, with the first failure as its ``__cause__``. """ @@ -2911,6 +2987,32 @@ def _flush_by_key(self, record_key: str) -> None: logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e except Exception as e: + duplicate = _duplicate_name_in(e) + if duplicate is not None: + # delta-rs folds case with Rust's ``to_lowercase``, which agrees with + # Python's ``str.lower`` (the check when rows are added) except for a + # few code points of newer Unicode versions. Every later flush would + # fail the same way, so the batch leaves the queue and nothing of it + # was written (ITL-1403). + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + arrow_type: Any = next( + (f.type for f in pending_batch.schema if f.name == duplicate), + pa.null(), + ) + refused = UnstorableColumnError( + database_kind=type(self).__name__, + column=duplicate, + arrow_type=arrow_type, + reason=( + "Delta reports its name as equal to another column's or " + f"struct field's under its case folding: {_CASE_INSENSITIVE}. " + f"The {pending_batch.num_rows} rows queued for table " + f"{record_key!r} were not written and are no longer queued" + ), + ) + logger.error(f"Refused batch for {record_key}: {refused}") + raise refused from e logger.error(f"Error flushing batch for {record_key}: {e}") # Put the tables back in the pending queue self._pending_batches[record_key] = pending_batch diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py new file mode 100644 index 000000000..1132c674d --- /dev/null +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -0,0 +1,178 @@ +"""What deltalake 1.6 refuses at commit, a ``DeltaTableDatabase`` refuses when rows are added. + +A flush that fails and puts its rows back in the queue fails at every later flush too. +So each case deltalake 1.5+ refuses is refused when the rows are added, with nothing +queued (ITL-1403, review of PR 504). The cases: + +- two struct fields differing only in case, one queued and one added; +- a recorded column whose record the append would change, in the small list form + (``pa.list_``) as in the large one; +- a logical column whose identifier (extension name AND metadata) would change; +- a stored table written before deltalake 1.5.1 with two names differing only in case, + which deltalake 1.6 cannot read; +- names equal only under Delta's case folding, which Python's ``str.lower`` does not + fold alike: refused at the flush, once, and the rows leave the queue. + +A bare ``null`` column appended to a stored logical column claims no type and is +stored. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, cast + +import deltalake +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InputValidationError, UnstorableColumnError + +PATH = ("t",) + + +def _rows(rid: bytes, **columns: Any) -> pa.Table: + return pa.table({"rid": pa.array([rid], pa.large_binary()), **columns}) + + +def _add(db: DeltaTableDatabase, table: pa.Table, **kwargs: Any) -> None: + db.add_records(PATH, table, record_id_column="rid", **kwargs) + + +def _stored_ids(root: Path) -> list[bytes]: + table = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="rid") + assert table is not None + return sorted(cast(list[bytes], table.column("rid").to_pylist())) + + +def test_a_struct_field_differing_in_case_from_a_queued_one(tmp_path: Path) -> None: + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", s=pa.array([{"x": 1}]))) + with pytest.raises(InputValidationError, match="'x' and 'X' differ only in case"): + _add(db, _rows(b"2", s=pa.array([{"X": 2}])), schema_handling="merge") + db.flush() # the first batch is intact and commits + assert _stored_ids(tmp_path) == [b"1"] + + +@pytest.mark.parametrize( + "make_list", [pa.list_, pa.large_list], ids=["list", "large_list"] +) +def test_a_recorded_list_of_structs_cannot_evolve( + tmp_path: Path, make_list: Any +) -> None: + db = DeltaTableDatabase(tmp_path) + _add( + db, + _rows( + b"1", x=pa.array([[{"a": 1}]], make_list(pa.struct([("a", pa.int64())]))) + ), + flush=True, + ) + evolved = make_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) + with pytest.raises(InputValidationError, match="recorded Arrow type"): + _add(db, _rows(b"2", x=pa.array([[{"a": 2, "b": 3}]], evolved))) + db.flush() # nothing was queued + assert _stored_ids(tmp_path) == [b"1"] + + +class _Unit(pa.ExtensionType): + def __init__(self, serial: bytes = b"x") -> None: + self.serial = serial + super().__init__(pa.int64(), "itl1403.review.unit") + + def __arrow_ext_serialize__(self) -> bytes: + return self.serial + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> "_Unit": + return cls(serialized) + + +@pytest.fixture +def unit_type() -> Any: + pa.register_extension_type(_Unit()) # pyright: ignore[reportArgumentType] # pyarrow's stub names only PyExtensionType; any ExtensionType registers + yield _Unit + pa.unregister_extension_type("itl1403.review.unit") + + +def test_a_logical_column_with_other_extension_metadata( + tmp_path: Path, unit_type: Any +) -> None: + """The same extension name and storage, other metadata: another logical type.""" + + def unit(value: int, serial: bytes) -> Any: + return pa.ExtensionArray.from_storage( + unit_type(serial), pa.array([value], pa.int64()) + ) + + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", x=unit(1, b"x")), flush=True) + with pytest.raises( + InputValidationError, match="logical type 'itl1403.review.unit'" + ): + _add(db, _rows(b"2", x=unit(2, b"y"))) + _add(db, _rows(b"3", x=unit(3, b"x")), flush=True) # the same identifier appends + assert _stored_ids(tmp_path) == [b"1", b"3"] + + +def test_a_bare_null_appended_to_a_logical_column_is_stored(tmp_path: Path) -> None: + converter = get_default_context().type_converter + logical = converter.python_dicts_to_arrow_table( + [{"x": Path("/a")}], python_schema={"x": Path | None} + ) + first = _rows(b"1").append_column(logical.schema.field("x"), logical.column("x")) + db = DeltaTableDatabase(tmp_path) + _add(db, first, flush=True) + _add(db, _rows(b"2", x=pa.nulls(1)), flush=True) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert back is not None + assert back.schema.field("x").type == logical.schema.field("x").type + assert back.sort_by("rid").column("x").to_pylist() == ["/a", None] + + +def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( + tmp_path: Path, +) -> None: + """A table with ``a`` and ``A``, as deltalake before 1.5.1 wrote it: an append of + ``a`` alone is refused when added, with nothing queued, not at every flush.""" + deltalake.write_deltalake( + str(tmp_path / "t"), + pa.table( + {"__record_id": pa.array([b"1"], pa.large_binary()), "a": [1], "b": [2]} + ), + ) + # Rename ``b`` to ``A`` in the log's schema: the table deltalake 1.0.2 would write. + log = tmp_path / "t" / "_delta_log" / "00000000000000000000.json" + lines = [json.loads(line) for line in log.read_text().splitlines()] + for action in lines: + if "metaData" in action: + schema = json.loads(action["metaData"]["schemaString"]) + schema["fields"][2]["name"] = "A" + action["metaData"]["schemaString"] = json.dumps(schema) + log.write_text("\n".join(json.dumps(action) for action in lines) + "\n") + + db = DeltaTableDatabase(tmp_path) + with pytest.raises( + InputValidationError, match="deltalake 1.5.1 and later cannot read" + ): + _add(db, _rows(b"2", a=pa.array([3]))) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + + +def test_names_folded_alike_only_by_delta_are_refused_once(tmp_path: Path) -> None: + """U+1C89 and U+1C8A: Delta's folding (Rust ``to_lowercase``) makes them one name, + Python's ``str.lower`` (3.12) does not. Whichever check sees it first refuses it + with ``UnstorableColumnError``, and nothing stays queued.""" + first, second = "Ᲊ", "ᲊ" + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError): + _add( + db, _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}), flush=True + ) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + assert not (tmp_path / "t" / "_delta_log").exists() diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 8adab576c..041417959 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1056,11 +1056,13 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field: the record is the column's field metadata, which Delta -(deltalake 1.5 and later) does not let a commit change, so such an append is refused, -naming the column, before anything is queued. A struct column without a record still -gains fields, and an append may still add a new column. Another logical type over a -stored logical column's storage type is refused the same way. +included) cannot gain a field, nor have a nested nullability change: the record is the +column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit +change, so such an append is refused, naming the column, before anything is queued. A +struct column without a record still gains fields, an append may still add a new column, +and an untyped `null` column takes the stored type. Another logical type over a stored +logical column (another extension name, or the same name with other extension metadata) +is refused the same way. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one From 646b10bffd4cd10717d53332824170bb2c0a678b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:27:50 -0800 Subject: [PATCH 08/23] test(databases): a storage-typed column carrying another extension name is refused when added (ITL-1403) Co-Authored-By: Claude Opus 5.5 --- .../test_delta_refused_before_queueing.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 1132c674d..466c17cbf 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -176,3 +176,26 @@ def test_names_folded_alike_only_by_delta_are_refused_once(tmp_path: Path) -> No assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() assert not (tmp_path / "t" / "_delta_log").exists() + + +def test_a_storage_typed_column_carrying_another_extension_name(tmp_path: Path) -> None: + """A logical identity given as ``ARROW:extension:*`` field metadata on a storage + type is compared as an extension type's is: another name is refused when added.""" + + def rows(rid: bytes, name: str) -> pa.Table: + field = pa.field( + "x", + pa.int64(), + metadata={"ARROW:extension:name": name, "ARROW:extension:metadata": ""}, + ) + return pa.Table.from_arrays( + [pa.array([rid], pa.large_binary()), pa.array([1])], + schema=pa.schema([pa.field("rid", pa.large_binary()), field]), + ) + + db = DeltaTableDatabase(tmp_path) + _add(db, rows(b"1", "itl1403.one"), flush=True) + with pytest.raises(InputValidationError, match="'itl1403.two'"): + _add(db, rows(b"2", "itl1403.two")) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + assert _stored_ids(tmp_path) == [b"1"] From 2960b633e6ea3eb895b63a525b016cfda13fe62b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:35:04 -0800 Subject: [PATCH 09/23] test(databases): every review finding of PR 504 has a test, its class parametrized (ITL-1403) Co-Authored-By: Claude Opus 5.5 --- .../test_delta_refused_before_queueing.py | 201 +++++++++++++----- .../test_delta_refusals_in_jobs.py | 113 ++++++++++ 2 files changed, 266 insertions(+), 48 deletions(-) create mode 100644 tests/test_pipeline/test_delta_refusals_in_jobs.py diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 466c17cbf..354c4f4b7 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -29,7 +29,11 @@ from orcapod.contexts import get_default_context from orcapod.databases import DeltaTableDatabase -from orcapod.errors import InputValidationError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) PATH = ("t",) @@ -48,32 +52,76 @@ def _stored_ids(root: Path) -> list[bytes]: return sorted(cast(list[bytes], table.column("rid").to_pylist())) -def test_a_struct_field_differing_in_case_from_a_queued_one(tmp_path: Path) -> None: +def _struct(name: str, value: int) -> Any: + return pa.array([{name: value}]) + + +# (queued, added): two names differing only in case at each depth, in both orders. +NESTED_CASE_CLASHES: dict[str, tuple[Any, Any]] = { + "top struct, lower first": (_struct("x", 1), _struct("X", 2)), + "top struct, upper first": (_struct("X", 1), _struct("x", 2)), + "struct in a struct": ( + pa.array([{"t": {"x": 1}}]), + pa.array([{"t": {"X": 2}}]), + ), + "struct in a list": ( + pa.array([[{"x": 1}]], pa.large_list(pa.struct([("x", pa.int64())]))), + pa.array([[{"X": 2}]], pa.large_list(pa.struct([("X", pa.int64())]))), + ), +} + + +@pytest.mark.parametrize("case", sorted(NESTED_CASE_CLASHES)) +def test_a_struct_field_differing_in_case_from_a_queued_one( + tmp_path: Path, case: str +) -> None: + """Review of PR 504, finding 1 (and CodeRabbit): checked on the merged type.""" + queued, added = NESTED_CASE_CLASHES[case] db = DeltaTableDatabase(tmp_path) - _add(db, _rows(b"1", s=pa.array([{"x": 1}]))) - with pytest.raises(InputValidationError, match="'x' and 'X' differ only in case"): - _add(db, _rows(b"2", s=pa.array([{"X": 2}])), schema_handling="merge") + _add(db, _rows(b"1", s=queued)) + with pytest.raises(InputValidationError, match="differ only in case"): + _add(db, _rows(b"2", s=added), schema_handling="merge") db.flush() # the first batch is intact and commits assert _stored_ids(tmp_path) == [b"1"] -@pytest.mark.parametrize( - "make_list", [pa.list_, pa.large_list], ids=["list", "large_list"] -) -def test_a_recorded_list_of_structs_cannot_evolve( - tmp_path: Path, make_list: Any -) -> None: +def _list_of_structs(make_list: Any, *names: str) -> Any: + return make_list(pa.struct([(n, pa.int64()) for n in names])) + + +# (stored, appended): an append that changes a recorded column's record. +RECORD_CHANGES: dict[str, tuple[Any, Any]] = { + "list of structs gains a field": ( + pa.array([[{"a": 1}]], _list_of_structs(pa.list_, "a")), + pa.array([[{"a": 2, "b": 3}]], _list_of_structs(pa.list_, "a", "b")), + ), + "large list of structs gains a field": ( + pa.array([[{"a": 1}]], _list_of_structs(pa.large_list, "a")), + pa.array([[{"a": 2, "b": 3}]], _list_of_structs(pa.large_list, "a", "b")), + ), + "struct holding uint8 gains a field": ( + pa.array([{"a": 1}], pa.struct([("a", pa.uint8())])), + pa.array([{"a": 2, "b": 3}], pa.struct([("a", pa.uint8()), ("b", pa.int64())])), + ), + "list items become nullable": ( + pa.array([[1]], pa.large_list(pa.field("item", pa.uint8(), nullable=False))), + pa.array([[2]], pa.large_list(pa.field("item", pa.uint8(), nullable=True))), + ), + "struct child becomes nullable": ( + pa.array([{"a": 1}], pa.struct([pa.field("a", pa.uint8(), nullable=False)])), + pa.array([{"a": 2}], pa.struct([pa.field("a", pa.uint8(), nullable=True)])), + ), +} + + +@pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) +def test_a_recorded_column_whose_record_would_change(tmp_path: Path, case: str) -> None: + """Review of PR 504, findings 2 and 6: what the commit would send is compared.""" + stored, appended = RECORD_CHANGES[case] db = DeltaTableDatabase(tmp_path) - _add( - db, - _rows( - b"1", x=pa.array([[{"a": 1}]], make_list(pa.struct([("a", pa.int64())]))) - ), - flush=True, - ) - evolved = make_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) + _add(db, _rows(b"1", x=stored), flush=True) with pytest.raises(InputValidationError, match="recorded Arrow type"): - _add(db, _rows(b"2", x=pa.array([[{"a": 2, "b": 3}]], evolved))) + _add(db, _rows(b"2", x=appended)) db.flush() # nothing was queued assert _stored_ids(tmp_path) == [b"1"] @@ -98,10 +146,16 @@ def unit_type() -> Any: pa.unregister_extension_type("itl1403.review.unit") +@pytest.mark.parametrize( + ("first", "second"), + [(b"x", b"y"), (b"", b"y"), (b"x", b"")], + ids=["other metadata", "metadata added", "metadata dropped"], +) def test_a_logical_column_with_other_extension_metadata( - tmp_path: Path, unit_type: Any + tmp_path: Path, unit_type: Any, first: bytes, second: bytes ) -> None: - """The same extension name and storage, other metadata: another logical type.""" + """Review of PR 504, finding 3 (and CodeRabbit): the same extension name and + storage with other metadata is another logical type.""" def unit(value: int, serial: bytes) -> Any: return pa.ExtensionArray.from_storage( @@ -109,43 +163,55 @@ def unit(value: int, serial: bytes) -> Any: ) db = DeltaTableDatabase(tmp_path) - _add(db, _rows(b"1", x=unit(1, b"x")), flush=True) + _add(db, _rows(b"1", x=unit(1, first)), flush=True) with pytest.raises( InputValidationError, match="logical type 'itl1403.review.unit'" ): - _add(db, _rows(b"2", x=unit(2, b"y"))) - _add(db, _rows(b"3", x=unit(3, b"x")), flush=True) # the same identifier appends + _add(db, _rows(b"2", x=unit(2, second))) + _add(db, _rows(b"3", x=unit(3, first)), flush=True) # the same identifier appends assert _stored_ids(tmp_path) == [b"1", b"3"] -def test_a_bare_null_appended_to_a_logical_column_is_stored(tmp_path: Path) -> None: +def _path_column() -> Any: converter = get_default_context().type_converter - logical = converter.python_dicts_to_arrow_table( + table = converter.python_dicts_to_arrow_table( [{"x": Path("/a")}], python_schema={"x": Path | None} ) - first = _rows(b"1").append_column(logical.schema.field("x"), logical.column("x")) + return table.schema.field("x"), table.column("x"), "/a" + + +def _unit_column() -> Any: + array = pa.ExtensionArray.from_storage(_Unit(b"x"), pa.array([7], pa.int64())) + return pa.field("x", array.type), array, 7 + + +@pytest.mark.parametrize( + "make", [_path_column, _unit_column], ids=["orcapod.path", "extension"] +) +def test_a_bare_null_appended_to_a_logical_column_is_stored( + tmp_path: Path, unit_type: Any, make: Any +) -> None: + """Review of PR 504, finding 5 (and CodeRabbit): a bare null claims no type.""" + field, column, value = make() db = DeltaTableDatabase(tmp_path) - _add(db, first, flush=True) + _add(db, _rows(b"1").append_column(field, column), flush=True) _add(db, _rows(b"2", x=pa.nulls(1)), flush=True) back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") assert back is not None - assert back.schema.field("x").type == logical.schema.field("x").type - assert back.sort_by("rid").column("x").to_pylist() == ["/a", None] + assert back.schema.field("x").type == field.type + assert back.sort_by("rid").column("x").to_pylist() == [value, None] -def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( - tmp_path: Path, -) -> None: - """A table with ``a`` and ``A``, as deltalake before 1.5.1 wrote it: an append of - ``a`` alone is refused when added, with nothing queued, not at every flush.""" +def _legacy_case_only_table(root: Path) -> None: + """A table with ``a`` and ``A``, as deltalake before 1.5.1 wrote it.""" deltalake.write_deltalake( - str(tmp_path / "t"), + str(root / "t"), pa.table( {"__record_id": pa.array([b"1"], pa.large_binary()), "a": [1], "b": [2]} ), ) - # Rename ``b`` to ``A`` in the log's schema: the table deltalake 1.0.2 would write. - log = tmp_path / "t" / "_delta_log" / "00000000000000000000.json" + # Rename ``b`` to ``A`` in the log's schema (deltalake 1.6 cannot write it). + log = root / "t" / "_delta_log" / "00000000000000000000.json" lines = [json.loads(line) for line in log.read_text().splitlines()] for action in lines: if "metaData" in action: @@ -154,25 +220,64 @@ def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( action["metaData"]["schemaString"] = json.dumps(schema) log.write_text("\n".join(json.dumps(action) for action in lines) + "\n") + +def test_a_stored_table_with_case_only_names_cannot_be_read(tmp_path: Path) -> None: + """Review of PR 504, finding 7, the stated limit: deltalake 1.6 reads no such + table (the release note says so).""" + _legacy_case_only_table(tmp_path) + with pytest.raises(OrcapodDatabaseReadError): + DeltaTableDatabase(tmp_path).get_all_records(PATH) + + +@pytest.mark.parametrize( + "columns", + [{"a": [3]}, {"b": [3]}, {"a": [3], "c": [4]}], + ids=["a held name", "a new name", "a held and a new name"], +) +def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( + tmp_path: Path, columns: dict[str, list[int]] +) -> None: + """Review of PR 504, finding 7: an append is refused when added, with nothing + queued, never left to fail at every flush.""" + _legacy_case_only_table(tmp_path) db = DeltaTableDatabase(tmp_path) with pytest.raises( InputValidationError, match="deltalake 1.5.1 and later cannot read" ): - _add(db, _rows(b"2", a=pa.array([3]))) + _add(db, _rows(b"2", **{k: pa.array(v) for k, v in columns.items()})) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() -def test_names_folded_alike_only_by_delta_are_refused_once(tmp_path: Path) -> None: - """U+1C89 and U+1C8A: Delta's folding (Rust ``to_lowercase``) makes them one name, - Python's ``str.lower`` (3.12) does not. Whichever check sees it first refuses it - with ``UnstorableColumnError``, and nothing stays queued.""" - first, second = "Ᲊ", "ᲊ" +# Pairs Delta's case folding (Rust ``to_lowercase``) makes one name and Python 3.12's +# ``str.lower`` does not (found by the review of PR 504, finding 4). +RUST_ONLY_FOLDS = [ + ("\u1c89", "\u1c8a"), + ("\ua7cb", "\u0264"), + ("\ua7cc", "\ua7cd"), + ("\ua7da", "\ua7db"), + ("\ua7ce", "\ua7cf"), + ("\U00016ea0", "\U00016ebb"), +] + + +@pytest.mark.parametrize("nested", [False, True], ids=["columns", "struct fields"]) +@pytest.mark.parametrize( + "pair", RUST_ONLY_FOLDS, ids=[ascii(a) for a, _ in RUST_ONLY_FOLDS] +) +def test_names_folded_alike_only_by_delta_are_refused_once( + tmp_path: Path, pair: tuple[str, str], nested: bool +) -> None: + """Whichever check sees it first (``str.lower`` when added, Delta's error at the + flush) refuses it with ``UnstorableColumnError``, and nothing stays queued.""" + first, second = pair + if nested: + rows = _rows(b"1", s=pa.array([{first: 1, second: 2}])) + else: + rows = _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}) db = DeltaTableDatabase(tmp_path) with pytest.raises(UnstorableColumnError): - _add( - db, _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}), flush=True - ) + _add(db, rows, flush=True) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() assert not (tmp_path / "t" / "_delta_log").exists() diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py new file mode 100644 index 000000000..b98c8b886 --- /dev/null +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -0,0 +1,113 @@ +"""Jobs that reach a ``DeltaTableDatabase`` refusal of deltalake 1.5+ (ITL-1403). + +Pins the behaviour disclosed in the review of PR 504, so that a change to it is noticed: + +- finding 6: an operator whose result TYPE depends on its data (list items nullable only + when a value exceeds 10) in an operator node that logs (``CacheMode.LOG``): the run + whose result type differs from the stored one fails at the store, instead of + silently changing the table's recorded type. Such an operator is a bug of the + operator; ITL-1410 is to refuse it at the operator. +- a function with output keys ``a`` and ``A`` (legal before) stops at its first write: + Delta column names are case-insensitive. + +Both on the sync and the async orchestrator. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import OrcapodDatabaseWriteError, UnstorableColumnError +from orcapod.types import CacheMode + + +class _ItemNullabilityFromValues(UnaryOperator): + """Lists whose items' Arrow nullability follows the values (a buggy operator).""" + + def validate_unary_input(self, stream: Any) -> None: + pass + + def identity_structure(self) -> Any: + return ("itl1403-item-nullability-from-values",) + + def unary_output_schema(self, stream: Any, **kwargs: Any) -> Any: + tags, _ = stream.output_schema(**kwargs) + values = pa.array([], type=pa.large_list(pa.field("item", pa.uint8()))) + _, data = ArrowTableStream(pa.table({"v": values})).output_schema(**kwargs) + return tags, data + + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns={"source": True, "system_tags": True}) + values = table["v"].to_pylist() + nullable = any(v > 10 for v in values) + shape = pa.large_list(pa.field("item", pa.uint8(), nullable=nullable)) + wrapped = pa.array([[v] for v in values], shape) + table = table.set_column(table.schema.get_field_index("v"), "v", wrapped) + return ArrowTableStream(table, tag_columns=stream.keys()[0]) + + +def _source(keys: list[int], values: list[int]) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"k": keys, "v": values}), + tag_columns=["k"], + tag_only_columns=True, + source_id="input", + record_id_columns=["k"], + ) + + +def _run(job: PipelineJob, use_async: bool) -> None: + if use_async: + asyncio.run(job.run_async()) + else: + job.run() + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_an_operator_whose_result_type_follows_its_data_fails_at_the_store( + tmp_path: Path, use_async: bool +) -> None: + def run(keys: list[int], values: list[int]) -> None: + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1403", database=database) + with job: + _ItemNullabilityFromValues()(_source(keys, values), label="shape") + job.nodes["shape"].attach_databases(database, cache_mode=CacheMode.LOG) + _run(job, use_async) + database.flush() + + run([1, 2], [1, 2]) # items non-nullable: stored + with pytest.raises(OrcapodDatabaseWriteError) as info: + run([3, 4], [11, 12]) # items nullable: the recorded type would change + assert "recorded Arrow type" in str( + info.value.__cause__ + ) or "recorded Arrow type" in str(info.value) + + +@function_pod(output_keys=["a", "A"]) +def _pair(v: int | None) -> tuple[int, int]: + return v or 0, (v or 0) + 10 + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_a_function_with_output_keys_differing_in_case_stops( + tmp_path: Path, use_async: bool +) -> None: + # Refused when the job attaches the database to the node, before anything runs. + with pytest.raises(UnstorableColumnError, match="differ only in case"): + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1403", database=database) + with job: + _pair.pod(_source([1, 2], [1, 2]), label="fn") + _run(job, use_async) + assert not (tmp_path / "itl1403").exists() From 6ba68ce4805d14814ac2e489b6286c1e54b6f2fe Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:54:33 -0800 Subject: [PATCH 10/23] fix(databases): refuse only what the commit would refuse; second review of PR 504 (ITL-1403) N2: a record or logical identifier that decodes to the stored one is sent as stored (Delta compares the strings); a real change is refused only on a route that sends it: a MERGE that evolves the schema, or an append (the flush's own _stores_as_is, and no stored id among the rows). A MERGE without schema evolution keeps the stored schema and commits, as main did. N3: a null column carrying a logical identifier the stored type reads is written under the stored identifier; any other is checked like any column. N4: names are checked against the queued rows after duplicates are skipped. N5: the flush backstop names the batch's own field, also with a quote in it. N1: the dangling pipeline records after a dropped result batch are ITL-1412's; a strict xfail test names it, sync and async. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 234 +++++++++++++++--- .../test_delta_refused_before_queueing.py | 212 ++++++++++++++++ .../test_dropped_result_batch.py | 62 +++++ 3 files changed, 478 insertions(+), 30 deletions(-) create mode 100644 tests/test_pipeline/test_dropped_result_batch.py diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 3027e6558..149debef4 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -53,6 +53,10 @@ if TYPE_CHECKING: import deltalake + + from orcapod.logical_types.protocols import ( + TypeConverterProtocol as LogicalTypeConverterProtocol, + ) import polars as pl import pyarrow as pa import pyarrow.compute as pc @@ -442,25 +446,96 @@ def _with_merged_records( ``written`` with the merged records. """ stored = _stored_arrow_schema(delta_table) - stored_records = { - f.name: recorded_type(f.metadata) for f in delta_table.schema().fields - } + stored_metadata = {f.name: dict(f.metadata) for f in delta_table.schema().fields} for index, field in enumerate(written.schema): position = stored.get_field_index(field.name) own = original.schema.field(field.name).type - if position < 0 or isinstance(own, pa.ExtensionType): + if position < 0: continue - merged = _merged_record( - stored.field(position).type, stored_records.get(field.name), own, field - ) + held = stored_metadata[field.name] + if pa.types.is_null(own): + # A null column claiming a logical identity the stored column reads is + # written under the stored identifier: it holds no value to read + # otherwise, and Delta refuses another identifier string (ITL-1403). + if _null_reads_as_stored(held, field.metadata): + identifier = { + key.encode(): str(held[key]).encode() + for key in _EXTENSION_TEXT_KEYS + if key in held + } + written = written.set_column( + index, + field.with_metadata({**dict(field.metadata or {}), **identifier}), + written.column(index), + ) + continue + if isinstance(own, pa.ExtensionType): + continue + stored_record = recorded_type(held) + merged = _merged_record(stored.field(position).type, stored_record, own, field) if merged is None: continue - written = written.set_column( - index, with_recorded_type(field, merged), written.column(index) - ) + recorded = with_recorded_type(field, merged) + if stored_record is not None and stored_record.equals( + merged, check_metadata=True + ): + # The same record: sent as stored, byte for byte. Delta compares the + # metadata strings, and a record that decodes to the same type may be + # serialized otherwise (ITL-1403). + recorded = recorded.with_metadata( + { + **dict(recorded.metadata or {}), + ARROW_TYPE_KEY: str(held[ARROW_TYPE_KEY.decode()]).encode(), + } + ) + written = written.set_column(index, recorded, written.column(index)) return written +# The field metadata keys that hold a logical column's identifier, as Delta keeps them. +_EXTENSION_TEXT_KEYS = ("ARROW:extension:name", "ARROW:extension:metadata") + + +def _null_reads_as_stored(held: Mapping[str, Any], metadata: Any) -> bool: + """Whether a null column's identifier is one the stored logical column reads. + + Args: + held: The stored column's field metadata, as Delta keeps it. + metadata: The null column's field metadata (bytes keys), or ``None``. + + Returns: + ``True`` when the null column names the stored extension, with the stored + extension metadata or one the registered logical type reads + (``readable_extension_metadata``). + """ + incoming = { + (k.decode() if isinstance(k, bytes) else str(k)): v + for k, v in (metadata or {}).items() + } + name = incoming.get("ARROW:extension:name") + stored_name = held.get("ARROW:extension:name") + if name is None or stored_name is None: + return False + if (name.decode() if isinstance(name, bytes) else str(name)) != stored_name: + return False + raw = incoming.get("ARROW:extension:metadata", b"") + raw = raw if isinstance(raw, bytes) else str(raw).encode() + if raw == str(held.get("ARROW:extension:metadata", "")).encode(): + return True + from orcapod.contexts import get_default_context + + # The context's converter implements the logical-type lookup of + # ``logical_types.protocols.TypeConverterProtocol``. + converter = cast( + "LogicalTypeConverterProtocol", + cast(object, get_default_context().type_converter), + ) + logical_type = converter.get_logical_type_by_arrow_extension_name(stored_name) + return ( + logical_type is not None and raw in logical_type.readable_extension_metadata() + ) + + def _merged_record( stored_type: pa.DataType, stored_record: pa.DataType | None, @@ -551,6 +626,46 @@ def _duplicate_name_in(error: BaseException) -> str | None: return None +def _all_fields(schema: pa.Schema) -> list["pa.Field[Any]"]: + """Every field of ``schema``: top-level columns and struct fields at any depth.""" + found: list[pa.Field[Any]] = [] + + def visit(field: "pa.Field[Any]") -> None: + found.append(field) + arrow_type = field.type + if isinstance(arrow_type, pa.ExtensionType): + arrow_type = arrow_type.storage_type + for i in range(arrow_type.num_fields): + visit(arrow_type.field(i)) + + for field in schema: + visit(field) + return found + + +def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: + """The field of ``schema`` delta-rs names as a duplicate in ``error``'s chain. + + The name is taken from the schema, the longest one Delta's message quotes, so a + name holding a quote is named whole. ``(the reported text, null)`` when no field + matches. + """ + messages: list[str] = [] + seen: BaseException | None = error + while seen is not None: + messages.append(str(seen)) + seen = seen.__cause__ or seen.__context__ + quoted = [ + f + for f in _all_fields(schema) + if any(f"(case-insensitive): '{f.name}'" in m for m in messages) + ] + if quoted: + field = max(quoted, key=lambda f: len(f.name)) + return field.name, field.type + return _duplicate_name_in(error) or "", pa.null() + + # Why a recorded column's record cannot change on Delta (ITL-1403). _RECORD_CHANGE = ( "the append would change the column's recorded Arrow type, and a recorded " @@ -741,7 +856,10 @@ def _metadata_sent(field: "pa.Field[Any]") -> dict[str, str]: def _changed_record( - delta_table: deltalake.DeltaTable, rows: pa.Table + delta_table: deltalake.DeltaTable, + rows: pa.Table, + schema_evolution: bool, + may_append: Callable[[], bool], ) -> tuple[str, str] | None: """The first stored column whose field metadata (or nested names) the append changes. @@ -753,12 +871,22 @@ def _changed_record( (``to_delta_layout``, ``_conformed_to_stored``, ``_with_merged_records``), so the rows are refused when they are added, never left to fail at every flush. A new key is accepted, as Delta adds it; so is a bare ``null`` column, which sends no - metadata and takes the stored type. A struct evolution that would put two field - names differing only in case into one struct is refused too. + metadata and takes the stored type. A record or identifier that decodes to the + stored one is sent as stored (``_with_merged_records``), so only a real change + remains, and it is refused only on a commit route that sends the metadata: a + MERGE that evolves the schema, or an append (``_stores_as_is``, the flush's own + decision). A MERGE without schema evolution keeps the stored schema and commits. + A struct evolution that would put two field names differing only in case into one + struct is refused too. Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. + schema_evolution: Whether the database's MERGE evolves the stored schema + (``allow_schema_evolution``). + may_append: Whether the commit may still be an append rather than a MERGE: + no id of the rows to commit is stored. Asked only when a real change is + found and the schema does not evolve. Returns: ``(column, reason)``, or ``None``. @@ -768,21 +896,25 @@ def _changed_record( empty = rows.slice(0, 0) # ``_conformed_to_stored`` refuses a struct the stored table cannot take, as the # flush would (``InputValidationError``). - sent_schema = _with_merged_records( + sent_table = _with_merged_records( delta_table, empty, _conformed_to_stored( delta_table, to_delta_layout(empty), delta_table.table_uri ), - ).schema + ) + sent_schema = sent_table.schema + # The flush appends rows whose ids are all new and that it stores as they are; + # every other batch is a MERGE, which sends its schema only when it evolves it. + as_is = DeltaTableDatabase._stores_as_is(delta_table, sent_table) for field in rows.schema: position = stored.get_field_index(field.name) - if position < 0 or pa.types.is_null(field.type): + if position < 0: continue held = stored_metadata[field.name] sent = _metadata_sent(sent_schema.field(field.name)) - changed = sorted(k for k, v in sent.items() if k in held and held[k] != v) - if changed: + changed = sorted(k for k, v in sent.items() if k in held and str(held[k]) != v) + if changed and (schema_evolution or (as_is and may_append())): if any(k.startswith("ARROW:extension:") for k in changed): return field.name, ( "it is stored as logical type " @@ -794,7 +926,7 @@ def _changed_record( "refuses such a commit)" ) return field.name, _RECORD_CHANGE - if isinstance(field.type, pa.ExtensionType): + if isinstance(field.type, pa.ExtensionType) or pa.types.is_null(field.type): continue try: evolved = merged_type( @@ -810,7 +942,10 @@ def _changed_record( def _append_refusal( - delta_table: deltalake.DeltaTable, rows: pa.Table + delta_table: deltalake.DeltaTable, + rows: pa.Table, + schema_evolution: bool, + may_append: Callable[[], bool], ) -> tuple[str, str] | None: """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). @@ -828,6 +963,9 @@ def _append_refusal( Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. + schema_evolution: Whether the database's MERGE evolves the stored schema + (``_changed_record``). + may_append: Whether the commit may still be an append (``_changed_record``). Returns: ``(column, reason)``, or ``None`` when the rows can be appended. @@ -842,7 +980,7 @@ def _append_refusal( clash = _differ_only_in_case([*held, field.name]) if clash is not None: return field.name, _case_reason(*clash) - changed = _changed_record(delta_table, rows) + changed = _changed_record(delta_table, rows, schema_evolution, may_append) if changed is not None: return changed violation = _non_null_violation(held, rows) @@ -1840,6 +1978,18 @@ def require_storable(self, schema: pa.Schema) -> None: reason=reason, ) + def _holds_a_stored_id( + self, record_path: tuple[str, ...], records: pa.Table + ) -> bool: + """Whether the rows queued for the table, or ``records``, hold a stored id. + + Such a batch is committed by a MERGE whatever is added later (ITL-1403). + """ + ids = self._non_null_ids(records) | set( + self._pending_record_ids.get(self._get_record_key(record_path), ()) + ) + return bool(ids & self._stored_ids(record_path)) + def _refuse_case_clash_with_pending( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1954,7 +2104,12 @@ def _refuse_unmergeable_append( ) from unreadable delta_table = None if delta_table is not None: - refusal = _append_refusal(delta_table, records) + refusal = _append_refusal( + delta_table, + records, + self.allow_schema_evolution, + lambda: not self._holds_a_stored_id(record_path, records), + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -2134,7 +2289,6 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) - self._refuse_case_clash_with_pending(record_path, records.schema) self._refuse_untyped_null_columns(record_path, records.schema) # Step 2: Deduplicate within input table (keep last occurrence) @@ -2153,6 +2307,10 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table + # Against the rows queued, on the rows that remain once duplicates are + # skipped: an all-duplicate add queues nothing and is not refused (ITL-1403). + self._refuse_case_clash_with_pending(record_path, filtered_table.schema) + # Columns match by name within a pending batch: rows with the pending # batch's columns in another order, each field equal, are put in its order # (ITL-1367). Only the pending batch: a stored table already takes an append @@ -2914,7 +3072,25 @@ def _flush_by_key(self, record_key: str) -> None: else: # The add-time check, against the version just loaded: another # writer may have committed since the rows were buffered (ITL-1334). - refusal = _append_refusal(delta_table, original_table) + refusal = _append_refusal( + delta_table, + original_table, + self.allow_schema_evolution, + lambda: ( + not ( + self._non_null_ids(original_table) + & ( + self._snapshot_for_commit( + record_key, + delta_table, + table_uri, + abs_path_components, + ).ids + or set() + ) + ) + ), + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -2987,8 +3163,10 @@ def _flush_by_key(self, record_key: str) -> None: logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e except Exception as e: - duplicate = _duplicate_name_in(e) - if duplicate is not None: + reported = _duplicate_name_in(e) + if reported is not None: + # The batch's own name, not the message's: a name may hold a quote. + duplicate, arrow_type = _reported_field(e, pending_batch.schema) # delta-rs folds case with Rust's ``to_lowercase``, which agrees with # Python's ``str.lower`` (the check when rows are added) except for a # few code points of newer Unicode versions. Every later flush would @@ -2996,10 +3174,6 @@ def _flush_by_key(self, record_key: str) -> None: # was written (ITL-1403). self._delta_table_cache.pop(record_key, None) self._snapshots.pop(record_key, None) - arrow_type: Any = next( - (f.type for f in pending_batch.schema if f.name == duplicate), - pa.null(), - ) refused = UnstorableColumnError( database_kind=type(self).__name__, column=duplicate, diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 354c4f4b7..a0a40c82c 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -304,3 +304,215 @@ def rows(rid: bytes, name: str) -> pa.Table: _add(db, rows(b"2", "itl1403.two")) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] assert _stored_ids(tmp_path) == [b"1"] + + +# ── Second review of PR 504 (N2-N5): refuse only what the commit would refuse ────── + +ROUTES = { + "append route (every id new)": [b"2"], + "MERGE route (a stored id among them)": [b"1", b"2"], +} + + +def _with_record_rewritten(root: Path, column: str, rewrite: Any) -> None: + """Rewrite one column's field metadata in the table's first log entry.""" + log = root / "t" / "_delta_log" / "00000000000000000000.json" + actions = [json.loads(line) for line in log.read_text().splitlines()] + for action in actions: + if "metaData" in action: + schema = json.loads(action["metaData"]["schemaString"]) + for field in schema["fields"]: + if field["name"] == column: + rewrite(field["metadata"]) + action["metaData"]["schemaString"] = json.dumps(schema) + log.write_text("\n".join(json.dumps(action) for action in actions) + "\n") + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +@pytest.mark.parametrize("route", sorted(ROUTES)) +def test_a_record_that_decodes_to_the_stored_type_is_not_a_change( + tmp_path: Path, route: str, evolution: bool +) -> None: + """N2: a stored record serialized otherwise (a trailing newline in its base64) + decodes to the same ``uint8``: the append is accepted and sent as stored, on every + commit route, as main stored it.""" + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1", x=pa.array([1], pa.uint8())), flush=True) + + def add_newline(metadata: dict[str, Any]) -> None: + metadata["orcapod:arrow_type"] += "\n" + + _with_record_rewritten(tmp_path, "x", add_newline) + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + ids = ROUTES[route] + db.add_records( + PATH, + pa.table( + { + "rid": pa.array(ids, pa.large_binary()), + "x": pa.array(list(range(1, len(ids) + 1)), pa.uint8()), + } + ), + record_id_column="rid", + skip_duplicates=len(ids) == 1, + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert back is not None + assert back.schema.field("x").type == pa.uint8() + assert sorted(cast(list[bytes], back.column("rid").to_pylist())) == [b"1", b"2"] + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +@pytest.mark.parametrize("route", sorted(ROUTES)) +def test_a_real_record_change_is_refused_only_where_the_commit_sends_it( + tmp_path: Path, route: str, evolution: bool +) -> None: + """N2: list items widening to nullable (non-null values). A MERGE that evolves the + schema sends the new record, which deltalake refuses: refused when added. Without + schema evolution the MERGE keeps the stored schema and commits, as main did.""" + stored = pa.large_list(pa.field("item", pa.uint8(), nullable=False)) + wider = pa.large_list(pa.field("item", pa.uint8(), nullable=True)) + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1", x=pa.array([[1]], stored)), flush=True) + ids = ROUTES[route] + rows = pa.table( + { + "rid": pa.array(ids, pa.large_binary()), + "x": pa.array([[n] for n in range(len(ids))], wider), + } + ) + + def add() -> None: + db.add_records( + PATH, + rows, + record_id_column="rid", + skip_duplicates=len(ids) == 1, + flush=True, + ) + + if evolution: + with pytest.raises(InputValidationError, match="recorded Arrow type"): + add() + assert _stored_ids(tmp_path) == [b"1"] + else: + add() + assert _stored_ids(tmp_path) == [b"1", b"2"] + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +@pytest.mark.parametrize("route", sorted(ROUTES)) +@pytest.mark.parametrize( + "variant", + [ + "no metadata", + "the stored identifier", + "a readable older identifier", + "another name", + ], +) +def test_a_null_column_is_checked_like_any_column( + tmp_path: Path, variant: str, route: str, evolution: bool +) -> None: + """N3: a null column with no metadata takes the stored type; one carrying an + identifier the stored logical type reads is written under the stored identifier; + one carrying another type's identifier is refused when added wherever the commit + would send it (an evolving MERGE, or an append of new ids only), and stored where + the MERGE keeps the stored schema. Nothing reaches a flush that Delta refuses.""" + field, column, _ = _path_column() + path_type = field.type + identifiers: dict[str, dict[str, Any] | None] = { + "no metadata": None, + "the stored identifier": { + "ARROW:extension:name": path_type.extension_name, + "ARROW:extension:metadata": path_type.__arrow_ext_serialize__(), + }, + "a readable older identifier": { + "ARROW:extension:name": path_type.extension_name, + "ARROW:extension:metadata": b"", + }, + "another name": { + "ARROW:extension:name": "itl1403.not.a.path", + "ARROW:extension:metadata": b"", + }, + } + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1").append_column(field, column), flush=True) + ids = ROUTES[route] + null_field = pa.field("x", pa.null(), metadata=identifiers[variant]) + rows = pa.table({"rid": pa.array(ids, pa.large_binary())}).append_column( + null_field, pa.nulls(len(ids)) + ) + + def add() -> None: + db.add_records( + PATH, + rows, + record_id_column="rid", + skip_duplicates=len(ids) == 1, + flush=True, + ) + + sends = evolution or len(ids) == 1 + if variant == "another name" and sends: + with pytest.raises(InputValidationError, match="itl1403.not.a.path"): + add() + assert _stored_ids(tmp_path) == [b"1"] + else: + add() + back = DeltaTableDatabase(tmp_path).get_all_records( + PATH, record_id_column="rid" + ) + assert back is not None + assert back.schema.field("x").type == path_type + assert back.sort_by("rid").column("x").to_pylist() == ["/a", None] + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize("nested", [False, True], ids=["column", "struct field"]) +def test_an_all_duplicate_add_is_skipped_not_refused( + tmp_path: Path, nested: bool +) -> None: + """N4: names are checked against the queued rows after duplicates are skipped: a + row whose id is stored, skipped with ``skip_duplicates``, queues nothing, whatever + its names.""" + db = DeltaTableDatabase(tmp_path) + + def add(name: str, rid: bytes, flush: bool = False) -> None: + data = {"s": pa.array([{name: 1}])} if nested else {name: pa.array([1])} + db.add_records( + PATH, + _rows(rid, **data), + record_id_column="rid", + schema_handling="merge", + skip_duplicates=True, + flush=flush, + ) + + add("a", b"stored", flush=True) + add("a", b"pending") + add("A", b"stored") # a stored id: skipped, not refused + db.flush() + assert _stored_ids(tmp_path) == [b"pending", b"stored"] + + +@pytest.mark.parametrize("suffix", ["'q", " space", '"dq', "(x)", "::y"]) +def test_the_backstop_names_the_column_whole(tmp_path: Path, suffix: str) -> None: + """N5: the column named by the flush's case-folding refusal is the batch's own + field, with its type, also when its name holds a quote.""" + first, second = RUST_ONLY_FOLDS[0][0] + suffix, RUST_ONLY_FOLDS[0][1] + suffix + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError) as info: + _add( + db, _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}), flush=True + ) + assert info.value.column in (first, second) + assert "int64" in str(info.value) diff --git a/tests/test_pipeline/test_dropped_result_batch.py b/tests/test_pipeline/test_dropped_result_batch.py new file mode 100644 index 000000000..93b1e2178 --- /dev/null +++ b/tests/test_pipeline/test_dropped_result_batch.py @@ -0,0 +1,62 @@ +"""A result batch the store refuses at a flush leaves no pipeline record behind. + +Review of PR 504 (second round, N1): when ``DeltaTableDatabase`` drops a result batch +at the flush (names Delta folds alike only by its own case folding, U+1C89 and U+1C8A), +the job's failure-time flush still committed the node's pipeline records, which then +name results that were never stored. The invariant (no pipeline record without its +result) is fixed for every cause under ITL-1412, which PR 504 waits for. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.system_constants import constants + +UPPER, LOWER = "Ᲊ", "ᲊ" + + +@function_pod(output_keys=[UPPER, LOWER]) +def _pair(x: int | None) -> tuple[int, int]: + return x or 0, (x or 0) + 10 + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1412: the failure-time flush commits pipeline records of a dropped result batch", +) +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_no_pipeline_record_names_a_dropped_result( + tmp_path: Path, use_async: bool +) -> None: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [3, 4]}), + tag_columns=["k"], + tag_only_columns=True, + record_id_columns=["k"], + source_id="s", + ) + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1403", database=database) + with job: + _pair.pod(source, label="pair") + with pytest.raises(Exception): # noqa: B017 # the run fails: the result batch is dropped + if use_async: + asyncio.run(job.run_async()) + else: + job.run() + fresh = DeltaTableDatabase(tmp_path) + referenced: list[object] = [] + for path in fresh.list_table_paths(): + table = fresh.get_all_records(path, record_id_column="__record_id") + if table is not None and constants.DATA_RECORD_ID in table.column_names: + referenced += table[constants.DATA_RECORD_ID].to_pylist() + assert [r for r in referenced if r is not None] == [] From a0965f9acfa9a8b20fa449fae6c0d517de85de88 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:57:56 -0800 Subject: [PATCH 11/23] fix(databases): walk an error chain once: a lost commit's last error loops back to its wrapper (ITL-1377) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index b9465e5f6..2c9b045b7 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -576,15 +576,27 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: def _duplicate_name_in(error: BaseException) -> str | None: """The name delta-rs reports as a case-insensitive duplicate in ``error``'s chain.""" - seen: BaseException | None = error - while seen is not None: + for seen in _error_chain(error): match = _DUPLICATE_NAME.search(str(seen)) if match is not None: return match.group(1) - seen = seen.__cause__ or seen.__context__ return None +def _error_chain(error: BaseException) -> list[BaseException]: + """``error`` and its causes and contexts, each once: a chain may loop. + + It does when an error is raised again inside the handler of an error that wraps + it (a lost commit's retry gives up with the error it lost to; ITL-1377). + """ + chain: list[BaseException] = [] + seen: BaseException | None = error + while seen is not None and all(seen is not e for e in chain): + chain.append(seen) + seen = seen.__cause__ or seen.__context__ + return chain + + # Why a recorded column's record cannot change on Delta (ITL-1403). _RECORD_CHANGE = ( "the append would change the column's recorded Arrow type, and a recorded " From d0a2363d5116df8a5ea2a93863f227dceaad4766 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:06:21 -0800 Subject: [PATCH 12/23] fix(databases): the Delta flush is the point of truth; refuse when added only what is certain (ITL-1403) The developer's decision (2026-11-22): no prediction of what deltalake will do at commit. When rows are added only exact checks remain: names differing only in case (top level and nested, also a struct evolution that would put two such names into one struct), a stored table deltalake cannot read, and the logical identifier of a typed column against the stored one. The record/metadata-change preflight (_changed_record, the route prediction, the stored-id lookup) is gone. At the flush a failed commit is classified (_permanent_commit_failure): SchemaMismatchError, the duplicate-name error and a DeltaError starting with one of PERMANENT_DELTA_ERROR_PREFIXES ('type_coercion', 'Invalid data found', 'Unsupported CAST') are raised once, naming the table, Delta's reason and the rows not written, and the batch leaves the queue; CommitFailedError and every other failure keep main's behaviour. The duplicate-name backstop locates the colliding field with Delta's own schema check. Tests: each permanent form provoked with deltalake itself; a storage failure keeps its rows queued; the review sweep as a property test (Orcapod refuses nothing Delta stores; nothing stays queued); every review finding asserts the flush behaviour where the add-time check was removed. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 37 ++- docs/reference/database-types.md | 26 +- docs/troubleshooting.md | 23 ++ src/orcapod/databases/delta_lake_databases.py | 296 ++++++++---------- .../test_delta_add_time_property.py | 185 +++++++++++ .../test_delta_append_preflight.py | 8 +- .../test_delta_commit_failures.py | 186 +++++++++++ .../test_delta_read_failures.py | 7 +- .../test_delta_refused_before_queueing.py | 162 +++++++--- .../test_delta_struct_evolution.py | 19 +- tests/test_databases/type_matrix.py | 26 +- .../test_delta_refusals_in_jobs.py | 21 +- 12 files changed, 751 insertions(+), 245 deletions(-) create mode 100644 tests/test_databases/test_delta_add_time_property.py create mode 100644 tests/test_databases/test_delta_commit_failures.py diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index 7c32c8d7f..fb9d91d2f 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -26,19 +26,30 @@ Rust's `to_lowercase` does: for the few code points where Python's `str.lower` differs, the refusal comes at the flush, once, as `UnstorableColumnError`, and the batch leaves the queue. The in-memory and connector databases still hold such names as two columns. -- `DeltaTableDatabase` refuses an append that would change a stored column's field - metadata (`InputValidationError` naming the column, before anything is queued): - deltalake 1.5 and later refuses such a commit. Two cases: - - A column's recorded Arrow type: every list and map column, and every struct holding - an unsigned integer, a non-microsecond time type, `float16` or a fixed-size type. A - field added to such a struct changes it, in the small list form as in the large one, - and so does a change of nested nullability (a list's items becoming nullable). - - A logical column's identifier: another extension name, or the same name with other - extension metadata. - - Still accepted: a struct column without a record gaining fields, a field omitted or - reordered, a new column, and an untyped `null` column, which takes the stored type. - Tables Orcapod's own nodes write are not concerned: their column types are fixed by +- On Delta the commit is the point of truth. When rows are added, `DeltaTableDatabase` + refuses only what it can tell for certain: names differing only in case (above), a + stored table deltalake cannot read, another logical type + (another extension name, or the same name with other extension metadata) over a stored + logical column, and a struct evolution that would put two names differing only in case + into one struct. Telling more rules up front is ITL-1418. +- What deltalake refuses at the commit for the rows themselves is raised by the flush + once, as `InputValidationError` ("Delta refused the commit to table ...") naming the + table, Delta's reason and the number of rows not written. Those rows leave the queue, + the other tables of the same flush still commit, and a second flush does nothing. A + job fails with `OrcapodDatabaseWriteError` and that cause. The permanent refusals are + `SchemaMismatchError`, the duplicate-name error, and a `DeltaError` whose message starts + with one of `PERMANENT_DELTA_ERROR_PREFIXES` (`type_coercion`, `Invalid data found`, + `Unsupported CAST`). Any other failure keeps its rows queued as before, so nothing is + dropped on a guess. Until ITL-1412, a job whose result batch is dropped this way can + keep pipeline records naming those results. +- This narrows what a Delta table takes from deltalake 1.5 on: a stored column's field + metadata cannot change in a commit. So a column whose Arrow type is recorded cannot + gain a struct field, or have a nested nullability change, when schema evolution is on. + A recorded column is every list and map column, and every struct holding an unsigned + integer, a non-microsecond time type, `float16` or a fixed-size type. A struct column + without a record still gains fields, a field may be omitted or reordered, a new column + may be added, and an untyped `null` column takes the stored type. +- Tables Orcapod's own nodes write are not concerned: their column types are fixed by their inputs' schemas, and a changed column type changes the table's path. The one exception is an operator whose result type depends on its data rather than on its input schemas, which is a bug of that operator. Example: a custom operator emitting diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index e295ea606..983ecb2c4 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -79,15 +79,23 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps -through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field, nor have a nested nullability change: the record is the -column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit -change, so such an append is refused, naming the column, before anything is queued. A -struct column without a record still gains fields, an append may still add a new column, -and an untyped `null` column takes the stored type. Another logical type over a stored -logical column (another extension name, or the same name with other extension metadata) -is refused the same way. +as nullable afterwards, as Delta stores it. + +On Delta, the commit is the point of truth. When rows are added, only what is certain is +refused, before anything is queued: two names differing only in case, a stored table +deltalake cannot read, another logical type (another +extension name or other extension metadata) over a stored logical column, and a struct +evolution that would put two names differing only in case into one struct. What +deltalake refuses at the commit for the rows themselves (a changed field metadata, a type +it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, +naming the table, Delta's reason and the rows not written; those rows leave the queue, +and the other tables of the flush still commit. Any other failure keeps its rows queued. +So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" +cells below, every list and map included) cannot gain a field when schema evolution is +on, nor have a nested nullability change: the record is the column's field metadata, +which deltalake 1.5 and later does not let a commit change. A struct column without a +record still gains fields, an append may still add a new column, and an untyped `null` +column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 4d494707e..e2dcebf95 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -205,6 +205,29 @@ the names of your functions, not their code. `loaded.run(load_only=True)` to fill the nodes from the database (bind in-memory sources first). To compute, run the script that defines the pipeline. +### `InputValidationError: Delta refused the commit to table ...` + +**Symptom.** A flush, or a job's commit (`OrcapodDatabaseWriteError` with this error as +its cause), fails with `Delta refused the commit to table '...': . The N +rows queued for it were not written and are no longer queued`. `UnstorableColumnError` +saying that Delta reports a name as equal to another's under its case folding is the same +kind of failure. + +**Cause.** A `DeltaTableDatabase` refuses only what it can tell for certain when rows are +added (names that differ only in case, a stored table deltalake cannot read, another logical type over a stored logical column). Everything +else is decided by deltalake when it commits. The refusals that would happen again at +every flush are raised once: a changed field metadata, which deltalake 1.5 and later +refuses (a struct with a recorded type gaining a field, a list's items becoming +nullable), a type DataFusion cannot insert or cast into the stored one, or a null in a +non-nullable column. The rows are dropped from the queue so that the next flush is not +refused the same way; other tables of the same flush still commit. A failure that may +pass, such as a storage error, keeps its rows queued, and the next flush tries them +again. + +**Fix.** Read Delta's reason, correct the rows (or their declared types) and add them +again. In a job, running it again computes the same rows and fails the same way until +then. [Data types per database](reference/database-types.md) lists what each database stores. + ## Problems that give no error ### I edited my function and the results did not change diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 149debef4..cf36ad012 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -617,61 +617,117 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: def _duplicate_name_in(error: BaseException) -> str | None: """The name delta-rs reports as a case-insensitive duplicate in ``error``'s chain.""" - seen: BaseException | None = error - while seen is not None: + for seen in _error_chain(error): match = _DUPLICATE_NAME.search(str(seen)) if match is not None: return match.group(1) - seen = seen.__cause__ or seen.__context__ return None -def _all_fields(schema: pa.Schema) -> list["pa.Field[Any]"]: - """Every field of ``schema``: top-level columns and struct fields at any depth.""" - found: list[pa.Field[Any]] = [] +def _error_chain(error: BaseException) -> list[BaseException]: + """``error`` and its causes and contexts, each once: a chain may loop. - def visit(field: "pa.Field[Any]") -> None: - found.append(field) - arrow_type = field.type - if isinstance(arrow_type, pa.ExtensionType): - arrow_type = arrow_type.storage_type - for i in range(arrow_type.num_fields): - visit(arrow_type.field(i)) + It does when an error is raised again inside the handler of an error that wraps + it (a lost commit's retry gives up with the error it lost to; ITL-1377). + """ + chain: list[BaseException] = [] + seen: BaseException | None = error + while seen is not None and all(seen is not e for e in chain): + chain.append(seen) + seen = seen.__cause__ or seen.__context__ + return chain + + +# The forms of a plain ``DeltaError`` that are permanent: DataFusion cannot insert the +# rows into the stored schema, cannot cast them to it, or the rows break a constraint of +# the stored table (a null in a non-nullable column). Every later flush would fail the +# same way. +# ``DeltaError`` is also how deltalake reports a storage failure, which may pass, so +# only these message forms are taken as permanent (deltalake 1.6.6; ITL-1403). +PERMANENT_DELTA_ERROR_PREFIXES = ( + "Generic DeltaTable error: type_coercion", + "Generic DeltaTable error: External error: Invalid data found", + "Generic DeltaTable error: This feature is not implemented: Unsupported CAST", +) - for field in schema: - visit(field) - return found + +def _permanent_commit_failure(error: BaseException) -> bool: + """Whether a failed commit would fail the same way at every later flush. + + Permanent: ``SchemaMismatchError`` (Delta refuses the rows' schema or field + metadata), the duplicate-name error (two names equal under Delta's case folding, + a bare ``Exception``), and a ``DeltaError`` whose message starts with one of + ``PERMANENT_DELTA_ERROR_PREFIXES``. Not permanent: ``CommitFailedError`` (another + writer committed first) and everything else, which keeps its rows queued. + """ + from deltalake.exceptions import ( + CommitFailedError, + DeltaError, + SchemaMismatchError, + ) + + if isinstance(error, CommitFailedError): + return False + if isinstance(error, SchemaMismatchError): + return True + if type(error) is Exception and _DUPLICATE_NAME.search(str(error)): + return True + if isinstance(error, DeltaError): + return str(error).startswith(PERMANENT_DELTA_ERROR_PREFIXES) + return False def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: """The field of ``schema`` delta-rs names as a duplicate in ``error``'s chain. - The name is taken from the schema, the longest one Delta's message quotes, so a + Delta's own schema check locates it: a column whose schema Delta refuses on its own + holds the colliding struct fields, and the field is named by its path in that + column (``s.ᲊ``) with its type; otherwise the collision is between top-level + columns. Names come from the schema, the longest one Delta's message quotes, so a name holding a quote is named whole. ``(the reported text, null)`` when no field matches. """ - messages: list[str] = [] - seen: BaseException | None = error - while seen is not None: - messages.append(str(seen)) - seen = seen.__cause__ or seen.__context__ - quoted = [ - f - for f in _all_fields(schema) - if any(f"(case-insensitive): '{f.name}'" in m for m in messages) - ] - if quoted: - field = max(quoted, key=lambda f: len(f.name)) + messages = [str(seen) for seen in _error_chain(error)] + + def quoted(field: "pa.Field[Any]") -> bool: + return any(f"(case-insensitive): '{field.name}'" in m for m in messages) + + for column in schema: + try: + deltalake.Schema.from_arrow(pa.schema([column])) + except Exception as refused: # noqa: BLE001 # only a duplicate name is looked at + if _duplicate_name_in(refused) is None: + continue + nested = [ + (path, field) + for path, field in _field_paths(column) + if path != column.name and quoted(field) + ] + if nested: + path, field = max(nested, key=lambda item: len(item[1].name)) + return path, field.type + top = [field for field in schema if quoted(field)] + if top: + field = max(top, key=lambda f: len(f.name)) return field.name, field.type return _duplicate_name_in(error) or "", pa.null() -# Why a recorded column's record cannot change on Delta (ITL-1403). -_RECORD_CHANGE = ( - "the append would change the column's recorded Arrow type, and a recorded " - "column's type cannot change on a Delta table: deltalake refuses a commit that " - "changes a column's field metadata (deltalake 1.5 and later)" -) +def _field_paths(column: "pa.Field[Any]") -> list[tuple[str, "pa.Field[Any]"]]: + """``column`` and every struct field inside it, each with its dotted path.""" + found: list[tuple[str, pa.Field[Any]]] = [] + + def visit(path: str, field: "pa.Field[Any]") -> None: + found.append((path, field)) + arrow_type = field.type + if isinstance(arrow_type, pa.ExtensionType): + arrow_type = arrow_type.storage_type + for i in range(arrow_type.num_fields): + child = arrow_type.field(i) + visit(f"{path}.{child.name}", child) + + visit(column.name, column) + return found _EXTENSION_KEYS = (b"ARROW:extension:name", b"ARROW:extension:metadata") @@ -836,97 +892,50 @@ def _non_null_violation( return None -def _metadata_sent(field: "pa.Field[Any]") -> dict[str, str]: - """The field metadata a commit sends to Delta for ``field``, as text. - - A logical column also carries its identifier as ``ARROW:extension:name`` and - ``ARROW:extension:metadata``, as the Arrow C interface hands it to delta-rs. - """ - sent = { - k.decode() if isinstance(k, bytes) else k: ( - v.decode(errors="replace") if isinstance(v, bytes) else v - ) - for k, v in (field.metadata or {}).items() - } - if isinstance(field.type, pa.ExtensionType): - identifier = arrow_type_identifier(field.type) - sent["ARROW:extension:name"] = identifier.name - sent["ARROW:extension:metadata"] = identifier.metadata.decode(errors="replace") - return sent - - -def _changed_record( - delta_table: deltalake.DeltaTable, - rows: pa.Table, - schema_evolution: bool, - may_append: Callable[[], bool], +def _exact_refusal( + delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: - """The first stored column whose field metadata (or nested names) the append changes. - - deltalake (1.5 and later) refuses a commit that gives a stored column's field - metadata key another value (delta-rs ``try_merge_metadata``). That metadata holds a - recorded column's record (``orcapod:arrow_type``) and a logical column's identifier - (``ARROW:extension:name`` and ``ARROW:extension:metadata``). The metadata the - commit would send is computed here by the functions the flush uses - (``to_delta_layout``, ``_conformed_to_stored``, ``_with_merged_records``), so the - rows are refused when they are added, never left to fail at every flush. A new key - is accepted, as Delta adds it; so is a bare ``null`` column, which sends no - metadata and takes the stored type. A record or identifier that decodes to the - stored one is sent as stored (``_with_merged_records``), so only a real change - remains, and it is refused only on a commit route that sends the metadata: a - MERGE that evolves the schema, or an append (``_stores_as_is``, the flush's own - decision). A MERGE without schema evolution keeps the stored schema and commits. - A struct evolution that would put two field names differing only in case into one - struct is refused too. + """What Orcapod can tell for certain about an append to ``delta_table`` (ITL-1403). + + The commit itself is the point of truth: what deltalake refuses for any other + reason is refused at the flush, once (``_permanent_commit_failure``). Only two + things are refused here, both certain: + + - a typed logical column whose identifier (extension name and metadata) is not + the stored column's: another logical type, whose values must not be read as + the stored one's; + - a struct evolution that would put two field names differing only in case into + one struct, which Delta refuses whatever the commit route. Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. - schema_evolution: Whether the database's MERGE evolves the stored schema - (``allow_schema_evolution``). - may_append: Whether the commit may still be an append rather than a MERGE: - no id of the rows to commit is stored. Asked only when a real change is - found and the schema does not evolve. Returns: ``(column, reason)``, or ``None``. """ stored = _stored_arrow_schema(delta_table) - stored_metadata = {f.name: dict(f.metadata) for f in delta_table.schema().fields} - empty = rows.slice(0, 0) - # ``_conformed_to_stored`` refuses a struct the stored table cannot take, as the - # flush would (``InputValidationError``). - sent_table = _with_merged_records( - delta_table, - empty, - _conformed_to_stored( - delta_table, to_delta_layout(empty), delta_table.table_uri - ), - ) - sent_schema = sent_table.schema - # The flush appends rows whose ids are all new and that it stores as they are; - # every other batch is a MERGE, which sends its schema only when it evolves it. - as_is = DeltaTableDatabase._stores_as_is(delta_table, sent_table) + held = {f.name: dict(f.metadata) for f in delta_table.schema().fields} for field in rows.schema: position = stored.get_field_index(field.name) if position < 0: continue - held = stored_metadata[field.name] - sent = _metadata_sent(sent_schema.field(field.name)) - changed = sorted(k for k, v in sent.items() if k in held and str(held[k]) != v) - if changed and (schema_evolution or (as_is and may_append())): - if any(k.startswith("ARROW:extension:") for k in changed): + if isinstance(field.type, pa.ExtensionType): + stored_name = held[field.name].get("ARROW:extension:name") + if stored_name is None: + continue + incoming = arrow_type_identifier(field.type) + stored_metadata = str(held[field.name].get("ARROW:extension:metadata", "")) + if (incoming.name, incoming.metadata.decode(errors="replace")) != ( + stored_name, + stored_metadata, + ): return field.name, ( - "it is stored as logical type " - f"{held.get('ARROW:extension:name')!r} " - f"({held.get('ARROW:extension:metadata')!r}) and the rows hold " - f"{sent.get('ARROW:extension:name')!r} " - f"({sent.get('ARROW:extension:metadata')!r}): a column's field " - "metadata cannot change on a Delta table (deltalake 1.5 and later " - "refuses such a commit)" + f"it is stored as logical type {stored_name!r} " + f"({stored_metadata!r}) and the rows hold {incoming.name!r} " + f"({incoming.metadata.decode(errors='replace')!r}): another " + "logical type" ) - return field.name, _RECORD_CHANGE - if isinstance(field.type, pa.ExtensionType) or pa.types.is_null(field.type): continue try: evolved = merged_type( @@ -942,10 +951,7 @@ def _changed_record( def _append_refusal( - delta_table: deltalake.DeltaTable, - rows: pa.Table, - schema_evolution: bool, - may_append: Callable[[], bool], + delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). @@ -963,9 +969,6 @@ def _append_refusal( Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. - schema_evolution: Whether the database's MERGE evolves the stored schema - (``_changed_record``). - may_append: Whether the commit may still be an append (``_changed_record``). Returns: ``(column, reason)``, or ``None`` when the rows can be appended. @@ -980,9 +983,9 @@ def _append_refusal( clash = _differ_only_in_case([*held, field.name]) if clash is not None: return field.name, _case_reason(*clash) - changed = _changed_record(delta_table, rows, schema_evolution, may_append) - if changed is not None: - return changed + exact = _exact_refusal(delta_table, rows) + if exact is not None: + return exact violation = _non_null_violation(held, rows) if violation is not None: name, omitted = violation @@ -1978,18 +1981,6 @@ def require_storable(self, schema: pa.Schema) -> None: reason=reason, ) - def _holds_a_stored_id( - self, record_path: tuple[str, ...], records: pa.Table - ) -> bool: - """Whether the rows queued for the table, or ``records``, hold a stored id. - - Such a batch is committed by a MERGE whatever is added later (ITL-1403). - """ - ids = self._non_null_ids(records) | set( - self._pending_record_ids.get(self._get_record_key(record_path), ()) - ) - return bool(ids & self._stored_ids(record_path)) - def _refuse_case_clash_with_pending( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -2104,12 +2095,7 @@ def _refuse_unmergeable_append( ) from unreadable delta_table = None if delta_table is not None: - refusal = _append_refusal( - delta_table, - records, - self.allow_schema_evolution, - lambda: not self._holds_a_stored_id(record_path, records), - ) + refusal = _append_refusal(delta_table, records) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -3072,25 +3058,7 @@ def _flush_by_key(self, record_key: str) -> None: else: # The add-time check, against the version just loaded: another # writer may have committed since the rows were buffered (ITL-1334). - refusal = _append_refusal( - delta_table, - original_table, - self.allow_schema_evolution, - lambda: ( - not ( - self._non_null_ids(original_table) - & ( - self._snapshot_for_commit( - record_key, - delta_table, - table_uri, - abs_path_components, - ).ids - or set() - ) - ) - ), - ) + refusal = _append_refusal(delta_table, original_table) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -3163,6 +3131,20 @@ def _flush_by_key(self, record_key: str) -> None: logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e except Exception as e: + if _permanent_commit_failure(e) and _duplicate_name_in(e) is None: + # Refused by Delta for the rows themselves: every later flush would be + # refused the same way, so the batch leaves the queue, and nothing of + # it was written (ITL-1403). The flush is the point of truth. + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + refused = InputValidationError( + f"Delta refused the commit to table {record_key!r}: " + f"{str(e).rstrip('.')}. The " + f"{pending_batch.num_rows} rows queued for it were not written " + "and are no longer queued: correct them and add them again." + ) + logger.error(f"Refused batch for {record_key}: {refused}") + raise refused from e reported = _duplicate_name_in(e) if reported is not None: # The batch's own name, not the message's: a name may hold a quote. diff --git a/tests/test_databases/test_delta_add_time_property.py b/tests/test_databases/test_delta_add_time_property.py new file mode 100644 index 000000000..37d513f98 --- /dev/null +++ b/tests/test_databases/test_delta_add_time_property.py @@ -0,0 +1,185 @@ +"""The property of a ``DeltaTableDatabase`` append: Orcapod refuses nothing Delta stores. + +The developer's decision for ITL-1403 (2026-11-22): the flush is the point of truth. +When rows are added, only what Orcapod can tell for certain is refused; everything else +is left to the commit, whose refusal the flush raises once, without keeping the rows +queued. This file is the review of PR 504's sweep, as a test: every stored type (same +schema, as written), every record change, struct evolution, null and layout case and +logical-type case, with schema evolution on and off, and with the commit an append +(every id new) or a MERGE (a stored id among the rows). For each: + +- what Orcapod refuses when the rows are added, Delta refuses too: the same rows given + to the database with Orcapod's add-time checks switched off are not stored (the one + exception is the logical-type rule, an Orcapod rule by design: another logical type's + values must not be read as the stored one's); +- nothing fails forever: after the flush, no row is still queued. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from itertools import product +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases as dld +from tests.test_databases import test_delta_append_types as append_types +from tests.test_databases import test_delta_refused_before_queueing as refused +from tests.test_databases import test_delta_struct_evolution as evolution + +PATH = ("t",) + + +def _variants() -> Iterator[tuple[str, Any, Any, Any, Any]]: + for param in append_types.all_types(): + name, arrow_type, nullable = param.values + if name in append_types.NOT_STORABLE: + continue + column = append_types.column(arrow_type) + field = pa.field("x", arrow_type, nullable=nullable) + yield f"same {param.id}", column, column, field, field + for label, (a, b) in refused.RECORD_CHANGES.items(): + yield f"record {label}", a, b, None, None + for label, (at, av, bt, bv, _) in evolution.CASES.items(): + yield f"evolution {label}", pa.array(av, at), pa.array(bv, bt), None, None + for label, (a, b) in { + "simple null": (pa.array([1]), pa.nulls(1)), + "null struct field": ( + pa.array([{"a": 1}]), + pa.array([{"a": None}], pa.struct([("a", pa.null())])), + ), + "null list item": ( + pa.array([[1]], pa.large_list(pa.int64())), + pa.array([[None]], pa.large_list(pa.null())), + ), + "null into recorded unsigned": (pa.array([1], pa.uint8()), pa.nulls(1)), + "null into recorded list": (pa.array([[1]], pa.list_(pa.int64())), pa.nulls(1)), + "plain field becomes nullable": ( + pa.array( + [{"a": 1}], pa.struct([pa.field("a", pa.int64(), nullable=False)]) + ), + pa.array([{"a": None}], pa.struct([("a", pa.int64())])), + ), + "small list then large": ( + pa.array([[1]], pa.list_(pa.int64())), + pa.array([[2]], pa.large_list(pa.int64())), + ), + }.items(): + yield f"null/layout {label}", a, b, None, None + field, column, _ = refused._path_column() # pyright: ignore[reportPrivateUsage] + stored = column.combine_chunks() if isinstance(column, pa.ChunkedArray) else column + for label, ext in { + "bare": None, + "current": field.type.__arrow_ext_serialize__(), + "readable old": b"", + "unknown": b"bogus", + }.items(): + metadata = ( + None + if ext is None + else { + b"ARROW:extension:name": field.type.extension_name.encode(), + b"ARROW:extension:metadata": ext, + } + ) + yield ( + f"path null {label}", + stored, + pa.nulls(1), + field, + pa.field("x", pa.null(), metadata=metadata), + ) + for label, a, b in [ + ("same", b"x", b"x"), + ("changed", b"x", b"y"), + ("empty to value", b"", b"y"), + ("value to empty", b"x", b""), + ]: + units = [ + pa.ExtensionArray.from_storage(refused._Unit(v), pa.array([1])) # pyright: ignore[reportPrivateUsage] + for v in (a, b) + ] + yield f"logical {label}", units[0], units[1], None, None + + +VARIANTS = {label: rest for label, *rest in _variants()} +LOGICAL_RULE = {"logical changed", "logical empty to value", "logical value to empty"} + + +def _rows(column: Any, ids: list[bytes], field: Any = None) -> pa.Table: + values = pa.concat_arrays([column] * len(ids)) if len(ids) > 1 else column + return pa.table( + [pa.array(ids, pa.large_binary()), values], + schema=pa.schema( + [ + pa.field("rid", pa.large_binary(), nullable=False), + field or pa.field("x", column.type), + ] + ), + ) + + +def _run( + root: Path, initial: pa.Table, incoming: pa.Table, evolve: bool +) -> tuple[str, bool]: + """``(outcome, rows still queued)``: ``stored``, ``refused when added``, or + ``refused at flush``.""" + db = DeltaTableDatabase(root, allow_schema_evolution=evolve) + db.add_records(PATH, initial, record_id_column="rid", flush=True) + try: + db.add_records(PATH, incoming, record_id_column="rid") + except Exception: # noqa: BLE001 # the outcome is the subject + return "refused when added", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] + try: + db.flush() + except Exception: # noqa: BLE001 + return "refused at flush", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] + return "stored", False + + +@pytest.fixture(autouse=True) +def _unit_registered(unit_type: Any) -> None: + """The logical cases use a registered extension type.""" + + +unit_type = refused.unit_type + + +@pytest.mark.parametrize( + "seen", [False, True], ids=["append (every id new)", "MERGE (a stored id)"] +) +@pytest.mark.parametrize("evolve", [False, True], ids=["evolution off", "evolution on"]) +@pytest.mark.parametrize("label", sorted(VARIANTS)) +def test_orcapod_refuses_nothing_delta_stores( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + label: str, + evolve: bool, + seen: bool, +) -> None: + a, b, field_a, field_b = VARIANTS[label] + initial = _rows(a, [b"1"], field_a) + incoming = _rows(b, [b"1", b"2"] if seen else [b"2"], field_b) + + live, queued = _run(tmp_path / "live", initial, incoming, evolve) + assert not queued, f"{label}: rows still queued after the flush ({live})" + + if live == "refused when added" and label not in LOGICAL_RULE: + # Delta's own verdict: the same rows with Orcapod's add-time checks off. + monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) + monkeypatch.setattr( + DeltaTableDatabase, "_refuse_case_clash_with_pending", lambda *args: None + ) + raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw != "stored", f"{label}: Orcapod refused rows Delta stores" + + +def test_the_sweep_covers_every_kind() -> None: + kinds = {label.split(" ")[0] for label in VARIANTS} + assert kinds == {"same", "record", "evolution", "null/layout", "path", "logical"} + assert len(VARIANTS) > 100 + _ = product # the sweep is the product of the three parameters above diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index 27327206c..6309da989 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -305,7 +305,7 @@ def test_a_null_child_of_an_evolving_struct_appends( ) -> None: """Delta's MERGE panicked on a ``null`` child of a struct that gains a field (pre-existing); the child is written as typed nulls of its stored type. Inside a - list (a recorded column) the evolution is refused instead (ITL-1403).""" + list (a recorded column) Delta refuses the evolution, once, at the flush (ITL-1403).""" stored_type = _struct(pa.field("a", I64)) in_list = pa.types.is_large_list(appended) db = DeltaTableDatabase(tmp_path) @@ -323,9 +323,9 @@ def test_a_null_child_of_an_evolving_struct_appends( ) value = {"a": None, "b": 2} if in_list: - # A list column is recorded, and its record would change: refused on Delta - # before anything is buffered (ITL-1403). - with pytest.raises(InputValidationError, match="recorded Arrow type"): + # A list column is recorded, and its record would change: Delta refuses the + # commit; the flush raises once and the batch leaves the queue (ITL-1403). + with pytest.raises(InputValidationError, match="Delta refused the commit"): db.add_records( PATH, _rows([b"2"], x=(appended, [[value]])), diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py new file mode 100644 index 000000000..25a15d368 --- /dev/null +++ b/tests/test_databases/test_delta_commit_failures.py @@ -0,0 +1,186 @@ +"""How a failed Delta commit is classified at the flush (ITL-1403). + +The flush is the point of truth: a commit deltalake refuses for the rows themselves +would be refused the same way at every later flush, so it is raised once and the batch +leaves the queue; anything else keeps its rows queued, so nothing is dropped on a guess. + +Each permanent form is provoked here with deltalake itself, so an upgrade that changes +an exception type or one of ``PERMANENT_DELTA_ERROR_PREFIXES`` fails this file. +""" + +from __future__ import annotations + +import os +import stat +import sys +from collections.abc import Callable +from pathlib import Path +from typing import Any, cast + +import deltalake +import pyarrow as pa +import pytest + +from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases as dld +from orcapod.errors import InputValidationError + +PATH = ("t",) + + +def _raised(action: Callable[[], Any]) -> BaseException: + try: + action() + except Exception as error: # noqa: BLE001 # the error is the subject + return error + raise AssertionError("deltalake did not refuse") + + +def _merge(table: deltalake.DeltaTable, rows: pa.Table, evolve: bool = True) -> Any: + return ( + table.merge( + rows, + "t.id = s.id", + source_alias="s", + target_alias="t", + merge_schema=evolve, + ) + .when_not_matched_insert_all() + .execute() + ) + + +def _metadata_change(root: Path) -> BaseException: + def table(value: str) -> pa.Table: + field = pa.field("x", pa.int64(), metadata={"k": value}) + return pa.Table.from_arrays( + [pa.array([1]), pa.array([1])], + schema=pa.schema([pa.field("id", pa.int64()), field]), + ) + + deltalake.write_deltalake(str(root), table("1")) + return _raised(lambda: _merge(deltalake.DeltaTable(str(root)), table("2"))) + + +def _type_coercion(root: Path) -> BaseException: + deltalake.write_deltalake( + str(root), pa.table({"id": [1], "s": pa.array([{"x": 1}])}) + ) + grown = pa.table({"id": [2], "s": pa.array([{"x": 2, "y": 3}])}) + return _raised(lambda: _merge(deltalake.DeltaTable(str(root)), grown, evolve=False)) + + +def _invalid_data(root: Path) -> BaseException: + schema = pa.schema( + [pa.field("id", pa.int64()), pa.field("v", pa.int64(), nullable=False)] + ) + deltalake.write_deltalake( + str(root), pa.Table.from_arrays([pa.array([1]), pa.array([1])], schema=schema) + ) + nulls = pa.table({"id": [2], "v": pa.array([None], pa.int64())}) + return _raised(lambda: _merge(deltalake.DeltaTable(str(root)), nulls)) + + +def _unsupported_cast(root: Path) -> BaseException: + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("s", pa.struct([pa.field("a", pa.int64(), nullable=False)])), + ] + ) + deltalake.write_deltalake( + str(root), + pa.Table.from_arrays( + [pa.array([1]), pa.array([{"a": 1}], schema.field("s").type)], schema=schema + ), + ) + loosened = pa.table( + {"id": [2], "s": pa.array([{"a": None}], pa.struct([("a", pa.int64())]))} + ) + return _raised( + lambda: _merge(deltalake.DeltaTable(str(root)), loosened, evolve=False) + ) + + +def _duplicate_name(root: Path) -> BaseException: + return _raised( + lambda: deltalake.write_deltalake( + str(root), pa.table({"id": [1], "a": [1], "A": [2]}) + ) + ) + + +PERMANENT: dict[str, Callable[[Path], BaseException]] = { + "SchemaMismatchError (field metadata)": _metadata_change, + "DeltaError 'type_coercion' (DataFusion cannot insert)": _type_coercion, + "DeltaError 'Invalid data found' (a null in a non-nullable column)": _invalid_data, + "DeltaError 'Unsupported CAST' (a nested field loosened, no evolution)": _unsupported_cast, + "Exception 'Duplicate field name' (case-insensitive names)": _duplicate_name, +} + + +@pytest.mark.parametrize("case", sorted(PERMANENT)) +def test_each_permanent_form_of_deltalake_is_classified_permanent( + tmp_path: Path, case: str +) -> None: + error = PERMANENT[case](tmp_path / "t") + assert dld._permanent_commit_failure(error), (type(error), str(error)) # pyright: ignore[reportPrivateUsage] + + +def test_the_prefixes_are_the_documented_three() -> None: + assert dld.PERMANENT_DELTA_ERROR_PREFIXES == ( + "Generic DeltaTable error: type_coercion", + "Generic DeltaTable error: External error: Invalid data found", + "Generic DeltaTable error: This feature is not implemented: Unsupported CAST", + ) + + +def test_a_concurrent_commit_is_not_permanent(tmp_path: Path) -> None: + from deltalake.exceptions import CommitFailedError + + root = str(tmp_path / "t") + deltalake.write_deltalake(root, pa.table({"id": [1]})) + stale = deltalake.DeltaTable(root) + _merge(deltalake.DeltaTable(root), pa.table({"id": [2]})) + error = _raised(lambda: _merge(stale, pa.table({"id": [3]}))) + assert isinstance(error, CommitFailedError) + assert not dld._permanent_commit_failure(error) # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="permissions") +def test_a_storage_failure_keeps_the_rows_queued(tmp_path: Path) -> None: + """A failure that may pass (here an unwritable table directory) is not dropped: + the rows stay queued, and a later flush, once the store is writable, commits them.""" + db = DeltaTableDatabase(tmp_path) + rows = lambda rid: pa.table({"rid": pa.array([rid], pa.large_binary()), "v": [1]}) # noqa: E731 + db.add_records(PATH, rows(b"1"), record_id_column="rid", flush=True) + db.add_records(PATH, rows(b"2"), record_id_column="rid", skip_duplicates=True) + table_dir = tmp_path / "t" + os.chmod(table_dir, stat.S_IRUSR | stat.S_IXUSR) + try: + with pytest.raises(Exception) as info: # noqa: B017 # main's error, unchanged + db.flush() + assert not isinstance(info.value, InputValidationError) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + finally: + os.chmod(table_dir, stat.S_IRWXU) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("rid").to_pylist())) == [b"1", b"2"] + + +def test_a_type_coercion_refusal_is_raised_once_through_orcapod(tmp_path: Path) -> None: + """A struct gaining a field with schema evolution off: accepted when added (nothing + Orcapod can tell for certain), refused by Delta at the commit, raised once.""" + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=False) + rows = lambda rid, value: pa.table( # noqa: E731 + {"rid": pa.array([rid], pa.large_binary()), "s": pa.array([value])} + ) + db.add_records(PATH, rows(b"1", {"x": 1}), record_id_column="rid", flush=True) + db.add_records(PATH, rows(b"2", {"x": 2, "y": 3}), record_id_column="rid") + with pytest.raises(InputValidationError, match="type_coercion") as info: + db.flush() + assert "1 rows queued for it were not written" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 842d37d1c..4af6e7292 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -471,14 +471,15 @@ def test_new_struct_field(self, base: Path) -> None: def test_new_struct_field_inside_a_list_is_refused(self, base: Path) -> None: """An append that adds a field to a struct inside a list column would change - the list column's recorded type: refused before anything is buffered, the - stored rows unchanged (deltalake refuses such a commit; ITL-1403).""" + the list column's recorded type: Delta refuses the commit, the flush raises + once and the batch leaves the queue, the stored rows unchanged (ITL-1403).""" db = DeltaTableDatabase(base_path=base) stored_type = pa.large_list(pa.struct([("a", pa.int64())])) append(db, rows([b"a"], pa.array([[{"a": 1}]], stored_type))) evolved = pa.large_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) - with pytest.raises(InputValidationError, match="recorded Arrow type"): + with pytest.raises(InputValidationError, match="Delta refused the commit"): append(db, rows([b"b"], pa.array([[{"a": 2, "b": 3}]], evolved))) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] back = DeltaTableDatabase(base_path=base).get_all_records( PATH, record_id_column="rid" diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index a0a40c82c..a2f86940c 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -52,6 +52,19 @@ def _stored_ids(root: Path) -> list[bytes]: return sorted(cast(list[bytes], table.column("rid").to_pylist())) +def _refused_once_at_flush(db: DeltaTableDatabase) -> InputValidationError: + """The flush is the point of truth (ITL-1403): the rows were accepted when added; + Delta refuses the commit, and the flush raises once, naming the table, Delta's + reason and the rows not written; nothing stays queued; a second flush is a no-op.""" + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + with pytest.raises(InputValidationError, match="Delta refused the commit") as info: + db.flush() + assert "were not written and are no longer queued" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op + return info.value + + def _struct(name: str, value: int) -> Any: return pa.array([{name: value}]) @@ -115,14 +128,16 @@ def _list_of_structs(make_list: Any, *names: str) -> Any: @pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) -def test_a_recorded_column_whose_record_would_change(tmp_path: Path, case: str) -> None: - """Review of PR 504, findings 2 and 6: what the commit would send is compared.""" +def test_a_recorded_column_whose_record_changes_is_refused_once_at_flush( + tmp_path: Path, case: str +) -> None: + """Review of PR 504, findings 2 and 6: Delta refuses the changed record; the flush + raises once and the batch leaves the queue.""" stored, appended = RECORD_CHANGES[case] db = DeltaTableDatabase(tmp_path) _add(db, _rows(b"1", x=stored), flush=True) - with pytest.raises(InputValidationError, match="recorded Arrow type"): - _add(db, _rows(b"2", x=appended)) - db.flush() # nothing was queued + _add(db, _rows(b"2", x=appended)) # accepted when added + _refused_once_at_flush(db) assert _stored_ids(tmp_path) == [b"1"] @@ -285,7 +300,8 @@ def test_names_folded_alike_only_by_delta_are_refused_once( def test_a_storage_typed_column_carrying_another_extension_name(tmp_path: Path) -> None: """A logical identity given as ``ARROW:extension:*`` field metadata on a storage - type is compared as an extension type's is: another name is refused when added.""" + type (CodeRabbit on PR 504): Delta refuses another name at the commit; the flush + raises once and the batch leaves the queue.""" def rows(rid: bytes, name: str) -> pa.Table: field = pa.field( @@ -300,9 +316,8 @@ def rows(rid: bytes, name: str) -> pa.Table: db = DeltaTableDatabase(tmp_path) _add(db, rows(b"1", "itl1403.one"), flush=True) - with pytest.raises(InputValidationError, match="'itl1403.two'"): - _add(db, rows(b"2", "itl1403.two")) - assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + _add(db, rows(b"2", "itl1403.two")) # accepted when added + assert "ARROW:extension:name" in str(_refused_once_at_flush(db)) assert _stored_ids(tmp_path) == [b"1"] @@ -369,7 +384,7 @@ def add_newline(metadata: dict[str, Any]) -> None: "evolution", [False, True], ids=["evolution off", "evolution on"] ) @pytest.mark.parametrize("route", sorted(ROUTES)) -def test_a_real_record_change_is_refused_only_where_the_commit_sends_it( +def test_a_real_record_change_is_refused_at_flush_only_where_delta_refuses_it( tmp_path: Path, route: str, evolution: bool ) -> None: """N2: list items widening to nullable (non-null values). A MERGE that evolves the @@ -387,21 +402,14 @@ def test_a_real_record_change_is_refused_only_where_the_commit_sends_it( } ) - def add() -> None: - db.add_records( - PATH, - rows, - record_id_column="rid", - skip_duplicates=len(ids) == 1, - flush=True, - ) - + db.add_records( + PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + ) # accepted when added, on every route if evolution: - with pytest.raises(InputValidationError, match="recorded Arrow type"): - add() + _refused_once_at_flush(db) assert _stored_ids(tmp_path) == [b"1"] else: - add() + db.flush() assert _stored_ids(tmp_path) == [b"1", b"2"] assert not db._pending_batches # pyright: ignore[reportPrivateUsage] @@ -452,22 +460,16 @@ def test_a_null_column_is_checked_like_any_column( null_field, pa.nulls(len(ids)) ) - def add() -> None: - db.add_records( - PATH, - rows, - record_id_column="rid", - skip_duplicates=len(ids) == 1, - flush=True, - ) - - sends = evolution or len(ids) == 1 - if variant == "another name" and sends: - with pytest.raises(InputValidationError, match="itl1403.not.a.path"): - add() + db.add_records( + PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + ) # accepted when added: the flush is the point of truth + # Delta sends another type's identifier, and refuses it, on an append (every id + # new) and on a MERGE that evolves the schema. + if variant == "another name" and (evolution or len(ids) == 1): + _refused_once_at_flush(db) assert _stored_ids(tmp_path) == [b"1"] else: - add() + db.flush() back = DeltaTableDatabase(tmp_path).get_all_records( PATH, record_id_column="rid" ) @@ -516,3 +518,91 @@ def test_the_backstop_names_the_column_whole(tmp_path: Path, suffix: str) -> Non ) assert info.value.column in (first, second) assert "int64" in str(info.value) + + +# ── Third review of PR 504: the flush is the point of truth ──────────────────────── + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +def test_a_null_with_a_foreign_identifier_after_a_queued_bare_null_is_stored( + tmp_path: Path, evolution: bool +) -> None: + """Third review: the batch the flush commits is what counts. A bare null queued, + then a null carrying a foreign identifier: the concatenated batch keeps the first + field's metadata, so Delta stores all rows; nothing is refused when added.""" + field, column, _ = _path_column() + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1").append_column(field, column), flush=True) + _add(db, _rows(b"2").append_column(pa.field("x", pa.null()), pa.nulls(1))) + foreign = pa.field( + "x", + pa.null(), + metadata={ + "ARROW:extension:name": "review.different", + "ARROW:extension:metadata": b"", + }, + ) + _add(db, _rows(b"3").append_column(foreign, pa.nulls(1))) + db.flush() + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert back is not None + assert back.schema.field("x").type == field.type + assert back.sort_by("rid").column("x").to_pylist() == ["/a", None, None] + + +def test_the_backstop_names_the_nested_field_beside_a_column_of_the_same_name( + tmp_path: Path, +) -> None: + """Third review: Delta's own schema check locates the collision, so the field named + is the nested one, with its type, not a top-level column of the same name.""" + upper, lower = RUST_ONLY_FOLDS[0] + db = DeltaTableDatabase(tmp_path) + for rid, name in ((b"1", upper), (b"2", lower)): + table = pa.table( + { + "rid": pa.array([rid], pa.large_binary()), + lower: [1], + "s": pa.array([{name: "value"}], pa.struct([(name, pa.string())])), + } + ) + db.add_records(PATH, table, record_id_column="rid", schema_handling="merge") + with pytest.raises(UnstorableColumnError) as info: + db.flush() + assert info.value.column == f"s.{lower}" + assert "string" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize( + "change", ["another writer deletes a stored row", "schema evolution turned on"] +) +def test_what_changes_between_add_and_flush_is_decided_at_the_flush( + tmp_path: Path, change: str +) -> None: + """Third review: the commit route can change after the rows are added. Nulls + carrying another logical name, with a stored id among them and schema evolution off, + are a MERGE that keeps the stored schema; when another writer deletes the stored row, + or schema evolution is turned on, the commit sends the foreign identifier and Delta + refuses it. The flush raises once; nothing stays queued.""" + field, column, _ = _path_column() + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=False) + _add(db, _rows(b"1").append_column(field, column), flush=True) + foreign = pa.field( + "x", + pa.null(), + metadata={ + "ARROW:extension:name": "review.different", + "ARROW:extension:metadata": b"", + }, + ) + rows = pa.table({"rid": pa.array([b"1", b"2"], pa.large_binary())}).append_column( + foreign, pa.nulls(2) + ) + db.add_records(PATH, rows, record_id_column="rid") # accepted when added + if change == "another writer deletes a stored row": + deltalake.DeltaTable(str(tmp_path / "t")).delete("__record_id = X'31'") + else: + db.allow_schema_evolution = True + _refused_once_at_flush(db) diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index f5cbe037b..210fbdc06 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -8,8 +8,9 @@ never swapped, never dropped. An append that would CHANGE a recorded column's record (a field added to a recorded -struct) is refused before anything is buffered: deltalake 1.5 and later refuses a commit -that changes a column's field metadata, and the record is field metadata (ITL-1403). A +struct) is refused by Delta at the commit: deltalake 1.5 and later refuses a commit that +changes a column's field metadata, and the record is field metadata. The flush raises it +once and the batch leaves the queue (ITL-1403: the flush is the point of truth). A struct with no record still gains fields, and a new column is still added. A ``null``-typed part with nothing stored at its path (a new struct field, the items of a @@ -157,9 +158,12 @@ def test_an_evolved_struct_keeps_every_value_under_its_name( @pytest.mark.parametrize("flush", [True, False], ids=["flushed", "queued"]) @pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) -def test_an_append_changing_a_recorded_type_is_refused_before_buffering( +def test_an_append_changing_a_recorded_type_is_refused_once_at_flush( tmp_path: pathlib.Path, case: str, flush: bool ) -> None: + """Accepted when added; Delta refuses the changed record at the commit; the flush + raises once, the batch leaves the queue, and a second flush is a no-op (ITL-1403: + the flush is the point of truth).""" first, first_values, appended, appended_values = RECORD_CHANGES[case] db = DeltaTableDatabase(tmp_path) db.add_records( @@ -168,17 +172,16 @@ def test_an_append_changing_a_recorded_type_is_refused_before_buffering( record_id_column="id", flush=True, ) - with pytest.raises( - InputValidationError, - match=r"column 'x': the append would change the column's recorded Arrow type", - ): + with pytest.raises(InputValidationError, match="Delta refused the commit"): db.add_records( PATH, _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)), record_id_column="id", flush=flush, ) - db.flush() # nothing was queued + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") assert back is not None assert back.column("id").to_pylist() == [b"1"] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 041417959..c62f11e09 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1054,15 +1054,23 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps -through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field, nor have a nested nullability change: the record is the -column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit -change, so such an append is refused, naming the column, before anything is queued. A -struct column without a record still gains fields, an append may still add a new column, -and an untyped `null` column takes the stored type. Another logical type over a stored -logical column (another extension name, or the same name with other extension metadata) -is refused the same way. +as nullable afterwards, as Delta stores it. + +On Delta, the commit is the point of truth. When rows are added, only what is certain is +refused, before anything is queued: two names differing only in case, a stored table +deltalake cannot read, another logical type (another +extension name or other extension metadata) over a stored logical column, and a struct +evolution that would put two names differing only in case into one struct. What +deltalake refuses at the commit for the rows themselves (a changed field metadata, a type +it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, +naming the table, Delta's reason and the rows not written; those rows leave the queue, +and the other tables of the flush still commit. Any other failure keeps its rows queued. +So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" +cells below, every list and map included) cannot gain a field when schema evolution is +on, nor have a nested nullability change: the record is the column's field metadata, +which deltalake 1.5 and later does not let a commit change. A struct column without a +record still gains fields, an append may still add a new column, and an untyped `null` +column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py index b98c8b886..6387cb5bb 100644 --- a/tests/test_pipeline/test_delta_refusals_in_jobs.py +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -4,8 +4,9 @@ - finding 6: an operator whose result TYPE depends on its data (list items nullable only when a value exceeds 10) in an operator node that logs (``CacheMode.LOG``): the run - whose result type differs from the stored one fails at the store, instead of - silently changing the table's recorded type. Such an operator is a bug of the + whose result type differs from the stored one fails at the store, where Delta + refuses the commit (the flush raises it once), instead of silently changing the + table's recorded type. Such an operator is a bug of the operator; ITL-1410 is to refuse it at the operator. - a function with output keys ``a`` and ``A`` (legal before) stops at its first write: Delta column names are case-insensitive. @@ -27,7 +28,11 @@ from orcapod.core.sources import ArrowTableSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase -from orcapod.errors import OrcapodDatabaseWriteError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseWriteError, + UnstorableColumnError, +) from orcapod.types import CacheMode @@ -89,9 +94,13 @@ def run(keys: list[int], values: list[int]) -> None: run([1, 2], [1, 2]) # items non-nullable: stored with pytest.raises(OrcapodDatabaseWriteError) as info: run([3, 4], [11, 12]) # items nullable: the recorded type would change - assert "recorded Arrow type" in str( - info.value.__cause__ - ) or "recorded Arrow type" in str(info.value) + # The flush is the point of truth (ITL-1403): Delta refuses the commit, and the + # flush raises it once, as the write error's cause; nothing stays queued. + cause = info.value.__cause__ + assert isinstance(cause, InputValidationError), repr(cause) + assert "Delta refused the commit" in str(cause) + with pytest.raises(OrcapodDatabaseWriteError): + run([3, 4], [11, 12]) # the same rows fail the same way again, never queued @function_pod(output_keys=["a", "A"]) From fef80e1f1ebe2668f6b54ce8484b94c565b40fdf Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:36:56 -0800 Subject: [PATCH 13/23] fix(databases): round-four review of PR 504 (ITL-1403) 2. A duplicate-name refusal is only deltalake's own error, matched where its message starts: a storage error whose path holds the words keeps its rows. 3. A name differing only in case from a stored column is refused only when schema evolution is on; without it Delta leaves the unknown column out. 7. The duplicate backstop locates the colliding struct by its direct children. 1, 5 (pinned) and 4, 6 (documentation): a failed CHECK constraint is taken as permanent; deltalake 1.6 refuses a null in a non-nullable nested field (a narrowing); only the listed refusals are raised once, everything else keeps its rows queued; the add-time unreadable-table refusal is the case-name one. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 23 +++-- docs/reference/database-types.md | 38 ++++--- docs/troubleshooting.md | 21 ++-- src/orcapod/databases/delta_lake_databases.py | 99 ++++++++++++------- .../test_delta_add_time_property.py | 25 +++++ .../test_delta_commit_failures.py | 91 +++++++++++++++++ .../test_delta_refused_before_queueing.py | 27 +++++ tests/test_databases/type_matrix.py | 38 ++++--- 8 files changed, 281 insertions(+), 81 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index fb9d91d2f..69c16555c 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -20,7 +20,8 @@ - `DeltaTableDatabase` refuses two columns, or two fields of one struct, whose names differ only in case (`a` and `A`), before anything is queued (`UnstorableColumnError`, or `InputValidationError` for a column or field added beside a - stored or queued one). Delta column names are case-insensitive, and deltalake 1.5.1 + queued one, or beside a stored one when schema evolution is on: without evolution Delta + leaves an unknown column out, as before). Delta column names are case-insensitive, and deltalake 1.5.1 and later refuses such a table. So a function job with output keys `a` and `A` now stops at its first write, on the sync and the async path alike. Delta folds case as Rust's `to_lowercase` does: for the few code points where Python's `str.lower` differs, @@ -28,19 +29,25 @@ the queue. The in-memory and connector databases still hold such names as two columns. - On Delta the commit is the point of truth. When rows are added, `DeltaTableDatabase` refuses only what it can tell for certain: names differing only in case (above), a - stored table deltalake cannot read, another logical type + stored table deltalake cannot read because two of its names differ only in case, + another logical type (another extension name, or the same name with other extension metadata) over a stored logical column, and a struct evolution that would put two names differing only in case into one struct. Telling more rules up front is ITL-1418. -- What deltalake refuses at the commit for the rows themselves is raised by the flush - once, as `InputValidationError` ("Delta refused the commit to table ...") naming the +- Four kinds of refusal by deltalake at the commit are raised by the flush once, as + `InputValidationError` ("Delta refused the commit to table ...") naming the table, Delta's reason and the number of rows not written. Those rows leave the queue, the other tables of the same flush still commit, and a second flush does nothing. A job fails with `OrcapodDatabaseWriteError` and that cause. The permanent refusals are `SchemaMismatchError`, the duplicate-name error, and a `DeltaError` whose message starts with one of `PERMANENT_DELTA_ERROR_PREFIXES` (`type_coercion`, `Invalid data found`, - `Unsupported CAST`). Any other failure keeps its rows queued as before, so nothing is - dropped on a guess. Until ITL-1412, a job whose result batch is dropped this way can + `Unsupported CAST`): a changed field metadata, two names equal under Delta's case + folding, a type DataFusion cannot insert or cast, and a row Delta finds invalid (a null + in a non-nullable column, a failed CHECK constraint; a constraint whose verdict changes + by chance would have accepted the rows later, and Orcapod writes none). Any other + failure keeps its rows queued as before, so nothing is dropped on a guess: a storage + error, a constraint whose evaluation itself fails, a table unreadable for another + reason. Until ITL-1412, a job whose result batch is dropped this way can keep pipeline records naming those results. - This narrows what a Delta table takes from deltalake 1.5 on: a stored column's field metadata cannot change in a commit. So a column whose Arrow type is recorded cannot @@ -49,6 +56,10 @@ integer, a non-microsecond time type, `float16` or a fixed-size type. A struct column without a record still gains fields, a field may be omitted or reordered, a new column may be added, and an untyped `null` column takes the stored type. +- deltalake 1.6 also refuses, with schema evolution on, a null in a struct field stored + non-nullable, also in a struct without a record: 1.0.2 stored it and made the field + nullable. An append that makes such a field nullable while holding no null in it is + still stored, and the field reads as nullable afterwards. - Tables Orcapod's own nodes write are not concerned: their column types are fixed by their inputs' schemas, and a changed column type changes the table's path. The one exception is an operator whose result type depends on its data rather than on its diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 983ecb2c4..477568fd5 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -79,23 +79,31 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a +null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit +(1.0.2 stored it and made the field nullable). On Delta, the commit is the point of truth. When rows are added, only what is certain is -refused, before anything is queued: two names differing only in case, a stored table -deltalake cannot read, another logical type (another -extension name or other extension metadata) over a stored logical column, and a struct -evolution that would put two names differing only in case into one struct. What -deltalake refuses at the commit for the rows themselves (a changed field metadata, a type -it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, -naming the table, Delta's reason and the rows not written; those rows leave the queue, -and the other tables of the flush still commit. Any other failure keeps its rows queued. -So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" -cells below, every list and map included) cannot gain a field when schema evolution is -on, nor have a nested nullability change: the record is the column's field metadata, -which deltalake 1.5 and later does not let a commit change. A struct column without a -record still gains fields, an append may still add a new column, and an untyped `null` -column takes the stored type. +refused, before anything is queued: two names differing only in case (a name differing +only in case from a stored column only when schema evolution is on, the only case in +which it would enter the stored schema), a stored table deltalake cannot read because two +of its names differ only in case, another logical type (another extension name or other +extension metadata) over a stored logical column, and a struct evolution that would put +two names differing only in case into one struct. Four kinds of refusal by deltalake at +the commit are raised by the flush once, naming the table, Delta's reason and the rows +not written, and those rows leave the queue (the other tables of the flush still commit): +a changed field metadata (`SchemaMismatchError`), two names equal under Delta's case +folding, a type DataFusion cannot insert or cast into the stored one, and a row Delta +finds invalid (a null in a non-nullable column, a failed CHECK constraint). A CHECK +constraint whose verdict changes by chance would accept such rows on a later try; +Orcapod writes none. Any other failure keeps its rows queued and is raised again by the +next flush, as before: a storage error, a constraint whose evaluation itself fails, a +stored table unreadable for another reason. So a column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map included) +cannot gain a field when schema evolution is on, nor have a nested nullability change: +the record is the column's field metadata, which deltalake 1.5 and later does not let a +commit change. A struct column without a record still gains fields, an append may still +add a new column, and an untyped `null` column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index e2dcebf95..893a59e9f 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -214,15 +214,18 @@ saying that Delta reports a name as equal to another's under its case folding is kind of failure. **Cause.** A `DeltaTableDatabase` refuses only what it can tell for certain when rows are -added (names that differ only in case, a stored table deltalake cannot read, another logical type over a stored logical column). Everything -else is decided by deltalake when it commits. The refusals that would happen again at -every flush are raised once: a changed field metadata, which deltalake 1.5 and later -refuses (a struct with a recorded type gaining a field, a list's items becoming -nullable), a type DataFusion cannot insert or cast into the stored one, or a null in a -non-nullable column. The rows are dropped from the queue so that the next flush is not -refused the same way; other tables of the same flush still commit. A failure that may -pass, such as a storage error, keeps its rows queued, and the next flush tries them -again. +added (names that differ only in case, a stored table deltalake cannot read because two of +its names differ only in case, another logical type over a stored logical column). +Everything else is decided by deltalake when it commits. Four kinds of refusal are raised +once, because every later flush would be refused the same way: a changed field metadata, +which deltalake 1.5 and later refuses (a struct with a recorded type gaining a field, a +list's items becoming nullable); two names equal under Delta's case folding; a type +DataFusion cannot insert or cast into the stored one; and a row Delta finds invalid (a +null in a non-nullable column, a failed CHECK constraint). The rows are dropped from the +queue so that the next flush is not refused the same way; other tables of the same flush +still commit. Any other failure keeps its rows queued, and the next flush tries them +again, as before: a storage error, a constraint whose evaluation itself fails, a stored +table unreadable for another reason. **Fix.** Read Delta's reason, correct the rows (or their declared types) and add them again. In a job, running it again computes the same rows and fails the same way until diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index cf36ad012..56e209b59 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -612,13 +612,31 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: # delta-rs reports two names equal under its case folding (Rust ``to_lowercase``). -_DUPLICATE_NAME = re.compile(r"Duplicate field name \(case-insensitive\): '([^']*)'") +# Delta's duplicate-name refusal, as deltalake 1.6.6 words it: at the START of the +# message of deltalake's own error (a bare ``Exception`` or a ``DeltaError``), after +# its ``External error:`` / ``Kernel error:`` / ``Generic DeltaTable error:`` wrappers. +# Never matched inside other text: a table's path may contain the same words +# (review of PR 504, round four). +_DUPLICATE_NAME = re.compile( + r"^(?:(?:External|Kernel|Generic DeltaTable) error: )*" + r"Schema error: Duplicate field name \(case-insensitive\): '(.*)'" +) + + +def _is_delta_error(error: BaseException) -> bool: + """Whether ``error`` is one deltalake raised: a ``DeltaError``, or the bare + ``Exception`` its schema conversion raises.""" + from deltalake.exceptions import DeltaError + + return type(error) is Exception or isinstance(error, DeltaError) def _duplicate_name_in(error: BaseException) -> str | None: """The name delta-rs reports as a case-insensitive duplicate in ``error``'s chain.""" for seen in _error_chain(error): - match = _DUPLICATE_NAME.search(str(seen)) + if not _is_delta_error(seen): + continue + match = _DUPLICATE_NAME.match(str(seen)) if match is not None: return match.group(1) return None @@ -670,7 +688,7 @@ def _permanent_commit_failure(error: BaseException) -> bool: return False if isinstance(error, SchemaMismatchError): return True - if type(error) is Exception and _DUPLICATE_NAME.search(str(error)): + if type(error) is Exception and _DUPLICATE_NAME.match(str(error)): return True if isinstance(error, DeltaError): return str(error).startswith(PERMANENT_DELTA_ERROR_PREFIXES) @@ -680,53 +698,52 @@ def _permanent_commit_failure(error: BaseException) -> bool: def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: """The field of ``schema`` delta-rs names as a duplicate in ``error``'s chain. - Delta's own schema check locates it: a column whose schema Delta refuses on its own - holds the colliding struct fields, and the field is named by its path in that - column (``s.ᲊ``) with its type; otherwise the collision is between top-level - columns. Names come from the schema, the longest one Delta's message quotes, so a - name holding a quote is named whole. ``(the reported text, null)`` when no field - matches. + Delta's own schema check locates it: each struct of the schema (the top level + included) is checked on its direct children alone, each child standing in as an + ``int64``, so a collision deeper down is not seen there. The struct Delta refuses + holds the pair, and the field is named by its path (``outer.right.ᲊ``) with its + type. Names come from the schema, the longest one Delta's message quotes, so a + name holding a quote is named whole. ``(the reported text, null)`` when no struct + is refused. """ messages = [str(seen) for seen in _error_chain(error)] def quoted(field: "pa.Field[Any]") -> bool: return any(f"(case-insensitive): '{field.name}'" in m for m in messages) - for column in schema: + for prefix, children in _structs_of(schema): + probe = pa.schema([pa.field(c.name, pa.int64()) for c in children]) try: - deltalake.Schema.from_arrow(pa.schema([column])) + deltalake.Schema.from_arrow(probe) except Exception as refused: # noqa: BLE001 # only a duplicate name is looked at if _duplicate_name_in(refused) is None: continue - nested = [ - (path, field) - for path, field in _field_paths(column) - if path != column.name and quoted(field) - ] - if nested: - path, field = max(nested, key=lambda item: len(item[1].name)) - return path, field.type - top = [field for field in schema if quoted(field)] - if top: - field = max(top, key=lambda f: len(f.name)) - return field.name, field.type + named = [c for c in children if quoted(c)] + if named: + field = max(named, key=lambda c: len(c.name)) + return prefix + field.name, field.type return _duplicate_name_in(error) or "", pa.null() -def _field_paths(column: "pa.Field[Any]") -> list[tuple[str, "pa.Field[Any]"]]: - """``column`` and every struct field inside it, each with its dotted path.""" - found: list[tuple[str, pa.Field[Any]]] = [] +def _structs_of(schema: pa.Schema) -> list[tuple[str, list["pa.Field[Any]"]]]: + """``(path prefix, direct children)`` of the top level and of every struct inside, + through lists, maps and logical types.""" + found: list[tuple[str, list[pa.Field[Any]]]] = [("", list(schema))] - def visit(path: str, field: "pa.Field[Any]") -> None: - found.append((path, field)) - arrow_type = field.type + def visit(prefix: str, arrow_type: pa.DataType) -> None: if isinstance(arrow_type, pa.ExtensionType): arrow_type = arrow_type.storage_type + if pa.types.is_struct(arrow_type): + children = [arrow_type.field(i) for i in range(arrow_type.num_fields)] + found.append((prefix, children)) + for child in children: + visit(f"{prefix}{child.name}.", child.type) + return for i in range(arrow_type.num_fields): - child = arrow_type.field(i) - visit(f"{path}.{child.name}", child) + visit(prefix, arrow_type.field(i).type) - visit(column.name, column) + for field in schema: + visit(f"{field.name}.", field.type) return found @@ -951,7 +968,7 @@ def _exact_refusal( def _append_refusal( - delta_table: deltalake.DeltaTable, rows: pa.Table + delta_table: deltalake.DeltaTable, rows: pa.Table, schema_evolution: bool ) -> tuple[str, str] | None: """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). @@ -969,6 +986,9 @@ def _append_refusal( Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. + schema_evolution: Whether the database's MERGE evolves the stored schema: + only then does a new column name enter it, so only then is a name + differing only in case from a stored one refused. Returns: ``(column, reason)``, or ``None`` when the rows can be appended. @@ -979,7 +999,10 @@ def _append_refusal( change = _column_change(held[field.name], field) if change is not None: return field.name, change - else: + elif schema_evolution: + # A new name enters the stored schema only when the MERGE evolves it; + # without evolution Delta leaves an unknown column out, as main did + # (review of PR 504, round four). clash = _differ_only_in_case([*held, field.name]) if clash is not None: return field.name, _case_reason(*clash) @@ -2095,7 +2118,9 @@ def _refuse_unmergeable_append( ) from unreadable delta_table = None if delta_table is not None: - refusal = _append_refusal(delta_table, records) + refusal = _append_refusal( + delta_table, records, self.allow_schema_evolution + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -3058,7 +3083,9 @@ def _flush_by_key(self, record_key: str) -> None: else: # The add-time check, against the version just loaded: another # writer may have committed since the rows were buffered (ITL-1334). - refusal = _append_refusal(delta_table, original_table) + refusal = _append_refusal( + delta_table, original_table, self.allow_schema_evolution + ) if refusal is not None: column, reason = refusal raise InputValidationError( diff --git a/tests/test_databases/test_delta_add_time_property.py b/tests/test_databases/test_delta_add_time_property.py index 37d513f98..65ddf84cd 100644 --- a/tests/test_databases/test_delta_add_time_property.py +++ b/tests/test_databases/test_delta_add_time_property.py @@ -183,3 +183,28 @@ def test_the_sweep_covers_every_kind() -> None: assert kinds == {"same", "record", "evolution", "null/layout", "path", "logical"} assert len(VARIANTS) > 100 _ = product # the sweep is the product of the three parameters above + + +@pytest.mark.parametrize("evolve", [False, True], ids=["evolution off", "evolution on"]) +def test_a_name_differing_in_case_from_a_stored_column( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, evolve: bool +) -> None: + """Review of PR 504, round four, finding 3: ``A`` beside a stored ``a``. Without + schema evolution Delta's MERGE leaves the unknown column out and stores the row (as + main did): nothing is refused. With evolution the name would enter the stored + schema, which Delta refuses: refused when added, and Delta refuses it too.""" + initial = pa.table( + {"rid": pa.array([b"1"], pa.large_binary()), "anchor": [1], "a": [11]} + ) + incoming = pa.table( + {"rid": pa.array([b"2"], pa.large_binary()), "anchor": [2], "A": [22]} + ) + live, queued = _run(tmp_path / "live", initial, incoming, evolve) + assert not queued + if not evolve: + assert live == "stored" + return + assert live == "refused when added" + monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) + raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw != "stored" diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index 25a15d368..cd8216543 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -184,3 +184,94 @@ def test_a_type_coercion_refusal_is_raised_once_through_orcapod(tmp_path: Path) assert "1 rows queued for it were not written" in str(info.value) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() # a no-op + + +# ── Review of PR 504, round four ──────────────────────────────────────────────────── + + +def test_a_check_constraint_refusal_is_permanent(tmp_path: Path) -> None: + """Finding 1, the stated limit: deltalake reports a failed CHECK constraint as + ``Invalid data found``, which is taken as permanent: the rows are raised once and + leave the queue. A constraint whose verdict changes by chance (``random()``) would + have accepted them on a later try; Orcapod writes no CHECK constraint, and the error + says the rows were not written.""" + db = DeltaTableDatabase(tmp_path) + rows = lambda rid, x: pa.table( # noqa: E731 + {"rid": pa.array([rid], pa.large_binary()), "x": pa.array([x], pa.int64())} + ) + db.add_records(PATH, rows(b"1", 1), record_id_column="rid", flush=True) + deltalake.DeltaTable(str(tmp_path / "t")).alter.add_constraint( + {"positive": "x > 0"} + ) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, rows(b"2", 0), record_id_column="rid") + with pytest.raises(InputValidationError, match="Invalid data found"): + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="permissions") +def test_a_storage_failure_whose_path_names_a_duplicate_is_not_dropped( + tmp_path: Path, +) -> None: + """Finding 2: only deltalake's own duplicate-name error counts, by where its message + starts. A permission error whose PATH holds the same words keeps its rows queued, + and a later flush, once the store is writable, commits them.""" + parent = tmp_path / "parent" + parent.mkdir() + path = ("parent", "Duplicate field name (case-insensitive): 'x'") + db = DeltaTableDatabase(tmp_path) + rows = pa.table({"rid": pa.array([b"1"], pa.large_binary()), "x": [11]}) + db.add_records(path, rows, record_id_column="rid") + parent.chmod(0o500) + try: + with pytest.raises(Exception) as info: # noqa: B017 # main's error, unchanged + db.flush() + assert not isinstance(info.value, InputValidationError) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + finally: + parent.chmod(0o700) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(path, record_id_column="rid") + assert stored is not None + assert stored.column("x").to_pylist() == [11] + + +@pytest.mark.parametrize("seen", [False, True], ids=["every id new", "a stored id"]) +def test_an_unrecorded_struct_child_loosened_to_nullable_is_refused_once( + tmp_path: Path, seen: bool +) -> None: + """Finding 5, a narrowing of deltalake 1.6: with schema evolution on, a null in a + struct child stored non-nullable (an unrecorded struct) is refused by Delta at the + commit (``Invalid data found``); deltalake 1.0.2 stored it and made the child + nullable. Raised once; nothing stays queued.""" + strict = pa.struct([pa.field("a", pa.int64(), nullable=False)]) + loose = pa.struct([pa.field("a", pa.int64())]) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + pa.table( + { + "rid": pa.array([b"1"], pa.large_binary()), + "s": pa.array([{"a": 1}], strict), + } + ), + record_id_column="rid", + flush=True, + ) + ids = [b"1", b"2"] if seen else [b"2"] + db.add_records( + PATH, + pa.table( + { + "rid": pa.array(ids, pa.large_binary()), + "s": pa.array([{"a": None}] * len(ids), loose), + } + ), + record_id_column="rid", + ) + with pytest.raises(InputValidationError, match="Invalid data found"): + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index a2f86940c..bcb5b9cca 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -606,3 +606,30 @@ def test_what_changes_between_add_and_flush_is_decided_at_the_flush( else: db.allow_schema_evolution = True _refused_once_at_flush(db) + + +def test_the_backstop_names_the_struct_that_holds_the_pair(tmp_path: Path) -> None: + """Review of PR 504, round four, finding 7: two structs under one column, the + colliding pair in ``outer.right`` and an unrelated field of the same name in + ``outer.left``: the field named is the one in the struct Delta refuses.""" + upper, lower = RUST_ONLY_FOLDS[0] + db = DeltaTableDatabase(tmp_path) + for rid, name in ((b"1", upper), (b"2", lower)): + outer = pa.struct( + [ + ("left", pa.struct([(lower, pa.int64())])), + ("right", pa.struct([(name, pa.string())])), + ] + ) + table = pa.table( + { + "rid": pa.array([rid], pa.large_binary()), + "outer": pa.array([{"left": {lower: 1}, "right": {name: "v"}}], outer), + } + ) + db.add_records(PATH, table, record_id_column="rid", schema_handling="merge") + with pytest.raises(UnstorableColumnError) as info: + db.flush() + assert info.value.column == f"outer.right.{lower}" + assert "string" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index c62f11e09..7bb37f072 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1054,23 +1054,31 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a +null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit +(1.0.2 stored it and made the field nullable). On Delta, the commit is the point of truth. When rows are added, only what is certain is -refused, before anything is queued: two names differing only in case, a stored table -deltalake cannot read, another logical type (another -extension name or other extension metadata) over a stored logical column, and a struct -evolution that would put two names differing only in case into one struct. What -deltalake refuses at the commit for the rows themselves (a changed field metadata, a type -it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, -naming the table, Delta's reason and the rows not written; those rows leave the queue, -and the other tables of the flush still commit. Any other failure keeps its rows queued. -So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" -cells below, every list and map included) cannot gain a field when schema evolution is -on, nor have a nested nullability change: the record is the column's field metadata, -which deltalake 1.5 and later does not let a commit change. A struct column without a -record still gains fields, an append may still add a new column, and an untyped `null` -column takes the stored type. +refused, before anything is queued: two names differing only in case (a name differing +only in case from a stored column only when schema evolution is on, the only case in +which it would enter the stored schema), a stored table deltalake cannot read because two +of its names differ only in case, another logical type (another extension name or other +extension metadata) over a stored logical column, and a struct evolution that would put +two names differing only in case into one struct. Four kinds of refusal by deltalake at +the commit are raised by the flush once, naming the table, Delta's reason and the rows +not written, and those rows leave the queue (the other tables of the flush still commit): +a changed field metadata (`SchemaMismatchError`), two names equal under Delta's case +folding, a type DataFusion cannot insert or cast into the stored one, and a row Delta +finds invalid (a null in a non-nullable column, a failed CHECK constraint). A CHECK +constraint whose verdict changes by chance would accept such rows on a later try; +Orcapod writes none. Any other failure keeps its rows queued and is raised again by the +next flush, as before: a storage error, a constraint whose evaluation itself fails, a +stored table unreadable for another reason. So a column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map included) +cannot gain a field when schema evolution is on, nor have a nested nullability change: +the record is the column's field metadata, which deltalake 1.5 and later does not let a +commit change. A struct column without a record still gains fields, an append may still +add a new column, and an untyped `null` column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one From 40df27894ff7d4702a0f24480d936becdb5cdf4f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:55:41 -0800 Subject: [PATCH 14/23] fix(databases): round-five review of PR 504 (ITL-1403) 1. A failed commit is classified on its own error and explicit causes only, never the caller's ambient __context__. 2. The duplicate-name pattern spans a newline in a name (still anchored). 3. A pair formed with a stored column names the batch's column and its type. 4. The troubleshooting page and changelog no longer promise that a CHECK refusal repeats, and name UnstorableColumnError for the duplicate case. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 5 ++- docs/troubleshooting.md | 13 +++--- src/orcapod/databases/delta_lake_databases.py | 18 ++++++--- .../test_delta_commit_failures.py | 40 ++++++++++++++++++- .../test_delta_refused_before_queueing.py | 20 +++++++++- 5 files changed, 81 insertions(+), 15 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index 69c16555c..e854ed960 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -35,8 +35,9 @@ logical column, and a struct evolution that would put two names differing only in case into one struct. Telling more rules up front is ITL-1418. - Four kinds of refusal by deltalake at the commit are raised by the flush once, as - `InputValidationError` ("Delta refused the commit to table ...") naming the - table, Delta's reason and the number of rows not written. Those rows leave the queue, + `InputValidationError` ("Delta refused the commit to table ...") naming the table, + Delta's reason and the number of rows not written, or, for two names equal under + Delta's case folding, as `UnstorableColumnError` naming the column. Those rows leave the queue, the other tables of the same flush still commit, and a second flush does nothing. A job fails with `OrcapodDatabaseWriteError` and that cause. The permanent refusals are `SchemaMismatchError`, the duplicate-name error, and a `DeltaError` whose message starts diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 893a59e9f..b3108ad17 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -216,20 +216,21 @@ kind of failure. **Cause.** A `DeltaTableDatabase` refuses only what it can tell for certain when rows are added (names that differ only in case, a stored table deltalake cannot read because two of its names differ only in case, another logical type over a stored logical column). -Everything else is decided by deltalake when it commits. Four kinds of refusal are raised -once, because every later flush would be refused the same way: a changed field metadata, +Everything else is decided by deltalake when it commits. Four kinds of refusal, which +deltalake makes for the rows themselves, are raised once: a changed field metadata, which deltalake 1.5 and later refuses (a struct with a recorded type gaining a field, a list's items becoming nullable); two names equal under Delta's case folding; a type DataFusion cannot insert or cast into the stored one; and a row Delta finds invalid (a null in a non-nullable column, a failed CHECK constraint). The rows are dropped from the -queue so that the next flush is not refused the same way; other tables of the same flush -still commit. Any other failure keeps its rows queued, and the next flush tries them +queue so that the next flush is not refused for them again; other tables of the same flush +still commit. A CHECK constraint whose verdict changes by chance might have accepted them +later; Orcapod writes no CHECK constraint. Any other failure keeps its rows queued, and the next flush tries them again, as before: a storage error, a constraint whose evaluation itself fails, a stored table unreadable for another reason. **Fix.** Read Delta's reason, correct the rows (or their declared types) and add them -again. In a job, running it again computes the same rows and fails the same way until -then. [Data types per database](reference/database-types.md) lists what each database stores. +again. In a job, running it again computes the same rows and is refused again until +then, except by a CHECK constraint whose verdict changes by chance. [Data types per database](reference/database-types.md) lists what each database stores. ## Problems that give no error diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 56e209b59..e363f9ba0 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -619,7 +619,8 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: # (review of PR 504, round four). _DUPLICATE_NAME = re.compile( r"^(?:(?:External|Kernel|Generic DeltaTable) error: )*" - r"Schema error: Duplicate field name \(case-insensitive\): '(.*)'" + r"Schema error: Duplicate field name \(case-insensitive\): '(.*)'", + re.DOTALL, # a name may hold a newline ) @@ -643,16 +644,17 @@ def _duplicate_name_in(error: BaseException) -> str | None: def _error_chain(error: BaseException) -> list[BaseException]: - """``error`` and its causes and contexts, each once: a chain may loop. + """``error`` and its explicit causes (``raise ... from``), each once. - It does when an error is raised again inside the handler of an error that wraps - it (a lost commit's retry gives up with the error it lost to; ITL-1377). + Never the implicit ``__context__``: that is whatever the caller was handling when + the commit failed, which says nothing about the commit (review of PR 504, round + five). Each error is taken once, so a chain that loops back ends. """ chain: list[BaseException] = [] seen: BaseException | None = error while seen is not None and all(seen is not e for e in chain): chain.append(seen) - seen = seen.__cause__ or seen.__context__ + seen = seen.__cause__ return chain @@ -722,6 +724,12 @@ def quoted(field: "pa.Field[Any]") -> bool: if named: field = max(named, key=lambda c: len(c.name)) return prefix + field.name, field.type + # No struct of the batch is refused on its own: the pair is a batch column and a + # stored column. Name the batch's column, with its type. + top = [field for field in schema if quoted(field)] + if top: + field = max(top, key=lambda f: len(f.name)) + return field.name, field.type return _duplicate_name_in(error) or "", pa.null() diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index cd8216543..6d1c64d4c 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -23,7 +23,7 @@ from orcapod.databases import DeltaTableDatabase from orcapod.databases import delta_lake_databases as dld -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, UnstorableColumnError PATH = ("t",) @@ -275,3 +275,41 @@ def test_an_unrecorded_struct_child_loosened_to_nullable_is_refused_once( db.flush() assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() # a no-op + + +# ── Review of PR 504, round five ──────────────────────────────────────────────────── + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="permissions") +def test_a_failure_inside_an_unrelated_handler_is_classified_on_its_own( + tmp_path: Path, +) -> None: + """Finding 1: a flush called while the caller handles an unrelated Delta + duplicate-name error fails on a permission error. Only the commit's own error and + its explicit causes are classified, never the ambient context: the valid rows stay + queued, and a later flush commits them.""" + parent = tmp_path / "parent" + parent.mkdir() + path = ("parent", "good") + db = DeltaTableDatabase(tmp_path) + rows = pa.table({"rid": pa.array([b"1"], pa.large_binary()), "x": [11]}) + db.add_records(path, rows, record_id_column="rid") + parent.chmod(0o500) + try: + try: + deltalake.Schema.from_arrow( + pa.schema([("x", pa.int64()), ("X", pa.int64())]) + ) + except Exception: # noqa: BLE001 # the unrelated error being handled + with pytest.raises(Exception) as info: # noqa: B017 # main's error + db.flush() + assert not isinstance( + info.value, (InputValidationError, UnstorableColumnError) + ) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + finally: + parent.chmod(0o700) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(path, record_id_column="rid") + assert stored is not None + assert stored.column("x").to_pylist() == [11] diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index bcb5b9cca..860f71428 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -506,7 +506,9 @@ def add(name: str, rid: bytes, flush: bool = False) -> None: assert _stored_ids(tmp_path) == [b"pending", b"stored"] -@pytest.mark.parametrize("suffix", ["'q", " space", '"dq', "(x)", "::y"]) +@pytest.mark.parametrize( + "suffix", ["'q", " space", '"dq', "(x)", "::y", "\nsecond line"] +) def test_the_backstop_names_the_column_whole(tmp_path: Path, suffix: str) -> None: """N5: the column named by the flush's case-folding refusal is the batch's own field, with its type, also when its name holds a quote.""" @@ -633,3 +635,19 @@ def test_the_backstop_names_the_struct_that_holds_the_pair(tmp_path: Path) -> No assert info.value.column == f"outer.right.{lower}" assert "string" in str(info.value) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +def test_the_backstop_names_the_column_colliding_with_a_stored_one( + tmp_path: Path, +) -> None: + """Review of PR 504, round five, finding 3: the pair forms at the commit, between a + stored column and the batch's column (Delta's case folding only). The batch's own + column is named, with its type.""" + upper, lower = RUST_ONLY_FOLDS[0] + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", **{upper: pa.array([1])}), flush=True) + with pytest.raises(UnstorableColumnError) as info: + _add(db, _rows(b"2", **{lower: pa.array([2], pa.int32())}), flush=True) + assert info.value.column == lower + assert "int32" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] From e07ce6708ad9bf51ad53cabca2449af1ffa11db0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 22:17:00 -0800 Subject: [PATCH 15/23] fix(databases): refuse a column name deltalake's MERGE reserves (ITL-1377) Every commit to an existing Delta table is a MERGE. deltalake 1.6.6's MERGE planner names columns of its own; a table holding one at the top level takes its first write and then fails every MERGE, so its rows stayed queued forever (review of PR 511). Like a backtick in a name (ITL-1375), such a name is now refused when rows are added, and for a table that already holds one. MERGE_RESERVED_COLUMNS is taken from the planner's source and pinned by a test that provokes each name, and its near neighbours, with deltalake itself. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1377.md | 10 +- docs/reference/database-types.md | 9 +- src/orcapod/databases/delta_lake_databases.py | 30 +++- .../test_delta_merge_reserved_names.py | 167 ++++++++++++++++++ tests/test_databases/type_matrix.py | 9 +- 5 files changed, 213 insertions(+), 12 deletions(-) create mode 100644 tests/test_databases/test_delta_merge_reserved_names.py diff --git a/changelog.d/ITL-1377.md b/changelog.d/ITL-1377.md index c144c54ea..086835350 100644 --- a/changelog.d/ITL-1377.md +++ b/changelog.d/ITL-1377.md @@ -7,9 +7,13 @@ commits every 100 rows by default) rather than per row, above all to tables holding large values. The stored rows, their values and types, and every hash, record id and stored path are unchanged; only the order of the rows within one commit may differ. -- `DeltaTableDatabase` refuses a top-level column whose name holds a backtick - (`UnstorableColumnError`, before anything is queued), and an append to a table that - holds one: delta-rs cannot MERGE such a table. +- `DeltaTableDatabase` refuses a top-level column whose name holds a backtick, or is + one deltalake's MERGE reserves for its own columns (`__delta_rs_source`, + `__delta_rs_target`, `__delta_rs_operation`, `__delta_rs_delete`, + `__delta_rs_target_insert`, `__delta_rs_target_update`, `__delta_rs_target_delete`, + `__delta_rs_target_copy`; `MERGE_RESERVED_COLUMNS`), with `UnstorableColumnError` + before anything is queued, and an append to a table that already holds one: delta-rs + cannot MERGE such a table, and every commit to an existing table is a MERGE. ### Fixed diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 36dc7efa8..189a0431a 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -66,9 +66,12 @@ Some refusals depend on the values or names as well as the type: field, so a map with such metadata is refused there. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. -- Delta refuses a column whose name holds a backtick, of any type: delta-rs cannot MERGE - such a table, and every commit to an existing Delta table is a MERGE. A table that - already holds such a column takes no further append. A backtick in a nested field's +- Delta refuses a column whose name holds a backtick, or is one deltalake's MERGE reserves + for its own columns (`__delta_rs_source`, `__delta_rs_target`, `__delta_rs_operation`, + `__delta_rs_delete`, `__delta_rs_target_insert`, `__delta_rs_target_update`, + `__delta_rs_target_delete`, `__delta_rs_target_copy`), of any type: delta-rs cannot + MERGE such a table, and every commit to an existing Delta table is a MERGE. A table + that already holds such a column takes no further append. A nested field with such a name is kept. A table holds one type per column. An append whose columns differ from the held ones diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 988dbd110..af85c19a1 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1213,9 +1213,10 @@ def _unmergeable_name_reason(name: str) -> str | None: """Say why Delta cannot commit to a table with a column named ``name``, or ``None``. delta-rs cannot MERGE a table with a top-level column whose name holds a backtick - (``Expected close delimiter``), and every commit to an existing table is a MERGE - (ITL-1377), so such a table would take only its first commit (ITL-1375). A - backtick in a nested field's name is merged as any other. + (``Expected close delimiter``) or is one its MERGE planner reserves + (``MERGE_RESERVED_COLUMNS``), and every commit to an existing table is a MERGE + (ITL-1377), so such a table would take only its first commit (ITL-1375). A nested + field's name is merged as any other. Args: name: A top-level column name. @@ -1228,9 +1229,32 @@ def _unmergeable_name_reason(name: str) -> str | None: "the name holds a backtick, and delta-rs cannot MERGE a table with such a " "column; every commit to an existing Delta table is a MERGE" ) + if name in MERGE_RESERVED_COLUMNS: + return ( + "deltalake's MERGE reserves this name for a column of its own, and every " + "commit to an existing Delta table is a MERGE" + ) return None +# The top-level column names deltalake 1.6.6's MERGE planner uses for columns of its +# own (``crates/core/src/operations/merge/mod.rs``): a table holding one takes its first +# write, and every MERGE into it then fails (an ambiguous or duplicate field). Each is +# provoked with deltalake by a test, so an upgrade that renames or adds one fails it. +MERGE_RESERVED_COLUMNS = frozenset( + { + "__delta_rs_source", + "__delta_rs_target", + "__delta_rs_operation", + "__delta_rs_delete", + "__delta_rs_target_insert", + "__delta_rs_target_update", + "__delta_rs_target_delete", + "__delta_rs_target_copy", + } +) + + def delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: """Say why Delta cannot hold a column, even through a recorded type, or ``None``. diff --git a/tests/test_databases/test_delta_merge_reserved_names.py b/tests/test_databases/test_delta_merge_reserved_names.py new file mode 100644 index 000000000..b34db0d85 --- /dev/null +++ b/tests/test_databases/test_delta_merge_reserved_names.py @@ -0,0 +1,167 @@ +"""Column names deltalake's MERGE reserves are refused on Delta when rows are added. + +Every commit to an existing Delta table is a MERGE (ITL-1377). deltalake 1.6.6's MERGE +planner names columns of its own (``crates/core/src/operations/merge/mod.rs``); a table +holding a top-level column with one of those names takes its first write, and every MERGE +into it then fails, so its rows would stay queued forever (review of PR 511). Like a +backtick in a name (ITL-1375), such a name is refused for certain: when rows are added, +and for a table that already holds one. + +The names are provoked with deltalake itself, so an upgrade that renames, adds or drops +one fails this file. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import deltalake +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.databases.delta_lake_databases import MERGE_RESERVED_COLUMNS +from orcapod.errors import InputValidationError, UnstorableColumnError + +PATH = ("t",) + +# Every ``__delta_rs_*`` name deltalake 1.6.6's merge planner writes, and names near +# them: the ones a MERGE refuses must be exactly ``MERGE_RESERVED_COLUMNS``. +CANDIDATES = sorted( + MERGE_RESERVED_COLUMNS + | { + "__delta_rs_target_row_ordinal_in_file", + "__delta_rs_match_cardinality_class", + "__delta_rs_update_expanded", + "__delta_rs_path", + "__delta_rs_c_x", + "__delta_rs_target_c_x", + "_change_type", + } +) + + +def _merge_fails(root: Path, name: str) -> bool: + deltalake.write_deltalake(str(root), pa.table({"id": [1], name: [1]})) + try: + ( + deltalake.DeltaTable(str(root)) + .merge( + pa.table({"id": [2], name: [2]}), + "t.id = s.id", + source_alias="s", + target_alias="t", + merge_schema=True, + streamed_exec=False, + ) + .when_not_matched_insert_all() + .execute() + ) + except Exception: # noqa: BLE001 # the refusal is the subject + return True + return False + + +@pytest.mark.parametrize("name", CANDIDATES) +def test_deltalake_merge_refuses_exactly_the_reserved_names( + tmp_path: Path, name: str +) -> None: + assert _merge_fails(tmp_path / "t", name) == (name in MERGE_RESERVED_COLUMNS) + + +def _rows(rid: bytes, name: str) -> pa.Table: + return pa.table({"rid": pa.array([rid], pa.large_binary()), name: [1]}) + + +@pytest.mark.parametrize("name", sorted(MERGE_RESERVED_COLUMNS)) +def test_a_reserved_name_is_refused_when_rows_are_added( + tmp_path: Path, name: str +) -> None: + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match="MERGE reserves") as info: + db.add_records(PATH, _rows(b"1", name), record_id_column="rid", flush=True) + assert info.value.column == name + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + assert not (tmp_path / "t" / "_delta_log").exists() + + +@pytest.mark.parametrize("with_column", [True, False], ids=["holding it", "without it"]) +def test_a_stored_table_holding_a_reserved_name_takes_no_append( + tmp_path: Path, with_column: bool +) -> None: + """A table written before this rule: an append is refused when added, naming the + column, with nothing queued, never left to fail at every flush.""" + name = "__delta_rs_source" + deltalake.write_deltalake( + str(tmp_path / "t"), + pa.table( + {"__record_id": pa.array([b"1"], pa.large_binary()), "v": [1], name: [1]} + ), + ) + db = DeltaTableDatabase(tmp_path) + rows = pa.table({"rid": pa.array([b"2"], pa.large_binary()), "v": [2]}) + if with_column: + rows = rows.append_column(name, pa.array([2])) + with pytest.raises( + (InputValidationError, UnstorableColumnError), match="MERGE reserves" + ): + db.add_records(PATH, rows, record_id_column="rid") + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op + + +@function_pod(output_keys=["__delta_rs_source"]) +def _reserved(v: int) -> int: + return v + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_a_job_writing_a_reserved_name_stops_at_its_first_write( + tmp_path: Path, use_async: bool +) -> None: + source = ArrowTableSource( + pa.Table.from_arrays( + [pa.array([1, 2], pa.int64()), pa.array([1, 2], pa.int64())], + schema=pa.schema( + [ + pa.field("k", pa.int64(), nullable=False), + pa.field("v", pa.int64(), nullable=False), + ] + ), + ), + tag_columns=["k"], + tag_only_columns=True, + source_id="s", + record_id_columns=["k"], + ) + with pytest.raises(UnstorableColumnError, match="MERGE reserves"): + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1377", database=database) + with job: + _reserved.pod(source, label="fn") + if use_async: + asyncio.run(job.run_async()) + else: + job.run() + + +def test_a_nested_field_with_a_reserved_name_is_kept(tmp_path: Path) -> None: + """Only a top-level column collides with the planner's columns.""" + db = DeltaTableDatabase(tmp_path) + for rid in (b"1", b"2"): + db.add_records( + PATH, + pa.table( + { + "rid": pa.array([rid], pa.large_binary()), + "s": pa.array([{"__delta_rs_source": 1}]), + } + ), + record_id_column="rid", + flush=True, + ) + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None and stored.num_rows == 2 diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 8943b9418..bbf509b70 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1041,9 +1041,12 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: field, so a map with such metadata is refused there. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. -- Delta refuses a column whose name holds a backtick, of any type: delta-rs cannot MERGE - such a table, and every commit to an existing Delta table is a MERGE. A table that - already holds such a column takes no further append. A backtick in a nested field's +- Delta refuses a column whose name holds a backtick, or is one deltalake's MERGE reserves + for its own columns (`__delta_rs_source`, `__delta_rs_target`, `__delta_rs_operation`, + `__delta_rs_delete`, `__delta_rs_target_insert`, `__delta_rs_target_update`, + `__delta_rs_target_delete`, `__delta_rs_target_copy`), of any type: delta-rs cannot + MERGE such a table, and every commit to an existing Delta table is a MERGE. A table + that already holds such a column takes no further append. A nested field with such a name is kept. A table holds one type per column. An append whose columns differ from the held ones From 8ce9ff7a3cc7ba59db93b212bb33616573e37ddb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 23:53:39 -0800 Subject: [PATCH 16/23] docs(databases): a null in a non-nullable struct field is refused; the table stays strict, no migration yet (ITL-1403) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 10 ++++++---- docs/reference/database-types.md | 8 +++++--- tests/test_databases/type_matrix.py | 8 +++++--- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index e854ed960..14e0506b9 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -57,10 +57,12 @@ integer, a non-microsecond time type, `float16` or a fixed-size type. A struct column without a record still gains fields, a field may be omitted or reordered, a new column may be added, and an untyped `null` column takes the stored type. -- deltalake 1.6 also refuses, with schema evolution on, a null in a struct field stored - non-nullable, also in a struct without a record: 1.0.2 stored it and made the field - nullable. An append that makes such a field nullable while holding no null in it is - still stored, and the field reads as nullable afterwards. +- A null in a struct field stored non-nullable, also in a struct without a record, is + refused at the commit (with schema evolution on), and those rows are not written: the + table stays strict to the type it was first declared with. deltalake 1.0.2 stored the + null and made the field nullable. Moving a stored table to a corrected type (a + migration) is not offered yet. An append that makes such a field nullable while + holding no null in it is still stored, and the field reads as nullable afterwards. - Tables Orcapod's own nodes write are not concerned: their column types are fixed by their inputs' schemas, and a changed column type changes the table's path. The one exception is an operator whose result type depends on its data rather than on its diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index e45a43ae3..0468ac5f7 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,9 +81,11 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a -null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit -(1.0.2 stored it and made the field nullable). +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it. A +null there, in a field stored non-nullable, is refused at the commit and those rows are +not written: the table stays strict to the type it was first declared with (deltalake +1.6; 1.0.2 stored the null and made the field nullable). Moving a stored table to a +corrected type is not offered yet. On Delta, the commit is the point of truth. When rows are added, only what is certain is refused, before anything is queued: two names differing only in case (a name differing diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 78f25ac03..246876cfa 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1085,9 +1085,11 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a -null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit -(1.0.2 stored it and made the field nullable). +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it. A +null there, in a field stored non-nullable, is refused at the commit and those rows are +not written: the table stays strict to the type it was first declared with (deltalake +1.6; 1.0.2 stored the null and made the field nullable). Moving a stored table to a +corrected type is not offered yet. On Delta, the commit is the point of truth. When rows are added, only what is certain is refused, before anything is queued: two names differing only in case (a name differing From 93d3e35e4fee518b4c5c537e613ca09a75b22936 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 00:01:12 -0800 Subject: [PATCH 17/23] test(pipeline): read each Delta commit's added rows from its log entry, an append or a MERGE (ITL-1377) test_mixed_function_commits (from main, PR 509) read operationMetrics ["num_added_rows"], which only a WRITE reports; every later commit is a MERGE here (num_target_rows_inserted). The rows are now the numRecords of each commit's add actions, for both. The cadence assertion is unchanged in strength: the same commits with the same rows per commit as main, the first a WRITE and every later one a MERGE. All 48 cases of the test compared with main 8ee6c6d4 (on deltalake 1.0.2): same cadence and same stored rows in all 36 Delta tables and the job output, except __pf_var_git_hash (the git state of the code's location, "unknown" for main's archived source). Co-Authored-By: Claude Opus 5.5 --- .../test_mixed_function_commits.py | 43 +++++++++++++------ 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 03182fff7..5603f847b 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json from collections import defaultdict from contextlib import AbstractContextManager from pathlib import Path @@ -103,13 +104,33 @@ def run(job: PipelineJob, asynchronous: bool, every: int | None) -> None: def delta_history(root: Path, kind: str) -> list[tuple[str, int]]: - """Read the operation and number of rows added by each Delta commit.""" + """Read the operation and number of rows added by each Delta commit. + + The rows are those of the data files each commit adds (the ``numRecords`` of its + add actions in the log), which holds for an append and a MERGE alike: their + operation metrics name the count differently (ITL-1377 makes every commit to an + existing table a MERGE). + """ (path,) = root.rglob(f"{kind}/_delta_log") - counts = deltalake.DeltaTable(str(path.parent)).history() - return [ - (item["operation"], int(item["operationMetrics"]["num_added_rows"])) - for item in reversed(counts) - ] + table = deltalake.DeltaTable(str(path.parent)) + history = list(reversed(table.history())) + commits: list[tuple[str, int]] = [] + for item in history: + version = int(item["version"]) + entry = path / f"{version:020d}.json" + added = 0 + for line in entry.read_text().splitlines(): + action = json.loads(line) + if "add" in action: + added += int(json.loads(action["add"]["stats"])["numRecords"]) + commits.append((str(item["operation"]), added)) + return commits + + +def commits_of(batches: list[int]) -> list[tuple[str, int]]: + """Main's cadence, one commit per batch, as ITL-1377 commits it: the first creates + the table (WRITE), every later one is a MERGE.""" + return [("WRITE" if i == 0 else "MERGE", rows) for i, rows in enumerate(batches)] @pytest.mark.parametrize("pipeline_kind", ["memory", "delta", "noop", "connector"]) @@ -193,13 +214,9 @@ def observe_promotion(db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: elif pipeline_kind == "connector": assert list(connector.upserts.values()) == [pipeline_batches] else: - assert delta_history(pipeline_root, PIPELINE) == [ - ("WRITE", rows) for rows in pipeline_batches - ] + assert delta_history(pipeline_root, PIPELINE) == commits_of(pipeline_batches) if result_kind == "delta": - assert delta_history(result_root, RESULT) == [ - ("WRITE", rows) for rows in result_batches - ] + assert delta_history(result_root, RESULT) == commits_of(result_batches) elif pipeline_kind == "noop": assert not promotions[RESULT], ( "main leaves separate in-memory results pending in a dry run" @@ -241,7 +258,7 @@ def test_noop_result_store_keeps_pipeline_records( results = NoOpArrowDatabase() job = make_job(db, results) run(job, asynchronous, 3) - assert delta_history(tmp_path, PIPELINE) == [("WRITE", 3), ("WRITE", 2)] + assert delta_history(tmp_path, PIPELINE) == commits_of([3, 2]) assert not results.list_table_paths() assert job.nodes["out"].as_table().num_rows == 5 assert job.nodes["out"].as_source().as_table().num_rows == 0 From 85aa36dbecb4f91fc9c3b461db810b90695cce58 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 09:04:17 -0800 Subject: [PATCH 18/23] fix(databases): a commit conflict or an unloadable table keeps its rows queued; a cached clash is checked again (ITL-1403) Review of PR 504, round seven (CodeRabbit on 8ce9ff7a): - Only an error deltalake raised for the write itself drops a batch for a duplicate name: a CommitFailedError, or a table that cannot be loaded at the flush (OrcapodDatabaseReadError), whose cause names one keeps its rows queued. - A refusal found against a cached handle of the stored table is checked again against the version stored now before the rows are refused. - The flush docstring lists the failures that drop a batch. - Tests: the property sweep reads stored ids back and runs Delta's comparison with every Orcapod check off (only a commit refusal counts); the queued struct-evolution case raises at the flush only; the probe test fails when deltalake accepts the pair; the dropped-result test requires the flush's UnstorableColumnError. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 7 +- src/orcapod/databases/delta_lake_databases.py | 95 ++++++++++++---- .../test_delta_add_time_property.py | 99 +++++++++++++---- .../test_delta_commit_failures.py | 102 +++++++++++++++++- .../test_delta_refused_before_queueing.py | 47 ++++++++ .../test_delta_struct_evolution.py | 18 ++-- .../test_dropped_result_batch.py | 14 ++- 7 files changed, 325 insertions(+), 57 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index 14e0506b9..597ca4c0e 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -33,7 +33,9 @@ another logical type (another extension name, or the same name with other extension metadata) over a stored logical column, and a struct evolution that would put two names differing only in case - into one struct. Telling more rules up front is ITL-1418. + into one struct. A refusal found against a version of the table this database had + cached is checked again against the version stored now, so a name another writer has + since removed does not refuse the rows. Telling more rules up front is ITL-1418. - Four kinds of refusal by deltalake at the commit are raised by the flush once, as `InputValidationError` ("Delta refused the commit to table ...") naming the table, Delta's reason and the number of rows not written, or, for two names equal under @@ -48,7 +50,8 @@ by chance would have accepted the rows later, and Orcapod writes none). Any other failure keeps its rows queued as before, so nothing is dropped on a guess: a storage error, a constraint whose evaluation itself fails, a table unreadable for another - reason. Until ITL-1412, a job whose result batch is dropped this way can + reason, another writer committing first, and a table that cannot be loaded at the + flush, even when Delta's cause names two names equal under its case folding. Until ITL-1412, a job whose result batch is dropped this way can keep pipeline records naming those results. - This narrows what a Delta table takes from deltalake 1.5 on: a stored column's field metadata cannot change in a commit. So a column whose Arrow type is recorded cannot diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index d2ae36699..9af616456 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -650,6 +650,22 @@ def _duplicate_name_in(error: BaseException) -> str | None: return None +def _write_refused_for_duplicate_name(error: BaseException) -> str | None: + """The duplicate name for which Delta refused the write itself, else ``None``. + + Only an error deltalake raised for the write counts, never one that merely carries + a duplicate-name cause: a ``CommitFailedError`` (another writer committed first) + and a table that could not be loaded (``OrcapodDatabaseReadError``, raised before + the write) keep their rows queued for a later flush (review of PR 504, round + seven). + """ + from deltalake.exceptions import CommitFailedError + + if not _is_delta_error(error) or isinstance(error, CommitFailedError): + return None + return _duplicate_name_in(error) + + def _error_chain(error: BaseException) -> list[BaseException]: """``error`` and its explicit causes (``raise ... from``), each once. @@ -2253,27 +2269,25 @@ def _refuse_unmergeable_append( f"{'omit it' if omitted else 'hold a null'}", ) if refusal is None: - try: - delta_table = self._get_delta_table(record_path) - except OrcapodDatabaseReadError as unreadable: - duplicate = _duplicate_name_in(unreadable) - if duplicate is not None: - # Written before deltalake 1.5.1, which no longer reads it: every - # flush would fail the same way, so nothing is queued (ITL-1403). - raise InputValidationError( - f"Cannot append to the stored table " - f"{self._get_table_uri(record_path)!r}: it holds columns whose " - f"names differ only in case (one is {duplicate!r}), which " - "deltalake 1.5.1 and later cannot read: " - f"{_CASE_INSENSITIVE} of them. Nothing was queued. Rebuild the " - "table with distinct names, using a deltalake version before " - "1.5.1 to read it." - ) from unreadable - delta_table = None + delta_table = self._stored_table_for_check(record_path) if delta_table is not None: refusal = _append_refusal( delta_table, records, self.allow_schema_evolution ) + if refusal is not None: + # The handle may be cached from a version another writer has since + # replaced: the rows are refused only if the version stored now + # refuses them too (review of PR 504, round seven). An accepted add + # keeps the cached handle, so it costs no reload. + self._delta_table_cache.pop(self._get_record_key(record_path), None) + delta_table = self._stored_table_for_check(record_path) + refusal = ( + None + if delta_table is None + else _append_refusal( + delta_table, records, self.allow_schema_evolution + ) + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -2282,6 +2296,35 @@ def _refuse_unmergeable_append( "The stored rows are unchanged and nothing was written." ) + def _stored_table_for_check( + self, record_path: tuple[str, ...] + ) -> deltalake.DeltaTable | None: + """The stored table rows added to ``record_path`` are checked against. + + ``None`` when no table is stored, or when it cannot be loaded for a reason the + flush reports (``OrcapodDatabaseReadError``). + + Raises: + InputValidationError: If the stored table holds two names differing only in + case, written before deltalake 1.5.1, which no longer reads it: every + flush would fail the same way, so nothing is queued (ITL-1403). + """ + try: + return self._get_delta_table(record_path) + except OrcapodDatabaseReadError as unreadable: + duplicate = _duplicate_name_in(unreadable) + if duplicate is not None: + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: it holds columns whose " + f"names differ only in case (one is {duplicate!r}), which " + "deltalake 1.5.1 and later cannot read: " + f"{_CASE_INSENSITIVE} of them. Nothing was queued. Rebuild the " + "table with distinct names, using a deltalake version before " + "1.5.1 to read it." + ) from unreadable + return None + def _refuse_declared_nulls( self, record_path: tuple[str, ...], rows: pa.Table ) -> None: @@ -3195,16 +3238,24 @@ def flush(self) -> None: (``_append_refusal``). The batch is dropped from the queue, since every later flush would refuse it too; the error says how many rows were not written. Correct the rows and add them again (ITL-1334). - - Any other failure (a table that cannot be loaded, a failed write): the batch - stays queued, so a later flush tries it again. + - Refused by Delta for the rows themselves (ITL-1403): a ``SchemaMismatchError``, + a ``DeltaError`` whose message starts with one of + ``PERMANENT_DELTA_ERROR_PREFIXES`` (raised as ``InputValidationError``), or two + names equal under Delta's case folding (raised as ``UnstorableColumnError``). + Every later flush would be refused the same way, so the batch is dropped from + the queue and nothing of it is written: correct the rows and add them again. + - Any other failure (a table that cannot be loaded, another writer committing + first, a storage error): the batch stays queued, so a later flush tries it + again. Raises: OrcapodDatabaseReadError: If a batch's existing table could not be loaded. It is raised as itself; every other batch that failed in this flush is added to it as a note. InputValidationError: If no batch failed with ``OrcapodDatabaseReadError`` but a - batch was refused by its stored table (dropped from the queue, above). - Other failed batches are added to it as notes. + batch was refused by its stored table or by Delta for its rows + (dropped from the queue, above). Other failed batches are added to it + as notes. UnstorableColumnError: If neither of the above, but Delta refused a batch for two names equal under its case folding (dropped from the queue: every later flush would refuse it too; ITL-1403). @@ -3438,7 +3489,7 @@ def _flush_by_key(self, record_key: str) -> None: raise refused from e except BaseException as e: permanent = isinstance(e, Exception) and _permanent_commit_failure(e) - reported = _duplicate_name_in(e) if isinstance(e, Exception) else None + reported = _write_refused_for_duplicate_name(e) if permanent and reported is None: # Refused by Delta for the rows themselves: every later flush would be # refused the same way, so the batch leaves the queue, and nothing of diff --git a/tests/test_databases/test_delta_add_time_property.py b/tests/test_databases/test_delta_add_time_property.py index 65ddf84cd..971e48cf4 100644 --- a/tests/test_databases/test_delta_add_time_property.py +++ b/tests/test_databases/test_delta_add_time_property.py @@ -20,7 +20,7 @@ from collections.abc import Iterator from itertools import product from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest @@ -107,7 +107,16 @@ def _variants() -> Iterator[tuple[str, Any, Any, Any, Any]]: VARIANTS = {label: rest for label, *rest in _variants()} -LOGICAL_RULE = {"logical changed", "logical empty to value", "logical value to empty"} +# Refused by the logical-identifier rule (ITL-1371, PR 492), an Orcapod rule by design: +# another logical type identifier's values must not be read as the stored one's, also +# for a null column that carries one. Delta itself may store these rows. +LOGICAL_RULE = { + "logical changed", + "logical empty to value", + "logical value to empty", + "path null readable old", + "path null unknown", +} def _rows(column: Any, ids: list[bytes], field: Any = None) -> pa.Table: @@ -123,22 +132,66 @@ def _rows(column: Any, ids: list[bytes], field: Any = None) -> pa.Table: ) +def _stored_ids(root: Path) -> list[bytes]: + table = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="rid") + return [] if table is None else cast(list[bytes], table.column("rid").to_pylist()) + + def _run( root: Path, initial: pa.Table, incoming: pa.Table, evolve: bool -) -> tuple[str, bool]: - """``(outcome, rows still queued)``: ``stored``, ``refused when added``, or - ``refused at flush``.""" +) -> tuple[str, bool, BaseException | None]: + """``(outcome, rows still queued, the error)``: ``stored``, ``refused when added``, + or ``refused at flush``. ``stored`` is read back through a fresh handle: every + incoming id is stored, each once (review of PR 504, round seven).""" db = DeltaTableDatabase(root, allow_schema_evolution=evolve) db.add_records(PATH, initial, record_id_column="rid", flush=True) + queued = lambda: bool(db._pending_batches) # noqa: E731 # pyright: ignore[reportPrivateUsage] try: db.add_records(PATH, incoming, record_id_column="rid") - except Exception: # noqa: BLE001 # the outcome is the subject - return "refused when added", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] + except Exception as error: # noqa: BLE001 # the outcome is the subject + return "refused when added", queued(), error try: db.flush() - except Exception: # noqa: BLE001 - return "refused at flush", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] - return "stored", False + except Exception as error: # noqa: BLE001 + return "refused at flush", queued(), error + expected = set(cast(list[bytes], initial.column("rid").to_pylist())) | set( + cast(list[bytes], incoming.column("rid").to_pylist()) + ) + stored = _stored_ids(root) + assert sorted(stored) == sorted(expected), f"stored {stored}, not {expected}" + return "stored", queued(), None + + +# Every check Orcapod makes when rows are added, and its stored-table check at the +# flush: switched off, the rows reach Delta's commit, whose verdict is the reference. +ADD_TIME_CHECKS = ( + "require_storable", + "_refuse_untyped_null_columns", + "_refuse_case_clash_with_pending", + "_refuse_changed_attributes", + "_refuse_declared_nulls", + "_refuse_unmergeable_append", +) + + +def _without_orcapod_checks(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ADD_TIME_CHECKS: + monkeypatch.setattr(DeltaTableDatabase, name, lambda *args: None) + monkeypatch.setattr(DeltaTableDatabase, "_identity_refusal", lambda *args: None) + monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) + + +def _refused_by_delta(error: BaseException | None) -> bool: + """Whether the commit itself was refused: an error deltalake raised is in the + chain of the flush's error.""" + from deltalake.exceptions import SchemaMismatchError + + seen: BaseException | None = error + while seen is not None: + if isinstance(seen, SchemaMismatchError) or dld._is_delta_error(seen): # pyright: ignore[reportPrivateUsage] + return True + seen = seen.__cause__ + return False @pytest.fixture(autouse=True) @@ -165,17 +218,19 @@ def test_orcapod_refuses_nothing_delta_stores( initial = _rows(a, [b"1"], field_a) incoming = _rows(b, [b"1", b"2"] if seen else [b"2"], field_b) - live, queued = _run(tmp_path / "live", initial, incoming, evolve) + live, queued, refusal = _run(tmp_path / "live", initial, incoming, evolve) assert not queued, f"{label}: rows still queued after the flush ({live})" - if live == "refused when added" and label not in LOGICAL_RULE: - # Delta's own verdict: the same rows with Orcapod's add-time checks off. - monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) - monkeypatch.setattr( - DeltaTableDatabase, "_refuse_case_clash_with_pending", lambda *args: None + if live == "refused when added" and label in LOGICAL_RULE: + assert "of logical type" in str(refusal), f"{label}: {refusal!r}" + elif live == "refused when added": + # Delta's own verdict: the same rows with every Orcapod check off reach the + # commit, and Delta refuses it. + _without_orcapod_checks(monkeypatch) + raw, _, error = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw == "refused at flush" and _refused_by_delta(error), ( + f"{label}: Orcapod refused rows Delta does not refuse ({raw}: {error!r})" ) - raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) - assert raw != "stored", f"{label}: Orcapod refused rows Delta stores" def test_the_sweep_covers_every_kind() -> None: @@ -199,12 +254,12 @@ def test_a_name_differing_in_case_from_a_stored_column( incoming = pa.table( {"rid": pa.array([b"2"], pa.large_binary()), "anchor": [2], "A": [22]} ) - live, queued = _run(tmp_path / "live", initial, incoming, evolve) + live, queued, _ = _run(tmp_path / "live", initial, incoming, evolve) assert not queued if not evolve: assert live == "stored" return assert live == "refused when added" - monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) - raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) - assert raw != "stored" + _without_orcapod_checks(monkeypatch) + raw, _, error = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw == "refused at flush" and _refused_by_delta(error) diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index 36efd6ca5..80a26be03 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -23,7 +23,14 @@ from orcapod.databases import DeltaTableDatabase from orcapod.databases import delta_lake_databases as dld -from orcapod.errors import InputValidationError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) +from tests.test_databases.test_delta_refused_before_queueing import ( + _legacy_case_only_table, # pyright: ignore[reportPrivateUsage] +) PATH = ("t",) @@ -307,6 +314,10 @@ def test_a_failure_inside_an_unrelated_handler_is_classified_on_its_own( info.value, (InputValidationError, UnstorableColumnError) ) assert db._pending_batches # pyright: ignore[reportPrivateUsage] + else: + # Review of PR 504, round seven: without the probe's error there is no + # ambient context, and the test would prove nothing. + pytest.fail("deltalake accepted two names equal under its case folding") finally: parent.chmod(0o700) db.flush() @@ -363,3 +374,92 @@ def row(rid: bytes, value: int) -> pa.Table: records, record_id_column="rid" ) assert stored is None or stored.num_rows == 0 + + +# ── Review of PR 504, round seven ─────────────────────────────────────────────────── + + +def _rows_of(*ids: bytes, column: str = "x") -> pa.Table: + return pa.table( + {"rid": pa.array(list(ids), pa.large_binary()), column: list(range(len(ids)))} + ) + + +@pytest.mark.parametrize("depth", [1, 2], ids=["its cause", "a cause of its cause"]) +@pytest.mark.parametrize( + "seen", [False, True], ids=["append (every id new)", "MERGE (a stored id)"] +) +def test_a_commit_conflict_carrying_a_duplicate_name_cause_stays_queued( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, seen: bool, depth: int +) -> None: + """Finding: a ``CommitFailedError`` (another writer committed first) whose cause + chain names a duplicate is not a refusal of the rows: the batch stays queued and a + later flush commits it, on the append path and the MERGE path.""" + from deltalake.exceptions import CommitFailedError, DeltaError + + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _rows_of(b"1"), record_id_column="rid", flush=True) + db.add_records( + PATH, + _rows_of(b"1", b"2", b"3") if seen else _rows_of(b"2", b"3"), + record_id_column="rid", + ) + called: list[str] = [] + + def conflict(*args: Any, **kwargs: Any) -> Any: + called.append("merge" if "predicate" in kwargs else "append") + cause: BaseException = Exception( + "Schema error: Duplicate field name (case-insensitive): 'x'" + ) + for _ in range(depth - 1): + outer = DeltaError("Generic DeltaTable error") + outer.__cause__ = cause + cause = outer + raise CommitFailedError("another writer committed first") from cause + + with monkeypatch.context() as patched: + patched.setattr(deltalake, "write_deltalake", conflict) + patched.setattr(deltalake.DeltaTable, "merge", conflict) + with pytest.raises(RuntimeError, match="Failed to flush") as info: + db.flush() + assert called == ["merge" if seen else "append"] + assert isinstance(info.value.__cause__, CommitFailedError) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("rid").to_pylist())) == [ + b"1", + b"2", + b"3", + ] + + +@pytest.mark.parametrize("column", ["a", "c"], ids=["a held name", "a new name"]) +def test_a_target_that_cannot_be_loaded_keeps_its_batch_queued( + tmp_path: Path, column: str +) -> None: + """Finding: rows queued for a table that a writer before deltalake 1.5.1 then + creates with ``a`` and ``A``. The flush fails loading the table, before any write: + the read error is raised as itself, the batch stays queued (a later flush retries + once the table is repaired), and a batch for another table is committed.""" + db = DeltaTableDatabase(tmp_path) + other = ("other",) + db.add_records(PATH, _rows_of(b"2", b"3", column=column), record_id_column="rid") + db.add_records(other, _rows_of(b"7", b"8"), record_id_column="rid") + _legacy_case_only_table(tmp_path) + with pytest.raises(OrcapodDatabaseReadError): + db.flush() + assert set(db._pending_batches) == {"t"} # pyright: ignore[reportPrivateUsage] + stored = DeltaTableDatabase(tmp_path).get_all_records(other, record_id_column="rid") + assert stored is not None and stored.num_rows == 2 + # Repaired: the table is removed, and the queued rows are committed. + import shutil + + shutil.rmtree(tmp_path / "t") + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("rid").to_pylist())) == [b"2", b"3"] diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index e7089e693..57f451a7a 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -656,3 +656,50 @@ def test_the_backstop_names_the_column_colliding_with_a_stored_one( assert info.value.column == lower assert "int32" in str(info.value) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +# (stored, added, what another writer stores instead): a name the added rows hold that +# differs only in case from a stored one, as a column and as a struct field. +STALE_CLASHES: dict[str, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]] = { + "column": ({"a": pa.array([1])}, {"A": pa.array([2])}, {"b": pa.array([1])}), + "struct field": ( + {"s": pa.array([{"a": 1, "c": 1}])}, + {"s": pa.array([{"A": 2, "c": 2}])}, + {"s": pa.array([{"b": 1, "c": 1}])}, + ), +} + + +@pytest.mark.parametrize("replaced", [True, False], ids=["replaced", "unchanged"]) +@pytest.mark.parametrize("kind", sorted(STALE_CLASHES)) +def test_a_clash_with_a_cached_version_is_checked_against_the_stored_one( + tmp_path: Path, kind: str, replaced: bool +) -> None: + """Review of PR 504, round seven: the database holds a cached handle of the table; + another writer replaces the clashing name. The rows are checked again against the + version stored now before they are refused: accepted and stored when the clash is + gone, refused (nothing queued) when it is still there.""" + stored, added, other = STALE_CLASHES[kind] + anchor = {"anchor": pa.array([1])} + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + _add(db, _rows(b"1", **anchor, **stored), flush=True) + db.get_all_records(PATH, record_id_column="rid") # the handle is cached + assert db._delta_table_cache # pyright: ignore[reportPrivateUsage] + if replaced: + current = deltalake.DeltaTable(str(tmp_path / "t")).to_pyarrow_table() + names = [n for n in current.column_names if n not in stored] + deltalake.write_deltalake( + str(tmp_path / "t"), + current.select(names).append_column( + *next(iter((pa.field(k, v.type), v) for k, v in other.items())) + ), + mode="overwrite", + schema_mode="overwrite", + ) + _add(db, _rows(b"2", **anchor, **added), flush=True) + assert _stored_ids(tmp_path) == [b"1", b"2"] + else: + with pytest.raises(InputValidationError, match="differ only in case"): + _add(db, _rows(b"2", **anchor, **added)) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + assert _stored_ids(tmp_path) == [b"1"] diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index 210fbdc06..c15dd6291 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -172,14 +172,16 @@ def test_an_append_changing_a_recorded_type_is_refused_once_at_flush( record_id_column="id", flush=True, ) - with pytest.raises(InputValidationError, match="Delta refused the commit"): - db.add_records( - PATH, - _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)), - record_id_column="id", - flush=flush, - ) - db.flush() + rows = _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)) + if flush: + with pytest.raises(InputValidationError, match="Delta refused the commit"): + db.add_records(PATH, rows, record_id_column="id", flush=True) + else: + # Accepted when added (review of PR 504, round seven): only the flush raises. + db.add_records(PATH, rows, record_id_column="id") + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + with pytest.raises(InputValidationError, match="Delta refused the commit"): + db.flush() assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() # a no-op back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") diff --git a/tests/test_pipeline/test_dropped_result_batch.py b/tests/test_pipeline/test_dropped_result_batch.py index 8fa1d17a9..11220740d 100644 --- a/tests/test_pipeline/test_dropped_result_batch.py +++ b/tests/test_pipeline/test_dropped_result_batch.py @@ -20,6 +20,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase +from orcapod.errors import OrcapodDatabaseWriteError, UnstorableColumnError from orcapod.system_constants import constants UPPER, LOWER = "Ᲊ", "ᲊ" @@ -45,11 +46,20 @@ def test_no_pipeline_record_names_a_dropped_result( job = PipelineJob(name="itl1403", database=database) with job: _pair.pod(source, label="pair") - with pytest.raises(Exception): # noqa: B017 # the run fails: the result batch is dropped + with pytest.raises(OrcapodDatabaseWriteError) as info: if use_async: asyncio.run(job.run_async()) else: job.run() + # The result batch was dropped at the flush, on Delta's own report of the two + # names (review of PR 504, round seven): not refused when added, and no other + # failure. + refusal = info.value.__cause__ + assert isinstance(refusal, UnstorableColumnError) + assert refusal.column == LOWER + assert "under its case folding" in str(refusal) + assert "were not written and are no longer queued" in str(refusal) + assert "_result" in str(refusal) fresh = DeltaTableDatabase(tmp_path) referenced: list[object] = [] for path in fresh.list_table_paths(): @@ -75,7 +85,7 @@ def test_a_result_batch_delta_refuses_withdraws_its_pipeline_records( import deltalake from deltalake.exceptions import SchemaMismatchError - from orcapod.errors import InputValidationError, OrcapodDatabaseWriteError + from orcapod.errors import InputValidationError real_write = deltalake.write_deltalake From ad1c51bc91cbab49eee478127999257942dacbdf Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 09:25:28 -0800 Subject: [PATCH 19/23] fix(databases): key Delta snapshots by table id; refuse a queued id added again; answer CodeRabbit on PR 511 (ITL-1377) Review of PR 511 (CodeRabbit on e07ce670, 0a928d94 and 93d3e35e): - A snapshot of stored ids records the Delta table's own id beside its version: a table removed and created again at version 0 is no longer read with the old table's ids, so a skip_duplicates row is not lost (ITL-1413). - add_records with skip_duplicates=False raises ValueError for an id already queued, as the in-memory database does, instead of storing it twice. - A case clash beside a repeated name is found by position (no KeyError). - Tests: interrupted retries keep the batch queued; a cached table holding a backtick or reserved name is checked again once rebuilt; worker cleanup and bounded barriers; the backtick refusal without a flush; per-file statistics. - The reference page and this PR's changelog fragment state the Delta-only case folding, the retry on the next flush, the narrowing of ITL-1403's statements and the measured commit costs. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1377.md | 25 +++- docs/dev/design_issues/ITL-1371-LI1.md | 6 +- docs/reference/database-types.md | 13 +- src/orcapod/databases/delta_lake_databases.py | 76 +++++++++-- .../test_delta_commit_failures.py | 14 +- .../test_delta_concurrent_writers.py | 124 ++++++++++++++++-- .../test_delta_merge_reserved_names.py | 48 ++++++- .../test_delta_refused_before_queueing.py | 28 ++++ .../test_delta_statistics_columns.py | 14 +- .../test_logical_identity_appends.py | 21 +-- tests/test_databases/type_matrix.py | 13 +- 11 files changed, 323 insertions(+), 59 deletions(-) diff --git a/changelog.d/ITL-1377.md b/changelog.d/ITL-1377.md index 086835350..a0e5223b5 100644 --- a/changelog.d/ITL-1377.md +++ b/changelog.d/ITL-1377.md @@ -5,15 +5,26 @@ the table was loaded. The flush then loads the table again and retries. A commit re-reads the stored rows, so its cost grows with the table: commit in batches (a job commits every 100 rows by default) rather than per row, above all to tables holding - large values. The stored rows, their values and types, and every hash, record id and - stored path are unchanged; only the order of the rows within one commit may differ. + large values. Measured against the append it replaces, on a local disk: a one-row + commit to a 10k-row table took about 16 ms instead of 5 ms, to a 1 GB table about + 66 ms instead of 7 ms, and to a 5 GB table about 1.2 s instead of 8 ms; 2,000 one-row + commits took 451 s instead of 42 s (with deltalake 1.0.2 this MERGE took 249 s: per-row + MERGEs on a table of about 2,000 files are slower on deltalake 1.6.6, so the faster + commits ITL-1403 reports are those it measured, not these). On a cloud store each + commit reads every data file of the table. The stored rows, their values and types, + and every hash, record id and stored path are unchanged; only the order of the rows + within one commit may differ. - `DeltaTableDatabase` refuses a top-level column whose name holds a backtick, or is one deltalake's MERGE reserves for its own columns (`__delta_rs_source`, `__delta_rs_target`, `__delta_rs_operation`, `__delta_rs_delete`, `__delta_rs_target_insert`, `__delta_rs_target_update`, `__delta_rs_target_delete`, `__delta_rs_target_copy`; `MERGE_RESERVED_COLUMNS`), with `UnstorableColumnError` before anything is queued, and an append to a table that already holds one: delta-rs - cannot MERGE such a table, and every commit to an existing table is a MERGE. + cannot MERGE such a table, and every commit to an existing table is a MERGE. These + names add to the refusals made when rows are added that ITL-1403 lists, and narrow + its statement that a table written by either deltalake version is appended to by the + other: a table holding such a top-level name, written by any version, takes no + further append. ### Fixed @@ -23,3 +34,11 @@ one stored: each id is stored once. Writers committing other ids all commit. - Two writers creating the same Delta table at once could lose the earlier writer's rows. The later create now fails and is retried as a MERGE. +- `DeltaTableDatabase.add_records` with `skip_duplicates=False` queued a row whose id + was already queued, and the flush stored both. It now raises `ValueError`, as the + in-memory database does. +- A table removed and created again by another writer starts over at version 0: a + `DeltaTableDatabase` that had read the old table could take the new one's ids for the + old one's at the same version, and skip a row with `skip_duplicates=True` as stored + when it was not (ITL-1413). The ids read are now tied to the Delta table's own id as well as its + version. diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 62dd996d0..eb89dda41 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -82,8 +82,10 @@ loaded, before anything is written. Two differences remain. One writes nothing e 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 +held handle's duplicate scan reused the old version's cached ids, so an old id was skipped as +a duplicate and a new one could be written twice. Fixed by ITL-1377 (review of PR 511): the +cached ids are keyed by the Delta table's own id as well as its version, and every commit to +an existing table is a MERGE. 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). diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 3eeba9e83..c7dd0063e 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -107,9 +107,11 @@ a changed field metadata (`SchemaMismatchError`), two names equal under Delta's folding, a type DataFusion cannot insert or cast into the stored one, and a row Delta finds invalid (a null in a non-nullable column, a failed CHECK constraint). A CHECK constraint whose verdict changes by chance would accept such rows on a later try; -Orcapod writes none. Any other failure keeps its rows queued and is raised again by the -next flush, as before: a storage error, a constraint whose evaluation itself fails, a -stored table unreadable for another reason. So a column whose Arrow type Delta keeps +Orcapod writes none. Any other failure keeps its rows queued, as before, and the next +flush tries them again: it writes them if the cause has passed (storage recovered, +another writer no longer committing first) and raises only if that try fails too: a +storage error, a constraint whose evaluation itself fails, a stored table that cannot be +loaded. So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" cells below, every list and map included) cannot gain a field when schema evolution is on, nor have a nested nullability change: the record is the column's field metadata, which deltalake 1.5 and later does not let a @@ -120,7 +122,10 @@ An append matches columns by name, exactly as Arrow matches them (`a` and `A` ar columns), never by position. Delta alone refuses two columns, or two fields of one struct, whose names differ only in case: Delta column names are case-insensitive, so such a table, or an append that would make one, is refused naming both, before anything -is queued. Rows whose columns are the held table's columns in another +is queued, when Python's `str.lower` finds the pair. Delta folds case as Rust's +`to_lowercase` does, which differs for a few code points (U+1C89 and U+1C8A, for +example): such a pair is found by Delta only, at the flush, which raises once naming the +column (`UnstorableColumnError`), and those rows leave the queue. Rows whose columns are the held table's columns in another order, each field equal to the held one (the same type at every depth, the same logical type, the same field attributes), are put in the held order, whether the table was flushed in between or not. The in-memory database matches them to the rows still pending, diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index e05325bd0..c2685a35c 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -622,11 +622,22 @@ def _merged_record( def _differ_only_in_case(names: list[str]) -> tuple[str, str] | None: """The first two of ``names`` that differ only in case, or ``None``.""" + position = _case_clash_position(names) + if position is None: + return None + second = names[position] + first = next(n for n in names if n.lower() == second.lower() and n != second) + return first, second + + +def _case_clash_position(names: list[str]) -> int | None: + """The position in ``names`` of the first name that differs only in case from an + earlier one, or ``None``. A position, since the name itself may be repeated.""" seen: dict[str, str] = {} - for name in names: + for position, name in enumerate(names): other = seen.setdefault(name.lower(), name) if other != name: - return other, name + return position return None @@ -1632,6 +1643,12 @@ def _database_error_to_raise(errors: list[Exception]) -> Exception | None: return None +def _table_id(delta_table: deltalake.DeltaTable) -> str: + """The Delta table's own id, which a table created again at the same path does + not share.""" + return str(delta_table.metadata().id) + + @dataclass class _CommittedSnapshot: """What one version of a stored Delta table holds, kept in memory (ITL-919). @@ -1642,6 +1659,10 @@ class _CommittedSnapshot: Attributes: version: The table version described. + table_id: The Delta table's own id (``metadata().id``, set when the table is + created), or ``""`` for a table this database has just created. A + version describes one table only: a table removed and created again + starts over at version 0 with another id (review of PR 511). ids: The stored record ids (never null), or ``None`` until first needed. rows: Indexes over every stored row, read exactly as ``get_all_records`` reads them, or ``None`` until first needed. @@ -1653,6 +1674,7 @@ class _CommittedSnapshot: """ version: int + table_id: str = "" ids: set[bytes] | None = None rows: KeyIndex | None = None files: frozenset[str] = frozenset() @@ -2100,9 +2122,14 @@ def _snapshot( The snapshot for the table's version; its parts are read on first use. """ version = delta_table.version() + table_id = _table_id(delta_table) snapshot = self._snapshots.get(record_key) - if snapshot is None or snapshot.version != version: - snapshot = _CommittedSnapshot(version) + if ( + snapshot is None + or snapshot.version != version + or snapshot.table_id != table_id + ): + snapshot = _CommittedSnapshot(version, table_id) self._snapshots[record_key] = snapshot return snapshot @@ -2249,12 +2276,16 @@ def require_storable(self, schema: pa.Schema) -> None: UnstorableColumnError: For the first column Delta cannot hold, naming the column, its Arrow type and Delta's reason. """ - clash = _differ_only_in_case(schema.names) - if clash is not None: + position = _case_clash_position(schema.names) + if position is not None: + # By position: the name may be repeated (``a``, ``A``, ``A``), and a + # lookup by a repeated name raises (review of PR 511). + clash = _differ_only_in_case(schema.names) + assert clash is not None raise UnstorableColumnError( database_kind=type(self).__name__, column=clash[1], - arrow_type=schema.field(clash[1]).type, + arrow_type=schema.field(position).type, reason=_case_reason(*clash), ) for field in schema: @@ -2701,8 +2732,24 @@ def add_records( logger.debug("All records were duplicates, nothing to insert") return None else: - # Check for conflicts - insert never allows duplicates when skip_duplicates=False - # self._check_all_conflicts(record_path, deduplicated_table) + # An id already queued would be committed twice: the commit inserts the + # ids the stored table does not hold, and both queued rows are such ids. + # Refused as the in-memory database refuses it (review of PR 511). + queued = self._pending_record_ids.get(self._get_record_key(record_path)) + if queued: + again = { + rid + for rid in cast( + list[bytes], + deduplicated_table[self.RECORD_ID_COLUMN].to_pylist(), + ) + if rid in queued + } + if again: + raise ValueError( + f"Records with IDs {again} already exist in the pending " + "batch. Use skip_duplicates=True to skip them." + ) filtered_table = deduplicated_table # Against the rows queued, on the rows that remain once duplicates are @@ -3796,17 +3843,19 @@ def _snapshot_for_commit( OrcapodDatabaseReadError: If the stored ids could not be read. """ cached = self._snapshots.get(record_key) + table_id = _table_id(delta_table) if ( cached is not None and cached.ids is not None and cached.version == delta_table.version() + and cached.table_id == table_id ): return cached try: ids = self._scan_ids(delta_table) except Exception as e: raise OrcapodDatabaseReadError(table_uri, abs_path_components) from e - return _CommittedSnapshot(delta_table.version(), ids=ids) + return _CommittedSnapshot(delta_table.version(), table_id, ids=ids) def _extend_snapshot( self, @@ -3835,10 +3884,11 @@ def _extend_snapshot( The new snapshot. """ version = committed.version() - if version != base.version + 1: - return _CommittedSnapshot(version) + table_id = _table_id(committed) + if version != base.version + 1 or base.table_id not in ("", table_id): + return _CommittedSnapshot(version, table_id) assert base.ids is not None - snapshot = _CommittedSnapshot(version, ids=base.ids | inserted_ids) + snapshot = _CommittedSnapshot(version, table_id, ids=base.ids | inserted_ids) if ( base.rows is None or base.dataset_schema is None diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index 80a26be03..4cebc60ab 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -386,15 +386,15 @@ def _rows_of(*ids: bytes, column: str = "x") -> pa.Table: @pytest.mark.parametrize("depth", [1, 2], ids=["its cause", "a cause of its cause"]) -@pytest.mark.parametrize( - "seen", [False, True], ids=["append (every id new)", "MERGE (a stored id)"] -) +@pytest.mark.parametrize("seen", [False, True], ids=["every id new", "a stored id"]) def test_a_commit_conflict_carrying_a_duplicate_name_cause_stays_queued( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, seen: bool, depth: int ) -> None: """Finding: a ``CommitFailedError`` (another writer committed first) whose cause - chain names a duplicate is not a refusal of the rows: the batch stays queued and a - later flush commits it, on the append path and the MERGE path.""" + chain names a duplicate is not a refusal of the rows: the commit is retried (every + commit to an existing table is a MERGE, ITL-1377), and after the last attempt the + batch stays queued and a later flush commits it, every id new or a stored id + among them.""" from deltalake.exceptions import CommitFailedError, DeltaError db = DeltaTableDatabase(tmp_path) @@ -418,11 +418,13 @@ def conflict(*args: Any, **kwargs: Any) -> Any: raise CommitFailedError("another writer committed first") from cause with monkeypatch.context() as patched: + patched.setattr(dld, "_COMMIT_ATTEMPTS", 3) + patched.setattr(dld, "_sleep_before_retry", lambda attempt: None) patched.setattr(deltalake, "write_deltalake", conflict) patched.setattr(deltalake.DeltaTable, "merge", conflict) with pytest.raises(RuntimeError, match="Failed to flush") as info: db.flush() - assert called == ["merge" if seen else "append"] + assert called == ["merge"] * 3 assert isinstance(info.value.__cause__, CommitFailedError) assert db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() diff --git a/tests/test_databases/test_delta_concurrent_writers.py b/tests/test_databases/test_delta_concurrent_writers.py index 01df46ec6..61afc0ef2 100644 --- a/tests/test_databases/test_delta_concurrent_writers.py +++ b/tests/test_databases/test_delta_concurrent_writers.py @@ -256,11 +256,19 @@ def test_writers_in_other_processes_store_each_id_once(tmp_path: Path) -> None: context.Process(target=_write_ids, args=(str(tmp_path), start, ids, value)) for value in (1, 2, 3) ] - for process in processes: - process.start() - for process in processes: - process.join(timeout=120) - assert process.exitcode == 0 + try: + for process in processes: + process.start() + for process in processes: + process.join(timeout=120) + assert [process.exitcode for process in processes] == [0, 0, 0] + finally: + # A worker still running after the timeout never outlives the test + # (review of PR 511). + for process in processes: + if process.is_alive(): + process.terminate() + process.join() stored = _stored(tmp_path) assert [rid for rid, _ in stored] == [bytes([n]) for n in ids] @@ -280,10 +288,12 @@ def test_writers_creating_one_table_at_once_store_an_id_once(tmp_path: Path) -> errors: list[BaseException] = [] def write(value: int) -> None: - db = DeltaTableDatabase(root) - db.add_records(PATH, _records(1, value), record_id_column="rid") - start.wait() + # A writer that fails before the barrier reports it, and the barrier's + # timeout lets the others report theirs (review of PR 511). try: + db = DeltaTableDatabase(root) + db.add_records(PATH, _records(1, value), record_id_column="rid") + start.wait(timeout=60) db.flush() except BaseException as e: # noqa: BLE001 # reported below errors.append(e) @@ -292,7 +302,8 @@ def write(value: int) -> None: for thread in threads: thread.start() for thread in threads: - thread.join() + thread.join(timeout=120) + assert not any(thread.is_alive() for thread in threads) assert errors == [] stored = _stored(root) assert [rid for rid, _ in stored] == [b"\x01"], trial @@ -334,3 +345,98 @@ def always_lose(*args: Any) -> Any: records, record_id_column="rid" ) assert stored is None or stored.num_rows == 0 + + +@pytest.mark.parametrize( + "interrupted", ["the wait", "the commit"], ids=["in the wait", "in the commit"] +) +def test_an_interrupted_retry_keeps_the_batch_queued( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, interrupted: str +) -> None: + """Review of PR 511: a ``KeyboardInterrupt`` during the wait between attempts, or + during an attempt, after a lost commit. A lost attempt wrote nothing: the + interrupt propagates, the batch and its ids are queued again (with a batch of + another table, untouched), and a later flush commits every row once.""" + db = DeltaTableDatabase(tmp_path) + other = ("other",) + db.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) + db.add_records(PATH, _records(2, 20), record_id_column="rid") + db.add_records(PATH, _records(3, 30), record_id_column="rid") + real_merge = deltalake.DeltaTable.merge + attempts: list[int] = [] + + def lose(self: Any, *args: Any, **kwargs: Any) -> Any: + attempts.append(1) + if interrupted == "the commit" and len(attempts) > 1: + raise KeyboardInterrupt + raise CommitFailedError("another writer committed first") + + def interrupt(attempt: int) -> None: + raise KeyboardInterrupt + + with monkeypatch.context() as patched: + patched.setattr(deltalake.DeltaTable, "merge", lose) + if interrupted == "the wait": + patched.setattr(delta_lake_databases, "_sleep_before_retry", interrupt) + with pytest.raises(KeyboardInterrupt): + db.flush_batch(PATH) + assert deltalake.DeltaTable.merge is real_merge + pending = db._pending_batches # pyright: ignore[reportPrivateUsage] + assert pending["t"].num_rows == 2 + assert db._pending_record_ids["t"] == {b"\x02", b"\x03"} # pyright: ignore[reportPrivateUsage] + db.add_records(other, _records(4, 40), record_id_column="rid") + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + assert _stored(tmp_path) == [(b"\x01", 10), (b"\x02", 20), (b"\x03", 30)] + + +@pytest.mark.parametrize("commits", [1, 2], ids=["same version", "another version"]) +def test_a_table_created_again_is_not_read_with_the_old_tables_ids( + tmp_path: Path, commits: int +) -> None: + """Review of PR 511: another writer removes the table and creates it again, so it + starts over at version 0. A commit of this database onto it must not take the old + table's ids for the new one's: a later ``skip_duplicates`` add of an id only the + old table held is stored, and one the new table holds is skipped.""" + import shutil + + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) + assert db.get_record_by_id(PATH, b"\x01") is not None # its ids are read + shutil.rmtree(tmp_path / "t") + other = DeltaTableDatabase(tmp_path) + for n in range(2, 2 + commits): + other.add_records(PATH, _records(n, 20), record_id_column="rid", flush=True) + db.add_records(PATH, _records(9, 90), record_id_column="rid", flush=True) + both = pa.concat_tables([_records(1, 11), _records(2, 21)]) + db.add_records(PATH, both, record_id_column="rid", skip_duplicates=True, flush=True) + assert _stored(tmp_path) == sorted( + [(b"\x01", 11), (b"\x09", 90)] + + [(bytes([n]), 20) for n in range(2, 2 + commits)] + ) + + +@pytest.mark.parametrize("stored", [False, True], ids=["new table", "stored table"]) +def test_an_id_already_queued_is_refused_without_skip_duplicates( + tmp_path: Path, stored: bool +) -> None: + """Review of PR 511: an id queued, added again without ``skip_duplicates``, would + be committed twice (both rows are ids the stored table does not hold). It is + refused with ``ValueError``, as the in-memory database refuses it, and nothing of + that add is queued; with ``skip_duplicates`` the queued row is kept.""" + db = DeltaTableDatabase(tmp_path) + if stored: + db.add_records(PATH, _records(9, 90), record_id_column="rid", flush=True) + db.add_records( + PATH, + pa.concat_tables([_records(1, 10), _records(2, 20)]), + record_id_column="rid", + ) + again = pa.concat_tables([_records(3, 30), _records(2, 21)]) + with pytest.raises(ValueError, match="already exist in the pending batch"): + db.add_records(PATH, again, record_id_column="rid") + assert db._pending_batches["t"].num_rows == 2 # pyright: ignore[reportPrivateUsage] + db.add_records(PATH, again, record_id_column="rid", skip_duplicates=True) + db.flush() + expected = [(b"\x01", 10), (b"\x02", 20), (b"\x03", 30)] + assert _stored(tmp_path) == sorted(expected + ([(b"\x09", 90)] if stored else [])) diff --git a/tests/test_databases/test_delta_merge_reserved_names.py b/tests/test_databases/test_delta_merge_reserved_names.py index b34db0d85..f39b4f42b 100644 --- a/tests/test_databases/test_delta_merge_reserved_names.py +++ b/tests/test_databases/test_delta_merge_reserved_names.py @@ -7,14 +7,18 @@ backtick in a name (ITL-1375), such a name is refused for certain: when rows are added, and for a table that already holds one. -The names are provoked with deltalake itself, so an upgrade that renames, adds or drops -one fails this file. +The names are provoked with deltalake itself, for the names ``CANDIDATES`` enumerates +only: an upgrade that drops or renames one of them, or starts reserving another of them, +fails this file. A name an upgrade newly reserves outside that list is not detected here; +``CANDIDATES`` is read from deltalake 1.6.6's merge planner and is to be read again on an +upgrade. """ from __future__ import annotations import asyncio from pathlib import Path +from typing import cast import deltalake import pyarrow as pa @@ -29,7 +33,8 @@ PATH = ("t",) # Every ``__delta_rs_*`` name deltalake 1.6.6's merge planner writes, and names near -# them: the ones a MERGE refuses must be exactly ``MERGE_RESERVED_COLUMNS``. +# them: the ones a MERGE refuses must be exactly ``MERGE_RESERVED_COLUMNS``. Only these +# names are probed (review of PR 511). CANDIDATES = sorted( MERGE_RESERVED_COLUMNS | { @@ -165,3 +170,40 @@ def test_a_nested_field_with_a_reserved_name_is_kept(tmp_path: Path) -> None: ) stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") assert stored is not None and stored.num_rows == 2 + + +@pytest.mark.parametrize("rebuilt", [True, False], ids=["rebuilt", "unchanged"]) +@pytest.mark.parametrize("name", ["a`b", "__delta_rs_source"]) +def test_a_cached_table_holding_such_a_name_is_checked_again_when_rebuilt( + tmp_path: Path, name: str, rebuilt: bool +) -> None: + """Review of PR 511: the database cached a handle of a table holding such a name; + the table is rebuilt without it. The refusal is checked again against the version + stored now: the rows are stored. Unchanged, they are still refused, nothing + queued.""" + root = str(tmp_path / "t") + deltalake.write_deltalake( + root, + pa.table( + {"__record_id": pa.array([b"1"], pa.large_binary()), "v": [1], name: [1]} + ), + ) + db = DeltaTableDatabase(tmp_path) + db.get_all_records(PATH) # the handle is cached + assert db._delta_table_cache # pyright: ignore[reportPrivateUsage] + rows = pa.table({"rid": pa.array([b"2", b"3"], pa.large_binary()), "v": [2, 3]}) + if not rebuilt: + with pytest.raises(InputValidationError, match="Delta|MERGE|backtick"): + db.add_records(PATH, rows, record_id_column="rid") + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + return + current = deltalake.DeltaTable(root).to_pyarrow_table().drop_columns([name]) + deltalake.write_deltalake(root, current, mode="overwrite", schema_mode="overwrite") + db.add_records(PATH, rows, record_id_column="rid", flush=True) + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("rid").to_pylist())) == [ + b"1", + b"2", + b"3", + ] diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index d62ca8672..0d8679a96 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -703,3 +703,31 @@ def test_a_clash_with_a_cached_version_is_checked_against_the_stored_one( _add(db, _rows(b"2", **anchor, **added)) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] assert _stored_ids(tmp_path) == [b"1"] + + +@pytest.mark.parametrize( + "names", + [["a", "A", "A"], ["A", "a", "a"], ["a", "b", "A", "b"]], + ids=lambda names: "".join(names), +) +def test_a_case_clash_beside_a_repeated_name_names_the_column( + tmp_path: Path, names: list[str] +) -> None: + """Review of PR 511: with a name repeated, the case clash is still refused with + ``UnstorableColumnError``, naming the column and the type at its position.""" + types = [pa.int8(), pa.int16(), pa.int32(), pa.int64()][: len(names)] + table = pa.Table.from_arrays( + [pa.array([b"1"], pa.large_binary())] + [pa.array([1], t) for t in types], + names=["rid", *names], + ) + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError) as info: + _add(db, table) + position = next( + i + for i, n in enumerate(names) + if any(m.lower() == n.lower() and m != n for m in names[:i]) + ) + assert info.value.column == names[position] + assert str(types[position]) in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index f8179d9ed..8864a220b 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -383,13 +383,15 @@ def test_backtick_name_is_refused_before_anything_is_queued( """delta-rs cannot MERGE such a table, and every later commit is one (ITL-1375).""" db = DeltaTableDatabase(tmp_path) with pytest.raises(UnstorableColumnError) as info: + # No flush: the refusal is when the rows are added (review of PR 511). db.add_records( PATH, rows(range(0, 3)).append_column("x`y", pa.array([0, 1, 2], pa.int64())), - flush=True, ) assert info.value.column == "x`y" assert "backtick" in info.value.reason + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() assert not (tmp_path / "t" / "_delta_log").exists() # A backtick inside a nested field's name is merged as any other. nested = pa.array([{"x`y": i} for i in range(3)]) @@ -499,11 +501,11 @@ def test_existing_table_without_the_property_is_unaltered( # deltalake 1.6 no longer logs the binary-column warning (1.0.2 did); what # the property was about stays: no min/max is kept for a binary column. assert configuration(tmp_path / "t") == {} - added = pa.table( - deltalake.DeltaTable(str(tmp_path / "t")).get_add_actions(flatten=True) - ) - assert "min.v" in added.column_names - assert not any(n.startswith("min.h") for n in added.column_names) + # Every data file, those the two MERGEs added included, has a minimum for + # ``v`` and none for the binary ``h`` (review of PR 511). + per_file = columns_with_statistics(tmp_path / "t") + assert len(per_file) >= 3 + assert all("v" in stats and "h" not in stats for stats in per_file) assert stored_ids(db) == sorted(f"id{i}".encode() for i in range(30)) def test_plain_deltalake_appends_to_a_table_with_the_property( diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index fad066234..3efdb8c1b 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -2316,16 +2316,15 @@ def test_delta_recorded_type_decides_a_child_the_log_keeps_plain( 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( +def test_delta_handle_after_delete_and_recreate_reads_the_new_tables_ids( tmp_path: Path, ) -> None: - """Pins a pre-existing limit (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). An id of the new table is no longer written again: - every commit to an existing table is a MERGE, which decides against the table - as it is (ITL-1377); on main it was stored twice.""" + """Round 5, finding 2 (ITL-1413), fixed by the review of PR 511: a held handle + whose table was deleted and recreated at the same path, at the same Delta version, + no longer reuses the old table's cached ids. Snapshots are keyed by the Delta + table's own id as well as its version, so an old id the new table lacks is stored, + and an id of the new table is skipped (every commit to an existing table is a + MERGE, ITL-1377).""" import shutil import deltalake @@ -2360,7 +2359,11 @@ def test_delta_stale_handle_after_delete_and_recreate_reuses_its_ids( ) 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"d"] + assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ + b"a", + b"c", + b"d", + ] def test_connector_lists_its_tables_once_per_append(tmp_path: Path) -> None: diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 6f3e017eb..be47d4377 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1111,9 +1111,11 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: folding, a type DataFusion cannot insert or cast into the stored one, and a row Delta finds invalid (a null in a non-nullable column, a failed CHECK constraint). A CHECK constraint whose verdict changes by chance would accept such rows on a later try; -Orcapod writes none. Any other failure keeps its rows queued and is raised again by the -next flush, as before: a storage error, a constraint whose evaluation itself fails, a -stored table unreadable for another reason. So a column whose Arrow type Delta keeps +Orcapod writes none. Any other failure keeps its rows queued, as before, and the next +flush tries them again: it writes them if the cause has passed (storage recovered, +another writer no longer committing first) and raises only if that try fails too: a +storage error, a constraint whose evaluation itself fails, a stored table that cannot be +loaded. So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" cells below, every list and map included) cannot gain a field when schema evolution is on, nor have a nested nullability change: the record is the column's field metadata, which deltalake 1.5 and later does not let a @@ -1124,7 +1126,10 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: columns), never by position. Delta alone refuses two columns, or two fields of one struct, whose names differ only in case: Delta column names are case-insensitive, so such a table, or an append that would make one, is refused naming both, before anything -is queued. Rows whose columns are the held table's columns in another +is queued, when Python's `str.lower` finds the pair. Delta folds case as Rust's +`to_lowercase` does, which differs for a few code points (U+1C89 and U+1C8A, for +example): such a pair is found by Delta only, at the flush, which raises once naming the +column (`UnstorableColumnError`), and those rows leave the queue. Rows whose columns are the held table's columns in another order, each field equal to the held one (the same type at every depth, the same logical type, the same field attributes), are put in the held order, whether the table was flushed in between or not. The in-memory database matches them to the rows still pending, From 1d6bc9446e11b6fb9d6945054547c26ee793e2f2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 11:06:52 -0800 Subject: [PATCH 20/23] fix(databases): drop a row as stored only if the table holds it now; extend a create's ids only for its own table (ITL-1377) Review of PR 511 (CodeRabbit on ad1c51bc): - skip_duplicates: before a row is dropped as stored, the table is loaded again, and only ids it holds now are dropped: a cached handle may describe a table another writer created again, or a version whose row was deleted. - A create commit carries a random token (orcapod.create_token in its commit info); the snapshot of the create is extended to the reloaded table only if its version 0 carries that token, so another writer's table created again in between is never seeded with this create's ids. The commit-cost tests are unchanged. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1377.md | 9 +- docs/dev/design_issues/ITL-1371-LI1.md | 6 +- src/orcapod/databases/delta_lake_databases.py | 50 ++++++++++- .../test_delta_concurrent_writers.py | 83 +++++++++++++++++++ 4 files changed, 141 insertions(+), 7 deletions(-) diff --git a/changelog.d/ITL-1377.md b/changelog.d/ITL-1377.md index a0e5223b5..de908c5b9 100644 --- a/changelog.d/ITL-1377.md +++ b/changelog.d/ITL-1377.md @@ -37,8 +37,13 @@ - `DeltaTableDatabase.add_records` with `skip_duplicates=False` queued a row whose id was already queued, and the flush stored both. It now raises `ValueError`, as the in-memory database does. +- A `skip_duplicates=True` add dropped a row as stored when the table this database had + loaded held its id, also after another writer deleted that row or created the table + again. A row is now dropped as stored only if the table at the path holds its id when + the rows are added (the table is loaded again before any row is dropped). - A table removed and created again by another writer starts over at version 0: a `DeltaTableDatabase` that had read the old table could take the new one's ids for the old one's at the same version, and skip a row with `skip_duplicates=True` as stored - when it was not (ITL-1413). The ids read are now tied to the Delta table's own id as well as its - version. + when it was not (ITL-1413). The ids read are now tied to the Delta table's own id as + well as its version, and after a create to a table whose create commit carries this + database's token (`orcapod.create_token` in the commit info). diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index eb89dda41..f6ce72dba 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -84,8 +84,10 @@ handle, where a reopened handle refuses it. The other is pre-existing, as on mai (ITL-1413): when the table is deleted and recreated at the same path and Delta version, the held handle's duplicate scan reused the old version's cached ids, so an old id was skipped as a duplicate and a new one could be written twice. Fixed by ITL-1377 (review of PR 511): the -cached ids are keyed by the Delta table's own id as well as its version, and every commit to -an existing table is a MERGE. A connector database compares against the +cached ids are keyed by the Delta table's own id as well as its version (after a create, only +a table whose create commit carries this writer's token is taken for its own), a row is +dropped as a stored duplicate only after the table is reloaded and still holds its id (also +when another writer deleted that row), and every commit to an existing table is a MERGE. 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). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c2685a35c..8c12ef40c 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -6,6 +6,7 @@ import re import sys import time +import uuid from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager @@ -1643,6 +1644,21 @@ def _database_error_to_raise(errors: list[Exception]) -> Exception | None: return None +# The commit-info key under which a create records its token (``_CommittedSnapshot``). +_CREATE_TOKEN_KEY = "orcapod.create_token" + + +def _created_with(delta_table: deltalake.DeltaTable, token: str) -> bool: + """Whether ``delta_table`` is at version 0 and its create commit carries ``token``.""" + if delta_table.version() != 0: + return False + try: + latest = delta_table.history(1) + except Exception: # noqa: BLE001 # unknown: the ids are read again on first use + return False + return bool(latest) and latest[0].get(_CREATE_TOKEN_KEY) == token + + def _table_id(delta_table: deltalake.DeltaTable) -> str: """The Delta table's own id, which a table created again at the same path does not share.""" @@ -1663,6 +1679,10 @@ class _CommittedSnapshot: created), or ``""`` for a table this database has just created. A version describes one table only: a table removed and created again starts over at version 0 with another id (review of PR 511). + create_token: For a table this database has just created, the random token + its create commit carries (``_CREATE_TOKEN_KEY``): the table reloaded + after the create is extended only if its version 0 carries it, since + another writer may have created the table again in between. ids: The stored record ids (never null), or ``None`` until first needed. rows: Indexes over every stored row, read exactly as ``get_all_records`` reads them, or ``None`` until first needed. @@ -1675,6 +1695,7 @@ class _CommittedSnapshot: version: int table_id: str = "" + create_token: str = "" ids: set[bytes] | None = None rows: KeyIndex | None = None files: frozenset[str] = frozenset() @@ -2837,6 +2858,14 @@ def _filter_existing_records( self._pending_record_ids[record_key] ) existing_in_delta = input_ids.intersection(self._stored_ids(record_path)) + if existing_in_delta: + # A row is dropped as stored only if the table at the path holds its id + # now: the cached handle may describe a table another writer has since + # replaced, or a version whose row was deleted, and a row dropped here is + # never written (review of PR 511). An add with no stored id costs no + # reload. + self._delta_table_cache.pop(record_key, None) + existing_in_delta &= self._stored_ids(record_path) all_existing = existing_in_pending.union(existing_in_delta) if not all_existing: @@ -3681,6 +3710,9 @@ def _commit_once( ) from load_error if delta_table is None: + # Tells this create's table from one another writer creates again at the + # path before it is reloaded (``_CommittedSnapshot.create_token``). + create_token = uuid.uuid4().hex try: # mode="error": a table another writer created after the load above # is never replaced; this attempt fails instead (ITL-1384). No commit @@ -3694,7 +3726,10 @@ def _commit_once( storage_options=self._storage_options or None, # Name the statistics columns once, at creation (ITL-1187). configuration=statistics_configuration(combined_table.schema), - commit_properties=deltalake.CommitProperties(max_commit_retries=0), + commit_properties=deltalake.CommitProperties( + max_commit_retries=0, + custom_metadata={_CREATE_TOKEN_KEY: create_token}, + ), ) except Exception as create_error: if self._table_exists_at(table_uri): @@ -3705,7 +3740,7 @@ def _commit_once( ) return ( None, - _CommittedSnapshot(version=-1, ids=set()), + _CommittedSnapshot(version=-1, ids=set(), create_token=create_token), self._non_null_ids(combined_table), ) @@ -3885,7 +3920,16 @@ def _extend_snapshot( """ version = committed.version() table_id = _table_id(committed) - if version != base.version + 1 or base.table_id not in ("", table_id): + # Only the table the commit built on: after a create, the table reloaded may + # be another writer's, created again at the path in between, so it must carry + # this create's token; otherwise its ids are read on first use (review of + # PR 511). + same_table = ( + _created_with(committed, base.create_token) + if base.create_token + else base.table_id == table_id + ) + if version != base.version + 1 or not same_table: return _CommittedSnapshot(version, table_id) assert base.ids is not None snapshot = _CommittedSnapshot(version, table_id, ids=base.ids | inserted_ids) diff --git a/tests/test_databases/test_delta_concurrent_writers.py b/tests/test_databases/test_delta_concurrent_writers.py index 61afc0ef2..f764b9af2 100644 --- a/tests/test_databases/test_delta_concurrent_writers.py +++ b/tests/test_databases/test_delta_concurrent_writers.py @@ -440,3 +440,86 @@ def test_an_id_already_queued_is_refused_without_skip_duplicates( db.flush() expected = [(b"\x01", 10), (b"\x02", 20), (b"\x03", 30)] assert _stored(tmp_path) == sorted(expected + ([(b"\x09", 90)] if stored else [])) + + +@pytest.mark.parametrize("change", ["created again", "row deleted"]) +def test_a_row_is_skipped_as_stored_only_if_the_table_holds_it_now( + tmp_path: Path, change: str +) -> None: + """Review of PR 511: the database holds a handle and ids of the table; another + writer creates the table again at the same version, or deletes a stored row. A + ``skip_duplicates`` add drops a row as stored only if the table at the path holds + its id now: the old id is stored, an id the table holds is skipped, a new id is + stored.""" + import shutil + + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + pa.concat_tables([_records(1, 10), _records(5, 50)]), + record_id_column="rid", + flush=True, + ) + db.add_records(PATH, _records(1, 11), record_id_column="rid", skip_duplicates=True) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + if change == "created again": + shutil.rmtree(tmp_path / "t") + DeltaTableDatabase(tmp_path).add_records( + PATH, _records(2, 20), record_id_column="rid", flush=True + ) + kept = [(b"\x02", 20)] + else: + deltalake.DeltaTable(str(tmp_path / "t")).delete("__record_id = X'01'") + kept = [(b"\x05", 50)] + added = pa.concat_tables([_records(1, 12), _records(2, 22), _records(3, 30)]) + db.add_records( + PATH, added, record_id_column="rid", skip_duplicates=True, flush=True + ) + new = [(b"\x01", 12), (b"\x03", 30)] + if change == "row deleted": + new.append((b"\x02", 22)) + assert _stored(tmp_path) == sorted(kept + new) + + +@pytest.mark.parametrize("replaced", [True, False], ids=["replaced", "own table"]) +def test_a_create_followed_by_another_writers_table_is_not_seeded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replaced: bool +) -> None: + """Review of PR 511: this database creates the table with ids 1 and 2; another + writer creates it again at the path (version 0, with id 7) before the reload. The + ids of the create are not taken for the reloaded table's: a later + ``skip_duplicates`` add of 1 is stored and of 7 skipped. Without the replacement, + the create's ids are kept, and the table is not read again for them.""" + import shutil + + real_write = deltalake.write_deltalake + + def create(table_or_uri: Any, data: Any, *args: Any, **kwargs: Any) -> Any: + real_write(table_or_uri, data, *args, **kwargs) + if replaced and kwargs.get("mode") == "error": + shutil.rmtree(str(table_or_uri)) + real_write( + str(table_or_uri), + _records(7, 70).rename_columns(["__record_id", "a", "z"]), + ) + + db = DeltaTableDatabase(tmp_path) + with monkeypatch.context() as patched: + patched.setattr(deltalake, "write_deltalake", create) + db.add_records( + PATH, + pa.concat_tables([_records(1, 10), _records(2, 20)]), + record_id_column="rid", + flush=True, + ) + snapshot = db._snapshots["t"] # pyright: ignore[reportPrivateUsage] + assert (snapshot.ids is None) == replaced + added = pa.concat_tables([_records(1, 11), _records(7, 71), _records(3, 30)]) + db.add_records( + PATH, added, record_id_column="rid", skip_duplicates=True, flush=True + ) + if replaced: + expected = [(b"\x01", 11), (b"\x03", 30), (b"\x07", 70)] + else: + expected = [(b"\x01", 10), (b"\x02", 20), (b"\x03", 30), (b"\x07", 71)] + assert _stored(tmp_path) == expected From 406b2364a99d9f6943c0df6b3351c4acecf7b02d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:21:54 -0800 Subject: [PATCH 21/23] fix(databases): a reopen drops the snapshot with the handle; a case clash beside a repeated name is refused (ITL-1403) Review of PR 504, round eight (CodeRabbit on a47bb0be): - A table reopened to check a refusal again (the stored-name check and the logical-identifier check, ITL-1371) drops the cached snapshot together with the handle (_forget_loaded_table): a table created again at the same version is no longer read through the old table's rows. This also closes ITL-1413's case on this path; its limit test now asserts the fixed result. - require_storable finds a case clash by position, so x, X, X is refused with UnstorableColumnError instead of raising KeyError. - _append_refusal folds the stored names once per check (nitpick). Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 6 +- src/orcapod/databases/delta_lake_databases.py | 54 ++++++++-- .../test_delta_refused_before_queueing.py | 99 +++++++++++++++++++ .../test_logical_identity_appends.py | 16 +-- 4 files changed, 156 insertions(+), 19 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 62dd996d0..83f377dfe 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -82,8 +82,10 @@ loaded, before anything is written. Two differences remain. One writes nothing e 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 +held handle's duplicate scan reused the old version's cached ids, so an old id was skipped as +a duplicate and a new one could be written twice. When an add reopens the table (another +identifier, or a refusal checked again), the snapshot is now dropped with the handle (review +of PR 504, round eight); the general fix is ITL-1377's. 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). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 18adc91c1..7044b409e 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -586,11 +586,22 @@ def _merged_record( def _differ_only_in_case(names: list[str]) -> tuple[str, str] | None: """The first two of ``names`` that differ only in case, or ``None``.""" + position = _case_clash_position(names) + if position is None: + return None + second = names[position] + first = next(n for n in names if n.lower() == second.lower() and n != second) + return first, second + + +def _case_clash_position(names: list[str]) -> int | None: + """The position in ``names`` of the first name that differs only in case from an + earlier one, or ``None``. A position, since the name itself may be repeated.""" seen: dict[str, str] = {} - for name in names: + for position, name in enumerate(names): other = seen.setdefault(name.lower(), name) if other != name: - return other, name + return position return None @@ -1145,6 +1156,11 @@ def _append_refusal( if identity is not None: return identity held = _held_columns(delta_table) + # Folded once per check, not once per new column (review of PR 504, round eight). + held_clash = _differ_only_in_case(list(held)) + held_folded: dict[str, str] = {} + for name in held: + held_folded.setdefault(name.lower(), name) for field in rows.schema: if field.name in held: change = _column_change(held[field.name], field) @@ -1154,9 +1170,11 @@ def _append_refusal( # A new name enters the stored schema only when the MERGE evolves it; # without evolution Delta leaves an unknown column out, as main did # (review of PR 504, round four). - clash = _differ_only_in_case([*held, field.name]) - if clash is not None: - return field.name, _case_reason(*clash) + if held_clash is not None: + return field.name, _case_reason(*held_clash) + stored_name = held_folded.get(field.name.lower()) + if stored_name is not None: + return field.name, _case_reason(stored_name, field.name) exact = _exact_refusal(delta_table, rows) if exact is not None: return exact @@ -2153,12 +2171,16 @@ def require_storable(self, schema: pa.Schema) -> None: UnstorableColumnError: For the first column Delta cannot hold, naming the column, its Arrow type and Delta's reason. """ - clash = _differ_only_in_case(schema.names) - if clash is not None: + position = _case_clash_position(schema.names) + if position is not None: + # By position: the name may be repeated (``x``, ``X``, ``X``), and a + # lookup by a repeated name raises (review of PR 504, round eight). + clash = _differ_only_in_case(schema.names) + assert clash is not None raise UnstorableColumnError( database_kind=type(self).__name__, column=clash[1], - arrow_type=schema.field(clash[1]).type, + arrow_type=schema.field(position).type, reason=_case_reason(*clash), ) for field in schema: @@ -2277,7 +2299,7 @@ def _refuse_unmergeable_append( # replaced: the rows are refused only if the version stored now # refuses them too (review of PR 504, round seven). An accepted add # keeps the cached handle, so it costs no reload. - self._delta_table_cache.pop(self._get_record_key(record_path), None) + self._forget_loaded_table(record_path) delta_table = self._stored_table_for_check(record_path) refusal = ( None @@ -2294,6 +2316,18 @@ def _refuse_unmergeable_append( "The stored rows are unchanged and nothing was written." ) + def _forget_loaded_table(self, record_path: tuple[str, ...]) -> None: + """Drop the table handle and the snapshot of it cached for ``record_path``. + + Both go together: the next load may find a table another writer created + again at the same version, and a snapshot is kept by version only, so a + snapshot left behind would serve the old table's rows for the new one + (review of PR 504, round eight). + """ + record_key = self._get_record_key(record_path) + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + def _stored_table_for_check( self, record_path: tuple[str, ...] ) -> deltalake.DeltaTable | None: @@ -2417,7 +2451,7 @@ def _stored_identity_refusal( 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) + self._forget_loaded_table(record_path) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 57f451a7a..0cf7306b1 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -703,3 +703,102 @@ def test_a_clash_with_a_cached_version_is_checked_against_the_stored_one( _add(db, _rows(b"2", **anchor, **added)) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] assert _stored_ids(tmp_path) == [b"1"] + + +@pytest.mark.parametrize( + "names", + [["a", "A", "A"], ["A", "a", "a"], ["a", "b", "A", "b"]], + ids=lambda names: "".join(names), +) +def test_a_case_clash_beside_a_repeated_name_names_the_column( + tmp_path: Path, names: list[str] +) -> None: + """Review of PR 504 (round eight) and PR 511: with a name repeated, the case clash + is still refused with ``UnstorableColumnError``, naming the column and the type at + its position.""" + types = [pa.int8(), pa.int16(), pa.int32(), pa.int64()][: len(names)] + table = pa.Table.from_arrays( + [pa.array([b"1"], pa.large_binary())] + [pa.array([1], t) for t in types], + names=["rid", *names], + ) + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError) as info: + _add(db, table) + position = next( + i + for i, n in enumerate(names) + if any(m.lower() == n.lower() and m != n for m in names[:i]) + ) + assert info.value.column == names[position] + assert str(types[position]) in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize("trigger", ["a case clash", "a logical identifier"]) +def test_a_table_reopened_for_a_refusal_is_read_as_the_table_stored_now( + tmp_path: Path, unit_type: Any, trigger: str +) -> None: + """Review of PR 504, round eight: the database read a table (its handle and the + snapshot of its rows are cached); another writer creates the table again at the + same version with other rows. An add refused against the cached version reopens + the table, which takes the rows; reads then show the table stored now, never the + old table's rows from the snapshot kept by version. Both reopen paths: the stored + case clash and the logical identifier (ITL-1371).""" + import shutil + + def unit(value: int, serial: bytes) -> Any: + return pa.ExtensionArray.from_storage( + unit_type(serial), pa.array([value], pa.int64()) + ) + + if trigger == "a case clash": + first = {"anchor": pa.array([1]), "a": pa.array([11])} + other = {"anchor": pa.array([99])} + added = {"anchor": pa.array([2]), "A": pa.array([22])} + else: + first = {"anchor": pa.array([1]), "x": unit(11, b"old")} + other = {"anchor": pa.array([99]), "x": unit(99, b"new")} + added = {"anchor": pa.array([2]), "x": unit(22, b"new")} + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + _add(db, _rows(b"1", **first), flush=True) + before = db.get_record_by_id(PATH, b"1") + assert before is not None and before.column("anchor").to_pylist() == [1] + shutil.rmtree(tmp_path / "t") + DeltaTableDatabase(tmp_path, allow_schema_evolution=True).add_records( + PATH, _rows(b"1", **other), record_id_column="rid", flush=True + ) + assert deltalake.DeltaTable(str(tmp_path / "t")).version() == 0 + _add(db, _rows(b"2", **added)) # accepted against the table stored now + after = db.get_record_by_id(PATH, b"1") + assert after is not None + assert after.column("anchor").to_pylist() == [99] + db.flush() + assert _stored_ids(tmp_path) == [b"1", b"2"] + + +@pytest.mark.parametrize("evolve", [True, False], ids=["evolution on", "evolution off"]) +@pytest.mark.parametrize( + "new", [["b", "C", "d"], ["d", "C", "b"]], ids=["one order", "another order"] +) +def test_new_columns_are_checked_against_every_stored_name( + tmp_path: Path, new: list[str], evolve: bool +) -> None: + """Review of PR 504, round eight (the stored names are folded once per check): + several new columns, one of them differing only in case from a stored one, in two + orders. With schema evolution the clashing column is refused, named with the + stored one; without it Delta leaves the unknown columns out and the rows are + stored.""" + stored = {"a": pa.array([1]), "c": pa.array([2])} + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolve) + _add(db, _rows(b"1", **stored), flush=True) + # The rows omit the stored ``c``: their own names never clash. + rows = _rows(b"2", a=pa.array([1]), **{n: pa.array([3]) for n in new}) + if evolve: + with pytest.raises( + InputValidationError, match="'c' and 'C' differ only in case" + ): + _add(db, rows) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + else: + _add(db, rows, flush=True) + assert _stored_ids(tmp_path) == [b"1", b"2"] diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 982767cb3..aa5f5cb0b 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -2316,14 +2316,16 @@ def test_delta_recorded_type_decides_a_child_the_log_keeps_plain( 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( +def test_delta_handle_after_delete_and_recreate_reads_the_new_tables_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.""" + """Round 5, finding 2 (ITL-1413): a held handle whose table was deleted and + recreated at the same path, at the same Delta version, no longer reuses the old + table's cached ids, so an old id the new table lacks is stored once, and an id of + the new table is not stored twice. Here the add of another identifier reopens the + table, and a reopen drops the snapshot with the handle (review of PR 504, round + eight); ITL-1377 also keys every snapshot by the Delta table's own id and commits + every append to an existing table as a MERGE.""" import shutil import deltalake @@ -2359,7 +2361,7 @@ def test_delta_stale_handle_after_delete_and_recreate_reuses_its_ids( 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"a", b"c", b"d", ] From b2feefd0c66d6cff895f2e288e73a3f72eb0f920 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:56:43 -0800 Subject: [PATCH 22/23] perf(databases): hold the queued names as a set; the pruning test checks there are files to prune (ITL-1403) From CodeRabbit's review of PR 511 on d6a25bb8, for code of this PR: - _refuse_case_clash_with_pending tests membership against a set of the queued names; the list keeps the order the clash is reported in (nitpick). - test_a_listed_column_prunes_files asserts three active files with disjoint v ranges before it checks that the query scans one of them. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 7 +++++-- .../test_delta_refused_before_queueing.py | 17 +++++++++++++++++ .../test_delta_statistics_columns.py | 7 +++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 7044b409e..d3a90ae43 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2209,8 +2209,11 @@ def _refuse_case_clash_with_pending( if pending is None: return queued = pending.schema.names + # A set for membership, the list for the order the clash is reported in + # (review of PR 511). + queued_names = set(queued) clash = _differ_only_in_case( - [*queued, *(n for n in schema.names if n not in queued)] + [*queued, *(n for n in schema.names if n not in queued_names)] ) if clash is not None: raise InputValidationError( @@ -2220,7 +2223,7 @@ def _refuse_case_clash_with_pending( # A struct queued and a struct added, merged as the flush would merge them, # must not hold two field names differing only in case, at any depth. for field in schema: - if field.name not in queued: + if field.name not in queued_names: continue try: merged = merged_type( diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 0cf7306b1..03f013147 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -802,3 +802,20 @@ def test_new_columns_are_checked_against_every_stored_name( else: _add(db, rows, flush=True) assert _stored_ids(tmp_path) == [b"1", b"2"] + + +@pytest.mark.parametrize( + "added", [["a", "B", "d"], ["d", "B", "a"]], ids=["one order", "another order"] +) +def test_a_column_differing_in_case_from_a_queued_one_is_named( + tmp_path: Path, added: list[str] +) -> None: + """Review of PR 511 (pending names held as a set for membership): rows queued with + ``a`` and ``b``; rows added with a queued name, a new name and ``B``, in two + orders. ``B`` is refused, named with the queued ``b``, and nothing of the add is + queued.""" + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", a=pa.array([1]), b=pa.array([2]))) + with pytest.raises(InputValidationError, match="'b' and 'B' differ only in case"): + _add(db, _rows(b"2", **{n: pa.array([3]) for n in added})) + assert db._pending_batches["t"].num_rows == 1 # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index e13b369d8..f988c7045 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -442,6 +442,13 @@ def test_a_listed_column_prunes_files(self, tmp_path: Path) -> None: db.add_records(PATH, rows(range(lo, lo + 5)), flush=True) table = deltalake.DeltaTable(str(tmp_path / "t")) + # There are files to prune: three active files, with disjoint ``v`` ranges, + # one of them holding 101 (review of PR 511). + ranges = sorted( + (add["min.v"], add["max.v"]) + for add in pa.table(table.get_add_actions(flatten=True)).to_pylist() + ) + assert ranges == [(0, 4), (100, 104), (200, 204)] plan = pa.table( deltalake.QueryBuilder() .register("t", table) From 543b1fbd3e03b548b7e827863168dac2b098a142 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:58:00 -0800 Subject: [PATCH 23/23] fix(databases): after the reload, skip every input id the table holds; daemon writer threads; qualify the retry guarantee (ITL-1377) Review of PR 511 (CodeRabbit on d6a25bb8): - skip_duplicates: once the table is loaded again, every input id it holds is skipped, also one another writer added after the cached version (the reload had kept only the ids the cached version held, so such a row was queued, and could be refused for a case clash with the queued rows). - The four-writer create test runs its writers as daemon threads, so one stalled in flush fails the test without keeping the process alive. - The changelog says a writer that keeps losing gives up after 200 attempts, its rows staying queued. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1377.md | 4 +- src/orcapod/databases/delta_lake_databases.py | 7 +-- .../test_delta_concurrent_writers.py | 43 ++++++++++++++++++- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/changelog.d/ITL-1377.md b/changelog.d/ITL-1377.md index de908c5b9..9c1b343b6 100644 --- a/changelog.d/ITL-1377.md +++ b/changelog.d/ITL-1377.md @@ -31,7 +31,9 @@ - Two writers (two `DeltaTableDatabase` objects, or two processes) that committed the same new record id to one Delta table both committed it, so the id was stored twice, with `skip_duplicates` true or false. Now the later writer leaves the id the earlier - one stored: each id is stored once. Writers committing other ids all commit. + one stored: each id is stored once. A writer whose commit loses to another writer's + loads the table again and retries, up to 200 attempts; under sustained contention it + can still fail after the last one, and its rows then stay queued for the next flush. - Two writers creating the same Delta table at once could lose the earlier writer's rows. The later create now fails and is retried as a MERGE. - `DeltaTableDatabase.add_records` with `skip_duplicates=False` queued a row whose id diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 7aeeb0350..96339a2b5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2879,10 +2879,11 @@ def _filter_existing_records( # A row is dropped as stored only if the table at the path holds its id # now: the cached handle may describe a table another writer has since # replaced, or a version whose row was deleted, and a row dropped here is - # never written (review of PR 511). An add with no stored id costs no - # reload. + # never written (review of PR 511). Every input id is checked against the + # table loaded again, so an id another writer added meanwhile is skipped + # too. An add with no stored id costs no reload. self._delta_table_cache.pop(record_key, None) - existing_in_delta &= self._stored_ids(record_path) + existing_in_delta = input_ids.intersection(self._stored_ids(record_path)) all_existing = existing_in_pending.union(existing_in_delta) if not all_existing: diff --git a/tests/test_databases/test_delta_concurrent_writers.py b/tests/test_databases/test_delta_concurrent_writers.py index f764b9af2..bae954080 100644 --- a/tests/test_databases/test_delta_concurrent_writers.py +++ b/tests/test_databases/test_delta_concurrent_writers.py @@ -298,7 +298,11 @@ def write(value: int) -> None: except BaseException as e: # noqa: BLE001 # reported below errors.append(e) - threads = [threading.Thread(target=write, args=(v,)) for v in range(4)] + # Daemon threads: one stalled in ``flush`` fails the assertion below and + # never keeps the test process alive (review of PR 511). + threads = [ + threading.Thread(target=write, args=(v,), daemon=True) for v in range(4) + ] for thread in threads: thread.start() for thread in threads: @@ -523,3 +527,40 @@ def create(table_or_uri: Any, data: Any, *args: Any, **kwargs: Any) -> Any: else: expected = [(b"\x01", 10), (b"\x02", 20), (b"\x03", 30), (b"\x07", 71)] assert _stored(tmp_path) == expected + + +@pytest.mark.parametrize("queued_clash", [False, True], ids=["plain", "a queued x"]) +@pytest.mark.parametrize( + "order", [(1, 2), (2, 1)], ids=["cached id first", "new id first"] +) +def test_an_id_another_writer_added_is_skipped_once_the_table_is_reloaded( + tmp_path: Path, order: tuple[int, int], queued_clash: bool +) -> None: + """Review of PR 511: the database holds ids 1 (cached); another writer adds 2. A + ``skip_duplicates`` add of 1 and 2, in either order, reloads the table for id 1 + and skips every id it holds then, 2 included: nothing is queued. With a column + ``x`` queued for another id, rows holding ``X`` whose ids are all stored are + skipped, not refused for the case clash.""" + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _records(1, 10), record_id_column="rid", flush=True) + db.add_records(PATH, _records(1, 11), record_id_column="rid", skip_duplicates=True) + DeltaTableDatabase(tmp_path).add_records( + PATH, _records(2, 20), record_id_column="rid", flush=True + ) + if queued_clash: + db.add_records( + PATH, + _records(3, 30).append_column("x", pa.array([1])), + record_id_column="rid", + ) + added = pa.concat_tables([_records(n, 99) for n in order]) + if queued_clash: + added = added.append_column("X", pa.array([1, 2])) + db.add_records(PATH, added, record_id_column="rid", skip_duplicates=True) + pending = db._pending_batches.get("t") # pyright: ignore[reportPrivateUsage] + assert (0 if pending is None else pending.num_rows) == (1 if queued_clash else 0) + db.flush() + expected = [(b"\x01", 10), (b"\x02", 20)] + if queued_clash: + expected.append((b"\x03", 30)) + assert _stored(tmp_path) == expected