diff --git a/changelog.d/ITL-1377.md b/changelog.d/ITL-1377.md new file mode 100644 index 000000000..9c1b343b6 --- /dev/null +++ b/changelog.d/ITL-1377.md @@ -0,0 +1,51 @@ +### 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. 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. 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 + +- 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. 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 + 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, 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/concepts/function-pods.md b/docs/concepts/function-pods.md index cfbbbc79f..59d9c53d8 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-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 83f377dfe..4d704d32f 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -84,8 +84,12 @@ 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. 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 +identifier, or a refusal checked again), the snapshot is dropped with the handle (review +of PR 504, round eight). Fixed in general by ITL-1377 (review of PR 511): 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/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. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 0468ac5f7..c7dd0063e 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -68,6 +68,13 @@ 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, 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 (stored, or still pending) in field metadata (the column's own, or a nested field's: a @@ -100,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 @@ -113,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 222e7e15b..b1008776a 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2,8 +2,11 @@ import logging import os +import random import re import sys +import time +import uuid from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager @@ -82,6 +85,38 @@ # 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). 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): + """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",), @@ -1132,6 +1167,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 logical type identifier known, from the Delta log, to differ from the stored one (``logical_identity_change``, ITL-1371); - a column change (``_column_change``): other field attributes, a struct that @@ -1156,6 +1193,11 @@ def _append_refusal( if identity is not None: return identity 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 # 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] = {} @@ -1329,6 +1371,52 @@ 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``) 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. + + 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" + ) + 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``. @@ -1341,6 +1429,10 @@ def delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: column already stored with a type, and a column with no stored type yet is refused by ``add_records``, which knows the stored table. + A top-level name holding a backtick is refused too (``_unmergeable_name_reason``, + ITL-1375), and so are two fields of one struct whose names differ only in case + (ITL-1403). + Args: field: A column, as given to the database. @@ -1348,6 +1440,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. """ + name_reason = _unmergeable_name_reason(field.name) + if name_reason is not None: + return name_reason nested = _nested_names_differing_in_case(field.type) if nested is not None: return _case_reason(*nested, nested=True) @@ -1554,6 +1649,27 @@ 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.""" + return str(delta_table.metadata().id) + + @dataclass class _CommittedSnapshot: """What one version of a stored Delta table holds, kept in memory (ITL-919). @@ -1564,6 +1680,14 @@ 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). + 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. @@ -1575,6 +1699,8 @@ class _CommittedSnapshot: """ version: int + table_id: str = "" + create_token: str = "" ids: set[bytes] | None = None rows: KeyIndex | None = None files: frozenset[str] = frozenset() @@ -2022,9 +2148,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 @@ -2174,7 +2305,7 @@ def require_storable(self, schema: pa.Schema) -> 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). + # lookup by a repeated name raises (reviews of PR 504 and PR 511). clash = _differ_only_in_case(schema.names) assert clash is not None raise UnstorableColumnError( @@ -2642,8 +2773,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 @@ -2731,6 +2878,15 @@ 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). 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 = input_ids.intersection(self._stored_ids(record_path)) all_existing = existing_in_pending.union(existing_in_delta) if not all_existing: @@ -3430,107 +3586,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, self.allow_schema_evolution - ) - 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``, @@ -3611,7 +3696,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 ) @@ -3626,6 +3711,158 @@ 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: + # 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 + # retry: deltalake 1.6 would otherwise commit this create on top of + # the other writer's, as an append (measured: two of four concurrent + # creates succeeded), and an id both hold would be stored twice. + 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), + 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): + 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(), create_token=create_token), + 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, self.allow_schema_evolution + ) + 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). + source = _merge_source_in_stored_layout(delta_table, combined_table) + delta_table.merge( + # Every array from offset zero: deltalake 1.6's MERGE panics on a + # sliced map column (arrow-rs, "range start index ... out of range"). + # ``take`` copies the values as they are. + source=source.take(pa.array(range(source.num_rows), pa.int64())), + predicate=f"target.{self.RECORD_ID_COLUMN} = source.{self.RECORD_ID_COLUMN}", + 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 + 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, @@ -3658,47 +3895,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.""" @@ -3735,17 +3931,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, @@ -3774,10 +3972,20 @@ def _extend_snapshot( The new snapshot. """ version = committed.version() - if version != base.version + 1: - return _CommittedSnapshot(version) + table_id = _table_id(committed) + # 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, 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_append_by_name.py b/tests/test_databases/test_append_by_name.py index 81a4f77c0..f139f767f 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -545,7 +545,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, ...], @@ -553,9 +553,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 @@ -573,16 +573,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) == [ @@ -759,12 +761,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) @@ -794,7 +797,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] @@ -885,12 +888,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 @@ -922,7 +926,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_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_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_databases/test_delta_concurrent_writers.py b/tests/test_databases/test_delta_concurrent_writers.py new file mode 100644 index 000000000..bae954080 --- /dev/null +++ b/tests/test_databases/test_delta_concurrent_writers.py @@ -0,0 +1,566 @@ +"""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, cast +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"] + + +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, 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: + """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( + cast(list[bytes], table["rid"].to_pylist()), + cast(list[int], 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 + BOUND)) + + 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 == 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 + BOUND + + +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 = BOUND - 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 == BOUND + 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) + ] + 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] + + +def test_writers_creating_one_table_at_once_store_an_id_once(tmp_path: Path) -> None: + """Four writers create the same table at the same moment, all with one id. + + deltalake 1.6 commits a create that lost the race on top of the winner's, as an + append, unless the create is committed without retries; the losers then load the + table and MERGE, which finds the id stored (ITL-1384, ITL-1377). + """ + import threading + + for trial in range(10): + root = tmp_path / str(trial) + start = threading.Barrier(4) + errors: list[BaseException] = [] + + def write(value: int) -> None: + # 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) + + # 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: + 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 + + +def test_a_batch_that_keeps_losing_withdraws_the_records_waiting_on_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The retry runs inside the pending-commit path (ITL-1412): a result batch that + loses every attempt raises after the bound, keeps its rows queued (a lost commit + is not permanent), and the records waiting on it are withdrawn, never published + by a later commit of other rows.""" + from deltalake.exceptions import CommitFailedError + + db = DeltaTableDatabase(tmp_path) + results, records = ("results",), ("records",) + + def row(rid: bytes) -> pa.Table: + return pa.table({"rid": pa.array([rid], pa.large_binary()), "a": [1], "z": [1]}) + + db.add_records(results, row(b"r1"), record_id_column="rid", flush=True) + db.add_records(results, row(b"r2"), record_id_column="rid") + dependency = db.pending_result(results, b"r2") + assert dependency is not None + with db.guard_record(records, b"p2", dependency): + db.add_records(records, row(b"p2"), record_id_column="rid") + + def always_lose(*args: Any) -> Any: + raise delta_lake_databases._LostCommitRace(CommitFailedError("lost")) # pyright: ignore[reportPrivateUsage] + + with monkeypatch.context() as patched: + patched.setattr(DeltaTableDatabase, "_commit_once", always_lose) + with pytest.raises(CommitFailedError): + db.flush_batch(results) + assert db._pending_batches.get("results") is not None # pyright: ignore[reportPrivateUsage] + db.flush() + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records( + 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 [])) + + +@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 + + +@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 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..f39b4f42b --- /dev/null +++ b/tests/test_databases/test_delta_merge_reserved_names.py @@ -0,0 +1,209 @@ +"""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, 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 +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``. Only these +# names are probed (review of PR 511). +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 + + +@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 03f013147..6b7f7c767 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -325,8 +325,8 @@ def rows(rid: bytes, name: str) -> pa.Table: # ── 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"], + "every id new": [b"2"], + "a stored id among them": [b"1", b"2"], } @@ -434,8 +434,8 @@ def test_a_null_column_is_checked_like_any_column( """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.""" + would send it (a MERGE that evolves the schema), 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] = { diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index f988c7045..cf03a532e 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,53 @@ 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: + # 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())), + ) + 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)]) + 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: @@ -478,11 +508,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/type_matrix.py b/tests/test_databases/type_matrix.py index 246876cfa..be47d4377 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1072,6 +1072,13 @@ 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, 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 (stored, or still pending) in field metadata (the column's own, or a nested field's: a @@ -1104,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 @@ -1117,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, diff --git a/tests/test_pipeline/test_job_batched_commits.py b/tests/test_pipeline/test_job_batched_commits.py index a9961e57f..c67f7612d 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: diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 98fd6598a..65a10db36 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