diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md new file mode 100644 index 000000000..31ce6301f --- /dev/null +++ b/changelog.d/ITL-1381.md @@ -0,0 +1,29 @@ +### Fixed + +- A writable connector database no longer fails with `ArrowInvalid` + when rows are queued for a table whose queued rows declare a column's nullability + differently. The combined batch declares the column nullable. Combining declarations + that disagree on a stored `NOT NULL` column is still refused. Queuing a null in a + stored `NOT NULL` column is also refused, regardless of the incoming declaration. + Rows holding a null where their own schema declares a column or nested field non-nullable + raise `NullInNonNullableColumnError` when they are queued, before anything is stored. + A SQLite upsert rolls back the whole attempted batch on failure. A failed flush + removes that batch and records guarded by its results. The error reports each + affected table, every removed key, and the database's reason. Other tables can + still commit. PostgreSQL rejects text containing NUL at enqueue. When two + handles update the same key, the last flush to commit that key wins. + (ITL-1381) +- A SQLite connector handles a conflict on the record id only, as PostgreSQL does + (`ON CONFLICT () DO NOTHING` or `DO UPDATE`). A `CHECK` violation is no longer + dropped silently with `skip_duplicates`, and a collision on another `UNIQUE` column + raises instead of deleting the other row. A row skipped because its id exists is + not checked further. `SQLiteConnector` now needs SQLite 3.24.0 or newer and refuses + an older library when it is built. (ITL-1490) +- Rows queued with and without `skip_duplicates` for one table are written as separate + batches, so an ordinary overwrite is no longer skipped when a `skip_duplicates` batch + is queued beside it. A flush interrupted by a `KeyboardInterrupt` or another + `BaseException` removes the attempted batch and names its keys, as a failed flush + does; the batch is never written again, and rows not yet sent stay queued. Each + batch's write is checked against the table's schema guard. A table's queued rows + and their ids change together, in one step, so an interruption never leaves them + out of step. (ITL-1381) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index a60973db0..988f5c3e1 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -133,6 +133,17 @@ queued order at a flush). A table keeps the column order of its first write. An adds, omits or retypes a column keeps each database's own rule. The order of a struct's fields is not covered: a struct whose fields are in another order is another type here. +When two connector database handles write the same record key, the last flush to +commit that key wins. Use `skip_duplicates=True` to keep an already stored key. + +SQLite and PostgreSQL roll back a failed bulk upsert. If a flush fails for a +table, its attempted batch leaves the queue along with records guarded by results +in that batch. The error names the affected tables, every removed key, and the +reason for the failure. Independent tables can still commit during the same +flush. Submit a new batch to try those rows again. A known violation of a stored +`NOT NULL` constraint is refused at enqueue. PostgreSQL also refuses text +containing NUL at enqueue. + ## Integer | Type | in-memory | Delta | SQLite | PostgreSQL | diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index a3891705f..09e810187 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -2,14 +2,60 @@ from __future__ import annotations -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterator, Mapping, Set from contextlib import contextmanager +from dataclasses import dataclass import pyarrow as pa +@dataclass(frozen=True) +class QueuedRows: + """One table's queued rows and their ids, replaced as a whole (ITL-1381). + + The queue never changes the rows and the ids in two steps: an interruption + (``KeyboardInterrupt``) between two statements leaves both as they were or + both as they become. + """ + + table: pa.Table + ids: frozenset[bytes] + + +class QueuedTables(Mapping[str, pa.Table]): + """Read-only view of each key's queued rows.""" + + def __init__(self, queue: dict[str, QueuedRows]) -> None: + self._queue = queue + + def __getitem__(self, key: str) -> pa.Table: + return self._queue[key].table + + def __iter__(self) -> Iterator[str]: + return iter(self._queue) + + def __len__(self) -> int: + return len(self._queue) + + +class QueuedIds(Mapping[str, frozenset[bytes]]): + """Read-only view of each key's queued ids.""" + + def __init__(self, queue: dict[str, QueuedRows]) -> None: + self._queue = queue + + def __getitem__(self, key: str) -> frozenset[bytes]: + return self._queue[key].ids + + def __iter__(self) -> Iterator[str]: + return iter(self._queue) + + def __len__(self) -> int: + return len(self._queue) + + class PendingCommit: - """The outcome of the current attempt to commit a table's pending rows.""" + """The outcome of an attempt to commit pending results.""" def __init__(self) -> None: self.committed = False @@ -19,12 +65,14 @@ def add_dependent(self, queue: PendingCommits, key: str, record_id: bytes) -> No """Withdraw this dependent record if the attempt fails.""" self._dependents.setdefault((queue, key), set()).add(record_id) - def finish(self, *, committed: bool) -> None: + def finish( + self, *, committed: bool, discarded: dict[str, set[bytes]] | None = None + ) -> None: """Release the guarded rows on success or withdraw them on failure.""" self.committed = committed if not committed: for (queue, key), ids in self._dependents.items(): - queue.discard(key, ids, self) + queue.discard(key, ids, self, discarded=discarded) self._dependents.clear() @@ -34,19 +82,44 @@ class PendingCommits: def __init__( self, record_id_column: str, - batches: dict[str, pa.Table], - ids: dict[str, set[bytes]], *, on_empty: Callable[[str], None] | None = None, ) -> None: self._record_id_column = record_id_column - self._batches = batches - self._ids = ids + # The queue itself: every change replaces a key's entry by one assignment. + self._queue: dict[str, QueuedRows] = {} + self._batches = QueuedTables(self._queue) + self._ids = QueuedIds(self._queue) self._on_empty = on_empty - self._attempts: dict[str, PendingCommit] = {} + self._attempts: dict[str, dict[bytes | None, PendingCommit]] = {} self._guards: dict[str, dict[bytes, PendingCommit]] = {} self._schema_checks: dict[str, Callable[[pa.Schema], None]] = {} + @property + def batches(self) -> Mapping[str, pa.Table]: + """Each key's queued rows (read-only).""" + return self._batches + + @property + def ids(self) -> Mapping[str, frozenset[bytes]]: + """Each key's queued ids (read-only).""" + return self._ids + + def queue(self, key: str, table: pa.Table, ids: Set[bytes]) -> None: + """Make ``table`` (with exactly ``ids``) the key's queued rows, in one step.""" + self._queue[key] = QueuedRows(table, frozenset(ids)) + + def clear(self) -> None: + """Drop every queued row.""" + self._queue.clear() + + def _replace(self, key: str, table: pa.Table, ids: frozenset[bytes]) -> None: + """Keep ``ids`` of the key's rows (``table``), or drop the key when none.""" + if ids: + self._queue[key] = QueuedRows(table, ids) + else: + self._queue.pop(key, None) + @contextmanager def guard_schema( self, key: str, check: Callable[[pa.Schema], None] @@ -63,19 +136,39 @@ def schema_check(self, key: str) -> Callable[[pa.Schema], None] | None: """Get the check for a batch being committed.""" return self._schema_checks.get(key) - def attempt(self, key: str) -> PendingCommit: - """Get the attempt shared by all rows currently pending for a table.""" - attempt = self._attempts.get(key) + def attempt(self, key: str, record_id: bytes | None = None) -> PendingCommit: + """Get a commit dependency for a row or for a table committed as a unit.""" + attempts = self._attempts.setdefault(key, {}) + attempt = attempts.get(record_id) if attempt is None: - attempt = self._attempts[key] = PendingCommit() + attempt = attempts[record_id] = PendingCommit() return attempt def finish(self, key: str, *, committed: bool) -> None: - """Resolve an attempt before another flush can consider its dependents.""" - attempt = self._attempts.pop(key, None) - if attempt is not None: + """Resolve all dependencies on this table's current commit attempt.""" + for attempt in self._attempts.pop(key, {}).values(): attempt.finish(committed=committed) + def finish_rows( + self, + key: str, + attempted: set[bytes], + *, + committed: bool, + discarded: dict[str, set[bytes]] | None = None, + ) -> None: + """Resolve dependents of attempted rows, leaving other guards in place.""" + attempts = self._attempts.get(key) + if attempts is None: + return + resolved = [ + attempts.pop(record_id) for record_id in attempts.keys() & attempted + ] + if not attempts: + self._attempts.pop(key) + for attempt in resolved: + attempt.finish(committed=committed, discarded=discarded) + @contextmanager def guard( self, key: str, record_id: bytes, attempt: PendingCommit @@ -92,48 +185,101 @@ def guard( if record_id not in self._ids.get(key, ()): self.forget(key, {record_id}) - def discard(self, key: str, ids: set[bytes], attempt: PendingCommit) -> None: + def discard( + self, + key: str, + ids: set[bytes], + attempt: PendingCommit, + *, + discarded: dict[str, set[bytes]] | None = None, + ) -> None: """Withdraw the records still guarded by the failed attempt.""" guards = self._guards.get(key, {}) ids = {record_id for record_id in ids if guards.get(record_id) is attempt} self.forget(key, ids) - held_ids = self._ids.get(key) - if held_ids is None or not held_ids.intersection(ids): + held = self._queue.get(key) + if held is None: + return + removed = ids & held.ids + if not removed: return - held_ids.difference_update(ids) - if held_ids: - self._batches[key] = self._select(self._batches[key], ids, keep=False) + remaining = held.ids - removed + if remaining: + self._replace(key, self._select(held.table, removed, keep=False), remaining) else: - self._batches.pop(key) - self._ids.pop(key) + self._queue.pop(key) self._schema_checks.pop(key, None) if self._on_empty is not None: self._on_empty(key) + if discarded is not None: + discarded.setdefault(key, set()).update(removed) + self.finish_rows(key, removed, committed=False, discarded=discarded) + + def peek_ready( + self, key: str, among: Set[bytes] | None = None + ) -> tuple[pa.Table, set[bytes]] | None: + """The records ready to commit, left in the queue (blocked ones excluded). - def take_ready(self, key: str) -> tuple[pa.Table, set[bytes]] | None: - """Take the records ready to commit, leaving blocked records readable.""" - batch = self._batches.get(key) - if batch is None or not batch.num_rows: + Args: + key: The table's key. + among: Only these ids (the rows of one write policy). ``None``: every + ready row. + + Returns: + The ready rows and their ids, or ``None`` when none is ready. Nothing + leaves the queue: ``remove`` takes them out once their write was tried. + """ + held = self._queue.get(key) + if held is None or not held.table.num_rows: return None blocked = { record_id for record_id, attempt in self._guards.get(key, {}).items() if not attempt.committed } - if not blocked: - return self._batches.pop(key), self._ids.pop(key, set()) - ids = self._ids[key] - blocked - if not ids: + ready = set(held.ids if among is None else held.ids & among) - blocked + if not ready: return None - self._batches[key] = self._select(batch, blocked, keep=True) - self._ids[key] = blocked - return self._select(batch, blocked, keep=False), ids + if ready == held.ids: + return held.table, ready + return self._select(held.table, ready, keep=True), ready + + def remove(self, key: str, ids: Set[bytes]) -> None: + """Take rows out of the queue, in one step.""" + held = self._queue.get(key) + if held is None or not ids & held.ids: + return + remaining = held.ids - ids + table = ( + self._select(held.table, set(ids), keep=False) if remaining else held.table + ) + self._replace(key, table, remaining) + + def take_ready( + self, key: str, among: Set[bytes] | None = None + ) -> tuple[pa.Table, set[bytes]] | None: + """Take the records ready to commit, leaving blocked records readable. + + Args: + key: The table's key. + among: Take only these ids; the other queued rows stay queued. + ``None`` takes every ready row. - def restore(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: + The taken and the remaining rows are built before the queue changes, and + the queue changes in one step (``remove``). + """ + ready = self.peek_ready(key, among) + if ready is not None: + self.remove(key, ready[1]) + return ready + + def restore(self, key: str, batch: pa.Table, ids: Set[bytes]) -> None: """Restore a retryable write ahead of rows that were held back.""" - held = self._batches.get(key) - self._batches[key] = batch if held is None else pa.concat_tables([batch, held]) - self._ids.setdefault(key, set()).update(ids) + held = self._queue.get(key) + if held is None: + self.queue(key, batch, ids) + else: + self.queue(key, pa.concat_tables([batch, held.table]), held.ids | ids) def forget(self, key: str, ids: set[bytes]) -> None: """Forget dependencies for records that are leaving the queue.""" @@ -146,7 +292,7 @@ def forget(self, key: str, ids: set[bytes]) -> None: if not guards: self._guards.pop(key) - def _select(self, batch: pa.Table, ids: set[bytes], *, keep: bool) -> pa.Table: + def _select(self, batch: pa.Table, ids: Set[bytes], *, keep: bool) -> pa.Table: """Keep or remove the given rows, preserving their order and schema.""" mask = [ (record_id in ids) == keep diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..ee07ad400 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -19,8 +19,7 @@ from __future__ import annotations import re -from collections import defaultdict -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Set from contextlib import AbstractContextManager from typing import Any, cast @@ -30,14 +29,17 @@ from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases.utils import ( coerce_record_id, + declared_null_path, first_changed_column, first_logical_identity_change, in_held_column_order, ) from orcapod.errors import ( InputValidationError, + NullInNonNullableColumnError, OrcapodDatabaseError, OrcapodDatabaseReadError, + OrcapodDatabaseWriteError, UnstorableColumnError, UnstorableTableNameError, ) @@ -57,9 +59,20 @@ def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: ] +def _stored_null_columns(records: pa.Table, stored: list[pa.Field[Any]]) -> list[str]: + """Find stored NOT NULL columns containing a null in incoming rows.""" + return [ + field.name + for field in stored + if not field.nullable + and field.name in records.column_names + and records[field.name].null_count + ] + + def _alike(parts: list[pa.Table]) -> list[pa.Table]: - """Stored and queued rows under one schema when they differ only in a column's - nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary + """Rows of one table (stored and queued, or queued by two calls) under one schema + when they differ only in a column's nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary key) that the queued rows declare nullable. Each such field is nullable when either side's is, and the arrays are re-wrapped under it, never cast. Any other difference is left for ``pa.concat_tables`` to refuse, as before.""" @@ -94,6 +107,11 @@ class ConnectorArrowDatabase: on ``flush()``. The ``record_path`` tuple is mapped to a sanitized SQL table name using ``"__".join(sanitized_parts)``. + If two handles write the same key, the last flush to commit that key wins. + With ``skip_duplicates=True``, an existing durable key is kept. A refused + flush drops the attempted batch and reports its keys and any removed + dependent records. + Args: connector: A ``DBConnectorProtocol`` implementation providing the underlying DB access (connection, type mapping, queries, writes). @@ -111,9 +129,7 @@ def __init__( connector: DBConnectorProtocol, max_hierarchy_depth: int = 10, _path_prefix: tuple[str, ...] = (), - _shared_pending_batches: dict[str, pa.Table] | None = None, - _shared_pending_record_ids: dict[str, set[bytes]] | None = None, - _shared_pending_skip_existing: dict[str, bool] | None = None, + _shared_pending_skip_existing: dict[str, set[bytes]] | None = None, _root: ConnectorArrowDatabase | None = None, _scoped_path: tuple[str, ...] = (), ) -> None: @@ -122,21 +138,15 @@ def __init__( self._path_prefix = _path_prefix self._root = _root self._scoped_path = _scoped_path - self._pending_batches: dict[str, pa.Table] = ( - _shared_pending_batches if _shared_pending_batches is not None else {} - ) - self._pending_record_ids: dict[str, set[bytes]] = ( - _shared_pending_record_ids - if _shared_pending_record_ids is not None - else defaultdict(set) - ) # The schema each stored table was read with, for the append check # (``_refuse_changed_columns``). self._stored_schemas: dict[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. - self._pending_skip_existing: dict[str, bool] = ( + # The ids of the queued rows added with skip_duplicates=True, per table: + # flush() writes them with skip_existing=True (the connector's + # ``ON CONFLICT () DO NOTHING``) and the other queued rows of the + # table as a separate batch, so one write policy never leaks to rows + # queued with the other (ITL-1381). + self._pending_skip_existing: dict[str, set[bytes]] = ( _shared_pending_skip_existing if _shared_pending_skip_existing is not None else {} @@ -147,11 +157,13 @@ def __init__( if _root is not None else PendingCommits( self.RECORD_ID_COLUMN, - self._pending_batches, - self._pending_record_ids, on_empty=self._discard_pending_duplicate_policy, ) ) + # Read-only views of the queue, shared by every view of the database. Each + # table's rows and ids change together, in one step (ITL-1381). + self._pending_batches = self._pending_commits.batches + self._pending_record_ids = self._pending_commits.ids def _discard_pending_duplicate_policy(self, key: str) -> None: """Forget the duplicate policy when an entire queued batch is discarded.""" @@ -471,9 +483,16 @@ def add_records( self.require_storable( normalize_schema_to_large_types(records.schema, keep_null=True) ) - self._require_table_name( - self._path_to_table_name(self._path_prefix + record_path) - ) + table_name = self._path_to_table_name(self._path_prefix + record_path) + self._require_table_name(table_name) + # Against the schema these rows were given with: combined with queued rows + # that declare the column nullable, the null would be stored (ITL-1381). + # Before the normalization, which refuses some such rows with another error. + null_path = declared_null_path(records) + if null_path is not None: + raise NullInNonNullableColumnError( + null_path, table="/".join(self._path_prefix + record_path) + ) records = normalize_table_to_large_types(records, keep_null=True) self._connector.validate_records(records) @@ -495,9 +514,11 @@ def add_records( if skip_duplicates: # Only filter records that conflict with the in-flight pending batch. # Committed duplicates are handled at flush time via - # upsert_records(skip_existing=True), which lets the connector use - # native INSERT-OR-IGNORE semantics — no full-table read needed here. - pending_conflicts = input_ids & self._pending_record_ids[record_key] + # upsert_records(skip_existing=True), which lets the connector skip + # stored ids natively — no full-table read needed here. + pending_conflicts = input_ids & self._pending_record_ids.get( + record_key, frozenset() + ) if pending_conflicts: mask = pc.invert( pc.is_in( @@ -508,26 +529,47 @@ 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 & self._pending_record_ids.get( + record_key, frozenset() + ) if conflicts: raise ValueError( f"Records with IDs {conflicts} already exist in the pending batch. " "Use skip_duplicates=True to skip them." ) + # A nullable input can still violate a constraint of the durable table. + # Only rows that actually contain nulls require this lookup. + if any(column.null_count for column in records.columns): + null_columns = _stored_null_columns( + records, self._stored_columns(table_name) or [] + ) + if null_columns: + raise NullInNonNullableColumnError(null_columns[0], table=record_key) + # Buffer in pending batch existing_pending = self._pending_batches.get(record_key) if existing_pending is None: - self._pending_batches[record_key] = records + queued = records else: - self._pending_batches[record_key] = pa.concat_tables( - [existing_pending, records] - ) - self._pending_record_ids[record_key].update( - cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) + # Two queued batches may declare a column's nullability differently, as + # stored and queued rows may (ITL-1381). + self._refuse_loosened_columns(record_path, existing_pending, records) + queued = pa.concat_tables(_alike([existing_pending, records])) + queued_ids = cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) + # Each row keeps the write policy it was queued with: flush() writes the + # rows of each policy as their own batch (ITL-1381). A policy recorded for + # an id not (yet) queued is never read. + skipped = self._pending_skip_existing.setdefault(record_key, set()) + if skip_duplicates: + skipped.update(queued_ids) + else: + skipped.difference_update(queued_ids) + self._pending_commits.queue( + record_key, + queued, + self._pending_record_ids.get(record_key, frozenset()).union(queued_ids), ) if flush: @@ -624,6 +666,36 @@ def _refuse_changed_columns( f"{changed[0]!r}: {changed[1]}. Nothing was written." ) + def _refuse_loosened_columns( + self, record_path: tuple[str, ...], pending: pa.Table, records: pa.Table + ) -> None: + """Refuse a batch that differs from the queued one in the nullability of a + column the stored table holds ``NOT NULL`` (ITL-1381). + + Combined, the column would be nullable and a flush could refuse it, taking the + rows of the valid batch with it. The stored table is looked up only when the + two batches differ. + + Raises: + InputValidationError: Naming the first such column and the path. + """ + differing = { + field.name + for field, other in zip(pending.schema, records.schema) + if field.name == other.name and field.nullable != other.nullable + } + if not differing: + return + table_name = self._path_to_table_name(self._path_prefix + record_path) + for field in self._stored_columns(table_name) or []: + if field.name in differing and not field.nullable: + raise InputValidationError( + f"Cannot append to the table at {record_path!r}: column " + f"{field.name!r} is stored NOT NULL, and these rows and the rows " + "queued before them declare its nullability differently. Declare " + "it NOT NULL in both. Nothing was queued." + ) + def _read_stored_schema(self, table_name: str) -> pa.Schema | None: """The schema a read of the stored table gives, its field metadata included. @@ -648,8 +720,8 @@ def base_path(self) -> tuple[str, ...]: def at(self, *path_components: str) -> "ConnectorArrowDatabase": """Return a new ConnectorArrowDatabase scoped to the given sub-path. - The returned instance shares the connector and all three pending dicts - (_pending_batches, _pending_record_ids, _pending_skip_existing) by reference. + The returned instance shares the connector, the pending queue + (``_pending_commits``) and the write policies (``_pending_skip_existing``). Calling flush() on any view drains the entire shared pending queue. Raises: @@ -673,8 +745,6 @@ def at(self, *path_components: str) -> "ConnectorArrowDatabase": connector=self._connector, max_hierarchy_depth=self.max_hierarchy_depth, _path_prefix=self._path_prefix + path_components, - _shared_pending_batches=self._pending_batches, - _shared_pending_record_ids=self._pending_record_ids, _shared_pending_skip_existing=self._pending_skip_existing, _root=new_root, _scoped_path=new_scoped_path, @@ -688,7 +758,7 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): - return self._pending_commits.attempt(key) + return self._pending_commits.attempt(key, record_id) if self.get_record_by_id(record_path, record_id) is None: raise ValueError("The referenced result is neither stored nor pending.") return None @@ -717,9 +787,20 @@ def guard_table_schema( ) def flush(self) -> None: - """Commit all pending batches to the connector via upsert.""" + """Try each table's pending batch and raise the first failure afterwards.""" + first_error: Exception | None = None for record_key in list(self._pending_batches): - self._flush_by_key(record_key) + try: + self._flush_by_key(record_key) + except Exception as error: + if first_error is None: + first_error = error + else: + first_error.add_note( + f"Flush of {record_key!r} also failed: {error}" + ) + if first_error is not None: + raise first_error def refresh_table(self, record_path: tuple[str, ...]) -> None: """Nothing to refresh: every read queries the connector's backend (ITL-1408).""" @@ -735,18 +816,71 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: self._flush_by_key(self._get_record_key(record_path)) def _flush_by_key(self, record_key: str) -> None: - """Commit the ready records at a key shared by all views.""" - ready = self._pending_commits.take_ready(record_key) - if ready is None: - return - pending, ids = ready + """Commit the ready records at a key shared by all views. + + Rows queued with ``skip_duplicates`` and rows queued without it are written + as two batches, each with its own write policy, never as one (ITL-1381). + Each batch leaves the queue, in one step, just before its write is tried + (``_commit_batch``): a batch not yet taken stays queued, with the table's + schema guard, whatever interrupts the flush, and a batch taken is never + written again. Each batch commits or leaves + the queue on its own; the first failure is raised after both were tried. + """ + first_error: Exception | None = None + try: + for skip_existing in (False, True): + skipped = self._pending_skip_existing.get(record_key, set()) + queued = self._pending_record_ids.get(record_key, frozenset[bytes]()) + among = queued & skipped if skip_existing else queued - skipped + try: + self._commit_batch(record_key, among, skip_existing) + except Exception as error: + if first_error is None: + first_error = error + else: + first_error.add_note(f"The second batch also failed: {error}") + finally: + remaining = self._pending_record_ids.get(record_key) + skipped = self._pending_skip_existing.get(record_key) + if not remaining: + self._pending_skip_existing.pop(record_key, None) + elif skipped is not None: + skipped.intersection_update(remaining) + if first_error is not None: + raise first_error + + def _commit_batch( + self, + record_key: str, + among: Set[bytes], + skip_existing: bool, + ) -> None: + """Take one write policy's ready rows out of the queue and write them. + + The rows leave the queue before their write is tried, so no interruption + can make them be written twice; the worst case is a batch removed (and + reported) but not written (N32, N49). Their ids are recorded as attempted + before the queue changes, so a failure or ``BaseException`` (a + ``KeyboardInterrupt``) at any later point reports them, and the records + guarded by them, as removed: a failure raises ``OrcapodDatabaseWriteError``; + a ``BaseException`` gets a note naming them and propagates. + + Args: + record_key: The table's key. + among: The ids of the queued rows of this write policy. + skip_existing: Whether these rows were queued with ``skip_duplicates``. + """ + attempted: set[bytes] = set() record_path = tuple(record_key.split("/")) table_name = self._path_to_table_name(record_path) - skip_existing = self._pending_skip_existing.get(record_key, False) - if record_key not in self._pending_batches: - self._pending_skip_existing.pop(record_key, None) - try: + ready = self._pending_commits.peek_ready(record_key, among) + if ready is None: + return + pending, ids = ready + attempted.update(ids) + # Out of the queue before the write is tried: never written twice. + self._pending_commits.remove(record_key, ids) self._require_table_name(table_name) columns = _arrow_schema_to_column_infos(pending.schema) @@ -784,6 +918,12 @@ def _fmt(cols: dict) -> str: "Schema evolution is not supported." ) + null_columns = _stored_null_columns(pending, existing) + if null_columns: + raise NullInNonNullableColumnError( + null_columns[0], table=record_key + ) + # Checked by exact name and type above: only then are the rows put # in the stored order, by name (ITL-1367). pending = in_held_column_order(pending, existing) @@ -797,13 +937,44 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) - except BaseException: - self._pending_commits.finish(record_key, committed=False) + except Exception as error: + if not attempted: + raise + discarded = self._discard_attempted(record_key, attempted) + raise OrcapodDatabaseWriteError( + record_path, flush=True, table_flush=True, discarded_records=discarded + ) from error + except BaseException as error: + if not attempted: + raise # Nothing was taken from the queue. + discarded = self._discard_attempted(record_key, attempted) + error.add_note( + f"Interrupted while committing pending writes to table {record_key!r}: " + "the write may have committed, so it is not tried again." + + "".join( + f"\nRemoved queued records from table {table!r} with keys " + + ", ".join(map(repr, sorted(keys))) + for table, keys in discarded.items() + ) + ) raise else: - self._pending_commits.finish(record_key, committed=True) - finally: - self._pending_commits.forget(record_key, ids) + self._pending_commits.finish_rows(record_key, attempted, committed=True) + self._pending_commits.forget(record_key, attempted) + + def _discard_attempted( + self, record_key: str, ids: set[bytes] + ) -> dict[str, set[bytes]]: + """Withdraw an attempted batch's keys and the records they guard; return + every removed key, by table. The keys may still be queued only when an + interruption came between recording and removing them.""" + self._pending_commits.remove(record_key, ids) + discarded = {record_key: ids.copy()} + self._pending_commits.finish_rows( + record_key, ids, committed=False, discarded=discarded + ) + self._pending_commits.forget(record_key, ids) + return discarded # ── Read methods ────────────────────────────────────────────────────────── diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..02a08d6d5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -7,7 +7,6 @@ import sys import time import uuid -from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from dataclasses import dataclass @@ -1746,8 +1745,6 @@ def __init__( _path_prefix: tuple[str, ...] = (), _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_delta_table_cache: "dict[str, deltalake.DeltaTable] | None" = None, _shared_snapshots: "dict[str, _CommittedSnapshot] | None" = None, _shared_pending_indexes: "dict[str, KeyIndex] | None" = None, @@ -1786,14 +1783,6 @@ def __init__( self._delta_table_cache: dict[str, deltalake.DeltaTable] = ( _shared_delta_table_cache if _shared_delta_table_cache is not None else {} ) - if _shared_pending_batches is not None: - self._pending_batches = _shared_pending_batches - else: - self._pending_batches: dict[str, pa.Table] = {} - 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) # 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] = ( @@ -1808,11 +1797,13 @@ def __init__( if _root is not None else PendingCommits( self.RECORD_ID_COLUMN, - self._pending_batches, - self._pending_record_ids, on_empty=self._discard_pending_index, ) ) + # Read-only views of the queue shared by every view of the database; each + # table's rows and ids change together, in one step (ITL-1381). + self._pending_batches = self._pending_commits.batches + self._pending_record_ids = self._pending_commits.ids # Record keys whose table was found absent (ITL-1173), so lookups do not try # to open it again on every row. Family-wide like the loaded tables, and # forgotten on any flush of the family and on a flush of the key: a table @@ -2848,7 +2839,10 @@ def add_records( ) if staged_pending is not None: self._refuse_unmergeable_append(record_path, staged_pending, staged_pending) - self._pending_batches[self._get_record_key(record_path)] = staged_pending + staged_key = self._get_record_key(record_path) + self._pending_commits.queue( + staged_key, staged_pending, self._pending_record_ids[staged_key] + ) # Step 7: Add to pending batch (no overwrite logic needed) self._add_to_pending_batch(record_path, schema_compatible_table) @@ -2898,7 +2892,7 @@ def _filter_existing_records( # Get IDs that already exist in pending batch or Delta table existing_in_pending = input_ids.intersection( - self._pending_record_ids[record_key] + self._pending_record_ids.get(record_key, frozenset()) ) existing_in_delta = input_ids.intersection(self._stored_ids(record_path)) if existing_in_delta: @@ -2931,7 +2925,9 @@ def _check_all_conflicts( 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, frozenset()) + ) if pending_conflicts: raise ValueError( f"Cannot insert records with IDs that already exist in pending batch: {pending_conflicts}. " @@ -3039,20 +3035,21 @@ def _add_to_pending_batch(self, record_path: tuple[str, ...], table: pa.Table): # Add row index column for internal tracking record_key = self._get_record_key(record_path) pending_batch = self._pending_batches.get(record_key) + pending_ids = cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist()) + queued_ids = self._pending_record_ids.get(record_key, frozenset()).union( + pending_ids + ) if pending_batch is None: - self._pending_batches[record_key] = table + self._pending_commits.queue(record_key, table, queued_ids) else: # Kept at O(log n) record batches, and its indexes extended in place, so a # lookup's cost does not grow with the rows pending (ITL-919). grown = compact_tail(pa.concat_tables([pending_batch, table])) - self._pending_batches[record_key] = grown + self._pending_commits.queue(record_key, grown, queued_ids) index = self._pending_indexes.get(record_key) 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()) - self._pending_record_ids[record_key].update(pending_ids) - def _should_auto_flush(self, record_path: tuple[str, ...]) -> bool: """Check if auto-flush should be triggered.""" record_key = self._get_record_key(record_path) @@ -3310,9 +3307,9 @@ def get_record_by_id( # Serve a pending record only if its id is not stored: a flush keeps the # stored row and drops the pending one. record_key = self._get_record_key(record_path) - if record_id in self._pending_record_ids[ - record_key - ] and record_id not in self._stored_ids(record_path): + if record_id in self._pending_record_ids.get( + record_key, frozenset() + ) and record_id not in self._stored_ids(record_path): # Return the pending record after removing the entry id column pending = self._pending_rows(record_path) assert pending is not None, "Pending batch should not be None" @@ -4287,8 +4284,6 @@ def at(self, *path_components: str) -> "DeltaTableDatabase": _path_prefix=self._path_prefix + path_components, _root=new_root, _scoped_path=new_scoped_path, - _shared_pending_batches=root_instance._pending_batches, - _shared_pending_record_ids=root_instance._pending_record_ids, _shared_delta_table_cache=root_instance._delta_table_cache, _shared_snapshots=root_instance._snapshots, _shared_pending_indexes=root_instance._pending_indexes, diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2ccb4d696..4695cfb0e 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -1,7 +1,6 @@ from __future__ import annotations import logging -from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from typing import TYPE_CHECKING, Any, cast @@ -54,8 +53,6 @@ def __init__( max_hierarchy_depth: int = 10, _path_prefix: tuple[str, ...] = (), _shared_tables: "dict[str, pa.Table] | None" = None, - _shared_pending_batches: "dict[str, pa.Table] | None" = None, - _shared_pending_record_ids: "dict[str, set[bytes]] | None" = None, _shared_indexes: "dict[str, KeyIndex] | None" = None, _root: InMemoryArrowDatabase | None = None, _scoped_path: tuple[str, ...] = (), @@ -67,14 +64,6 @@ def __init__( self._tables: dict[str, pa.Table] = ( _shared_tables if _shared_tables is not None else {} ) - self._pending_batches: dict[str, pa.Table] = ( - _shared_pending_batches if _shared_pending_batches is not None else {} - ) - self._pending_record_ids: dict[str, set[bytes]] = ( - _shared_pending_record_ids - if _shared_pending_record_ids is not None - else defaultdict(set) - ) self._indexes: dict[str, KeyIndex] = ( _shared_indexes if _shared_indexes is not None else {} ) @@ -82,10 +71,12 @@ def __init__( self._pending_commits = ( _root._pending_commits if _root is not None - else PendingCommits( - self.RECORD_ID_COLUMN, self._pending_batches, self._pending_record_ids - ) + else PendingCommits(self.RECORD_ID_COLUMN) ) + # Read-only views of the queue shared by every view of the database; each + # table's rows and ids change together, in one step (ITL-1381). + self._pending_batches = self._pending_commits.batches + self._pending_record_ids = self._pending_commits.ids # ------------------------------------------------------------------ # Path helpers @@ -197,7 +188,7 @@ def _filter_existing_records( ) -> "pa.Table": """Filter out records whose IDs are already in pending or committed database.""" input_ids = set(table[self.RECORD_ID_COLUMN].to_pylist()) - pending_ids = self._pending_record_ids[record_key] + pending_ids = self._pending_record_ids.get(record_key, frozenset()) committed_ids = self._committed_id_index(record_key) all_existing = { record_id @@ -319,7 +310,9 @@ def add_records( 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 & self._pending_record_ids.get( + record_key, frozenset() + ) if pending_conflicts: raise ValueError( f"Records with IDs {pending_conflicts} already exist in the " @@ -328,14 +321,17 @@ def add_records( # Add to pending batch existing_pending = self._pending_batches.get(record_key) - if existing_pending is None: - self._pending_batches[record_key] = records - else: - self._pending_batches[record_key] = pa.concat_tables( - [existing_pending, records] - ) + queued = ( + records + if existing_pending is None + else pa.concat_tables([existing_pending, records]) + ) pending_ids = cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) - self._pending_record_ids[record_key].update(pending_ids) + self._pending_commits.queue( + record_key, + queued, + self._pending_record_ids.get(record_key, frozenset()).union(pending_ids), + ) if flush: self.flush() @@ -501,8 +497,6 @@ def at(self, *path_components: str) -> "InMemoryArrowDatabase": max_hierarchy_depth=self.max_hierarchy_depth, _path_prefix=self._path_prefix + path_components, _shared_tables=self._tables, - _shared_pending_batches=self._pending_batches, - _shared_pending_record_ids=self._pending_record_ids, _shared_indexes=self._indexes, _root=new_root, _scoped_path=new_scoped_path, @@ -605,7 +599,7 @@ def get_record_by_id( record_key = self._get_record_key(record_path) # Check pending first - if record_id in self._pending_record_ids[record_key]: + if record_id in self._pending_record_ids.get(record_key, frozenset()): pending = self._pending_batches[record_key] filtered = pending.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows > 0: diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 0417c04c5..0bd4fad7c 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -23,9 +23,10 @@ from typing import TYPE_CHECKING, Any import pyarrow as pa +import pyarrow.compute as pc from orcapod.databases.utils import is_direct_projection -from orcapod.errors import UnstorableTableNameError +from orcapod.errors import UnstorableTableNameError, UnsupportedValueError from orcapod.types import ColumnInfo from orcapod.utils.lazy_module import LazyModule @@ -702,7 +703,7 @@ def upsert_records( with conn.cursor() as cur: cur.executemany(sql, rows_iter) conn.commit() - except Exception: + except BaseException: conn.rollback() raise @@ -773,7 +774,7 @@ def _require_table_name(self, table_name: str) -> None: ) def validate_records(self, records: pa.Table) -> None: - """Reject tables carrying any Arrow field or schema metadata. + """Reject Arrow metadata and text containing a NUL character. ``PostgreSQLConnector`` does not preserve Arrow field or schema metadata across read/write cycles — any metadata present would be silently lost. @@ -786,7 +787,8 @@ def validate_records(self, records: pa.Table) -> None: Raises: ValueError: If any field (or any nested child field) carries - metadata, or if the schema itself carries metadata. + metadata, if the schema itself carries metadata, or if a text + value contains a NUL character. """ problem_fields = [f.name for f in records.schema if _field_has_metadata(f)] has_schema_meta = bool(records.schema.metadata) @@ -801,6 +803,15 @@ def validate_records(self, records: pa.Table) -> None: f"PostgreSQLConnector does not preserve Arrow metadata " f"({', '.join(parts)})." ) + for field, column in zip(records.schema, records.columns, strict=True): + if pa.types.is_string_view(field.type): + column = column.cast(pa.large_string()) + if pa.types.is_string(column.type) or pa.types.is_large_string(column.type): + if pc.any(pc.match_substring(column, pattern="\x00")).as_py(): + raise UnsupportedValueError( + f"Column {field.name!r} contains a NUL character (U+0000), " + "which PostgreSQL text cannot store." + ) # ── Lifecycle ───────────────────────────────────────────────────────────── diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index e3bb8e10f..16e33c92d 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -226,6 +226,11 @@ def _field_has_metadata(field: pa.Field) -> bool: # --------------------------------------------------------------------------- +# The first SQLite with upsert (``INSERT ... ON CONFLICT``), which +# ``SQLiteConnector.upsert_records`` uses (ITL-1490). +_MIN_SQLITE_VERSION = (3, 24, 0) + + class SQLiteConnector: """DBConnectorProtocol implementation backed by stdlib sqlite3. @@ -233,12 +238,24 @@ class SQLiteConnector: Thread-safe via an internal threading.RLock. Not suitable for use on network filesystems (NFS, SMB/CIFS) due to unreliable file locking. + Requires SQLite 3.24.0 or newer, the first with upsert + (``INSERT ... ON CONFLICT``). + Args: db_path: Path to the SQLite database file, or ":memory:" for an in-process in-memory database. Defaults to ":memory:". + + Raises: + RuntimeError: If the SQLite library Python uses is older than 3.24.0. """ def __init__(self, db_path: str | os.PathLike = ":memory:") -> None: + if sqlite3.sqlite_version_info < _MIN_SQLITE_VERSION: + raise RuntimeError( + "SQLiteConnector needs SQLite 3.24.0 or newer (upsert, " + f"INSERT ... ON CONFLICT); this Python uses SQLite " + f"{sqlite3.sqlite_version}." + ) self._db_path = db_path self._conn: sqlite3.Connection | None = sqlite3.connect( str(db_path), check_same_thread=False, isolation_level=None @@ -457,16 +474,21 @@ def upsert_records( id_column: str, skip_existing: bool = False, ) -> None: - """Write records to a table using upsert semantics. + """Write records to a table in one upsert transaction. Args: table_name: Target table (must already exist). records: Arrow table of records to write. - id_column: Column used as the unique row identifier. Conflict - detection is handled by the SQL PRIMARY KEY constraint; - this argument is accepted for protocol compliance. - skip_existing: If True, skip rows whose id already exists - (INSERT OR IGNORE). If False, overwrite (INSERT OR REPLACE). + id_column: Column used as the unique row identifier, the table's + primary key. Conflict handling covers this column only + (``ON CONFLICT ()``), as PostgreSQL's does: any other + constraint violation (``CHECK``, ``NOT NULL``, another ``UNIQUE`` + column) raises and rolls the whole batch back, unless the row is + skipped because its id already exists (ITL-1490). + skip_existing: If True, skip a row whose id already exists and keep + the stored row (``DO NOTHING``): nothing of that row is written, + so nothing else it would collide on is checked, and nothing is + deleted. If False, update the stored row in place (``DO UPDATE``). """ with self._lock: conn = self._require_open() @@ -474,10 +496,29 @@ def upsert_records( cols = list(records.column_names) col_list = ", ".join('"' + c.replace('"', '""') + '"' for c in cols) placeholders = ", ".join("?" for _ in cols) - verb = "INSERT OR IGNORE" if skip_existing else "INSERT OR REPLACE" - sql = f'{verb} INTO "{table_name}" ({col_list}) VALUES ({placeholders})' + escaped_id = id_column.replace('"', '""') + updates = ", ".join( + f'"{escaped}" = excluded."{escaped}"' + for escaped in (c.replace('"', '""') for c in cols if c != id_column) + ) + action = ( + "DO NOTHING" + if skip_existing or not updates + else f"DO UPDATE SET {updates}" + ) + sql = ( + f'INSERT INTO "{table_name}" ({col_list}) VALUES ({placeholders}) ' + f'ON CONFLICT ("{escaped_id}") {action}' + ) rows = (tuple(row[c] for c in cols) for row in records.to_pylist()) - conn.executemany(sql, rows) + try: + conn.execute("BEGIN") + conn.executemany(sql, rows) + conn.commit() + except BaseException: + if conn.in_transaction: + conn.rollback() + raise @property def keeps_field_metadata(self) -> bool: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 789f1b076..4a4afb7c2 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -560,6 +560,87 @@ def first_logical_identity_change( return None +def declared_null_path(rows: "pa.Table") -> str | None: + """The first place, at any depth, where ``rows`` hold a null their own schema + declares non-nullable (ITL-1381). + + A value under a null list, struct or map is not a value of the rows and never + counts. A schema that declares nothing non-nullable costs no look at the values. + + Args: + rows: The rows, under the schema they were given with. + + Returns: + The path, e.g. ``"a"``, ``"g.x"`` or ``"items[]"``, or ``None``. + """ + for field, column in zip(rows.schema, rows.columns): + found = _declared_null_below(field, list(column.chunks), field.name) + if found is not None: + return found + return None + + +def _declares_non_null(field: "pa.Field[Any]") -> bool: + """Whether ``field`` or any field nested in it is non-nullable.""" + return not field.nullable or any( + _declares_non_null(child) for _, child in _child_fields(field.type) + ) + + +def _child_fields(data_type: "pa.DataType") -> "list[tuple[str, pa.Field[Any]]]": + """The nested fields whose values can be null, with their path text. A map's keys + are never null, but the fields nested in them can be.""" + if isinstance(data_type, pa.BaseExtensionType): + data_type = data_type.storage_type + if pa.types.is_struct(data_type): + return [(f".{f.name}", f) for f in data_type] + if pa.types.is_map(data_type): + # The key itself is never null, whatever its flag says; only below it. + return [ + ("{key}", data_type.key_field.with_nullable(True)), + ("{}", data_type.item_field), + ] + if ( + pa.types.is_list(data_type) + or pa.types.is_large_list(data_type) + or pa.types.is_fixed_size_list(data_type) + or pa.types.is_list_view(data_type) + or pa.types.is_large_list_view(data_type) + ): + return [("[]", data_type.value_field)] + return [] + + +def _declared_null_below( + field: "pa.Field[Any]", arrays: list[Any], path: str +) -> str | None: + if not _declares_non_null(field): + return None + if not field.nullable and any(a.null_count for a in arrays): + return path + # Only the values of valid rows: what a null row hides is not a value. + arrays = [a.storage if isinstance(a, pa.ExtensionArray) else a for a in arrays] + arrays = [a.drop_null() if a.null_count else a for a in arrays] + for index, (segment, child) in enumerate(_child_fields(field.type)): + if segment == "[]": + below = [a.flatten() for a in arrays] + elif segment in ("{key}", "{}"): + # ``MapArray.keys`` and ``items`` ignore a slice; the list over its + # offsets does not. + below = [ + pa.ListArray.from_arrays( + a.offsets, a.keys if segment == "{key}" else a.items + ).flatten() + for a in arrays + ] + else: + below = [a.field(index) for a in arrays] + found = _declared_null_below(child, below, path + segment) + if found is not None: + return found + return None + + def in_held_column_order( records: "pa.Table", held: "Sequence[pa.Field[Any]] | None" ) -> "pa.Table": diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 7720e7980..2ee41ed28 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1,4 +1,4 @@ -from collections.abc import Mapping +from collections.abc import Collection, Mapping from typing import Any, Self @@ -1081,6 +1081,7 @@ def __init__( *, flush: bool = False, table_flush: bool = False, + discarded_records: Mapping[str, Collection[bytes]] | None = None, ) -> None: """Create the error for one failed write. @@ -1091,10 +1092,16 @@ def __init__( tag: Tag values of the row being stored, if the write covered one row. flush: Whether committing pending writes failed. table_flush: Whether the flush was scoped to the given table. + discarded_records: Removed keys grouped by table when a connector + refuses a queued batch. """ self.record_path: tuple[str, ...] = tuple(record_path) self.flush: bool = flush self._table_flush = table_flush + self.discarded_records = { + table: tuple(sorted(keys)) + for table, keys in (discarded_records or {}).items() + } super().__init__( self.record_path, node_label, tag, node_label=node_label, tag=tag ) @@ -1130,9 +1137,16 @@ def __str__(self) -> str: if self.flush: node = f" for node {self.node_label!r}" if self.node_label else "" if self._table_flush: + discarded = "".join( + f"\nRemoved queued records from table {table!r} with keys " + + ", ".join(map(repr, keys)) + for table, keys in self.discarded_records.items() + ) return ( f"Could not commit pending writes to the database{node} " - f"(table {'/'.join(self.record_path)!r}){reason}. " + retry + f"(table {'/'.join(self.record_path)!r}){reason}. " + + retry + + discarded ) return ( f"Could not commit pending writes to the database{node} " diff --git a/src/orcapod/protocols/db_connector_protocol.py b/src/orcapod/protocols/db_connector_protocol.py index 6ed2f94bd..57c4cddc2 100644 --- a/src/orcapod/protocols/db_connector_protocol.py +++ b/src/orcapod/protocols/db_connector_protocol.py @@ -106,15 +106,19 @@ def upsert_records( id_column: str, skip_existing: bool = False, ) -> None: - """Write records to a table using upsert semantics. + """Write records to a table atomically using upsert semantics. + + Roll back the whole batch on a rejected write. Conflict handling covers + ``id_column`` only: any other constraint violation (``CHECK``, + ``NOT NULL``, a ``UNIQUE`` column other than the id) raises (ITL-1490). Args: table_name: Target table (must already exist). records: Arrow table of records to write. id_column: Column used as the unique row identifier. - skip_existing: If ``True``, skip records whose ``id_column`` value - already exists in the table (INSERT OR IGNORE). - If ``False``, overwrite existing records (INSERT OR REPLACE). + skip_existing: If ``True``, keep the stored row of an ``id_column`` + value that already exists (``ON CONFLICT () DO NOTHING``). + If ``False``, update it in place (``ON CONFLICT () DO UPDATE``). """ ... diff --git a/tests/test_core/function_pod/test_ephemeral_result.py b/tests/test_core/function_pod/test_ephemeral_result.py index 2d0e6cfd1..5df2d968e 100644 --- a/tests/test_core/function_pod/test_ephemeral_result.py +++ b/tests/test_core/function_pod/test_ephemeral_result.py @@ -727,7 +727,7 @@ def test_persistent_miss_warns_and_recomputes(self, caplog): # Wipe the result DB to simulate data loss result_db._tables.clear() - result_db._pending_batches.clear() + result_db._pending_commits.clear() # Recreate node with same pipeline_db (tag entry still there) but empty result_db node2, _ = _make_node( @@ -773,7 +773,7 @@ def counting_double(x: int) -> int: # Simulate data loss result_db._tables.clear() - result_db._pending_batches.clear() + result_db._pending_commits.clear() # Session 2: miss → recompute → appends new record to pipeline_db pf2 = PythonDataFunction(counting_double, output_keys="result") diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 8cb22a0f0..51edc8a45 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -14,11 +14,12 @@ from __future__ import annotations +import asyncio import os import sqlite3 import uuid -from collections.abc import Iterator -from contextlib import ExitStack +from collections.abc import Iterator, Sequence +from contextlib import ExitStack, closing, contextmanager from pathlib import Path from typing import Any, cast from unittest.mock import patch @@ -33,11 +34,15 @@ InMemoryArrowDatabase, SQLiteConnector, ) -from orcapod.databases.utils import in_held_column_order +from orcapod.databases.utils import declared_null_path, in_held_column_order from orcapod.errors import ( InputValidationError, + NullInNonNullableColumnError, + OrcapodDatabaseWriteError, UnstorableColumnError, + UnsupportedValueError, ) +from tests.test_databases.test_connector_arrow_database import MockDBConnector from tests.test_databases.type_matrix import open_database PATH = ("t",) @@ -682,7 +687,7 @@ def test_a_table_changed_between_queue_and_flush_is_refused_as_on_main( with sqlite3.connect(path) as other: CHANGES[change](other) before = _sqlite(path).get_all_records(PATH, record_id_column="rid") - with pytest.raises(ValueError, match="Schema mismatch"): + with pytest.raises(OrcapodDatabaseWriteError, match="Schema mismatch"): db.flush() after = _sqlite(path).get_all_records(PATH, record_id_column="rid") assert before is not None and after is not None @@ -1027,6 +1032,624 @@ def test_queued_rows_combine_with_a_stored_key_read_back_not_null( ) +def _declared(order: list[str], ns: list[int], *, not_null: bool) -> pa.Table: + """Rows ``ns`` with the id and ``a`` declared ``NOT NULL``, or nullable.""" + table = _rows(order, ns) + schema = pa.schema( + f.with_nullable(not (not_null and f.name in (ID, "a"))) for f in table.schema + ) + return pa.Table.from_arrays(table.columns, schema=schema) + + +def _check_lookups(db: Any, ns: list[int]) -> None: + """The rows ``ns`` by one id, by several ids and by column values.""" + several = db.get_records_by_ids( + PATH, [_row(n)[ID] for n in reversed(ns)], record_id_column=ID + ) + assert sorted(several[ID].to_pylist()) == [_row(n)[ID] for n in ns] + for n in ns: + one = db.get_record_by_id(PATH, _row(n)[ID], record_id_column=ID) + valued = db.get_records_with_column_value( + PATH, {"a": n, "c": 100 + n}, record_id_column=ID + ) + assert one.to_pylist() == valued.to_pylist() == [_row(n)] + + +@contextmanager +def _connector_database(kind: str, tmp_path: Path) -> Iterator[Any]: + if kind == "SQLite, key read NOT NULL": + yield ConnectorArrowDatabase(_KeyNotNullSQLite(str(tmp_path / "store.db"))) + elif kind == "writable mock": + yield ConnectorArrowDatabase(MockDBConnector()) + else: + with open_database(kind, tmp_path) as db: + yield db + + +CONNECTOR_DATABASES = ("SQLite", "SQLite, key read NOT NULL") + + +@pytest.mark.parametrize("kind", CONNECTOR_DATABASES) +@pytest.mark.parametrize("order", [["id", "a", "c", "b"], ["b", "c", "id", "a"]]) +@pytest.mark.parametrize("stored", [True, False]) +@pytest.mark.parametrize("queued", [True, False]) +def test_lookups_before_a_flush_combine_rows_of_differing_nullability( + tmp_path: Path, kind: str, order: list[str], stored: bool, queued: bool +) -> None: + """Stored and queued rows that declare the key and a data column ``NOT NULL`` or + nullable read together, whole and by id and by value (ITL-1381).""" + with _connector_database(kind, tmp_path) as db: + _add(db, _declared([ID, "a", "c", "b"], [1, 2], not_null=stored), flush=True) + _add(db, _declared(order, [3, 4], not_null=queued)) + rows = db.get_all_records(PATH, record_id_column=ID) + _check(rows, _given_order(kind, [ID, "a", "c", "b"]), [1, 2, 3, 4]) + _check_lookups(db, [1, 2, 3, 4]) + + +@pytest.mark.parametrize("kind", CONNECTOR_DATABASES) +@pytest.mark.parametrize("order", [["id", "a", "c", "b"], ["b", "c", "id", "a"]]) +@pytest.mark.parametrize("not_null", [(True, False, True), (False, True, False)]) +def test_queued_batches_of_differing_nullability_are_one_batch( + tmp_path: Path, kind: str, order: list[str], not_null: tuple[bool, ...] +) -> None: + """Batches queued by several calls that declare the key and a data column + ``NOT NULL`` and nullable are one nullable batch, before and after the flush + (ITL-1381): the second call raised ``ArrowInvalid``.""" + with _connector_database(kind, tmp_path) as db: + first = [ID, "a", "c", "b"] + for n, flag in enumerate(not_null, start=1): + _add(db, _declared(order if n > 1 else first, [n], not_null=flag)) + _check(db.get_all_records(PATH, record_id_column=ID), first, [1, 2, 3]) + _check_lookups(db, [1, 2, 3]) + assert db.get_all_records(PATH, record_id_column=ID).schema.field("a").nullable + db.flush() + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order(kind, first), + [1, 2, 3], + ) + _check_lookups(db, [1, 2, 3]) + + +@pytest.mark.parametrize("stored", [True, False]) +@pytest.mark.parametrize("first", [True, False]) +@pytest.mark.parametrize("skip", [True, False]) +def test_a_refused_batch_leaves_the_queued_rows_to_be_flushed( + tmp_path: Path, stored: bool, first: bool, skip: bool +) -> None: + """Queued batches of differing nullability are combined unless the stored column is + ``NOT NULL`` (CodeRabbit on PR 539): the second is then refused when it is queued, + in either order, so a flush never drops rows of a valid batch with it.""" + order = [ID, "a", "c", "b"] + with _connector_database("SQLite", tmp_path) as db: + _add(db, _declared(order, [1], not_null=stored), flush=True) + _add(db, _declared(order, [2], not_null=first)) + second = _declared(["c", ID, "b", "a"], [3], not_null=not first) + if stored: + with pytest.raises(InputValidationError, match="stored NOT NULL"): + db.add_records(PATH, second, record_id_column=ID, skip_duplicates=skip) + # The refused batch changed neither the rows nor the duplicate policy. + assert not any(db._pending_skip_existing.values()) + # A batch whose rows are all queued already has nothing to combine. + again = _declared(order, [2], not_null=not first) + db.add_records(PATH, again, record_id_column=ID, skip_duplicates=True) + ns = [1, 2] + else: + db.add_records(PATH, second, record_id_column=ID, skip_duplicates=skip) + ns = [1, 2, 3] + _check(db.get_all_records(PATH, record_id_column=ID), order, ns) + db.flush() + _check(db.get_all_records(PATH, record_id_column=ID), order, ns) + + +def _nullable_values( + rows: Sequence[tuple[bytes, int | None]], *, nullable: bool = True +) -> pa.Table: + return pa.Table.from_arrays( + [ + pa.array([key for key, _ in rows], pa.large_binary()), + pa.array([value for _, value in rows], pa.int64()), + ], + schema=pa.schema( + [ + pa.field(ID, pa.large_binary()), + pa.field("v", pa.int64(), nullable=nullable), + ] + ), + ) + + +def _read_values( + database: ConnectorArrowDatabase, path: tuple[str, ...] = PATH +) -> pa.Table: + rows = database.get_all_records(path, record_id_column=ID) + assert rows is not None + return rows.sort_by(ID) + + +@pytest.mark.parametrize("bad_first", [False, True]) +@pytest.mark.parametrize("stored_at_enqueue", [False, True]) +def test_stored_not_null_refusal_preserves_other_rows_and_tables( + tmp_path: Path, bad_first: bool, stored_at_enqueue: bool +) -> None: + """Refuse a known violation at add time and a concurrent schema change at flush.""" + db_file = str(tmp_path / "store.db") + with ( + SQLiteConnector(db_file) as connector, + SQLiteConnector(db_file) as reader_connector, + ): + writer = ConnectorArrowDatabase(connector) + reader = ConnectorArrowDatabase(reader_connector) + seed = _nullable_values([(b"changed", 1)], nullable=False) + good = _nullable_values([(b"valid", 2), (b"later", 3)]) + bad_rows: list[tuple[bytes, int | None]] = [(b"bad", None), (b"also-bad", None)] + if stored_at_enqueue: + _add(reader, seed, flush=True) + bad_rows.insert(0, (b"changed", 2)) + bad = _nullable_values(bad_rows).select(["v", ID]) + for batch in (bad, good) if bad_first else (good, bad): + if batch is bad and stored_at_enqueue: + with pytest.raises(NullInNonNullableColumnError, match="'v'"): + _add(writer, batch) + else: + _add(writer, batch) + if stored_at_enqueue: + _add(reader, _nullable_values([(b"changed", 77)]), flush=True) + else: + _add(reader, seed, flush=True) + with pytest.raises(OrcapodDatabaseWriteError, match="'v'") as raised: + writer.flush() + assert all( + repr(key) in str(raised.value) + for key in (b"bad", b"also-bad", b"valid", b"later") + ) + expected = [{ID: b"changed", "v": 1}] + if stored_at_enqueue: + expected = [ + {ID: b"changed", "v": 77}, + {ID: b"later", "v": 3}, + {ID: b"valid", "v": 2}, + ] + assert _read_values(writer).to_pylist() == expected + independent = _nullable_values([(b"ok", 5), (b"also-ok", 6)]) + writer.add_records( + ("independent",), independent, record_id_column=ID, flush=True + ) + assert _read_values(reader, ("independent",)).equals(independent.sort_by(ID)) + writer.flush() + assert _read_values(reader).to_pylist() == expected + + +@pytest.mark.parametrize("bad_first", [False, True]) +@pytest.mark.parametrize("shared_first", [False, True]) +def test_connector_writes_to_the_same_key_follow_flush_order( + tmp_path: Path, bad_first: bool, shared_first: bool +) -> None: + db_file = str(tmp_path / "store.db") + with closing(sqlite3.connect(db_file)) as sql: + sql.execute( + 'CREATE TABLE t ("__record_id" BLOB PRIMARY KEY, v INTEGER CHECK (v > 0))' + ) + with ( + SQLiteConnector(db_file) as connector_a, + SQLiteConnector(db_file) as connector_b, + ): + writer_a = ConnectorArrowDatabase(connector_a) + writer_b = ConnectorArrowDatabase(connector_b) + _add(writer_b, _nullable_values([(b"shared", 1)]), flush=True) + good = [(b"shared", 10), (b"also-good", 20)] + valid = _nullable_values(good if shared_first else good[::-1]) + refused = _nullable_values([(b"bad", -1)]) + for batch in (refused, valid) if bad_first else (valid, refused): + _add(writer_a, batch) + with pytest.raises(OrcapodDatabaseWriteError, match="CHECK"): + writer_a.flush() + assert _read_values(writer_b).to_pylist() == [{ID: b"shared", "v": 1}] + + _add(writer_b, _nullable_values([(b"shared", 99)]), flush=True) + assert _read_values(writer_b).to_pylist() == [{ID: b"shared", "v": 99}] + writer_a.flush() + assert _read_values(writer_b).to_pylist() == [{ID: b"shared", "v": 99}] + _add(writer_a, valid, flush=True) + assert _read_values(writer_b).to_pylist() == [ + {ID: b"also-good", "v": 20}, + {ID: b"shared", "v": 10}, + ] + + +@pytest.mark.parametrize("bad_first", [False, True]) +@pytest.mark.parametrize("on_event_loop", [False, True]) +@pytest.mark.parametrize("refusal", ["ABORT", "ROLLBACK", "deferred foreign key"]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_sqlite_refusal_drops_and_names_the_whole_batch( + tmp_path: Path, + bad_first: bool, + on_event_loop: bool, + refusal: str, + skip_duplicates: bool, +) -> None: + db_file = str(tmp_path / "store.db") + with closing(sqlite3.connect(db_file)) as sql: + if refusal == "deferred foreign key": + sql.executescript( + """ + CREATE TABLE parents (v INTEGER PRIMARY KEY); + INSERT INTO parents VALUES (1), (2), (3); + CREATE TABLE t ("__record_id" BLOB PRIMARY KEY, + v INTEGER REFERENCES parents(v) DEFERRABLE INITIALLY DEFERRED); + """ + ) + else: + sql.execute('CREATE TABLE t ("__record_id" BLOB PRIMARY KEY, v INTEGER)') + sql.execute( + f"""CREATE TRIGGER positive BEFORE INSERT ON t WHEN NEW.v < 0 + BEGIN SELECT RAISE({refusal}, 'must be positive'); END""" + ) + with ( + SQLiteConnector(db_file) as writer_connector, + SQLiteConnector(db_file) as reader_connector, + ): + writer = ConnectorArrowDatabase(writer_connector) + reader = ConnectorArrowDatabase(reader_connector) + + def check() -> None: + message = "must be positive" + if refusal == "deferred foreign key": + list(writer_connector.iter_batches("PRAGMA foreign_keys=ON")) + message = "FOREIGN KEY constraint failed" + _add(reader, _nullable_values([(b"seed", 1)]), flush=True) + left = _nullable_values([(b"bad-1", -1), (b"good-1", 2)]) + right = _nullable_values([(b"good-2", 3), (b"bad-2", -2)]).select(["v", ID]) + independent = ("independent",) + independent_rows = _nullable_values([(b"other-1", 4), (b"other-2", 5)]) + if not bad_first: + writer.add_records(independent, independent_rows, record_id_column=ID) + for batch in (left, right) if bad_first else (right, left): + writer.add_records( + PATH, batch, record_id_column=ID, skip_duplicates=skip_duplicates + ) + if bad_first: + writer.add_records(independent, independent_rows, record_id_column=ID) + with pytest.raises(OrcapodDatabaseWriteError, match=message) as raised: + writer.flush() + expected = [{ID: b"seed", "v": 1}] + assert _read_values(reader).to_pylist() == expected + assert "'t'" in str(raised.value) + assert all( + repr(key) in str(raised.value) + for key in (b"bad-1", b"bad-2", b"good-1", b"good-2") + ) + assert _read_values(writer).to_pylist() == expected + assert _read_values(reader, independent).equals( + independent_rows.sort_by(ID) + ) + writer.flush() + assert _read_values(reader).to_pylist() == expected + + async def on_loop() -> None: + check() + + if on_event_loop: + asyncio.run(on_loop()) + else: + check() + + +@pytest.mark.parametrize("bad_first", [False, True]) +def test_refused_result_batch_drops_and_names_its_guarded_records( + tmp_path: Path, bad_first: bool +) -> None: + db_file = str(tmp_path / "store.db") + with closing(sqlite3.connect(db_file)) as sql: + sql.executescript( + """ + CREATE TABLE t ("__record_id" BLOB PRIMARY KEY, v INTEGER); + CREATE TRIGGER positive BEFORE INSERT ON t WHEN NEW.v < 0 + BEGIN SELECT RAISE(ABORT, 'must be positive'); END; + """ + ) + with ( + SQLiteConnector(db_file) as result_connector, + SQLiteConnector(db_file) as record_connector, + ): + results = ConnectorArrowDatabase(result_connector) + records = ConnectorArrowDatabase(record_connector) + dependent_path = ("dependents",) + downstream_path = ("downstream",) + accepted = [(b"good-1", 1), (b"good-2", 2)] + refused = [(b"bad-1", -1), (b"bad-2", -2)] + for batch in (refused, accepted) if bad_first else (accepted, refused): + _add(results, _nullable_values(batch)) + for result_id, value in batch: + dependency = results.pending_result(PATH, result_id) + assert dependency is not None + record_id = b"record-" + result_id + with records.guard_record(dependent_path, record_id, dependency): + records.add_records( + dependent_path, + _nullable_values([(record_id, value)]), + record_id_column=ID, + ) + downstream_guard = records.pending_result(dependent_path, record_id) + assert downstream_guard is not None + downstream_id = b"downstream-" + result_id + with records.guard_record( + downstream_path, downstream_id, downstream_guard + ): + records.add_records( + downstream_path, + _nullable_values([(downstream_id, value)]), + record_id_column=ID, + ) + records.flush() + assert results.get_all_records(dependent_path, record_id_column=ID) is None + + with pytest.raises( + OrcapodDatabaseWriteError, match="must be positive" + ) as raised: + results.flush_result_batch(PATH, publish_records=True) + results.fail_pending_result(PATH) + assert results.get_all_records(PATH, record_id_column=ID) is None + assert records.get_all_records(dependent_path, record_id_column=ID) is None + assert records.get_all_records(downstream_path, record_id_column=ID) is None + assert all( + repr(table) in str(raised.value) + for table in ("t", "dependents", "downstream") + ) + for key, _ in accepted + refused: + assert repr(key) in str(raised.value) + assert repr(b"record-" + key) in str(raised.value) + assert repr(b"downstream-" + key) in str(raised.value) + records.flush() + assert results.get_all_records(dependent_path, record_id_column=ID) is None + + +@pytest.mark.parametrize("bad_first", [False, True]) +def test_postgresql_refuses_nul_text_at_enqueue( + tmp_path: Path, bad_first: bool +) -> None: + good = pa.table( + { + ID: [b"first", b"second"], + "description": ["a", None], + "payload": [b"\x00", b"data"], + } + ) + bad = pa.table( + { + ID: [b"bad-1", b"bad-2"], + "description": ["a\x00b", "other"], + "payload": [b"data", b"\x00"], + } + ).select(["payload", ID, "description"]) + with open_database("PostgreSQL", tmp_path) as database: + for batch in (bad, good) if bad_first else (good, bad): + if batch is bad: + with pytest.raises(UnsupportedValueError, match="'description'.*NUL"): + _add(database, batch) + else: + _add(database, batch) + assert _read_values(database).to_pylist() == good.to_pylist() + + +def _int_list(values: list[int | None], *, declared: bool) -> Any: + item = pa.field("item", pa.int64(), nullable=not declared) + offsets = pa.array(range(len(values) + 1), pa.int64()) + return pa.LargeListArray.from_arrays( + offsets, pa.array(values, pa.int64()), type=pa.large_list(item) + ) + + +def _null_case(place: str, n: int, *, null: bool, not_null: bool) -> pa.Table: + """Row ``n`` whose value at ``place`` (declared ``NOT NULL`` there, at the top level + only with ``not_null``) is null with ``null``; built without Arrow checking it.""" + value = [None if null else n] + other = pa.array([n], pa.int64()) + nullable = not not_null + if place == "column": + column = pa.array(value, pa.int64()) + elif place == "struct": + column = pa.StructArray.from_arrays( + [other, pa.array(value, pa.int64())], + fields=[pa.field("o", pa.int64()), pa.field("x", pa.int64(), False)], + ) + elif place == "list": + column = _int_list(value, declared=True) + else: + column = pa.StructArray.from_arrays( + [other, _int_list(value, declared=True)], + fields=[ + pa.field("o", pa.int64()), + pa.field("xs", pa.large_list(pa.field("item", pa.int64(), False))), + ], + ) + ids = pa.array([f"r{n}".encode()], pa.large_binary()) + return pa.Table.from_arrays( + [ids, column, other], + schema=pa.schema( + [ + pa.field(ID, pa.large_binary()), + pa.field("v", column.type, nullable=nullable), + pa.field("w", pa.int64()), + ] + ), + ) + + +NULL_PATHS = { + "column": "v", + "struct": "v.x", + "list": "v[]", + "list in struct": "v.xs[]", +} +NULL_CASES = [ + *[(kind, "column") for kind in CONNECTOR_DATABASES], + *[("writable mock", place) for place in NULL_PATHS if place != "column"], +] + + +@pytest.mark.parametrize(("kind", "place"), NULL_CASES) +@pytest.mark.parametrize("violating_first", [True, False]) +@pytest.mark.parametrize("existing", [True, False]) +@pytest.mark.parametrize("skip", [True, False]) +@pytest.mark.parametrize("run_async", [True, False]) +def test_rows_are_checked_against_their_own_declaration_before_they_are_queued( + tmp_path: Path, + kind: str, + place: str, + violating_first: bool, + existing: bool, + skip: bool, + run_async: bool, +) -> None: + """Review of PR 539: a null declared ``NOT NULL``, combined with a valid nullable + batch, was stored. It is refused when queued, whichever batch comes first, and the + valid batch is stored alone. Queued from this thread or from an event loop's tasks + (a connector database has no async path of its own).""" + + def queue(db: Any, violating: bool) -> None: + rows = _null_case( + place, 3 if violating else 2, null=violating, not_null=violating + ) + if violating: + with pytest.raises(NullInNonNullableColumnError) as refused: + db.add_records(PATH, rows, record_id_column=ID, skip_duplicates=skip) + assert refused.value.column == NULL_PATHS[place] + else: + db.add_records(PATH, rows, record_id_column=ID, skip_duplicates=skip) + + async def queue_async(db: Any) -> None: + for violating in (violating_first, not violating_first): + await asyncio.create_task(asyncio.to_thread(queue, db, violating)) + + with _connector_database(kind, tmp_path) as db: + if existing: + _add(db, _null_case(place, 1, null=False, not_null=False), flush=True) + if run_async and not kind.startswith("SQLite"): + asyncio.run(queue_async(db)) + elif run_async: + + async def on_loop() -> None: + # A SQLite connection stays on its own thread. + for violating in (violating_first, not violating_first): + queue(db, violating) + + asyncio.run(on_loop()) + else: + for violating in (violating_first, not violating_first): + queue(db, violating) + ids = [b"r1", b"r2"] if existing else [b"r2"] + for flush in (False, True): + if flush: + db.flush() + rows = db.get_all_records(PATH, record_id_column=ID) + assert sorted(rows.column(ID).to_pylist()) == ids + assert rows.column("v").null_count == 0 + + +@pytest.mark.parametrize("violating_first", [True, False]) +def test_a_postgresql_database_checks_the_declaration_before_anything_is_sent( + tmp_path: Path, violating_first: bool +) -> None: + with open_database("PostgreSQL", tmp_path) as db: + valid = _null_case("column", 2, null=False, not_null=False) + violating = _null_case("column", 3, null=True, not_null=True) + if not violating_first: + _add(db, valid) + with pytest.raises(NullInNonNullableColumnError, match="'v'"): + _add(db, violating) + if violating_first: + _add(db, valid) + rows = db.get_all_records(PATH, record_id_column=ID) + assert rows is not None + assert rows[ID].to_pylist() == [b"r2"] + + +@pytest.mark.parametrize("kind", [*CONNECTOR_DATABASES, "PostgreSQL"]) +@pytest.mark.parametrize("id_type", [pa.binary(), pa.large_binary()]) +@pytest.mark.parametrize("null_in", ["v", "the id"]) +@pytest.mark.parametrize("queued", [True, False]) +def test_each_record_id_type_gets_the_declared_null_error( + tmp_path: Path, kind: str, id_type: Any, null_in: str, queued: bool +) -> None: + """Review of PR 539: with a ``binary`` record id the rows are normalized, and the + normalization raised a plain ``ValueError`` first.""" + + def rows(n: int, *, null: bool) -> pa.Table: + table = _null_case("column", n, null=null and null_in == "v", not_null=null) + ids = pa.array([None if null and null_in == "the id" else b"r%d" % n], id_type) + field = pa.field(ID, id_type, nullable=not null) + return pa.Table.from_arrays( + [ids, *table.columns[1:]], schema=table.schema.set(0, field) + ) + + with _connector_database(kind, tmp_path) as db: + if queued: + _add(db, rows(2, null=False)) + with pytest.raises(NullInNonNullableColumnError) as refused: + _add(db, rows(3, null=True)) + assert refused.value.column == ("v" if null_in == "v" else "__record_id") + rows_read = db.get_all_records(PATH, record_id_column=ID) + held = [] if rows_read is None else rows_read[ID].to_pylist() + assert held == ([b"r2"] if queued else []) + + +def test_the_declared_null_rule_reads_only_the_values_of_the_rows() -> None: + """A value under a null struct, outside a slice, or at a nullable place never + counts; a map's values do.""" + + def path(array: Any, nullable: bool = True) -> str | None: + field = pa.field("c", array.type, nullable=nullable) + return declared_null_path( + pa.Table.from_arrays([array], schema=pa.schema([field])) + ) + + ints = pa.array([1, None, 3]) + x = pa.field("x", pa.int64(), nullable=False) + assert (path(ints), path(ints, False)) == (None, "c") + assert path(pa.StructArray.from_arrays([ints], fields=[x])) == "c.x" + hidden = pa.array([False, True, False]) + masked = pa.StructArray.from_arrays([ints], fields=[x], mask=hidden) + assert (path(masked), path(masked, False)) == (None, "c") + lists = _int_list([1, None], declared=True) + assert (path(lists), path(lists.slice(0, 1)), path(lists.slice(1))) == ( + "c[]", + None, + "c[]", + ) + assert path(_int_list([1, None], declared=False)) is None + # The pyarrow stubs do not know the ``type`` argument of ``from_arrays``. + arrow: Any = pa + fixed = arrow.FixedSizeListArray.from_arrays( + pa.array([1, None, 3, 4]), type=pa.list_(pa.field("item", pa.int64(), False), 2) + ) + assert (path(fixed), path(fixed.slice(1))) == ("c[]", None) + maps = arrow.MapArray.from_arrays( + pa.array([0, 1, 2], pa.int32()), + pa.array(["a", "b"]), + pa.array([1, None]), + type=arrow.map_(pa.string(), x), + ) + assert (path(maps), path(maps.slice(0, 1)), path(maps.slice(1))) == ( + "c{}", + None, + "c{}", + ) + # A key is never null, but a field nested in it can be (CodeRabbit on PR 539). + for declared in (True, False): + child = pa.field("x", pa.int64(), nullable=not declared) + keys = pa.StructArray.from_arrays([pa.array([1, None])], fields=[child]) + keyed = arrow.MapArray.from_arrays( + pa.array([0, 1, 2], pa.int32()), + keys, + pa.array([1, 2]), + type=arrow.map_(pa.field("key", keys.type, nullable=False), pa.int64()), + ) + found = "c{key}.x" if declared else None + assert path(keyed) == path(keyed.slice(1)) == found + assert path(keyed.slice(0, 1)) is None + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 5fdb3934a..42d3e46c2 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -23,9 +23,10 @@ from __future__ import annotations +import asyncio import re from collections.abc import Iterator -from typing import Any +from typing import Any, cast import pyarrow as pa import pyarrow.compute as pc @@ -35,10 +36,12 @@ # Imports under test — all of these will fail until the modules are created # --------------------------------------------------------------------------- +from orcapod.errors import OrcapodDatabaseWriteError, UnsupportedValueError from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.types import ColumnInfo from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.databases import ConnectorArrowDatabase +from orcapod.databases.sqlite_connector import SQLiteConnector # --------------------------------------------------------------------------- @@ -750,6 +753,67 @@ def test_same_path_always_yields_same_table_name(self, db): assert db._path_to_table_name(path) == db._path_to_table_name(path) +@pytest.mark.parametrize("invalid_first", [False, True]) +@pytest.mark.parametrize("order", [["id", "s", "y"], ["y", "id", "s"]]) +@pytest.mark.parametrize("run_async", [False, True]) +def test_validate_records_refuses_null_structs_without_discarding_valid_rows( + invalid_first: bool, order: list[str], run_async: bool +) -> None: + class RejectsNullStructs(MockDBConnector): + def validate_records(self, records: pa.Table) -> None: + super().validate_records(records) + if records["s"].null_count: + raise UnsupportedValueError("column 's' holds a null struct") + + path = ("t",) + valid_rows = [ + {"id": b"valid-1", "s": {"val": 10}, "y": 100}, + {"id": b"valid-2", "s": {"val": 20}, "y": 200}, + ] + invalid_rows = [ + {"id": b"bad-1", "s": {"val": 30}, "y": 300}, + {"id": b"bad-2", "s": None, "y": 400}, + ] + fields = { + "id": pa.field("id", pa.large_binary()), + "s": pa.field("s", pa.struct([("val", pa.int64())])), + "y": pa.field("y", pa.int64(), nullable=False), + } + valid = pa.Table.from_pylist(valid_rows, schema=pa.schema(fields.values())) + fields["y"] = fields["y"].with_nullable(True) + invalid = pa.Table.from_pylist( + invalid_rows, schema=pa.schema([fields[name] for name in order]) + ) + + connector = RejectsNullStructs() + + def check() -> None: + db = ConnectorArrowDatabase(connector) + for table in (invalid, valid) if invalid_first else (valid, invalid): + if table is invalid: + with pytest.raises(UnsupportedValueError, match="'s'.*null struct"): + db.add_records(path, table, record_id_column="id") + else: + db.add_records(path, table, record_id_column="id") + queued = db.get_all_records(path, record_id_column="id") + db.flush() + committed = ConnectorArrowDatabase(connector).get_all_records( + path, record_id_column="id" + ) + for rows in (queued, committed): + assert rows is not None + assert rows.sort_by("id").to_pylist() == valid_rows + assert not rows.schema.field("y").nullable + + async def on_loop() -> None: + check() + + if run_async: + asyncio.run(on_loop()) + else: + check() + + # =========================================================================== # 11. Flush behaviour # =========================================================================== @@ -785,6 +849,356 @@ def test_multiple_flushes_accumulate_records(self, db): assert result is not None assert result.num_rows == 2 + @pytest.mark.parametrize("reverse", [False, True]) + def test_failed_connector_batch_is_reported_and_removed( + self, monkeypatch: pytest.MonkeyPatch, reverse: bool + ) -> None: + connector = MockDBConnector() + db = ConnectorArrowDatabase(connector) + db.add_record(self.PATH, b"old", make_table(v=[1]), flush=True) + keys = [b"first", b"second", b"third"] + for key in reversed(keys) if reverse else keys: + db.add_record(self.PATH, key, make_table(v=[2]), skip_duplicates=True) + + def refuse_write(*args: object, **kwargs: object) -> None: + raise OSError("store unavailable") + + with monkeypatch.context() as patch: + patch.setattr(connector, "upsert_records", refuse_write) + with pytest.raises( + OrcapodDatabaseWriteError, match="store unavailable" + ) as raised: + db.flush() + assert all(repr(key) in str(raised.value) for key in keys) + db.flush() + rows = db.get_all_records(self.PATH, record_id_column="id") + assert rows is not None + assert rows.to_pylist() == [{"id": b"old", "v": 1}] + db.add_record(self.PATH, b"old", make_table(v=[99]), flush=True) + stored = ConnectorArrowDatabase(connector).get_all_records( + self.PATH, record_id_column="id" + ) + assert stored is not None + assert stored.to_pylist() == [{"id": b"old", "v": 99}] + + @staticmethod + def _stored_values( + connector: DBConnectorProtocol, path: tuple[str, ...] + ) -> dict[bytes, int]: + rows = ConnectorArrowDatabase(connector).get_all_records( + path, record_id_column="id" + ) + return {} if rows is None else {row["id"]: row["v"] for row in rows.to_pylist()} + + @pytest.mark.parametrize("skip_first", [False, True]) + def test_a_skip_batch_does_not_change_the_policy_of_an_ordinary_write( + self, skip_first: bool + ) -> None: + """Batches of different write policies are never written as one: the + ordinary overwrite of a stored key is not dropped (ITL-1381, round 5).""" + with SQLiteConnector(":memory:") as connector: + db = ConnectorArrowDatabase(connector) + db.add_record(self.PATH, b"existing", make_table(v=[1]), flush=True) + db.add_record(self.PATH, b"kept", make_table(v=[5]), flush=True) + writes = [ + lambda: db.add_record(self.PATH, b"existing", make_table(v=[2])), + lambda: db.add_records( + self.PATH, + pa.table( + { + "id": pa.array([b"kept", b"new"], type=pa.large_binary()), + "v": pa.array([6, 3], type=pa.int64()), + } + ), + record_id_column="id", + skip_duplicates=True, + ), + ] + for write in reversed(writes) if skip_first else writes: + write() + db.flush() + assert self._stored_values(connector, self.PATH) == { + b"existing": 2, + b"kept": 5, + b"new": 3, + } + + @staticmethod + def _mixed_policies(db: ConnectorArrowDatabase, path: tuple[str, ...]) -> None: + """Queue one ordinary row and one skip_duplicates row for one table.""" + db.add_record(path, b"plain", make_table(v=[1])) + db.add_record(path, b"skipping", make_table(v=[2]), skip_duplicates=True) + + @pytest.mark.parametrize( + "where", ["pyarrow.compute.is_in", "PendingCommits._select"] + ) + def test_an_interrupt_while_splitting_by_policy_leaves_the_queue_whole( + self, monkeypatch: pytest.MonkeyPatch, where: str + ) -> None: + """Only a batch whose write was attempted leaves the queue: an interrupt + before the first policy batch is sent keeps every row queued + (ITL-1381, round 5).""" + from orcapod.databases._pending_commits import PendingCommits + + with SQLiteConnector(":memory:") as connector: + db = ConnectorArrowDatabase(connector) + self._mixed_policies(db, self.PATH) + db.add_record(("other", "v1"), b"o", make_table(v=[3])) + interrupted: list[str] = [] + + def interrupt_once(original: Any) -> Any: + def wrapped(*args: Any, **kwargs: Any) -> Any: + if not interrupted: + interrupted.append(where) + raise KeyboardInterrupt + return original(*args, **kwargs) + + return wrapped + + with monkeypatch.context() as patch: + patch.setattr(pc, "is_in", interrupt_once(pc.is_in)) + patch.setattr( + PendingCommits, "_select", interrupt_once(PendingCommits._select) + ) + with pytest.raises(KeyboardInterrupt): + db.flush() + assert interrupted + db.flush() + assert self._stored_values(connector, self.PATH) == { + b"plain": 1, + b"skipping": 2, + } + assert self._stored_values(connector, ("other", "v1")) == {b"o": 3} + + def test_an_interrupt_between_any_two_lines_of_a_flush_loses_no_row( + self, + ) -> None: + """A KeyboardInterrupt injected (by a line trace) between any two statements + of the queue bookkeeping or of a table's flush leaves each queued table's + rows and ids consistent; every row is then stored once, or named as removed + (ITL-1381, round 5). A batch leaves the queue before its write is tried, so + none is ever written twice. + + Interrupts are injected between statements only, which is N58's scope: an + interrupt inside a single statement is out of scope. A repeated line event + of one line (a comprehension's loop) is inside a statement, and on Python + 3.12 an exception a trace function raises there skips the frame's + ``except`` handlers, which a real ``KeyboardInterrupt`` does not.""" + import sys + from pathlib import Path + + from orcapod.databases import _pending_commits + from orcapod.databases import connector_arrow_database as module + + traced_files = {_pending_commits.__file__, module.__file__} + traced_functions = { + "_flush_by_key", + "_commit_batch", + "_discard_attempted", + } + + class LoggingConnector(SQLiteConnector): + def __init__(self) -> None: + super().__init__(":memory:") + self.written: list[bytes] = [] + + def upsert_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool = False, + ) -> None: + super().upsert_records( + table_name, records, id_column, skip_existing=skip_existing + ) + self.written.extend(cast(list[bytes], records[id_column].to_pylist())) + + expected = {b"plain": 1, b"skipping": 2, b"o": 3} + position = 0 + while True: + position += 1 + connector = LoggingConnector() + try: + db = ConnectorArrowDatabase(connector) + self._mixed_policies(db, self.PATH) + db.add_record(("other", "v1"), b"o", make_table(v=[3])) + lines = 0 + last_line: dict[int, int] = {} + + def trace(frame: Any, event: str, arg: Any) -> Any: + nonlocal lines + code = frame.f_code + if code.co_filename not in traced_files or ( + Path(code.co_filename).name != "_pending_commits.py" + and code.co_name not in traced_functions + ): + return None + # Between statements only: a repeated line event of one line + # is inside a statement (a comprehension's loop), out of + # scope (N58), and there an exception a trace function raises + # skips the frame's handlers on Python 3.12. + if event == "line" and last_line.get(id(frame)) != frame.f_lineno: + last_line[id(frame)] = frame.f_lineno + lines += 1 + if lines == position: + raise KeyboardInterrupt + return trace + + notes = "" + sys.settrace(trace) + try: + db.flush() + except KeyboardInterrupt as interrupt: + notes = "\n".join(getattr(interrupt, "__notes__", [])) + finally: + sys.settrace(None) + if lines < position: + break # Every line was interrupted once. + for key, table in db._pending_batches.items(): + queued = set( + table[ConnectorArrowDatabase.RECORD_ID_COLUMN].to_pylist() + ) + assert queued == set(db._pending_record_ids[key]), position + db.flush() + assert len(connector.written) == len(set(connector.written)), position + stored = self._stored_values(connector, self.PATH) + stored |= self._stored_values(connector, ("other", "v1")) + for key, value in expected.items(): + assert stored.get(key) == value or repr(key) in notes, ( + position, + key, + ) + finally: + connector.close() + assert position > 20 + + def test_each_policy_batch_is_checked_against_the_schema_guard(self) -> None: + """The table's schema guard checks every write of a split flush, not only + the first (ITL-1381, round 5).""" + checked: list[pa.Schema] = [] + + def refuse(schema: pa.Schema) -> None: + checked.append(schema) + raise ValueError("schema refused") + + with SQLiteConnector(":memory:") as connector: + db = ConnectorArrowDatabase(connector) + with db.guard_table_schema(self.PATH, refuse): + self._mixed_policies(db, self.PATH) + with pytest.raises( + OrcapodDatabaseWriteError, match="schema refused" + ) as raised: + db.flush() + assert len(checked) == 2 + assert "second batch also failed" in "\n".join( + getattr(raised.value, "__notes__", []) + ) + assert ConnectorArrowDatabase(connector).get_all_records(self.PATH) is None + + def test_an_interrupt_in_the_cleanup_of_a_failed_commit_never_replays_it( + self, + ) -> None: + """A connector that commits and then raises, and a KeyboardInterrupt at the + start of the failure cleanup: the batch already left the queue before its + write was tried, so it is never written again (ITL-1381, round 5, N32).""" + import sys + + from orcapod.databases import connector_arrow_database as module + + class CommitsThenRaises(SQLiteConnector): + def __init__(self) -> None: + super().__init__(":memory:") + self.written: list[int] = [] + self.fail = True + + def upsert_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool = False, + ) -> None: + super().upsert_records( + table_name, records, id_column, skip_existing=skip_existing + ) + self.written.extend(cast(list[int], records["v"].to_pylist())) + if self.fail: + self.fail = False + raise RuntimeError("refused after commit") + + # The failure cleanup's first line. + cleanup = {"_discard_attempted"} + + def trace(frame: Any, event: str, arg: Any) -> Any: + code = frame.f_code + if code.co_filename == module.__file__ and code.co_name in cleanup: + if event == "line": + raise KeyboardInterrupt + return trace + return None + + connector = CommitsThenRaises() + try: + db = ConnectorArrowDatabase(connector) + db.add_record(self.PATH, b"key", make_table(v=[1])) + sys.settrace(trace) + try: + with pytest.raises(KeyboardInterrupt): + db.flush() + finally: + sys.settrace(None) + ConnectorArrowDatabase(connector).add_record( + self.PATH, b"key", make_table(v=[77]), flush=True + ) + db.flush() + assert connector.written == [1, 77] + assert self._stored_values(connector, self.PATH) == {b"key": 77} + finally: + connector.close() + + def test_a_flush_interrupted_after_its_commit_is_never_replayed(self) -> None: + """A BaseException during a flush removes the attempted batch as a + failure does, names its keys, and propagates (ITL-1381, round 5).""" + + class InterruptedAfterCommit(SQLiteConnector): + def __init__(self) -> None: + super().__init__(":memory:") + self.written: list[int] = [] + self.interrupt = True + + def upsert_records( + self, table_name, records, id_column, skip_existing=False + ): + super().upsert_records( + table_name, records, id_column, skip_existing=skip_existing + ) + self.written.extend(cast(list[int], records["v"].to_pylist())) + if self.interrupt: + self.interrupt = False + raise KeyboardInterrupt + + connector = InterruptedAfterCommit() + try: + db = ConnectorArrowDatabase(connector) + db.add_record(self.PATH, b"key", make_table(v=[1])) + with pytest.raises(KeyboardInterrupt) as raised: + db.flush() + assert any( + "flush/v1" in note and repr(b"key") in note + for note in getattr(raised.value, "__notes__", []) + ) + assert db.get_all_records(self.PATH) is not None + assert db._get_record_key(self.PATH) not in db._pending_batches + ConnectorArrowDatabase(connector).add_record( + self.PATH, b"key", make_table(v=[77]), flush=True + ) + db.flush() + assert connector.written == [1, 77] + assert self._stored_values(connector, self.PATH) == {b"key": 77} + finally: + connector.close() + def test_second_flush_on_existing_table_upserts(self, db): """Flushing the same path twice should not duplicate rows.""" db.add_record(self.PATH, b"u1", make_table(v=[1]), flush=True) @@ -815,7 +1229,7 @@ def test_flush_with_skip_duplicates_passes_skip_existing_to_connector( assert result is not None assert result["v"][0].as_py() == 1 # original preserved via skip_existing=True - def test_flush_schema_mismatch_raises_value_error(self, db): + def test_flush_schema_mismatch_reports_discarded_keys(self, db): """flush() must raise ValueError when the pending schema differs from the table already in the connector — before any data is written.""" db.add_record(("t",), b"a", make_table(v=[1]), flush=True) @@ -825,7 +1239,7 @@ def test_flush_schema_mismatch_raises_value_error(self, db): pa.table({"__record_id": pa.array([b"b"]), "x": pa.array([2])}), record_id_column="__record_id", ) - with pytest.raises(ValueError, match="Schema mismatch"): + with pytest.raises(OrcapodDatabaseWriteError, match="Schema mismatch"): db.flush() diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 900535e90..7d612efea 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -3,8 +3,10 @@ from __future__ import annotations +import asyncio import pathlib import socket +from collections.abc import Iterable, Iterator from typing import Any from unittest.mock import MagicMock, patch @@ -12,13 +14,129 @@ import pyarrow as pa import pytest +from orcapod.databases import ConnectorArrowDatabase from orcapod.databases.postgresql_connector import ( PostgreSQLConnector, _arrow_type_to_pg_sql, _coerce_pg_value, _pg_type_to_arrow, ) +from orcapod.errors import OrcapodDatabaseWriteError from orcapod.protocols.db_connector_protocol import DBConnectorProtocol +from orcapod.types import ColumnInfo + + +class _PostgreSQLTransaction: + """Track PostgreSQL's aborted transaction and durable writes.""" + + def __init__(self) -> None: + self.committed = {b"seed": 1} + self.pending = self.committed.copy() + self.aborted = False + self.commands: list[str] = [] + + def execute(self, sql: str, row: tuple[bytes, int] | None = None) -> None: + assert not self.aborted + if sql.startswith("INSERT "): + assert row is not None + key, value = row + if value < 0: + self.aborted = True + raise psycopg.errors.CheckViolation("value must be positive") + self.pending[key] = value + else: + assert sql.startswith("CREATE TABLE IF NOT EXISTS") + self.commands.append(sql) + + def executemany(self, sql: str, rows: Iterable[tuple[bytes, int]]) -> None: + for row in rows: + self.execute(sql, row) + + def commit(self) -> None: + assert not self.aborted + self.committed = self.pending.copy() + self.commands.append("COMMIT") + + def rollback(self) -> None: + self.aborted = False + self.pending = self.committed.copy() + self.commands.append("ROLLBACK") + + def read(self) -> Iterator[pa.RecordBatch]: + yield pa.RecordBatch.from_arrays( + [ + pa.array(list(self.committed), pa.large_binary()), + pa.array(list(self.committed.values()), pa.int64()), + ], + names=["__record_id", "v"], + ) + + +@pytest.mark.parametrize("bad_first", [False, True]) +@pytest.mark.parametrize("on_event_loop", [False, True]) +def test_postgresql_check_refusal_rolls_back_and_names_the_whole_batch( + bad_first: bool, on_event_loop: bool +) -> None: + transaction = _PostgreSQLTransaction() + connection = MagicMock() + cursor = connection.cursor.return_value.__enter__.return_value + cursor.execute.side_effect = transaction.execute + cursor.executemany.side_effect = transaction.executemany + connection.commit.side_effect = transaction.commit + connection.rollback.side_effect = transaction.rollback + with patch("psycopg.connect", return_value=connection): + connector = PostgreSQLConnector("dbname=test") + + with ( + connector, + patch.object(connector, "get_table_names", return_value=["t"]), + patch.object( + connector, + "get_column_info", + return_value=[ + ColumnInfo("__record_id", pa.large_binary(), nullable=False), + ColumnInfo("v", pa.int64(), nullable=True), + ], + ), + patch.object( + connector, "iter_batches", side_effect=lambda *args: transaction.read() + ), + ): + writer = ConnectorArrowDatabase(connector) + reader = ConnectorArrowDatabase(connector) + + def check() -> None: + left = pa.table({"id": [b"bad-1", b"good-1"], "v": [-1, 11]}) + right = pa.table({"id": [b"good-2", b"bad-2"], "v": [12, -2]}) + for batch in (left, right) if bad_first else (right, left): + writer.add_records(("t",), batch, record_id_column="id") + with pytest.raises( + OrcapodDatabaseWriteError, match="must be positive" + ) as refused: + writer.flush() + for handle in (reader, writer): + rows = handle.get_all_records(("t",), record_id_column="id") + assert rows is not None + assert rows.to_pylist() == [{"id": b"seed", "v": 1}] + assert "'t'" in str(refused.value) + assert all( + repr(key) in str(refused.value) + for key in (b"bad-1", b"bad-2", b"good-1", b"good-2") + ) + assert transaction.commands.count("ROLLBACK") == 1 + assert transaction.commands[-1] == "ROLLBACK" + cursor.executemany.assert_called_once() + before = transaction.commands.copy() + writer.flush() + assert transaction.commands == before + + async def on_loop() -> None: + check() + + if on_event_loop: + asyncio.run(on_loop()) + else: + check() class TestPgTypeToArrow: diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index ae5436de4..2da4c790a 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -30,6 +30,7 @@ import pyarrow as pa import pytest +from orcapod.errors import OrcapodDatabaseWriteError from orcapod.databases import ConnectorArrowDatabase, PostgreSQLConnector from orcapod.types import ColumnInfo @@ -474,7 +475,7 @@ def test_schema_mismatch_raises(self, db: ConnectorArrowDatabase) -> None: db.add_record(("fn", "mismatch"), record_id="r1", record=r1, flush=True) r2 = pa.table({"x": pa.array([2.0], type=pa.float64())}) db.add_record(("fn", "mismatch"), record_id="r2", record=r2) - with pytest.raises(ValueError, match="Schema mismatch"): + with pytest.raises(OrcapodDatabaseWriteError, match="Schema mismatch"): db.flush() diff --git a/tests/test_databases/test_sqlite_connector.py b/tests/test_databases/test_sqlite_connector.py index d3ca2bcdd..18f334755 100644 --- a/tests/test_databases/test_sqlite_connector.py +++ b/tests/test_databases/test_sqlite_connector.py @@ -2,6 +2,8 @@ from __future__ import annotations +import re +import sqlite3 from collections.abc import Iterator from pathlib import Path @@ -33,6 +35,13 @@ def connector() -> Iterator[SQLiteConnector]: pass +def _execute(connector: SQLiteConnector, sql: str) -> sqlite3.Cursor: + """Run SQL on the connector's own connection, as a test needs to.""" + conn = connector._conn # pyright: ignore[reportPrivateUsage] + assert conn is not None + return conn.execute(sql) + + # --------------------------------------------------------------------------- # Type helpers # --------------------------------------------------------------------------- @@ -104,6 +113,26 @@ def test_unsupported_type_raises_instead_of_text(self): _arrow_type_to_sqlite_sql(arrow_type) +class TestSqliteVersion: + @pytest.mark.parametrize("version", [(3, 23, 1), (2, 99, 0)]) + def test_an_sqlite_library_without_upsert_is_refused( + self, monkeypatch: pytest.MonkeyPatch, version: tuple[int, int, int] + ) -> None: + text = ".".join(map(str, version)) + monkeypatch.setattr(sqlite3, "sqlite_version_info", version) + monkeypatch.setattr(sqlite3, "sqlite_version", text) + with pytest.raises(RuntimeError, match=rf"3\.24\.0.*{re.escape(text)}"): + SQLiteConnector(":memory:") + + @pytest.mark.parametrize("version", [(3, 24, 0), (3, 45, 1)]) + def test_an_sqlite_library_with_upsert_is_accepted( + self, monkeypatch: pytest.MonkeyPatch, version: tuple[int, int, int] + ) -> None: + monkeypatch.setattr(sqlite3, "sqlite_version_info", version) + monkeypatch.setattr(sqlite3, "sqlite_version", ".".join(map(str, version))) + SQLiteConnector(":memory:").close() + + class TestSQLiteConnectorScaffold: def test_isinstance_dbconnector_protocol(self) -> None: connector = SQLiteConnector(":memory:") @@ -366,6 +395,167 @@ def test_skip_existing_keeps_original(self, connector: SQLiteConnector) -> None: ) assert cursor.fetchone()[0] == 1.0 + @pytest.mark.parametrize("bad_first", [False, True]) + def test_failed_upsert_rolls_back_the_whole_batch( + self, tmp_path: Path, bad_first: bool + ) -> None: + db_path = str(tmp_path / "store.db") + with SQLiteConnector(db_path) as writer, SQLiteConnector(db_path) as reader: + writer.create_table_if_not_exists( + "t", + [ + ColumnInfo("__record_id", pa.large_string(), nullable=False), + ColumnInfo("value", pa.float64(), nullable=False), + ], + "__record_id", + ) + seed = self._make_table(["changed"], [1.0]) + writer.upsert_records("t", seed, "__record_id") + ids = ( + ["bad", "changed", "later"] + if bad_first + else ["changed", "bad", "later"] + ) + values = {"changed": 2.0, "bad": None, "later": 3.0} + with pytest.raises(sqlite3.IntegrityError, match="NOT NULL"): + writer.upsert_records( + "t", + self._make_table(ids, [values[row_id] for row_id in ids]), + "__record_id", + ) + committed = pa.Table.from_batches( + list(reader.iter_batches('SELECT * FROM "t"')) + ) + assert committed.to_pylist() == seed.to_pylist() + reader.upsert_records( + "t", self._make_table(["changed"], [77.0]), "__record_id" + ) + committed = pa.Table.from_batches( + list(writer.iter_batches('SELECT * FROM "t"')) + ) + assert committed["value"].to_pylist() == [77.0] + + @staticmethod + def _constrained_table(connector: SQLiteConnector) -> None: + """A table with a CHECK and a UNIQUE constraint besides the id (ITL-1490).""" + _execute( + connector, + 'CREATE TABLE "c" ("__record_id" TEXT PRIMARY KEY, ' + '"value" REAL NOT NULL CHECK ("value" >= 0), "name" TEXT UNIQUE)', + ) + + @staticmethod + def _constrained_rows( + ids: list[str], values: list[float], names: list[str] + ) -> pa.Table: + return pa.table( + { + "__record_id": pa.array(ids, type=pa.large_string()), + "value": pa.array(values, type=pa.float64()), + "name": pa.array(names, type=pa.large_string()), + } + ) + + def _stored(self, connector: SQLiteConnector) -> list[tuple[object, ...]]: + rows = _execute( + connector, + 'SELECT "__record_id", "value", "name" FROM "c" ORDER BY "__record_id"', + ).fetchall() + return [tuple(row) for row in rows] + + @pytest.mark.parametrize("skip_existing", [False, True]) + @pytest.mark.parametrize("bad_first", [False, True]) + def test_check_violation_raises_whatever_the_conflict_policy( + self, connector: SQLiteConnector, skip_existing: bool, bad_first: bool + ) -> None: + """Conflict handling covers the id only: a CHECK violation is never + swallowed, and its valid sibling is not committed (ITL-1490).""" + self._constrained_table(connector) + ids, values, names = ["bad", "good"], [-1.0, 1.0], ["x", "y"] + if not bad_first: + ids, values, names = ids[::-1], values[::-1], names[::-1] + with pytest.raises(sqlite3.IntegrityError, match="CHECK"): + connector.upsert_records( + "c", + self._constrained_rows(ids, values, names), + "__record_id", + skip_existing=skip_existing, + ) + assert self._stored(connector) == [] + + @pytest.mark.parametrize("skip_existing", [False, True]) + def test_unique_collision_on_another_column_raises_and_deletes_nothing( + self, connector: SQLiteConnector, skip_existing: bool + ) -> None: + """A new id colliding on a non-id UNIQUE column raises; the stored row + it collides with is kept (ITL-1490).""" + self._constrained_table(connector) + connector.upsert_records( + "c", + self._constrained_rows(["a", "b"], [1.0, 2.0], ["x", "y"]), + "__record_id", + ) + with pytest.raises(sqlite3.IntegrityError, match="UNIQUE"): + connector.upsert_records( + "c", + self._constrained_rows(["new", "b"], [3.0, 5.0], ["x", "z"]), + "__record_id", + skip_existing=skip_existing, + ) + assert self._stored(connector) == [("a", 1.0, "x"), ("b", 2.0, "y")] + + @pytest.mark.parametrize("skip_existing", [False, True]) + def test_id_conflicts_follow_the_policy_in_place( + self, connector: SQLiteConnector, skip_existing: bool + ) -> None: + """An id conflict updates the row in place, or keeps it with + skip_existing, and leaves the other rows alone (ITL-1490).""" + self._constrained_table(connector) + connector.upsert_records( + "c", + self._constrained_rows(["a", "b"], [1.0, 2.0], ["x", "y"]), + "__record_id", + ) + connector.upsert_records( + "c", + self._constrained_rows(["b", "c"], [9.0, 3.0], ["w", "z"]), + "__record_id", + skip_existing=skip_existing, + ) + updated = ("b", 2.0, "y") if skip_existing else ("b", 9.0, "w") + assert self._stored(connector) == [("a", 1.0, "x"), updated, ("c", 3.0, "z")] + + @pytest.mark.parametrize("skip_existing", [False, True]) + def test_a_row_colliding_on_its_id_and_another_unique_column( + self, connector: SQLiteConnector, skip_existing: bool + ) -> None: + """With skip_existing, a row whose id exists is skipped, whatever else it + collides on; updated in place, its other UNIQUE value raises. Nothing is + deleted either way (ITL-1490).""" + self._constrained_table(connector) + connector.upsert_records( + "c", + self._constrained_rows(["a", "b"], [1.0, 2.0], ["x", "y"]), + "__record_id", + ) + colliding = self._constrained_rows(["b"], [9.0], ["x"]) + if skip_existing: + connector.upsert_records("c", colliding, "__record_id", skip_existing=True) + else: + with pytest.raises(sqlite3.IntegrityError, match="UNIQUE"): + connector.upsert_records("c", colliding, "__record_id") + assert self._stored(connector) == [("a", 1.0, "x"), ("b", 2.0, "y")] + + def test_a_table_holding_only_the_id_skips_conflicts( + self, connector: SQLiteConnector + ) -> None: + _execute(connector, 'CREATE TABLE "o" ("__record_id" TEXT PRIMARY KEY)') + rows = pa.table({"__record_id": pa.array(["a"], type=pa.large_string())}) + connector.upsert_records("o", rows, "__record_id") + connector.upsert_records("o", rows, "__record_id") + stored = _execute(connector, 'SELECT * FROM "o"').fetchall() + assert [tuple(row) for row in stored] == [("a",)] + def test_raises_on_invalid_table_name(self, connector: SQLiteConnector) -> None: records = self._make_table(["a"], [1.0]) with pytest.raises(ValueError, match="double-quote"): diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index 6720ea0cb..b109e6bd0 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -7,6 +7,7 @@ import pyarrow as pa import pytest +from orcapod.errors import OrcapodDatabaseWriteError from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector @@ -105,7 +106,7 @@ def test_second_flush_schema_mismatch_raises( # Incompatible schema: different column type for 'x' r2 = pa.table({"x": pa.array([2.0], type=pa.float64())}) db.add_record(("fn", "test"), record_id="r2", record=r2) - with pytest.raises(ValueError, match="Schema mismatch"): + with pytest.raises(OrcapodDatabaseWriteError, match="Schema mismatch"): db.flush() def test_get_records_by_ids(self, db: ConnectorArrowDatabase) -> None: diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 614e9900e..417045856 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1129,6 +1129,17 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: queued order at a flush). A table keeps the column order of its first write. An append that also adds, omits or retypes a column keeps each database's own rule. The order of a struct's fields is not covered: a struct whose fields are in another order is another type here. + +When two connector database handles write the same record key, the last flush to +commit that key wins. Use `skip_duplicates=True` to keep an already stored key. + +SQLite and PostgreSQL roll back a failed bulk upsert. If a flush fails for a +table, its attempted batch leaves the queue along with records guarded by results +in that batch. The error names the affected tables, every removed key, and the +reason for the failure. Independent tables can still commit during the same +flush. Submit a new batch to try those rows again. A known violation of a stored +`NOT NULL` constraint is refused at enqueue. PostgreSQL also refuses text +containing NUL at enqueue. """