diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md new file mode 100644 index 000000000..e40eac5bf --- /dev/null +++ b/changelog.d/ITL-1386.md @@ -0,0 +1,42 @@ +### Breaking changes and migration + +- `add_record` and `add_records` now raise `ValueError` with the default + `skip_duplicates=False` when a record ID is already stored or pending. A batch + rejected for a duplicate queues no rows. Use `skip_duplicates=True` for + write-if-missing behavior. If another writer commits an ID after the add-time + check, the first commit keeps the row. SQLite still applies its existing + replace or ignore policy when only a separate unique constraint conflicts. + (ITL-1386, ITL-1487) + +### Fixed + +- Delta accepts extension-backed record IDs outside Python's date range and + skips late duplicate list and struct IDs when flushing. (ITL-1386) +- Delta rejects a changed nested record ID storage type before queueing the add, + including when an append omits a nullable field inside the ID. (ITL-1386) +- Delta compares nested timestamp IDs across the input and stored timestamp units. + (ITL-1386) +- Delta checks nested extension storage types before skipping a matching stored + ID. Connector-backed databases report a failed stored-ID lookup as a read + error. Writable connectors implement `existing_record_ids` to check only the + incoming IDs by primary key. (ITL-1386) +- Appends reject mismatches in known field metadata inside Arrow extension + storage. Delta accepts IPC-decoded whole-column extensions that are + unregistered when the existing append checks pass. (ITL-1415) +- Delta excludes the record ID column from data-skipping statistics for every ID + type so concurrent MERGEs detect conflicting writes. The statistics property + is written at table creation. Tables created earlier keep their settings. + (ITL-1444) + +### Known limitations + +- If Delta cannot refresh its cached snapshot, a successful strict add can + also miss an ID another writer committed before the add-time check. A + successful flush keeps the stored row. (ITL-1386) +- As before, with Delta's `schema_handling="coerce"`, strict adds can miss + duplicate IDs that become equal when cast to the pending batch's type. + (ITL-1662) +- After a Delta commit, the log has no metadata for list items or map keys and + values inside extension storage. Appends can compare those fields against + queued rows only. A create file's Parquet footer can carry list item metadata, + while files written by a later MERGE can omit it. (ITL-1415) diff --git a/docs/dev/design_issues/ITL-1377-CW1.md b/docs/dev/design_issues/ITL-1377-CW1.md index 8721b1467..c9456d401 100644 --- a/docs/dev/design_issues/ITL-1377-CW1.md +++ b/docs/dev/design_issues/ITL-1377-CW1.md @@ -31,8 +31,8 @@ table does not hold (`_commit_once`), with `streamed_exec=False`. 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). + each id once. ITL-1386 refuses an id visible at add time in strict mode. A key + committed by another writer after the add-time check is still skipped at flush. - **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). diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md new file mode 100644 index 000000000..cb281c31a --- /dev/null +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -0,0 +1,23 @@ +## `src/orcapod/databases/` + +### WK1 — A strict add accepts an already stored record ID +**Status:** resolved +**Severity:** high +**Issue:** ITL-1386 + +A strict add of an already stored ID was silently skipped by Delta and silently +replaced the row in memory and connector-backed stores. All three refused an ID +that was already in the pending batch. + +**Fix:** Check stored IDs when adding, along with the pending IDs, and reject the +entire add if any conflict. The write-if-missing option still skips duplicates. +Writable connectors look up only the incoming IDs by primary key. +SQLite keeps its existing conflict policy for unique constraints on other columns. +Delta reuses the loaded table and ID snapshot when the log has not advanced. +Delta compares extension IDs by their Arrow storage values on both the writing +handle and reopened handles, including extension IDs stored as lists or structs. +Delta refuses an add whose nested ID storage type differs from the pending or +stored ID type, before schema handling can change the ID. +Arrow's primitive comparison preserves values outside Python's date range. +Delta streams the MERGE for nested IDs so a batch that loses to a committed row +can still flush and insert any distinct IDs it holds. diff --git a/docs/dev/design_issues/ITL-1415-WK3.md b/docs/dev/design_issues/ITL-1415-WK3.md new file mode 100644 index 000000000..b3ee49c57 --- /dev/null +++ b/docs/dev/design_issues/ITL-1415-WK3.md @@ -0,0 +1,24 @@ +## `src/orcapod/databases/` + +### WK3 — Appends accept changed field metadata inside extension storage +**Status:** resolved +**Severity:** high +**Issue:** ITL-1415 + +The append check skipped the nested fields of extension types. An append could +carry different field metadata inside a struct-backed extension and read back +with the held column's metadata. + +**Fix:** Compare field metadata recursively in extension storage. Delta checks +the metadata held in its log against the incoming storage fields before enqueue +and also checks against the version loaded for a commit. +Nested logical identifiers are checked separately from ordinary field metadata. +When IPC exposes an unregistered whole-column extension as storage with an +Arrow annotation, Delta refuses conflicting metadata explicitly present on +corresponding struct fields of both sides and treats missing attributes as +unknown. Delta refuses extensions nested inside another type (ITL-1372). + +The Delta log has no field metadata for list items or map keys and values +inside extension storage. For committed rows, those annotations are unknown. +The initial Parquet footer can carry list item metadata, while later MERGE +footers can omit it. diff --git a/docs/dev/design_issues/ITL-1444-WK4.md b/docs/dev/design_issues/ITL-1444-WK4.md new file mode 100644 index 000000000..c49a3cd1c --- /dev/null +++ b/docs/dev/design_issues/ITL-1444-WK4.md @@ -0,0 +1,12 @@ +## `src/orcapod/databases/delta_statistics.py` + +### WK4 — Delta file statistics on typed record IDs can let concurrent commits miss an overlap +**Status:** resolved +**Severity:** high +**Issue:** ITL-1444 + +Statistics on non-binary record IDs could let Delta file skipping hide a conflict +when two handles committed the same new ID. + +**Fix:** Exclude the record ID from every new table's statistics configuration. +Existing table properties are retained. diff --git a/docs/dev/design_issues/ITL-1487-WK2.md b/docs/dev/design_issues/ITL-1487-WK2.md new file mode 100644 index 000000000..c2bbcc945 --- /dev/null +++ b/docs/dev/design_issues/ITL-1487-WK2.md @@ -0,0 +1,13 @@ +## `src/orcapod/databases/connector_arrow_database.py` + +### WK2 — A second connector commit replaces the first writer's row +**Status:** resolved +**Severity:** high +**Issue:** ITL-1487 + +Two connector-backed database handles could queue the same new ID, then commit +different values. The last flush replaced the first writer's row when adding +with the default duplicate policy. + +**Fix:** Use the connector's insert-if-missing operation at commit in both modes. +A conflicting ID visible at add time is refused in strict mode. diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index b4bfe48d4..af91c96c6 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -478,8 +478,8 @@ def store( output_data: The computed output data to store. variation_datagram: Function variation metadata as a Datagram. execution_datagram: Execution environment metadata as a Datagram. - skip_duplicates: If True, silently skip if a record with the - same ID already exists. + skip_duplicates: If True, skip a record with the same output UUID + already pending or stored. data_context_key: Key of the caller's data context, stored on the row. Raises: @@ -487,6 +487,8 @@ def store( is not a ``large_string`` (``RESULT_TOKEN_COLUMN``) or names no output of ``output_data``; nothing is written. An output with no token column is stored with a null token. + OrcapodDatabaseWriteError: If the database refuses the write, including + when the output UUID already exists and ``skip_duplicates=False``. """ require_same_data_context(input_data.data_context_key, data_context_key) require_same_data_context(output_data.data_context_key, data_context_key) diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py index 255573b72..299124deb 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -67,6 +67,12 @@ def create_table_if_not_exists( """Create a record table in the verified schema.""" ... + def existing_record_ids( + self, table_name: str, id_column: str, ids: set[bytes], *, schema: str + ) -> set[bytes]: + """Return the supplied record IDs currently present in the verified table.""" + ... + def upsert_records( self, table_name: str, @@ -79,6 +85,18 @@ def upsert_records( """Write rows to the record table in the verified schema.""" ... + def insert_store_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + *, + skip_duplicates: bool, + schema: str, + ) -> None: + """Insert rows into the verified table, skipping IDs won by another writer.""" + ... + def catalog_name_pattern(name: str) -> str: """Escape a physical name prefix for a SQL LIKE expression with escape '!'.""" diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 71ed8c774..988eb59aa 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -3,7 +3,7 @@ Implements the full ArrowDatabaseProtocol on top of any DBConnectorProtocol, owning all record-management logic: record_path → table name mapping, ``__record_id`` column convention, in-memory pending-batch management, -deduplication, upsert, and flush. +deduplication and flush. Connector implementations (SQLiteConnector, PostgreSQLConnector, SpiralDBConnector) need only satisfy DBConnectorProtocol; they do not implement ArrowDatabaseProtocol. @@ -189,9 +189,8 @@ def __init__( # The schema each stored table was read with, for the append check # (``_refuse_changed_columns``). self._stored_schemas: dict[tuple[str | None, str], pa.Schema] = {} - # Per-batch flag: True when the batch was added with skip_duplicates=True, - # so flush() can pass skip_existing=True to the connector and let it use - # native INSERT-OR-IGNORE semantics rather than Python-side prefiltering. + # Keep the SQL store's existing write-if-missing policy for a batch that + # includes those writes. Strict-only batches skip ID conflicts at commit. self._pending_skip_existing: dict[str, bool] = ( _shared_pending_skip_existing if _shared_pending_skip_existing is not None @@ -215,7 +214,7 @@ def __init__( self.RECORD_ID_COLUMN, self._pending_batches, self._pending_record_ids, - on_empty=self._discard_pending_duplicate_policy, + on_empty=self._discard_pending_state, ) ) self._receipt_peers: _ReceiptPeers | None = None @@ -226,7 +225,7 @@ def __init__( connector, self._pending_commits ) - def _discard_pending_duplicate_policy(self, key: str) -> None: + def _discard_pending_state(self, key: str) -> None: """Forget indexes when an entire queued batch is discarded.""" self._pending_skip_existing.pop(key, None) owner_key = self._pending_owner_keys.pop(key, None) @@ -387,6 +386,19 @@ def _get_committed_table( return None return pa.Table.from_batches(batches) + def _stored_conflicts( + self, table: tuple[str | None, str], input_ids: set[bytes] + ) -> set[bytes]: + """Return input IDs found in the committed table.""" + schema, name = table + column = self.RECORD_ID_COLUMN + if self._sql_store is not None: + assert schema is not None + return self._sql_store.existing_record_ids( + name, column, input_ids, schema=schema + ) + return self._connector.existing_record_ids(name, column, input_ids) + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. @@ -643,11 +655,14 @@ def add_records( self._connector.validate_records(records) record_key = self._get_record_key(record_path) + committed_table = None pending_owner_key: tuple[str, str] | None = None if self._sql_store is not None: schema = self._schema_from_record_key(record_key) assert schema is not None - _ = self._find_committed_table(table_name, full_path, schema=schema) + committed_table = self._find_committed_table( + table_name, full_path, schema=schema + ) pending_owner_key = (schema, table_name) queued = self._pending_table_owners.get(pending_owner_key) if queued is not None and queued[0] != record_key: @@ -684,15 +699,31 @@ def add_records( records = records.filter(mask) if records.num_rows == 0: return - # Mark this pending slot so flush() uses skip_existing=True. - self._pending_skip_existing[record_key] = True else: - conflicts = input_ids & self._pending_record_ids[record_key] + conflicts = input_ids.intersection( + self._pending_record_ids.get(record_key, ()) + ) if conflicts: raise ValueError( f"Records with IDs {conflicts} already exist in the pending batch. " "Use skip_duplicates=True to skip them." ) + if self._sql_store is None: + committed_table = self._find_committed_table( + table_name, full_path, schema=None + ) + if committed_table is not None: + try: + conflicts = self._stored_conflicts(committed_table, input_ids) + except OrcapodDatabaseError: + raise + except Exception as exc: + raise OrcapodDatabaseReadError(table_name, full_path) from exc + if conflicts: + raise ValueError( + f"Records with IDs {conflicts} already exist in the stored " + "table. Use skip_duplicates=True to skip them." + ) # Buffer in pending batch existing_pending = self._pending_batches.get(record_key) @@ -710,6 +741,8 @@ def add_records( ) added = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) self._pending_record_ids[record_key].update(added) + if skip_duplicates: + self._pending_skip_existing[record_key] = True self._pending_commits.record_receipts(record_key, added) report_records(record_key, added=added) @@ -913,7 +946,7 @@ def guard_table_schema( ) def flush(self) -> None: - """Commit all pending batches to the connector via upsert.""" + """Insert all ready batches into the connector.""" for record_key in list(self._pending_batches): self._flush_by_key(record_key) @@ -945,7 +978,7 @@ def _flush_by_key(self, record_key: str) -> None: if ready is None: return pending, ids = ready - skip_existing = self._pending_skip_existing.get(record_key, False) + skip_duplicates = self._pending_skip_existing.get(record_key, False) try: record_path = self._record_path_from_key(record_key) table_name = self._path_to_table_name(record_path) @@ -963,7 +996,12 @@ def _flush_by_key(self, record_key: str) -> None: ) with transaction as (schema, table_exists): self._write_ready_batch( - record_key, table_name, pending, skip_existing, table_exists, schema + record_key, + table_name, + pending, + skip_duplicates, + table_exists, + schema, ) except BaseException: self._pending_commits.fail_batch(record_key, pending, ids) @@ -983,14 +1021,14 @@ def _flush_by_key(self, record_key: str) -> None: ) finally: if record_key not in self._pending_batches: - self._discard_pending_duplicate_policy(record_key) + self._discard_pending_state(record_key) def _write_ready_batch( self, record_key: str, table_name: str, pending: pa.Table, - skip_existing: bool, + skip_duplicates: bool, table_exists: bool, schema: str | None, ) -> None: @@ -1002,6 +1040,14 @@ def _write_ready_batch( if check is not None: check(pending.schema if existing is None else pa.schema(existing)) if existing is not None: + if self.keeps_field_metadata: + # A different handle may have created the table after this batch + # was queued. The connector's ColumnInfo omits field metadata. + held = self._read_stored_schema(table_name, schema) + if held is not None: + self._refuse_changed_columns( + self._record_path_from_key(record_key), pending, [held] + ) # A connector reads text and binary back in their large variants, # which are the same types (ITL-1162). existing_cols = {f.name: cast(pa.DataType, f.type) for f in existing} @@ -1026,6 +1072,8 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: ) pending = in_held_column_order(pending, existing) + # Another writer can commit an ID after it was checked at add time. + # Use the connector's atomic insert-if-missing for both modes. if self._sql_store is None: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN @@ -1034,19 +1082,30 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: table_name, pending, id_column=self.RECORD_ID_COLUMN, - skip_existing=skip_existing, + skip_existing=True, ) else: + assert schema is not None self._sql_store.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN, schema=schema ) - self._sql_store.upsert_records( - table_name, - pending, - id_column=self.RECORD_ID_COLUMN, - skip_existing=skip_existing, - schema=schema, - ) + if table_exists: + self._sql_store.insert_store_records( + table_name, + pending, + id_column=self.RECORD_ID_COLUMN, + skip_duplicates=skip_duplicates, + schema=schema, + ) + else: + # The store transaction serializes creation with other store writers. + self._sql_store.upsert_records( + table_name, + pending, + id_column=self.RECORD_ID_COLUMN, + skip_existing=skip_duplicates, + schema=schema, + ) # ── Read methods ────────────────────────────────────────────────────────── diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 4e2fa16cc..b8fbf5679 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -7,12 +7,21 @@ import sys import uuid from collections import defaultdict -from collections.abc import Callable, Collection, Iterable, Mapping +from collections.abc import ( + Callable, + Collection, + Hashable, + Iterable, + Iterator, + Mapping, + Sequence, +) from contextlib import AbstractContextManager from dataclasses import dataclass from pathlib import Path from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast +from weakref import ReferenceType, ref import polars as pl import pyarrow as pa @@ -969,7 +978,9 @@ def _evolution_change( return None -def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: +def _column_change( + held: "pa.Field[Any]", field: "pa.Field[Any]", *, from_delta_log: bool = False +) -> str | None: """Say why rows of column ``field`` cannot be appended where ``held`` is held. The column's own field metadata and its nested field tree must be the held ones @@ -984,18 +995,29 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: held: The column as the table holds it (its record, else its stored type, with its field metadata; or a pending batch's column). field: The column of the rows to append. + from_delta_log: Whether the held column came from the Delta log. Returns: The reason, naming the path, or ``None``. """ - if _is_logical(field) or _is_logical(held): - if _metadata(held.metadata) == _metadata(field.metadata): - return None - return f"{field.name} has other field metadata than the stored column" - return appended_field_change( - held.with_metadata(cast(Any, _metadata(held.metadata))), + held_metadata = metadata_bytes(held.metadata) + logical = _is_logical(field) or _is_logical(held) + partial_extension_metadata = logical and ( + not isinstance(field.type, pa.BaseExtensionType) + or ( + not isinstance(held.type, pa.BaseExtensionType) + and (not from_delta_log or _EXTENSION_KEYS[1] not in held_metadata) + ) + ) + changed = appended_field_change( + held.with_metadata(cast(Any, _metadata(held_metadata))), field.with_metadata(cast(Any, _metadata(field.metadata))), - ) or _evolution_change( + delta_log_storage=from_delta_log and ARROW_TYPE_KEY not in held_metadata, + partial_extension_metadata=partial_extension_metadata, + ) + if changed is not None or logical: + return changed + return _evolution_change( arrow_utils.normalize_to_large_types(held.type, keep_null=True), arrow_utils.normalize_to_large_types(field.type, keep_null=True), field.name, @@ -1005,7 +1027,7 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any]"]: """Each stored column as the table holds it: its recorded type, else its stored type, with its field metadata as stored. Read from the log; no data is read.""" - stored = _stored_arrow_schema(delta_table) + stored = _stored_arrow_schema(delta_table, keep_nested_metadata=True) fields: dict[str, pa.Field[Any]] = {} for delta_field in delta_table.schema().fields: record = recorded_type(delta_field.metadata) @@ -1266,7 +1288,7 @@ def _append_refusal( held_folded.setdefault(name.lower(), name) for field in rows.schema: if field.name in held: - change = _column_change(held[field.name], field) + change = _column_change(held[field.name], field, from_delta_log=True) if change is not None: return field.name, change elif schema_evolution: @@ -1638,40 +1660,66 @@ def _merge_source_in_stored_layout( return batch -def _without_field_metadata(delta_type: Any) -> Any: - """Return a Delta type with the metadata of every nested field dropped. +def _plain_delta_type(delta_type: Any, *, keep_user_metadata: bool) -> Any: + """Return a Delta type with extension markers stripped at every depth. Args: delta_type: A ``deltalake.schema`` type. + keep_user_metadata: Preserve user metadata on nested fields. Returns: - The same type with no field metadata at any depth. + The same storage type with the requested metadata. """ from deltalake.schema import ArrayType, Field, MapType, StructType if isinstance(delta_type, StructType): return StructType( [ - Field(f.name, _without_field_metadata(f.type), nullable=f.nullable) + Field( + f.name, + _plain_delta_type(f.type, keep_user_metadata=keep_user_metadata), + nullable=f.nullable, + metadata=( + { + k: v + for k, v in f.metadata.items() + if k.encode() != _EXTENSION_KEYS[0] + and ( + k.encode() != _EXTENSION_KEYS[1] + or _EXTENSION_KEYS[0].decode() not in f.metadata + ) + } + if keep_user_metadata + else None + ), + ) for f in delta_type.fields ] ) if isinstance(delta_type, ArrayType): return ArrayType( - _without_field_metadata(delta_type.element_type), + _plain_delta_type( + delta_type.element_type, keep_user_metadata=keep_user_metadata + ), contains_null=delta_type.contains_null, ) if isinstance(delta_type, MapType): return MapType( - _without_field_metadata(delta_type.key_type), - _without_field_metadata(delta_type.value_type), + _plain_delta_type( + delta_type.key_type, keep_user_metadata=keep_user_metadata + ), + _plain_delta_type( + delta_type.value_type, keep_user_metadata=keep_user_metadata + ), value_contains_null=delta_type.value_contains_null, ) return delta_type -def _stored_arrow_schema(delta_table: deltalake.DeltaTable) -> pa.Schema: - """Return the Arrow schema of the table's stored Delta schema, without metadata. +def _stored_arrow_schema( + delta_table: deltalake.DeltaTable, *, keep_nested_metadata: bool = False +) -> pa.Schema: + """Return the Arrow schema of the table's stored Delta schema, stripped of markers. Delta keeps the Arrow field metadata it was written with, including the extension type name of a logical type. Reading that back into pyarrow would @@ -1681,6 +1729,8 @@ def _stored_arrow_schema(delta_table: deltalake.DeltaTable) -> pa.Schema: Args: delta_table: The loaded stored table. + keep_nested_metadata: Keep user metadata on stored struct fields for the + append attribute check, while stripping extension markers. Returns: The stored schema as plain Arrow types. @@ -1690,7 +1740,11 @@ def _stored_arrow_schema(delta_table: deltalake.DeltaTable) -> pa.Schema: stored = delta_table.schema() plain = Schema( [ - Field(f.name, _without_field_metadata(f.type), nullable=f.nullable) + Field( + f.name, + _plain_delta_type(f.type, keep_user_metadata=keep_nested_metadata), + nullable=f.nullable, + ) for f in stored.fields ] ) @@ -1786,6 +1840,85 @@ def _table_id(delta_table: deltalake.DeltaTable) -> str: return str(delta_table.metadata().id) +@dataclass(frozen=True) +class _CompositeIdKey: + """An in-memory comparison key distinct from a binary record ID.""" + + value: bytes + + def __repr__(self) -> str: + """Show the storage value when reporting a duplicate.""" + return self.value.decode("utf-8") + + +@dataclass(frozen=True) +class _ArrowIdKey: + """A primitive storage value outside its Python counterpart's domain.""" + + scalar: pa.Scalar[Any] + + def __repr__(self) -> str: + """Describe the ID without converting it to an out-of-range value.""" + return f"<{self.scalar.type} storage value>" + + +def _primitive_id_value(scalar: pa.Scalar[Any]) -> Hashable: + """Preserve Arrow values that cannot be represented as Python objects.""" + try: + return scalar.as_py() + except (OverflowError, ValueError): + return _ArrowIdKey(scalar) + + +def _composite_id_value(scalar: pa.Scalar[Any] | None) -> object: + """Represent a nested Arrow value independently of its physical layout.""" + if scalar is None or not scalar.is_valid: + return None + if isinstance(scalar, (pa.ExtensionScalar, pa.DictionaryScalar)): + return _composite_id_value(scalar.value) + if isinstance(scalar, pa.StructScalar): + return { + name: _composite_id_value(scalar[name]) for name in sorted(scalar.keys()) + } + if isinstance( + scalar, + (pa.ListScalar, pa.LargeListScalar, pa.FixedSizeListScalar, pa.MapScalar), + ): + values = cast("pa.Array[Any] | None", scalar.values) + assert values is not None + return [_composite_id_value(item) for item in values] + if isinstance(scalar, pa.Date32Scalar): + return scalar.cast(pa.int32()).as_py() + if isinstance(scalar, pa.TimestampScalar): + # Delta rescales native timestamps to microseconds. Use nanosecond + # ticks on both sides of the lookup, preserving sub-microsecond values + # and matching the integer layout of a plain timestamp[ns] leaf. + tick = scalar.value + assert tick is not None + nanoseconds_per_tick = { + "s": 1_000_000_000, + "ms": 1_000_000, + "us": 1_000, + "ns": 1, + } + return tick * nanoseconds_per_tick[scalar.type.unit] + if isinstance( + scalar, + ( + pa.Date64Scalar, + pa.Time32Scalar, + pa.Time64Scalar, + pa.DurationScalar, + ), + ): + # Python's date and time objects can lose the low bits of the value. + return scalar.value + value: object = scalar.as_py() + if isinstance(value, float) and value == 0.0: + return 0.0 + return value + + @dataclass class _CommittedSnapshot: """What one version of a stored Delta table holds, kept in memory (ITL-919). @@ -1817,7 +1950,7 @@ class _CommittedSnapshot: version: int table_id: str = "" create_token: str = "" - ids: set[bytes] | None = None + ids: set[Hashable] | None = None rows: KeyIndex | None = None files: frozenset[str] = frozenset() dataset_schema: "pa.Schema | None" = None @@ -1856,7 +1989,7 @@ def __init__( _root: "DeltaTableDatabase | None" = None, _scoped_path: tuple[str, ...] = (), _shared_pending_batches: "dict[str, pa.Table] | None" = None, - _shared_pending_record_ids: "defaultdict[str, set[bytes]] | None" = None, + _shared_pending_record_ids: "defaultdict[str, set[Hashable]] | None" = None, _shared_delta_table_cache: "dict[str, deltalake.DeltaTable] | None" = None, _shared_snapshots: "dict[str, _CommittedSnapshot] | None" = None, _shared_pending_indexes: "dict[str, KeyIndex] | None" = None, @@ -1895,6 +2028,11 @@ def __init__( self._delta_table_cache: dict[str, deltalake.DeltaTable] = ( _shared_delta_table_cache if _shared_delta_table_cache is not None else {} ) + # A local directory stamp can show that a loaded log has not changed + # without asking Delta to list its commits again for every strict add. + self._local_log_stamps: dict[ + str, tuple[ReferenceType[deltalake.DeltaTable], os.stat_result] + ] = _root._local_log_stamps if _root is not None else {} if _shared_pending_batches is not None: self._pending_batches = _shared_pending_batches else: @@ -1902,7 +2040,7 @@ def __init__( if _shared_pending_record_ids is not None: self._pending_record_ids = _shared_pending_record_ids else: - self._pending_record_ids: dict[str, set[bytes]] = defaultdict(set) + self._pending_record_ids: dict[str, set[Hashable]] = defaultdict(set) # The committed rows of each loaded table version (ITL-919), shared like the # loaded tables: a snapshot describes the cached table's version only. self._snapshots: dict[str, _CommittedSnapshot] = ( @@ -1918,7 +2056,9 @@ def __init__( else PendingCommits( self.RECORD_ID_COLUMN, self._pending_batches, - self._pending_record_ids, + # Commit dependencies guard byte IDs. Other keys only travel + # through the queue's take/restore operations. + cast("dict[str, set[bytes]]", self._pending_record_ids), on_empty=self._discard_pending_index, ) ) @@ -2038,9 +2178,7 @@ def _get_delta_table( return None try: - delta_table = deltalake.DeltaTable( - table_uri, storage_options=self._storage_options or None - ) + delta_table = self._open_delta_table(table_uri) self._delta_table_cache[record_key] = delta_table logger.debug(f"Loaded existing Delta table for {record_key}") return delta_table @@ -2070,16 +2208,15 @@ def _load_delta_table_for_commit( """ from deltalake.exceptions import TableNotFoundError - options = self._storage_options or None try: - return deltalake.DeltaTable(table_uri, storage_options=options) + return self._open_delta_table(table_uri) except TableNotFoundError as missing_log: if self._is_cloud or not self._has_orphaned_delta_data_files(table_uri): return None for delay in _MISSING_LOG_RETRY_DELAYS: sleep(delay) try: - return deltalake.DeltaTable(table_uri, storage_options=options) + return self._open_delta_table(table_uri) except TableNotFoundError: continue raise FileNotFoundError( @@ -2119,6 +2256,72 @@ def _read_failed(self, record_path: tuple[str, ...]) -> OrcapodDatabaseReadError self._get_table_uri(record_path), self._path_prefix + record_path ) + def _local_log_stamp(self, table_uri: str) -> os.stat_result | None: + """Observe the local log directory, or return None if it is unavailable.""" + if self._is_cloud: + return None + try: + return (Path(table_uri) / "_delta_log").stat() + except OSError: + return None + + def _open_delta_table(self, table_uri: str) -> deltalake.DeltaTable: + """Load a table and remember the local log stamp from before the load.""" + stamp = self._local_log_stamp(table_uri) + table = deltalake.DeltaTable( + table_uri, storage_options=self._storage_options or None + ) + if stamp is not None: + self._local_log_stamps[table_uri] = (ref(table), stamp) + return table + + def _refresh_before_strict_add(self, record_path: tuple[str, ...]) -> None: + """Bring a cached table up to date without reopening it on each add.""" + record_key = self._get_record_key(record_path) + table_uri = self._get_table_uri(record_path) + stamp = self._local_log_stamp(table_uri) + cached = self._delta_table_cache.get(record_key) + if cached is not None: + if not self._is_cloud: + loaded = self._local_log_stamps.get(table_uri) + if ( + stamp is None + or loaded is None + or loaded[0]() is not cached + or not os.path.samestat(stamp, loaded[1]) + ): + # An incremental update cannot detect a different table + # recreated at the same path and version. + self._delta_table_cache.pop(record_key, None) + return + if (stamp.st_mtime_ns, stamp.st_ctime_ns) == ( + loaded[1].st_mtime_ns, + loaded[1].st_ctime_ns, + ): + return + try: + cached.update_incremental() + except Exception: # noqa: BLE001 # the commit reload reports the failure + # Keep the readable snapshot for lookups during the rest of the + # batch. The failed refresh must be retried on the next strict add. + return + if stamp is not None: + self._local_log_stamps[table_uri] = (ref(cached), stamp) + return + if record_key in self._absent_tables: + try: + appeared = ( + deltalake.DeltaTable.is_deltatable( + table_uri, storage_options=self._storage_options or None + ) + if self._is_cloud + else stamp is not None + ) + except Exception: # noqa: BLE001 # let the next load report any read failure + appeared = True + if appeared: + self._absent_tables.discard(record_key) + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the Delta tables stored under ``prefix``. @@ -2343,7 +2546,7 @@ def _snapshot( return snapshot @classmethod - def _scan_ids(cls, delta_table: deltalake.DeltaTable) -> set[bytes]: + def _scan_ids(cls, delta_table: deltalake.DeltaTable) -> set[Hashable]: """Read the record ids stored in ``delta_table`` (nulls left out). Args: @@ -2366,8 +2569,7 @@ def _scan_ids(cls, delta_table: deltalake.DeltaTable) -> set[bytes]: [id_field.with_type(arrow_utils.normalize_to_large_types(id_field.type))] ) dataset = delta_to_pyarrow_dataset(delta_table, schema=id_schema) - ids = dataset.to_table()[cls.RECORD_ID_COLUMN] - return {record_id for record_id in ids.to_pylist() if record_id is not None} + return cls._non_null_ids(dataset.to_table()) @staticmethod def _scan_rows( @@ -2405,7 +2607,7 @@ def _describe_read( snapshot.dataset_format = dataset.format snapshot.dataset_filesystem = dataset.filesystem - def _stored_ids(self, record_path: tuple[str, ...]) -> set[bytes]: + def _stored_ids(self, record_path: tuple[str, ...]) -> set[Hashable]: """Return the record ids stored at ``record_path`` (in the loaded version). Raises: @@ -2830,9 +3032,9 @@ def _refuse_changed_attributes( delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: delta_table = None - held: list[dict[str, pa.Field[Any]]] = [] + held: list[tuple[dict[str, pa.Field[Any]], bool]] = [] if pending is not None: - held.append({f.name: f for f in pending.schema}) + held.append(({f.name: f for f in pending.schema}, False)) if delta_table is not None: # The identity rule on this very table, from its log, before its recorded # types are decoded: the table loaded here may not be the one @@ -2844,12 +3046,14 @@ def _refuse_changed_attributes( f"{self._get_table_uri(record_path)!r}: column {found[0]!r}: " f"{found[1]}. The stored rows are unchanged and nothing was written." ) - held.append(_held_columns(delta_table)) - for given in held: + held.append((_held_columns(delta_table), True)) + for given, from_delta_log in held: for field in schema: if field.name not in given: continue - change = _column_change(given[field.name], field) + change = _column_change( + given[field.name], field, from_delta_log=from_delta_log + ) if change is not None: raise InputValidationError( f"Cannot append to the stored table " @@ -2921,17 +3125,21 @@ def add_records( flush: bool = False, schema_handling: Literal["merge", "error", "coerce"] = "error", ) -> None: - """ - Insert new records. By default, never overwrites existing records. + """Insert new records, keeping the first commit for each record ID. Args: - schema_handling: How to handle schema differences - skip_duplicates: If True, skip records with IDs that already exist. - If False, raise error on duplicates. - flush: Whether to flush immediately after the insert + record_path: Path to the record table, relative to this database. + records: Rows to add. + record_id_column: Name of the ID column. Defaults to the first column. + skip_duplicates: Skip pending or stored IDs when True, raise when + False. A key another writer commits after the add-time check is + skipped at commit in either mode. + flush: Whether to flush immediately after the insert. + schema_handling: How to handle schema differences. Raises: - ValueError: If any record IDs already exist and skip_duplicates=False + ValueError: If the ID column is absent or when a strict add encounters + a pending or stored ID. """ self._validate_record_path(record_path) @@ -2967,6 +3175,8 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) + if not skip_duplicates: + self._refresh_before_strict_add(record_path) self._refuse_untyped_null_columns(record_path, records.schema) # A logical type identifier known to differ from the held one is refused # first (ITL-1371), whatever skip_duplicates: found from the Delta log, before @@ -2977,6 +3187,14 @@ def add_records( if identity is not None: raise InputValidationError(identity) + id_type = records.schema.field(self.RECORD_ID_COLUMN).type + storage_type = self._id_storage_type(id_type) + # Main also refuses cross-schema plain nested IDs in write-if-missing mode. + if pa.types.is_nested(storage_type) and ( + not skip_duplicates or pa.types.is_nested(id_type) + ): + self._require_matching_nested_id_type(record_path, storage_type) + # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) @@ -2997,24 +3215,7 @@ def add_records( logger.debug("All records were duplicates, nothing to insert") return None else: - # 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." - ) + self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table # Against the rows queued, on the rows that remain once duplicates are @@ -3101,7 +3302,9 @@ def _filter_existing_records( self, record_path: tuple[str, ...], table: pa.Table ) -> tuple[pa.Table, set[bytes]]: """Filter out records that already exist (for skip_duplicates=True).""" - input_ids = set(cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist())) + ids = self._id_storage(table) + id_keys = self._id_keys(ids) + input_ids = set(id_keys) record_key = self._get_record_key(record_path) # Get IDs that already exist in pending batch or Delta table @@ -3118,41 +3321,165 @@ def _filter_existing_records( # 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)) + if ( + existing_in_delta + and pa.types.is_nested(ids.type) + and isinstance( + table.schema.field(self.RECORD_ID_COLUMN).type, pa.BaseExtensionType + ) + ): + self._require_compatible_stored_extension_id(record_path, ids.type) all_existing = existing_in_pending.union(existing_in_delta) + # Pipeline receipts use bytes IDs; the duplicate index also holds other keys. + durable = cast("set[bytes]", existing_in_delta) if not all_existing: - return table, existing_in_delta # No duplicates found + return table, durable # No duplicates found # Filter out existing records - mask = pc.invert( - pc.is_in(table[self.RECORD_ID_COLUMN], pa.array(list(all_existing))) - ) + if pa.types.is_nested(ids.type): + mask = pa.array( + [key not in all_existing for key in id_keys], type=pa.bool_() + ) + elif isinstance( + table.schema.field(self.RECORD_ID_COLUMN).type, pa.BaseExtensionType + ) or any(isinstance(key, _ArrowIdKey) for key in all_existing): + pending = self._pending_batches.get(record_key) + pending_ids = ( + self._id_storage(pending) + if pending is not None and existing_in_pending + else None + ) + matches = self._match_primitive_ids( + ids, + pending_ids, + existing_in_delta if pending_ids is not None else all_existing, + ) + if matches is None: + matches = pc.is_in( + table[self.RECORD_ID_COLUMN], + pa.array(cast("list[Any]", list(all_existing))), + ) + mask = pc.invert(matches) + else: + values = cast("list[Any]", list(all_existing)) + mask = pc.invert(pc.is_in(ids, pa.array(values))) filtered = table.filter(mask) logger.debug(f"Skipped {len(all_existing)} duplicate records") - return filtered, existing_in_delta + return filtered, durable + + def _require_compatible_stored_extension_id( + self, record_path: tuple[str, ...], incoming_type: pa.DataType + ) -> None: + """Check storage types before a matching nested extension ID is dropped.""" + delta_table = self._get_delta_table(record_path) + assert delta_table is not None # The duplicate scan just loaded this table. + column = self.RECORD_ID_COLUMN + stored_type = _stored_arrow_schema(delta_table).field(column).type + # Delta can normalize an extension's storage when writing it, for example + # changing timestamps to microseconds. Compare in that same layout. + written = _as_delta_writer_stores(pa.schema([pa.field(column, incoming_type)])) + if _types_conflict( + _comparable_storage_type(stored_type), + _comparable_storage_type(written.field(column).type), + ): + raise InputValidationError( + f"Record ID storage type {incoming_type} differs from the " + f"stored table's record ID storage type {stored_type}." + ) + + def _require_matching_nested_id_type( + self, record_path: tuple[str, ...], incoming_type: pa.DataType + ) -> None: + """Refuse nested IDs that schema handling could change after lookup.""" + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + pending_type = self._id_storage_type( + pending.schema.field(self.RECORD_ID_COLUMN).type + ) + if not incoming_type.equals(pending_type): + raise InputValidationError( + f"Record ID storage type {incoming_type} differs from the " + f"pending batch's record ID storage type {pending_type}." + ) + + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + # The duplicate scan and flush already handle a failed table read. + return + if delta_table is None: + return + for field in delta_table.schema().fields: + if field.name != self.RECORD_ID_COLUMN: + continue + recorded = _recorded_field(field.name, field.metadata) + if recorded is not None: + stored_type = self._id_storage_type(recorded.type) + matches = incoming_type.equals(stored_type) + else: + stored_type = _stored_arrow_schema(delta_table).field(field.name).type + # The Delta log alone does not preserve Arrow offset widths. + normalize = arrow_utils.normalize_to_large_types + matches = normalize(incoming_type, keep_null=True).equals( + normalize(stored_type, keep_null=True) + ) + if not matches: + raise InputValidationError( + f"Record ID storage type {incoming_type} differs from the " + f"stored table's record ID storage type {stored_type}." + ) + return def _check_all_conflicts( self, record_path: tuple[str, ...], table: pa.Table ) -> None: """Check for conflicts with both pending batch and Delta table.""" - input_ids = set(table[self.RECORD_ID_COLUMN].to_pylist()) + input_ids = set(self._id_keys(self._id_storage(table))) record_key = self._get_record_key(record_path) - # Check conflicts with pending batch - pending_conflicts = input_ids.intersection(self._pending_record_ids[record_key]) + pending_conflicts = input_ids.intersection( + self._pending_record_ids.get(record_key, ()) + ) + if pending_conflicts and self._has_primitive_extension_id(table): + pending_ids = self._id_storage(self._pending_batches[record_key]) + matches = self._match_primitive_ids( + self._id_storage(table), pending_ids, set() + ) + if matches is not None and not pc.any(matches).as_py(): + pending_conflicts.clear() if pending_conflicts: raise ValueError( - f"Cannot insert records with IDs that already exist in pending batch: {pending_conflicts}. " - f"Use skip_duplicates=True to skip existing records or update() method to overwrite." + f"Records with IDs {pending_conflicts} already exist in the pending " + "batch. Use skip_duplicates=True to skip them." ) - # Check conflicts with Delta table - existing_ids = self._stored_ids(record_path) - delta_conflicts = input_ids.intersection(existing_ids) + try: + stored_ids = self._stored_ids(record_path) + except OrcapodDatabaseReadError: + # As with schema preflight, flush checks the store again and reports + # the read error if it still cannot read this table. + return + if not stored_ids: + return + field = table.schema.field(self.RECORD_ID_COLUMN) + if not field.type.equals(written_field(field).type): + # The ID cache holds the values in the physical Delta layout, e.g. + # integer ticks for a nanosecond timestamp. + input_ids = self._non_null_ids( + to_delta_layout(table.select([self.RECORD_ID_COLUMN])) + ) + delta_conflicts = input_ids.intersection(stored_ids) + if delta_conflicts and self._has_primitive_extension_id(table): + matches = self._match_primitive_ids( + self._id_storage(table), None, delta_conflicts + ) + if matches is not None and not pc.any(matches).as_py(): + delta_conflicts.clear() if delta_conflicts: raise ValueError( - f"Cannot insert records with IDs that already exist in Delta table: {delta_conflicts}. " - f"Use skip_duplicates=True to skip existing records or update() method to overwrite." + f"Records with IDs {delta_conflicts} already exist in the stored " + "table. Use skip_duplicates=True to skip them." ) def _handle_schema_compatibility( @@ -3260,9 +3587,9 @@ def _add_to_pending_batch( if index is not None and index.table is pending_batch: index.append(table, grown) - pending_ids = set(cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist())) + pending_ids = set(self._id_keys(self._id_storage(table))) self._pending_record_ids[record_key].update(pending_ids) - return pending_ids + return cast("set[bytes]", pending_ids) def _should_auto_flush(self, record_path: tuple[str, ...]) -> bool: """Check if auto-flush should be triggered.""" @@ -3315,7 +3642,7 @@ def _without_stored_ids( # is kept. keep = [ record_id is None or record_id not in stored_ids - for record_id in pending[self.RECORD_ID_COLUMN].to_pylist() + for record_id in self._id_keys(self._id_storage(pending)) ] if not all(keep): pending = pending.filter(pa.array(keep, type=pa.bool_())) @@ -3788,10 +4115,11 @@ def refresh_table(self, record_path: tuple[str, ...]) -> None: cached = self._delta_table_cache.get(record_key) if cached is None: return + table_uri = self._get_table_uri(record_path) + stamp = self._local_log_stamp(table_uri) try: latest = deltalake.DeltaTable( - self._get_table_uri(record_path), - storage_options=self._storage_options or None, + table_uri, storage_options=self._storage_options or None ) except Exception: # The next read loads the table again and reports a failure itself. @@ -3800,6 +4128,8 @@ def refresh_table(self, record_path: tuple[str, ...]) -> None: return if latest.version() != cached.version(): self._delta_table_cache[record_key] = latest + if stamp is not None: + self._local_log_stamps[table_uri] = (ref(latest), stamp) self._snapshots.pop(record_key, None) def _flush_by_key(self, record_key: str) -> None: @@ -3962,9 +4292,7 @@ def _flush_by_key(self, record_key: str) -> None: committed = ( delta_table if delta_table is not None - else deltalake.DeltaTable( - table_uri, storage_options=self._storage_options or None - ) + else self._open_delta_table(table_uri) ) self._delta_table_cache[record_key] = committed self._snapshots[record_key] = self._extend_snapshot( @@ -3982,7 +4310,7 @@ def _commit_once( table_uri: str, abs_path_components: tuple[str, ...], original_table: pa.Table, - ) -> tuple[deltalake.DeltaTable | None, _CommittedSnapshot, set[bytes]]: + ) -> tuple[deltalake.DeltaTable | None, _CommittedSnapshot, set[Hashable]]: """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 @@ -4108,13 +4436,12 @@ 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, + # A non-streamed MERGE translates the source's ID range to SQL. + # Delta cannot express nested ID literals there, but can still + # compare those IDs in the join. For primitive IDs, keep range + # planning (ITL-1377). New tables exclude IDs from file statistics + # (ITL-1444), so the commit still checks for concurrent writes. + streamed_exec=pa.types.is_nested(self._id_storage(combined_table).type), ).when_not_matched_insert_all().execute() except CommitFailedError as conflict: raise _LostCommitRace(conflict) from conflict @@ -4164,11 +4491,100 @@ def _rows_with_ids( return rows_at(rows.table, sorted(positions)) @classmethod - def _non_null_ids(cls, table: pa.Table) -> set[bytes]: + def _id_storage(cls, table: pa.Table) -> pa.ChunkedArray[Any]: + """Return the ID column as storage values for duplicate checks. + + A Delta scan reads storage values. A buffered or just-committed Arrow + column may still be wrapped in an extension or dictionary encoding. + """ + ids = table[cls.RECORD_ID_COLUMN] + while True: + id_type = ids.type + if isinstance(id_type, pa.BaseExtensionType): + # The stubs cannot infer the storage type from the extension. + storage_type: Any = id_type.storage_type + ids = pa.chunked_array( + [ + cast("pa.ExtensionArray[Any]", chunk).storage + for chunk in ids.chunks + ], + type=storage_type, + ) + elif isinstance(id_type, pa.DictionaryType): + ids = ids.cast(id_type.value_type) + else: + return ids + + @staticmethod + def _id_storage_type(arrow_type: pa.DataType) -> pa.DataType: + """Return the type read by the duplicate index after decoding the ID.""" + while isinstance(arrow_type, (pa.BaseExtensionType, pa.DictionaryType)): + if isinstance(arrow_type, pa.BaseExtensionType): + arrow_type = arrow_type.storage_type + else: + arrow_type = arrow_type.value_type + return arrow_type + + @staticmethod + def _id_keys(ids: pa.ChunkedArray[Any]) -> Sequence[Hashable]: + """Build row-aligned comparison keys from the unwrapped ID column.""" + if not pa.types.is_nested(ids.type): + try: + return ids.to_pylist() + except (OverflowError, ValueError): + return [ + _primitive_id_value(scalar) + for scalar in cast("Iterator[pa.Scalar[Any]]", iter(ids)) + ] + # List/struct set lookup has no Arrow kernel, and the hash of a ListScalar + # only distinguishes its length. Encode the value tree (ordered lists and + # structs in name order) as bytes for the in-memory duplicate indexes. + scalars = cast("Iterator[pa.Scalar[Any]]", iter(ids)) + return [ + _CompositeIdKey(repr(_composite_id_value(scalar)).encode("utf-8")) + if scalar.is_valid + else None + for scalar in scalars + ] + + @classmethod + def _has_primitive_extension_id(cls, table: pa.Table) -> bool: + """Return whether Arrow can compare this ID after unwrapping it.""" + return isinstance( + table.schema.field(cls.RECORD_ID_COLUMN).type, pa.BaseExtensionType + ) and not pa.types.is_nested(cls._id_storage(table).type) + + @staticmethod + def _match_primitive_ids( + ids: pa.ChunkedArray[Any], + pending: pa.ChunkedArray[Any] | None, + stored: set[Hashable], + ) -> pa.Array[Any] | None: + """Compare primitive IDs in Arrow, preserving the storage type.""" + if pending is not None and not pending.type.equals(ids.type): + return None + candidates = pa.array( + [ + key.scalar + if isinstance(key, _ArrowIdKey) + else pa.scalar(key, type=ids.type) + for key in stored + ], + type=ids.type, + ) + if pending is not None: + candidates = pa.concat_arrays([pending.combine_chunks(), candidates]) + try: + return pc.is_in(ids, candidates) + except pa.ArrowNotImplementedError: + return None + + @classmethod + def _non_null_ids(cls, table: pa.Table) -> set[Hashable]: """Return the record ids of ``table``'s rows, nulls left out.""" return { record_id - for record_id in table[cls.RECORD_ID_COLUMN].to_pylist() + for record_id in cls._id_keys(cls._id_storage(table)) if record_id is not None } @@ -4217,7 +4633,7 @@ def _extend_snapshot( self, base: _CommittedSnapshot, committed: deltalake.DeltaTable, - inserted_ids: set[bytes], + inserted_ids: set[Hashable], ) -> _CommittedSnapshot: """Return the snapshot of ``committed``, built from ``base`` plus this commit. diff --git a/src/orcapod/databases/delta_statistics.py b/src/orcapod/databases/delta_statistics.py index a5b81a0c9..b640c19c3 100644 --- a/src/orcapod/databases/delta_statistics.py +++ b/src/orcapod/databases/delta_statistics.py @@ -11,7 +11,9 @@ the one rule for that list. A column is listed when it is a top-level column whose type, or the storage type of its extension type, is one delta-rs makes statistics for: an integer, ``float32`` or ``float64``, a boolean, a string, ``date32``, a timestamp or -``decimal128``. Every other column is left out: binary of any kind, lists, maps, +``decimal128``. The record ID is excluded regardless of its type so that concurrent +MERGEs cannot skip files when checking for a conflicting write (ITL-1444). Every other +unsupported type is left out: binary of any kind, lists, maps, structs, ``null`` and the rest. A column whose name holds a comma or a backtick is left out too: delta-rs splits the property on commas before it reads quoting, and it cannot MERGE into a table with a backtick in a column name whether or not the column is listed @@ -34,8 +36,8 @@ The property is set once, when the table is created, and Orcapod never changes it. A column added later by schema evolution is not in the list: delta-rs makes no statistics for it and logs nothing for it, unless it has a nested binary field named like a listed -column (then delta-rs warns for that field). A table created before this change has no property and is -read and appended to as before, unaltered; delta-rs keeps logging its warnings (see +column (then delta-rs warns for that field). Tables created before this change retain +their configuration. Tables without the property still log their warnings (see ``docs/troubleshooting.md``). The property is Delta table metadata only: it changes no stored value, column, hash, path or layout. @@ -116,7 +118,8 @@ def statistics_columns(schema: pa.Schema) -> list[str]: schema: The schema of the rows that create the table, as written to Delta. Returns: - The top-level columns whose type delta-rs makes statistics for, whose name holds + The top-level columns other than the record ID whose type delta-rs makes + statistics for, whose name holds no comma and no backtick, and whose name is no nested part's name (``_nested_names``) in any column of ``schema``. """ @@ -126,7 +129,8 @@ def statistics_columns(schema: pa.Schema) -> list[str]: return [ field.name for field in schema - if _has_statistics(field.type) + if field.name != "__record_id" + and _has_statistics(field.type) and "," not in field.name and "`" not in field.name and field.name not in nested diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 3a94109e5..7a917cc6f 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -324,16 +324,24 @@ def add_records( report_records(record_key, added=set(), durable=durable) return else: - # Check for conflicts in the pending batch only input_ids = set( cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) ) - pending_conflicts = input_ids & self._pending_record_ids[record_key] + pending_conflicts = input_ids.intersection( + self._pending_record_ids.get(record_key, ()) + ) if pending_conflicts: raise ValueError( f"Records with IDs {pending_conflicts} already exist in the " f"pending batch. Use skip_duplicates=True to skip them." ) + committed_ids = self._committed_id_index(record_key) + stored_conflicts = {rid for rid in input_ids if rid in committed_ids} + if stored_conflicts: + raise ValueError( + f"Records with IDs {stored_conflicts} already exist in the stored " + "table. Use skip_duplicates=True to skip them." + ) # Add to pending batch existing_pending = self._pending_batches.get(record_key) @@ -452,20 +460,14 @@ def _promote(self, record_key: str, pending: "pa.Table") -> None: self._tables[record_key] = pending.combine_chunks() return - # Insert-if-not-exists: keep committed rows not overwritten by new batch, - # then append the new batch on top. - new_ids = pending[self.RECORD_ID_COLUMN].to_pylist() committed_ids = self._committed_id_index(record_key) - if any(record_id in committed_ids for record_id in new_ids): - mask = pc.invert( - pc.is_in(committed[self.RECORD_ID_COLUMN], pa.array(list(new_ids))) + ids = pending[self.RECORD_ID_COLUMN] + conflicts = {rid for rid in ids.to_pylist() if rid in committed_ids} + if conflicts: + pending = pending.filter( + pc.invert(pc.is_in(ids, pa.array(list(conflicts)))) ) - kept = committed.filter(mask) - self._tables[record_key] = pa.concat_tables( - [kept, pending] - ).combine_chunks() - # Rows moved: the indexes are rebuilt on the next lookup. - self._indexes.pop(record_key, None) + if pending.num_rows == 0: return appended = compact_tail(pa.concat_tables([committed, pending])) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 32620eb99..600238a32 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -571,6 +571,42 @@ def get_current_store_schema(self) -> str: _require_persistent_store_schema(schema, row[1]) return schema + def existing_record_ids( + self, + table_name: str, + id_column: str, + ids: set[bytes], + *, + schema: str | None = None, + ) -> set[bytes]: + """Look up existing record IDs using the table's primary key.""" + from psycopg import sql + + relation = (table_name,) if schema is None else (schema, table_name) + table = sql.Identifier(*(part.replace("%", "%%") for part in relation)) + column = sql.Identifier(id_column.replace("%", "%%")) + conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) + with self._lock, conn.transaction(force_rollback=True), conn.cursor() as cur: + _ = cur.execute( + sql.SQL( + "SELECT {id} FROM {table} WHERE {id} = ANY(%s::bytea[])" + ).format(id=column, table=table), + (list(ids),), + ) + return {cast(bytes, row[0]) for row in cur} + + def insert_store_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + *, + skip_duplicates: bool, + schema: str, + ) -> None: + """Insert rows, skipping only ID conflicts at commit in either mode.""" + self.upsert_records(table_name, records, id_column, True, schema=schema) + @contextmanager def store_table_transaction( self, table_name: str, path_json: str, *, schema: str diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 056090f6b..f3e3726a4 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1066,6 +1066,13 @@ def create_table_if_not_exists( self._require_open() raise SpiralDBWriteNotSupportedError(_NO_WRITES) + def existing_record_ids( + self, table_name: str, id_column: str, ids: set[bytes] + ) -> set[bytes]: + """Refuse a duplicate check for writes, which SpiralDB does not support.""" + self._require_open() + raise SpiralDBWriteNotSupportedError(_NO_WRITES) + def upsert_records( self, table_name: str, diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 684de8bb7..83fa8831f 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -349,6 +349,32 @@ def get_current_store_schema(self) -> str: self._require_open() return "main" + def existing_record_ids( + self, + table_name: str, + id_column: str, + ids: set[bytes], + *, + schema: str | None = None, + ) -> set[bytes]: + """Look up existing record IDs using the table's primary key.""" + table = sql_table_identifier(table_name, schema) + column = sql_table_identifier(id_column) + values = list(ids) + found: set[bytes] = set() + with self._lock: + conn = self._require_open() + # Stay below SQLite's variable limit, including builds limited to 999. + for start in range(0, len(values), 500): + keys = values[start : start + 500] + placeholders = ", ".join("?" for _ in keys) + cursor = conn.execute( + f"SELECT {column} FROM {table} WHERE {column} IN ({placeholders})", + keys, + ) + found.update(cast(bytes, row[0]) for row in cursor) + return found + @contextmanager def store_table_transaction( self, table_name: str, path_json: str, *, schema: str @@ -618,14 +644,52 @@ def upsert_records( (INSERT OR IGNORE). If False, overwrite (INSERT OR REPLACE). schema: The verified schema when called by a connector store. """ + policy = " OR IGNORE" if skip_existing else " OR REPLACE" + self._insert_records(table_name, records, schema, policy=policy) + + def insert_store_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + *, + skip_duplicates: bool, + schema: str, + ) -> None: + """Insert with SQLite's usual conflict policy, keeping any committed ID.""" + if skip_duplicates: + self.upsert_records(table_name, records, id_column, True, schema=schema) + else: + column = sql_table_identifier(id_column) + self._insert_records( + table_name, + records, + schema, + policy=" OR REPLACE", + conflict_clause=f" ON CONFLICT ({column}) DO NOTHING", + ) + + def _insert_records( + self, + table_name: str, + records: pa.Table, + schema: str | None, + *, + policy: str, + conflict_clause: str = "", + ) -> None: + """Write a batch under the selected SQLite conflict policy.""" with self._lock: conn = self._require_open() self._validate_table_name(table_name) cols = list(records.column_names) - col_list = ", ".join('"' + c.replace('"', '""') + '"' for c in cols) + col_list = ", ".join(sql_table_identifier(c) for c in cols) placeholders = ", ".join("?" for _ in cols) - verb = "INSERT OR IGNORE" if skip_existing else "INSERT OR REPLACE" - sql = f"{verb} INTO {sql_table_identifier(table_name, schema)} ({col_list}) VALUES ({placeholders})" + target = sql_table_identifier(table_name, schema) + sql = ( + f"INSERT{policy} INTO {target} ({col_list}) VALUES ({placeholders})" + f"{conflict_clause}" + ) rows = (tuple(row[c] for c in cols) for row in records.to_pylist()) conn.executemany(sql, rows) diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 1bb640db2..4476ae823 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -132,16 +132,20 @@ def metadata_bytes(metadata: Mapping[Any, Any] | None) -> dict[bytes, bytes]: def appended_field_change( - held: "pa.Field[Any]", incoming: "pa.Field[Any]" + held: "pa.Field[Any]", + incoming: "pa.Field[Any]", + *, + delta_log_storage: bool = False, + partial_extension_metadata: bool = False, ) -> str | None: """Say why rows of ``incoming`` would not read back as written, appended to a column a database holds as ``held`` (ITL-1334). A table holds one type per column, so an appended column must have the held column's field metadata and, at every depth, each nested field's name and metadata - (a struct's children, matched by name; a list's item; a map's key and item) and a - map's ``keys_sorted``: otherwise one side's rows read back with the other side's - attributes. A struct field on one side only, and a difference in a type's kind or + (a struct's children, matched by name; a list's item; a map's key and item; + fields of extension storage) and a map's ``keys_sorted``: otherwise one side's + rows read back with the other side's attributes. A struct field on one side only, and a difference in a type's kind or parameters, are left to the database's own append rule (struct evolution, a type conflict). Nullability, at any depth, is too: whether a nullability change is refused belongs to the nullability audit (ITL-842). @@ -149,6 +153,13 @@ def appended_field_change( Args: held: The column as the database holds it (stored or pending). incoming: The column of the rows to append. + delta_log_storage: The held type is the physical Delta log type. Within + extension storage the log cannot describe metadata on list items or + map keys and values. Struct field metadata is still known, apart + from the logical identifiers checked separately against the log. + partial_extension_metadata: A top-level Arrow annotation describes an + extension without a concrete type. Compare explicit metadata values + on corresponding storage fields. Missing attributes are unknown. Returns: The reason, naming the path (``x``, ``x.a``, ``x[]``, ``x.key``), or ``None``. @@ -159,43 +170,125 @@ def appended_field_change( arrow_utils.normalize_to_large_types(held.type, keep_null=True), arrow_utils.normalize_to_large_types(incoming.type, keep_null=True), incoming.name, + delta_log_storage=delta_log_storage, + metadata_only=partial_extension_metadata, + partial_metadata=partial_extension_metadata, ) def _child_change( - held: "pa.Field[Any]", incoming: "pa.Field[Any]", path: str + held: "pa.Field[Any]", + incoming: "pa.Field[Any]", + path: str, + *, + metadata_only: bool, + delta_log_storage: bool, + partial_metadata: bool, + check_metadata: bool = True, ) -> str | None: - if held.name != incoming.name: + if not metadata_only and held.name != incoming.name: return f"{path} is named {incoming.name!r}, the stored column's {held.name!r}" - if metadata_bytes(held.metadata) != metadata_bytes(incoming.metadata): + held_metadata = metadata_bytes(held.metadata) + incoming_metadata = metadata_bytes(incoming.metadata) + partial_child_storage = partial_metadata + if metadata_only: + for field, metadata in ((held, held_metadata), (incoming, incoming_metadata)): + if _EXTENSION_NAME in metadata: + # The identifier check owns these annotations. A decoded + # extension may still expose explicit storage field metadata. + del metadata[_EXTENSION_NAME] + metadata.pop(_EXTENSION_METADATA, None) + partial_child_storage |= not isinstance( + field.type, pa.BaseExtensionType + ) + if partial_metadata: + common = held_metadata.keys() & incoming_metadata.keys() + held_metadata = {key: held_metadata[key] for key in common} + incoming_metadata = {key: incoming_metadata[key] for key in common} + if check_metadata and held_metadata != incoming_metadata: return f"{path} has other field metadata than the stored column" - return _nested_change(held.type, incoming.type, path) + return _nested_change( + held.type, + incoming.type, + path, + metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + partial_metadata=partial_child_storage, + ) -def _nested_change(held: Any, incoming: Any, path: str) -> str | None: +def _nested_change( + held: Any, + incoming: Any, + path: str, + *, + delta_log_storage: bool, + metadata_only: bool = False, + partial_metadata: bool = False, +) -> str | None: + # Field metadata matters inside extension storage. Its layout is checked + # separately, and may use physical field names (e.g. Delta's list "element"). + while isinstance(held, pa.BaseExtensionType): + held = held.storage_type + metadata_only = True + while isinstance(incoming, pa.BaseExtensionType): + incoming = incoming.storage_type + metadata_only = True t = pa.types if t.is_struct(held) and t.is_struct(incoming): known = {f.name: f for f in held} for field in incoming: if field.name in known: - found = _child_change(known[field.name], field, f"{path}.{field.name}") + found = _child_change( + known[field.name], + field, + f"{path}.{field.name}", + metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + partial_metadata=partial_metadata, + ) if found is not None: return found return None + # Delta has no field annotation for these positions. Continue into their + # types because a struct child further down still has its own metadata. + collection_metadata_known = not ( + metadata_only and (delta_log_storage or partial_metadata) + ) if t.is_map(held) and t.is_map(incoming): - if held.keys_sorted != incoming.keys_sorted: + if not metadata_only and held.keys_sorted != incoming.keys_sorted: return ( f"{path} has keys_sorted={incoming.keys_sorted}, the stored column " f"{held.keys_sorted}" ) return _child_change( - held.key_field, incoming.key_field, f"{path}.key" - ) or _child_change(held.item_field, incoming.item_field, f"{path}.item") + held.key_field, + incoming.key_field, + f"{path}.key", + metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + partial_metadata=partial_metadata, + check_metadata=collection_metadata_known, + ) or _child_change( + held.item_field, + incoming.item_field, + f"{path}.item", + metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + partial_metadata=partial_metadata, + check_metadata=collection_metadata_known, + ) lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) if any(k(held) for k in lists) and any(k(incoming) for k in lists): # cast: the type guards above narrow the types in the stubs' terms. return _child_change( - cast(Any, held).value_field, cast(Any, incoming).value_field, f"{path}[]" + cast(Any, held).value_field, + cast(Any, incoming).value_field, + f"{path}[]", + metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + partial_metadata=partial_metadata, + check_metadata=collection_metadata_known, ) return None diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index 15779e33a..b87eb12dc 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -85,7 +85,9 @@ def add_record( record: pa.Table, skip_duplicates: bool = False, flush: bool = False, - ) -> None: ... + ) -> None: + """Add one record using the duplicate policy of ``add_records``.""" + ... def add_records( self, @@ -94,7 +96,15 @@ def add_records( record_id_column: str | None = None, skip_duplicates: bool = False, flush: bool = False, - ) -> None: ... + ) -> None: + """Add records, retaining the last row per ID within this input table. + + With ``skip_duplicates=False``, raise ``ValueError`` if an ID is already + pending or visible in storage when the rows are added. With + ``skip_duplicates=True``, skip those IDs. In either mode a key committed + by another writer after the add-time check is skipped at commit. + """ + ... def get_record_by_id( self, diff --git a/src/orcapod/protocols/db_connector_protocol.py b/src/orcapod/protocols/db_connector_protocol.py index 6ed2f94bd..1fd57380f 100644 --- a/src/orcapod/protocols/db_connector_protocol.py +++ b/src/orcapod/protocols/db_connector_protocol.py @@ -84,6 +84,16 @@ def iter_batches( # ── Write ───────────────────────────────────────────────────────────────── + def existing_record_ids( + self, table_name: str, id_column: str, ids: set[bytes] + ) -> set[bytes]: + """Look up which supplied binary IDs exist in a record table. + + Use the table's primary key to look up only the supplied IDs, returning + only the matching IDs. Read-only connectors may refuse this write check. + """ + ... + def create_table_if_not_exists( self, table_name: str, diff --git a/tests/test_core/sources/test_db_table_source.py b/tests/test_core/sources/test_db_table_source.py index 3c96c2b42..6375826b8 100644 --- a/tests/test_core/sources/test_db_table_source.py +++ b/tests/test_core/sources/test_db_table_source.py @@ -71,6 +71,12 @@ def iter_batches( for batch in table.to_batches(max_chunksize=batch_size): yield batch + def existing_record_ids( + self, table_name: str, id_column: str, ids: set[bytes] + ) -> set[bytes]: + """Refuse duplicate checks on this read-only connector.""" + raise NotImplementedError + def create_table_if_not_exists(self, *args: Any, **kwargs: Any) -> None: pass # not used by DBTableSource diff --git a/tests/test_core/sources/test_repeated_dict_keys.py b/tests/test_core/sources/test_repeated_dict_keys.py index 1529249ec..90b74662c 100644 --- a/tests/test_core/sources/test_repeated_dict_keys.py +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -924,7 +924,8 @@ def test_a_cached_source_refuses_a_stored_row_with_a_repeated_key() -> None: def test_a_plain_derived_source_refuses_a_stored_row_with_a_repeated_key() -> None: stream = ArrowTableStream(_one_row(["dup", "dup"]), tag_columns=["a", "b"]) - database = InMemoryArrowDatabase() + tables: dict[str, pa.Table] = {} + database = InMemoryArrowDatabase(_shared_tables=tables) node = OperatorJobNode( operator=SelectDataColumns(["d"]), input_streams=[stream], @@ -941,18 +942,13 @@ def test_a_plain_derived_source_refuses_a_stored_row_with_a_repeated_key() -> No with pytest.raises(RepeatedDictKeyError): list(derived.iter_data()) - # Correct the logged record. The same source should retry the read. - (path,) = database.list_table_paths() - stored = database.get_all_records(path, record_id_column=node.HASH_COLUMN_NAME) - assert stored is not None - corrected = stored.set_column( + # Repair the stored fixture in place so the same source can retry the read. + ((key, stored),) = tables.items() + tables[key] = stored.set_column( stored.schema.get_field_index("d"), stored.schema.field("d"), _one_row(["ok"])["d"], ) - database.add_records( - path, corrected, record_id_column=node.HASH_COLUMN_NAME, flush=True - ) assert derived.as_table()["d"].to_pylist() == [_entries("ok")] diff --git a/tests/test_core/sources/test_tag_columns_normalization.py b/tests/test_core/sources/test_tag_columns_normalization.py index 2b3f73bba..a400cc540 100644 --- a/tests/test_core/sources/test_tag_columns_normalization.py +++ b/tests/test_core/sources/test_tag_columns_normalization.py @@ -372,6 +372,12 @@ def iter_batches( if table is not None: yield from table.to_batches() + def existing_record_ids( + self, table_name: str, id_column: str, ids: set[bytes] + ) -> set[bytes]: + """Refuse duplicate checks on this read-only connector.""" + raise NotImplementedError + def create_table_if_not_exists(self, *a: Any, **kw: Any) -> None: pass diff --git a/tests/test_core/test_result_cache.py b/tests/test_core/test_result_cache.py index 774641fbe..8102f9555 100644 --- a/tests/test_core/test_result_cache.py +++ b/tests/test_core/test_result_cache.py @@ -30,7 +30,7 @@ InMemoryArrowDatabase, SpiralDBConnector, ) -from orcapod.errors import UnrecordedTableSchemaWarning +from orcapod.errors import OrcapodDatabaseWriteError, UnrecordedTableSchemaWarning from orcapod.protocols.core_protocols.datagrams import DataProtocol from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.semantic_types import UniversalTypeConverter @@ -91,6 +91,43 @@ def _compute_and_store(cache: ResultCache, pf: PythonDataFunction, input_data: D TIE_ORDERS = [(0, 1), (1, 0), (0, 2, 1), (2, 1, 0)] +@pytest.mark.parametrize("backend", ["memory", "delta"]) +def test_store_refuses_a_reused_output_uuid(tmp_path: Path, backend: str) -> None: + """A real duplicate is reported as a cache write error, with the cause.""" + db = ( + InMemoryArrowDatabase() if backend == "memory" else DeltaTableDatabase(tmp_path) + ) + cache = ResultCache(result_database=db, record_path=("test",), revision="rev1") + input_data = Data({"x": 10}) + output = _make_pf().direct_call(input_data) + assert output is not None + variation, execution = ( + Datagram({"function_name": "double"}), + Datagram({"executor": "test"}), + ) + + def store(*, skip_duplicates: bool = False) -> None: + cache.store( + input_data, + output, + variation, + execution, + skip_duplicates=skip_duplicates, + data_context_key=CONTEXT_KEY, + ) + + store() + db.flush() + with pytest.raises(OrcapodDatabaseWriteError) as info: + store() + assert isinstance(info.value.__cause__, ValueError) + assert "already exist in the stored table" in str(info.value.__cause__) + store(skip_duplicates=True) + db.flush() + rows = db.get_all_records(cache.record_path, record_id_column="id") + assert rows is not None and rows["id"].to_pylist() == [output.datagram_uuid.bytes] + + def check_result_lookup_timestamp_tie( database: ArrowDatabaseProtocol, order: tuple[int, ...], diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 599042e9a..b22b8053b 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -537,9 +537,13 @@ def test_a_reordered_append_is_stored_once_across_writers( PATH, _race_rows(1, 10, ("rid", "a", "b")), record_id_column="rid", flush=True ) snapshot = stale._snapshot_for_commit + winner_committed: list[bool] = [] def interleave(*args: Any) -> Any: taken = snapshot(*args) + if winner_committed: + return taken + winner_committed.append(True) other.add_records( PATH, _race_rows(2, 20, other_order), @@ -805,12 +809,15 @@ def test_a_refused_reordered_append_leaves_the_next_batch_committed( db.add_records(PATH, bad, **kwargs) if race: snapshot = db._snapshot_for_commit + winner_committed: list[bool] = [] def interleave(*args: Any) -> Any: taken = snapshot(*args) - DeltaTableDatabase(tmp_path).add_records( - PATH, _abc(3), flush=True, **kwargs - ) + if not winner_committed: + winner_committed.append(True) + DeltaTableDatabase(tmp_path).add_records( + PATH, _abc(3), flush=True, **kwargs + ) return taken with patch.object(db, "_snapshot_for_commit", side_effect=interleave): @@ -935,12 +942,15 @@ def rows(n: int) -> pa.Table: write_deltalake(tmp_path / "t", rows(1), mode="overwrite") db.add_records(PATH, rows(2), record_id_column="__record_id") snapshot = db._snapshot_for_commit + winner_committed: list[bool] = [] def interleave(*args: Any) -> Any: taken = snapshot(*args) - DeltaTableDatabase(tmp_path).add_records( - PATH, rows(3), flush=True, record_id_column="__record_id" - ) + if not winner_committed: + winner_committed.append(True) + DeltaTableDatabase(tmp_path).add_records( + PATH, rows(3), flush=True, record_id_column="__record_id" + ) return taken with patch.object(db, "_snapshot_for_commit", side_effect=interleave): diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index b4640fb66..9d454ec48 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -18,7 +18,9 @@ import pyarrow as pa import pytest +from orcapod.databases import ConnectorArrowDatabase, DeltaTableDatabase from orcapod.errors import InputValidationError, UnstorableColumnError +from tests.test_databases.test_connector_arrow_database import MockDBConnector from tests.test_databases.type_matrix import ( expected_field, field_difference, @@ -250,3 +252,331 @@ def test_delta_compares_attributes_before_schema_handling_casts( assert back is not None assert _values(back) == _values(written) _assert_kept_field(first, back) + + +class _StructExtension(pa.ExtensionType): + """An extension whose struct storage carries field metadata.""" + + def __init__(self, storage_type: pa.DataType) -> None: + super().__init__(storage_type, "itl1415.struct") + + def __arrow_ext_serialize__(self) -> bytes: + return b"" + + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> _StructExtension: + return cls(storage_type) + + +class _NestedExtension(_StructExtension): + """An extension with its own identity for use inside another extension.""" + + def __init__(self, storage_type: pa.DataType) -> None: + pa.ExtensionType.__init__(self, storage_type, "itl1415.nested") + + +def _ipc_round_trip(table: pa.Table) -> pa.Table: + """Deserialize the table with the current Arrow extension registry.""" + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, table.schema) as writer: + writer.write_table(table) + return pa.ipc.open_stream(sink.getvalue()).read_all() + + +def _extension_rows(rid: bytes, value: int, extension: _StructExtension) -> pa.Table: + """Build a row with the extension's struct storage and field metadata.""" + storage = pa.array([{"a": value}], type=extension.storage_type) + return pa.table( + {"id": [rid], "x": pa.ExtensionArray.from_storage(extension, storage)} + ) + + +class _MetadataConnector(MockDBConnector): + """An Arrow connector that stores fields and their metadata.""" + + keeps_field_metadata = True + + def validate_records(self, records: pa.Table) -> None: + """Accept Arrow metadata.""" + + +def test_connector_refuses_extension_storage_metadata_committed_after_add() -> None: + """A connector rechecks the storage metadata in the table found at flush.""" + connector = _MetadataConnector() + first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) + metres, seconds = (_StructExtension(_struct_child(u).type) for u in ("m", "s")) + first.add_records(PATH, _extension_rows(b"a", 1, metres)) + second.add_records(PATH, _extension_rows(b"b", 2, seconds), flush=True) + with pytest.raises(InputValidationError, match=r"x\.a has other field metadata"): + first.flush() + rows = second.get_all_records(PATH, record_id_column="id") + assert rows is not None and rows["id"].to_pylist() == [b"b"] + + +@pytest.mark.parametrize("database", DATABASES) +@pytest.mark.parametrize("pending", [False, True], ids=["stored", "pending"]) +@pytest.mark.parametrize("units", [("m", "s"), ("s", "m")]) +def test_metadata_inside_extension_storage_must_match( + tmp_path: Path, database: str, pending: bool, units: tuple[str, str] +) -> None: + """The struct field's metadata is checked even inside an extension type.""" + first, second = (_StructExtension(_struct_child(u).type) for u in units) + + pa.register_extension_type(first) # pyright: ignore[reportArgumentType] # Arrow accepts ExtensionType + try: + with open_database(database, tmp_path) as db: + db.add_records(PATH, _extension_rows(b"a", 1, first), flush=not pending) + with pytest.raises( + InputValidationError, match=r"x\.a has other field metadata" + ): + db.add_records(PATH, _extension_rows(b"b", 2, second)) + db.add_records(PATH, _extension_rows(b"c", 3, first), flush=True) + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert sorted(stored["id"].to_pylist()) == [b"a", b"c"] + finally: + pa.unregister_extension_type(first.extension_name) + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_refuses_ipc_decoded_unregistered_extension_child( + tmp_path: Path, skip_duplicates: bool +) -> None: + """Delta refuses a logical child even when IPC exposes only its annotation.""" + inner = pa.large_string() + + class _UnregisteredChild(pa.ExtensionType): + def __init__(self) -> None: + super().__init__(inner, "itl1415.unregistered-child") + + def __arrow_ext_serialize__(self) -> bytes: + return b"v1" + + child = pa.ExtensionArray.from_storage( + _UnregisteredChild(), pa.array(["x"], type=inner) + ) + storage = pa.StructArray.from_arrays([child], names=["a"]) + extension = _StructExtension(storage.type) + first = pa.table( + {"id": [b"a"], "x": pa.ExtensionArray.from_storage(extension, storage)} + ) + pa.register_extension_type(extension) # pyright: ignore[reportArgumentType] # Arrow accepts ExtensionType + try: + decoded = _ipc_round_trip(first) + decoded_type = decoded.schema.field("x").type + assert isinstance(decoded_type, _StructExtension) + decoded_child = decoded_type.storage_type.field(0) + assert decoded_child.type == inner + assert decoded_child.metadata == { + b"ARROW:extension:name": b"itl1415.unregistered-child", + b"ARROW:extension:metadata": b"v1", + } + + database = DeltaTableDatabase(tmp_path) + for table in (first, decoded): + with pytest.raises(UnstorableColumnError, match=r"x\.a"): + database.add_records( + PATH, table, skip_duplicates=skip_duplicates, flush=True + ) + assert database.get_all_records(PATH, record_id_column="id") is None + finally: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("round_trip", [False, True], ids=["direct", "ipc"]) +@pytest.mark.parametrize( + "registered", [False, True], ids=["unregistered", "registered"] +) +@pytest.mark.parametrize("shape", ["list", "struct", "nested"]) +def test_delta_requires_whole_column_extension_before_and_after_ipc( + tmp_path: Path, + skip_duplicates: bool, + round_trip: bool, + registered: bool, + shape: str, +) -> None: + """Delta accepts whole-column extensions and refuses nested ones before and after IPC.""" + + storage: pa.Array[Any] = pa.array([[1]], type=pa.large_list(I64)) + if shape == "struct": + storage = pa.StructArray.from_arrays([pa.array([1])], names=["a"]) + nested = _NestedExtension(storage.type) + if shape == "nested": + child = pa.ExtensionArray.from_storage(nested, storage) + storage = pa.StructArray.from_arrays([child], names=["a"]) + outer = _StructExtension(storage.type) + first = pa.table( + {"id": [b"a"], "x": pa.ExtensionArray.from_storage(outer, storage)} + ) + extensions = (outer, nested) if shape == "nested" else (outer,) + if registered: + for extension in extensions: + pa.register_extension_type(extension) # pyright: ignore[reportArgumentType] # Arrow accepts ExtensionType + try: + incoming = first.set_column(0, "id", pa.array([b"b"])) + if round_trip: + incoming = _ipc_round_trip(incoming) + decoded = incoming.schema.field("x") + assert isinstance(decoded.type, pa.ExtensionType) == registered + if not registered: + metadata = decoded.metadata + assert metadata is not None + assert metadata[b"ARROW:extension:name"] == b"itl1415.struct" + if shape == "nested": + database = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match=r"x\.a"): + database.add_records( + PATH, incoming, skip_duplicates=skip_duplicates, flush=True + ) + assert database.get_all_records(PATH, record_id_column="id") is None + return + DeltaTableDatabase(tmp_path).add_records(PATH, first, flush=True) + reopened = DeltaTableDatabase(tmp_path) + reopened.add_records( + PATH, incoming, skip_duplicates=skip_duplicates, flush=True + ) + finally: + if registered: + for extension in extensions: + pa.unregister_extension_type(extension.extension_name) + # Read IDs with the registry cleared: Delta can normalize the list's + # physical type, which Arrow cannot cast between two registered extensions. + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("id")["id"].to_pylist() == [b"a", b"b"] + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_refuses_known_struct_metadata_after_ipc( + tmp_path: Path, skip_duplicates: bool +) -> None: + """An unregistered extension can still carry explicit storage metadata.""" + + def rows(rid: bytes, unit: str) -> pa.Table: + storage = pa.array([{"a": 1}], type=_struct_child(unit).type) + return pa.table( + { + "id": [rid], + "x": pa.ExtensionArray.from_storage( + _StructExtension(storage.type), storage + ), + } + ) + + first = _ipc_round_trip(rows(b"a", "m")) + # An Arrow producer may omit the optional serialized extension metadata. + field = first.schema.field("x").with_metadata( + {b"ARROW:extension:name": b"itl1415.struct"} + ) + first = _ipc_round_trip(first.set_column(1, field, first["x"])) + DeltaTableDatabase(tmp_path).add_records(PATH, first, flush=True) + reopened = DeltaTableDatabase(tmp_path) + with pytest.raises(InputValidationError, match=r"x\.a has other field metadata"): + reopened.add_records(PATH, rows(b"b", "s"), skip_duplicates=skip_duplicates) + reopened.add_records( + PATH, rows(b"c", "m"), skip_duplicates=skip_duplicates, flush=True + ) + stored = reopened.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("id")["id"].to_pylist() == [b"a", b"c"] + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_appends_when_ipc_extension_storage_metadata_is_unknown( + tmp_path: Path, skip_duplicates: bool +) -> None: + """Storage attributes below an annotation alone cannot establish a mismatch.""" + + def rows(rid: bytes, unit: str | None) -> pa.Table: + storage = pa.array([{"a": 1}], type=_struct_child(unit).type) + extension = _StructExtension(storage.type) + return pa.table( + {"id": [rid], "x": pa.ExtensionArray.from_storage(extension, storage)} + ) + + first = rows(b"a", "m") + DeltaTableDatabase(tmp_path).add_records(PATH, first, flush=True) + incoming = _ipc_round_trip(rows(b"b", None)) + decoded = incoming.schema.field("x") + assert not isinstance(decoded.type, pa.BaseExtensionType) + metadata = decoded.metadata + assert metadata is not None and b"ARROW:extension:name" in metadata + DeltaTableDatabase(tmp_path).add_records( + PATH, incoming, skip_duplicates=skip_duplicates, flush=True + ) + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("id")["id"].to_pylist() == [b"a", b"b"] + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_appends_identical_reserved_key_used_as_nested_metadata( + tmp_path: Path, skip_duplicates: bool +) -> None: + """A nested key with no special meaning is compared as ordinary metadata.""" + key = "orcapod:arrow_type" + extension = _StructExtension(pa.struct([pa.field("a", I64, metadata={key: "m"})])) + changed = _StructExtension(pa.struct([pa.field("a", I64, metadata={key: "s"})])) + pa.register_extension_type(extension) # pyright: ignore[reportArgumentType] # Arrow accepts ExtensionType + try: + DeltaTableDatabase(tmp_path).add_records( + PATH, _extension_rows(b"a", 1, extension), flush=True + ) + fresh = DeltaTableDatabase(tmp_path) + fresh.add_records( + PATH, + _extension_rows(b"b", 2, extension), + skip_duplicates=skip_duplicates, + flush=True, + ) + with pytest.raises( + InputValidationError, match=r"x\.a has other field metadata" + ): + fresh.add_records( + PATH, _extension_rows(b"c", 3, changed), skip_duplicates=skip_duplicates + ) + stored = fresh.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("id")["id"].to_pylist() == [b"a", b"b"] + finally: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize("nested", [False, True], ids=["list", "struct-of-list"]) +def test_delta_can_append_when_extension_list_item_metadata_is_unknown( + tmp_path: Path, nested: bool +) -> None: + """The Delta log lacks list item metadata, including in extension storage.""" + + def rows(rid: bytes, unit: str) -> pa.Table: + storage_type = _list_item(unit).type + value = [1] + if nested: + storage_type = pa.struct([pa.field("a", storage_type)]) + value = {"a": value} + extension = _StructExtension(storage_type) + storage = pa.array([value], type=storage_type) + return pa.table( + {"id": [rid], "x": pa.ExtensionArray.from_storage(extension, storage)} + ) + + first = rows(b"a", "m") + extension = first.schema.field("x").type + assert isinstance(extension, _StructExtension) + pa.register_extension_type(extension) # pyright: ignore[reportArgumentType] # Arrow accepts ExtensionType + try: + DeltaTableDatabase(tmp_path).add_records(PATH, first, flush=True) + fresh = DeltaTableDatabase(tmp_path) + fresh.add_records(PATH, rows(b"b", "m")) + with pytest.raises(InputValidationError, match="has other field metadata"): + fresh.add_records(PATH, rows(b"c", "s")) + fresh.flush() + fresh.add_records(PATH, rows(b"c", "s"), flush=True) + stored = fresh.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("id")["id"].to_pylist() == [b"a", b"b", b"c"] + finally: + pa.unregister_extension_type(extension.extension_name) diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 5fdb3934a..7fe775901 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -119,6 +119,12 @@ def iter_batches( # ── Write ───────────────────────────────────────────────────────────────── + def existing_record_ids( + self, table_name: str, id_column: str, ids: set[bytes] + ) -> set[bytes]: + """Return the matching IDs from the stored Arrow table.""" + return ids.intersection(self._tables[table_name][id_column].to_pylist()) + def create_table_if_not_exists( self, table_name: str, columns: list[ColumnInfo], pk_column: str ) -> None: @@ -516,6 +522,33 @@ def test_add_records_raises_if_record_id_type_is_not_binary(self, db): # =========================================================================== +def test_strict_append_looks_up_only_incoming_ids( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Refuse a stored conflict after one call with exactly the incoming IDs.""" + connector = MockDBConnector() + db = ConnectorArrowDatabase(connector) + path = ("records",) + db.add_record(path, b"first", pa.table({"payload": ["stored"]}), flush=True) + + requests = [] + lookup = connector.existing_record_ids + + def existing_record_ids( + table_name: str, id_column: str, ids: set[bytes] + ) -> set[bytes]: + requests.append((table_name, id_column, ids)) + return lookup(table_name, id_column, ids) + + monkeypatch.setattr(connector, "existing_record_ids", existing_record_ids) + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records( + path, + pa.table({"id": [b"first", b"new"], "payload": ["replacement", "new"]}), + ) + assert requests == [("records", "__record_id", {b"first", b"new"})] + + class TestDuplicateHandling: PATH = ("dup", "v1") diff --git a/tests/test_databases/test_delta_add_time_property.py b/tests/test_databases/test_delta_add_time_property.py index 971e48cf4..1e73194ca 100644 --- a/tests/test_databases/test_delta_add_time_property.py +++ b/tests/test_databases/test_delta_add_time_property.py @@ -5,8 +5,7 @@ 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: +logical-type case, with schema evolution on and off, and with every ID new or a stored ID among the input 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 @@ -138,7 +137,12 @@ def _stored_ids(root: Path) -> list[bytes]: def _run( - root: Path, initial: pa.Table, incoming: pa.Table, evolve: bool + root: Path, + initial: pa.Table, + incoming: pa.Table, + evolve: bool, + *, + skip_duplicates: bool = False, ) -> 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 @@ -147,7 +151,9 @@ def _run( 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") + db.add_records( + PATH, incoming, record_id_column="rid", skip_duplicates=skip_duplicates + ) except Exception as error: # noqa: BLE001 # the outcome is the subject return "refused when added", queued(), error try: @@ -203,7 +209,9 @@ def _unit_registered(unit_type: Any) -> None: @pytest.mark.parametrize( - "seen", [False, True], ids=["append (every id new)", "MERGE (a stored id)"] + "seen", + [False, True], + ids=["strict (every id new)", "skip duplicates (a stored id)"], ) @pytest.mark.parametrize("evolve", [False, True], ids=["evolution off", "evolution on"]) @pytest.mark.parametrize("label", sorted(VARIANTS)) @@ -218,7 +226,9 @@ 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, refusal = _run(tmp_path / "live", initial, incoming, evolve) + live, queued, refusal = _run( + tmp_path / "live", initial, incoming, evolve, skip_duplicates=seen + ) assert not queued, f"{label}: rows still queued after the flush ({live})" if live == "refused when added" and label in LOGICAL_RULE: @@ -227,7 +237,9 @@ def test_orcapod_refuses_nothing_delta_stores( # 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) + raw, _, error = _run( + tmp_path / "raw", initial, incoming, evolve, skip_duplicates=seen + ) assert raw == "refused at flush" and _refused_by_delta(error), ( f"{label}: Orcapod refused rows Delta does not refuse ({raw}: {error!r})" ) diff --git a/tests/test_databases/test_delta_commit_cost.py b/tests/test_databases/test_delta_commit_cost.py index c2314a502..8a8682192 100644 --- a/tests/test_databases/test_delta_commit_cost.py +++ b/tests/test_databases/test_delta_commit_cost.py @@ -143,7 +143,9 @@ def test_append_commit_loads_once_and_reads_only_its_files( files_before = set(_data_files(table_dir)) counts["table_loads"] = counts["datasets"] = 0 files_read.clear() - db.add_records(PATH, _rows([f"r{commit}_{k}" for k in range(3)])) + db.add_records( + PATH, _rows([f"r{commit}_{k}" for k in range(3)]), skip_duplicates=True + ) db.flush() # Lookups between commits are answered from the extended rows. assert db.get_record_by_id(PATH, f"r{commit}_1".encode()) is not None diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index 9d5f62c86..4d7e20b99 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -279,6 +279,7 @@ def test_an_unrecorded_struct_child_loosened_to_nullable_is_refused_once( } ), record_id_column="rid", + skip_duplicates=seen, ) with pytest.raises(InputValidationError, match="Invalid data found"): db.flush() @@ -405,6 +406,7 @@ def test_a_commit_conflict_carrying_a_duplicate_name_cause_stays_queued( PATH, _rows_of(b"1", b"2", b"3") if seen else _rows_of(b"2", b"3"), record_id_column="rid", + skip_duplicates=seen, ) called: list[str] = [] diff --git a/tests/test_databases/test_delta_committed_snapshot.py b/tests/test_databases/test_delta_committed_snapshot.py index cd3847f8f..0a220fc4a 100644 --- a/tests/test_databases/test_delta_committed_snapshot.py +++ b/tests/test_databases/test_delta_committed_snapshot.py @@ -172,13 +172,13 @@ def test_commits_with_new_ids_are_merged_and_stored_unchanged(tmp_path: Path) -> assert _values(DeltaTableDatabase(tmp_path).get_all_records(PATH)) == list(range(9)) -def test_a_stored_id_goes_through_merge_and_keeps_the_stored_row( +def test_skip_duplicates_preserves_the_stored_row_during_merge( tmp_path: Path, ) -> None: - """A batch holding a stored id is MERGEd: the stored row stays, the new ones land.""" + """A mixed batch skips the stored row and MERGEs the new rows.""" db = DeltaTableDatabase(tmp_path) db.add_records(PATH, _rows(["a", "b"], [1, 2]), flush=True) - db.add_records(PATH, _rows(["b", "c"], [20, 3]), flush=True) + db.add_records(PATH, _rows(["b", "c"], [20, 3]), skip_duplicates=True, flush=True) assert _operations(tmp_path / "table") == ["WRITE", "MERGE"] assert _values(DeltaTableDatabase(tmp_path).get_all_records(PATH)) == [1, 2, 3] assert _values(db.get_records_with_column_value(PATH, {"g": b"g"})) == [1, 2, 3] @@ -189,9 +189,10 @@ def test_ids_another_writer_stored_are_not_appended_twice(tmp_path: Path) -> Non db = DeltaTableDatabase(tmp_path) db.add_records(PATH, _rows(["a"], [1]), flush=True) assert _values(db.get_records_with_column_value(PATH, {"g": b"g"})) == [1] - # Another writer stores ``b`` after this family loaded the table. + # Another writer stores ``b`` after this family queued it. + db.add_records(PATH, _rows(["b", "c"], [20, 3])) DeltaTableDatabase(tmp_path).add_records(PATH, _rows(["b"], [2]), flush=True) - db.add_records(PATH, _rows(["b", "c"], [20, 3]), flush=True) + 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["rid"].to_pylist())) == [b"a", b"b", b"c"] diff --git a/tests/test_databases/test_delta_concurrent_writers.py b/tests/test_databases/test_delta_concurrent_writers.py index cd8e5a4dc..c9e2cdffa 100644 --- a/tests/test_databases/test_delta_concurrent_writers.py +++ b/tests/test_databases/test_delta_concurrent_writers.py @@ -13,6 +13,8 @@ from __future__ import annotations +import datetime +import decimal import multiprocessing import sys from pathlib import Path @@ -243,7 +245,13 @@ def _write_ids(root: str, start: Any, ids: list[int], value: int) -> None: db = DeltaTableDatabase(root) start.wait() for n in ids: - db.add_records(PATH, _records(n, value), record_id_column="rid", flush=True) + db.add_records( + PATH, + _records(n, value), + record_id_column="rid", + skip_duplicates=True, + flush=True, + ) @pytest.mark.skipif(sys.platform == "win32", reason="spawned writers on one table") @@ -564,3 +572,44 @@ def test_an_id_another_writer_added_is_skipped_once_the_table_is_reloaded( if queued_clash: expected.append((b"\x03", 30)) assert _stored(tmp_path) == expected + + +@pytest.mark.parametrize( + ("id_type", "initial", "contested"), + [ + ( + pa.timestamp("us"), + datetime.datetime(2026, 1, 1), + datetime.datetime(2026, 1, 2), + ), + (pa.decimal128(38, 18), decimal.Decimal("1.125"), decimal.Decimal("2.125")), + (pa.float64(), 1.125, 2.125), + ], + ids=["timestamp", "decimal", "float"], +) +def test_typed_record_ids_have_no_file_statistics_and_keep_the_first_commit( + tmp_path: Path, id_type: pa.DataType, initial: Any, contested: Any +) -> None: + """The typed ID must not let a MERGE miss a concurrent write to that ID.""" + a, b = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + + def rows(rid: Any, value: int) -> pa.Table: + return pa.table({"id": pa.array([rid], type=id_type), "v": [value]}) + + a.add_records(PATH, rows(initial, 0), flush=True) + a.add_records(PATH, rows(contested, 1)) + with _commit_after_load( + a, lambda: b.add_records(PATH, rows(contested, 2), flush=True) + ): + a.flush() + + props = deltalake.DeltaTable(str(tmp_path / "t")).metadata().configuration + assert props["delta.dataSkippingStatsColumns"] == "`v`" + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("id").to_pylist() == [ + {"id": initial, "v": 0}, + {"id": contested, "v": 2}, + ] + with pytest.raises(ValueError, match="already exist.*stored"): + a.add_records(PATH, rows(contested, 3)) diff --git a/tests/test_databases/test_delta_database_lookup_equivalence.py b/tests/test_databases/test_delta_database_lookup_equivalence.py index 06520e9b7..0582152fa 100644 --- a/tests/test_databases/test_delta_database_lookup_equivalence.py +++ b/tests/test_databases/test_delta_database_lookup_equivalence.py @@ -191,7 +191,8 @@ def test_a_stored_id_written_again_keeps_the_stored_row(tmp_path: Path) -> None: """A commit never replaces a stored row (insert-if-not-exists), as before.""" db = DeltaTableDatabase(tmp_path) _write(db, 0, 10, 5) - db.add_record(PATH, b"id-3", _row(3, "changed", 0)) + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_record(PATH, b"id-3", _row(3, "changed", 0)) db.add_record(PATH, b"id-new", _row(99, "g0", 0)) db.flush() everything = db.get_all_records(PATH, record_id_column="rid") diff --git a/tests/test_databases/test_delta_list_binary_commits.py b/tests/test_databases/test_delta_list_binary_commits.py index 59961ae08..3c7e9243a 100644 --- a/tests/test_databases/test_delta_list_binary_commits.py +++ b/tests/test_databases/test_delta_list_binary_commits.py @@ -136,6 +136,7 @@ def test_list_bytes_batch_holding_a_stored_id(tmp_path: Path) -> None: db.add_records( path, _bytes_rows([b"r1", b"r2", b"r3", b"r4"], [[b"X"], [b"c"], None, [None, b"d"]]), + skip_duplicates=True, flush=True, ) @@ -144,7 +145,7 @@ def test_list_bytes_batch_holding_a_stored_id(tmp_path: Path) -> None: ) # reopened assert table is not None got = dict(zip(table["__record_id"].to_pylist(), table["v"].to_pylist())) - # the stored id keeps its stored row (skipped, as when_not_matched_insert_all does) + # the stored id keeps its stored row (skipped at add time) assert got == { b"r0": [b"a"], b"r1": [b"b"], diff --git a/tests/test_databases/test_delta_native_fs_filtered_reads.py b/tests/test_databases/test_delta_native_fs_filtered_reads.py index b30b55982..aa08354e6 100644 --- a/tests/test_databases/test_delta_native_fs_filtered_reads.py +++ b/tests/test_databases/test_delta_native_fs_filtered_reads.py @@ -75,10 +75,12 @@ def _rows(ids: list[str], values: list[int], groups: list[int]) -> pa.Table: def _stored_and_pending(store: Path) -> DeltaTableDatabase: - """Store ``a`` and ``c``, then queue ``b``, ``d`` and a ``c`` that repeats a stored id.""" + """Queue rows while another handle commits the overlapping ID ``c``.""" db = DeltaTableDatabase(store) - db.add_records(PATH, _rows(["a", "c"], [1, 3], [1, 0]), flush=True) + db.add_records(PATH, _rows(["a"], [1], [1]), flush=True) db.add_records(PATH, _rows(["b", "c", "d"], [2, 30, 4], [1, 1, 1])) + DeltaTableDatabase(store).add_records(PATH, _rows(["c"], [3], [0]), flush=True) + db.refresh_table(PATH) return db diff --git a/tests/test_databases/test_delta_read_your_writes.py b/tests/test_databases/test_delta_read_your_writes.py index 235f30681..25bdf1e06 100644 --- a/tests/test_databases/test_delta_read_your_writes.py +++ b/tests/test_databases/test_delta_read_your_writes.py @@ -184,8 +184,11 @@ def test_pending_row_with_stored_id_reads_as_flush_keeps_it( ) -> None: """A pending row whose id is already stored is never returned; the stored row is.""" db = DeltaTableDatabase(tmp_path).at(SCOPE) - db.add_records(PATH, _rows(["a"], [1]), flush=True) db.add_records(PATH, _rows(["a", "d"], [10, 4]), skip_duplicates=skip_duplicates) + DeltaTableDatabase(tmp_path).at(SCOPE).add_records( + PATH, _rows(["a"], [1]), flush=True + ) + db.refresh_table(PATH) for when in ("before flush", "after flush"): assert _values(db.get_all_records(PATH)) == [1, 4], when @@ -223,13 +226,13 @@ def test_failed_id_refresh_is_retried_by_the_next_read( tmp_path: Path, method: str ) -> None: """After a failed stored-ID refresh, a pending row with a stored id is still not returned.""" - # Another root stores ``b``: this handle has to read the stored ids. (A handle's - # own commit tells it which ids it stored, so it reads none afterwards, ITL-919.) + # Another root commits ``b`` after this handle queues it. + db = DeltaTableDatabase(tmp_path).at(SCOPE) + db.add_records(PATH, _rows(["a", "b"], [1, 20])) DeltaTableDatabase(tmp_path).at(SCOPE).add_records( PATH, _rows(["b"], [2]), flush=True ) - db = DeltaTableDatabase(tmp_path).at(SCOPE) - db.add_records(PATH, _rows(["a", "b"], [1, 20])) + db.refresh_table(PATH) # The failed refresh is a failed stored read (ITL-884): never "no stored ids". with pytest.raises(OrcapodDatabaseReadError) as info: @@ -243,11 +246,12 @@ def test_failed_id_refresh_is_retried_by_the_next_read( def test_get_records_by_ids_raises_on_failed_id_refresh(tmp_path: Path) -> None: """A failed stored-ID refresh raises ``OrcapodDatabaseReadError``, never "no records" (ITL-884).""" # Another root stores ``a`` and ``b``: this handle has to read the stored ids (ITL-919). + db = DeltaTableDatabase(tmp_path).at(SCOPE) + db.add_records(PATH, _rows(["c"], [3], [1])) DeltaTableDatabase(tmp_path).at(SCOPE).add_records( PATH, _rows(["a", "b"], [1, 2], [0, 1]), flush=True ) - db = DeltaTableDatabase(tmp_path).at(SCOPE) - db.add_records(PATH, _rows(["c"], [3], [1])) + db.refresh_table(PATH) with pytest.raises(OrcapodDatabaseReadError) as info: _ = db.get_records_by_ids(PATH, [b"a", b"c"]) @@ -267,16 +271,16 @@ def test_unreadable_table_with_sibling_pending_rows_raises_and_drops_nothing( rather than returning only the pending rows (ITL-864); once it is readable again the same read returns both rows, so nothing was dropped from the pending batch. """ + root = DeltaTableDatabase(tmp_path) + reader, writer = root.at(SCOPE), root.at(SCOPE) + writer.add_records(PATH, _rows(["a"], [1])) DeltaTableDatabase(tmp_path).at(SCOPE).add_records( PATH, _rows(["b"], [2]), flush=True ) - root = DeltaTableDatabase(tmp_path) - reader, writer = root.at(SCOPE), root.at(SCOPE) + reader.refresh_table(PATH) if cache == "warm": - # The family has loaded the table and its stored ids before the failure. - assert _values(reader.get_all_records(PATH)) == [2] - assert reader.get_record_by_id(PATH, b"a") is None - writer.add_records(PATH, _rows(["a"], [1])) + # The family holds the stored rows, while the ID projection is unread. + assert reader.get_record_by_id(PATH, b"b") is not None def unreadable(*_args: object, **_kwargs: object) -> pa.Table: """Fail as a storage outage would.""" @@ -305,11 +309,10 @@ def test_fresh_handle_drops_pending_rows_with_stored_ids( tmp_path: Path, method: str ) -> None: """A handle that loaded a table written by another root still drops pending rows with stored ids.""" - DeltaTableDatabase(tmp_path).add_records(PATH, _rows(["b"], [2]), flush=True) db = DeltaTableDatabase(tmp_path) - assert _values(db.get_all_records(PATH)) == [2] # loads the table, no ids yet - db.add_records(PATH, _rows(["a", "b"], [1, 20])) + DeltaTableDatabase(tmp_path).add_records(PATH, _rows(["b"], [2]), flush=True) + db.refresh_table(PATH) assert _values(READS[method](db, PATH)) == EXPECTED[method] diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 6b7f7c767..713a01517 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -372,7 +372,7 @@ def add_newline(metadata: dict[str, Any]) -> None: } ), record_id_column="rid", - skip_duplicates=len(ids) == 1, + skip_duplicates=b"1" in ids, flush=True, ) back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") @@ -404,7 +404,7 @@ def test_a_real_record_change_is_refused_at_flush_only_where_delta_refuses_it( ) db.add_records( - PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + PATH, rows, record_id_column="rid", skip_duplicates=b"1" in ids ) # accepted when added, on every route if evolution: _refused_once_at_flush(db) @@ -466,13 +466,11 @@ def test_a_null_column_is_checked_like_any_column( # rows are added, on every route, whatever schema evolution says. with pytest.raises(InputValidationError, match="logical type"): db.add_records( - PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + PATH, rows, record_id_column="rid", skip_duplicates=b"1" in ids ) assert _stored_ids(tmp_path) == [b"1"] else: - db.add_records( - PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 - ) + db.add_records(PATH, rows, record_id_column="rid", skip_duplicates=b"1" in ids) db.flush() back = DeltaTableDatabase(tmp_path).get_all_records( PATH, record_id_column="rid" @@ -593,7 +591,7 @@ def test_what_changes_between_add_and_flush_is_decided_at_the_flush( MERGE that keeps the stored schema stores them. When schema evolution is turned on before the flush, the commit sends the changed record and Delta refuses it: the flush raises once, nothing stays queued. When another writer deletes a stored row, - the commit is still decided at the flush, and the rows are stored.""" + the new row still commits. The skipped row is not queued and stays deleted.""" 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=False) @@ -604,11 +602,11 @@ def test_what_changes_between_add_and_flush_is_decided_at_the_flush( "x": pa.array([[1], [2]], wider), } ) - db.add_records(PATH, rows, record_id_column="rid") # accepted when added + db.add_records(PATH, rows, record_id_column="rid", skip_duplicates=True) if change == "another writer deletes a stored row": deltalake.DeltaTable(str(tmp_path / "t")).delete("__record_id = X'31'") db.flush() - assert _stored_ids(tmp_path) == [b"1", b"2"] + assert _stored_ids(tmp_path) == [b"2"] assert not db._pending_batches # pyright: ignore[reportPrivateUsage] else: db.allow_schema_evolution = True diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index cf03a532e..3f3c6b758 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -213,12 +213,18 @@ def test_create_append_merge_and_schema_evolution( STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" } + other = DeltaTableDatabase(tmp_path) + other.add_records(PATH, rows(range(15, 30))) db.add_records(PATH, rows(range(10, 20)), flush=True) assert stats_warnings(capfd) == [], "append" - # One stored id among the new ones forces the MERGE path. - db.add_records(PATH, rows(range(15, 30)), skip_duplicates=False, flush=True) + # Five IDs were committed after the second handle queued them. + other.flush() assert stats_warnings(capfd) == [], "merge" + merge = deltalake.DeltaTable(str(tmp_path / "t")).history(1)[0] + assert merge["operation"] == "MERGE" + assert merge["operationMetrics"]["num_source_rows"] == 15 + assert merge["operationMetrics"]["num_target_rows_inserted"] == 10 # New columns (one binary, one int): schema evolution, through MERGE. db.add_records(PATH, rows(range(30, 40), extra=True), flush=True) @@ -358,9 +364,7 @@ def test_every_kind_is_written_without_warning( capfd.readouterr() db.add_records(PATH, _every_kind(range(0, 3)), flush=True) db.add_records(PATH, _every_kind(range(3, 6)), flush=True) - db.add_records( - PATH, _every_kind(range(5, 9)), skip_duplicates=False, flush=True - ) + db.add_records(PATH, _every_kind(range(5, 9)), skip_duplicates=True, flush=True) assert stats_warnings(capfd) == [] assert set(statistics_columns(_delta_schema(tmp_path / "t"))) == LISTED @@ -453,7 +457,7 @@ def table(ids: range) -> pa.Table: capfd.readouterr() db.add_records(PATH, table(range(0, 3)), flush=True) db.add_records(PATH, table(range(3, 6)), flush=True) - db.add_records(PATH, table(range(5, 9)), skip_duplicates=False, flush=True) + db.add_records(PATH, table(range(5, 9)), skip_duplicates=True, flush=True) assert stats_warnings(capfd) == [] assert configuration(tmp_path / "t") == {STATS_COLUMNS_PROPERTY: "`c`"} assert len(stored_ids(db)) == 9 @@ -493,6 +497,21 @@ def test_a_listed_column_prunes_files(self, tmp_path: Path) -> None: class TestTablesCreatedElsewhere: + def test_existing_statistics_property_with_a_typed_id_is_retained( + self, tmp_path: Path + ) -> None: + """Appending does not rewrite the statistics property of an older table.""" + location = tmp_path / "t" + record_id = DeltaTableDatabase.RECORD_ID_COLUMN + old_property = {STATS_COLUMNS_PROPERTY: f"`{record_id}`,`v`"} + deltalake.write_deltalake( + location, pa.table({record_id: [1.0], "v": [1]}), configuration=old_property + ) + + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, pa.table({record_id: [2.0], "v": [2]}), flush=True) + assert configuration(location) == old_property + def test_existing_table_without_the_property_is_unaltered( self, tmp_path: Path, capfd: pytest.CaptureFixture[str] ) -> None: @@ -503,7 +522,7 @@ def test_existing_table_without_the_property_is_unaltered( capfd.readouterr() db.add_records(PATH, rows(range(10, 20)), flush=True) - db.add_records(PATH, rows(range(15, 30)), skip_duplicates=False, flush=True) + db.add_records(PATH, rows(range(15, 30)), skip_duplicates=True, flush=True) # 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. diff --git a/tests/test_databases/test_in_memory_database_lookup_equivalence.py b/tests/test_databases/test_in_memory_database_lookup_equivalence.py index 1f7d6c3b0..fef06cb0b 100644 --- a/tests/test_databases/test_in_memory_database_lookup_equivalence.py +++ b/tests/test_databases/test_in_memory_database_lookup_equivalence.py @@ -107,13 +107,13 @@ def test_lookup_accepts_a_list_of_pairs(): @pytest.mark.parametrize("pairs", LOOKUPS, ids=lambda p: "-".join(p)) -def test_lookup_after_a_flush_overwrites_a_committed_id(pairs: dict[str, Any]): - """A rewritten committed id moves its row to the end and lookups follow it.""" +def test_lookup_after_rejecting_a_committed_id(pairs: dict[str, Any]): + """Rejecting a committed ID leaves the existing indexes valid for the next append.""" db = InMemoryArrowDatabase() _fill(db, 40) _ = db.get_records_with_column_value(PATH, pairs) # build the indexes first - # A committed id written again replaces its row, which moves to the end. - db.add_record(PATH, b"id-5", _row(5, "g1", 4)) + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_record(PATH, b"id-5", _row(5, "g1", 4)) db.add_record(PATH, b"id-40", _row(40, "g1", 4)) db.flush() actual = db.get_records_with_column_value(PATH, pairs, record_id_column="rid") @@ -121,7 +121,7 @@ def test_lookup_after_a_flush_overwrites_a_committed_id(pairs: dict[str, Any]): everything = db.get_all_records(PATH, record_id_column="rid") assert everything is not None assert everything.num_rows == 41 - assert everything["rid"].to_pylist()[-2:] == [b"id-5", b"id-40"] + assert everything["rid"].to_pylist()[-2:] == [b"id-39", b"id-40"] def test_indexes_follow_appends_after_they_are_built(): diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index fd28ee20b..07a925690 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1351,8 +1351,8 @@ def annotated(meta: bytes, name: str = "key") -> "pa.Field[Any]": def test_delta_merge_source_keeps_the_held_identifier_bytes(tmp_path: Path) -> None: - """A list-typed extension column appended to a stored table goes to the MERGE (a - batch with an id already stored) in the stored layout with its identifier: the bytes Arrow holds (the ones the + """A list-typed extension column appended to a stored table goes to the MERGE + in the stored layout with its identifier: the bytes Arrow holds (the ones the identity rule compared), not its serializer asked again, which may answer otherwise. The stored identifier stays the one written.""" import deltalake @@ -1378,7 +1378,7 @@ def rows(ext: Any, ids: list[bytes]) -> pa.Table: db = DeltaTableDatabase(tmp_path / "delta") db.add_records(PATH, rows(ListExt(b"m"), [b"1"]), record_id_column="id", flush=True) second = ListExt(b"m") - given = rows(second, [b"1", b"22"]) + given = rows(second, [b"22"]) second.payload = b"changed" # the serializer now answers otherwise db.add_records(PATH, given, record_id_column="id", flush=True) stored = deltalake.DeltaTable(str(tmp_path / "delta" / "t")).schema().fields[1] @@ -1607,16 +1607,15 @@ def test_delta_refusals_are_decided_on_the_table_stored_now(tmp_path: Path) -> N record_id_column="id", skip_duplicates=True, ) - # A fresh id of ``n`` on a stale handle that accepts it: refused at flush. + # A fresh id of ``m`` queued before replacement is refused at flush. other_stale = DeltaTableDatabase(root) - other_stale.get_all_records(PATH, record_id_column="id") + other_stale.add_records(PATH, _annotated_top(b"m", [b"333"]), record_id_column="id") deltalake.write_deltalake( str(root / "t"), _annotated_top(b"n", [b"1", b"22"]).rename_columns(["__record_id", "x"]), mode="overwrite", schema_mode="overwrite", ) - other_stale.add_records(PATH, _annotated_top(b"m", [b"333"]), record_id_column="id") with pytest.raises( InputValidationError, match="the stored column's 'itl1371.a;6e'" ): @@ -1784,7 +1783,7 @@ def rows(ext: Any, ids: list[bytes]) -> pa.Table: db = DeltaTableDatabase(tmp_path / "delta", allow_schema_evolution=schema_evolution) db.add_records(PATH, rows(ListExt(b"m"), [b"1"]), record_id_column="id", flush=True) second = ListExt(b"m") - given = rows(second, [b"1", b"22"]) + given = rows(second, [b"22"]) second.payload = b"changed" if serializer == "changed" else None db.add_records(PATH, given, record_id_column="id", flush=True) stored = deltalake.DeltaTable(str(tmp_path / "delta" / "t")).schema().fields[1] diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 92e7a1388..9ec39ca51 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -116,6 +116,27 @@ def _make_table(ids: list[str], values: list[float | None]) -> pa.Table: # --------------------------------------------------------------------------- +@pytest.mark.postgres +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_connector_database_rejects_stored_ids_and_skips_lost_commit_races( + connector: PostgreSQLConnector, skip_duplicates: bool +) -> None: + """PostgreSQL preserves the winning row even when the other writer flushes last.""" + path = ("write_conflict",) + first = ConnectorArrowDatabase(connector) + with PostgreSQLConnector(connector._dsn) as second_connector: + second = ConnectorArrowDatabase(second_connector) + first.add_record( + path, b"x", pa.table({"value": [1]}), skip_duplicates=skip_duplicates + ) + second.add_record(path, b"x", pa.table({"value": [2]}), flush=True) + first.flush() + with pytest.raises(ValueError, match="already exist.*stored"): + first.add_record(path, b"x", pa.table({"value": [3]})) + rows = second.get_all_records(path) + assert rows is not None and rows.to_pylist() == [{"value": 2}] + + @pytest.mark.postgres @pytest.mark.parametrize("order", TIE_ORDERS) def test_postgresql_result_lookup_timestamp_tie( @@ -1174,7 +1195,7 @@ def test_unsupported_catalog_layout_is_refused( one, two = pa.table({"value": [1]}), pa.table({"value": [2]}) db.add_record(path, b"id", one, flush=True) if operation in ("flush", "pending_point"): - db.add_record(path, b"id", two) + db.add_record(path, b"pending", two) connector._require_open().commit() catalog = sql.Identifier(STORE_PATH_CATALOG) with psycopg.connect(connector._dsn) as conn: @@ -1466,13 +1487,13 @@ def test_store_writes_to_the_verified_schema_when_a_temp_table_shadows_its_name( ) temp = sql.Identifier("pg_temp", name) _ = conn.execute( - sql.SQL("INSERT INTO {} VALUES (%s, %s)").format(temp), (b"id", 99) + sql.SQL("INSERT INTO {} VALUES (%s, %s)").format(temp), (b"new", 99) ) - db.add_record(path, b"id", pa.table({"value": [2]}), flush=True) + db.add_record(path, b"new", pa.table({"value": [2]}), flush=True) assert conn.execute(sql.SQL("SELECT value FROM {}").format(temp)).fetchone() == ( 99, ) - rows = db.get_all_records(path) + rows = db.get_record_by_id(path, b"new") assert rows is not None and rows.to_pylist() == [{"value": 2}] diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index 32dc4dac9..a32332ddd 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -236,7 +236,7 @@ def test_unsupported_catalog_layout_is_refused(self, operation: str) -> None: db = ConnectorArrowDatabase(connector) db.add_record(path, b"id", one, flush=True) if operation in ("flush", "pending_point"): - db.add_record(path, b"id", two) + db.add_record(path, b"pending", two) conn = connector._require_open() _ = conn.execute("PRAGMA ignore_check_constraints=ON") _ = conn.execute( @@ -281,11 +281,14 @@ def test_store_uses_main_when_a_temp_table_shadows_its_name( _ = conn.execute( f'CREATE TEMP TABLE "{name}" ("__record_id" BLOB PRIMARY KEY, value INTEGER)' ) - _ = conn.execute(f'INSERT INTO temp."{name}" VALUES (?, ?)', (b"id", 99)) + _ = conn.execute(f'INSERT INTO temp."{name}" VALUES (?, ?)', (b"new", 99)) if write: - store.add_record(path, b"id", two, flush=True) + store.add_record(path, b"new", two, flush=True) assert tuple( - conn.execute(f'SELECT value FROM main."{name}"').fetchone() + conn.execute( + f'SELECT value FROM main."{name}" WHERE "__record_id" = ?', + (b"new",), + ).fetchone() ) == (2,) assert tuple( conn.execute(f'SELECT value FROM temp."{name}"').fetchone() @@ -338,21 +341,17 @@ def test_unregistered_physical_name_is_not_claimed(self) -> None: db.add_record(path, b"one", pa.table({"value": [1]}), flush=True) assert connector.get_table_names() == [name] - def test_registration_and_table_creation_roll_back_on_write_error( - self, monkeypatch: pytest.MonkeyPatch - ) -> None: + def test_registration_and_table_creation_roll_back_on_write_error(self) -> None: with SQLiteConnector(":memory:") as connector: db = ConnectorArrowDatabase(connector) - - def fail_write(*args: object, **kwargs: object) -> None: - raise RuntimeError("simulated write failure") - - with monkeypatch.context() as patch: - patch.setattr(connector, "upsert_records", fail_write) - with pytest.raises(RuntimeError, match="simulated write failure"): - db.add_record( - ("new",), b"one", pa.table({"value": [1]}), flush=True - ) + schema = pa.schema([pa.field("value", pa.int64(), nullable=False)]) + with pytest.raises(sqlite3.IntegrityError, match="NOT NULL"): + db.add_record( + ("new",), + b"one", + pa.table({"value": [None]}, schema=schema), + flush=True, + ) assert connector.get_table_names() == [] db.add_record(("new",), b"one", pa.table({"value": [1]}), flush=True) assert db.list_table_paths() == [("new",)] @@ -522,7 +521,7 @@ def _check_catalog_operation( elif operation == "read": db.get_all_records(path) elif operation == "pending_point": - db.get_record_by_id(path, b"id") + db.get_record_by_id(path, b"pending") elif operation == "queue": db.add_record(path, b"id", table) elif operation == "flush": diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py new file mode 100644 index 000000000..16bc0fd89 --- /dev/null +++ b/tests/test_databases/test_write_conflicts.py @@ -0,0 +1,878 @@ +"""Write conflicts are checked when rows are added (ITL-1386, ITL-1487).""" + +import re +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal +from enum import Enum +from pathlib import Path +from sqlite3 import SQLITE_DENY, SQLITE_OK, SQLITE_READ, DatabaseError, IntegrityError +from typing import Any, Literal, cast + +import pyarrow as pa +import pytest +from typing_extensions import override + +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SQLiteConnector, +) +from orcapod.errors import InputValidationError, OrcapodDatabaseReadError +from tests.test_databases.test_connector_arrow_database import MockDBConnector + +PATH = ("records",) + + +class _RecordKey(Enum): + FIRST = 1 + SECOND = 2 + + +class _RecordKeyScalar(pa.ExtensionScalar): + @override + def as_py(self, **kwargs: object) -> _RecordKey | None: + """Decode the stored integer to a distinct Python value.""" + value = cast("pa.Int64Scalar | None", self.value) + return None if value is None else _RecordKey(value.as_py()) + + +class _RecordKeyType(pa.ExtensionType): + """Use fixed integer storage for the enum record IDs.""" + + def __init__(self) -> None: + super().__init__(pa.int64(), "orcapod.tests.write_conflicts.record_key") + + @override + def __arrow_ext_serialize__(self) -> bytes: + """Serialize without a payload because the storage type is fixed.""" + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_RecordKeyType": + """Restore the fixed int64 extension type.""" + return cls() + + @override + def __arrow_ext_scalar_class__(self) -> type[_RecordKeyScalar]: + """Decode storage integers as enum members.""" + return _RecordKeyScalar + + +@pytest.mark.parametrize("encoding", ["extension", "dictionary", "plain"]) +@pytest.mark.parametrize("handle", ["pending", "writer", "reopened"]) +def test_delta_strict_add_compares_id_storage( + tmp_path: Path, encoding: str, handle: str +) -> None: + """Strict writes check IDs even if a reader sees different Arrow encodings.""" + writer = DeltaTableDatabase(tmp_path) + extension = _RecordKeyType() + + def rows( + key: _RecordKey, label: str, *, reverse_dictionary: bool = False + ) -> pa.Table: + storage = pa.array([key.value], type=pa.int64()) + if encoding == "extension": + ids = pa.ExtensionArray.from_storage(extension, storage) + elif encoding == "dictionary": + dictionary = [1, 2] if reverse_dictionary else [2, 1] + ids = pa.DictionaryArray.from_arrays( + pa.array([dictionary.index(key.value)], type=pa.int8()), + pa.array(dictionary, type=pa.int64()), + ) + else: + ids = storage + return pa.table({"id": ids, "v": [label]}) + + pa.register_extension_type(cast(Any, extension)) + try: + writer.add_records( + PATH, rows(_RecordKey.FIRST, "first"), flush=handle != "pending" + ) + db = DeltaTableDatabase(tmp_path) if handle == "reopened" else writer + if handle == "reopened": + visible = db.get_all_records(PATH, record_id_column="id") + assert visible is not None + assert visible["id"].to_pylist() == [ + _RecordKey.FIRST if encoding == "extension" else _RecordKey.FIRST.value + ] + location = "pending" if handle == "pending" else "stored" + with pytest.raises(ValueError, match=f"already exist.*{location}"): + db.add_records( + PATH, rows(_RecordKey.FIRST, "duplicate", reverse_dictionary=True) + ) + db.add_records(PATH, rows(_RecordKey.SECOND, "second")) + db.flush() + stored = db.get_all_records(PATH) + assert stored is not None + assert stored.num_rows == 2 + assert set(stored["v"].to_pylist()) == {"first", "second"} + finally: + pa.unregister_extension_type(extension.extension_name) + + +class _CompositeKeyScalar(pa.ExtensionScalar): + @override + def as_py(self, **kwargs: object) -> tuple[int, ...] | None: + """Expose a hashable point over either list or struct storage.""" + value = self.value + if value is None: + return None + point = cast("list[int] | dict[str, int]", value.as_py()) + return tuple(point.values() if isinstance(point, dict) else point) + + +class _CompositeKeyType(pa.ExtensionType): + """Expose a hashable ID backed by a list or struct.""" + + def __init__(self, storage_type: pa.DataType) -> None: + super().__init__(storage_type, "orcapod.tests.write_conflicts.composite_key") + + @override + def __arrow_ext_serialize__(self) -> bytes: + """Use the supplied Arrow storage type instead of a serialized payload.""" + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_CompositeKeyType": + """Preserve struct storage and normalize Delta list offsets and item names.""" + return cls( + pa.list_(pa.int64()) + if pa.types.is_list(storage_type) or pa.types.is_large_list(storage_type) + else storage_type + ) + + @override + def __arrow_ext_scalar_class__(self) -> type[_CompositeKeyScalar]: + """Decode nested storage to a hashable tuple.""" + return _CompositeKeyScalar + + +class _OrdinalDateScalar(pa.ExtensionScalar): + @override + def as_py(self, **kwargs: object) -> int | None: + """Expose Arrow's entire date32 domain as integer day counts.""" + value = cast("pa.Date32Scalar | None", self.value) + return None if value is None else value.cast(pa.int32()).as_py() + + +class _OrdinalDateType(pa.ExtensionType): + """Use fixed date32 storage for day counts outside Python's date range.""" + + def __init__(self) -> None: + super().__init__(pa.date32(), "orcapod.tests.write_conflicts.ordinal_date") + + @override + def __arrow_ext_serialize__(self) -> bytes: + """Serialize without a payload because the storage type is fixed.""" + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_OrdinalDateType": + """Restore the fixed date32 extension type.""" + return cls() + + @override + def __arrow_ext_scalar_class__(self) -> type[_OrdinalDateScalar]: + """Decode dates as integer day counts.""" + return _OrdinalDateScalar + + +class _NativeIdType(pa.ExtensionType): + """Wrap the supplied Arrow storage type for primitive ID comparisons.""" + + def __init__(self, storage_type: pa.DataType) -> None: + super().__init__(storage_type, "orcapod.tests.write_conflicts.native_id") + + @override + def __arrow_ext_serialize__(self) -> bytes: + """Use the supplied Arrow storage type instead of a serialized payload.""" + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_NativeIdType": + """Rebuild the extension over the storage type supplied by Arrow.""" + return cls(storage_type) + + +_PRIMITIVE_IDS = [ + pytest.param(pa.bool_(), True, id="bool"), + *[ + pytest.param(storage_type, 1, id=str(storage_type)) + for storage_type in ( + pa.int8(), + pa.int16(), + pa.int32(), + pa.int64(), + pa.uint8(), + pa.uint16(), + pa.uint32(), + pa.uint64(), + ) + ], + pytest.param(pa.float16(), 1.5, id="float16"), + pytest.param(pa.float32(), 1.5, id="float32"), + pytest.param(pa.float64(), 1.5, id="float64"), + pytest.param(pa.string(), "key", id="string"), + pytest.param(pa.large_string(), "key", id="large-string"), + pytest.param(pa.binary(), b"key", id="binary"), + pytest.param(pa.large_binary(), b"key", id="large-binary"), + pytest.param(pa.binary(3), b"key", id="fixed-binary"), + pytest.param(pa.date32(), date(2026, 1, 2), id="date32"), + pytest.param(pa.date64(), date(2026, 1, 2), id="date64"), + pytest.param(pa.time32("ms"), time(1, 2, 3), id="time32"), + pytest.param(pa.time64("ns"), time(1, 2, 3), id="time64"), + pytest.param(pa.duration("ns"), timedelta(seconds=1), id="duration"), + *[ + pytest.param(pa.timestamp(unit), datetime(2026, 1, 2), id=f"timestamp-{unit}") + for unit in ("s", "ms", "us", "ns") + ], + pytest.param( + pa.timestamp("us", tz="UTC"), + datetime(2026, 1, 2, tzinfo=timezone.utc), + id="timestamp-utc", + ), + pytest.param(pa.decimal128(20, 4), Decimal("1.2500"), id="decimal"), + pytest.param(pa.dictionary(pa.int8(), pa.string()), "key", id="dictionary"), +] + + +@pytest.mark.parametrize(("storage_type", "value"), _PRIMITIVE_IDS) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("reopen", [False, True]) +def test_delta_duplicate_policy_for_primitive_id_storage( + tmp_path: Path, + storage_type: pa.DataType, + value: object, + skip_duplicates: bool, + reopen: bool, +) -> None: + """Exercise the primitive ID types that support a first write on main.""" + ids = pa.array([value], type=storage_type) + first = pa.table( + {"id": ids, "tag_a": ["a"], "tag_b": ["b"], "v": ["first"], "w": [1]} + ) + repeat = first.set_column(3, "v", pa.array(["repeat"])) + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, first, skip_duplicates=skip_duplicates, flush=True) + db = DeltaTableDatabase(tmp_path) if reopen else writer + if skip_duplicates: + if pa.types.is_float16(storage_type): + # Main's Arrow lookup has no half-float kernel. The first write + # succeeds, and a repeat without coercion still reports that error. + with pytest.raises(pa.ArrowNotImplementedError, match="is_in"): + db.add_records(PATH, repeat, skip_duplicates=True, flush=True) + else: + db.add_records(PATH, repeat, skip_duplicates=True, flush=True) + else: + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records(PATH, repeat) + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.to_pylist() == first.to_pylist() + + +@pytest.mark.parametrize( + ("storage_type", "value"), + [ + case + for case in _PRIMITIVE_IDS + # These storage types either require Orcapod's plain-type encoding or + # do not read back with an extension registered over the native type. + if case.id + not in { + "float16", + "string", + "binary", + "fixed-binary", + "time32", + "time64", + "duration", + "dictionary", + } + ], +) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("reopen", [False, True]) +def test_delta_duplicate_policy_for_primitive_extension_id_storage( + tmp_path: Path, + storage_type: pa.DataType, + value: object, + skip_duplicates: bool, + reopen: bool, +) -> None: + """Compare typed storage on the writing handle and a fresh handle.""" + extension = _NativeIdType(storage_type) + ids = pa.ExtensionArray.from_storage( + extension, pa.array([value], type=storage_type) + ) + first = pa.table( + {"id": ids, "tag_a": ["a"], "tag_b": ["b"], "v": ["first"], "w": [1]} + ) + repeat = first.set_column(3, "v", pa.array(["repeat"])) + pa.register_extension_type(cast(Any, extension)) + try: + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, first, skip_duplicates=skip_duplicates, flush=True) + db = DeltaTableDatabase(tmp_path) if reopen else writer + if skip_duplicates: + db.add_records(PATH, repeat, skip_duplicates=True, flush=True) + else: + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records(PATH, repeat) + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.to_pylist() == first.to_pylist() + finally: + pa.unregister_extension_type(extension.extension_name) + + +def test_delta_skip_pending_timestamp_extension_id_preserves_nanoseconds( + tmp_path: Path, +) -> None: + """A pending extension ID is matched at its Arrow timestamp resolution.""" + storage_type = pa.timestamp("ns") + extension = _NativeIdType(storage_type) + ids = pa.ExtensionArray.from_storage(extension, pa.array([1001], type=storage_type)) + first = pa.table( + {"id": ids, "tag_a": ["a"], "tag_b": ["b"], "v": ["first"], "w": [1]} + ) + repeat = first.set_column(3, "v", pa.array(["repeat"])) + pa.register_extension_type(cast(Any, extension)) + try: + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, first, skip_duplicates=True) + db.add_records(PATH, repeat, skip_duplicates=True) + pending = db.get_all_records(PATH, record_id_column="id") + assert pending is not None + assert pending.equals(first) + db.flush() + stored = db.get_all_records(PATH) + assert stored is not None + assert stored["v"].to_pylist() == ["first"] + finally: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize( + ("tick", "stored_tick", "tz"), + [(1001, 1, None), (-1001, -1, "America/New_York")], +) +def test_delta_writer_skips_persisted_lossy_root_timestamp_extension_id( + tmp_path: Path, + tick: int, + stored_tick: int, + tz: str | None, +) -> None: + """The writer keeps the original row when the persisted root ID is repeated.""" + timestamp = pa.timestamp("ns") if tz is None else pa.timestamp("ns", tz) + extension = _NativeIdType(timestamp) + pa.register_extension_type(cast(Any, extension)) + try: + first = pa.ExtensionArray.from_storage( + extension, pa.array([tick], type=timestamp) + ) + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, pa.table({"id": first, "v": ["first"]}), flush=True) + persisted = DeltaTableDatabase(tmp_path).get_all_records( + PATH, record_id_column="id" + ) + assert persisted is not None + held_timestamp = pa.timestamp("us") if tz is None else pa.timestamp("us", "UTC") + held_type = _NativeIdType(held_timestamp) + assert persisted["id"].type == held_type + held_id = pa.ExtensionArray.from_storage( + held_type, pa.array([stored_tick], type=held_timestamp) + ) + assert persisted["id"].equals(pa.chunked_array([held_id])) + + distinct = pa.ExtensionArray.from_storage( + held_type, pa.array([tick], type=held_timestamp) + ) + writer.add_records( + PATH, + pa.table({"id": distinct, "v": ["distinct"]}), + skip_duplicates=True, + flush=True, + ) + writer.add_records( + PATH, + persisted.set_column(1, "v", pa.array(["repeat"])), + skip_duplicates=True, + flush=True, + ) + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert stored is not None + assert stored.num_rows == 2 + assert set(stored["v"].to_pylist()) == {"distinct", "first"} + finally: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize(("unit", "microseconds"), [("s", 1_000_000), ("ms", 1_000)]) +@pytest.mark.parametrize("reopen", [False, True]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_compares_nested_timestamps_across_storage_units( + tmp_path: Path, + unit: Literal["s", "ms"], + microseconds: int, + reopen: bool, + skip_duplicates: bool, +) -> None: + """A distinct ID may have the same raw ticks as a stored ID in another unit.""" + id_type = pa.struct([("ts", pa.timestamp(unit, "UTC"))]) + + def row(tick: int, label: str) -> pa.Table: + """Build one row with the timestamp expressed in the input unit.""" + return pa.table({"id": pa.array([{"ts": tick}], type=id_type), "v": [label]}) + + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, row(1, "first"), flush=True) + db = DeltaTableDatabase(tmp_path) if reopen else writer + if skip_duplicates: + db.add_records(PATH, row(1, "repeat"), skip_duplicates=True, flush=True) + else: + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records(PATH, row(1, "repeat")) + db.add_records( + PATH, row(microseconds, "distinct"), skip_duplicates=skip_duplicates, flush=True + ) + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert stored is not None + assert stored.num_rows == 2 + assert set(stored["v"].to_pylist()) == {"distinct", "first"} + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("handle", ["pending", "writer", "reopened"]) +def test_delta_date_extension_id_outside_python_date_range( + tmp_path: Path, skip_duplicates: bool, handle: str +) -> None: + """Write and compare an ordinal ID that Python's date cannot represent.""" + extension = _OrdinalDateType() + ids = pa.ExtensionArray.from_storage( + extension, pa.array([4_000_000], type=extension.storage_type) + ) + # Main's statistics selection also excludes this field name in a payload + # struct, so its create is readable for a date outside Python's range. + first = pa.table( + { + "id": ids, + "tag_a": ["a"], + "tag_b": ["b"], + "v": ["first"], + "w": [{"__record_id": 1}], + } + ) + repeat = first.set_column(3, "v", pa.array(["repeat"])) + pa.register_extension_type(cast(Any, extension)) + try: + writer = DeltaTableDatabase(tmp_path) + writer.add_records( + PATH, first, skip_duplicates=skip_duplicates, flush=handle != "pending" + ) + db = DeltaTableDatabase(tmp_path) if handle == "reopened" else writer + if skip_duplicates: + db.add_records(PATH, repeat, skip_duplicates=True) + else: + location = "pending" if handle == "pending" else "stored" + with pytest.raises(ValueError, match=f"already exist.*{location}"): + db.add_records(PATH, repeat) + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.to_pylist() == first.to_pylist() + finally: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("nested_type", ["list", "struct"]) +@pytest.mark.parametrize("mixed", [False, True]) +def test_delta_nested_extension_id_loses_at_flush( + tmp_path: Path, + skip_duplicates: bool, + nested_type: str, + mixed: bool, +) -> None: + """A duplicate queued before the winner commits is skipped at flush.""" + if nested_type == "list": + storage = pa.array([[1, 2]], type=pa.large_list(pa.int64())) + new_storage = pa.array([[3, 4]], type=storage.type) + else: + storage = pa.array( + [{"x": 1, "y": 2}], type=pa.struct([("x", pa.int64()), ("y", pa.int64())]) + ) + new_storage = pa.array([{"x": 3, "y": 4}], type=storage.type) + extension = _CompositeKeyType(storage.type) + ids = pa.ExtensionArray.from_storage(extension, storage) + first = pa.table( + {"id": ids, "tag_a": ["a"], "tag_b": ["b"], "v": ["winner"], "w": [1]} + ) + repeat = first.set_column(3, "v", pa.array(["loser"])) + new = first.set_column(3, "v", pa.array(["new"])).set_column( + 0, "id", pa.ExtensionArray.from_storage(extension, new_storage) + ) + pa.register_extension_type(cast(Any, extension)) + try: + loser = DeltaTableDatabase(tmp_path) + winner = DeltaTableDatabase(tmp_path) + loser.add_records(PATH, repeat, skip_duplicates=skip_duplicates) + if mixed: + loser.add_records(PATH, new, skip_duplicates=skip_duplicates) + winner.add_records(PATH, first, skip_duplicates=skip_duplicates, flush=True) + loser.flush() + stored = loser.get_all_records(PATH, record_id_column="id") + assert stored is not None + expected = pa.concat_tables([first, new]) if mixed else first + assert sorted(stored.to_pylist(), key=lambda row: row["v"]) == sorted( + expected.to_pylist(), key=lambda row: row["v"] + ) + loser.flush() + finally: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize( + "encoding", ["string", "integer", "dictionary", "enum", "list", "struct"] +) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("handle", ["pending", "writer", "reopened"]) +def test_delta_duplicate_policy_for_id_storage( + tmp_path: Path, encoding: str, skip_duplicates: bool, handle: str +) -> None: + """First writes and repeats work with primitive and composite ID storage.""" + extension: pa.ExtensionType | None = None + if encoding == "string": + ids = pa.array(["first"]) + elif encoding == "dictionary": + ids = pa.array([1]).dictionary_encode() + elif encoding == "integer": + ids = pa.array([1]) + else: + if encoding == "enum": + extension = _RecordKeyType() + storage = pa.array([1]) + elif encoding == "list": + extension = _CompositeKeyType(pa.list_(pa.int64())) + storage = pa.array([[1, 2]], type=pa.list_(pa.int64())) + else: + extension = _CompositeKeyType( + pa.struct([("x", pa.int64()), ("y", pa.int64())]) + ) + storage = pa.array([{"x": 1, "y": 2}], type=extension.storage_type) + ids = pa.ExtensionArray.from_storage(extension, storage) + + first = pa.table({"id": ids, "v": ["first"]}) + duplicate = pa.table({"id": ids, "v": ["duplicate"]}) + if extension is not None: + pa.register_extension_type(cast(Any, extension)) + try: + writer = DeltaTableDatabase(tmp_path) + writer.add_records( + PATH, first, flush=handle != "pending", skip_duplicates=skip_duplicates + ) + db = DeltaTableDatabase(tmp_path) if handle == "reopened" else writer + if skip_duplicates: + db.add_records(PATH, duplicate, skip_duplicates=True) + else: + location = "pending" if handle == "pending" else "stored" + with pytest.raises(ValueError, match=f"already exist.*{location}"): + db.add_records(PATH, duplicate) + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.to_pylist() == first.to_pylist() + finally: + if extension is not None: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize("backend", ["delta", "memory", "sqlite", "connector"]) +def test_add_refuses_stored_id_without_buffering_other_rows( + tmp_path: Path, backend: str +) -> None: + """Both add methods reject a stored key, leaving the entire add unapplied.""" + with SQLiteConnector(":memory:") as sqlite: + db = { + "delta": DeltaTableDatabase(tmp_path), + "memory": InMemoryArrowDatabase(), + "sqlite": ConnectorArrowDatabase(sqlite), + "connector": ConnectorArrowDatabase(MockDBConnector()), + }[backend] + db.add_record(PATH, b"x", pa.table({"v": [1]}), flush=True) + + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_record(PATH, b"x", pa.table({"v": [2]})) + rows = pa.table({"id": [b"x", b"y"], "v": [2, 3]}) + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records(PATH, rows, record_id_column="id") + db.flush() + + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.to_pylist() == [{"id": b"x", "v": 1}] + + +@pytest.mark.parametrize("backend", ["delta", "sqlite", "connector"]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_conflict_at_flush_keeps_first_commit( + tmp_path: Path, backend: str, skip_duplicates: bool +) -> None: + """A write accepted before another handle commits the key loses at flush.""" + path = tmp_path / "store.db" + with SQLiteConnector(str(path)) as first, SQLiteConnector(str(path)) as second: + mock = MockDBConnector() + a, b = { + "delta": (DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path)), + "sqlite": (ConnectorArrowDatabase(first), ConnectorArrowDatabase(second)), + "connector": (ConnectorArrowDatabase(mock), ConnectorArrowDatabase(mock)), + }[backend] + a.add_record(PATH, b"x", pa.table({"v": [1]}), skip_duplicates=skip_duplicates) + b.add_record(PATH, b"x", pa.table({"v": [2]}), flush=True) + if backend == "delta": + a.add_record( + PATH, b"y", pa.table({"v": [3]}), skip_duplicates=skip_duplicates + ) + a.flush() + reader = DeltaTableDatabase(tmp_path) if backend == "delta" else b + stored = reader.get_all_records(PATH) + assert stored is not None + assert stored.sort_by("v").to_pylist() == ( + [{"v": 2}, {"v": 3}] if backend == "delta" else [{"v": 2}] + ) + + +@pytest.mark.parametrize("initial", ["absent", "existing", "replaced"]) +def test_delta_add_sees_id_committed_since_its_last_read( + tmp_path: Path, initial: str +) -> None: + """The strict add checks the current store, including for a warm handle.""" + a, b = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + if initial != "absent": + a.add_record(PATH, b"initial", pa.table({"v": [0]}), flush=True) + assert a.get_record_by_id(PATH, b"x") is None + if initial == "replaced": + _ = (tmp_path / PATH[0]).rename(tmp_path / "old") + b.add_record(PATH, b"x", pa.table({"v": [1]}), flush=True) + with pytest.raises(ValueError, match="already exist.*stored"): + a.add_record(PATH, b"x", pa.table({"v": [2]})) + + +@pytest.mark.parametrize("container", ["struct", "list", "map"]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_refuses_changed_nested_id_type_against_stored( + tmp_path: Path, container: str, skip_duplicates: bool +) -> None: + """Main refuses the repeat. A rejected add must leave the original row intact.""" + stored_type = pa.struct([("key", pa.int64()), ("extra", pa.int64())]) + incoming_type = pa.struct([("key", pa.int64())]) + key: dict[str, int] | list[dict[str, int]] | list[tuple[str, dict[str, int]]] + distinct_key: ( + dict[str, int] | list[dict[str, int]] | list[tuple[str, dict[str, int]]] + ) + key = {"key": 1} + distinct_key = {"key": 2} + if container == "list": + stored_type, incoming_type = pa.list_(stored_type), pa.list_(incoming_type) + key, distinct_key = [key], [distinct_key] + elif container == "map": + stored_type = pa.map_(pa.string(), stored_type) + incoming_type = pa.map_(pa.string(), incoming_type) + key, distinct_key = [("a", key)], [("a", distinct_key)] + first = pa.table({"id": pa.array([key], type=stored_type), "v": [1]}) + repeat = pa.table({"id": pa.array([key], type=incoming_type), "v": [2]}) + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, first, flush=True, record_id_column="id") + reopened = DeltaTableDatabase(tmp_path) + initial = reopened.get_all_records(PATH, record_id_column="id") + assert initial is not None + with pytest.raises( + InputValidationError, + match=rf"{re.escape(str(incoming_type))}.*stored table.*{re.escape(str(stored_type))}", + ): + reopened.add_records( + PATH, repeat, record_id_column="id", skip_duplicates=skip_duplicates + ) + # MERGE would also keep just the first row if the mismatched add had queued. + # An add using the original type must still be able to queue and flush. + distinct = pa.table({"id": pa.array([distinct_key], type=stored_type), "v": [3]}) + reopened.add_records(PATH, distinct, record_id_column="id", flush=True) + stored = reopened.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("v")["v"].to_pylist() == [1, 3] + + +@pytest.mark.parametrize("reopen", [False, True]) +def test_delta_does_not_skip_a_different_nested_extension_id( + tmp_path: Path, reopen: bool +) -> None: + """Timestamp ticks and integer IDs with the same encoding denote different keys.""" + timestamp = _CompositeKeyType(pa.struct([("x", pa.timestamp("us", "UTC"))])) + milliseconds = _CompositeKeyType(pa.struct([("x", pa.timestamp("ms", "UTC"))])) + integer = _CompositeKeyType(pa.struct([("x", pa.int64())])) + + def row(extension: _CompositeKeyType, tick: int, label: str) -> pa.Table: + storage = pa.array([{"x": tick}], type=extension.storage_type) + return pa.table( + {"id": pa.ExtensionArray.from_storage(extension, storage), "v": [label]} + ) + + pa.register_extension_type(cast(Any, timestamp)) + try: + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, row(timestamp, 1000, "first"), flush=True) + db = DeltaTableDatabase(tmp_path) if reopen else writer + with pytest.raises(InputValidationError, match="Record ID storage type"): + db.add_records( + PATH, row(integer, 1_000_000, "different"), skip_duplicates=True + ) + db.add_records(PATH, row(milliseconds, 1, "repeat"), skip_duplicates=True) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) + assert stored is not None + assert stored["v"].to_pylist() == ["first"] + finally: + pa.unregister_extension_type(timestamp.extension_name) + + +def test_sqlite_strict_add_reports_a_stored_id_read_error() -> None: + """A failed lookup reports the backend read error before queueing the row.""" + with SQLiteConnector(":memory:") as sqlite: + db = ConnectorArrowDatabase(sqlite) + db.add_record(PATH, b"x", pa.table({"v": [1]}), flush=True) + conn = sqlite._require_open() # pyright: ignore[reportPrivateUsage] + + def authorize( + action: int, + _table: str | None, + column: str | None, + _database: str | None, + _trigger: str | None, + ) -> int: + if action == SQLITE_READ and column == "__record_id": + return SQLITE_DENY + return SQLITE_OK + + conn.set_authorizer(authorize) + try: + with pytest.raises(OrcapodDatabaseReadError) as info: + db.add_record(PATH, b"y", pa.table({"v": [2]})) + finally: + conn.set_authorizer(None) + assert info.value.record_path == PATH + assert isinstance(info.value.__cause__, DatabaseError) + db.flush() + stored = db.get_all_records(PATH) + assert stored is not None and stored["v"].to_pylist() == [1] + + +@pytest.mark.parametrize("committed", [False, True]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_refuses_pending_struct_id_coercion( + tmp_path: Path, committed: bool, skip_duplicates: bool +) -> None: + """Main refuses the repeat, and the original pending rows still flush.""" + pending_type = pa.struct([("key", pa.int64()), ("extra", pa.int64())]) + incoming_type = pa.struct([("key", pa.int64())]) + db = DeltaTableDatabase(tmp_path) + if committed: + seed = pa.table({"id": pa.array([{"key": 0}], type=pending_type), "v": [0]}) + db.add_records(PATH, seed, record_id_column="id", flush=True) + first = pa.table({"id": pa.array([{"key": 1}], type=pending_type), "v": [1]}) + repeat = pa.table({"id": pa.array([{"key": 1}], type=incoming_type), "v": [2]}) + db.add_records(PATH, first, record_id_column="id") + with pytest.raises( + InputValidationError, + match=rf"{re.escape(str(incoming_type))}.*pending batch.*{re.escape(str(pending_type))}", + ): + db.add_records( + PATH, + repeat, + record_id_column="id", + schema_handling="coerce", + skip_duplicates=skip_duplicates, + ) + db.flush() + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None + assert stored.sort_by("v")["v"].to_pylist() == ([0, 1] if committed else [1]) + + +def test_strict_sqlite_insert_reports_a_constraint_error() -> None: + """Strict writes skip a lost ID race and still report other SQL errors.""" + with SQLiteConnector(":memory:") as sqlite: + db = ConnectorArrowDatabase(sqlite) + schema = pa.schema([pa.field("v", pa.int64(), nullable=False)]) + db.add_record(PATH, b"x", pa.table({"v": [1]}, schema=schema), flush=True) + with pytest.raises(IntegrityError, match="NOT NULL"): + db.add_record( + PATH, b"y", pa.table({"v": [None]}, schema=schema), flush=True + ) + db.add_record( + PATH, + b"y", + pa.table({"v": [None]}, schema=schema), + skip_duplicates=True, + flush=True, + ) + stored = db.get_all_records(PATH) + assert stored is not None and stored.to_pylist() == [{"v": 1}] + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("id_committed_before_add", [False, True]) +@pytest.mark.parametrize( + ("key", "payload"), + [(b"new", "taken"), (b"existing", "fresh"), (b"existing", "taken")], + ids=["payload-only", "id-only", "both"], +) +def test_sqlite_store_with_a_unique_payload_index( + tmp_path: Path, + skip_duplicates: bool, + id_committed_before_add: bool, + key: bytes, + payload: str, +) -> None: + """Apply the ID policy while preserving SQLite's other unique conflicts.""" + location = str(tmp_path / "store.sqlite") + with SQLiteConnector(location) as first, SQLiteConnector(location) as second: + writer, other = ConnectorArrowDatabase(first), ConnectorArrowDatabase(second) + other.add_record(PATH, b"owner", pa.table({"payload": ["taken"]}), flush=True) + name = next(n for n in second.get_table_names() if n.startswith("o1_")) + conn = second._require_open() + _ = conn.execute(f'CREATE UNIQUE INDEX payload_unique ON "{name}" (payload)') + conn.commit() + + original = pa.table({"payload": ["original"]}) + if id_committed_before_add: + other.add_record(PATH, b"existing", original, flush=True) + incoming = pa.table({"payload": [payload]}) + if id_committed_before_add and key == b"existing" and not skip_duplicates: + with pytest.raises(ValueError, match="already exist.*stored"): + writer.add_record(PATH, key, incoming) + else: + writer.add_record(PATH, key, incoming, skip_duplicates=skip_duplicates) + if not id_committed_before_add: + other.add_record(PATH, b"existing", original, flush=True) + writer.flush() + + stored = other.get_all_records(PATH, record_id_column="id") + assert stored is not None + expected = {b"existing": "original", b"owner": "taken"} + if key == b"new" and not skip_duplicates: + expected = {b"existing": "original", b"new": "taken"} + assert stored.num_rows == len(expected) + assert {row["id"]: row["payload"] for row in stored.to_pylist()} == expected diff --git a/tests/test_pipeline/test_attachment_store_io.py b/tests/test_pipeline/test_attachment_store_io.py index a640498bf..11cb5813b 100644 --- a/tests/test_pipeline/test_attachment_store_io.py +++ b/tests/test_pipeline/test_attachment_store_io.py @@ -11,7 +11,7 @@ from contextlib import contextmanager from pathlib import Path from typing import Any, cast -from unittest.mock import patch +from unittest.mock import Mock, patch import psycopg import pyarrow as pa @@ -31,6 +31,7 @@ from orcapod.invocation import InvocationContext from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import SideEffectPod, SideEffectPodConfig from orcapod.sources import DictSource @@ -217,7 +218,11 @@ def rollback(self) -> None: @contextmanager def _measured_store( - backend: str, log: StoreIO, monkeypatch: pytest.MonkeyPatch + backend: str, + log: StoreIO, + monkeypatch: pytest.MonkeyPatch, + *, + generic: bool = False, ) -> Iterator[ArrowDatabaseProtocol]: """Use real SQL drivers and count public in-memory lookups.""" for method in ( @@ -254,7 +259,11 @@ def sqlite_connect(*args: Any, **kwargs: Any) -> CountingConnection: monkeypatch.setattr(sqlite3, "connect", sqlite_connect) with SQLiteConnector() as connector: - yield ConnectorArrowDatabase(connector) + yield ConnectorArrowDatabase( + Mock(spec=DBConnectorProtocol, wraps=connector) + if generic + else connector + ) else: schema = f"io_{uuid.uuid4().hex[:12]}" dsn = _base_dsn() @@ -283,7 +292,11 @@ def postgres_connect(*args: Any, **kwargs: Any) -> CountingConnection: with PostgreSQLConnector( f"{dsn} options=-csearch_path={schema}" ) as connector: - yield ConnectorArrowDatabase(connector) + yield ConnectorArrowDatabase( + Mock(spec=DBConnectorProtocol, wraps=connector) + if generic + else connector + ) finally: _ = admin.execute(sql.SQL("DROP SCHEMA {} CASCADE").format(identifier)) @@ -491,3 +504,73 @@ async def test_attachment_runs_stay_within_main_store_io( if scenario in ATTACHMENT_FLUSHES: budget.update(flush[kind]) assert not (extra := Counter(actual[kind]) - budget), (kind, dict(extra)) + + +@pytest.mark.parametrize( + ("backend", "generic"), + ( + ("memory", False), + ("sqlite", False), + ("sqlite", True), + pytest.param("postgres", False, marks=pytest.mark.postgres), + pytest.param("postgres", True, marks=pytest.mark.postgres), + ), +) +def test_strict_append_io_is_bounded_by_incoming_ids( + backend: str, generic: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """Read no data rows for new keys, then fetch only the existing duplicates.""" + path = ("records",) + ids = [i.to_bytes(4, "big") for i in range(40)] + log = StoreIO() + with _measured_store(backend, log, monkeypatch, generic=generic) as store: + table_name = ( + store._path_to_table_name(path) # pyright: ignore[reportPrivateUsage] # match the physical SQL relation + if isinstance(store, ConnectorArrowDatabase) + else path[0] + ) + log.reset() + for record_id in ids: + store.add_record(path, record_id, pa.table({"payload": [1]}), flush=True) + distinct = log.snapshot() + + duplicate_ids = [ids[0], ids[-1]] + fresh = b"new" + log.reset() + with pytest.raises(ValueError, match="already exist.*stored") as exc: + store.add_records( + path, + pa.table({"id": [*duplicate_ids, fresh], "payload": [2, 3, 4]}), + flush=True, + ) + duplicates = log.snapshot() + for record_id in duplicate_ids: + assert repr(record_id) in str(exc.value) + assert repr(fresh) not in str(exc.value) + stored = store.get_all_records(path) + assert stored is not None and stored["payload"].to_pylist() == [1] * len(ids) + + if backend == "memory": + assert distinct == duplicates == {"statements": {}, "rows": {}} + return + + relation = f'"{table_name}"' + if not generic: + relation = ('"main".' if backend == "sqlite" else '"schema".') + relation + lookup = f'SELECT "__record_id" FROM {relation} WHERE "__record_id"' + if backend == "sqlite": + one_key, three_keys = f"{lookup} IN (?)", f"{lookup} IN (?, ?, ?)" + else: + one_key = three_keys = f"{lookup} = ANY(%s::bytea[])" + + for phase, query, calls, rows in ( + (distinct, one_key, len(ids) - 1, 0), + (duplicates, three_keys, 1, len(duplicate_ids)), + ): + data_reads = { + statement: count + for statement, count in phase["statements"].items() + if statement.startswith("SELECT ") and f"FROM {relation}" in statement + } + assert data_reads == {query: calls} + assert phase["rows"].get(query, 0) == rows diff --git a/tests/test_pipeline/test_result_database.py b/tests/test_pipeline/test_result_database.py index d0ec933ab..05fda8610 100644 --- a/tests/test_pipeline/test_result_database.py +++ b/tests/test_pipeline/test_result_database.py @@ -544,8 +544,15 @@ def new_store(name: str) -> ArrowDatabaseProtocol: schema_mode="overwrite", ) else: - holder.add_records(path, foreign, record_id_column="__rid") - holder.flush() + assert isinstance(holder, InMemoryArrowDatabase) + key = "/".join(path) + stored_id = holder.RECORD_ID_COLUMN + holder._tables[key] = foreign.rename_columns( # pyright: ignore[reportPrivateUsage] # inject a foreign completion + [ + stored_id if name == "__rid" else name + for name in foreign.column_names + ] + ) job.bind(sources={"s": make_source([1.0, 2.0, 3.0], "new")}) with pytest.raises(SideEffectLogDataContextError): @@ -922,6 +929,32 @@ def counted(self: DeltaTableDatabase, record_path: tuple[str, ...]) -> None: assert refreshed.count(result_table) == 2 # one per node, not per row +def test_warm_delta_job_reuses_the_result_table_handle( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A warm job opens its result table only as often as on main before ITL-1386.""" + import deltalake + + db = DeltaTableDatabase(tmp_path) + _ = one_step_job("warm", db, [1.0], double).run( + orchestrator=SyncPipelineOrchestrator() + ) + job = one_step_job("warm", db, [float(i) for i in range(2, 502)], double) + open_table = deltalake.DeltaTable + result_opens = 0 + + def count_open(uri: str, *args: Any, **kwargs: Any) -> deltalake.DeltaTable: + nonlocal result_opens + if uri.rstrip("/").endswith("/rdb_v1"): + result_opens += 1 + return open_table(uri, *args, **kwargs) + + monkeypatch.setattr(deltalake, "DeltaTable", count_open) + _ = job.run(orchestrator=SyncPipelineOrchestrator()) + assert result_opens == 6 + assert len(calls) == 501 + + @pytest.mark.xfail( strict=True, raises=AssertionError,