From 9c08ddcbeba3374f48e6a7dc73391e4a1fcdc166 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 09:31:47 -0800 Subject: [PATCH 01/16] fix(databases): queued batches of differing nullability combine on a connector database (ITL-1381) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1381.md | 6 ++ .../databases/connector_arrow_database.py | 8 +- tests/test_databases/test_append_by_name.py | 79 ++++++++++++++++++- 3 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 changelog.d/ITL-1381.md diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md new file mode 100644 index 000000000..bfe6de93c --- /dev/null +++ b/changelog.d/ITL-1381.md @@ -0,0 +1,6 @@ +### Fixed + +- A connector database (SQLite, PostgreSQL, SpiralDB) 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. A read before the flush + already combined stored and queued rows that differ that way. (ITL-1381) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..ce3b706fa 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -58,8 +58,8 @@ def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: 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.""" @@ -523,8 +523,10 @@ def add_records( if existing_pending is None: self._pending_batches[record_key] = records else: + # Two queued batches may declare a column's nullability differently, as + # stored and queued rows may (ITL-1381). self._pending_batches[record_key] = pa.concat_tables( - [existing_pending, records] + _alike([existing_pending, records]) ) self._pending_record_ids[record_key].update( cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index c3f05014c..0c6890725 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -18,7 +18,7 @@ import sqlite3 import uuid from collections.abc import Iterator -from contextlib import ExitStack +from contextlib import ExitStack, contextmanager from pathlib import Path from typing import Any, cast from unittest.mock import patch @@ -1051,6 +1051,83 @@ 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"))) + else: + with open_database(kind, tmp_path) as db: + yield db + + +CONNECTOR_DATABASES = ("SQLite", "SQLite, key read NOT NULL", "SpiralDB") + + +@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]) + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── From f8cc49269559e1659b08cac8520fd62e3f3676a7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 09:49:45 -0800 Subject: [PATCH 02/16] fix(databases): refuse a queued batch that loosens a stored NOT NULL column (ITL-1381) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1381.md | 4 +- .../databases/connector_arrow_database.py | 36 ++++++++++++++++- tests/test_databases/test_append_by_name.py | 40 +++++++++++++++++++ 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index bfe6de93c..487ad43ab 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -2,5 +2,7 @@ - A connector database (SQLite, PostgreSQL, SpiralDB) 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. A read before the flush + differently; the combined batch declares the column nullable. Where the + stored column is `NOT NULL`, the second batch is refused when it is queued, with an error + naming the column, and the rows queued before it are kept. A read before the flush already combined stored and queued rows that differ that way. (ITL-1381) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index ce3b706fa..f82af357d 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -508,8 +508,6 @@ 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] if conflicts: @@ -525,9 +523,13 @@ def add_records( else: # 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) self._pending_batches[record_key] = pa.concat_tables( _alike([existing_pending, records]) ) + if skip_duplicates: + # Mark this pending slot so flush() uses skip_existing=True. + self._pending_skip_existing[record_key] = True self._pending_record_ids[record_key].update( cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) ) @@ -626,6 +628,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. diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 0c6890725..63268d25c 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -37,6 +37,7 @@ from orcapod.databases.utils import in_held_column_order from orcapod.errors import ( InputValidationError, + NullabilityRecordMismatchError, UnstorableColumnError, ) from tests.test_databases.type_matrix import open_database @@ -1128,6 +1129,45 @@ def test_queued_batches_of_differing_nullability_are_one_batch( _check_lookups(db, [1, 2, 3]) +@pytest.mark.parametrize("kind", ["SQLite", "SpiralDB"]) +@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, kind: str, 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(kind, 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] + given = _given_order(kind, order) + _check(db.get_all_records(PATH, record_id_column=ID), given, ns) + if stored and not first and kind == "SpiralDB": + # The queued rows themselves are what SpiralDB refuses (ITL-936). + with pytest.raises(NullabilityRecordMismatchError): + db.flush() + ns = [1] + else: + db.flush() + _check(db.get_all_records(PATH, record_id_column=ID), given, ns) + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── From e2966a642e06c4a7b0454fc830ab5bedb78fabd4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:34:48 -0800 Subject: [PATCH 03/16] fix(databases): check queued rows against their own declared nullability (ITL-1381) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1381.md | 4 +- .../databases/connector_arrow_database.py | 9 + src/orcapod/databases/utils.py | 71 +++++++ tests/test_databases/test_append_by_name.py | 180 +++++++++++++++++- 4 files changed, 262 insertions(+), 2 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index 487ad43ab..1dd33e2d8 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -4,5 +4,7 @@ when rows are queued for a table whose queued rows declare a column's nullability differently; the combined batch declares the column nullable. Where the stored column is `NOT NULL`, the second batch is refused when it is queued, with an error - naming the column, and the rows queued before it are kept. A read before the flush + naming the column, and the rows queued before it are kept. + 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 read before the flush already combined stored and queued rows that differ that way. (ITL-1381) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index f82af357d..b3a3f90cb 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -30,12 +30,14 @@ 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, UnstorableColumnError, @@ -476,6 +478,13 @@ def add_records( ) records = normalize_table_to_large_types(records, keep_null=True) self._connector.validate_records(records) + # Against the schema these rows were given with: combined with queued rows + # that declare the column nullable, the null would be stored (ITL-1381). + null_path = declared_null_path(records) + if null_path is not None: + raise NullInNonNullableColumnError( + null_path, table="/".join(self._path_prefix + record_path) + ) record_key = self._get_record_key(record_path) # Columns match by name: rows with the held columns in another order are diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 789f1b076..5add45d05 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -560,6 +560,77 @@ 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.""" + 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): + return [("{}", 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) + ): + 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 == "{}": + # ``MapArray.items`` ignores a slice; the list over its offsets does not. + below = [ + pa.ListArray.from_arrays(a.offsets, 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/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 63268d25c..3dc05ec6c 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -14,6 +14,7 @@ from __future__ import annotations +import asyncio import os import sqlite3 import uuid @@ -34,10 +35,11 @@ SpiralDBConnector, 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, NullabilityRecordMismatchError, + NullInNonNullableColumnError, UnstorableColumnError, ) from tests.test_databases.type_matrix import open_database @@ -1168,6 +1170,182 @@ def test_a_refused_batch_leaves_the_queued_rows_to_be_flushed( _check(db.get_all_records(PATH, record_id_column=ID), given, ns) +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], + *[("SpiralDB", 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) + assert list(db._pending_batches["/".join(PATH)]["__record_id"].to_pylist()) == [ + b"r2" + ] + + +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{}", + ) + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── From 369b777a067b4b2561b5f40055e80d0a397b3044 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:55:45 -0800 Subject: [PATCH 04/16] fix(databases): the declared-null rule looks inside map keys (ITL-1381) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/utils.py | 18 +++++++++++++----- tests/test_databases/test_append_by_name.py | 13 +++++++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 5add45d05..3503b3da0 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -589,13 +589,17 @@ def _declares_non_null(field: "pa.Field[Any]") -> bool: 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.""" + 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): - return [("{}", data_type.item_field)] + # 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) @@ -618,10 +622,14 @@ def _declared_null_below( for index, (segment, child) in enumerate(_child_fields(field.type)): if segment == "[]": below = [a.flatten() for a in arrays] - elif segment == "{}": - # ``MapArray.items`` ignores a slice; the list over its offsets does not. + 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.items).flatten() for a in arrays + 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] diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 3dc05ec6c..596586d60 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -1344,6 +1344,19 @@ def path(array: Any, nullable: bool = True) -> str | None: 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) ────────────────────────── From 74eafc49fa08f2f0ce3791bf1ee72194064c9442 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 11:00:50 -0800 Subject: [PATCH 05/16] fix(databases): check declared nulls before the rows are normalized (ITL-1381) Co-Authored-By: Claude Opus 5.5 --- .../databases/connector_arrow_database.py | 5 ++-- src/orcapod/databases/utils.py | 2 ++ tests/test_databases/test_append_by_name.py | 29 +++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b3a3f90cb..2a6544703 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -476,15 +476,16 @@ def add_records( self._require_table_name( self._path_to_table_name(self._path_prefix + record_path) ) - records = normalize_table_to_large_types(records, keep_null=True) - self._connector.validate_records(records) # 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) record_key = self._get_record_key(record_path) # Columns match by name: rows with the held columns in another order are diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 3503b3da0..4a4afb7c2 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -604,6 +604,8 @@ def _child_fields(data_type: "pa.DataType") -> "list[tuple[str, pa.Field[Any]]]" 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 [] diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 596586d60..a4c8c6a3e 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -1303,6 +1303,35 @@ def test_a_postgresql_database_checks_the_declaration_before_anything_is_sent( ] +@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") + pending = db._pending_batches.get("/".join(PATH)) + held = [] if pending is None else pending["__record_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.""" From 4f2c3544f505f11bb426b2cbd3a7bed1fb7018a9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 01:06:34 -0800 Subject: [PATCH 06/16] fix(databases): retain queued rows when a connector flush fails (ITL-1381) --- changelog.d/ITL-1381.md | 8 +- .../databases/connector_arrow_database.py | 13 ++- tests/test_databases/test_append_by_name.py | 36 +++---- .../test_connector_arrow_database.py | 96 +++++++++++++++++++ 4 files changed, 124 insertions(+), 29 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index 1dd33e2d8..d917b8179 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -1,10 +1,12 @@ ### Fixed -- A connector database (SQLite, PostgreSQL, SpiralDB) no longer fails with `ArrowInvalid` +- 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. Where the stored column is `NOT NULL`, the second batch is refused when it is queued, with an error naming the column, and the rows queued before it are kept. 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 read before the flush - already combined stored and queued rows that differ that way. (ITL-1381) + raise `NullInNonNullableColumnError` when they are queued, before anything is stored. + If the connector rejects a flush, the attempted rows remain queued for retry. + A read before the flush already combined stored and queued rows that differ that way. + (ITL-1381) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 2a6544703..80f3cd229 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -761,7 +761,7 @@ def guard_table_schema( ) def flush(self) -> None: - """Commit all pending batches to the connector via upsert.""" + """Commit pending batches via upsert, retaining a rejected batch for retry.""" for record_key in list(self._pending_batches): self._flush_by_key(record_key) @@ -783,12 +783,11 @@ def _flush_by_key(self, record_key: str) -> None: ready = self._pending_commits.take_ready(record_key) if ready is None: return - pending, ids = ready + batch, ids = ready + pending = batch 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: self._require_table_name(table_name) @@ -842,12 +841,16 @@ def _fmt(cols: dict) -> str: skip_existing=skip_existing, ) except BaseException: + # Keep the original queued order when the connector needed stored order. + # A rejected write cannot distinguish valid rows from the rest of the batch. + self._pending_commits.restore(record_key, batch, ids) self._pending_commits.finish(record_key, committed=False) raise else: self._pending_commits.finish(record_key, committed=True) - finally: self._pending_commits.forget(record_key, ids) + if record_key not in self._pending_batches: + self._pending_skip_existing.pop(record_key, None) # ── Read methods ────────────────────────────────────────────────────────── diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index afcdc2daa..69204423a 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -37,10 +37,10 @@ from orcapod.databases.utils import declared_null_path, in_held_column_order from orcapod.errors import ( InputValidationError, - NullabilityRecordMismatchError, NullInNonNullableColumnError, UnstorableColumnError, ) +from tests.test_databases.test_connector_arrow_database import MockDBConnector from tests.test_databases.type_matrix import open_database PATH = ("t",) @@ -1057,12 +1057,14 @@ def _check_lookups(db: Any, ns: list[int]) -> None: 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", "SpiralDB") +CONNECTOR_DATABASES = ("SQLite", "SQLite, key read NOT NULL") @pytest.mark.parametrize("kind", CONNECTOR_DATABASES) @@ -1107,18 +1109,17 @@ def test_queued_batches_of_differing_nullability_are_one_batch( _check_lookups(db, [1, 2, 3]) -@pytest.mark.parametrize("kind", ["SQLite", "SpiralDB"]) @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, kind: str, stored: bool, first: bool, skip: bool + 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(kind, tmp_path) as db: + 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) @@ -1134,16 +1135,9 @@ def test_a_refused_batch_leaves_the_queued_rows_to_be_flushed( else: db.add_records(PATH, second, record_id_column=ID, skip_duplicates=skip) ns = [1, 2, 3] - given = _given_order(kind, order) - _check(db.get_all_records(PATH, record_id_column=ID), given, ns) - if stored and not first and kind == "SpiralDB": - # The queued rows themselves are what SpiralDB refuses (ITL-936). - with pytest.raises(NullabilityRecordMismatchError): - db.flush() - ns = [1] - else: - db.flush() - _check(db.get_all_records(PATH, record_id_column=ID), given, ns) + _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 _int_list(values: list[int | None], *, declared: bool) -> Any: @@ -1198,7 +1192,7 @@ def _null_case(place: str, n: int, *, null: bool, not_null: bool) -> pa.Table: } NULL_CASES = [ *[(kind, "column") for kind in CONNECTOR_DATABASES], - *[("SpiralDB", place) for place in NULL_PATHS if place != "column"], + *[("writable mock", place) for place in NULL_PATHS if place != "column"], ] @@ -1274,9 +1268,9 @@ def test_a_postgresql_database_checks_the_declaration_before_anything_is_sent( _add(db, violating) if violating_first: _add(db, valid) - assert list(db._pending_batches["/".join(PATH)]["__record_id"].to_pylist()) == [ - b"r2" - ] + 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"]) @@ -1303,8 +1297,8 @@ def rows(n: int, *, null: bool) -> pa.Table: with pytest.raises(NullInNonNullableColumnError) as refused: _add(db, rows(3, null=True)) assert refused.value.column == ("v" if null_in == "v" else "__record_id") - pending = db._pending_batches.get("/".join(PATH)) - held = [] if pending is None else pending["__record_id"].to_pylist() + 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 []) diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 5fdb3934a..336ccbd89 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -23,6 +23,7 @@ from __future__ import annotations +import asyncio import re from collections.abc import Iterator from typing import Any @@ -35,6 +36,7 @@ # Imports under test — all of these will fail until the modules are created # --------------------------------------------------------------------------- +from orcapod.errors import UnsupportedValueError from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.types import ColumnInfo from orcapod.protocols.database_protocols import ArrowDatabaseProtocol @@ -750,6 +752,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 +848,39 @@ def test_multiple_flushes_accumulate_records(self, db): assert result is not None assert result.num_rows == 2 + def test_failed_flush_retains_queued_rows_and_duplicate_policy( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + connector = MockDBConnector() + db = ConnectorArrowDatabase(connector) + path = self.PATH + db.add_record(path, b"old", make_table(v=[1]), flush=True) + db.add_record(path, b"old", make_table(v=[99]), skip_duplicates=True) + db.add_record(path, b"first", make_table(v=[2])) + db.add_record(path, b"second", make_table(v=[3])) + + def refuse_write(*args: Any, **kwargs: Any) -> None: + raise UnsupportedValueError("write refused by the store") + + with monkeypatch.context() as patch: + patch.setattr(connector, "upsert_records", refuse_write) + with pytest.raises(UnsupportedValueError, match="write refused"): + db.flush() + + pending_and_stored = db.get_all_records(path, record_id_column="id") + assert pending_and_stored is not None + assert pending_and_stored.sort_by("v")["v"].to_pylist() == [1, 2, 3, 99] + db.flush() + + reader = ConnectorArrowDatabase(connector) + stored = reader.get_all_records(path, record_id_column="id") + assert stored is not None + assert stored.sort_by("id").to_pylist() == [ + {"id": b"first", "v": 2}, + {"id": b"old", "v": 1}, + {"id": b"second", "v": 3}, + ] + 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) From 60b624a2f41c675b9b3af438feb7f5eec45ed2b9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:08:21 -0800 Subject: [PATCH 07/16] fix(databases): make SQLite upserts atomic and isolate rejected rows (ITL-1381) --- changelog.d/ITL-1381.md | 13 +- src/orcapod/databases/_pending_commits.py | 6 + .../databases/connector_arrow_database.py | 82 +++++++++++-- src/orcapod/databases/sqlite_connector.py | 40 ++++++- .../protocols/db_connector_protocol.py | 5 +- tests/test_databases/test_append_by_name.py | 113 +++++++++++++++++- tests/test_databases/test_sqlite_connector.py | 41 +++++++ 7 files changed, 280 insertions(+), 20 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index d917b8179..461e012ee 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -2,11 +2,14 @@ - 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. Where the - stored column is `NOT NULL`, the second batch is refused when it is queued, with an error - naming the column, and the rows queued before it are kept. + 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. - If the connector rejects a flush, the attempted rows remain queued for retry. - A read before the flush already combined stored and queued rows that differ that way. + SQLite now rolls back the full upsert on failure. A flush drops rows it identifies + as invalid and keeps the other attempted rows for retry. It also tries each table + before reporting an error. Atomicity applies to each upsert. Table creation and + writes to separate tables commit independently. Backend errors that do not identify + a rejected row may leave the entire atomic batch queued. (ITL-1381) diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index a3891705f..6c3d2318d 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -8,6 +8,12 @@ import pyarrow as pa +class RejectedWriteRow: + """Attach the rejected row's input position to an atomic connector error.""" + + row_index: int | None = None + + class PendingCommit: """The outcome of the current attempt to commit a table's pending rows.""" diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 80f3cd229..3e3d98b0c 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -27,7 +27,11 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases._pending_commits import PendingCommit, PendingCommits +from orcapod.databases._pending_commits import ( + PendingCommit, + PendingCommits, + RejectedWriteRow, +) from orcapod.databases.utils import ( coerce_record_id, declared_null_path, @@ -59,6 +63,17 @@ 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]: """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 @@ -473,9 +488,8 @@ 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. @@ -526,6 +540,15 @@ def add_records( "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: @@ -761,9 +784,20 @@ def guard_table_schema( ) def flush(self) -> None: - """Commit pending batches via upsert, retaining a rejected batch for retry.""" + """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).""" @@ -784,6 +818,7 @@ def _flush_by_key(self, record_key: str) -> None: if ready is None: return batch, ids = ready + retry_ids = ids pending = batch record_path = tuple(record_key.split("/")) table_name = self._path_to_table_name(record_path) @@ -820,6 +855,7 @@ def _fmt(cols: dict) -> str: + "}" ) + retry_ids = set() raise ValueError( f"Schema mismatch for table {table_name!r}: " f"existing={_fmt(existing_cols)}, " @@ -827,6 +863,23 @@ def _fmt(cols: dict) -> str: "Schema evolution is not supported." ) + null_columns = _stored_null_columns(pending, existing) + if null_columns: + valid = pc.is_valid(batch[null_columns[0]]) + for column in null_columns[1:]: + valid = pc.and_(valid, pc.is_valid(batch[column])) + batch = batch.filter(valid) + retry_ids = set( + cast(list[bytes], batch[self.RECORD_ID_COLUMN].to_pylist()) + ) + error = NullInNonNullableColumnError( + null_columns[0], table=record_key + ) + error.add_note( + f"Dropped {len(ids - retry_ids)} invalid queued row(s)." + ) + raise error + # 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) @@ -840,15 +893,24 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) - except BaseException: - # Keep the original queued order when the connector needed stored order. - # A rejected write cannot distinguish valid rows from the rest of the batch. - self._pending_commits.restore(record_key, batch, ids) + except BaseException as error: + if isinstance(error, RejectedWriteRow) and error.row_index is not None: + index = error.row_index + dropped = cast(bytes, batch[self.RECORD_ID_COLUMN][index].as_py()) + retry_ids = ids - {dropped} + batch = pa.concat_tables( + [batch.slice(0, index), batch.slice(index + 1)] + ) + error.add_note(f"Dropped one invalid queued row from {record_key!r}.") + if retry_ids: + self._pending_commits.restore(record_key, batch, retry_ids) self._pending_commits.finish(record_key, committed=False) + self._pending_commits.forget(record_key, ids - retry_ids) raise else: self._pending_commits.finish(record_key, committed=True) self._pending_commits.forget(record_key, ids) + finally: if record_key not in self._pending_batches: self._pending_skip_existing.pop(record_key, None) diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index e3bb8e10f..45a93d28a 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -23,12 +23,17 @@ import pyarrow as pa +from orcapod.databases._pending_commits import RejectedWriteRow from orcapod.databases.utils import is_direct_projection from orcapod.types import ColumnInfo logger = logging.getLogger(__name__) +class _SQLiteRejectedWriteRow(sqlite3.IntegrityError, RejectedWriteRow): + """A native SQLite integrity error with the index of the rejected row.""" + + # --------------------------------------------------------------------------- # Module-level helpers (pure functions, no I/O) # --------------------------------------------------------------------------- @@ -457,7 +462,7 @@ 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). @@ -476,8 +481,37 @@ def upsert_records( 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})' - rows = (tuple(row[c] for c in cols) for row in records.to_pylist()) - conn.executemany(sql, rows) + row_index = -1 + + def rows() -> Iterator[tuple[Any, ...]]: + nonlocal row_index + for row_index, row in enumerate(records.to_pylist()): + yield tuple(row[c] for c in cols) + + conn.execute("BEGIN") + try: + conn.executemany(sql, rows()) + row_index = -1 # Commit-time failures have no individual row. + conn.commit() + except BaseException as error: + conn.rollback() + # sqlite3 steps each row before asking the iterator for the next one. + # These two constraints diagnose the row being stepped. + if ( + isinstance(error, sqlite3.IntegrityError) + and row_index >= 0 + and error.sqlite_errorcode + in ( + sqlite3.SQLITE_CONSTRAINT_NOTNULL, + sqlite3.SQLITE_CONSTRAINT_CHECK, + ) + ): + rejected = _SQLiteRejectedWriteRow(*error.args) + rejected.sqlite_errorcode = error.sqlite_errorcode + rejected.sqlite_errorname = error.sqlite_errorname + rejected.row_index = row_index + raise rejected from error + raise @property def keeps_field_metadata(self) -> bool: diff --git a/src/orcapod/protocols/db_connector_protocol.py b/src/orcapod/protocols/db_connector_protocol.py index 6ed2f94bd..dc489eb87 100644 --- a/src/orcapod/protocols/db_connector_protocol.py +++ b/src/orcapod/protocols/db_connector_protocol.py @@ -106,7 +106,10 @@ 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 batch on a rejected write so the caller can safely retain + uncommitted records for another attempt. Args: table_name: Target table (must already exist). diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 69204423a..2743b95a1 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -19,7 +19,7 @@ import sqlite3 import uuid from collections.abc import Iterator -from contextlib import ExitStack, contextmanager +from contextlib import ExitStack, closing, contextmanager from pathlib import Path from typing import Any, cast from unittest.mock import patch @@ -1140,6 +1140,117 @@ def test_a_refused_batch_leaves_the_queued_rows_to_be_flushed( _check(db.get_all_records(PATH, record_id_column=ID), order, ns) +def _nullable_values( + rows: list[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(NullInNonNullableColumnError, match="'v'"): + writer.flush() + expected = [ + {ID: b"changed", "v": 77 if stored_at_enqueue else 1}, + {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]) +def test_sqlite_check_failure_drops_only_the_rejected_row( + tmp_path: Path, bad_first: bool +) -> None: + db_file = str(tmp_path / "store.db") + # CHECK is backend metadata the Arrow schema cannot describe. + 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, + SQLiteConnector(db_file) as reader_connector, + ): + writer = ConnectorArrowDatabase(connector) + reader = ConnectorArrowDatabase(reader_connector) + _add(reader, _nullable_values([(b"seed", 1)]), flush=True) + good = _nullable_values([(b"good-1", 2), (b"good-2", 3)]) + mixed = _nullable_values([(b"bad", -1), (b"good-3", 4)]) + for batch in (mixed, good) if bad_first else (good, mixed): + _add(writer, batch) + independent_path = ("independent",) + independent = _nullable_values([(b"other-1", 5), (b"other-2", 6)]) + writer.add_records(independent_path, independent, record_id_column=ID) + with pytest.raises(sqlite3.IntegrityError, match="CHECK"): + writer.flush() + assert _read_values(reader).to_pylist() == [{ID: b"seed", "v": 1}] + assert _read_values(reader, independent_path).equals(independent.sort_by(ID)) + expected = [ + {ID: b"good-1", "v": 2}, + {ID: b"good-2", "v": 3}, + {ID: b"good-3", "v": 4}, + {ID: b"seed", "v": 1}, + ] + assert _read_values(writer).to_pylist() == expected + writer.flush() + assert _read_values(reader).to_pylist() == expected + + 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()) diff --git a/tests/test_databases/test_sqlite_connector.py b/tests/test_databases/test_sqlite_connector.py index d3ca2bcdd..ac21ffac7 100644 --- a/tests/test_databases/test_sqlite_connector.py +++ b/tests/test_databases/test_sqlite_connector.py @@ -2,6 +2,7 @@ from __future__ import annotations +import sqlite3 from collections.abc import Iterator from pathlib import Path @@ -366,6 +367,46 @@ 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] + 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"): From 48c779cb66ea19cfd7f1fe8776d48fa33f13d434 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:42:40 -0800 Subject: [PATCH 08/16] fix(databases): isolate connector writes after unlocated row refusals (ITL-1381) --- changelog.d/ITL-1381.md | 10 +- docs/reference/database-types.md | 11 ++ src/orcapod/databases/_sql_writes.py | 51 ++++++ .../databases/connector_arrow_database.py | 96 ++++++++++-- src/orcapod/databases/postgresql_connector.py | 48 +++++- src/orcapod/databases/sqlite_connector.py | 34 +++- tests/test_databases/test_append_by_name.py | 87 ++++++++++- .../test_connector_arrow_database.py | 49 +++++- .../test_postgresql_connector.py | 145 ++++++++++++++++++ tests/test_databases/type_matrix.py | 11 ++ 10 files changed, 516 insertions(+), 26 deletions(-) create mode 100644 src/orcapod/databases/_sql_writes.py diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index 461e012ee..7ac9e0fb6 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -8,8 +8,10 @@ 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. SQLite now rolls back the full upsert on failure. A flush drops rows it identifies - as invalid and keeps the other attempted rows for retry. It also tries each table - before reporting an error. Atomicity applies to each upsert. Table creation and - writes to separate tables commit independently. Backend errors that do not identify - a rejected row may leave the entire atomic batch queued. + as invalid and keeps the other attempted rows for retry. If a backend refuses the + data without identifying a row, it isolates the rows in one pass, commits valid + rows, and reports the rejected keys and their reasons. A transaction-wide failure + can leave uncommitted rows queued. Table creation and writes to separate tables + commit independently. When two handles update the same key, the last flush to + commit that key wins. (ITL-1381) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index a60973db0..6b1404d28 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. That includes a flush of a row retained after a failure, even +if another handle has written that key in the meantime. Use +`skip_duplicates=True` to keep an already stored key. + +SQLite and PostgreSQL roll back a failed bulk upsert. If the backend refuses the +data without identifying the row, the flush tries each row once in order, using a +savepoint per row. It commits valid rows and reports each dropped row's key and the +backend's reason. Other tables can still commit. A transaction-wide failure leaves +the uncommitted rows queued for retry. + ## Integer | Type | in-memory | Delta | SQLite | PostgreSQL | diff --git a/src/orcapod/databases/_sql_writes.py b/src/orcapod/databases/_sql_writes.py new file mode 100644 index 000000000..5d7deaa80 --- /dev/null +++ b/src/orcapod/databases/_sql_writes.py @@ -0,0 +1,51 @@ +"""Row isolation for a SQL upsert that rolled back after a data refusal.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from typing import Protocol, runtime_checkable + +import pyarrow as pa + + +@runtime_checkable +class IsolatesRefusedRows(Protocol): + def isolate_refused_rows( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool, + error: Exception, + ) -> dict[int, str] | None: + """After a refusal, commit other rows and return the rejected positions. + + Return None for an error that is not a data refusal. A failure in isolation + itself must roll back all writes in the isolation transaction. + """ + ... + + +class _Execute(Protocol): + def __call__(self, sql: str, params: tuple[object, ...] = (), /) -> object: ... + + +def write_with_savepoints( + execute: _Execute, + sql: str, + rows: Iterable[tuple[object, ...]], + is_refusal: Callable[[Exception], bool], +) -> dict[int, str]: + """Write rows in the caller's transaction, rolling back each refused statement.""" + refused: dict[int, str] = {} + for index, row in enumerate(rows): + execute("SAVEPOINT orcapod_row") + try: + execute(sql, row) + except Exception as error: + if not is_refusal(error): + raise + execute("ROLLBACK TO SAVEPOINT orcapod_row") + refused[index] = str(error) + execute("RELEASE SAVEPOINT orcapod_row") + return refused diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 3e3d98b0c..4d59e52da 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -32,6 +32,7 @@ PendingCommits, RejectedWriteRow, ) +from orcapod.databases._sql_writes import IsolatesRefusedRows from orcapod.databases.utils import ( coerce_record_id, declared_null_path, @@ -46,6 +47,7 @@ OrcapodDatabaseReadError, UnstorableColumnError, UnstorableTableNameError, + UnsupportedValueError, ) from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol from orcapod.utils.arrow_utils import ( @@ -111,6 +113,10 @@ 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, + including a flush of a row retained after an earlier failure. With + ``skip_duplicates=True``, an existing durable key is kept. + Args: connector: A ``DBConnectorProtocol`` implementation providing the underlying DB access (connection, type mapping, queries, writes). @@ -812,13 +818,74 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: """Commit one table's ready records.""" self._flush_by_key(self._get_record_key(record_path)) + def _write_pending_rows( + self, + table_name: str, + records: pa.Table, + skip_existing: bool, + retry_ids: set[bytes], + ) -> None: + """Write the batch or isolate an unlocated data refusal once.""" + write = self._connector.upsert_records + id_column = self.RECORD_ID_COLUMN + try: + write(table_name, records, id_column, skip_existing=skip_existing) + except Exception as error: + if isinstance(error, RejectedWriteRow): + raise + refused: dict[int, str] | None = None + if isinstance(self._connector, IsolatesRefusedRows): + refused = self._connector.isolate_refused_rows( + table_name, records, id_column, skip_existing, error + ) + if refused is not None: + retry_ids.clear() + elif isinstance(error, (InputValidationError, UnsupportedValueError)): + # Connectors without SQL savepoints can isolate a known refusal + # with their existing atomic upsert, once per row. + refused = {} + for index, key in enumerate(records[id_column].to_pylist()): + try: + write( + table_name, + records.slice(index, 1), + id_column, + skip_existing=skip_existing, + ) + except (InputValidationError, UnsupportedValueError) as refused_row: + refused[index] = str(refused_row) + except BaseException as interrupted: + if refused: + interrupted.add_note( + self._refused_rows_message(table_name, records, refused) + ) + raise + retry_ids.remove(cast(bytes, key)) + else: + raise + if refused: + raise InputValidationError( + self._refused_rows_message(table_name, records, refused) + ) from error + else: + retry_ids.clear() + + def _refused_rows_message( + self, table_name: str, records: pa.Table, refused: dict[int, str] + ) -> str: + keys = records[self.RECORD_ID_COLUMN] + rows = "\n".join( + f" {keys[index].as_py()!r} — {reason}" for index, reason in refused.items() + ) + return f"Refused rows in table {table_name!r}\n{rows}" + 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 batch, ids = ready - retry_ids = ids + retry_ids = ids.copy() pending = batch record_path = tuple(record_key.split("/")) table_name = self._path_to_table_name(record_path) @@ -868,9 +935,11 @@ def _fmt(cols: dict) -> str: valid = pc.is_valid(batch[null_columns[0]]) for column in null_columns[1:]: valid = pc.and_(valid, pc.is_valid(batch[column])) - batch = batch.filter(valid) retry_ids = set( - cast(list[bytes], batch[self.RECORD_ID_COLUMN].to_pylist()) + cast( + list[bytes], + batch[self.RECORD_ID_COLUMN].filter(valid).to_pylist(), + ) ) error = NullInNonNullableColumnError( null_columns[0], table=record_key @@ -887,22 +956,21 @@ def _fmt(cols: dict) -> str: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) - self._connector.upsert_records( - table_name, - pending, - id_column=self.RECORD_ID_COLUMN, - skip_existing=skip_existing, - ) + self._write_pending_rows(table_name, pending, skip_existing, retry_ids) except BaseException as error: if isinstance(error, RejectedWriteRow) and error.row_index is not None: index = error.row_index dropped = cast(bytes, batch[self.RECORD_ID_COLUMN][index].as_py()) - retry_ids = ids - {dropped} - batch = pa.concat_tables( - [batch.slice(0, index), batch.slice(index + 1)] - ) - error.add_note(f"Dropped one invalid queued row from {record_key!r}.") + retry_ids.remove(dropped) + error.add_note(f"Dropped queued row {dropped!r} from {record_key!r}.") if retry_ids: + if retry_ids != ids: + batch = batch.filter( + pc.is_in( + batch[self.RECORD_ID_COLUMN], + value_set=pa.array(list(retry_ids), type=pa.large_binary()), + ) + ) self._pending_commits.restore(record_key, batch, retry_ids) self._pending_commits.finish(record_key, committed=False) self._pending_commits.forget(record_key, ids - retry_ids) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 0417c04c5..edeaa6e31 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -24,6 +24,7 @@ import pyarrow as pa +from orcapod.databases._sql_writes import write_with_savepoints from orcapod.databases.utils import is_direct_projection from orcapod.errors import UnstorableTableNameError from orcapod.types import ColumnInfo @@ -37,6 +38,13 @@ logger = logging.getLogger(__name__) +def _is_row_refusal(error: Exception) -> bool: + return isinstance( + error, + (psycopg.IntegrityError, psycopg.DataError, psycopg.errors.RaiseException), + ) + + # --------------------------------------------------------------------------- # Module-level helpers (pure functions, no I/O) # These are kept module-level so AsyncPostgreSQLConnector (future) can reuse @@ -668,6 +676,33 @@ def upsert_records( skip_existing: bool = False, ) -> None: """Write records to a table using upsert semantics.""" + self._upsert_records( + table_name, records, id_column, skip_existing, isolate=False + ) + + def isolate_refused_rows( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool, + error: Exception, + ) -> dict[int, str] | None: + if not _is_row_refusal(error): + return None + return self._upsert_records( + table_name, records, id_column, skip_existing, isolate=True + ) + + def _upsert_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool, + *, + isolate: bool, + ) -> dict[int, str]: self._require_table_name(table_name) with self._lock: conn = self._require_open() @@ -700,9 +735,18 @@ def upsert_records( rows_iter = (tuple(row[c] for c in cols) for row in records.to_pylist()) try: with conn.cursor() as cur: - cur.executemany(sql, rows_iter) + if isolate: + # Report deferred constraint violations inside the row's savepoint. + cur.execute("SET CONSTRAINTS ALL IMMEDIATE") + refused = write_with_savepoints( + cur.execute, sql, rows_iter, _is_row_refusal + ) + else: + cur.executemany(sql, rows_iter) + refused = {} conn.commit() - except Exception: + return refused + except BaseException: conn.rollback() raise diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 45a93d28a..f65bea449 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -24,6 +24,7 @@ import pyarrow as pa from orcapod.databases._pending_commits import RejectedWriteRow +from orcapod.databases._sql_writes import write_with_savepoints from orcapod.databases.utils import is_direct_projection from orcapod.types import ColumnInfo @@ -34,6 +35,10 @@ class _SQLiteRejectedWriteRow(sqlite3.IntegrityError, RejectedWriteRow): """A native SQLite integrity error with the index of the rejected row.""" +def _is_row_refusal(error: Exception) -> bool: + return isinstance(error, (sqlite3.IntegrityError, sqlite3.DataError)) + + # --------------------------------------------------------------------------- # Module-level helpers (pure functions, no I/O) # --------------------------------------------------------------------------- @@ -473,6 +478,23 @@ def upsert_records( skip_existing: If True, skip rows whose id already exists (INSERT OR IGNORE). If False, overwrite (INSERT OR REPLACE). """ + self._upsert_records(table_name, records, skip_existing, isolate=False) + + def isolate_refused_rows( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool, + error: Exception, + ) -> dict[int, str] | None: + if not _is_row_refusal(error): + return None + return self._upsert_records(table_name, records, skip_existing, isolate=True) + + def _upsert_records( + self, table_name: str, records: pa.Table, skip_existing: bool, *, isolate: bool + ) -> dict[int, str]: with self._lock: conn = self._require_open() self._validate_table_name(table_name) @@ -490,15 +512,23 @@ def rows() -> Iterator[tuple[Any, ...]]: conn.execute("BEGIN") try: - conn.executemany(sql, rows()) + if isolate: + refused = write_with_savepoints( + conn.execute, sql, rows(), _is_row_refusal + ) + else: + conn.executemany(sql, rows()) + refused = {} row_index = -1 # Commit-time failures have no individual row. conn.commit() + return refused except BaseException as error: conn.rollback() # sqlite3 steps each row before asking the iterator for the next one. # These two constraints diagnose the row being stepped. if ( - isinstance(error, sqlite3.IntegrityError) + not isolate + and isinstance(error, sqlite3.IntegrityError) and row_index >= 0 and error.sqlite_errorcode in ( diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 2743b95a1..694957af2 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -18,7 +18,7 @@ import os import sqlite3 import uuid -from collections.abc import Iterator +from collections.abc import Iterator, Sequence from contextlib import ExitStack, closing, contextmanager from pathlib import Path from typing import Any, cast @@ -1141,7 +1141,7 @@ def test_a_refused_batch_leaves_the_queued_rows_to_be_flushed( def _nullable_values( - rows: list[tuple[bytes, int | None]], *, nullable: bool = True + rows: Sequence[tuple[bytes, int | None]], *, nullable: bool = True ) -> pa.Table: return pa.Table.from_arrays( [ @@ -1251,6 +1251,89 @@ def test_sqlite_check_failure_drops_only_the_rejected_row( 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(sqlite3.IntegrityError, 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"also-good", "v": 20}, + {ID: b"shared", "v": 10}, + ] + + +@pytest.mark.parametrize("bad_first", [False, True]) +@pytest.mark.parametrize("on_event_loop", [False, True]) +def test_sqlite_trigger_refusal_commits_valid_rows_and_names_rejected_keys( + tmp_path: Path, bad_first: bool, on_event_loop: 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)') + sql.execute( + """CREATE TRIGGER positive BEFORE INSERT ON t WHEN NEW.v < 0 + BEGIN SELECT RAISE(ABORT, '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: + _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]) + for batch in (left, right) if bad_first else (right, left): + _add(writer, batch) + with pytest.raises( + InputValidationError, match="must be positive" + ) as refused: + writer.flush() + expected = [ + {ID: b"good-1", "v": 2}, + {ID: b"good-2", "v": 3}, + {ID: b"seed", "v": 1}, + ] + assert _read_values(reader).to_pylist() == expected + assert "bad-1" in str(refused.value) and "bad-2" in str(refused.value) + assert _read_values(writer).to_pylist() == expected + writer.flush() + + async def on_loop() -> None: + check() + + if on_event_loop: + asyncio.run(on_loop()) + else: + check() + + 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()) diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 336ccbd89..b147335f9 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -860,11 +860,11 @@ def test_failed_flush_retains_queued_rows_and_duplicate_policy( db.add_record(path, b"second", make_table(v=[3])) def refuse_write(*args: Any, **kwargs: Any) -> None: - raise UnsupportedValueError("write refused by the store") + raise OSError("store temporarily unavailable") with monkeypatch.context() as patch: patch.setattr(connector, "upsert_records", refuse_write) - with pytest.raises(UnsupportedValueError, match="write refused"): + with pytest.raises(OSError, match="store temporarily unavailable"): db.flush() pending_and_stored = db.get_all_records(path, record_id_column="id") @@ -881,6 +881,51 @@ def refuse_write(*args: Any, **kwargs: Any) -> None: {"id": b"second", "v": 3}, ] + def test_non_sql_isolation_does_not_replay_rows_settled_before_an_interruption( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + connector = MockDBConnector() + db = ConnectorArrowDatabase(connector) + other_handle = ConnectorArrowDatabase(connector) + upsert = connector.upsert_records + path = self.PATH + db.add_records( + path, + pa.table({"id": [b"good", b"bad", b"later"], "v": [10, -1, 20]}), + record_id_column="id", + ) + + def reject_or_interrupt( + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool = False, + ) -> None: + values = records["v"].to_pylist() + if -1 in values: + raise UnsupportedValueError("negative values are refused") + if 20 in values: + raise OSError("store temporarily unavailable") + upsert(table_name, records, id_column, skip_existing=skip_existing) + + with monkeypatch.context() as patch: + patch.setattr(connector, "upsert_records", reject_or_interrupt) + with pytest.raises( + OSError, match="store temporarily unavailable" + ) as raised: + db.flush() + assert "b'bad' — negative values are refused" in "\n".join( + raised.value.__notes__ + ) + other_handle.add_record(path, b"good", make_table(v=[99]), flush=True) + db.flush() + stored = other_handle.get_all_records(path, record_id_column="id") + assert stored is not None + assert stored.sort_by("id").to_pylist() == [ + {"id": b"good", "v": 99}, + {"id": b"later", "v": 20}, + ] + 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) diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 900535e90..411688dd6 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,156 @@ 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 InputValidationError from orcapod.protocols.db_connector_protocol import DBConnectorProtocol +from orcapod.types import ColumnInfo + + +class _PostgreSQLTransaction: + """Track PostgreSQL's aborted transaction and the effects of savepoint commands.""" + + def __init__(self) -> None: + self.committed = {b"seed": 1} + self.pending = self.committed.copy() + self.savepoint: dict[bytes, int] | None = None + self.aborted = False + self.commands: list[str] = [] + + def execute(self, sql: str, row: tuple[bytes, int] | None = None) -> None: + if sql.startswith("ROLLBACK TO SAVEPOINT "): + assert self.savepoint is not None + self.pending = self.savepoint.copy() + self.aborted = False + assert not self.aborted + if sql.startswith("SAVEPOINT "): + assert self.savepoint is None + self.savepoint = self.pending.copy() + elif sql.startswith("RELEASE SAVEPOINT "): + assert self.savepoint is not None + self.savepoint = None + elif 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 + elif not sql.startswith("ROLLBACK TO SAVEPOINT "): + assert sql.startswith("CREATE TABLE IF NOT EXISTS") or sql == ( + "SET CONSTRAINTS ALL IMMEDIATE" + ) + 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 + assert self.savepoint is None + self.committed = self.pending.copy() + self.commands.append("COMMIT") + + def rollback(self) -> None: + self.aborted = False + self.pending = self.committed.copy() + self.savepoint = None + 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_uses_savepoints_to_commit_valid_rows( + 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( + InputValidationError, 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.sort_by("id").to_pylist() == [ + {"id": b"good-1", "v": 11}, + {"id": b"good-2", "v": 12}, + {"id": b"seed", "v": 1}, + ] + assert "bad-1" in str(refused.value) and "bad-2" in str(refused.value) + assert ( + sum( + command.startswith("SAVEPOINT ") for command in transaction.commands + ) + == 4 + ) + assert ( + sum( + command.startswith("ROLLBACK TO SAVEPOINT ") + for command in transaction.commands + ) + == 2 + ) + assert transaction.commands.count("ROLLBACK") == 1 + assert transaction.commands[-1] == "COMMIT" + 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/type_matrix.py b/tests/test_databases/type_matrix.py index 614e9900e..ad323e59b 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. That includes a flush of a row retained after a failure, even +if another handle has written that key in the meantime. Use +`skip_duplicates=True` to keep an already stored key. + +SQLite and PostgreSQL roll back a failed bulk upsert. If the backend refuses the +data without identifying the row, the flush tries each row once in order, using a +savepoint per row. It commits valid rows and reports each dropped row's key and the +backend's reason. Other tables can still commit. A transaction-wide failure leaves +the uncommitted rows queued for retry. """ From a4a252475a97ed0c69cdcb16f5b624dd51afa3b2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 03:12:14 -0800 Subject: [PATCH 09/16] fix(databases): preserve isolated SQLite writes and their dependents (ITL-1381) --- changelog.d/ITL-1381.md | 11 +- docs/reference/database-types.md | 11 +- src/orcapod/databases/_pending_commits.py | 30 +++-- src/orcapod/databases/_sql_writes.py | 18 ++- .../databases/connector_arrow_database.py | 84 +++++++------ src/orcapod/databases/postgresql_connector.py | 29 +++-- src/orcapod/databases/sqlite_connector.py | 52 +++++--- tests/test_databases/test_append_by_name.py | 111 ++++++++++++++++-- tests/test_databases/type_matrix.py | 11 +- 9 files changed, 262 insertions(+), 95 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index 7ac9e0fb6..a4f78a49f 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -10,8 +10,11 @@ SQLite now rolls back the full upsert on failure. A flush drops rows it identifies as invalid and keeps the other attempted rows for retry. If a backend refuses the data without identifying a row, it isolates the rows in one pass, commits valid - rows, and reports the rejected keys and their reasons. A transaction-wide failure - can leave uncommitted rows queued. Table creation and writes to separate tables - commit independently. When two handles update the same key, the last flush to - commit that key wins. + rows, and reports the rejected keys and their reasons. SQLite uses a transaction + per isolated row to handle rollback triggers and deferred foreign keys. + Partial commits preserve records guarded by results that became durable. + PostgreSQL rejects text containing NUL at enqueue. An interruption can leave + unsettled rows queued. Table creation and writes to separate tables commit + independently. When two handles update the same key, the last flush to commit + that key wins. (ITL-1381) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 6b1404d28..3350a2715 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -139,10 +139,13 @@ if another handle has written that key in the meantime. Use `skip_duplicates=True` to keep an already stored key. SQLite and PostgreSQL roll back a failed bulk upsert. If the backend refuses the -data without identifying the row, the flush tries each row once in order, using a -savepoint per row. It commits valid rows and reports each dropped row's key and the -backend's reason. Other tables can still commit. A transaction-wide failure leaves -the uncommitted rows queued for retry. +data without identifying the row, the flush tries each row once in order. SQLite +uses a transaction per row so that a rollback trigger or a deferred foreign key can +reject that row without losing earlier commits. PostgreSQL uses a savepoint per +row. The flush reports each dropped row's key and the backend's reason. Other +tables can still commit, and records guarded by committed results remain eligible +to write. An interruption leaves unsettled rows queued for retry. PostgreSQL +refuses text containing NUL at enqueue. ## Integer diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 6c3d2318d..6c1d85a49 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -15,7 +15,7 @@ class RejectedWriteRow: 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 @@ -49,7 +49,7 @@ def __init__( self._batches = batches self._ids = ids 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]] = {} @@ -69,19 +69,31 @@ 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: set[bytes] + ) -> None: + """Release dependents of durable rows and withdraw those of failed rows.""" + attempts = self._attempts.get(key) + if attempts is None: + return + for record_id in attempts.keys() & attempted: + attempts.pop(record_id).finish(committed=record_id in committed) + if not attempts: + self._attempts.pop(key) + @contextmanager def guard( self, key: str, record_id: bytes, attempt: PendingCommit diff --git a/src/orcapod/databases/_sql_writes.py b/src/orcapod/databases/_sql_writes.py index 5d7deaa80..77ba4457a 100644 --- a/src/orcapod/databases/_sql_writes.py +++ b/src/orcapod/databases/_sql_writes.py @@ -3,11 +3,20 @@ from __future__ import annotations from collections.abc import Callable, Iterable +from dataclasses import dataclass, field from typing import Protocol, runtime_checkable import pyarrow as pa +@dataclass +class RowIsolation: + """Positions that became durable or were definitively refused.""" + + settled: set[int] = field(default_factory=set) + refused: dict[int, str] = field(default_factory=dict) + + @runtime_checkable class IsolatesRefusedRows(Protocol): def isolate_refused_rows( @@ -17,11 +26,12 @@ def isolate_refused_rows( id_column: str, skip_existing: bool, error: Exception, - ) -> dict[int, str] | None: - """After a refusal, commit other rows and return the rejected positions. + progress: RowIsolation, + ) -> bool: + """After a refusal, commit other rows and record each settled position. - Return None for an error that is not a data refusal. A failure in isolation - itself must roll back all writes in the isolation transaction. + Return False for an error that is not a data refusal. If isolation is + interrupted, retain any positions already settled. """ ... diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 4d59e52da..2169d5b7b 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -32,7 +32,7 @@ PendingCommits, RejectedWriteRow, ) -from orcapod.databases._sql_writes import IsolatesRefusedRows +from orcapod.databases._sql_writes import IsolatesRefusedRows, RowIsolation from orcapod.databases.utils import ( coerce_record_id, declared_null_path, @@ -761,7 +761,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 @@ -824,6 +824,7 @@ def _write_pending_rows( records: pa.Table, skip_existing: bool, retry_ids: set[bytes], + committed_ids: set[bytes], ) -> None: """Write the batch or isolate an unlocated data refusal once.""" write = self._connector.upsert_records @@ -833,42 +834,50 @@ def _write_pending_rows( except Exception as error: if isinstance(error, RejectedWriteRow): raise - refused: dict[int, str] | None = None - if isinstance(self._connector, IsolatesRefusedRows): - refused = self._connector.isolate_refused_rows( - table_name, records, id_column, skip_existing, error + progress = RowIsolation() + try: + isolated = isinstance( + self._connector, IsolatesRefusedRows + ) and self._connector.isolate_refused_rows( + table_name, records, id_column, skip_existing, error, progress ) - if refused is not None: - retry_ids.clear() - elif isinstance(error, (InputValidationError, UnsupportedValueError)): - # Connectors without SQL savepoints can isolate a known refusal - # with their existing atomic upsert, once per row. - refused = {} - for index, key in enumerate(records[id_column].to_pylist()): - try: - write( - table_name, - records.slice(index, 1), - id_column, - skip_existing=skip_existing, - ) - except (InputValidationError, UnsupportedValueError) as refused_row: - refused[index] = str(refused_row) - except BaseException as interrupted: - if refused: - interrupted.add_note( - self._refused_rows_message(table_name, records, refused) - ) + if not isolated: + if not isinstance( + error, (InputValidationError, UnsupportedValueError) + ): raise - retry_ids.remove(cast(bytes, key)) - else: + # Use one atomic upsert per row for connectors without their own + # refusal isolation. + for index in range(records.num_rows): + try: + write( + table_name, + records.slice(index, 1), + id_column, + skip_existing=skip_existing, + ) + except (InputValidationError, UnsupportedValueError) as refused: + progress.refused[index] = str(refused) + progress.settled.add(index) + except BaseException as interrupted: + if progress.refused: + interrupted.add_note( + self._refused_rows_message( + table_name, records, progress.refused + ) + ) raise - if refused: + finally: + keys = records[id_column] + for index in progress.settled: + key = cast(bytes, keys[index].as_py()) + retry_ids.remove(key) + if index not in progress.refused: + committed_ids.add(key) + if progress.refused: raise InputValidationError( - self._refused_rows_message(table_name, records, refused) + self._refused_rows_message(table_name, records, progress.refused) ) from error - else: - retry_ids.clear() def _refused_rows_message( self, table_name: str, records: pa.Table, refused: dict[int, str] @@ -886,6 +895,7 @@ def _flush_by_key(self, record_key: str) -> None: return batch, ids = ready retry_ids = ids.copy() + committed_ids: set[bytes] = set() pending = batch record_path = tuple(record_key.split("/")) table_name = self._path_to_table_name(record_path) @@ -956,7 +966,9 @@ def _fmt(cols: dict) -> str: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) - self._write_pending_rows(table_name, pending, skip_existing, retry_ids) + self._write_pending_rows( + table_name, pending, skip_existing, retry_ids, committed_ids + ) except BaseException as error: if isinstance(error, RejectedWriteRow) and error.row_index is not None: index = error.row_index @@ -972,11 +984,11 @@ def _fmt(cols: dict) -> str: ) ) self._pending_commits.restore(record_key, batch, retry_ids) - self._pending_commits.finish(record_key, committed=False) + self._pending_commits.finish_rows(record_key, ids, committed_ids) self._pending_commits.forget(record_key, ids - retry_ids) raise else: - self._pending_commits.finish(record_key, committed=True) + self._pending_commits.finish_rows(record_key, ids, ids) self._pending_commits.forget(record_key, ids) finally: if record_key not in self._pending_batches: diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index edeaa6e31..fbac7e3a6 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -23,10 +23,11 @@ from typing import TYPE_CHECKING, Any import pyarrow as pa +import pyarrow.compute as pc -from orcapod.databases._sql_writes import write_with_savepoints +from orcapod.databases._sql_writes import RowIsolation, write_with_savepoints 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 @@ -687,12 +688,16 @@ def isolate_refused_rows( id_column: str, skip_existing: bool, error: Exception, - ) -> dict[int, str] | None: + progress: RowIsolation, + ) -> bool: if not _is_row_refusal(error): - return None - return self._upsert_records( + return False + refused = self._upsert_records( table_name, records, id_column, skip_existing, isolate=True ) + progress.refused.update(refused) + progress.settled.update(range(records.num_rows)) + return True def _upsert_records( self, @@ -817,7 +822,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. @@ -830,7 +835,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) @@ -845,6 +851,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 f65bea449..b5fec125f 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -24,7 +24,7 @@ import pyarrow as pa from orcapod.databases._pending_commits import RejectedWriteRow -from orcapod.databases._sql_writes import write_with_savepoints +from orcapod.databases._sql_writes import RowIsolation from orcapod.databases.utils import is_direct_projection from orcapod.types import ColumnInfo @@ -478,7 +478,7 @@ def upsert_records( skip_existing: If True, skip rows whose id already exists (INSERT OR IGNORE). If False, overwrite (INSERT OR REPLACE). """ - self._upsert_records(table_name, records, skip_existing, isolate=False) + self._upsert_records(table_name, records, skip_existing) def isolate_refused_rows( self, @@ -487,14 +487,21 @@ def isolate_refused_rows( id_column: str, skip_existing: bool, error: Exception, - ) -> dict[int, str] | None: + progress: RowIsolation, + ) -> bool: if not _is_row_refusal(error): - return None - return self._upsert_records(table_name, records, skip_existing, isolate=True) + return False + self._upsert_records(table_name, records, skip_existing, progress=progress) + return True def _upsert_records( - self, table_name: str, records: pa.Table, skip_existing: bool, *, isolate: bool - ) -> dict[int, str]: + self, + table_name: str, + records: pa.Table, + skip_existing: bool, + *, + progress: RowIsolation | None = None, + ) -> None: with self._lock: conn = self._require_open() self._validate_table_name(table_name) @@ -510,25 +517,36 @@ def rows() -> Iterator[tuple[Any, ...]]: for row_index, row in enumerate(records.to_pylist()): yield tuple(row[c] for c in cols) + if progress is not None: + # RAISE(ROLLBACK) ends the transaction, and a deferred foreign key + # is checked only at commit. Each row therefore owns a transaction. + for values in rows(): + conn.execute("BEGIN") + try: + conn.execute(sql, values) + conn.commit() + except BaseException as error: + if conn.in_transaction: + conn.rollback() + if not isinstance(error, Exception) or not _is_row_refusal( + error + ): + raise + progress.refused[row_index] = str(error) + progress.settled.add(row_index) + return + conn.execute("BEGIN") try: - if isolate: - refused = write_with_savepoints( - conn.execute, sql, rows(), _is_row_refusal - ) - else: - conn.executemany(sql, rows()) - refused = {} + conn.executemany(sql, rows()) row_index = -1 # Commit-time failures have no individual row. conn.commit() - return refused except BaseException as error: conn.rollback() # sqlite3 steps each row before asking the iterator for the next one. # These two constraints diagnose the row being stepped. if ( - not isolate - and isinstance(error, sqlite3.IntegrityError) + isinstance(error, sqlite3.IntegrityError) and row_index >= 0 and error.sqlite_errorcode in ( diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 694957af2..e3ec83edf 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -39,6 +39,7 @@ InputValidationError, NullInNonNullableColumnError, UnstorableColumnError, + UnsupportedValueError, ) from tests.test_databases.test_connector_arrow_database import MockDBConnector from tests.test_databases.type_matrix import open_database @@ -1288,16 +1289,27 @@ def test_connector_writes_to_the_same_key_follow_flush_order( @pytest.mark.parametrize("bad_first", [False, True]) @pytest.mark.parametrize("on_event_loop", [False, True]) -def test_sqlite_trigger_refusal_commits_valid_rows_and_names_rejected_keys( - tmp_path: Path, bad_first: bool, on_event_loop: bool +@pytest.mark.parametrize("refusal", ["ABORT", "ROLLBACK", "deferred foreign key"]) +def test_sqlite_refusal_isolation_commits_valid_rows_and_names_rejected_keys( + tmp_path: Path, bad_first: bool, on_event_loop: bool, refusal: str ) -> 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)') - sql.execute( - """CREATE TRIGGER positive BEFORE INSERT ON t WHEN NEW.v < 0 - BEGIN SELECT RAISE(ABORT, 'must be positive'); END""" - ) + 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, @@ -1306,14 +1318,16 @@ def test_sqlite_trigger_refusal_commits_valid_rows_and_names_rejected_keys( 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]) for batch in (left, right) if bad_first else (right, left): _add(writer, batch) - with pytest.raises( - InputValidationError, match="must be positive" - ) as refused: + with pytest.raises(InputValidationError, match=message) as refused: writer.flush() expected = [ {ID: b"good-1", "v": 2}, @@ -1334,6 +1348,83 @@ async def on_loop() -> None: check() +@pytest.mark.parametrize("bad_first", [False, True]) +def test_partial_result_commit_preserves_records_guarded_by_committed_results( + 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",) + 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, + ) + records.flush() + assert results.get_all_records(dependent_path, record_id_column=ID) is None + + with pytest.raises(InputValidationError, match="must be positive"): + results.flush_result_batch(PATH, publish_records=True) + results.fail_pending_result(PATH) + assert _read_values(results).to_pylist() == [ + {ID: key, "v": value} for key, value in accepted + ] + records.flush() + assert _read_values(results, dependent_path).to_pylist() == [ + {ID: b"record-" + key, "v": value} for key, value in accepted + ] + + +@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()) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index ad323e59b..a840c2694 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1136,10 +1136,13 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: `skip_duplicates=True` to keep an already stored key. SQLite and PostgreSQL roll back a failed bulk upsert. If the backend refuses the -data without identifying the row, the flush tries each row once in order, using a -savepoint per row. It commits valid rows and reports each dropped row's key and the -backend's reason. Other tables can still commit. A transaction-wide failure leaves -the uncommitted rows queued for retry. +data without identifying the row, the flush tries each row once in order. SQLite +uses a transaction per row so that a rollback trigger or a deferred foreign key can +reject that row without losing earlier commits. PostgreSQL uses a savepoint per +row. The flush reports each dropped row's key and the backend's reason. Other +tables can still commit, and records guarded by committed results remain eligible +to write. An interruption leaves unsettled rows queued for retry. PostgreSQL +refuses text containing NUL at enqueue. """ From 992388ae015375e2b96f3e3a1a4075ca49a0746d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 03:43:16 -0800 Subject: [PATCH 10/16] fix(databases): discard and report refused connector batches (ITL-1381) --- changelog.d/ITL-1381.md | 15 +- docs/reference/database-types.md | 21 ++- src/orcapod/databases/_pending_commits.py | 47 ++++-- src/orcapod/databases/_sql_writes.py | 61 -------- .../databases/connector_arrow_database.py | 142 +++--------------- src/orcapod/databases/postgresql_connector.py | 50 +----- src/orcapod/databases/sqlite_connector.py | 87 +---------- src/orcapod/errors.py | 18 ++- tests/test_databases/test_append_by_name.py | 137 +++++++++-------- .../test_connector_arrow_database.py | 90 +++-------- .../test_postgresql_connector.py | 55 ++----- .../test_postgresql_connector_integration.py | 3 +- .../test_sqlite_connector_integration.py | 3 +- tests/test_databases/type_matrix.py | 21 ++- 14 files changed, 215 insertions(+), 535 deletions(-) delete mode 100644 src/orcapod/databases/_sql_writes.py diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index a4f78a49f..169de14ed 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -7,14 +7,9 @@ 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. - SQLite now rolls back the full upsert on failure. A flush drops rows it identifies - as invalid and keeps the other attempted rows for retry. If a backend refuses the - data without identifying a row, it isolates the rows in one pass, commits valid - rows, and reports the rejected keys and their reasons. SQLite uses a transaction - per isolated row to handle rollback triggers and deferred foreign keys. - Partial commits preserve records guarded by results that became durable. - PostgreSQL rejects text containing NUL at enqueue. An interruption can leave - unsettled rows queued. Table creation and writes to separate tables commit - independently. When two handles update the same key, the last flush to commit - that key wins. + 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) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 3350a2715..988f5c3e1 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -134,18 +134,15 @@ adds, omits or retypes a column keeps each database's own rule. The order of a 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. That includes a flush of a row retained after a failure, even -if another handle has written that key in the meantime. Use -`skip_duplicates=True` to keep an already stored key. - -SQLite and PostgreSQL roll back a failed bulk upsert. If the backend refuses the -data without identifying the row, the flush tries each row once in order. SQLite -uses a transaction per row so that a rollback trigger or a deferred foreign key can -reject that row without losing earlier commits. PostgreSQL uses a savepoint per -row. The flush reports each dropped row's key and the backend's reason. Other -tables can still commit, and records guarded by committed results remain eligible -to write. An interruption leaves unsettled rows queued for retry. PostgreSQL -refuses text containing NUL at enqueue. +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 diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 6c1d85a49..8e3c589cf 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -8,12 +8,6 @@ import pyarrow as pa -class RejectedWriteRow: - """Attach the rejected row's input position to an atomic connector error.""" - - row_index: int | None = None - - class PendingCommit: """The outcome of an attempt to commit pending results.""" @@ -25,12 +19,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() @@ -83,16 +79,24 @@ def finish(self, key: str, *, committed: bool) -> None: attempt.finish(committed=committed) def finish_rows( - self, key: str, attempted: set[bytes], committed: set[bytes] + self, + key: str, + attempted: set[bytes], + *, + committed: bool, + discarded: dict[str, set[bytes]] | None = None, ) -> None: - """Release dependents of durable rows and withdraw those of failed rows.""" + """Resolve dependents of attempted rows, leaving other guards in place.""" attempts = self._attempts.get(key) if attempts is None: return - for record_id in attempts.keys() & attempted: - attempts.pop(record_id).finish(committed=record_id in committed) + 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( @@ -110,15 +114,25 @@ 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): + if held_ids is None: + return + removed = ids & held_ids + if not removed: return - held_ids.difference_update(ids) + held_ids.difference_update(removed) if held_ids: self._batches[key] = self._select(self._batches[key], ids, keep=False) else: @@ -127,6 +141,9 @@ def discard(self, key: str, ids: set[bytes], attempt: PendingCommit) -> None: 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 take_ready(self, key: str) -> tuple[pa.Table, set[bytes]] | None: """Take the records ready to commit, leaving blocked records readable.""" diff --git a/src/orcapod/databases/_sql_writes.py b/src/orcapod/databases/_sql_writes.py deleted file mode 100644 index 77ba4457a..000000000 --- a/src/orcapod/databases/_sql_writes.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Row isolation for a SQL upsert that rolled back after a data refusal.""" - -from __future__ import annotations - -from collections.abc import Callable, Iterable -from dataclasses import dataclass, field -from typing import Protocol, runtime_checkable - -import pyarrow as pa - - -@dataclass -class RowIsolation: - """Positions that became durable or were definitively refused.""" - - settled: set[int] = field(default_factory=set) - refused: dict[int, str] = field(default_factory=dict) - - -@runtime_checkable -class IsolatesRefusedRows(Protocol): - def isolate_refused_rows( - self, - table_name: str, - records: pa.Table, - id_column: str, - skip_existing: bool, - error: Exception, - progress: RowIsolation, - ) -> bool: - """After a refusal, commit other rows and record each settled position. - - Return False for an error that is not a data refusal. If isolation is - interrupted, retain any positions already settled. - """ - ... - - -class _Execute(Protocol): - def __call__(self, sql: str, params: tuple[object, ...] = (), /) -> object: ... - - -def write_with_savepoints( - execute: _Execute, - sql: str, - rows: Iterable[tuple[object, ...]], - is_refusal: Callable[[Exception], bool], -) -> dict[int, str]: - """Write rows in the caller's transaction, rolling back each refused statement.""" - refused: dict[int, str] = {} - for index, row in enumerate(rows): - execute("SAVEPOINT orcapod_row") - try: - execute(sql, row) - except Exception as error: - if not is_refusal(error): - raise - execute("ROLLBACK TO SAVEPOINT orcapod_row") - refused[index] = str(error) - execute("RELEASE SAVEPOINT orcapod_row") - return refused diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 2169d5b7b..b2f28f0fc 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -27,12 +27,7 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases._pending_commits import ( - PendingCommit, - PendingCommits, - RejectedWriteRow, -) -from orcapod.databases._sql_writes import IsolatesRefusedRows, RowIsolation +from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases.utils import ( coerce_record_id, declared_null_path, @@ -45,9 +40,9 @@ NullInNonNullableColumnError, OrcapodDatabaseError, OrcapodDatabaseReadError, + OrcapodDatabaseWriteError, UnstorableColumnError, UnstorableTableNameError, - UnsupportedValueError, ) from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol from orcapod.utils.arrow_utils import ( @@ -113,9 +108,10 @@ 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, - including a flush of a row retained after an earlier failure. With - ``skip_duplicates=True``, an existing durable key is kept. + 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 @@ -818,84 +814,12 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: """Commit one table's ready records.""" self._flush_by_key(self._get_record_key(record_path)) - def _write_pending_rows( - self, - table_name: str, - records: pa.Table, - skip_existing: bool, - retry_ids: set[bytes], - committed_ids: set[bytes], - ) -> None: - """Write the batch or isolate an unlocated data refusal once.""" - write = self._connector.upsert_records - id_column = self.RECORD_ID_COLUMN - try: - write(table_name, records, id_column, skip_existing=skip_existing) - except Exception as error: - if isinstance(error, RejectedWriteRow): - raise - progress = RowIsolation() - try: - isolated = isinstance( - self._connector, IsolatesRefusedRows - ) and self._connector.isolate_refused_rows( - table_name, records, id_column, skip_existing, error, progress - ) - if not isolated: - if not isinstance( - error, (InputValidationError, UnsupportedValueError) - ): - raise - # Use one atomic upsert per row for connectors without their own - # refusal isolation. - for index in range(records.num_rows): - try: - write( - table_name, - records.slice(index, 1), - id_column, - skip_existing=skip_existing, - ) - except (InputValidationError, UnsupportedValueError) as refused: - progress.refused[index] = str(refused) - progress.settled.add(index) - except BaseException as interrupted: - if progress.refused: - interrupted.add_note( - self._refused_rows_message( - table_name, records, progress.refused - ) - ) - raise - finally: - keys = records[id_column] - for index in progress.settled: - key = cast(bytes, keys[index].as_py()) - retry_ids.remove(key) - if index not in progress.refused: - committed_ids.add(key) - if progress.refused: - raise InputValidationError( - self._refused_rows_message(table_name, records, progress.refused) - ) from error - - def _refused_rows_message( - self, table_name: str, records: pa.Table, refused: dict[int, str] - ) -> str: - keys = records[self.RECORD_ID_COLUMN] - rows = "\n".join( - f" {keys[index].as_py()!r} — {reason}" for index, reason in refused.items() - ) - return f"Refused rows in table {table_name!r}\n{rows}" - 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 batch, ids = ready - retry_ids = ids.copy() - committed_ids: set[bytes] = set() pending = batch record_path = tuple(record_key.split("/")) table_name = self._path_to_table_name(record_path) @@ -932,7 +856,6 @@ def _fmt(cols: dict) -> str: + "}" ) - retry_ids = set() raise ValueError( f"Schema mismatch for table {table_name!r}: " f"existing={_fmt(existing_cols)}, " @@ -942,22 +865,9 @@ def _fmt(cols: dict) -> str: null_columns = _stored_null_columns(pending, existing) if null_columns: - valid = pc.is_valid(batch[null_columns[0]]) - for column in null_columns[1:]: - valid = pc.and_(valid, pc.is_valid(batch[column])) - retry_ids = set( - cast( - list[bytes], - batch[self.RECORD_ID_COLUMN].filter(valid).to_pylist(), - ) - ) - error = NullInNonNullableColumnError( + raise NullInNonNullableColumnError( null_columns[0], table=record_key ) - error.add_note( - f"Dropped {len(ids - retry_ids)} invalid queued row(s)." - ) - raise error # Checked by exact name and type above: only then are the rows put # in the stored order, by name (ITL-1367). @@ -966,29 +876,27 @@ def _fmt(cols: dict) -> str: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) - self._write_pending_rows( - table_name, pending, skip_existing, retry_ids, committed_ids + self._connector.upsert_records( + table_name, + pending, + id_column=self.RECORD_ID_COLUMN, + skip_existing=skip_existing, ) - except BaseException as error: - if isinstance(error, RejectedWriteRow) and error.row_index is not None: - index = error.row_index - dropped = cast(bytes, batch[self.RECORD_ID_COLUMN][index].as_py()) - retry_ids.remove(dropped) - error.add_note(f"Dropped queued row {dropped!r} from {record_key!r}.") - if retry_ids: - if retry_ids != ids: - batch = batch.filter( - pc.is_in( - batch[self.RECORD_ID_COLUMN], - value_set=pa.array(list(retry_ids), type=pa.large_binary()), - ) - ) - self._pending_commits.restore(record_key, batch, retry_ids) - self._pending_commits.finish_rows(record_key, ids, committed_ids) - self._pending_commits.forget(record_key, ids - retry_ids) + except Exception as error: + discarded = {record_key: ids.copy()} + self._pending_commits.finish_rows( + record_key, ids, committed=False, discarded=discarded + ) + self._pending_commits.forget(record_key, ids) + raise OrcapodDatabaseWriteError( + record_path, flush=True, table_flush=True, discarded_records=discarded + ) from error + except BaseException: + self._pending_commits.restore(record_key, batch, ids) + self._pending_commits.finish_rows(record_key, ids, committed=False) raise else: - self._pending_commits.finish_rows(record_key, ids, ids) + self._pending_commits.finish_rows(record_key, ids, committed=True) self._pending_commits.forget(record_key, ids) finally: if record_key not in self._pending_batches: diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index fbac7e3a6..0bd4fad7c 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -25,7 +25,6 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases._sql_writes import RowIsolation, write_with_savepoints from orcapod.databases.utils import is_direct_projection from orcapod.errors import UnstorableTableNameError, UnsupportedValueError from orcapod.types import ColumnInfo @@ -39,13 +38,6 @@ logger = logging.getLogger(__name__) -def _is_row_refusal(error: Exception) -> bool: - return isinstance( - error, - (psycopg.IntegrityError, psycopg.DataError, psycopg.errors.RaiseException), - ) - - # --------------------------------------------------------------------------- # Module-level helpers (pure functions, no I/O) # These are kept module-level so AsyncPostgreSQLConnector (future) can reuse @@ -677,37 +669,6 @@ def upsert_records( skip_existing: bool = False, ) -> None: """Write records to a table using upsert semantics.""" - self._upsert_records( - table_name, records, id_column, skip_existing, isolate=False - ) - - def isolate_refused_rows( - self, - table_name: str, - records: pa.Table, - id_column: str, - skip_existing: bool, - error: Exception, - progress: RowIsolation, - ) -> bool: - if not _is_row_refusal(error): - return False - refused = self._upsert_records( - table_name, records, id_column, skip_existing, isolate=True - ) - progress.refused.update(refused) - progress.settled.update(range(records.num_rows)) - return True - - def _upsert_records( - self, - table_name: str, - records: pa.Table, - id_column: str, - skip_existing: bool, - *, - isolate: bool, - ) -> dict[int, str]: self._require_table_name(table_name) with self._lock: conn = self._require_open() @@ -740,17 +701,8 @@ def _upsert_records( rows_iter = (tuple(row[c] for c in cols) for row in records.to_pylist()) try: with conn.cursor() as cur: - if isolate: - # Report deferred constraint violations inside the row's savepoint. - cur.execute("SET CONSTRAINTS ALL IMMEDIATE") - refused = write_with_savepoints( - cur.execute, sql, rows_iter, _is_row_refusal - ) - else: - cur.executemany(sql, rows_iter) - refused = {} + cur.executemany(sql, rows_iter) conn.commit() - return refused except BaseException: conn.rollback() raise diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index b5fec125f..be386fcab 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -23,22 +23,12 @@ import pyarrow as pa -from orcapod.databases._pending_commits import RejectedWriteRow -from orcapod.databases._sql_writes import RowIsolation from orcapod.databases.utils import is_direct_projection from orcapod.types import ColumnInfo logger = logging.getLogger(__name__) -class _SQLiteRejectedWriteRow(sqlite3.IntegrityError, RejectedWriteRow): - """A native SQLite integrity error with the index of the rejected row.""" - - -def _is_row_refusal(error: Exception) -> bool: - return isinstance(error, (sqlite3.IntegrityError, sqlite3.DataError)) - - # --------------------------------------------------------------------------- # Module-level helpers (pure functions, no I/O) # --------------------------------------------------------------------------- @@ -478,30 +468,6 @@ def upsert_records( skip_existing: If True, skip rows whose id already exists (INSERT OR IGNORE). If False, overwrite (INSERT OR REPLACE). """ - self._upsert_records(table_name, records, skip_existing) - - def isolate_refused_rows( - self, - table_name: str, - records: pa.Table, - id_column: str, - skip_existing: bool, - error: Exception, - progress: RowIsolation, - ) -> bool: - if not _is_row_refusal(error): - return False - self._upsert_records(table_name, records, skip_existing, progress=progress) - return True - - def _upsert_records( - self, - table_name: str, - records: pa.Table, - skip_existing: bool, - *, - progress: RowIsolation | None = None, - ) -> None: with self._lock: conn = self._require_open() self._validate_table_name(table_name) @@ -510,55 +476,14 @@ def _upsert_records( 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})' - row_index = -1 - - def rows() -> Iterator[tuple[Any, ...]]: - nonlocal row_index - for row_index, row in enumerate(records.to_pylist()): - yield tuple(row[c] for c in cols) - - if progress is not None: - # RAISE(ROLLBACK) ends the transaction, and a deferred foreign key - # is checked only at commit. Each row therefore owns a transaction. - for values in rows(): - conn.execute("BEGIN") - try: - conn.execute(sql, values) - conn.commit() - except BaseException as error: - if conn.in_transaction: - conn.rollback() - if not isinstance(error, Exception) or not _is_row_refusal( - error - ): - raise - progress.refused[row_index] = str(error) - progress.settled.add(row_index) - return - - conn.execute("BEGIN") + rows = (tuple(row[c] for c in cols) for row in records.to_pylist()) try: - conn.executemany(sql, rows()) - row_index = -1 # Commit-time failures have no individual row. + conn.execute("BEGIN") + conn.executemany(sql, rows) conn.commit() - except BaseException as error: - conn.rollback() - # sqlite3 steps each row before asking the iterator for the next one. - # These two constraints diagnose the row being stepped. - if ( - isinstance(error, sqlite3.IntegrityError) - and row_index >= 0 - and error.sqlite_errorcode - in ( - sqlite3.SQLITE_CONSTRAINT_NOTNULL, - sqlite3.SQLITE_CONSTRAINT_CHECK, - ) - ): - rejected = _SQLiteRejectedWriteRow(*error.args) - rejected.sqlite_errorcode = error.sqlite_errorcode - rejected.sqlite_errorname = error.sqlite_errorname - rejected.row_index = row_index - raise rejected from error + except BaseException: + if conn.in_transaction: + conn.rollback() raise @property 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/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index e3ec83edf..51edc8a45 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -38,6 +38,7 @@ from orcapod.errors import ( InputValidationError, NullInNonNullableColumnError, + OrcapodDatabaseWriteError, UnstorableColumnError, UnsupportedValueError, ) @@ -686,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 @@ -1196,13 +1197,19 @@ def test_stored_not_null_refusal_preserves_other_rows_and_tables( _add(reader, _nullable_values([(b"changed", 77)]), flush=True) else: _add(reader, seed, flush=True) - with pytest.raises(NullInNonNullableColumnError, match="'v'"): + with pytest.raises(OrcapodDatabaseWriteError, match="'v'") as raised: writer.flush() - expected = [ - {ID: b"changed", "v": 77 if stored_at_enqueue else 1}, - {ID: b"later", "v": 3}, - {ID: b"valid", "v": 2}, - ] + 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( @@ -1213,45 +1220,6 @@ def test_stored_not_null_refusal_preserves_other_rows_and_tables( assert _read_values(reader).to_pylist() == expected -@pytest.mark.parametrize("bad_first", [False, True]) -def test_sqlite_check_failure_drops_only_the_rejected_row( - tmp_path: Path, bad_first: bool -) -> None: - db_file = str(tmp_path / "store.db") - # CHECK is backend metadata the Arrow schema cannot describe. - 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, - SQLiteConnector(db_file) as reader_connector, - ): - writer = ConnectorArrowDatabase(connector) - reader = ConnectorArrowDatabase(reader_connector) - _add(reader, _nullable_values([(b"seed", 1)]), flush=True) - good = _nullable_values([(b"good-1", 2), (b"good-2", 3)]) - mixed = _nullable_values([(b"bad", -1), (b"good-3", 4)]) - for batch in (mixed, good) if bad_first else (good, mixed): - _add(writer, batch) - independent_path = ("independent",) - independent = _nullable_values([(b"other-1", 5), (b"other-2", 6)]) - writer.add_records(independent_path, independent, record_id_column=ID) - with pytest.raises(sqlite3.IntegrityError, match="CHECK"): - writer.flush() - assert _read_values(reader).to_pylist() == [{ID: b"seed", "v": 1}] - assert _read_values(reader, independent_path).equals(independent.sort_by(ID)) - expected = [ - {ID: b"good-1", "v": 2}, - {ID: b"good-2", "v": 3}, - {ID: b"good-3", "v": 4}, - {ID: b"seed", "v": 1}, - ] - assert _read_values(writer).to_pylist() == expected - 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( @@ -1274,13 +1242,15 @@ def test_connector_writes_to_the_same_key_follow_flush_order( refused = _nullable_values([(b"bad", -1)]) for batch in (refused, valid) if bad_first else (valid, refused): _add(writer_a, batch) - with pytest.raises(sqlite3.IntegrityError, match="CHECK"): + 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}, @@ -1290,8 +1260,13 @@ def test_connector_writes_to_the_same_key_follow_flush_order( @pytest.mark.parametrize("bad_first", [False, True]) @pytest.mark.parametrize("on_event_loop", [False, True]) @pytest.mark.parametrize("refusal", ["ABORT", "ROLLBACK", "deferred foreign key"]) -def test_sqlite_refusal_isolation_commits_valid_rows_and_names_rejected_keys( - tmp_path: Path, bad_first: bool, on_event_loop: bool, refusal: str +@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: @@ -1325,19 +1300,31 @@ def check() -> None: _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): - _add(writer, batch) - with pytest.raises(InputValidationError, match=message) as refused: + 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"good-1", "v": 2}, - {ID: b"good-2", "v": 3}, - {ID: b"seed", "v": 1}, - ] + expected = [{ID: b"seed", "v": 1}] assert _read_values(reader).to_pylist() == expected - assert "bad-1" in str(refused.value) and "bad-2" in str(refused.value) + 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() @@ -1349,7 +1336,7 @@ async def on_loop() -> None: @pytest.mark.parametrize("bad_first", [False, True]) -def test_partial_result_commit_preserves_records_guarded_by_committed_results( +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") @@ -1368,6 +1355,7 @@ def test_partial_result_commit_preserves_records_guarded_by_committed_results( 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): @@ -1382,19 +1370,38 @@ def test_partial_result_commit_preserves_records_guarded_by_committed_results( _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(InputValidationError, match="must be positive"): + with pytest.raises( + OrcapodDatabaseWriteError, match="must be positive" + ) as raised: results.flush_result_batch(PATH, publish_records=True) results.fail_pending_result(PATH) - assert _read_values(results).to_pylist() == [ - {ID: key, "v": value} for key, value in accepted - ] + 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 _read_values(results, dependent_path).to_pylist() == [ - {ID: b"record-" + key, "v": value} for key, value in accepted - ] + assert results.get_all_records(dependent_path, record_id_column=ID) is None @pytest.mark.parametrize("bad_first", [False, True]) diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index b147335f9..67d663cc4 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -36,7 +36,7 @@ # Imports under test — all of these will fail until the modules are created # --------------------------------------------------------------------------- -from orcapod.errors import UnsupportedValueError +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 @@ -848,83 +848,37 @@ def test_multiple_flushes_accumulate_records(self, db): assert result is not None assert result.num_rows == 2 - def test_failed_flush_retains_queued_rows_and_duplicate_policy( - self, monkeypatch: pytest.MonkeyPatch + @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) - path = self.PATH - db.add_record(path, b"old", make_table(v=[1]), flush=True) - db.add_record(path, b"old", make_table(v=[99]), skip_duplicates=True) - db.add_record(path, b"first", make_table(v=[2])) - db.add_record(path, b"second", make_table(v=[3])) + 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: Any, **kwargs: Any) -> None: - raise OSError("store temporarily unavailable") + 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(OSError, match="store temporarily unavailable"): - db.flush() - - pending_and_stored = db.get_all_records(path, record_id_column="id") - assert pending_and_stored is not None - assert pending_and_stored.sort_by("v")["v"].to_pylist() == [1, 2, 3, 99] - db.flush() - - reader = ConnectorArrowDatabase(connector) - stored = reader.get_all_records(path, record_id_column="id") - assert stored is not None - assert stored.sort_by("id").to_pylist() == [ - {"id": b"first", "v": 2}, - {"id": b"old", "v": 1}, - {"id": b"second", "v": 3}, - ] - - def test_non_sql_isolation_does_not_replay_rows_settled_before_an_interruption( - self, monkeypatch: pytest.MonkeyPatch - ) -> None: - connector = MockDBConnector() - db = ConnectorArrowDatabase(connector) - other_handle = ConnectorArrowDatabase(connector) - upsert = connector.upsert_records - path = self.PATH - db.add_records( - path, - pa.table({"id": [b"good", b"bad", b"later"], "v": [10, -1, 20]}), - record_id_column="id", - ) - - def reject_or_interrupt( - table_name: str, - records: pa.Table, - id_column: str, - skip_existing: bool = False, - ) -> None: - values = records["v"].to_pylist() - if -1 in values: - raise UnsupportedValueError("negative values are refused") - if 20 in values: - raise OSError("store temporarily unavailable") - upsert(table_name, records, id_column, skip_existing=skip_existing) - - with monkeypatch.context() as patch: - patch.setattr(connector, "upsert_records", reject_or_interrupt) with pytest.raises( - OSError, match="store temporarily unavailable" + OrcapodDatabaseWriteError, match="store unavailable" ) as raised: db.flush() - assert "b'bad' — negative values are refused" in "\n".join( - raised.value.__notes__ - ) - other_handle.add_record(path, b"good", make_table(v=[99]), flush=True) + assert all(repr(key) in str(raised.value) for key in keys) db.flush() - stored = other_handle.get_all_records(path, record_id_column="id") + 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.sort_by("id").to_pylist() == [ - {"id": b"good", "v": 99}, - {"id": b"later", "v": 20}, - ] + assert stored.to_pylist() == [{"id": b"old", "v": 99}] def test_second_flush_on_existing_table_upserts(self, db): """Flushing the same path twice should not duplicate rows.""" @@ -956,7 +910,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) @@ -966,7 +920,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 411688dd6..7d612efea 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -21,44 +21,31 @@ _coerce_pg_value, _pg_type_to_arrow, ) -from orcapod.errors import InputValidationError +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 the effects of savepoint commands.""" + """Track PostgreSQL's aborted transaction and durable writes.""" def __init__(self) -> None: self.committed = {b"seed": 1} self.pending = self.committed.copy() - self.savepoint: dict[bytes, int] | None = None self.aborted = False self.commands: list[str] = [] def execute(self, sql: str, row: tuple[bytes, int] | None = None) -> None: - if sql.startswith("ROLLBACK TO SAVEPOINT "): - assert self.savepoint is not None - self.pending = self.savepoint.copy() - self.aborted = False assert not self.aborted - if sql.startswith("SAVEPOINT "): - assert self.savepoint is None - self.savepoint = self.pending.copy() - elif sql.startswith("RELEASE SAVEPOINT "): - assert self.savepoint is not None - self.savepoint = None - elif sql.startswith("INSERT "): + 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 - elif not sql.startswith("ROLLBACK TO SAVEPOINT "): - assert sql.startswith("CREATE TABLE IF NOT EXISTS") or sql == ( - "SET CONSTRAINTS ALL IMMEDIATE" - ) + else: + assert sql.startswith("CREATE TABLE IF NOT EXISTS") self.commands.append(sql) def executemany(self, sql: str, rows: Iterable[tuple[bytes, int]]) -> None: @@ -67,14 +54,12 @@ def executemany(self, sql: str, rows: Iterable[tuple[bytes, int]]) -> None: def commit(self) -> None: assert not self.aborted - assert self.savepoint is None self.committed = self.pending.copy() self.commands.append("COMMIT") def rollback(self) -> None: self.aborted = False self.pending = self.committed.copy() - self.savepoint = None self.commands.append("ROLLBACK") def read(self) -> Iterator[pa.RecordBatch]: @@ -89,7 +74,7 @@ def read(self) -> Iterator[pa.RecordBatch]: @pytest.mark.parametrize("bad_first", [False, True]) @pytest.mark.parametrize("on_event_loop", [False, True]) -def test_postgresql_check_refusal_uses_savepoints_to_commit_valid_rows( +def test_postgresql_check_refusal_rolls_back_and_names_the_whole_batch( bad_first: bool, on_event_loop: bool ) -> None: transaction = _PostgreSQLTransaction() @@ -126,33 +111,21 @@ def check() -> None: for batch in (left, right) if bad_first else (right, left): writer.add_records(("t",), batch, record_id_column="id") with pytest.raises( - InputValidationError, match="must be positive" + 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.sort_by("id").to_pylist() == [ - {"id": b"good-1", "v": 11}, - {"id": b"good-2", "v": 12}, - {"id": b"seed", "v": 1}, - ] - assert "bad-1" in str(refused.value) and "bad-2" in str(refused.value) - assert ( - sum( - command.startswith("SAVEPOINT ") for command in transaction.commands - ) - == 4 - ) - assert ( - sum( - command.startswith("ROLLBACK TO SAVEPOINT ") - for command in transaction.commands - ) - == 2 + 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] == "COMMIT" + assert transaction.commands[-1] == "ROLLBACK" + cursor.executemany.assert_called_once() before = transaction.commands.copy() writer.flush() assert transaction.commands == before 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_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 a840c2694..417045856 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1131,18 +1131,15 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: 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. That includes a flush of a row retained after a failure, even -if another handle has written that key in the meantime. Use -`skip_duplicates=True` to keep an already stored key. - -SQLite and PostgreSQL roll back a failed bulk upsert. If the backend refuses the -data without identifying the row, the flush tries each row once in order. SQLite -uses a transaction per row so that a rollback trigger or a deferred foreign key can -reject that row without losing earlier commits. PostgreSQL uses a savepoint per -row. The flush reports each dropped row's key and the backend's reason. Other -tables can still commit, and records guarded by committed results remain eligible -to write. An interruption leaves unsettled rows queued for retry. PostgreSQL -refuses text containing NUL at enqueue. +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. """ From 744be4a58804e7b15ebb102a5a60621618e1d14b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 07:40:58 -0800 Subject: [PATCH 11/16] fix(databases): scope SQLite upsert conflicts to the record id (ITL-1490) INSERT OR IGNORE swallowed CHECK violations and INSERT OR REPLACE deleted a different row on a non-id UNIQUE collision. Use ON CONFLICT () DO NOTHING / DO UPDATE, as the PostgreSQL connector does, so every other constraint violation raises and rolls the batch back. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/sqlite_connector.py | 29 +++-- .../protocols/db_connector_protocol.py | 11 +- tests/test_databases/test_sqlite_connector.py | 107 ++++++++++++++++++ 3 files changed, 135 insertions(+), 12 deletions(-) diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index be386fcab..5dc434100 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -462,11 +462,14 @@ def upsert_records( 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: every other + constraint violation (``CHECK``, ``NOT NULL``, another ``UNIQUE`` + column) raises and rolls the whole batch back (ITL-1490). + skip_existing: If True, keep the stored row of an id that already + exists (``DO NOTHING``). If False, update it in place + (``DO UPDATE``). """ with self._lock: conn = self._require_open() @@ -474,8 +477,20 @@ 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()) try: conn.execute("BEGIN") diff --git a/src/orcapod/protocols/db_connector_protocol.py b/src/orcapod/protocols/db_connector_protocol.py index dc489eb87..57c4cddc2 100644 --- a/src/orcapod/protocols/db_connector_protocol.py +++ b/src/orcapod/protocols/db_connector_protocol.py @@ -108,16 +108,17 @@ def upsert_records( ) -> None: """Write records to a table atomically using upsert semantics. - Roll back the batch on a rejected write so the caller can safely retain - uncommitted records for another attempt. + 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_databases/test_sqlite_connector.py b/tests/test_databases/test_sqlite_connector.py index ac21ffac7..c2ea1ea78 100644 --- a/tests/test_databases/test_sqlite_connector.py +++ b/tests/test_databases/test_sqlite_connector.py @@ -34,6 +34,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 # --------------------------------------------------------------------------- @@ -407,6 +414,106 @@ def test_failed_upsert_rolls_back_the_whole_batch( ) 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")] + + 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"): From 7d2c26bb6be48fca0f94d20957cd9caec5946c69 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 07:40:59 -0800 Subject: [PATCH 12/16] fix(databases): flush each write policy separately; never replay an interrupted flush (ITL-1381) Rows queued with skip_duplicates and without it are written as two batches, so one policy never leaks to the other's rows. A BaseException during a flush removes the attempted batch and reports its keys as a failure does, then propagates: the write may have committed, so it is never retried. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1381.md | 9 ++ .../databases/connector_arrow_database.py | 147 ++++++++++++++---- .../test_connector_arrow_database.py | 88 ++++++++++- 3 files changed, 216 insertions(+), 28 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index 169de14ed..671371718 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -13,3 +13,12 @@ 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. (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. (ITL-1381) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b2f28f0fc..3c0d58406 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -132,7 +132,7 @@ def __init__( _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: @@ -152,10 +152,12 @@ def __init__( # 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 {} @@ -521,8 +523,8 @@ 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. + # 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[record_key] if pending_conflicts: mask = pc.invert( @@ -562,12 +564,15 @@ def add_records( self._pending_batches[record_key] = 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). + skipped = self._pending_skip_existing.setdefault(record_key, set()) if skip_duplicates: - # Mark this pending slot so flush() uses skip_existing=True. - self._pending_skip_existing[record_key] = True - self._pending_record_ids[record_key].update( - cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) - ) + skipped.update(queued_ids) + else: + skipped.difference_update(queued_ids) + self._pending_record_ids[record_key].update(queued_ids) if flush: self.flush() @@ -815,16 +820,91 @@ 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.""" + """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 commits or leaves the queue on its own; the first failure is + raised after both were tried. + """ ready = self._pending_commits.take_ready(record_key) if ready is None: return batch, ids = ready - pending = batch + skipped = self._pending_skip_existing.get(record_key, set()) + groups = [ + (group_ids, skip_existing) + for group_ids, skip_existing in ( + (ids - skipped, False), + (ids & skipped, True), + ) + if group_ids + ] + first_error: Exception | None = None + try: + for index, (group_ids, skip_existing) in enumerate(groups): + group = ( + batch + if len(groups) == 1 + else batch.filter( + pc.is_in( + batch[self.RECORD_ID_COLUMN], + pa.array( + list(group_ids), type=batch[self.RECORD_ID_COLUMN].type + ), + ) + ) + ) + try: + self._commit_batch(record_key, group, group_ids, 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}") + except BaseException: + # Batches not yet tried were never sent: they stay queued. + for untried_ids, _ in groups[index + 1 :]: + self._pending_commits.restore( + record_key, + batch.filter( + pc.is_in( + batch[self.RECORD_ID_COLUMN], + pa.array( + list(untried_ids), + type=batch[self.RECORD_ID_COLUMN].type, + ), + ) + ), + untried_ids, + ) + raise + finally: + remaining = self._pending_record_ids.get(record_key) + if remaining: + skipped.intersection_update(remaining) + else: + self._pending_skip_existing.pop(record_key, None) + if first_error is not None: + raise first_error + + def _commit_batch( + self, + record_key: str, + pending: pa.Table, + ids: set[bytes], + skip_existing: bool, + ) -> None: + """Write one batch taken from the queue with one write policy. + + The batch leaves the queue whatever happens: committed, or refused with + its keys, and the records guarded by them, removed and named (N32). A + ``BaseException`` (``KeyboardInterrupt``) is treated as a refusal, since + the write may have committed: the batch is never written again, the + removed keys are named in a note, and the exception propagates. + """ 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) - try: self._require_table_name(table_name) columns = _arrow_schema_to_column_infos(pending.schema) @@ -883,24 +963,37 @@ def _fmt(cols: dict) -> str: skip_existing=skip_existing, ) except Exception as error: - discarded = {record_key: ids.copy()} - self._pending_commits.finish_rows( - record_key, ids, committed=False, discarded=discarded - ) - self._pending_commits.forget(record_key, ids) + discarded = self._discard_attempted(record_key, ids) raise OrcapodDatabaseWriteError( record_path, flush=True, table_flush=True, discarded_records=discarded ) from error - except BaseException: - self._pending_commits.restore(record_key, batch, ids) - self._pending_commits.finish_rows(record_key, ids, committed=False) + except BaseException as error: + discarded = self._discard_attempted(record_key, ids) + 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_rows(record_key, ids, committed=True) self._pending_commits.forget(record_key, ids) - finally: - if record_key not in self._pending_batches: - self._pending_skip_existing.pop(record_key, None) + + 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.""" + 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/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 67d663cc4..6be0ac00f 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -26,7 +26,7 @@ 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 @@ -41,6 +41,7 @@ from orcapod.types import ColumnInfo from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.databases import ConnectorArrowDatabase +from orcapod.databases.sqlite_connector import SQLiteConnector # --------------------------------------------------------------------------- @@ -880,6 +881,91 @@ def refuse_write(*args: object, **kwargs: object) -> None: 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" + ) + assert rows is not None + return {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, + } + + 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) From 2238ac23b45f20a8b5450ea85a158c168ee694fc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 10:32:16 -0800 Subject: [PATCH 13/16] fix(databases): keep unsent policy batches queued and checked; require SQLite 3.24 (ITL-1381, ITL-1490) Each write-policy batch is taken from the queue only when it is written, split into new objects before the queue changes, so an interruption leaves unsent rows queued and the schema guard checks every write. SQLiteConnector refuses a SQLite library without upsert, and its docstring says a row skipped by its existing id is not checked further. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1381.md | 7 +- src/orcapod/databases/_pending_commits.py | 35 +++++++--- .../databases/connector_arrow_database.py | 66 +++++------------ src/orcapod/databases/sqlite_connector.py | 29 ++++++-- .../test_connector_arrow_database.py | 70 +++++++++++++++++++ tests/test_databases/test_sqlite_connector.py | 42 +++++++++++ 6 files changed, 184 insertions(+), 65 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index 671371718..7d1b14e20 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -16,9 +16,12 @@ - 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. (ITL-1490) + 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. (ITL-1381) + 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. (ITL-1381) diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 8e3c589cf..d7a61f8a2 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -145,24 +145,41 @@ def discard( discarded.setdefault(key, set()).update(removed) self.finish_rows(key, removed, committed=False, discarded=discarded) - def take_ready(self, key: str) -> tuple[pa.Table, set[bytes]] | None: - """Take the records ready to commit, leaving blocked records readable.""" + 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 rows of one write policy); the other + queued rows stay queued. ``None`` takes every ready row. + + The taken and the remaining rows are built as new objects before the queue + is changed, so an interruption while splitting leaves the queue as it was. + """ batch = self._batches.get(key) if batch is None or not batch.num_rows: return None + held = self._ids.get(key, set()) 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: + taken = (held if among is None else held & among) - blocked + if not taken: return None - self._batches[key] = self._select(batch, blocked, keep=True) - self._ids[key] = blocked - return self._select(batch, blocked, keep=False), ids + if taken == held: + self._batches.pop(key) + self._ids.pop(key, None) + return batch, taken + taken_rows = self._select(batch, taken, keep=True) + remaining_rows = self._select(batch, taken, keep=False) + remaining_ids = held - taken + self._batches[key] = remaining_rows + self._ids[key] = remaining_ids + return taken_rows, taken def restore(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: """Restore a retryable write ahead of rows that were held back.""" diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 3c0d58406..ec4a67be7 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -824,67 +824,35 @@ def _flush_by_key(self, record_key: str) -> None: 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 commits or leaves the queue on its own; the first failure is - raised after both were tried. + Each batch is taken from the queue only when it is written, so a batch not + yet sent stays queued, whatever interrupts the flush, and the table's schema + guard stays with it and checks its write too. Each batch commits or leaves + the queue on its own; the first failure is raised after both were tried. """ - ready = self._pending_commits.take_ready(record_key) - if ready is None: - return - batch, ids = ready - skipped = self._pending_skip_existing.get(record_key, set()) - groups = [ - (group_ids, skip_existing) - for group_ids, skip_existing in ( - (ids - skipped, False), - (ids & skipped, True), - ) - if group_ids - ] first_error: Exception | None = None try: - for index, (group_ids, skip_existing) in enumerate(groups): - group = ( - batch - if len(groups) == 1 - else batch.filter( - pc.is_in( - batch[self.RECORD_ID_COLUMN], - pa.array( - list(group_ids), type=batch[self.RECORD_ID_COLUMN].type - ), - ) - ) - ) + for skip_existing in (False, True): + skipped = self._pending_skip_existing.get(record_key, set()) + queued = self._pending_record_ids.get(record_key, set()) + among = queued & skipped if skip_existing else queued - skipped + ready = self._pending_commits.take_ready(record_key, among) + if ready is None: + continue + batch, ids = ready try: - self._commit_batch(record_key, group, group_ids, skip_existing) + self._commit_batch(record_key, batch, ids, 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}") - except BaseException: - # Batches not yet tried were never sent: they stay queued. - for untried_ids, _ in groups[index + 1 :]: - self._pending_commits.restore( - record_key, - batch.filter( - pc.is_in( - batch[self.RECORD_ID_COLUMN], - pa.array( - list(untried_ids), - type=batch[self.RECORD_ID_COLUMN].type, - ), - ) - ), - untried_ids, - ) - raise finally: remaining = self._pending_record_ids.get(record_key) - if remaining: - skipped.intersection_update(remaining) - else: + 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 diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 5dc434100..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 @@ -464,12 +481,14 @@ def upsert_records( records: Arrow table of records to write. 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: every other + (``ON CONFLICT ()``), as PostgreSQL's does: any other constraint violation (``CHECK``, ``NOT NULL``, another ``UNIQUE`` - column) raises and rolls the whole batch back (ITL-1490). - skip_existing: If True, keep the stored row of an id that already - exists (``DO NOTHING``). If False, update it in place - (``DO UPDATE``). + 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() diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 6be0ac00f..406d39a08 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -924,6 +924,76 @@ def test_a_skip_batch_does_not_change_the_policy_of_an_ordinary_write( 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_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_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).""" diff --git a/tests/test_databases/test_sqlite_connector.py b/tests/test_databases/test_sqlite_connector.py index c2ea1ea78..18f334755 100644 --- a/tests/test_databases/test_sqlite_connector.py +++ b/tests/test_databases/test_sqlite_connector.py @@ -2,6 +2,7 @@ from __future__ import annotations +import re import sqlite3 from collections.abc import Iterator from pathlib import Path @@ -112,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:") @@ -504,6 +525,27 @@ def test_id_conflicts_follow_the_policy_in_place( 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: From cae3ae7888d214b473d1e97004722e03e5d0513d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 11:15:01 -0800 Subject: [PATCH 14/16] fix(databases): replace a table's queued rows and ids in one step (ITL-1381) The pending queue held a table's rows and its id set in two dicts, changed by two assignments: an interrupt between them left them out of step and the next flush lost the unsent row. PendingCommits now holds one immutable QueuedRows per key, replaced by a single assignment; the databases read it through read-only views. A connector flush leaves a batch queued until its write is tried and removes it inside the guarded write. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1381.md | 4 +- src/orcapod/databases/_pending_commits.py | 176 ++++++++++++++---- .../databases/connector_arrow_database.py | 60 +++--- src/orcapod/databases/delta_lake_databases.py | 47 +++-- src/orcapod/databases/in_memory_databases.py | 46 ++--- .../function_pod/test_ephemeral_result.py | 4 +- .../test_connector_arrow_database.py | 93 ++++++++- 7 files changed, 303 insertions(+), 127 deletions(-) diff --git a/changelog.d/ITL-1381.md b/changelog.d/ITL-1381.md index 7d1b14e20..31ce6301f 100644 --- a/changelog.d/ITL-1381.md +++ b/changelog.d/ITL-1381.md @@ -24,4 +24,6 @@ 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. (ITL-1381) + 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/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index d7a61f8a2..09e810187 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -2,12 +2,58 @@ 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 an attempt to commit pending results.""" @@ -36,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, 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] @@ -126,18 +197,17 @@ def discard( 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: + held = self._queue.get(key) + if held is None: return - removed = ids & held_ids + removed = ids & held.ids if not removed: return - held_ids.difference_update(removed) - 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) @@ -145,47 +215,71 @@ def discard( discarded.setdefault(key, set()).update(removed) self.finish_rows(key, removed, committed=False, discarded=discarded) - def take_ready( - self, key: str, among: set[bytes] | None = None + def peek_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. + """The records ready to commit, left in the queue (blocked ones excluded). Args: key: The table's key. - among: Take only these ids (the rows of one write policy); the other - queued rows stay queued. ``None`` takes every ready row. + among: Only these ids (the rows of one write policy). ``None``: every + ready row. - The taken and the remaining rows are built as new objects before the queue - is changed, so an interruption while splitting leaves the queue as it was. + 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. """ - batch = self._batches.get(key) - if batch is None or not batch.num_rows: + held = self._queue.get(key) + if held is None or not held.table.num_rows: return None - held = self._ids.get(key, set()) blocked = { record_id for record_id, attempt in self._guards.get(key, {}).items() if not attempt.committed } - taken = (held if among is None else held & among) - blocked - if not taken: + ready = set(held.ids if among is None else held.ids & among) - blocked + if not ready: return None - if taken == held: - self._batches.pop(key) - self._ids.pop(key, None) - return batch, taken - taken_rows = self._select(batch, taken, keep=True) - remaining_rows = self._select(batch, taken, keep=False) - remaining_ids = held - taken - self._batches[key] = remaining_rows - self._ids[key] = remaining_ids - return taken_rows, taken - - def restore(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: + 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. + + 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.""" @@ -198,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 ec4a67be7..d3bbd114d 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -19,7 +19,6 @@ from __future__ import annotations import re -from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from typing import Any, cast @@ -130,8 +129,6 @@ 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, set[bytes]] | None = None, _root: ConnectorArrowDatabase | None = None, _scoped_path: tuple[str, ...] = (), @@ -141,14 +138,6 @@ 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] = {} @@ -168,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.""" @@ -525,7 +516,9 @@ def add_records( # Committed duplicates are handled at flush time via # 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[record_key] + pending_conflicts = input_ids & self._pending_record_ids.get( + record_key, frozenset() + ) if pending_conflicts: mask = pc.invert( pc.is_in( @@ -537,7 +530,9 @@ def add_records( if records.num_rows == 0: return 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. " @@ -556,23 +551,26 @@ def add_records( # 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: # 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) - self._pending_batches[record_key] = pa.concat_tables( - _alike([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). + # 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_record_ids[record_key].update(queued_ids) + self._pending_commits.queue( + record_key, + queued, + self._pending_record_ids.get(record_key, frozenset()).union(queued_ids), + ) if flush: self.flush() @@ -722,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: @@ -747,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, @@ -824,9 +820,10 @@ def _flush_by_key(self, record_key: str) -> None: 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 is taken from the queue only when it is written, so a batch not - yet sent stays queued, whatever interrupts the flush, and the table's schema - guard stays with it and checks its write too. Each batch commits or leaves + Each batch stays in the queue until its write is tried (``_commit_batch`` + takes it out, in one step), so a batch not yet sent stays queued, whatever + interrupts the flush, and the table's schema guard stays with it and checks + its write too. Each batch commits or leaves the queue on its own; the first failure is raised after both were tried. """ first_error: Exception | None = None @@ -835,7 +832,8 @@ def _flush_by_key(self, record_key: str) -> None: skipped = self._pending_skip_existing.get(record_key, set()) queued = self._pending_record_ids.get(record_key, set()) among = queued & skipped if skip_existing else queued - skipped - ready = self._pending_commits.take_ready(record_key, among) + # Left in the queue until its write is tried (``_commit_batch``). + ready = self._pending_commits.peek_ready(record_key, among) if ready is None: continue batch, ids = ready @@ -930,6 +928,9 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) + # Inside the try: an interruption after the write still takes the rows + # out of the queue (below), so they are never written again. + self._pending_commits.remove(record_key, ids) except Exception as error: discarded = self._discard_attempted(record_key, ids) raise OrcapodDatabaseWriteError( @@ -956,6 +957,7 @@ def _discard_attempted( ) -> dict[str, set[bytes]]: """Withdraw an attempted batch's keys and the records they guard; return every removed key, by table.""" + self._pending_commits.remove(record_key, ids) discarded = {record_key: ids.copy()} self._pending_commits.finish_rows( record_key, ids, committed=False, discarded=discarded 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/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_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 406d39a08..c3ab44a00 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -888,8 +888,7 @@ def _stored_values( rows = ConnectorArrowDatabase(connector).get_all_records( path, record_id_column="id" ) - assert rows is not None - return {row["id"]: row["v"] for row in rows.to_pylist()} + 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( @@ -971,6 +970,96 @@ def wrapped(*args: Any, **kwargs: Any) -> Any: } 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) before any line 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).""" + 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 + + 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 + if event == "line": + 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).""" From d312eba0115d8bba195618cc1e351bff00dd52c5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 11:45:20 -0800 Subject: [PATCH 15/16] fix(databases): take a batch out of the queue before its write is tried (ITL-1381) A connector that committed and then raised, with an interrupt at the start of the failure cleanup, left the committed batch queued and the next flush wrote it again. _commit_batch now records the batch's ids as attempted and takes it out of the queue in one step before the write; any failure or interruption after that reports the keys as removed, so no write is ever tried twice (N32, N49). Co-Authored-By: Claude Opus 5.5 --- .../databases/connector_arrow_database.py | 67 +++++++++------- .../test_connector_arrow_database.py | 78 +++++++++++++++++-- 2 files changed, 112 insertions(+), 33 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index d3bbd114d..ee07ad400 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -19,7 +19,7 @@ from __future__ import annotations import re -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Set from contextlib import AbstractContextManager from typing import Any, cast @@ -820,25 +820,20 @@ def _flush_by_key(self, record_key: str) -> None: 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 stays in the queue until its write is tried (``_commit_batch`` - takes it out, in one step), so a batch not yet sent stays queued, whatever - interrupts the flush, and the table's schema guard stays with it and checks - its write too. Each batch commits or leaves + 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, set()) + queued = self._pending_record_ids.get(record_key, frozenset[bytes]()) among = queued & skipped if skip_existing else queued - skipped - # Left in the queue until its write is tried (``_commit_batch``). - ready = self._pending_commits.peek_ready(record_key, among) - if ready is None: - continue - batch, ids = ready try: - self._commit_batch(record_key, batch, ids, skip_existing) + self._commit_batch(record_key, among, skip_existing) except Exception as error: if first_error is None: first_error = error @@ -857,21 +852,35 @@ def _flush_by_key(self, record_key: str) -> None: def _commit_batch( self, record_key: str, - pending: pa.Table, - ids: set[bytes], + among: Set[bytes], skip_existing: bool, ) -> None: - """Write one batch taken from the queue with one write policy. + """Take one write policy's ready rows out of the queue and write them. - The batch leaves the queue whatever happens: committed, or refused with - its keys, and the records guarded by them, removed and named (N32). A - ``BaseException`` (``KeyboardInterrupt``) is treated as a refusal, since - the write may have committed: the batch is never written again, the - removed keys are named in a note, and the exception propagates. + 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) 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) @@ -928,16 +937,17 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) - # Inside the try: an interruption after the write still takes the rows - # out of the queue (below), so they are never written again. - self._pending_commits.remove(record_key, ids) except Exception as error: - discarded = self._discard_attempted(record_key, ids) + 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: - discarded = self._discard_attempted(record_key, ids) + 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." @@ -949,14 +959,15 @@ def _fmt(cols: dict) -> str: ) raise else: - self._pending_commits.finish_rows(record_key, ids, committed=True) - 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.""" + 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( diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index c3ab44a00..d7f99134b 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -973,10 +973,11 @@ def wrapped(*args: Any, **kwargs: Any) -> Any: def test_an_interrupt_between_any_two_lines_of_a_flush_loses_no_row( self, ) -> None: - """A KeyboardInterrupt injected (by a line trace) before any line 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 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.""" import sys from pathlib import Path @@ -1017,6 +1018,7 @@ def upsert_records( 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 @@ -1026,7 +1028,12 @@ def trace(frame: Any, event: str, arg: Any) -> Any: and code.co_name not in traced_functions ): return None - if event == "line": + # 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 @@ -1083,6 +1090,67 @@ def refuse(schema: pa.Schema) -> None: ) 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).""" From 4c5bdf753e7dbe28e24224f2d6e016f4c2c68d0c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 11:59:51 -0800 Subject: [PATCH 16/16] test(databases): note why the line-trace test interrupts between statements (ITL-1381) Co-Authored-By: Claude Opus 5.5 --- tests/test_databases/test_connector_arrow_database.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index d7f99134b..42d3e46c2 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -977,7 +977,13 @@ def test_an_interrupt_between_any_two_lines_of_a_flush_loses_no_row( 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.""" + 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