From c2c1e07b1a3a5689534e78c9b1257d8d5aa9169e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:47:23 -0800 Subject: [PATCH 01/19] fix(databases)!: enforce database write rules (ITL-1386) --- changelog.d/ITL-1386.md | 16 ++ docs/dev/design_issues/ITL-1377-CW1.md | 4 +- docs/dev/design_issues/ITL-1386-WK1.md | 13 ++ docs/dev/design_issues/ITL-1415-WK3.md | 14 ++ docs/dev/design_issues/ITL-1444-WK4.md | 12 ++ docs/dev/design_issues/ITL-1487-WK2.md | 13 ++ src/orcapod/core/result_cache.py | 6 +- src/orcapod/databases/_sql_store.py | 14 +- .../databases/connector_arrow_database.py | 84 ++++++++--- src/orcapod/databases/delta_lake_databases.py | 142 +++++++++++------- src/orcapod/databases/delta_statistics.py | 14 +- src/orcapod/databases/in_memory_databases.py | 30 ++-- src/orcapod/databases/postgresql_connector.py | 30 ++++ src/orcapod/databases/sqlite_connector.py | 64 +++++++- src/orcapod/databases/utils.py | 50 ++++-- src/orcapod/protocols/database_protocols.py | 14 +- tests/test_core/test_result_cache.py | 39 ++++- tests/test_databases/test_append_by_name.py | 22 ++- .../test_appended_field_attributes.py | 73 +++++++++ .../test_delta_add_time_property.py | 26 +++- .../test_databases/test_delta_commit_cost.py | 4 +- .../test_delta_commit_failures.py | 2 + .../test_delta_committed_snapshot.py | 11 +- .../test_delta_concurrent_writers.py | 51 ++++++- .../test_delta_database_lookup_equivalence.py | 3 +- .../test_delta_list_binary_commits.py | 3 +- .../test_delta_native_fs_filtered_reads.py | 6 +- .../test_delta_read_your_writes.py | 35 +++-- .../test_delta_refused_before_queueing.py | 16 +- .../test_delta_statistics_columns.py | 25 ++- ...t_in_memory_database_lookup_equivalence.py | 10 +- .../test_logical_identity_appends.py | 13 +- .../test_postgresql_connector_integration.py | 29 +++- .../test_sqlite_connector_integration.py | 35 +++-- tests/test_databases/test_write_conflicts.py | 96 ++++++++++++ tests/test_pipeline/test_result_database.py | 11 +- 36 files changed, 822 insertions(+), 208 deletions(-) create mode 100644 changelog.d/ITL-1386.md create mode 100644 docs/dev/design_issues/ITL-1386-WK1.md create mode 100644 docs/dev/design_issues/ITL-1415-WK3.md create mode 100644 docs/dev/design_issues/ITL-1444-WK4.md create mode 100644 docs/dev/design_issues/ITL-1487-WK2.md create mode 100644 tests/test_databases/test_write_conflicts.py diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md new file mode 100644 index 000000000..f09139b32 --- /dev/null +++ b/changelog.d/ITL-1386.md @@ -0,0 +1,16 @@ +### 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. (ITL-1386, ITL-1487) + +### Fixed + +- Appends reject mismatched field metadata inside Arrow extension storage, as + they do for plain struct children. (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) 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..4c042d56f --- /dev/null +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -0,0 +1,13 @@ +## `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. 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..4888311f4 --- /dev/null +++ b/docs/dev/design_issues/ITL-1415-WK3.md @@ -0,0 +1,14 @@ +## `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. 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 e341983bf..85c0ad102 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -422,8 +422,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: @@ -431,6 +431,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..aec84e053 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -67,16 +67,22 @@ def create_table_if_not_exists( """Create a record table in the verified schema.""" ... - def upsert_records( + def existing_store_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 insert_store_records( self, table_name: str, records: pa.Table, id_column: str, - skip_existing: bool = False, *, - schema: str | None = None, + skip_duplicates: bool, + schema: str, ) -> None: - """Write rows to the record table in the verified schema.""" + """Insert rows into the verified table, skipping IDs won by another writer.""" ... diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 267caf622..939086ba8 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. @@ -159,9 +159,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 @@ -185,11 +184,11 @@ 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, ) ) - 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) @@ -350,6 +349,23 @@ 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_store_ids( + name, column, input_ids, schema=schema + ) + query = f"SELECT * FROM {sql_table_identifier(name, schema)}" + conflicts: set[bytes] = set() + for batch in self._connector.iter_batches(query): + conflicts.update(input_ids.intersection(batch[column].to_pylist())) + return conflicts + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. @@ -606,11 +622,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: @@ -647,15 +666,26 @@ 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: + conflicts = self._stored_conflicts(committed_table, input_ids) + 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) @@ -674,6 +704,8 @@ def add_records( self._pending_record_ids[record_key].update( cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) ) + if skip_duplicates: + self._pending_skip_existing[record_key] = True if flush: self.flush() @@ -874,7 +906,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) @@ -906,9 +938,9 @@ 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) if record_key not in self._pending_batches: - self._discard_pending_duplicate_policy(record_key) + self._discard_pending_state(record_key) record_path = self._record_path_from_key(record_key) table_name = self._path_to_table_name(record_path) @@ -927,7 +959,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.finish(record_key, committed=False) @@ -942,7 +979,7 @@ def _write_ready_batch( record_key: str, table_name: str, pending: pa.Table, - skip_existing: bool, + skip_duplicates: bool, table_exists: bool, schema: str | None, ) -> None: @@ -954,6 +991,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} @@ -978,6 +1023,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 @@ -986,17 +1033,18 @@ 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( + self._sql_store.insert_store_records( table_name, pending, id_column=self.RECORD_ID_COLUMN, - skip_existing=skip_existing, + skip_duplicates=skip_duplicates, schema=schema, ) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..ecf27b435 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -928,14 +928,13 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: 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( + changed = appended_field_change( held.with_metadata(cast(Any, _metadata(held.metadata))), field.with_metadata(cast(Any, _metadata(field.metadata))), - ) or _evolution_change( + ) + if changed is not None or _is_logical(field) or _is_logical(held): + 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, @@ -945,7 +944,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) @@ -1529,40 +1528,62 @@ 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() not in (ARROW_TYPE_KEY, *_EXTENSION_KEYS) + } + 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 @@ -1572,6 +1593,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. @@ -1581,7 +1604,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 ] ) @@ -2734,17 +2761,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) @@ -2772,6 +2803,12 @@ 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: + # Strict adds check the table as it stands now. The ID snapshot can + # still be reused when the table's ID and version match. + record_key = self._get_record_key(record_path) + self._delta_table_cache.pop(record_key, None) + self._absent_tables.discard(record_key) 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 @@ -2796,24 +2833,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 @@ -2930,21 +2950,35 @@ def _check_all_conflicts( """Check for conflicts with both pending batch and Delta table.""" input_ids = set(table[self.RECORD_ID_COLUMN].to_pylist()) 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: 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: 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( @@ -3896,9 +3930,9 @@ def _commit_once( # 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. + # (ITL-1377). New tables exclude the id column from file statistics + # (ITL-1444), so no file is skipped, and a concurrent commit of any + # id still makes this commit fail. streamed_exec=False, ).when_not_matched_insert_all().execute() except CommitFailedError as conflict: 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 2ccb4d696..2868e4ced 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -317,14 +317,22 @@ def add_records( if records.num_rows == 0: return else: - # Check for conflicts in the pending batch only input_ids = set(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) @@ -442,20 +450,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 b767a955d..0722378f6 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -542,6 +542,36 @@ def get_current_store_schema(self) -> str: _require_persistent_store_schema(schema, row[1]) return schema + def existing_store_ids( + self, table_name: str, id_column: str, ids: set[bytes], *, schema: str + ) -> set[bytes]: + """Look up existing record IDs using the table's primary key.""" + from psycopg import sql + + table = sql.Identifier(schema.replace("%", "%%"), table_name.replace("%", "%%")) + 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/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 684de8bb7..a114905dd 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -349,6 +349,27 @@ def get_current_store_schema(self) -> str: self._require_open() return "main" + def existing_store_ids( + self, table_name: str, id_column: str, ids: set[bytes], *, schema: str + ) -> 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 +639,51 @@ 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, preserving SQLite's existing write-if-missing behavior.""" + 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, + 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..968d0d626 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -139,9 +139,9 @@ def appended_field_change( 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). @@ -163,39 +163,65 @@ def appended_field_change( 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 ) -> 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): 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) -def _nested_change(held: Any, incoming: Any, path: str) -> str | None: +def _nested_change( + held: Any, incoming: Any, path: str, *, metadata_only: 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, + ) if found is not None: return found return None 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, + ) or _child_change( + held.item_field, + incoming.item_field, + f"{path}.item", + metadata_only=metadata_only, + ) 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, ) 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/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 fe428e867..e2f65f560 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -536,9 +536,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), @@ -804,12 +808,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): @@ -934,12 +941,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..720df3cea 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 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,74 @@ 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) + + +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) 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..7f56345b7 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -217,7 +217,7 @@ def test_create_append_merge_and_schema_evolution( 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) + db.add_records(PATH, rows(range(15, 30)), skip_duplicates=True, flush=True) assert stats_warnings(capfd) == [], "merge" # New columns (one binary, one int): schema evolution, through MERGE. @@ -358,9 +358,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 +451,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 +491,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 +516,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 a37606b8e..49ec7b769 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -1594,8 +1594,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 @@ -1621,7 +1621,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] @@ -1876,16 +1876,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'" ): @@ -2064,7 +2063,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 9e8006978..0f1c214e0 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -107,6 +107,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( @@ -789,7 +810,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: @@ -1081,13 +1102,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..c6d0e82d9 --- /dev/null +++ b/tests/test_databases/test_write_conflicts.py @@ -0,0 +1,96 @@ +"""Write conflicts are checked when rows are added (ITL-1386, ITL-1487).""" + +from pathlib import Path +from sqlite3 import IntegrityError + +import pyarrow as pa +import pytest + +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SQLiteConnector, +) +from tests.test_databases.test_connector_arrow_database import MockDBConnector + +PATH = ("records",) + + +@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) + a.flush() + stored = b.get_all_records(PATH) + assert stored is not None + assert stored.to_pylist() == [{"v": 2}] + + +def test_delta_add_sees_id_committed_since_its_last_read(tmp_path: Path) -> None: + """The strict add checks the current store, including for a warm handle.""" + a, b = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + a.add_record(PATH, b"initial", pa.table({"v": [0]}), flush=True) + assert a.get_record_by_id(PATH, b"x") is None + 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]})) + + +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}] diff --git a/tests/test_pipeline/test_result_database.py b/tests/test_pipeline/test_result_database.py index 637173c43..3cfd3f04d 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): From c7f79d733806c0bcf6ba99501a7d5d59b7afeab3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:14:45 -0800 Subject: [PATCH 02/19] fix(databases): allow Delta appends with unrecorded extension metadata (ITL-1415) --- changelog.d/ITL-1386.md | 7 +++ docs/dev/design_issues/ITL-1415-WK3.md | 5 ++ src/orcapod/databases/delta_lake_databases.py | 23 ++++++---- src/orcapod/databases/utils.py | 46 +++++++++++++++++-- .../test_appended_field_attributes.py | 39 +++++++++++++++- .../test_delta_statistics_columns.py | 10 +++- 6 files changed, 114 insertions(+), 16 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index f09139b32..090f0547b 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -14,3 +14,10 @@ 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 + +- 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-1415-WK3.md b/docs/dev/design_issues/ITL-1415-WK3.md index 4888311f4..a0485b99a 100644 --- a/docs/dev/design_issues/ITL-1415-WK3.md +++ b/docs/dev/design_issues/ITL-1415-WK3.md @@ -12,3 +12,8 @@ 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. + +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/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index ecf27b435..0abe8b4ee 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -909,7 +909,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 @@ -924,13 +926,16 @@ 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``. """ + held_metadata = metadata_bytes(held.metadata) changed = appended_field_change( - held.with_metadata(cast(Any, _metadata(held.metadata))), + held.with_metadata(cast(Any, _metadata(held_metadata))), field.with_metadata(cast(Any, _metadata(field.metadata))), + delta_log_storage=from_delta_log and ARROW_TYPE_KEY not in held_metadata, ) if changed is not None or _is_logical(field) or _is_logical(held): return changed @@ -1205,7 +1210,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: @@ -2670,9 +2675,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 @@ -2684,12 +2689,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 " diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 968d0d626..7a8f6e35b 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -132,7 +132,10 @@ 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, ) -> str | None: """Say why rows of ``incoming`` would not read back as written, appended to a column a database holds as ``held`` (ITL-1334). @@ -149,6 +152,9 @@ 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. Returns: The reason, naming the path (``x``, ``x.a``, ``x[]``, ``x.key``), or ``None``. @@ -159,21 +165,41 @@ 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, ) def _child_change( - held: "pa.Field[Any]", incoming: "pa.Field[Any]", path: str, *, metadata_only: bool + held: "pa.Field[Any]", + incoming: "pa.Field[Any]", + path: str, + *, + metadata_only: bool, + delta_log_storage: bool, + check_metadata: bool = True, ) -> str | None: 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): + if check_metadata and metadata_bytes(held.metadata) != metadata_bytes( + incoming.metadata + ): return f"{path} has other field metadata than the stored column" - return _nested_change(held.type, incoming.type, path, metadata_only=metadata_only) + return _nested_change( + held.type, + incoming.type, + path, + metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + ) def _nested_change( - held: Any, incoming: Any, path: str, *, metadata_only: bool = False + held: Any, + incoming: Any, + path: str, + *, + delta_log_storage: bool, + metadata_only: 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"). @@ -193,10 +219,14 @@ def _nested_change( field, f"{path}.{field.name}", metadata_only=metadata_only, + delta_log_storage=delta_log_storage, ) 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) if t.is_map(held) and t.is_map(incoming): if not metadata_only and held.keys_sorted != incoming.keys_sorted: return ( @@ -208,11 +238,15 @@ def _nested_change( incoming.key_field, f"{path}.key", metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + 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, + 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): @@ -222,6 +256,8 @@ def _nested_change( cast(Any, incoming).value_field, f"{path}[]", metadata_only=metadata_only, + delta_log_storage=delta_log_storage, + check_metadata=collection_metadata_known, ) return None diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index 720df3cea..2fd5f50e4 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -18,7 +18,7 @@ import pyarrow as pa import pytest -from orcapod.databases import ConnectorArrowDatabase +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 ( @@ -323,3 +323,40 @@ def test_metadata_inside_extension_storage_must_match( assert sorted(stored["id"].to_pylist()) == [b"a", b"c"] finally: pa.unregister_extension_type(first.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_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index 7f56345b7..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=True, 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) From 1e48d3dafe23ca8de51ac378b587bca976fb0d6a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:59:40 -0800 Subject: [PATCH 03/19] fix(databases): preserve Delta append metadata and reuse strict write snapshots --- docs/dev/design_issues/ITL-1386-WK1.md | 1 + docs/dev/design_issues/ITL-1415-WK3.md | 3 + src/orcapod/databases/delta_lake_databases.py | 102 +++++++++++++++--- src/orcapod/databases/utils.py | 16 ++- .../test_appended_field_attributes.py | 85 +++++++++++++++ tests/test_databases/test_write_conflicts.py | 10 +- tests/test_pipeline/test_result_database.py | 26 +++++ 7 files changed, 219 insertions(+), 24 deletions(-) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index 4c042d56f..b5a306b6d 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -11,3 +11,4 @@ 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. +Delta reuses the loaded table and ID snapshot when the log has not advanced. diff --git a/docs/dev/design_issues/ITL-1415-WK3.md b/docs/dev/design_issues/ITL-1415-WK3.md index a0485b99a..67312395b 100644 --- a/docs/dev/design_issues/ITL-1415-WK3.md +++ b/docs/dev/design_issues/ITL-1415-WK3.md @@ -12,6 +12,9 @@ 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. +This allows an IPC-decoded logical child to carry its identifier as Arrow metadata +when its extension is unregistered. 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. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 0abe8b4ee..fff20a973 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -13,6 +13,7 @@ from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast +from weakref import ReferenceType, ref import polars as pl import pyarrow as pa @@ -1556,7 +1557,11 @@ def _plain_delta_type(delta_type: Any, *, keep_user_metadata: bool) -> Any: { k: v for k, v in f.metadata.items() - if k.encode() not in (ARROW_TYPE_KEY, *_EXTENSION_KEYS) + 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 @@ -1818,6 +1823,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: @@ -1962,9 +1972,7 @@ def _get_delta_table( try: # Try to load existing table - 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 @@ -1991,6 +1999,71 @@ 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 # let the next load report any read failure + self._delta_table_cache.pop(record_key, None) + else: + 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``. @@ -2811,11 +2884,7 @@ 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: - # Strict adds check the table as it stands now. The ID snapshot can - # still be reused when the table's ID and version match. - record_key = self._get_record_key(record_path) - self._delta_table_cache.pop(record_key, None) - self._absent_tables.discard(record_key) + 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 @@ -3617,10 +3686,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. @@ -3629,6 +3699,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: @@ -3782,9 +3854,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( @@ -3838,9 +3908,7 @@ def _commit_once( # Only TableNotFoundError means "absent": a table that exists but cannot be # loaded is never created over (ITL-884). try: - delta_table = deltalake.DeltaTable( - table_uri, storage_options=self._storage_options or None - ) + delta_table = self._open_delta_table(table_uri) except TableNotFoundError: delta_table = None except Exception as load_error: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 7a8f6e35b..a02a5ce0c 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -154,7 +154,8 @@ def appended_field_change( 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. + map keys and values. Struct field metadata is still known, apart + from the logical identifiers checked separately against the log. Returns: The reason, naming the path (``x``, ``x.a``, ``x[]``, ``x.key``), or ``None``. @@ -180,10 +181,15 @@ def _child_change( ) -> str | None: 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 check_metadata and metadata_bytes(held.metadata) != metadata_bytes( - incoming.metadata - ): - return f"{path} has other field metadata than the stored column" + if check_metadata: + incoming_metadata = metadata_bytes(incoming.metadata) + if delta_log_storage and metadata_only and _EXTENSION_NAME in incoming_metadata: + # The physical Delta schema omits these keys to prevent Arrow from + # decoding the extension. The identity check uses the raw log instead. + del incoming_metadata[_EXTENSION_NAME] + incoming_metadata.pop(_EXTENSION_METADATA, None) + if metadata_bytes(held.metadata) != incoming_metadata: + return f"{path} has other field metadata than the stored column" return _nested_change( held.type, incoming.type, diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index 2fd5f50e4..820c4e428 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -325,6 +325,91 @@ def test_metadata_inside_extension_storage_must_match( pa.unregister_extension_type(first.extension_name) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_delta_appends_ipc_decoded_unregistered_extension_child( + tmp_path: Path, skip_duplicates: bool +) -> None: + """An IPC reader can expose a logical child as storage plus its identifier.""" + 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: + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, first.schema) as writer: + writer.write_table(first) + decoded = pa.ipc.open_stream(sink.getvalue()).read_all() + 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", + } + + DeltaTableDatabase(tmp_path).add_records(PATH, first, flush=True) + fresh = DeltaTableDatabase(tmp_path) + fresh.add_records( + PATH, + decoded.set_column(0, "id", pa.array([b"b"])), + skip_duplicates=skip_duplicates, + 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"] + finally: + pa.unregister_extension_type(extension.extension_name) + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("key", ["orcapod:arrow_type", "ARROW:extension:metadata"]) +def test_delta_appends_identical_reserved_key_used_as_nested_metadata( + tmp_path: Path, skip_duplicates: bool, key: str +) -> None: + """A nested key with no special meaning is compared as ordinary metadata.""" + 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 diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index c6d0e82d9..8bb0ce1e2 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -65,11 +65,17 @@ def test_conflict_at_flush_keeps_first_commit( assert stored.to_pylist() == [{"v": 2}] -def test_delta_add_sees_id_committed_since_its_last_read(tmp_path: Path) -> None: +@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) - a.add_record(PATH, b"initial", pa.table({"v": [0]}), flush=True) + 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]})) diff --git a/tests/test_pipeline/test_result_database.py b/tests/test_pipeline/test_result_database.py index 3cfd3f04d..cdbe737ee 100644 --- a/tests/test_pipeline/test_result_database.py +++ b/tests/test_pipeline/test_result_database.py @@ -929,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, From 6f11cbec5da287ae6d89e51fcc8d776c51457e9c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:06:09 -0800 Subject: [PATCH 04/19] fix(databases): keep the readable snapshot after a failed Delta refresh --- src/orcapod/databases/delta_lake_databases.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index fff20a973..791558058 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2044,11 +2044,12 @@ def _refresh_before_strict_add(self, record_path: tuple[str, ...]) -> None: return try: cached.update_incremental() - except Exception: # noqa: BLE001 # let the next load report any read failure - self._delta_table_cache.pop(record_key, None) - else: - if stamp is not None: - self._local_log_stamps[table_uri] = (ref(cached), stamp) + 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: From d4a4cc2b6ad3ed6637f996bdb7b38bb0cd12e03a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 07:04:29 -0800 Subject: [PATCH 05/19] fix(delta): allow appends with unknown IPC extension storage metadata --- changelog.d/ITL-1386.md | 5 +- docs/dev/design_issues/ITL-1415-WK3.md | 6 +- src/orcapod/databases/delta_lake_databases.py | 16 ++- src/orcapod/databases/utils.py | 24 ++-- .../test_appended_field_attributes.py | 121 +++++++++++++++++- 5 files changed, 154 insertions(+), 18 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index 090f0547b..cbfe552f7 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -8,8 +8,9 @@ ### Fixed -- Appends reject mismatched field metadata inside Arrow extension storage, as - they do for plain struct children. (ITL-1415) +- Appends reject mismatches in known field metadata inside Arrow extension + storage. Delta accepts IPC-decoded columns and children whose extensions 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. diff --git a/docs/dev/design_issues/ITL-1415-WK3.md b/docs/dev/design_issues/ITL-1415-WK3.md index 67312395b..e926b5444 100644 --- a/docs/dev/design_issues/ITL-1415-WK3.md +++ b/docs/dev/design_issues/ITL-1415-WK3.md @@ -13,8 +13,10 @@ with the held column's metadata. 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. -This allows an IPC-decoded logical child to carry its identifier as Arrow metadata -when its extension is unregistered. +When IPC exposes an unregistered extension as storage with an Arrow annotation, +the comparison leaves that extension's storage attributes to the existing append +checks. This applies to both the column's extension and an extension nested inside +its storage. 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. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 791558058..bbbd803ed 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -933,12 +933,26 @@ def _column_change( The reason, naming the path, or ``None``. """ held_metadata = metadata_bytes(held.metadata) + logical = _is_logical(field) or _is_logical(held) + if 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) + ) + ): + # An annotated storage array does not supply the extension's storage + # schema. The physical log can supply struct metadata for a concrete + # incoming extension when it has the stored extension annotation. + if _metadata(held_metadata) != _metadata(field.metadata): + return f"{field.name} has other field metadata than the stored column" + return None changed = appended_field_change( held.with_metadata(cast(Any, _metadata(held_metadata))), field.with_metadata(cast(Any, _metadata(field.metadata))), delta_log_storage=from_delta_log and ARROW_TYPE_KEY not in held_metadata, ) - if changed is not None or _is_logical(field) or _is_logical(held): + if changed is not None or logical: return changed return _evolution_change( arrow_utils.normalize_to_large_types(held.type, keep_null=True), diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index a02a5ce0c..2d764a5cc 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -181,15 +181,21 @@ def _child_change( ) -> str | None: 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 check_metadata: - incoming_metadata = metadata_bytes(incoming.metadata) - if delta_log_storage and metadata_only and _EXTENSION_NAME in incoming_metadata: - # The physical Delta schema omits these keys to prevent Arrow from - # decoding the extension. The identity check uses the raw log instead. - del incoming_metadata[_EXTENSION_NAME] - incoming_metadata.pop(_EXTENSION_METADATA, None) - if metadata_bytes(held.metadata) != incoming_metadata: - return f"{path} has other field metadata than the stored column" + held_metadata = metadata_bytes(held.metadata) + incoming_metadata = metadata_bytes(incoming.metadata) + storage_unknown = False + 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 field + # with only the annotation cannot establish the storage schema. + del metadata[_EXTENSION_NAME] + metadata.pop(_EXTENSION_METADATA, None) + storage_unknown |= not isinstance(field.type, pa.BaseExtensionType) + if check_metadata and held_metadata != incoming_metadata: + return f"{path} has other field metadata than the stored column" + if storage_unknown: + return None return _nested_change( held.type, incoming.type, diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index 820c4e428..c9fa0dacb 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -270,6 +270,21 @@ def __arrow_ext_deserialize__( 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) @@ -349,10 +364,7 @@ def __arrow_ext_serialize__(self) -> bytes: ) pa.register_extension_type(extension) # pyright: ignore[reportArgumentType] # Arrow accepts ExtensionType try: - sink = pa.BufferOutputStream() - with pa.ipc.new_stream(sink, first.schema) as writer: - writer.write_table(first) - decoded = pa.ipc.open_stream(sink.getvalue()).read_all() + 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) @@ -377,6 +389,107 @@ def __arrow_ext_serialize__(self) -> bytes: 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_appends_extension_storage_before_and_after_ipc( + tmp_path: Path, + skip_duplicates: bool, + round_trip: bool, + registered: bool, + shape: str, +) -> None: + """Delta accepts the same storage through native and IPC-decoded Arrow columns.""" + + 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" + 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 nested 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]) +@pytest.mark.parametrize("nested", [False, True], ids=["outer", "child"]) +def test_delta_appends_when_ipc_extension_storage_metadata_is_unknown( + tmp_path: Path, skip_duplicates: bool, nested: 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) + if nested: + child = pa.ExtensionArray.from_storage( + _NestedExtension(storage.type), storage + ) + storage = pa.StructArray.from_arrays([child], names=["child"]) + extension = _StructExtension(storage.type) + return pa.table( + {"id": [rid], "x": pa.ExtensionArray.from_storage(extension, storage)} + ) + + first = rows(b"a", "m") + outer = first.schema.field("x").type + assert isinstance(outer, _StructExtension) + if nested: + pa.register_extension_type(outer) # pyright: ignore[reportArgumentType] # Arrow accepts ExtensionType + try: + DeltaTableDatabase(tmp_path).add_records(PATH, first, flush=True) + incoming = _ipc_round_trip(rows(b"b", None)) + decoded = incoming.schema.field("x") + if nested: + assert isinstance(decoded.type, _StructExtension) + decoded = decoded.type.storage_type.field(0) + 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 + ) + finally: + if nested: + pa.unregister_extension_type(outer.extension_name) + 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]) @pytest.mark.parametrize("key", ["orcapod:arrow_type", "ARROW:extension:metadata"]) def test_delta_appends_identical_reserved_key_used_as_nested_metadata( From 2123aefff13f99e7cc889cc131d5b0192355482b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 07:59:50 -0800 Subject: [PATCH 06/19] fix(delta): compare duplicate IDs using Arrow storage values --- docs/dev/design_issues/ITL-1386-WK1.md | 2 + src/orcapod/databases/delta_lake_databases.py | 41 +++++++-- tests/test_databases/test_write_conflicts.py | 88 +++++++++++++++++++ 3 files changed, 122 insertions(+), 9 deletions(-) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index b5a306b6d..59854e73d 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -12,3 +12,5 @@ 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. 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. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index bbbd803ed..ac65cf124 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2326,8 +2326,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( @@ -3004,7 +3003,8 @@ def _filter_existing_records( self, record_path: tuple[str, ...], table: pa.Table ) -> pa.Table: """Filter out records that already exist (for skip_duplicates=True).""" - input_ids = set(table[self.RECORD_ID_COLUMN].to_pylist()) + ids = self._id_storage(table) + input_ids = set(ids.to_pylist()) record_key = self._get_record_key(record_path) # Get IDs that already exist in pending batch or Delta table @@ -3027,9 +3027,7 @@ def _filter_existing_records( return table # No duplicates found # Filter out existing records - mask = pc.invert( - pc.is_in(table[self.RECORD_ID_COLUMN], pa.array(list(all_existing))) - ) + mask = pc.invert(pc.is_in(ids, pa.array(list(all_existing)))) filtered = table.filter(mask) logger.debug(f"Skipped {len(all_existing)} duplicate records") @@ -3039,7 +3037,7 @@ 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_storage(table).to_pylist()) record_key = self._get_record_key(record_path) pending_conflicts = input_ids.intersection( self._pending_record_ids.get(record_key, ()) @@ -3175,7 +3173,7 @@ def _add_to_pending_batch(self, record_path: tuple[str, ...], table: pa.Table): if index is not None and index.table is pending_batch: index.append(table, grown) - pending_ids = cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist()) + pending_ids = cast(list[bytes], self._id_storage(table).to_pylist()) self._pending_record_ids[record_key].update(pending_ids) def _should_auto_flush(self, record_path: tuple[str, ...]) -> bool: @@ -4072,12 +4070,37 @@ def _rows_with_ids( positions = {p for r in set(record_ids) for p in id_index.get(r, ())} return rows_at(rows.table, sorted(positions)) + @classmethod + 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 + @classmethod def _non_null_ids(cls, table: pa.Table) -> set[bytes]: """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_storage(table).to_pylist() if record_id is not None } diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 8bb0ce1e2..ceed4b6de 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -1,10 +1,13 @@ """Write conflicts are checked when rows are added (ITL-1386, ITL-1487).""" +from enum import Enum from pathlib import Path from sqlite3 import IntegrityError +from typing import Any, cast import pyarrow as pa import pytest +from typing_extensions import override from orcapod.databases import ( ConnectorArrowDatabase, @@ -17,6 +20,91 @@ 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): + def __init__(self) -> None: + super().__init__(pa.int64(), "orcapod.tests.write_conflicts.record_key") + + @override + def __arrow_ext_serialize__(self) -> bytes: + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_RecordKeyType": + return cls() + + @override + def __arrow_ext_scalar_class__(self) -> type[_RecordKeyScalar]: + 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) + + @pytest.mark.parametrize("backend", ["delta", "memory", "sqlite", "connector"]) def test_add_refuses_stored_id_without_buffering_other_rows( tmp_path: Path, backend: str From 3db039f471401b57045c637a61a9b55b59d52504 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 08:56:37 -0800 Subject: [PATCH 07/19] fix(delta): compare composite extension record IDs --- docs/dev/design_issues/ITL-1386-WK1.md | 2 +- src/orcapod/databases/delta_lake_databases.py | 103 +++++++++++++++--- tests/test_databases/test_write_conflicts.py | 91 ++++++++++++++++ 3 files changed, 179 insertions(+), 17 deletions(-) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index 59854e73d..1cfd9d496 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -13,4 +13,4 @@ that was already in the pending batch. entire add if any conflict. The write-if-missing option still skips duplicates. 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. +handle and reopened handles, including extension IDs stored as lists or structs. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index ac65cf124..627c53bde 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -8,7 +8,7 @@ import time import uuid from collections import defaultdict -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Hashable, Iterator, Mapping, Sequence from contextlib import AbstractContextManager from dataclasses import dataclass from pathlib import Path @@ -1728,6 +1728,52 @@ 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") + + +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.Date64Scalar, + pa.Time32Scalar, + pa.Time64Scalar, + pa.TimestampScalar, + 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). @@ -1759,7 +1805,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 @@ -1798,7 +1844,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, @@ -1849,7 +1895,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] = ( @@ -1865,7 +1911,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, ) ) @@ -2303,7 +2351,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: @@ -2364,7 +2412,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: @@ -3004,7 +3052,8 @@ def _filter_existing_records( ) -> pa.Table: """Filter out records that already exist (for skip_duplicates=True).""" ids = self._id_storage(table) - input_ids = set(ids.to_pylist()) + 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 @@ -3027,7 +3076,13 @@ def _filter_existing_records( return table # No duplicates found # Filter out existing records - mask = pc.invert(pc.is_in(ids, 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_() + ) + 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") @@ -3037,7 +3092,7 @@ 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(self._id_storage(table).to_pylist()) + input_ids = set(self._id_keys(self._id_storage(table))) record_key = self._get_record_key(record_path) pending_conflicts = input_ids.intersection( self._pending_record_ids.get(record_key, ()) @@ -3173,7 +3228,7 @@ def _add_to_pending_batch(self, record_path: tuple[str, ...], table: pa.Table): if index is not None and index.table is pending_batch: index.append(table, grown) - pending_ids = cast(list[bytes], self._id_storage(table).to_pylist()) + pending_ids = self._id_keys(self._id_storage(table)) self._pending_record_ids[record_key].update(pending_ids) def _should_auto_flush(self, record_path: tuple[str, ...]) -> bool: @@ -3227,7 +3282,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_())) @@ -3885,7 +3940,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 @@ -4095,12 +4150,28 @@ def _id_storage(cls, table: pa.Table) -> pa.ChunkedArray[Any]: else: return ids + @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): + return ids.to_pylist() + # 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 _non_null_ids(cls, table: pa.Table) -> set[bytes]: + 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 cls._id_storage(table).to_pylist() + for record_id in cls._id_keys(cls._id_storage(table)) if record_id is not None } @@ -4149,7 +4220,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/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index ceed4b6de..221d62bab 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -105,6 +105,97 @@ def rows( 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): + 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: + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_CompositeKeyType": + # Delta may expose different list offsets or item names on disk. + 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]: + return _CompositeKeyScalar + + +@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 From bb141c75b16617a075438f27f278f06b49464561 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:53:07 -0800 Subject: [PATCH 08/19] fix(delta): preserve typed record IDs during duplicate checks --- changelog.d/ITL-1386.md | 2 + docs/dev/design_issues/ITL-1386-WK1.md | 3 + src/orcapod/databases/delta_lake_databases.py | 107 ++++++- tests/test_databases/test_write_conflicts.py | 295 ++++++++++++++++++ 4 files changed, 399 insertions(+), 8 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index cbfe552f7..80758dd42 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -8,6 +8,8 @@ ### Fixed +- Delta accepts extension-backed record IDs outside Python's date range and + skips late duplicate list and struct IDs when flushing. (ITL-1386) - Appends reject mismatches in known field metadata inside Arrow extension storage. Delta accepts IPC-decoded columns and children whose extensions are unregistered when the existing append checks pass. (ITL-1415) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index 1cfd9d496..68d4604b7 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -14,3 +14,6 @@ entire add if any conflict. The write-if-missing option still skips duplicates. 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. +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/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 627c53bde..07f725820 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1739,6 +1739,25 @@ def __repr__(self) -> str: 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: @@ -1756,6 +1775,8 @@ def _composite_id_value(scalar: pa.Scalar[Any] | None) -> object: 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, ( @@ -3080,6 +3101,26 @@ def _filter_existing_records( 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))) @@ -3097,6 +3138,13 @@ def _check_all_conflicts( 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"Records with IDs {pending_conflicts} already exist in the pending " @@ -3119,6 +3167,12 @@ def _check_all_conflicts( 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"Records with IDs {delta_conflicts} already exist in the stored " @@ -4070,13 +4124,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). New tables exclude the id column from file statistics - # (ITL-1444), 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 @@ -4154,7 +4207,13 @@ def _id_storage(cls, table: pa.Table) -> pa.ChunkedArray[Any]: 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): - return ids.to_pylist() + 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. @@ -4166,6 +4225,38 @@ def _id_keys(ids: pa.ChunkedArray[Any]) -> Sequence[Hashable]: 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.""" diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 221d62bab..e457d0bd0 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -1,5 +1,7 @@ """Write conflicts are checked when rows are added (ITL-1386, ITL-1487).""" +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal from enum import Enum from pathlib import Path from sqlite3 import IntegrityError @@ -141,6 +143,299 @@ def __arrow_ext_scalar_class__(self) -> type[_CompositeKeyScalar]: 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): + def __init__(self) -> None: + super().__init__(pa.date32(), "orcapod.tests.write_conflicts.ordinal_date") + + @override + def __arrow_ext_serialize__(self) -> bytes: + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_OrdinalDateType": + return cls() + + @override + def __arrow_ext_scalar_class__(self) -> type[_OrdinalDateScalar]: + return _OrdinalDateScalar + + +class _NativeIdType(pa.ExtensionType): + 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: + return b"" + + @classmethod + @override + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "_NativeIdType": + 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("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"] ) From 296f2912198e162cde65c486fe86ffada5f1d835 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 11:38:12 -0800 Subject: [PATCH 09/19] fix(databases): honor stored struct IDs and known IPC metadata --- changelog.d/ITL-1386.md | 2 + docs/dev/design_issues/ITL-1386-WK1.md | 2 + docs/dev/design_issues/ITL-1415-WK3.md | 7 +-- src/orcapod/databases/delta_lake_databases.py | 23 ++++++---- src/orcapod/databases/utils.py | 33 +++++++++++--- .../test_appended_field_attributes.py | 43 +++++++++++++++++++ tests/test_databases/test_write_conflicts.py | 25 +++++++++++ 7 files changed, 116 insertions(+), 19 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index 80758dd42..dc7efd1b1 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -10,6 +10,8 @@ - Delta accepts extension-backed record IDs outside Python's date range and skips late duplicate list and struct IDs when flushing. (ITL-1386) +- Delta strict writes detect a stored struct ID even when the append omits a + nullable ID field whose stored value is null. (ITL-1386) - Appends reject mismatches in known field metadata inside Arrow extension storage. Delta accepts IPC-decoded columns and children whose extensions are unregistered when the existing append checks pass. (ITL-1415) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index 68d4604b7..3b8a3bcd0 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -14,6 +14,8 @@ entire add if any conflict. The write-if-missing option still skips duplicates. 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. +For plain struct IDs, strict adds fill omitted nullable fields with nulls before +comparing against stored IDs, as the commit does. 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 index e926b5444..d5a66fced 100644 --- a/docs/dev/design_issues/ITL-1415-WK3.md +++ b/docs/dev/design_issues/ITL-1415-WK3.md @@ -14,9 +14,10 @@ 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 extension as storage with an Arrow annotation, -the comparison leaves that extension's storage attributes to the existing append -checks. This applies to both the column's extension and an extension nested inside -its storage. +the comparison refuses conflicting metadata explicitly present on corresponding +struct fields of both sides and treats missing attributes as unknown. This +applies to both the column's extension and an extension nested inside its +storage. 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. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 07f725820..3d6859a51 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -934,23 +934,18 @@ def _column_change( """ held_metadata = metadata_bytes(held.metadata) logical = _is_logical(field) or _is_logical(held) - if logical and ( + 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) ) - ): - # An annotated storage array does not supply the extension's storage - # schema. The physical log can supply struct metadata for a concrete - # incoming extension when it has the stored extension annotation. - if _metadata(held_metadata) != _metadata(field.metadata): - return f"{field.name} has other field metadata than the stored column" - return None + ) changed = appended_field_change( held.with_metadata(cast(Any, _metadata(held_metadata))), field.with_metadata(cast(Any, _metadata(field.metadata))), 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 @@ -3160,7 +3155,17 @@ def _check_all_conflicts( if not stored_ids: return field = table.schema.field(self.RECORD_ID_COLUMN) - if not field.type.equals(written_field(field).type): + if pa.types.is_struct(field.type): + # The commit fills in omitted nullable fields before comparing IDs. + delta_table = self._get_delta_table(record_path) + assert delta_table is not None # stored_ids came from its snapshot + written = to_delta_layout(table.select([self.RECORD_ID_COLUMN])) + input_ids = self._non_null_ids( + _conformed_to_stored( + delta_table, written, self._get_table_uri(record_path) + ) + ) + elif 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( diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 2d764a5cc..4476ae823 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -136,6 +136,7 @@ def appended_field_change( 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). @@ -156,6 +157,9 @@ def appended_field_change( 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``. @@ -167,6 +171,8 @@ def appended_field_change( 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, ) @@ -177,31 +183,37 @@ def _child_change( *, metadata_only: bool, delta_log_storage: bool, + partial_metadata: bool, check_metadata: bool = True, ) -> str | None: if not metadata_only and held.name != incoming.name: return f"{path} is named {incoming.name!r}, the stored column's {held.name!r}" held_metadata = metadata_bytes(held.metadata) incoming_metadata = metadata_bytes(incoming.metadata) - storage_unknown = False + 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 field - # with only the annotation cannot establish the storage schema. + # 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) - storage_unknown |= not isinstance(field.type, pa.BaseExtensionType) + 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" - if storage_unknown: - return None return _nested_change( held.type, incoming.type, path, metadata_only=metadata_only, delta_log_storage=delta_log_storage, + partial_metadata=partial_child_storage, ) @@ -212,6 +224,7 @@ def _nested_change( *, 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"). @@ -232,13 +245,16 @@ def _nested_change( 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) + collection_metadata_known = not ( + metadata_only and (delta_log_storage or partial_metadata) + ) if t.is_map(held) and t.is_map(incoming): if not metadata_only and held.keys_sorted != incoming.keys_sorted: return ( @@ -251,6 +267,7 @@ def _nested_change( 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, @@ -258,6 +275,7 @@ def _nested_change( 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) @@ -269,6 +287,7 @@ def _nested_change( 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/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index c9fa0dacb..c25ffc139 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -445,6 +445,49 @@ def test_delta_appends_extension_storage_before_and_after_ipc( assert stored.sort_by("id")["id"].to_pylist() == [b"a", b"b"] +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("nested", [False, True], ids=["outer", "child"]) +def test_delta_refuses_known_struct_metadata_after_ipc( + tmp_path: Path, skip_duplicates: bool, nested: 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) + if nested: + child = pa.ExtensionArray.from_storage( + _NestedExtension(storage.type), storage + ) + storage = pa.StructArray.from_arrays([child], names=["child"]) + return pa.table( + { + "id": [rid], + "x": pa.ExtensionArray.from_storage( + _StructExtension(storage.type), storage + ), + } + ) + + first = _ipc_round_trip(rows(b"a", "m")) + if not nested: + # 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) + path = r"x\.child\.a" if nested else r"x\.a" + with pytest.raises(InputValidationError, match=rf"{path} 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]) @pytest.mark.parametrize("nested", [False, True], ids=["outer", "child"]) def test_delta_appends_when_ipc_extension_storage_metadata_is_unknown( diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index e457d0bd0..f6697ea27 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -555,6 +555,31 @@ def test_delta_add_sees_id_committed_since_its_last_read( a.add_record(PATH, b"x", pa.table({"v": [2]})) +def test_delta_strict_add_compares_struct_id_in_stored_layout(tmp_path: Path) -> None: + """Omitting a nullable ID field is equivalent to providing its stored null.""" + stored_type = pa.struct([("key", pa.int64()), ("extra", pa.int64())]) + incoming_type = pa.struct([("key", pa.int64())]) + writer = DeltaTableDatabase(tmp_path) + writer.add_records( + PATH, + pa.table({"id": pa.array([{"key": 1}], type=stored_type), "v": [1]}), + flush=True, + ) + reopened = DeltaTableDatabase(tmp_path) + with pytest.raises(ValueError, match="already exist.*stored"): + reopened.add_records( + PATH, pa.table({"id": pa.array([{"key": 1}], type=incoming_type), "v": [3]}) + ) + reopened.add_records( + PATH, + pa.table({"id": pa.array([{"key": 2}], type=incoming_type), "v": [4]}), + 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, 4] + + 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: From 4d0a81a425a52c04a21c297aa6782eb8d40e1e42 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:19:39 -0800 Subject: [PATCH 10/19] fix(delta): refuse mismatched nested record ID types --- changelog.d/ITL-1386.md | 4 +- docs/dev/design_issues/ITL-1386-WK1.md | 4 +- src/orcapod/databases/delta_lake_databases.py | 73 +++++++++++++--- tests/test_databases/test_write_conflicts.py | 83 +++++++++++++++---- 4 files changed, 134 insertions(+), 30 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index dc7efd1b1..2ade9b81f 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -10,8 +10,8 @@ - Delta accepts extension-backed record IDs outside Python's date range and skips late duplicate list and struct IDs when flushing. (ITL-1386) -- Delta strict writes detect a stored struct ID even when the append omits a - nullable ID field whose stored value is null. (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) - Appends reject mismatches in known field metadata inside Arrow extension storage. Delta accepts IPC-decoded columns and children whose extensions are unregistered when the existing append checks pass. (ITL-1415) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index 3b8a3bcd0..d6b91e3a3 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -14,8 +14,8 @@ entire add if any conflict. The write-if-missing option still skips duplicates. 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. -For plain struct IDs, strict adds fill omitted nullable fields with nulls before -comparing against stored IDs, as the commit does. +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/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 3d6859a51..05cf2b44d 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2973,6 +2973,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) @@ -3124,6 +3132,49 @@ def _filter_existing_records( logger.debug(f"Skipped {len(all_existing)} duplicate records") return filtered + 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: @@ -3155,17 +3206,7 @@ def _check_all_conflicts( if not stored_ids: return field = table.schema.field(self.RECORD_ID_COLUMN) - if pa.types.is_struct(field.type): - # The commit fills in omitted nullable fields before comparing IDs. - delta_table = self._get_delta_table(record_path) - assert delta_table is not None # stored_ids came from its snapshot - written = to_delta_layout(table.select([self.RECORD_ID_COLUMN])) - input_ids = self._non_null_ids( - _conformed_to_stored( - delta_table, written, self._get_table_uri(record_path) - ) - ) - elif not field.type.equals(written_field(field).type): + 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( @@ -4208,6 +4249,16 @@ def _id_storage(cls, table: pa.Table) -> pa.ChunkedArray[Any]: 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.""" diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index f6697ea27..1fad8ccee 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -1,5 +1,6 @@ """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 @@ -17,6 +18,7 @@ InMemoryArrowDatabase, SQLiteConnector, ) +from orcapod.errors import InputValidationError from tests.test_databases.test_connector_arrow_database import MockDBConnector PATH = ("records",) @@ -555,29 +557,80 @@ def test_delta_add_sees_id_committed_since_its_last_read( a.add_record(PATH, b"x", pa.table({"v": [2]})) -def test_delta_strict_add_compares_struct_id_in_stored_layout(tmp_path: Path) -> None: - """Omitting a nullable ID field is equivalent to providing its stored null.""" +@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())]) - writer = DeltaTableDatabase(tmp_path) - writer.add_records( - PATH, - pa.table({"id": pa.array([{"key": 1}], type=stored_type), "v": [1]}), - flush=True, + 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) - with pytest.raises(ValueError, match="already exist.*stored"): + 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, pa.table({"id": pa.array([{"key": 1}], type=incoming_type), "v": [3]}) + PATH, repeat, record_id_column="id", skip_duplicates=skip_duplicates ) - reopened.add_records( - PATH, - pa.table({"id": pa.array([{"key": 2}], type=incoming_type), "v": [4]}), - flush=True, - ) + # 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, 4] + assert stored.sort_by("v")["v"].to_pylist() == [1, 3] + + +@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: From 8c08ee15106f235baba1db9356056f00e504aa5d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:06:19 -0800 Subject: [PATCH 11/19] fix(sqlite): preserve replacement for separate unique constraints --- changelog.d/ITL-1386.md | 4 +- docs/dev/design_issues/ITL-1386-WK1.md | 1 + src/orcapod/databases/sqlite_connector.py | 5 ++- tests/test_databases/test_write_conflicts.py | 46 ++++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index 2ade9b81f..e497b5364 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -4,7 +4,9 @@ `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. (ITL-1386, ITL-1487) + 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 diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index d6b91e3a3..ed2737925 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -11,6 +11,7 @@ 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. +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. diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index a114905dd..fe6501293 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -651,7 +651,7 @@ def insert_store_records( skip_duplicates: bool, schema: str, ) -> None: - """Insert, preserving SQLite's existing write-if-missing behavior.""" + """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: @@ -660,6 +660,7 @@ def insert_store_records( table_name, records, schema, + policy=" OR REPLACE", conflict_clause=f" ON CONFLICT ({column}) DO NOTHING", ) @@ -669,7 +670,7 @@ def _insert_records( records: pa.Table, schema: str | None, *, - policy: str = "", + policy: str, conflict_clause: str = "", ) -> None: """Write a batch under the selected SQLite conflict policy.""" diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 1fad8ccee..052f68213 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -652,3 +652,49 @@ def test_strict_sqlite_insert_reports_a_constraint_error() -> None: ) 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 From 3c4bcddea667226b4a6a52a1bfde18510de11223 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 14:43:12 -0800 Subject: [PATCH 12/19] test(delta): verify persisted rows after a conflicting flush --- changelog.d/ITL-1386.md | 3 ++ tests/test_databases/test_write_conflicts.py | 31 ++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index e497b5364..a1b330d45 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -24,6 +24,9 @@ ### 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) - 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, diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 052f68213..981f768c4 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -38,11 +38,14 @@ def as_py(self, **kwargs: object) -> _RecordKey | None: 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 @@ -50,10 +53,12 @@ def __arrow_ext_serialize__(self) -> bytes: 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 @@ -121,11 +126,14 @@ def as_py(self, **kwargs: object) -> tuple[int, ...] | None: 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 @@ -133,7 +141,7 @@ def __arrow_ext_serialize__(self) -> bytes: def __arrow_ext_deserialize__( cls, storage_type: pa.DataType, serialized: bytes ) -> "_CompositeKeyType": - # Delta may expose different list offsets or item names on disk. + """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) @@ -142,6 +150,7 @@ def __arrow_ext_deserialize__( @override def __arrow_ext_scalar_class__(self) -> type[_CompositeKeyScalar]: + """Decode nested storage to a hashable tuple.""" return _CompositeKeyScalar @@ -154,11 +163,14 @@ def as_py(self, **kwargs: object) -> int | None: 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 @@ -166,19 +178,24 @@ def __arrow_ext_serialize__(self) -> bytes: 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 @@ -186,6 +203,7 @@ def __arrow_ext_serialize__(self) -> bytes: 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) @@ -535,10 +553,17 @@ def test_conflict_at_flush_keeps_first_commit( }[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() - stored = b.get_all_records(PATH) + reader = DeltaTableDatabase(tmp_path) if backend == "delta" else b + stored = reader.get_all_records(PATH) assert stored is not None - assert stored.to_pylist() == [{"v": 2}] + assert stored.sort_by("v").to_pylist() == ( + [{"v": 2}, {"v": 3}] if backend == "delta" else [{"v": 2}] + ) @pytest.mark.parametrize("initial", ["absent", "existing", "replaced"]) From 8c8b0738ba71baa25d9bca9979b9452a2648391b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:44:47 -0800 Subject: [PATCH 13/19] fix(delta): check persisted timestamp IDs after lossy writes --- changelog.d/ITL-1386.md | 3 ++ docs/dev/design_issues/ITL-1386-WK1.md | 2 ++ src/orcapod/databases/delta_lake_databases.py | 34 ++++++++++++++----- tests/test_databases/test_write_conflicts.py | 34 +++++++++++++++++++ 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index 27a34e28d..d737d2c79 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -27,6 +27,9 @@ - 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, diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index ed2737925..4ba5e61df 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -18,5 +18,7 @@ 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. +When Delta rounds an extension-backed timestamp ID at creation, the next +duplicate lookup reads the committed IDs instead of using the input values. 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/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index fc7db37af..bd421df3c 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -4237,7 +4237,7 @@ def _commit_once( table_uri: str, abs_path_components: tuple[str, ...], original_table: pa.Table, - ) -> tuple[deltalake.DeltaTable | None, _CommittedSnapshot, set[Hashable]]: + ) -> tuple[deltalake.DeltaTable | None, _CommittedSnapshot, set[Hashable] | None]: """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 @@ -4255,7 +4255,8 @@ def _commit_once( Returns: The table the rows were merged through (moved to the version it committed), or ``None`` for a table this attempt created; the snapshot - of the version the commit built on; and the non-null ids it inserted. + of the version the commit built on; and the non-null ids it inserted, + or ``None`` when they must be read from storage. Raises: _LostCommitRace: If another writer committed first; the caller loads @@ -4286,6 +4287,21 @@ def _commit_once( ) if delta_table is None: + inserted_ids = self._non_null_ids(combined_table) + id_type = self._id_storage_type( + combined_table.schema.field(self.RECORD_ID_COLUMN).type + ) + if pa.types.is_timestamp(id_type) and id_type.unit == "ns": + # Plain nanosecond timestamps have already become integer ticks. + # Delta writes native timestamps inside extensions at microsecond + # precision. A lossy cast requires a fresh scan of the written IDs. + try: + _ = pc.cast( + self._id_storage(combined_table), + pa.timestamp("us", tz=id_type.tz), + ) + except pa.ArrowInvalid: + inserted_ids = None # Tells this create's table from one another writer creates again at the # path before it is reloaded (``_CommittedSnapshot.create_token``). create_token = uuid.uuid4().hex @@ -4317,7 +4333,7 @@ def _commit_once( return ( None, _CommittedSnapshot(version=-1, ids=set(), create_token=create_token), - self._non_null_ids(combined_table), + inserted_ids, ) # The add-time check, against the version just loaded: another writer may @@ -4560,13 +4576,13 @@ def _extend_snapshot( self, base: _CommittedSnapshot, committed: deltalake.DeltaTable, - inserted_ids: set[Hashable], + inserted_ids: set[Hashable] | None, ) -> _CommittedSnapshot: """Return the snapshot of ``committed``, built from ``base`` plus this commit. When ``committed`` is the version right after ``base`` (no other writer - committed in between), its ids are ``base``'s plus the inserted ones, and - its rows, if ``base`` has them, are ``base``'s plus the rows of the data + committed in between), its ids are ``base``'s plus any known inserted ids. + Its rows, if ``base`` has them, are ``base``'s plus the rows of the data files the commit added, read as ``get_all_records`` reads them. Only those files are read, with the format and filesystem of the dataset ``base``'s rows came from (ITL-1173); a partitioned table, whose partition values are @@ -4577,7 +4593,8 @@ def _extend_snapshot( Args: base: The snapshot of the version the commit built on. committed: The table reloaded after the commit. - inserted_ids: The non-null record ids the commit inserted. + inserted_ids: The non-null record ids the commit inserted, or ``None`` + when the committed ids must be read from storage. Returns: The new snapshot. @@ -4596,7 +4613,8 @@ def _extend_snapshot( if version != base.version + 1 or not same_table: return _CommittedSnapshot(version, table_id) assert base.ids is not None - snapshot = _CommittedSnapshot(version, table_id, ids=base.ids | inserted_ids) + ids = None if inserted_ids is None else base.ids | inserted_ids + snapshot = _CommittedSnapshot(version, table_id, ids=ids) if ( base.rows is None or base.dataset_schema is None diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 981f768c4..ab2ca56e4 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -366,6 +366,40 @@ def test_delta_skip_pending_timestamp_extension_id_preserves_nanoseconds( pa.unregister_extension_type(extension.extension_name) +@pytest.mark.parametrize("tick", [1001, -1001]) +def test_delta_strict_add_rejects_persisted_timestamp_extension_id( + tmp_path: Path, tick: int +) -> None: + """The writer and a fresh handle both recognize the ID read from storage.""" + extension = _NativeIdType(pa.timestamp("ns")) + ids = pa.ExtensionArray.from_storage( + extension, pa.array([tick], type=extension.storage_type) + ) + first = pa.table( + {"id": ids, "tag_a": ["a"], "tag_b": ["b"], "v": ["first"], "w": [1]} + ) + pa.register_extension_type(cast(Any, extension)) + try: + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, first, flush=True) + reopened = DeltaTableDatabase(tmp_path) + persisted = reopened.get_all_records(PATH, record_id_column="id") + assert persisted is not None + assert persisted["id"].type == _NativeIdType(pa.timestamp("us")) + repeat = persisted.set_column(3, "v", pa.array(["repeat"])) + for db in (reopened, writer): + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records(PATH, repeat) + writer.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records( + PATH, record_id_column="id" + ) + assert stored is not None + assert stored.equals(persisted) + finally: + pa.unregister_extension_type(extension.extension_name) + + @pytest.mark.parametrize("skip_duplicates", [False, True]) @pytest.mark.parametrize("handle", ["pending", "writer", "reopened"]) def test_delta_date_extension_id_outside_python_date_range( From e9122fd8a6d03d7a2a39a846c8d5beb7084a66c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 21:34:45 -0800 Subject: [PATCH 14/19] fix(delta): refresh IDs after native temporal conversions --- changelog.d/ITL-1386.md | 3 + docs/dev/design_issues/ITL-1386-WK1.md | 5 +- src/orcapod/databases/delta_lake_databases.py | 40 +++--- tests/test_databases/test_write_conflicts.py | 116 +++++++++++++++--- 4 files changed, 132 insertions(+), 32 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index d737d2c79..7c934da87 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -14,6 +14,9 @@ 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 against the committed IDs after creating a table with + extension-backed timestamps or dates that change representation on write, + including inside lists and structs. (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) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index 4ba5e61df..6b2133f8c 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -18,7 +18,8 @@ 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. -When Delta rounds an extension-backed timestamp ID at creation, the next -duplicate lookup reads the committed IDs instead of using the input values. +When Delta can change a native timestamp or date key at any depth during +creation, the next duplicate lookup reads the committed IDs. The writer seeds +the cache directly for integer and string IDs. 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/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index bd421df3c..351769360 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1865,6 +1865,25 @@ def _primitive_id_value(scalar: pa.Scalar[Any]) -> Hashable: return _ArrowIdKey(scalar) +def _delta_changes_id_keys(arrow_type: pa.DataType) -> bool: + """Whether Delta's native temporal conversions can change an ID key.""" + if isinstance(arrow_type, pa.BaseExtensionType): + return _delta_changes_id_keys(arrow_type.storage_type) + if pa.types.is_dictionary(arrow_type): + return _delta_changes_id_keys(arrow_type.value_type) + if pa.types.is_timestamp(arrow_type): + # Even exact conversions can change the integer ticks used by nested keys. + return arrow_type.unit != "us" or arrow_type.tz not in (None, "UTC") + if pa.types.is_date64(arrow_type): + # Delta's Arrow schema maps native dates to day counts. + return True + # Struct fields, list items, and the key and value of a map's entries struct. + return any( + _delta_changes_id_keys(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + 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: @@ -4287,21 +4306,14 @@ def _commit_once( ) if delta_table is None: - inserted_ids = self._non_null_ids(combined_table) - id_type = self._id_storage_type( - combined_table.schema.field(self.RECORD_ID_COLUMN).type + # Use the written layout: plain nanosecond timestamps and dates + # requiring a type record have already become integer ticks. + id_type = combined_table.schema.field(self.RECORD_ID_COLUMN).type + inserted_ids = ( + None + if _delta_changes_id_keys(id_type) + else self._non_null_ids(combined_table) ) - if pa.types.is_timestamp(id_type) and id_type.unit == "ns": - # Plain nanosecond timestamps have already become integer ticks. - # Delta writes native timestamps inside extensions at microsecond - # precision. A lossy cast requires a fresh scan of the written IDs. - try: - _ = pc.cast( - self._id_storage(combined_table), - pa.timestamp("us", tz=id_type.tz), - ) - except pa.ArrowInvalid: - inserted_ids = None # Tells this create's table from one another writer creates again at the # path before it is reloaded (``_CommittedSnapshot.create_token``). create_token = uuid.uuid4().hex diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index ab2ca56e4..443273434 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -6,7 +6,7 @@ from enum import Enum from pathlib import Path from sqlite3 import IntegrityError -from typing import Any, cast +from typing import Any, Literal, cast import pyarrow as pa import pytest @@ -207,6 +207,15 @@ def __arrow_ext_deserialize__( return cls(storage_type) +class _NativeCompositeIdType(_NativeIdType): + """Expose a hashable tuple while retaining the supplied storage type.""" + + @override + def __arrow_ext_scalar_class__(self) -> type[_CompositeKeyScalar]: + """Decode nested storage to a hashable tuple.""" + return _CompositeKeyScalar + + _PRIMITIVE_IDS = [ pytest.param(pa.bool_(), True, id="bool"), *[ @@ -366,18 +375,56 @@ def test_delta_skip_pending_timestamp_extension_id_preserves_nanoseconds( pa.unregister_extension_type(extension.extension_name) -@pytest.mark.parametrize("tick", [1001, -1001]) -def test_delta_strict_add_rejects_persisted_timestamp_extension_id( - tmp_path: Path, tick: int +@pytest.mark.parametrize("handle", ["writer", "reopened"]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("layout", ["root", "struct", "list"]) +@pytest.mark.parametrize( + ("unit", "tick", "stored_tick", "tz"), + [ + ("ns", 1001, 1, None), + ("ns", -1001, -1, "America/New_York"), + ("ns", 1000, 1, None), + ("ms", 1, 1000, None), + ("s", 1, 1_000_000, None), + ], +) +def test_delta_duplicate_policy_for_persisted_timestamp_extension_id( + tmp_path: Path, + handle: str, + skip_duplicates: bool, + layout: str, + unit: Literal["s", "ms", "ns"], + tick: int, + stored_tick: int, + tz: str | None, ) -> None: - """The writer and a fresh handle both recognize the ID read from storage.""" - extension = _NativeIdType(pa.timestamp("ns")) - ids = pa.ExtensionArray.from_storage( - extension, pa.array([tick], type=extension.storage_type) - ) - first = pa.table( - {"id": ids, "tag_a": ["a"], "tag_b": ["b"], "v": ["first"], "w": [1]} + """Both handles recognize the committed ID and still write a distinct ID.""" + + def extension_for(timestamp: pa.DataType) -> _NativeIdType: + """Wrap the timestamp in the layout under test.""" + if layout == "struct": + return _NativeCompositeIdType(pa.struct([("ts", timestamp)])) + if layout == "list": + return _NativeCompositeIdType(pa.large_list(timestamp)) + return _NativeIdType(timestamp) + + def ids_at(ext: pa.ExtensionType, value: int) -> "pa.ExtensionArray[Any]": + """Build an ID with the given physical timestamp tick.""" + item = ( + {"ts": value} + if layout == "struct" + else [value] + if layout == "list" + else value + ) + return pa.ExtensionArray.from_storage( + ext, pa.array([item], type=ext.storage_type) + ) + + extension = extension_for( + pa.timestamp(unit) if tz is None else pa.timestamp(unit, tz) ) + first = pa.table({"id": ids_at(extension, tick), "v": ["first"]}) pa.register_extension_type(cast(Any, extension)) try: writer = DeltaTableDatabase(tmp_path) @@ -385,17 +432,54 @@ def test_delta_strict_add_rejects_persisted_timestamp_extension_id( reopened = DeltaTableDatabase(tmp_path) persisted = reopened.get_all_records(PATH, record_id_column="id") assert persisted is not None - assert persisted["id"].type == _NativeIdType(pa.timestamp("us")) - repeat = persisted.set_column(3, "v", pa.array(["repeat"])) - for db in (reopened, writer): + held_type = persisted["id"].type + assert isinstance(held_type, pa.ExtensionType) + held_timestamp = pa.timestamp("us") if tz is None else pa.timestamp("us", "UTC") + assert held_type == extension_for(held_timestamp) + assert persisted["id"].equals( + pa.chunked_array([ids_at(held_type, stored_tick)]) + ) + + db = reopened if handle == "reopened" else writer + repeat = persisted.set_column(1, "v", pa.array(["repeat"])) + if not skip_duplicates: with pytest.raises(ValueError, match="already exist.*stored"): db.add_records(PATH, repeat) - writer.flush() + distinct = pa.table({"id": ids_at(held_type, tick), "v": ["distinct"]}) + db.add_records(PATH, distinct, skip_duplicates=skip_duplicates, flush=True) + if skip_duplicates: + db.add_records(PATH, repeat, skip_duplicates=True, flush=True) stored = DeltaTableDatabase(tmp_path).get_all_records( PATH, record_id_column="id" ) assert stored is not None - assert stored.equals(persisted) + assert stored.num_rows == 2 + assert set(stored["v"].to_pylist()) == {"distinct", "first"} + finally: + pa.unregister_extension_type(extension.extension_name) + + +def test_delta_strict_add_rejects_persisted_nested_date_extension_id( + tmp_path: Path, +) -> None: + """A nested date written as milliseconds is compared as committed days.""" + extension = _NativeCompositeIdType(pa.struct([("day", pa.date64())])) + storage = pa.array([{"day": 86_400_001}], type=extension.storage_type) + first = pa.table( + {"id": pa.ExtensionArray.from_storage(extension, storage), "v": [1]} + ) + pa.register_extension_type(cast(Any, extension)) + try: + writer = DeltaTableDatabase(tmp_path) + writer.add_records(PATH, first, flush=True) + reopened = DeltaTableDatabase(tmp_path) + persisted = reopened.get_all_records(PATH, record_id_column="id") + assert persisted is not None + assert persisted["id"].type == _NativeCompositeIdType( + pa.struct([("day", pa.date32())]) + ) + with pytest.raises(ValueError, match="already exist.*stored"): + writer.add_records(PATH, persisted) finally: pa.unregister_extension_type(extension.extension_name) From db437787f5e84943336bd138080f968d36d31bf4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:19:34 -0800 Subject: [PATCH 15/19] fix(delta): restore reviewed ID cache behavior --- changelog.d/ITL-1386.md | 3 - docs/dev/design_issues/ITL-1386-WK1.md | 3 - src/orcapod/databases/delta_lake_databases.py | 46 ++---- tests/test_databases/test_write_conflicts.py | 134 +++++------------- 4 files changed, 43 insertions(+), 143 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index 7c934da87..d737d2c79 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -14,9 +14,6 @@ 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 against the committed IDs after creating a table with - extension-backed timestamps or dates that change representation on write, - including inside lists and structs. (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) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index 6b2133f8c..ed2737925 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -18,8 +18,5 @@ 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. -When Delta can change a native timestamp or date key at any depth during -creation, the next duplicate lookup reads the committed IDs. The writer seeds -the cache directly for integer and string IDs. 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/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 351769360..fc7db37af 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1865,25 +1865,6 @@ def _primitive_id_value(scalar: pa.Scalar[Any]) -> Hashable: return _ArrowIdKey(scalar) -def _delta_changes_id_keys(arrow_type: pa.DataType) -> bool: - """Whether Delta's native temporal conversions can change an ID key.""" - if isinstance(arrow_type, pa.BaseExtensionType): - return _delta_changes_id_keys(arrow_type.storage_type) - if pa.types.is_dictionary(arrow_type): - return _delta_changes_id_keys(arrow_type.value_type) - if pa.types.is_timestamp(arrow_type): - # Even exact conversions can change the integer ticks used by nested keys. - return arrow_type.unit != "us" or arrow_type.tz not in (None, "UTC") - if pa.types.is_date64(arrow_type): - # Delta's Arrow schema maps native dates to day counts. - return True - # Struct fields, list items, and the key and value of a map's entries struct. - return any( - _delta_changes_id_keys(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) - ) - - 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: @@ -4256,7 +4237,7 @@ def _commit_once( table_uri: str, abs_path_components: tuple[str, ...], original_table: pa.Table, - ) -> tuple[deltalake.DeltaTable | None, _CommittedSnapshot, set[Hashable] | None]: + ) -> 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 @@ -4274,8 +4255,7 @@ def _commit_once( Returns: The table the rows were merged through (moved to the version it committed), or ``None`` for a table this attempt created; the snapshot - of the version the commit built on; and the non-null ids it inserted, - or ``None`` when they must be read from storage. + of the version the commit built on; and the non-null ids it inserted. Raises: _LostCommitRace: If another writer committed first; the caller loads @@ -4306,14 +4286,6 @@ def _commit_once( ) if delta_table is None: - # Use the written layout: plain nanosecond timestamps and dates - # requiring a type record have already become integer ticks. - id_type = combined_table.schema.field(self.RECORD_ID_COLUMN).type - inserted_ids = ( - None - if _delta_changes_id_keys(id_type) - else self._non_null_ids(combined_table) - ) # Tells this create's table from one another writer creates again at the # path before it is reloaded (``_CommittedSnapshot.create_token``). create_token = uuid.uuid4().hex @@ -4345,7 +4317,7 @@ def _commit_once( return ( None, _CommittedSnapshot(version=-1, ids=set(), create_token=create_token), - inserted_ids, + self._non_null_ids(combined_table), ) # The add-time check, against the version just loaded: another writer may @@ -4588,13 +4560,13 @@ def _extend_snapshot( self, base: _CommittedSnapshot, committed: deltalake.DeltaTable, - inserted_ids: set[Hashable] | None, + inserted_ids: set[Hashable], ) -> _CommittedSnapshot: """Return the snapshot of ``committed``, built from ``base`` plus this commit. When ``committed`` is the version right after ``base`` (no other writer - committed in between), its ids are ``base``'s plus any known inserted ids. - Its rows, if ``base`` has them, are ``base``'s plus the rows of the data + committed in between), its ids are ``base``'s plus the inserted ones, and + its rows, if ``base`` has them, are ``base``'s plus the rows of the data files the commit added, read as ``get_all_records`` reads them. Only those files are read, with the format and filesystem of the dataset ``base``'s rows came from (ITL-1173); a partitioned table, whose partition values are @@ -4605,8 +4577,7 @@ def _extend_snapshot( Args: base: The snapshot of the version the commit built on. committed: The table reloaded after the commit. - inserted_ids: The non-null record ids the commit inserted, or ``None`` - when the committed ids must be read from storage. + inserted_ids: The non-null record ids the commit inserted. Returns: The new snapshot. @@ -4625,8 +4596,7 @@ def _extend_snapshot( if version != base.version + 1 or not same_table: return _CommittedSnapshot(version, table_id) assert base.ids is not None - ids = None if inserted_ids is None else base.ids | inserted_ids - snapshot = _CommittedSnapshot(version, table_id, ids=ids) + snapshot = _CommittedSnapshot(version, table_id, ids=base.ids | inserted_ids) if ( base.rows is None or base.dataset_schema is None diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 443273434..56fe093af 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -6,7 +6,7 @@ from enum import Enum from pathlib import Path from sqlite3 import IntegrityError -from typing import Any, Literal, cast +from typing import Any, cast import pyarrow as pa import pytest @@ -207,15 +207,6 @@ def __arrow_ext_deserialize__( return cls(storage_type) -class _NativeCompositeIdType(_NativeIdType): - """Expose a hashable tuple while retaining the supplied storage type.""" - - @override - def __arrow_ext_scalar_class__(self) -> type[_CompositeKeyScalar]: - """Decode nested storage to a hashable tuple.""" - return _CompositeKeyScalar - - _PRIMITIVE_IDS = [ pytest.param(pa.bool_(), True, id="bool"), *[ @@ -375,111 +366,56 @@ def test_delta_skip_pending_timestamp_extension_id_preserves_nanoseconds( pa.unregister_extension_type(extension.extension_name) -@pytest.mark.parametrize("handle", ["writer", "reopened"]) -@pytest.mark.parametrize("skip_duplicates", [False, True]) -@pytest.mark.parametrize("layout", ["root", "struct", "list"]) @pytest.mark.parametrize( - ("unit", "tick", "stored_tick", "tz"), - [ - ("ns", 1001, 1, None), - ("ns", -1001, -1, "America/New_York"), - ("ns", 1000, 1, None), - ("ms", 1, 1000, None), - ("s", 1, 1_000_000, None), - ], + ("tick", "stored_tick", "tz"), + [(1001, 1, None), (-1001, -1, "America/New_York")], ) -def test_delta_duplicate_policy_for_persisted_timestamp_extension_id( +def test_delta_writer_skips_persisted_lossy_root_timestamp_extension_id( tmp_path: Path, - handle: str, - skip_duplicates: bool, - layout: str, - unit: Literal["s", "ms", "ns"], tick: int, stored_tick: int, tz: str | None, ) -> None: - """Both handles recognize the committed ID and still write a distinct ID.""" - - def extension_for(timestamp: pa.DataType) -> _NativeIdType: - """Wrap the timestamp in the layout under test.""" - if layout == "struct": - return _NativeCompositeIdType(pa.struct([("ts", timestamp)])) - if layout == "list": - return _NativeCompositeIdType(pa.large_list(timestamp)) - return _NativeIdType(timestamp) - - def ids_at(ext: pa.ExtensionType, value: int) -> "pa.ExtensionArray[Any]": - """Build an ID with the given physical timestamp tick.""" - item = ( - {"ts": value} - if layout == "struct" - else [value] - if layout == "list" - else value - ) - return pa.ExtensionArray.from_storage( - ext, pa.array([item], type=ext.storage_type) - ) - - extension = extension_for( - pa.timestamp(unit) if tz is None else pa.timestamp(unit, tz) - ) - first = pa.table({"id": ids_at(extension, tick), "v": ["first"]}) + """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, first, flush=True) - reopened = DeltaTableDatabase(tmp_path) - persisted = reopened.get_all_records(PATH, record_id_column="id") + 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_type = persisted["id"].type - assert isinstance(held_type, pa.ExtensionType) held_timestamp = pa.timestamp("us") if tz is None else pa.timestamp("us", "UTC") - assert held_type == extension_for(held_timestamp) - assert persisted["id"].equals( - pa.chunked_array([ids_at(held_type, stored_tick)]) + 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])) - db = reopened if handle == "reopened" else writer - repeat = persisted.set_column(1, "v", pa.array(["repeat"])) - if not skip_duplicates: - with pytest.raises(ValueError, match="already exist.*stored"): - db.add_records(PATH, repeat) - distinct = pa.table({"id": ids_at(held_type, tick), "v": ["distinct"]}) - db.add_records(PATH, distinct, skip_duplicates=skip_duplicates, flush=True) - if skip_duplicates: - db.add_records(PATH, repeat, skip_duplicates=True, flush=True) - stored = DeltaTableDatabase(tmp_path).get_all_records( - PATH, record_id_column="id" + distinct = pa.ExtensionArray.from_storage( + held_type, pa.array([tick], type=held_timestamp) ) - 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) - - -def test_delta_strict_add_rejects_persisted_nested_date_extension_id( - tmp_path: Path, -) -> None: - """A nested date written as milliseconds is compared as committed days.""" - extension = _NativeCompositeIdType(pa.struct([("day", pa.date64())])) - storage = pa.array([{"day": 86_400_001}], type=extension.storage_type) - first = pa.table( - {"id": pa.ExtensionArray.from_storage(extension, storage), "v": [1]} - ) - pa.register_extension_type(cast(Any, extension)) - try: - writer = DeltaTableDatabase(tmp_path) - writer.add_records(PATH, first, flush=True) - reopened = DeltaTableDatabase(tmp_path) - persisted = reopened.get_all_records(PATH, record_id_column="id") - assert persisted is not None - assert persisted["id"].type == _NativeCompositeIdType( - pa.struct([("day", pa.date32())]) + writer.add_records( + PATH, + pa.table({"id": distinct, "v": ["distinct"]}), + skip_duplicates=True, + flush=True, ) - with pytest.raises(ValueError, match="already exist.*stored"): - writer.add_records(PATH, persisted) + 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 sorted(stored["v"].to_pylist()) == ["distinct", "first"] finally: pa.unregister_extension_type(extension.extension_name) From 597bbbf303b4a55d91135ac9f872b18fc075d1f2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:22:09 -0800 Subject: [PATCH 16/19] fix(delta): compare nested timestamp IDs in one unit --- changelog.d/ITL-1386.md | 2 + src/orcapod/databases/delta_lake_databases.py | 14 ++++++- tests/test_databases/test_write_conflicts.py | 39 ++++++++++++++++++- 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index d737d2c79..e39efe709 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -14,6 +14,8 @@ 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) - 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) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index fc7db37af..7855a5d34 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1884,13 +1884,25 @@ def _composite_id_value(scalar: pa.Scalar[Any] | None) -> object: 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.TimestampScalar, pa.DurationScalar, ), ): diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 56fe093af..1325f3796 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -6,7 +6,7 @@ from enum import Enum from pathlib import Path from sqlite3 import IntegrityError -from typing import Any, cast +from typing import Any, Literal, cast import pyarrow as pa import pytest @@ -415,11 +415,46 @@ def test_delta_writer_skips_persisted_lossy_root_timestamp_extension_id( ) stored = DeltaTableDatabase(tmp_path).get_all_records(PATH) assert stored is not None - assert sorted(stored["v"].to_pylist()) == ["distinct", "first"] + 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( From 1d3bcf92050bc99c12226f9beba50ddf97943419 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 00:25:22 -0800 Subject: [PATCH 17/19] fix(databases): tighten stored record ID checks --- changelog.d/ITL-1386.md | 3 + .../databases/connector_arrow_database.py | 19 ++++-- src/orcapod/databases/delta_lake_databases.py | 28 ++++++++ .../test_connector_arrow_database.py | 23 +++++++ tests/test_databases/test_write_conflicts.py | 68 ++++++++++++++++++- 5 files changed, 134 insertions(+), 7 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index e39efe709..e39abfc29 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -16,6 +16,9 @@ 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, and generic connectors read only IDs for that check. (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) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 5af9be281..5d1c55c3f 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -397,11 +397,15 @@ def _stored_conflicts( return self._sql_store.existing_store_ids( name, column, input_ids, schema=schema ) - query = f"SELECT * FROM {sql_table_identifier(name, schema)}" - conflicts: set[bytes] = set() + query = ( + f"SELECT {sql_table_identifier(column)} FROM " + f"{sql_table_identifier(name, schema)}" + ) for batch in self._connector.iter_batches(query): - conflicts.update(input_ids.intersection(batch[column].to_pylist())) - return conflicts + conflicts = input_ids.intersection(batch[column].to_pylist()) + if conflicts: + return conflicts + return set() def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. @@ -717,7 +721,12 @@ def add_records( table_name, full_path, schema=None ) if committed_table is not None: - conflicts = self._stored_conflicts(committed_table, input_ids) + 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 " diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index e67779ddc..b8fbf5679 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -3321,6 +3321,14 @@ 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) @@ -3361,6 +3369,26 @@ def _filter_existing_records( logger.debug(f"Skipped {len(all_existing)} duplicate records") 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: diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 5fdb3934a..e7d5da7de 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -516,6 +516,29 @@ def test_add_records_raises_if_record_id_type_is_not_binary(self, db): # =========================================================================== +def test_strict_append_reads_only_ids_until_first_conflict( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Use a projected query and stop streaming when the add must be refused.""" + connector = MockDBConnector() + db = ConnectorArrowDatabase(connector) + path = ("records",) + db.add_record(path, b"first", pa.table({"payload": ["stored"]}), flush=True) + + batches_read = [] + + def iter_batches(query: str) -> Iterator[pa.RecordBatch]: + assert query == 'SELECT "__record_id" FROM "records"' + for record_id in (b"first", b"second"): + batches_read.append(record_id) + yield pa.record_batch({"__record_id": [record_id]}) + + monkeypatch.setattr(connector, "iter_batches", iter_batches) + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_record(path, b"first", pa.table({"payload": ["replacement"]})) + assert batches_read == [b"first"] + + class TestDuplicateHandling: PATH = ("dup", "v1") diff --git a/tests/test_databases/test_write_conflicts.py b/tests/test_databases/test_write_conflicts.py index 1325f3796..16bc0fd89 100644 --- a/tests/test_databases/test_write_conflicts.py +++ b/tests/test_databases/test_write_conflicts.py @@ -5,7 +5,7 @@ from decimal import Decimal from enum import Enum from pathlib import Path -from sqlite3 import IntegrityError +from sqlite3 import SQLITE_DENY, SQLITE_OK, SQLITE_READ, DatabaseError, IntegrityError from typing import Any, Literal, cast import pyarrow as pa @@ -18,7 +18,7 @@ InMemoryArrowDatabase, SQLiteConnector, ) -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, OrcapodDatabaseReadError from tests.test_databases.test_connector_arrow_database import MockDBConnector PATH = ("records",) @@ -715,6 +715,70 @@ def test_delta_refuses_changed_nested_id_type_against_stored( 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( From aa37cc6cbc427683f2078389737587aece1c1245 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 00:47:49 -0800 Subject: [PATCH 18/19] test(sources): repair stored fixture without a duplicate append --- tests/test_core/sources/test_repeated_dict_keys.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) 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")] From 1cb4bdda67273f9a77b76e4abc432258fffe3fcd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 01:32:37 -0800 Subject: [PATCH 19/19] fix(databases): look up only incoming strict append IDs --- changelog.d/ITL-1386.md | 3 +- docs/dev/design_issues/ITL-1386-WK1.md | 1 + src/orcapod/databases/_sql_store.py | 2 +- .../databases/connector_arrow_database.py | 12 +-- src/orcapod/databases/postgresql_connector.py | 12 ++- src/orcapod/databases/spiraldb_connector.py | 7 ++ src/orcapod/databases/sqlite_connector.py | 9 +- .../protocols/db_connector_protocol.py | 10 ++ .../test_core/sources/test_db_table_source.py | 6 ++ .../sources/test_tag_columns_normalization.py | 6 ++ .../test_connector_arrow_database.py | 32 ++++--- .../test_pipeline/test_attachment_store_io.py | 91 ++++++++++++++++++- 12 files changed, 159 insertions(+), 32 deletions(-) diff --git a/changelog.d/ITL-1386.md b/changelog.d/ITL-1386.md index e39abfc29..e40eac5bf 100644 --- a/changelog.d/ITL-1386.md +++ b/changelog.d/ITL-1386.md @@ -18,7 +18,8 @@ (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, and generic connectors read only IDs for that check. (ITL-1386) + 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) diff --git a/docs/dev/design_issues/ITL-1386-WK1.md b/docs/dev/design_issues/ITL-1386-WK1.md index ed2737925..cb281c31a 100644 --- a/docs/dev/design_issues/ITL-1386-WK1.md +++ b/docs/dev/design_issues/ITL-1386-WK1.md @@ -11,6 +11,7 @@ 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 diff --git a/src/orcapod/databases/_sql_store.py b/src/orcapod/databases/_sql_store.py index fc13671e6..299124deb 100644 --- a/src/orcapod/databases/_sql_store.py +++ b/src/orcapod/databases/_sql_store.py @@ -67,7 +67,7 @@ def create_table_if_not_exists( """Create a record table in the verified schema.""" ... - def existing_store_ids( + 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.""" diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 5d1c55c3f..988eb59aa 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -394,18 +394,10 @@ def _stored_conflicts( column = self.RECORD_ID_COLUMN if self._sql_store is not None: assert schema is not None - return self._sql_store.existing_store_ids( + return self._sql_store.existing_record_ids( name, column, input_ids, schema=schema ) - query = ( - f"SELECT {sql_table_identifier(column)} FROM " - f"{sql_table_identifier(name, schema)}" - ) - for batch in self._connector.iter_batches(query): - conflicts = input_ids.intersection(batch[column].to_pylist()) - if conflicts: - return conflicts - return set() + 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``. diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 869128e62..600238a32 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -571,13 +571,19 @@ def get_current_store_schema(self) -> str: _require_persistent_store_schema(schema, row[1]) return schema - def existing_store_ids( - self, table_name: str, id_column: str, ids: set[bytes], *, schema: str + 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 - table = sql.Identifier(schema.replace("%", "%%"), table_name.replace("%", "%%")) + 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: 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 fe6501293..83fa8831f 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -349,8 +349,13 @@ def get_current_store_schema(self) -> str: self._require_open() return "main" - def existing_store_ids( - self, table_name: str, id_column: str, ids: set[bytes], *, schema: str + 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) 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_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_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index e7d5da7de..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,27 +522,31 @@ def test_add_records_raises_if_record_id_type_is_not_binary(self, db): # =========================================================================== -def test_strict_append_reads_only_ids_until_first_conflict( +def test_strict_append_looks_up_only_incoming_ids( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Use a projected query and stop streaming when the add must be refused.""" + """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) - batches_read = [] + requests = [] + lookup = connector.existing_record_ids - def iter_batches(query: str) -> Iterator[pa.RecordBatch]: - assert query == 'SELECT "__record_id" FROM "records"' - for record_id in (b"first", b"second"): - batches_read.append(record_id) - yield pa.record_batch({"__record_id": [record_id]}) + 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, "iter_batches", iter_batches) + monkeypatch.setattr(connector, "existing_record_ids", existing_record_ids) with pytest.raises(ValueError, match="already exist.*stored"): - db.add_record(path, b"first", pa.table({"payload": ["replacement"]})) - assert batches_read == [b"first"] + 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: 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