From b93c3f0ac6527a92cc899ef230b0d44c5dd7faee Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 01:38:03 -0800 Subject: [PATCH 01/13] feat(databases): a tested matrix of the types each database keeps; every type kept or refused ITL-1334. tests/test_databases/type_matrix.py writes and reads 73 column types (every integer width, floats, decimals, temporal types of every unit and zone, text and binary, lists, fixed-size lists, structs, maps, nullability, every Orcapod logical type and the library value types) through the in-memory, Delta, SQLite, PostgreSQL (the connector's rule, no server) and SpiralDB (disk fake) databases. Each cell is kept, kept through a recorded type, or refused naming the column; test_type_matrix.py fails on any other outcome and on a drift of docs/reference/database-types.md, which scripts/database_type_matrix.py writes. The silent cells found on main, fixed: - Delta keeps float16 (as float32), fixed-size lists, nested and with null rows (as large_list; they read back as large_list or not at all), fixed-size binary and lists with non-null items, through the recorded-type mechanism; a restore that cannot be exact raises naming the column (ITL-1275, ITL-1283, also ITL-999). - Delta refuses what it cannot hold (decimal256, an interval, as its own writer's conversion decides; a new all-null untyped column) with UnstorableColumnError before anything is buffered, also as the job's up-front check (require_storable). - SQLite and PostgreSQL read a NOT NULL column back non-null (ITL-1276). - SpiralDB refuses logical (extension) types, which it would give back as storage types, and reads a fixed-size list with non-null items and a null row (only changed columns are cast). - The SpiralDB fake rebuilds a map from its parts: pyarrow 23 aborts casting it. No golden value moves (--check matches). Fixes ITL-1334, ITL-1275, ITL-1283, ITL-1276 Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1334.md | 43 ++ docs/concepts/pipeline-job.md | 22 +- docs/reference/database-types.md | 185 +++++ scripts/database_type_matrix.py | 48 ++ site/astro.config.mjs | 1 + src/orcapod/contexts/stored.py | 5 +- src/orcapod/databases/delta_arrow_types.py | 189 ++++- src/orcapod/databases/delta_lake_databases.py | 111 +++ src/orcapod/databases/postgresql_connector.py | 22 +- src/orcapod/databases/spiraldb_connector.py | 30 +- src/orcapod/databases/spiraldb_nullability.py | 24 +- src/orcapod/databases/sqlite_connector.py | 9 +- src/orcapod/errors.py | 8 +- tests/test_databases/fake_pyspiral.py | 22 + .../test_databases/test_delta_append_types.py | 26 +- .../test_delta_arrow_type_roundtrip.py | 152 ++++ .../test_delta_read_your_writes.py | 27 +- .../test_postgresql_connector.py | 29 + .../test_spiraldb_connector_fake.py | 48 ++ tests/test_databases/test_sqlite_connector.py | 32 + tests/test_databases/test_type_matrix.py | 78 ++ tests/test_databases/type_matrix.py | 727 ++++++++++++++++++ .../test_function_node_stored_values.py | 14 - 23 files changed, 1771 insertions(+), 81 deletions(-) create mode 100644 changelog.d/ITL-1334.md create mode 100644 docs/reference/database-types.md create mode 100644 scripts/database_type_matrix.py create mode 100644 tests/test_databases/test_type_matrix.py create mode 100644 tests/test_databases/type_matrix.py diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md new file mode 100644 index 000000000..3943792e8 --- /dev/null +++ b/changelog.d/ITL-1334.md @@ -0,0 +1,43 @@ +### Added + +- **Data types per database:** a new reference page, + `docs/reference/database-types.md`, lists every Arrow type + (integers of every width, floats, decimals, dates, times, timestamps of every unit and + zone, durations, text and binary, lists, fixed-size lists, structs, maps, nullability, + every Orcapod logical type and the library value types) for every database (in-memory, + Delta Lake, SQLite, PostgreSQL, SpiralDB): kept, kept through a recorded type, or + refused. It is generated from a test that writes and reads each type through each + database, and that fails if any database gives a column back as another type without an + error. (ITL-1334) +- **`DeltaTableDatabase` keeps more types:** `float16` (written as `float32`, which holds + every `float16` exactly), fixed-size lists, also nested and with null rows (written as a + `large_list`; a fixed-size list used to read back as a `large_list`, and with a null row + could not be read back at all), fixed-size binary (read back as `large_binary` before) + and lists with non-null items (their item field was renamed `element`), all through the + recorded-type mechanism already used for unsigned integers and nanosecond timestamps. + A restore never pads, cuts or rounds: stored rows that cannot be what was written raise, + naming the column. (ITL-1275, ITL-1283, ITL-1334) + +### Changed + +- **`DeltaTableDatabase` refuses what Delta cannot hold, naming the column:** a + `decimal256` or an interval column (as Delta's own writer decides), and a new column + holding only nulls with no type, raise `UnstorableColumnError` when added, before + anything is buffered, and a job refuses such a column up front (`require_storable`). They + used to fail the flush with an error that named no column. A `null`-typed value in a + column the table already stores with a type is still kept. (ITL-1334) +- **The SQLite and PostgreSQL connectors read a non-null column back non-null:** the + column is created `NOT NULL`, and the read now gives the field that flag; it read back + nullable before. (ITL-1276) +- **`SpiralDBConnector` refuses a logical (extension) type:** `File`, `Directory`, + `Path`, `UPath`, `UUID`, `list[T]` and `set[T]` of them, user classes and the library + value types read back from SpiralDB as their plain storage type (SpiralDB drops the + field metadata that names them). They are refused with `UnstorableColumnError` before + anything is written. (ITL-1334) + +### Fixed + +- **`SpiralDBConnector` reads back a fixed-size list with non-null items and a null row:** + the read cast every column to the restored schema, and pyarrow refuses that cast when a + null row hides null item slots; only columns whose type changes are cast now. + (ITL-1334) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 4e3d61e4c..4eda01f0d 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -108,7 +108,15 @@ Any Orcapod database can hold a job's results. Two are used most: - **`InMemoryArrowDatabase()`** keeps results for the lifetime of the Python process. Use it for experiments and tests. - **`DeltaTableDatabase("some/directory")`** writes [Delta Lake](https://delta.io/) tables - under a directory, and is what makes results survive between sessions. + under a directory, and is what makes results survive between sessions. It keeps every + type Orcapod uses: where Delta has no column type (an unsigned integer, a nanosecond + timestamp, `float16`, a fixed-size list), the column's Arrow type is recorded and + restored on read. It refuses, naming the column, the few types Delta cannot hold at all + (`decimal256`, an interval) and a new column holding only nulls with no type. + +No database gives a column back as another type: each keeps a type exactly or refuses it +before anything of the table is written. [Data types per database](../reference/database-types.md) +lists every type for every database. On disk the layout is `///...` for each function, plus `//_result/...`. The job's `name` is the top level, so jobs with @@ -134,11 +142,15 @@ and binary columns come back as `large_string` and `large_binary`, the types Orc | `SQLiteConnector` | `bool`, `int64`, `double`, `large_string`, `large_binary` | | `PostgreSQLConnector` | `bool`, `int32`, `int64`, `float`, `double`, `large_string`, `large_binary`, `date32`, `timestamp[us]`, `timestamp[us, tz=UTC]` | -Any other type (lists, structs, dates or timestamps on SQLite, narrower integers and floats, -logical types) is refused. PostgreSQL also refuses a column name or a table name longer than +A non-null column is created `NOT NULL` and reads back non-null. Any other type (lists, +structs, dates or timestamps on SQLite, narrower integers and floats, logical types) is +refused. PostgreSQL also refuses a column name or a table name longer than 63 bytes, which it would truncate (`UnstorableTableNameError` for a table). `SpiralDBConnector` stores other types as written, except a -timestamp with a time zone (SpiralDB drops the zone), and SpiralDB reserves the `__` prefix on -value columns (the `__record_id` key is allowed) and `.` in any column name. +timestamp with a time zone (SpiralDB drops the zone), a logical (extension) type such as +`File`, `Path`, `UUID`, a user class or `set[int]` (SpiralDB drops the field metadata that +names it), and a null struct; SpiralDB reserves the `__` prefix on +value columns (the `__record_id` key is allowed) and `.` in any column name. The full list, +type by type, is [Data types per database](../reference/database-types.md). Orcapod's own stored tables hold such columns. A function node's result table holds list-valued executor columns and `__`-prefixed columns. A side-effect node's log holds a UTC diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md new file mode 100644 index 000000000..d17371391 --- /dev/null +++ b/docs/reference/database-types.md @@ -0,0 +1,185 @@ +# Data types per database + + + +Each database Orcapod stores into keeps some Arrow types exactly and refuses the others. +None of them gives a column back as another type: a type a database cannot keep is +refused, with an error naming the column, before anything of the table is written. This +page lists every type for every database. It is generated from a test that writes and +reads each type through each database, so it cannot drift from the code. + +What a cell says: + +- **kept**: read back exactly, with its Arrow type (nested field names and nullability + included) and its values. Text, binary and list columns may come back in their large + variants (`large_string`, `large_binary`, `large_list`), the types every Orcapod table + uses. +- **kept (recorded type)**: kept by `DeltaTableDatabase` through a recorded type. Delta Lake + has no column type for it, so the column's Arrow type is recorded in its field metadata, + its values are written in a form Delta keeps (an integer form, `float32` for + `float16`, a `large_list` for a fixed-size list) and the type is restored on read. +- **kept (by rule)**: PostgreSQL stores the column, by the connector's own rule. No + PostgreSQL server is used to build this page, so this cell is the rule, not a measured + read. +- **refused**: writing the column raises an error naming it (`UnstorableColumnError` for + a connector database), and nothing of the table is written. + +How it is measured: a table holding two columns of the type (the second nullable, with a +null row) is written with `add_records`, flushed and read back with `get_all_records`. +The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which +models what SpiralDB does to a column (no SpiralDB is used). No database tells tag +columns from data columns, so a type is kept or refused the same way in either role. +The library value types (NumPy, pandas, Polars, torch) are +[provisional](../concepts/arrays.md): their stored form may change in a later release. + +The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and +`ConnectorArrowDatabase` over `SQLiteConnector`, `PostgreSQLConnector` and +`SpiralDBConnector`. See [The database](../concepts/pipeline-job.md#the-database) for how a +job uses one. + +Three refusals depend on the values as well as the type: + +- SpiralDB cannot store a null struct, so a struct column with a null row is refused + (the rows below have one); a struct column with no null row is kept. +- Delta has no `null` type: a new column holding only nulls with no type is refused (the + `null` row below), while a `null`-typed value is kept in a column the table already + stores with a type. +- A fixed-size list or fixed-size binary read back by Delta with another length or width + than its type is refused on read, never padded or cut. + +## Integer + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `int8` | kept | kept | refused | refused | kept | +| `int16` | kept | kept | refused | refused | kept | +| `int32` | kept | kept | refused | kept (by rule) | kept | +| `int64` | kept | kept | kept | kept (by rule) | kept | +| `uint8` | kept | kept (recorded type) | refused | refused | kept | +| `uint16` | kept | kept (recorded type) | refused | refused | kept | +| `uint32` | kept | kept (recorded type) | refused | refused | kept | +| `uint64` | kept | kept (recorded type) | refused | refused | kept | + +## Float + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `halffloat (float16)` | kept | kept (recorded type) | refused | refused | kept | +| `float (float32)` | kept | kept | refused | kept (by rule) | kept | +| `double (float64)` | kept | kept | kept | kept (by rule) | kept | + +## Decimal + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `decimal128(10, 2)` | kept | kept | refused | refused | kept | +| `decimal128(38, 4)` | kept | kept | refused | refused | kept | +| `decimal256(40, 2)` | kept | refused | refused | refused | kept | +| `decimal256(76, 10)` | kept | refused | refused | refused | kept | + +## Boolean + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `bool` | kept | kept | kept | kept (by rule) | kept | + +## Null + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `null` | kept | refused | refused | refused | kept | + +## Temporal + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `date32` | kept | kept | refused | kept (by rule) | kept | +| `date64` | kept | kept (recorded type) | refused | refused | kept | +| `time32[s]` | kept | kept (recorded type) | refused | refused | kept | +| `time32[ms]` | kept | kept (recorded type) | refused | refused | kept | +| `time64[us]` | kept | kept (recorded type) | refused | refused | kept | +| `time64[ns]` | kept | kept (recorded type) | refused | refused | kept | +| `timestamp[s]` | kept | kept (recorded type) | refused | refused | kept | +| `timestamp[ms]` | kept | kept (recorded type) | refused | refused | kept | +| `timestamp[us]` | kept | kept | refused | kept (by rule) | kept | +| `timestamp[ns]` | kept | kept (recorded type) | refused | refused | kept | +| `timestamp[s, tz=UTC]` | kept | kept (recorded type) | refused | refused | refused | +| `timestamp[ms, tz=UTC]` | kept | kept (recorded type) | refused | refused | refused | +| `timestamp[us, tz=UTC]` | kept | kept | refused | kept (by rule) | refused | +| `timestamp[ns, tz=UTC]` | kept | kept (recorded type) | refused | refused | refused | +| `timestamp[s, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | +| `timestamp[ms, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | +| `timestamp[us, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | +| `timestamp[ns, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | +| `duration[s]` | kept | kept (recorded type) | refused | refused | kept | +| `duration[ms]` | kept | kept (recorded type) | refused | refused | kept | +| `duration[us]` | kept | kept (recorded type) | refused | refused | kept | +| `duration[ns]` | kept | kept (recorded type) | refused | refused | kept | + +## String and binary + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `string` | kept | kept | kept | kept (by rule) | kept | +| `large_string` | kept | kept | kept | kept (by rule) | kept | +| `binary` | kept | kept | kept | kept (by rule) | kept | +| `large_binary` | kept | kept | kept | kept (by rule) | kept | +| `fixed_size_binary[4]` | kept | kept (recorded type) | refused | refused | kept | + +## List + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `list` | kept | kept | refused | refused | kept | +| `list` | kept | kept (recorded type) | refused | refused | kept | +| `large_list` | kept | kept | refused | refused | kept | +| `large_list` | kept | kept (recorded type) | refused | refused | kept | +| `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | kept | +| `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | kept | +| `large_list` | kept | kept (recorded type) | refused | refused | kept | + +## Struct and map + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `struct` | kept | kept | refused | refused | refused | +| `struct[2]>` | kept | kept (recorded type) | refused | refused | refused | +| `map` | kept | kept | refused | refused | kept | + +## Nullability + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `int64 not null` | kept | kept | kept | kept (by rule) | kept | +| `string not null` | kept | kept | kept | kept (by rule) | kept | + +## Orcapod logical type + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `File` | kept | kept | refused | refused | refused | +| `Directory` | kept | kept | refused | refused | refused | +| `Path` | kept | kept | refused | refused | refused | +| `UPath` | kept | kept | refused | refused | refused | +| `uuid.UUID` | kept | kept | refused | refused | refused | +| `list[Path]` | kept | kept | refused | refused | refused | +| `set[int]` | kept | kept | refused | refused | refused | +| `set[uuid.UUID]` | kept | kept | refused | refused | refused | +| `dict[str, int]` | kept | kept | refused | refused | kept | +| `user class, exact (dataclass)` | kept | kept | refused | refused | refused | +| `user class, structural (orcapod.dataclass)` | kept | kept | refused | refused | refused | + +## Library value type + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `numpy.ndarray` (provisional) | kept | kept | refused | refused | refused | +| `pandas.DataFrame` (provisional) | kept | kept | refused | refused | refused | +| `pandas.Series` (provisional) | kept | kept | refused | refused | refused | +| `polars.DataFrame` (provisional) | kept | kept | refused | refused | refused | +| `polars.Series` (provisional) | kept | kept | refused | refused | refused | +| `torch.Tensor` (provisional) | kept | kept | refused | refused | refused | diff --git a/scripts/database_type_matrix.py b/scripts/database_type_matrix.py new file mode 100644 index 000000000..409adce80 --- /dev/null +++ b/scripts/database_type_matrix.py @@ -0,0 +1,48 @@ +"""Write, or check, the data-types-per-database page (ITL-1334). + +usage: uv run python scripts/database_type_matrix.py [--check] + +Measures every cell of the matrix (``tests/test_databases/type_matrix.py``: every type +written and read back through every database, in a temporary directory) and writes +``docs/reference/database-types.md``. With ``--check`` it writes nothing and exits 1 when +the committed page differs from the measurements. +""" + +from __future__ import annotations + +import argparse +import logging +import sys +import tempfile +import warnings +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + + +def main() -> int: + """Measure the matrix and write or check the page.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="compare, write nothing") + args = parser.parse_args() + + from tests.test_databases.type_matrix import PAGE, measure_all, render + + warnings.simplefilter("ignore") + logging.disable(logging.WARNING) + with tempfile.TemporaryDirectory() as tmp: + text = render(measure_all(Path(tmp))) + if args.check: + if PAGE.read_text(encoding="utf-8") != text: + print(f"{PAGE} differs from the measurements; run without --check") + return 1 + print(f"{PAGE} matches the measurements") + return 0 + PAGE.write_text(text, encoding="utf-8") + print(f"wrote {PAGE}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/site/astro.config.mjs b/site/astro.config.mjs index 818e80bb1..e8407a005 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -156,6 +156,7 @@ export default defineConfig({ page('Hashing', 'reference/hashing'), page('Golden hashes', 'reference/golden-hashes'), page('Data function types', 'reference/data-function-types'), + page('Data types per database', 'reference/database-types'), ], }, page('Troubleshooting', 'troubleshooting'), diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 605c04c92..c72357c10 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -602,8 +602,9 @@ def require_storable(database: object, schema: pa.Schema) -> None: The one check for ``ColumnCheckingDatabaseProtocol`` (ITL-1162): a job node asks it about each table it stores when a database is attached, before anything runs. - A database that states no rule (in-memory, Delta) stores every column, and - nothing is checked. + A database that states no rule (in-memory) stores every column, and nothing is + checked. Delta states one: the types it cannot hold even through a recorded type + (ITL-1334). Args: database: Any database object. diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index 144bedf8e..7c1010235 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -1,10 +1,14 @@ -"""Keep a column's Arrow type through a Delta table (ITL-928). +"""Keep a column's Arrow type through a Delta table (ITL-928, ITL-1334). Delta Lake has no unsigned integer, no nanosecond, second or millisecond timestamp, -no zone other than UTC, and no ``date64``, ``time`` or ``duration`` type. The Delta -writer converts the first kinds (unsigned to the signed type of the same width, which -fails for a value above the signed maximum; every timestamp to microseconds, dropping -nanosecond digits; a zone to UTC) and cannot store the others at all. +no zone other than UTC, no ``date64``, ``time``, ``duration``, ``float16`` or fixed-size +binary type, and no fixed-size list. The Delta writer converts the first kinds +(unsigned to the signed type of the same width, which fails for a value above the signed +maximum; every timestamp to microseconds, dropping nanosecond digits; a zone to UTC; a +fixed-size binary to ``large_binary``; a fixed-size list to a list, which reads back as +``large_list`` and, with a null row, cannot be read back as a fixed-size list at all), +renames the item field of a list whose items are non-null (``item`` to ``element``), and +cannot store the others. A Delta database must give back the type it was given: a tag read back with another type changes every record id computed from it. So before a write, a column whose type Delta @@ -15,12 +19,27 @@ * an unsigned integer as the signed integer of the same width, bit for bit; * ``timestamp[ns]``, ``date64``, ``time32``, ``time64`` and ``duration`` as their - integer value (``int64``, or ``int32`` for ``time32``). + integer value (``int64``, or ``int32`` for ``time32``); +* ``float16`` as ``float32``, which holds every ``float16`` value exactly; +* a fixed-size list as a ``large_list`` of the same items (ITL-1275, ITL-1283); +* a fixed-size binary as ``large_binary``, and a list with non-null items as it is (its + item field's name is restored from the record; ITL-1334). + +What Delta cannot hold even so (``decimal256``, an interval) is refused before anything +is written: ``DeltaTableDatabase.require_storable`` asks the Delta writer's own +conversion about the column as it is written (``written_field``). A ``null``-typed value +is not recorded: it fits a column already stored with a type (the append check leaves it +out), and a column with no stored type yet is refused by ``add_records``. ``timestamp[s]``, ``timestamp[ms]`` and a zone other than UTC are left to Delta's own conversion, which is lossless. A read casts each recorded column back to its recorded -type (large-normalized). A column whose type has an extension (logical) type anywhere is -left as it is: its type is restored from its extension metadata. +type (large-normalized), at every depth, because the whole column type is recorded: a +fixed-size list is rebuilt from the list Delta gives back (a null row comes back with no +items, which a cast cannot fill), refusing a row of another length; a ``float16`` is +checked to hold exactly the ``float32`` value read; and a fixed-size binary to hold +values of its width. A column whose type has an +extension (logical) type anywhere is left as it is: its type is restored from its +extension metadata. A table written before this existed has no recorded type and reads back with Delta's types; such a database must be rebuilt. @@ -30,14 +49,16 @@ import base64 from collections.abc import Collection, Mapping -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: + import numpy as np import pyarrow as pa else: + np = LazyModule("numpy") pa = LazyModule("pyarrow") # Field metadata key holding a column's original Arrow type. @@ -62,10 +83,15 @@ def _stored_form(arrow_type: pa.DataType) -> pa.DataType: Returns: ``arrow_type`` with each unsigned integer replaced by the signed integer of - the same width and each ``timestamp[ns]``, ``date64``, ``time`` and - ``duration`` by its integer type; every other part unchanged. + the same width, each ``timestamp[ns]``, ``date64``, ``time`` and + ``duration`` by its integer type, each ``float16`` by ``float32`` and each + fixed-size list by a ``large_list`` of its items; every other part unchanged. """ t = pa.types + if t.is_float16(arrow_type): + return pa.float32() + if t.is_fixed_size_binary(arrow_type): + return pa.large_binary() if t.is_unsigned_integer(arrow_type): return {8: pa.int8(), 16: pa.int16(), 32: pa.int32(), 64: pa.int64()}[ arrow_type.bit_width @@ -81,7 +107,7 @@ def _stored_form(arrow_type: pa.DataType) -> pa.DataType: if t.is_list(arrow_type): return pa.list_(_stored_field(arrow_type.value_field)) if t.is_fixed_size_list(arrow_type): - return pa.list_(_stored_field(arrow_type.value_field), arrow_type.list_size) + return pa.large_list(_stored_field(arrow_type.value_field)) if t.is_struct(arrow_type): return pa.struct([_stored_field(f) for f in arrow_type]) if t.is_map(arrow_type): @@ -116,7 +142,8 @@ def _is_recorded(arrow_type: pa.DataType) -> bool: It does when it has, at any depth, a part Delta would not give back: an unsigned integer, a timestamp in another unit than microseconds or with a zone other than - UTC, or a ``date64``, ``time`` or ``duration``. + UTC, a ``date64``, ``time``, ``duration``, ``float16`` or fixed-size binary, + a fixed-size list, or a list whose items are non-null (Delta renames its item field). """ t = pa.types if ( @@ -124,6 +151,13 @@ def _is_recorded(arrow_type: pa.DataType) -> bool: or t.is_date64(arrow_type) or t.is_time(arrow_type) or t.is_duration(arrow_type) + or t.is_float16(arrow_type) + or t.is_fixed_size_binary(arrow_type) + or t.is_fixed_size_list(arrow_type) + ): + return True + if (t.is_list(arrow_type) or t.is_large_list(arrow_type)) and not ( + arrow_type.value_field.nullable ): return True if t.is_timestamp(arrow_type): @@ -174,19 +208,127 @@ def from_delta_layout(table: pa.Table) -> pa.Table: metadata = field.metadata or {} if ARROW_TYPE_KEY not in metadata: continue - original = arrow_utils.normalize_to_large_types( + # Any: pyarrow's stubs type ``chunked_array``'s ``type`` too narrowly. + original: Any = arrow_utils.normalize_to_large_types( _deserialize(metadata[ARROW_TYPE_KEY]) ) rest = {k: v for k, v in metadata.items() if k != ARROW_TYPE_KEY} + column = table.column(index) + try: + restored = pa.chunked_array( + [_restore(chunk, original) for chunk in column.chunks], type=original + ) + except ValueError as exc: + raise ValueError( + f"Column {field.name!r} cannot be read back as its recorded type " + f"{original}: {exc}" + ) from exc table = table.set_column( index, pa.field(field.name, original, field.nullable, rest or None), - # Values were written from this type, so the cast back is exact. - table.column(index).cast(original, safe=False), + restored, ) return table +def _needs_rebuild(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` has, at any depth, a part a cast cannot restore exactly + (a fixed-size list, which a null row breaks) or must check (a ``float16``).""" + t = pa.types + if t.is_fixed_size_list(arrow_type) or t.is_float16(arrow_type): + return True + return any( + _needs_rebuild(arrow_type.field(i).type) for i in range(arrow_type.num_fields) + ) + + +def _restore(array: Any, target: Any) -> Any: + """Return ``array``, as read from Delta, with the type ``target`` it was written as. + + Values were written from ``target``, so a cast restores them, except where + ``_needs_rebuild``: a fixed-size list is rebuilt from the list read, and a + ``float16`` is checked to hold exactly the value read. Containers holding one are + rebuilt around their restored children. + + Raises: + ValueError: A list row has another length than its fixed size, a value is not + a ``float16`` value, or a fixed-size binary has another width: the stored + rows are not what was written. + """ + if array.type == target: + return array + t = pa.types + if not _needs_rebuild(target): + # Values were written from this type, so the cast back is exact. + return array.cast(target, safe=False) + mask = array.is_null() if array.null_count else None + if t.is_float16(target): + restored = array.cast(target, safe=False) + if not _same_floats(restored.cast(array.type), array): + raise ValueError("a value is not a float16 value") + return restored + if t.is_fixed_size_list(target): + return _fixed_size_list(array, target) + if t.is_struct(target): + children = [ + _restore(array.field(i), target.field(i).type) + for i in range(target.num_fields) + ] + return pa.StructArray.from_arrays(children, fields=list(target), mask=mask) + if t.is_map(target): + return pa.MapArray.from_arrays( + array.offsets, + _restore(array.keys, target.key_type), + _restore(array.items, target.item_type), + type=cast(Any, target), # pyarrow's stubs type ``type`` too narrowly + mask=mask, + ) + if t.is_large_list(target) or t.is_list(target): + array_class = pa.LargeListArray if t.is_large_list(target) else pa.ListArray + return array_class.from_arrays( + array.offsets, + _restore(array.values, target.value_type), + type=target, + mask=mask, + ) + raise ValueError(f"no restore for {target}") # pragma: no cover # every kind above + + +def _same_floats(a: Any, b: Any) -> bool: + """Whether two float arrays hold the same values and nulls (NaN equal to NaN).""" + if a.null_count != b.null_count or not a.is_null().equals(b.is_null()): + return False + left = a.to_numpy(zero_copy_only=False) + right = b.to_numpy(zero_copy_only=False) + return bool(np.array_equal(left, right, equal_nan=True)) + + +def _fixed_size_list(array: Any, target: Any) -> Any: + """Rebuild a fixed-size list column from the list Delta gives back. + + A valid row holds its items; a null row may hold none (Delta writes no items for a + null list), so its slots are filled with nulls, which no reader sees. + + Raises: + ValueError: A valid row holds another number of items than the fixed size. + """ + size = target.list_size + rows = len(array) + offsets = array.offsets.to_numpy(zero_copy_only=False).astype(np.int64) + lengths = np.diff(offsets) + valid = ~array.is_null().to_numpy(zero_copy_only=False) + if np.any(lengths[valid] != size): + raise ValueError(f"a list row does not hold {size} items") + indices = np.repeat(offsets[:-1], size) + np.tile(np.arange(size), rows) + filled = np.repeat(valid | (lengths == size), size) + values = array.values.take(pa.array(indices, pa.int64(), mask=~filled)) + return pa.FixedSizeListArray.from_arrays( + _restore(values, target.value_type), + type=target, + mask=None if valid.all() else pa.array(~valid), + ) + + def recorded_type( metadata: "Mapping[bytes, bytes] | Mapping[str, str] | None", ) -> pa.DataType | None: @@ -234,3 +376,18 @@ def first_column_out_of_stored_range( except pa.ArrowInvalid: return name return None + + +def written_field(field: "pa.Field[Any]") -> "pa.Field[Any]": + """Return ``field`` as ``to_delta_layout`` writes it: in its stored form when its + type is recorded, otherwise unchanged (metadata aside). + + Args: + field: A column, as given to the database. + + Returns: + The field Delta is handed for it. + """ + if _has_extension_type(field.type) or not _is_recorded(field.type): + return field + return _stored_field(field) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 8399c3dd9..2e9dac5c3 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -22,12 +22,14 @@ OrcapodDatabaseReadError, TableListingNotSupportedError, TypeIdentityError, + UnstorableColumnError, ) from orcapod.databases.delta_arrow_types import ( first_column_out_of_stored_range, from_delta_layout, recorded_type, to_delta_layout, + written_field, ) from orcapod.databases.delta_statistics import statistics_configuration from orcapod.databases.storage_utils import ( @@ -260,6 +262,45 @@ def _as_delta_writer_stores(schema: pa.Schema) -> pa.Schema: ) +def _holds_null_type(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` is or nests a ``null`` type (Delta has none; ITL-1334).""" + if pa.types.is_null(arrow_type): + return True + return any( + _holds_null_type(arrow_type.field(i).type) for i in range(arrow_type.num_fields) + ) + + +def _delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: + """Say why Delta cannot hold a column, even through a recorded type, or ``None``. + + The column as it is written (``written_field``) goes through the Delta writer's + own conversion and type mapping (``_as_delta_writer_stores``), so the answer + follows the installed ``deltalake``: a timestamp in seconds is converted, a + ``decimal256`` or an interval is refused. + + A ``null``-typed part is left out, as the append check leaves it out: it fits a + column already stored with a type, and a column with no stored type yet is + refused by ``add_records``, which knows the stored table. + + Args: + field: A column, as given to the database. + + Returns: + Delta's reason (``Invalid data type for Delta Lake: Decimal256(40, 2)``), or + ``None`` when Delta holds the column. + """ + written = written_field(field) + reduced = _without_null_types(written.type) + if reduced is None: + return None + try: + _ = _as_delta_writer_stores(pa.schema([written.with_type(reduced)])) + except Exception as exc: # noqa: BLE001 # deltalake raises a bare Exception + return str(exc).removeprefix("Schema error: ") + return None + + def _merge_source_in_stored_layout( delta_table: deltalake.DeltaTable, batch: pa.Table ) -> pa.Table: @@ -1014,6 +1055,72 @@ def add_record( flush=flush, ) + def require_storable(self, schema: pa.Schema) -> None: + """Refuse a table schema with a column Delta cannot hold (ITL-1334). + + Most types Delta has no column type for are kept through a recorded type + (``delta_arrow_types``); the rest (``decimal256``, an interval) are refused, + as Delta's own schema conversion decides. Called by ``add_records`` before + anything of the table is buffered, and by a job node when the database is + attached to it (``contexts/stored.require_storable``), before anything runs. + + Args: + schema: The Arrow schema of a table this database is to hold. + + Raises: + UnstorableColumnError: For the first column Delta cannot hold, naming the + column, its Arrow type and Delta's reason. + """ + for field in schema: + reason = _delta_unstorable_reason(field) + if reason is not None: + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=field.name, + arrow_type=field.type, + reason=reason, + ) + + def _refuse_untyped_null_columns( + self, record_path: tuple[str, ...], schema: pa.Schema + ) -> None: + """Refuse a column with ``null``-typed parts that no stored column types (ITL-1334). + + Delta has no ``null`` type. A ``null``-typed value fits a column the stored + table (or a batch pending for it) already has with a type, and the append + check leaves it out; a column no stored or pending batch gives a type cannot be + written, so it is refused here, before anything is buffered, instead of failing + the flush without naming it. + + Args: + record_path: The table the rows are for. + schema: The schema of the rows about to be added. + + Raises: + UnstorableColumnError: For the first such column. + """ + untyped = [f for f in schema if _holds_null_type(f.type)] + if not untyped: + return + typed: set[str] = set() + delta_table = self._get_delta_table(record_path) + if delta_table is not None: + typed.update(_stored_arrow_schema(delta_table).names) + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + typed.update(f.name for f in pending.schema if not _holds_null_type(f.type)) + for field in untyped: + if field.name not in typed: + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=field.name, + arrow_type=field.type, + reason=( + "Delta has no null type, and no stored column gives this " + "all-null column a type" + ), + ) + def add_records( self, record_path: tuple[str, ...], @@ -1059,6 +1166,10 @@ def add_records( total_name_map = {k: rename_map.get(k, k) for k in records.column_names} records = records.rename_columns(total_name_map) + # A column Delta cannot hold is refused before anything is buffered (ITL-1334). + self.require_storable(records.schema) + self._refuse_untyped_null_columns(record_path, records.schema) + # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index cd59c4dc4..b41e1397e 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -260,9 +260,10 @@ def _coerce_pg_value(value: Any, arrow_type: "pa.DataType") -> Any: def _resolve_column_type_lookup( query: str, connector: "PostgreSQLConnector", -) -> dict[str, pa.DataType]: +) -> dict[str, ColumnInfo]: """Parse the FROM clause of query to find the source table, then return - a column-name → Arrow-type dict from get_column_info. + a column-name → column info (Arrow type and nullability) dict from + get_column_info. Returns an empty dict if no single unambiguous table can be identified, causing iter_batches to fall back to pa.large_string() for all columns. @@ -272,7 +273,7 @@ def _resolve_column_type_lookup( connector: The connector to call get_column_info on. Returns: - Dict mapping column name to Arrow DataType. + Dict mapping column name to its ``ColumnInfo``. """ # Be conservative: only resolve types when we can unambiguously identify # a single source table. For multi-table queries (JOINs, comma-separated @@ -310,7 +311,7 @@ def _resolve_column_type_lookup( if "," in from_tail: return {} - return {ci.name: ci.arrow_type for ci in connector.get_column_info(table_name)} + return {ci.name: ci for ci in connector.get_column_info(table_name)} def _field_has_metadata(field: pa.Field) -> bool: @@ -589,10 +590,17 @@ def iter_batches( if cur.description is None: return col_names = [d.name for d in cur.description] - type_lookup = _resolve_column_type_lookup(query, self) - arrow_types = [type_lookup.get(n, _pa.large_string()) for n in col_names] + infos = _resolve_column_type_lookup(query, self) + arrow_types = [ + infos[n].arrow_type if n in infos else _pa.large_string() + for n in col_names + ] + # A column created NOT NULL reads back non-null (ITL-1276). schema = _pa.schema( - [_pa.field(n, t) for n, t in zip(col_names, arrow_types)] + [ + _pa.field(n, t, infos[n].nullable if n in infos else True) + for n, t in zip(col_names, arrow_types) + ] ) rows = cur.fetchmany(batch_size) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index cd0679ef6..57a1a565f 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -28,6 +28,7 @@ from orcapod.databases.spiraldb_nullability import ( apply_nullability_record, + cast_changed_columns, check_no_nulls, enforce_nullability_record, read_nullability_record, @@ -396,6 +397,23 @@ def _holds_zone_aware_timestamp(arrow_type: pa.DataType) -> bool: ) +def _holds_extension_type(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` is or nests an extension (logical) type (ITL-1334). + + Args: + arrow_type: The column's Arrow type. + + Returns: + ``True`` for an extension type at any depth of lists, structs and maps. + """ + if isinstance(arrow_type, pa.ExtensionType): + return True + return any( + _holds_extension_type(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + class SpiralDBConnector: """DBConnectorProtocol implementation backed by SpiralDB (pyspiral). @@ -630,7 +648,7 @@ def prepare(batch: pa.RecordBatch) -> pa.RecordBatch: if needs_rebuild: target_schema = _pa.schema(new_fields, metadata=restored_schema_meta) - batch = batch.cast(target_schema) + batch = cast_changed_columns(batch, target_schema) if paths is not None: with _about_table(qualified): batch = enforce_nullability_record(batch, paths) @@ -1013,7 +1031,10 @@ def unstorable_column_reason( and the ``__`` prefix on value (column group) columns; a key column may start with ``__`` (``__record_id``). It drops a timestamp's time zone, so a time-zone-aware timestamp column (``timestamp[us, tz=UTC]``) would read - back as another type and is refused. + back as another type and is refused. It drops Arrow field metadata, so an + extension (logical) type at any depth (``File``, ``Path``, ``UUID``, a user + class, ``set[int]``, a NumPy array) would read back as its storage type and + is refused (ITL-1334; keeping it is a follow-up). Args: name: The column's name. @@ -1037,6 +1058,11 @@ def unstorable_column_reason( "SpiralDB drops the time zone of a timestamp nested in it, so it " "reads back as another type" ) + if _holds_extension_type(arrow_type): + return ( + "SpiralDB drops Arrow field metadata, so a logical (extension) type " + "reads back as its storage type" + ) return None def unstorable_table_name_reason(self, table_name: str) -> str | None: diff --git a/src/orcapod/databases/spiraldb_nullability.py b/src/orcapod/databases/spiraldb_nullability.py index 8f6b4592c..71792600d 100644 --- a/src/orcapod/databases/spiraldb_nullability.py +++ b/src/orcapod/databases/spiraldb_nullability.py @@ -392,6 +392,28 @@ def check_no_nulls( raise NullInNonNullableColumnError(render_path(path)) +def cast_changed_columns(batch: pa.RecordBatch, target: pa.Schema) -> pa.RecordBatch: + """Return ``batch`` under ``target``, casting only the columns whose type changes. + + A column whose type is already the target's keeps its array: pyarrow refuses to + cast (view) a fixed-size list with non-null items to its own type when a null row + hides null item slots (ITL-1334), and a field's nullability or metadata needs no + cast. + + Args: + batch: Rows as read. + target: The schema to give them, column for column. + + Returns: + The rows with ``target``'s schema. + """ + arrays = [ + column if column.type == field.type else column.cast(field.type) + for column, field in zip(batch.columns, target) + ] + return pa.RecordBatch.from_arrays(arrays, schema=target) + + def enforce_nullability_record( batch: pa.RecordBatch, paths: frozenset[ColumnPath] ) -> pa.RecordBatch: @@ -408,4 +430,4 @@ def enforce_nullability_record( check_no_nulls(batch, paths) if target.equals(batch.schema, check_metadata=True): return batch - return batch.cast(target) + return cast_changed_columns(batch, target) diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index d3d20d491..b462bb893 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -341,6 +341,9 @@ def iter_batches( # column-name collisions that would arise from scanning all tables. # Fallback to large_string() for computed/aliased/unknown columns. type_lookup: dict[str, _pa.DataType] = {} + # A column created NOT NULL reads back non-null (ITL-1276): the stored + # flag, not the type alone, makes the field. + nullable_lookup: dict[str, bool] = {} table_match = _re.search(r'FROM\s+"([^"]+)"', query, _re.IGNORECASE) if not table_match: table_match = _re.search(r"FROM\s+(\w+)", query, _re.IGNORECASE) @@ -348,6 +351,7 @@ def iter_batches( queried_table = table_match.group(1) for ci in self.get_column_info(queried_table): type_lookup[ci.name] = ci.arrow_type + nullable_lookup[ci.name] = ci.nullable # rowid is an implicit SQLite integer column; it does not appear in # PRAGMA table_info, so it would otherwise fall back to large_string. @@ -358,7 +362,10 @@ def iter_batches( type_lookup.get(name, _pa.large_string()) for name in col_names ] schema = _pa.schema( - [_pa.field(name, atype) for name, atype in zip(col_names, arrow_types)] + [ + _pa.field(name, atype, nullable_lookup.get(name, True)) + for name, atype in zip(col_names, arrow_types) + ] ) chunk = cursor.fetchmany(batch_size) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 5ae3a904b..f7e858160 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -277,10 +277,16 @@ def add_context(self, node_label: str | None = None) -> None: def __str__(self) -> str: node = f"node {self.node_label!r}: " if self.node_label is not None else "" + # Delta refuses only what no database but the in-memory one keeps (ITL-1334). + instead = ( + "an InMemoryArrowDatabase" + if self.database_kind == "DeltaTableDatabase" + else "an InMemoryArrowDatabase or a DeltaTableDatabase" + ) return ( f"{node}a {self.database_kind} database cannot store column " f"{self.column!r} of Arrow type {self.arrow_type}: {self.reason}. " - "Use an InMemoryArrowDatabase or a DeltaTableDatabase instead." + f"Use {instead} instead." ) diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index 88dd25328..d34caab80 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -653,9 +653,31 @@ def _cast_storage( if pa.types.is_timestamp(col.type) and pa.types.is_timestamp(target): # dropping the tz keeps the UTC instant (what SpiralDB was seen to do) return pc.cast(col, pa.timestamp(col.type.unit, tz="UTC")).cast(target) + if pa.types.is_map(col.type) and pa.types.is_map(target): + # pyarrow 23 aborts the process (not an exception) casting some map arrays + # ("Map array keys array should have no nulls"), so a map is rebuilt from its + # parts: offsets, keys and items cast on their own, validity kept (ITL-1334). + # (cast: pyarrow's stubs type ``chunked_array``'s ``type`` too narrowly.) + return pa.chunked_array( + [_cast_map_chunk(chunk, target) for chunk in col.chunks], + type=cast(Any, target), + ) return col.cast(target) +def _cast_map_chunk(chunk: Any, target: Any) -> Any: + """Return the map array ``chunk`` with its keys and items cast to ``target``'s.""" + keys = _cast_storage(pa.chunked_array([chunk.keys]), target.key_type) + items = _cast_storage(pa.chunked_array([chunk.items]), target.item_type) + return pa.MapArray.from_arrays( + chunk.offsets, + keys.combine_chunks(), + items.combine_chunks(), + type=target, + mask=chunk.is_null() if chunk.null_count else None, + ) + + class FakeProject: """What ``Spiral.project(id)`` returns: list, open, create and drop tables.""" diff --git a/tests/test_databases/test_delta_append_types.py b/tests/test_databases/test_delta_append_types.py index 20553096f..7442a2450 100644 --- a/tests/test_databases/test_delta_append_types.py +++ b/tests/test_databases/test_delta_append_types.py @@ -28,7 +28,7 @@ from orcapod.contexts import get_default_context from orcapod.databases import DeltaTableDatabase -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, UnstorableColumnError from orcapod.logical_types.directory_type import Directory from orcapod.logical_types.file_type import File @@ -172,20 +172,17 @@ def column(arrow_type: pa.DataType) -> pa.Array[Any]: "logical list[Path]": list[pathlib.Path], } -# Types the Delta writer cannot store at all (deltalake 1.0.2): the first write -# fails, before the append check is ever reached, on main as on this branch. Kept +# Types the Delta writer cannot store at all (deltalake 1.0.2): the first write is +# refused (``DeltaTableDatabase.require_storable``, ITL-1334). Kept # explicit so a deltalake upgrade that starts storing one of them makes the test # fail and the type join the guarded list. NOT_STORABLE: set[str] = { - "float16", "decimal256(40, 2)", } # ``date64``, ``time`` and ``duration`` are stored as their integer value with the -# Arrow type recorded since ITL-928 (``orcapod.databases.delta_arrow_types``). - -# Types Delta stores but whose append Delta's own merge rejects, on main as on -# this branch (not the append check): tracked in ITL-916. -MERGE_REJECTS: set[str] = {"fixed_size_list"} +# Arrow type recorded since ITL-928, and ``float16`` (as ``float32``) and a fixed-size +# list (as a ``large_list``, which also appends) since ITL-1334 +# (``orcapod.databases.delta_arrow_types``). def table(arrow_type: pa.DataType, rid: bytes, *, nullable: bool) -> pa.Table: @@ -205,18 +202,12 @@ def all_types() -> list[Any]: """Every (id, Arrow type) pair, nullable and non-nullable.""" types = dict(PLAIN_TYPES) types.update({name: _logical(t) for name, t in LOGICAL_TYPES.items()}) - merge_rejects = pytest.mark.xfail( - raises=RuntimeError, - strict=True, - reason="deltalake rejects this type on append: its list item field is named 'element', not 'item' (ITL-1076)", - ) return [ pytest.param( name, arrow_type, nullable, id=f"{name}-{'nullable' if nullable else 'non-null'}", - marks=[merge_rejects] if name in MERGE_REJECTS else [], ) for name, arrow_type in types.items() for nullable in (True, False) @@ -236,8 +227,9 @@ def test_identical_schema_appends( """A second batch with the stored batch's exact schema appends and reads back.""" db = DeltaTableDatabase(base_path=tmp_path) if name in NOT_STORABLE: - # Delta cannot store the type: the first write already fails. - with pytest.raises(RuntimeError): + # Delta cannot store the type: the first write is refused, naming the column, + # before anything is buffered (ITL-1334). + with pytest.raises(UnstorableColumnError, match="'x'"): write(db, table(arrow_type, b"a", nullable=nullable)) return write(db, table(arrow_type, b"a", nullable=nullable)) diff --git a/tests/test_databases/test_delta_arrow_type_roundtrip.py b/tests/test_databases/test_delta_arrow_type_roundtrip.py index 0b9c54c9f..81b4f9bf9 100644 --- a/tests/test_databases/test_delta_arrow_type_roundtrip.py +++ b/tests/test_databases/test_delta_arrow_type_roundtrip.py @@ -63,6 +63,30 @@ [{"u": i, "t": _T[i].replace(microsecond=0)} for i in range(3)], pa.struct([("u", pa.uint16()), ("t", pa.timestamp("ms"))]), ), + # ITL-1283, ITL-1275, ITL-1334: kept through a recorded type, null rows included. + "float16": pa.array([0.5, None, 65504.0], pa.float16()), + "fixed_size_list[2]": pa.array( + [[1, 2], None, [3, None]], pa.list_(pa.int64(), 2) + ), + "fixed_size_list[2]": pa.array( + [[1, 2], None, [3, 4]], pa.list_(pa.field("item", pa.int64(), False), 2) + ), + "struct[2]>": pa.array( + [{"f": [0.5, 1.5]}, {"f": None}, None], + pa.struct([("f", pa.list_(pa.float16(), 2))]), + ), + "map[2]>": pa.array( + [[("a", [1, 2])], None, [("b", None), ("c", [3, 4])]], + pa.map_(pa.string(), pa.list_(pa.int8(), 2)), + ), + "large_list[3]>": pa.array( + [[[1, 2, 3]], [], [None, [4, 5, 6]]], + pa.large_list(pa.list_(pa.uint8(), 3)), + ), + "fixed_size_binary[3]": pa.array([b"abc", None, b"\x00\x01\x02"], pa.binary(3)), + "large_list": pa.array( + [[1], [], [2, 3]], pa.large_list(pa.field("item", pa.int64(), False)) + ), } @@ -500,3 +524,131 @@ def test_an_unsigned_value_beyond_an_unrecorded_signed_column_is_refused( read = DeltaTableDatabase(tmp_path).get_all_records(("t",)) assert read is not None assert read.column("c").to_pylist() == [1] + + +# --------------------------------------------------------------------------- +# ITL-1334: float16 values bit for bit, refused restores, refused types +# --------------------------------------------------------------------------- + + +def test_float16_special_values_round_trip_bit_for_bit(tmp_path: pathlib.Path) -> None: + """``float32`` holds every ``float16`` exactly: NaN, both infinities, both zeros, + the smallest subnormal and the largest value come back with their bits.""" + import numpy as np + + values = np.array( + [np.nan, np.inf, -np.inf, 0.0, -0.0, 2.0**-24, 65504.0, -65504.0], + dtype=np.float16, + ) + # Three rows per write (the helper's ids): three writes cover the eight values. + for start in (0, 3, 5): + chunk = values[start : start + 3] + read = _written_and_read(tmp_path / f"w{start}", pa.array(chunk, pa.float16())) + assert read.schema.field("c").type == pa.float16() + back = read.column("c").to_numpy() + assert back.view(np.uint16).tolist() == chunk.view(np.uint16).tolist() + + +def _recorded(stored: pa.Array[Any], original: pa.DataType) -> pa.Table: + """A table as read from Delta: ``stored`` under a field recording ``original``.""" + from orcapod.databases.delta_arrow_types import ARROW_TYPE_KEY, _serialize # pyright: ignore[reportPrivateUsage] + + field = pa.field("c", stored.type, metadata={ARROW_TYPE_KEY: _serialize(original)}) + return pa.Table.from_arrays([stored], schema=pa.schema([field])) + + +@pytest.mark.parametrize( + ("stored", "original", "problem"), + [ + ( + pa.array([[1, 2], [3]], pa.large_list(pa.int64())), + pa.list_(pa.int64(), 2), + "does not hold 2 items", + ), + ( + pa.array([{"f": [1, 2, 3]}], pa.struct([("f", pa.large_list(pa.int64()))])), + pa.struct([("f", pa.list_(pa.int64(), 2))]), + "does not hold 2 items", + ), + (pa.array([0.1], pa.float32()), pa.float16(), "not a float16 value"), + (pa.array([b"abcd"], pa.large_binary()), pa.binary(3), "widths must match"), + ], + ids=["fixed_size_list", "nested fixed_size_list", "float16", "fixed_size_binary"], +) +def test_stored_rows_that_are_not_the_recorded_type_are_refused_naming_the_column( + stored: pa.Array[Any], original: pa.DataType, problem: str +) -> None: + """A restore never makes up a value: rows that cannot be what was written raise.""" + from orcapod.databases.delta_arrow_types import from_delta_layout + + with pytest.raises(ValueError, match=f"Column 'c'.*{problem}"): + from_delta_layout(_recorded(stored, original)) + + +@pytest.mark.parametrize( + "arrow_type", + [ + pa.decimal256(40, 2), + pa.month_day_nano_interval(), + pa.struct([("d", pa.decimal256(76, 10))]), + pa.large_list(pa.decimal256(40, 2)), + ], + ids=["decimal256", "interval", "struct", "large_list"], +) +def test_a_type_delta_cannot_hold_is_refused_before_anything_is_written( + arrow_type: Any, tmp_path: pathlib.Path +) -> None: + from orcapod.errors import UnstorableColumnError + + db = DeltaTableDatabase(tmp_path) + table = pa.table( + { + "id": pa.array([b"a"], pa.large_binary()), + "ok": pa.array([1], pa.int64()), + "bad": pa.nulls(1, arrow_type), + } + ) + with pytest.raises(UnstorableColumnError, match="'bad'") as caught: + db.add_records(("t",), table, record_id_column="id", flush=True) + assert caught.value.database_kind == "DeltaTableDatabase" + assert "Use an InMemoryArrowDatabase instead" in str(caught.value) + db.flush() + assert db.get_all_records(("t",), record_id_column="id") is None + + +def test_a_job_refuses_a_column_delta_cannot_hold_before_it_runs( + tmp_path: pathlib.Path, +) -> None: + """``require_storable`` is the job's up-front check too (ITL-1162 hook).""" + from orcapod.contexts.stored import require_storable + from orcapod.errors import UnstorableColumnError + + with pytest.raises(UnstorableColumnError, match="'d'"): + require_storable( + DeltaTableDatabase(tmp_path), + pa.schema([("k", pa.int64()), ("d", pa.decimal256(40, 2))]), + ) + require_storable( + DeltaTableDatabase(tmp_path), + pa.schema([("k", pa.uint64()), ("h", pa.float16()), ("n", pa.null())]), + ) + + +@pytest.mark.parametrize( + "arrow_type", + [pa.null(), pa.struct([("a", pa.null())]), pa.large_list(pa.null())], + ids=["null", "struct", "large_list"], +) +def test_a_new_all_null_column_is_refused_naming_it( + arrow_type: Any, tmp_path: pathlib.Path +) -> None: + """Delta has no null type: a column no stored column types is refused when added, + instead of failing the flush without naming it (ITL-1334).""" + from orcapod.errors import UnstorableColumnError + + db = DeltaTableDatabase(tmp_path) + table = pa.table( + {"id": pa.array([b"a"], pa.large_binary()), "n": pa.nulls(1, arrow_type)} + ) + with pytest.raises(UnstorableColumnError, match="'n'"): + db.add_records(("t",), table, record_id_column="id") diff --git a/tests/test_databases/test_delta_read_your_writes.py b/tests/test_databases/test_delta_read_your_writes.py index cd0156f3a..fd0ee7e12 100644 --- a/tests/test_databases/test_delta_read_your_writes.py +++ b/tests/test_databases/test_delta_read_your_writes.py @@ -17,7 +17,7 @@ import pytest from orcapod.databases import DeltaTableDatabase -from orcapod.errors import OrcapodDatabaseReadError +from orcapod.errors import OrcapodDatabaseReadError, UnstorableColumnError PATH = ("table",) SCOPE = "scope" @@ -429,24 +429,21 @@ def test_read_of_stored_and_pending_rows_with_different_types_raises( _ = READS_AC[method](db) -def test_pending_null_typed_column_reads_back_but_does_not_flush( +def test_a_new_null_typed_column_is_refused_before_it_is_pending( tmp_path: Path, ) -> None: - """A new all-null ``null``-typed column reads back as ``null``; Delta cannot store it. - - The flush fails and the batch stays pending, so the read is unchanged after it. - """ + """A new all-null ``null``-typed column has no type Delta can store: it is refused + naming the column, before anything is pending (it used to stay pending and fail the + flush without naming it; ITL-1334).""" db = DeltaTableDatabase(tmp_path) db.add_records(PATH, _without_x(_table("a", pa.array([1]))), flush=True) - db.add_records(PATH, _table("c", pa.nulls(1))) - - before = _read_sorted(db, "get_all_records") - assert before.schema.field("x").type == pa.null() - assert before.column("x").to_pylist() == [None, None] - - with pytest.raises(RuntimeError, match="Failed to flush"): - db.flush() - assert _read_sorted(db, "get_all_records").equals(before) + with pytest.raises(UnstorableColumnError, match="'x'"): + db.add_records(PATH, _table("c", pa.nulls(1))) + db.flush() + stored = db.get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert stored.column_names == ["rid", "v"] + assert stored.column("rid").to_pylist() == [b"a"] @pytest.mark.parametrize( diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index b73c7fcc2..ef0bc896b 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -772,3 +772,32 @@ def test_an_address_is_passed_as_given(self, dsn: str, hostaddr: str) -> None: def test_a_socket_directory_is_not_resolved(self) -> None: attempts = self._passed_to_libpq("host=/var/run/postgresql dbname=x") assert [attempt.get("hostaddr") for attempt in attempts] == [None] + + +def test_iter_batches_reads_a_not_null_column_back_non_null() -> None: + """The batch schema takes each column's nullability from ``get_column_info`` + (``is_nullable``), as its type, so a column created NOT NULL reads back non-null + (ITL-1276); a nullable one stays nullable. Unit level: no server.""" + from orcapod.types import ColumnInfo + + with patch("psycopg.connect") as mock_connect: + mock_connect.return_value = MagicMock() + connector = PostgreSQLConnector("postgresql://localhost/test") + cursor = MagicMock() + cursor.description = [MagicMock(), MagicMock()] + cursor.description[0].name = "required" + cursor.description[1].name = "optional" + cursor.fetchmany.side_effect = [[(1, None), (2, 5)], []] + mock_connect.return_value.cursor.return_value = cursor + infos = [ + ColumnInfo(name="required", arrow_type=pa.int64(), nullable=False), + ColumnInfo(name="optional", arrow_type=pa.int64(), nullable=True), + ] + with patch.object(PostgreSQLConnector, "get_column_info", return_value=infos): + batches = list(connector.iter_batches('SELECT * FROM "t"')) + connector._conn = None # skip actual close + assert len(batches) == 1 + schema = batches[0].schema + assert schema.field("required").nullable is False + assert schema.field("optional").nullable is True + assert batches[0].column("required").to_pylist() == [1, 2] diff --git a/tests/test_databases/test_spiraldb_connector_fake.py b/tests/test_databases/test_spiraldb_connector_fake.py index 9b0362b4e..fb8475594 100644 --- a/tests/test_databases/test_spiraldb_connector_fake.py +++ b/tests/test_databases/test_spiraldb_connector_fake.py @@ -8,6 +8,7 @@ import json from pathlib import Path +from typing import Any import pyarrow as pa import pytest @@ -591,3 +592,50 @@ def test_result_store_refuses_a_null_struct(self, tmp_path: Path): ) with pytest.raises(UnsupportedValueError, match="'g'"): db.flush() + + +class TestKeptOrRefused: + """ITL-1334: SpiralDB keeps a column exactly or refuses it, naming it.""" + + @pytest.fixture() + def database(self, tmp_path: Path): + """A connector database over the fake project ``p``.""" + with fake_pyspiral.install(tmp_path / "spiral"): + fake_pyspiral.FakeSpiral().project("p") + yield ConnectorArrowDatabase(SpiralDBConnector("p")) + + @pytest.mark.parametrize("python_type", [Path, set[int]], ids=["Path", "set[int]"]) + def test_a_logical_type_is_refused_naming_the_column(self, database, python_type): + """SpiralDB drops field metadata, so the type would read back as its storage.""" + from orcapod.contexts import get_default_context + from orcapod.errors import UnstorableColumnError + + value = Path("/a") if python_type is Path else {1, 2} + table = get_default_context().type_converter.python_dicts_to_arrow_table( + [{"id": b"r1", "v": value}], + python_schema={"id": bytes, "v": python_type}, + ) + with pytest.raises(UnstorableColumnError, match="'v'.*storage type"): + database.add_records(("t",), table, record_id_column="id", flush=True) + + def test_a_fixed_size_list_with_non_null_items_and_a_null_row_reads_back( + self, database + ): + """A null row's hidden item slots are null; the read keeps the column as is + (pyarrow refuses to cast it to its own type, so only changed columns are cast).""" + item = pa.field("item", pa.int64(), nullable=False) + fsl_type: Any = pa.list_(item, 2) # pyarrow's stubs type ``type`` narrowly + column = pa.FixedSizeListArray.from_arrays( + pa.array([1, 2, None, None, 5, 6]), + type=fsl_type, + mask=pa.array([False, True, False]), + ) + table = pa.Table.from_arrays( + [pa.array([b"a", b"b", b"c"], pa.large_binary()), column], + names=["id", "f"], + ) + database.add_records(("t",), table, record_id_column="id", flush=True) + back = database.get_all_records(("t",), record_id_column="id") + assert back is not None + assert back.schema.field("f").type == pa.list_(item, 2) + assert back.sort_by("id").column("f").to_pylist() == [[1, 2], None, [5, 6]] diff --git a/tests/test_databases/test_sqlite_connector.py b/tests/test_databases/test_sqlite_connector.py index b3fc9c908..1ce6ba693 100644 --- a/tests/test_databases/test_sqlite_connector.py +++ b/tests/test_databases/test_sqlite_connector.py @@ -556,3 +556,35 @@ def test_rejects_nested_list_value_field_metadata(self, c): ) with pytest.raises(ValueError, match="metadata"): c.validate_records(table) + + +@pytest.mark.parametrize("arrow_type", [pa.int64(), pa.large_string()]) +def test_a_non_null_column_reads_back_non_null( + tmp_path: Path, arrow_type: pa.DataType +) -> None: + """The connector creates a non-null column NOT NULL and reads the flag back with the + rows (ITL-1276); a nullable column stays nullable.""" + from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector + + db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "s.db"))) + values = [1, 2] if arrow_type == pa.int64() else ["a", "b"] + table = pa.Table.from_arrays( + [ + pa.array([b"r1", b"r2"], pa.large_binary()), + pa.array(values, arrow_type), + pa.array([values[0], None], arrow_type), + ], + schema=pa.schema( + [ + pa.field("id", pa.large_binary(), nullable=False), + pa.field("required", arrow_type, nullable=False), + pa.field("optional", arrow_type), + ] + ), + ) + db.add_records(("t",), table, record_id_column="id", flush=True) + back = db.get_all_records(("t",), record_id_column="id") + assert back is not None + assert back.schema.field("required").nullable is False + assert back.schema.field("optional").nullable is True + assert back.sort_by("id").column("required").to_pylist() == values diff --git a/tests/test_databases/test_type_matrix.py b/tests/test_databases/test_type_matrix.py new file mode 100644 index 000000000..d922e22e0 --- /dev/null +++ b/tests/test_databases/test_type_matrix.py @@ -0,0 +1,78 @@ +"""The supported-data-types matrix: every type kept or refused by every database (ITL-1334). + +``type_matrix.measure_all`` writes and reads every type of the matrix through every +database. No cell may be silent (another type, other values, an error that does not name +the column), and the committed page ``docs/reference/database-types.md`` must equal the +page rendered from the measurements (``scripts/database_type_matrix.py`` writes it). +""" + +from __future__ import annotations + +import logging +import warnings +from pathlib import Path + +import pytest + +from tests.test_databases.type_matrix import ( + DATABASES, + KEPT, + KEPT_BY_RULE, + PAGE, + REFUSED, + ROWS, + SILENT, + Cell, + measure_all, + render, +) + + +@pytest.fixture(scope="module") +def cells(tmp_path_factory: pytest.TempPathFactory) -> dict[tuple[str, str], Cell]: + """Every cell, measured once for the module (its warnings and logs silenced).""" + previous = logging.root.manager.disable + logging.disable(logging.WARNING) + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return measure_all(tmp_path_factory.mktemp("matrix")) + finally: + logging.disable(previous) + + +def test_no_database_changes_a_type_silently( + cells: dict[tuple[str, str], Cell], +) -> None: + silent = {key: cell.detail for key, cell in cells.items() if cell.kind == SILENT} + assert not silent, "\n".join( + f"{row} / {db}: {d}" for (row, db), d in silent.items() + ) + + +def test_every_row_has_every_database(cells: dict[tuple[str, str], Cell]) -> None: + assert set(cells) == {(row.label, db) for row in ROWS for db in DATABASES} + assert len({row.label for row in ROWS}) == len(ROWS) + + +def test_the_in_memory_database_keeps_every_type( + cells: dict[tuple[str, str], Cell], +) -> None: + assert {cells[(row.label, "in-memory")].kind for row in ROWS} == {KEPT} + + +def test_the_postgresql_column_is_the_connectors_rule( + cells: dict[tuple[str, str], Cell], +) -> None: + """No server is used: a PostgreSQL cell is the rule's verdict, never a read.""" + assert {cells[(row.label, "PostgreSQL")].kind for row in ROWS} <= { + KEPT_BY_RULE, + REFUSED, + } + + +def test_the_committed_page_matches_the_measurements( + cells: dict[tuple[str, str], Cell], +) -> None: + """``uv run python scripts/database_type_matrix.py`` rewrites the page.""" + assert Path(PAGE).read_text(encoding="utf-8") == render(cells) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py new file mode 100644 index 000000000..e01aeb57e --- /dev/null +++ b/tests/test_databases/type_matrix.py @@ -0,0 +1,727 @@ +"""The supported-data-types matrix: what each database keeps of each Arrow type (ITL-1334). + +Every row is a column type, every column a database. A cell is measured, never declared: +a table holding two columns of the type (the second with a null when the type is +nullable) is written with ``add_records``, flushed and read back with +``get_all_records``, then compared with what was written, up to the large variants every +Orcapod table uses (``arrow_utils.normalize_to_large_types``). The outcome is one of: + +- ``KEPT``: read back equal, type (with nested nullability) and values. +- ``KEPT VIA RECORDED TYPE``: read back equal through Delta's recorded-type mechanism + (``databases/delta_arrow_types.py``: the type is recorded in the field metadata, the + values written in a form Delta keeps, the type restored on read). +- ``REFUSED``: the write raised an error naming the column, before anything was stored. +- ``SILENT``: anything else (another type, other values, an error that does not name the + column, a failed read). The test fails on any silent cell. + +The databases: in-memory, Delta Lake (local directory), the connector database over +SQLite, over PostgreSQL and over SpiralDB. No PostgreSQL server and no SpiralDB is used: +the PostgreSQL cell comes from the connector's own storability rule +(``unstorable_column_reason`` and ``validate_records``, over a mocked connection), so it +is ``KEPT BY RULE`` or ``REFUSED``, never a measured read; the SpiralDB cell is measured +through the disk fake (``tests/test_databases/fake_pyspiral.py``). No database tells tag +columns from data columns: the connector databases tell only the record-id key, which +Orcapod always writes as ``large_binary``. +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import datetime as dt +import decimal +import uuid +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import pyarrow as pa + +import orcapod +from orcapod.contexts import get_default_context +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + PostgreSQLConnector, + SQLiteConnector, + SpiralDBConnector, +) +from orcapod.databases.delta_arrow_types import _is_recorded # pyright: ignore[reportPrivateUsage] +from orcapod.utils.arrow_utils import normalize_to_large_types + +KEPT = "KEPT" +RECORDED = "KEPT VIA RECORDED TYPE" +KEPT_BY_RULE = "KEPT BY RULE" +REFUSED = "REFUSED" +SILENT = "SILENT" + +DATABASES = ("in-memory", "Delta", "SQLite", "PostgreSQL", "SpiralDB") + + +@dataclasses.dataclass(frozen=True) +class Cell: + """One measured outcome: its kind and what was seen.""" + + kind: str + detail: str = "" + + +# --------------------------------------------------------------------------- +# The rows +# --------------------------------------------------------------------------- + + +@dataclasses.dataclass +class MatrixExact: + """An exact user class (an ordinary dataclass) with two fields.""" + + n: int + s: str + + +@orcapod.dataclass +class MatrixStructural: + """A structural user class with two fields.""" + + n: int + s: str + + +@dataclasses.dataclass(frozen=True) +class Row: + """One row of the matrix: a label, a group, and how to build its two columns.""" + + label: str + group: str + build: Callable[ + [Path], tuple["pa.Field[Any]", "pa.Field[Any]", list[Any], list[Any]] + ] + provisional: bool = False + + +def _plain( + arrow_type: pa.DataType, values: list[Any], nullable: bool = True +) -> Callable[[Path], tuple[Any, Any, list[Any], list[Any]]]: + """Two columns of ``arrow_type``; the second has a null in the middle if nullable.""" + + def build(_root: Path) -> tuple[Any, Any, list[Any], list[Any]]: + second = [values[0], None, values[2]] if nullable else list(reversed(values)) + return ( + pa.field("x", arrow_type, nullable=nullable), + pa.field("y", arrow_type, nullable=nullable), + values, + second, + ) + + return build + + +def _logical( + python_type: Any, make: Callable[[Path], list[Any]] +) -> Callable[[Path], tuple[Any, Any, list[Any], list[Any]]]: + """Two columns of a logical (or library) type, typed by the data context's converter: + ``x`` of ``T`` and ``y`` of ``T | None`` with a null.""" + + def build(root: Path) -> tuple[Any, Any, list[Any], list[Any]]: + values = make(root) + return ("logical", python_type, values, [values[0], None, values[2]]) # pyright: ignore[reportReturnType] + + return build + + +D = decimal.Decimal +_TS = [ + dt.datetime(2026, 1, 1, 0, 0, 1), + dt.datetime(2026, 1, 2), + dt.datetime(2026, 3, 4), +] +_TSZ = [t.replace(tzinfo=dt.timezone.utc) for t in _TS] +_DATES = [dt.date(2026, 1, 1), dt.date(2026, 1, 2), dt.date(1999, 12, 31)] +_TIMES = [dt.time(1, 2, 3), dt.time(4, 5, 6), dt.time(23, 59, 59)] +_DURATIONS = [dt.timedelta(seconds=1), dt.timedelta(seconds=2), dt.timedelta(days=1)] + + +def _files(root: Path) -> list[Any]: + out = [] + for i in range(3): + path = root / f"f{i}.txt" + path.write_text(f"file {i}") + out.append(orcapod.File(path)) + return out + + +def _directories(root: Path) -> list[Any]: + out = [] + for i in range(3): + path = root / f"d{i}" + path.mkdir(exist_ok=True) + (path / "a.txt").write_text(f"dir {i}") + out.append(orcapod.Directory(path)) + return out + + +def _arrays(_root: Path) -> list[Any]: + import numpy as np + + return [np.arange(3), np.arange(4.0), np.zeros((2, 2), dtype=np.int8)] + + +def _pandas_frames(_root: Path) -> list[Any]: + import pandas as pd + + return [pd.DataFrame({"a": [1, 2]}), pd.DataFrame({"b": ["x"]}), pd.DataFrame()] + + +def _pandas_series(_root: Path) -> list[Any]: + import pandas as pd + + return [pd.Series([1, 2]), pd.Series(["x"]), pd.Series([1.5])] + + +def _polars_frames(_root: Path) -> list[Any]: + import polars as pl + + return [pl.DataFrame({"a": [1, 2]}), pl.DataFrame({"b": ["x"]}), pl.DataFrame()] + + +def _polars_series(_root: Path) -> list[Any]: + import polars as pl + + return [pl.Series("a", [1, 2]), pl.Series("b", ["x"]), pl.Series("c", [1.5])] + + +def _tensors(_root: Path) -> list[Any]: + import torch + + return [torch.arange(3), torch.zeros(2, 2), torch.ones(1, dtype=torch.float16)] + + +def _upaths(root: Path) -> list[Any]: + from upath import UPath + + return [UPath(f"memory://matrix/{i}") for i in range(3)] + + +ROWS: tuple[Row, ...] = ( + *( + Row(str(t), "integer", _plain(t, [1, 2, 100])) + for t in (pa.int8(), pa.int16(), pa.int32(), pa.int64()) + ), + *( + Row(str(t), "integer", _plain(t, [1, 2, 200])) + for t in (pa.uint8(), pa.uint16(), pa.uint32(), pa.uint64()) + ), + Row("halffloat (float16)", "float", _plain(pa.float16(), [1.5, 2.0, 0.25])), + Row("float (float32)", "float", _plain(pa.float32(), [1.5, 2.0, 0.25])), + Row("double (float64)", "float", _plain(pa.float64(), [1.5, 2.0, 0.1])), + Row( + "decimal128(10, 2)", + "decimal", + _plain(pa.decimal128(10, 2), [D("1.25"), D("-2.50"), D("0.01")]), + ), + Row( + "decimal128(38, 4)", + "decimal", + _plain( + pa.decimal128(38, 4), + [D("1.2500"), D("-2.5000"), D("12345678901234567890.1234")], + ), + ), + Row( + "decimal256(40, 2)", + "decimal", + _plain( + pa.decimal256(40, 2), + [D("1.25"), D("-2.50"), D("12345678901234567890123456789012345678.01")], + ), + ), + Row( + "decimal256(76, 10)", + "decimal", + _plain(pa.decimal256(76, 10), [D("1.25"), D("-2.5"), D("0.0000000001")]), + ), + Row("bool", "boolean", _plain(pa.bool_(), [True, False, True])), + Row("null", "null", _plain(pa.null(), [None, None, None])), + Row("date32", "temporal", _plain(pa.date32(), _DATES)), + Row("date64", "temporal", _plain(pa.date64(), _DATES)), + Row("time32[s]", "temporal", _plain(pa.time32("s"), _TIMES)), + Row("time32[ms]", "temporal", _plain(pa.time32("ms"), _TIMES)), + Row("time64[us]", "temporal", _plain(pa.time64("us"), _TIMES)), + Row("time64[ns]", "temporal", _plain(pa.time64("ns"), _TIMES)), + *( + Row(f"timestamp[{u}]", "temporal", _plain(pa.timestamp(u), _TS)) + for u in ("s", "ms", "us", "ns") + ), + *( + Row( + f"timestamp[{u}, tz=UTC]", + "temporal", + _plain(pa.timestamp(u, tz="UTC"), _TSZ), + ) + for u in ("s", "ms", "us", "ns") + ), + *( + Row( + f"timestamp[{u}, tz=Europe/Berlin]", + "temporal", + _plain(pa.timestamp(u, tz="Europe/Berlin"), _TSZ), + ) + for u in ("s", "ms", "us", "ns") + ), + *( + Row(f"duration[{u}]", "temporal", _plain(pa.duration(u), _DURATIONS)) + for u in ("s", "ms", "us", "ns") + ), + Row("string", "string and binary", _plain(pa.string(), ["a", "bc", ""])), + Row( + "large_string", "string and binary", _plain(pa.large_string(), ["a", "bc", ""]) + ), + Row("binary", "string and binary", _plain(pa.binary(), [b"a", b"bc", b""])), + Row( + "large_binary", + "string and binary", + _plain(pa.large_binary(), [b"a", b"bc", b""]), + ), + Row( + "fixed_size_binary[4]", + "string and binary", + _plain(pa.binary(4), [b"abcd", b"efgh", b"\x00\x01\x02\x03"]), + ), + Row("list", "list", _plain(pa.list_(pa.int64()), [[1, 2], [], [3, None]])), + Row( + "list", + "list", + _plain( + pa.list_(pa.field("item", pa.int64(), nullable=False)), [[1, 2], [], [3]] + ), + ), + Row( + "large_list", + "list", + _plain(pa.large_list(pa.int64()), [[1, 2], [], [3, None]]), + ), + Row( + "large_list", + "list", + _plain( + pa.large_list(pa.field("item", pa.int64(), nullable=False)), + [[1, 2], [], [3]], + ), + ), + Row( + "fixed_size_list[2]", + "list", + _plain(pa.list_(pa.int64(), 2), [[1, 2], [3, None], [5, 6]]), + ), + Row( + "fixed_size_list[2]", + "list", + _plain( + pa.list_(pa.field("item", pa.int64(), nullable=False), 2), + [[1, 2], [3, 4], [5, 6]], + ), + ), + Row( + "large_list", + "list", + _plain(pa.large_list(pa.float16()), [[1.5], [], [0.25, None]]), + ), + Row( + "struct", + "struct and map", + _plain( + pa.struct( + [pa.field("a", pa.int32()), pa.field("b", pa.string(), nullable=False)] + ), + [{"a": 1, "b": "x"}, {"a": None, "b": "y"}, {"a": 3, "b": ""}], + ), + ), + Row( + "struct[2]>", + "struct and map", + _plain( + pa.struct([pa.field("f", pa.list_(pa.int64(), 2))]), + [{"f": [1, 2]}, {"f": None}, {"f": [5, 6]}], + ), + ), + Row( + "map", + "struct and map", + _plain( + pa.map_(pa.string(), pa.int64()), [[("a", 1)], [], [("b", 2), ("c", None)]] + ), + ), + Row("int64 not null", "nullability", _plain(pa.int64(), [1, 2, 3], nullable=False)), + Row( + "string not null", + "nullability", + _plain(pa.string(), ["a", "b", "c"], nullable=False), + ), + Row("File", "Orcapod logical type", _logical(orcapod.File, _files)), + Row("Directory", "Orcapod logical type", _logical(orcapod.Directory, _directories)), + Row( + "Path", + "Orcapod logical type", + _logical(Path, lambda r: [Path("/a"), Path("b/c"), Path(".")]), + ), + Row("UPath", "Orcapod logical type", _logical(Any, _upaths)), # resolved below + Row( + "uuid.UUID", + "Orcapod logical type", + _logical(uuid.UUID, lambda r: [uuid.UUID(int=i + 1) for i in range(3)]), + ), + Row( + "list[Path]", + "Orcapod logical type", + _logical(list[Path], lambda r: [[Path("/a")], [], [Path("b"), Path("c")]]), + ), + Row( + "set[int]", + "Orcapod logical type", + _logical(set[int], lambda r: [{1, 2}, set(), {3}]), + ), + Row( + "set[uuid.UUID]", + "Orcapod logical type", + _logical( + set[uuid.UUID], lambda r: [{uuid.UUID(int=1)}, set(), {uuid.UUID(int=2)}] + ), + ), + Row( + "dict[str, int]", + "Orcapod logical type", + _logical(dict[str, int], lambda r: [{"a": 1}, {}, {"b": 2}]), + ), + Row( + "user class, exact (dataclass)", + "Orcapod logical type", + _logical( + MatrixExact, + lambda r: [MatrixExact(1, "a"), MatrixExact(2, "b"), MatrixExact(3, "")], + ), + ), + Row( + "user class, structural (orcapod.dataclass)", + "Orcapod logical type", + _logical( + MatrixStructural, + lambda r: [ + MatrixStructural(1, "a"), + MatrixStructural(2, "b"), + MatrixStructural(3, ""), + ], + ), + ), + Row( + "numpy.ndarray", "library value type", _logical(Any, _arrays), provisional=True + ), + Row( + "pandas.DataFrame", + "library value type", + _logical(Any, _pandas_frames), + provisional=True, + ), + Row( + "pandas.Series", + "library value type", + _logical(Any, _pandas_series), + provisional=True, + ), + Row( + "polars.DataFrame", + "library value type", + _logical(Any, _polars_frames), + provisional=True, + ), + Row( + "polars.Series", + "library value type", + _logical(Any, _polars_series), + provisional=True, + ), + Row( + "torch.Tensor", "library value type", _logical(Any, _tensors), provisional=True + ), +) + + +def _python_type(label: str, declared: Any) -> Any: + """The Python type of a logical row (the library and UPath types imported late).""" + if declared is not Any: + return declared + if label == "UPath": + from upath import UPath + + return UPath + if label == "numpy.ndarray": + import numpy as np + + return np.ndarray + if label.startswith("pandas."): + import pandas as pd + + return getattr(pd, label.split(".")[1]) + if label.startswith("polars."): + import polars as pl + + return getattr(pl, label.split(".")[1]) + if label == "torch.Tensor": + import torch + + return torch.Tensor + raise AssertionError(label) + + +def build_table(row: Row, root: Path) -> pa.Table: + """The table written for ``row``: a non-null ``large_binary`` id, then ``x`` and ``y``.""" + first, second, xs, ys = row.build(root) + ids = pa.array([b"r1", b"r2", b"r3"], pa.large_binary()) + id_field = pa.field("id", pa.large_binary(), nullable=False) + if first == "logical": + python_type = _python_type(row.label, second) + converter = get_default_context().type_converter + table = converter.python_dicts_to_arrow_table( + [{"x": x, "y": y} for x, y in zip(xs, ys)], + python_schema={"x": python_type, "y": python_type | None}, + ) + return pa.Table.from_arrays( + [ids, table.column("x"), table.column("y")], + schema=pa.schema( + [id_field, table.schema.field("x"), table.schema.field("y")] + ), + ) + return pa.Table.from_arrays( + [ids, pa.array(xs, first.type), pa.array(ys, second.type)], + schema=pa.schema([id_field, first, second]), + ) + + +# --------------------------------------------------------------------------- +# The databases +# --------------------------------------------------------------------------- + + +@contextlib.contextmanager +def _database(name: str, root: Path) -> Iterator[Any]: + if name == "in-memory": + yield InMemoryArrowDatabase() + elif name == "Delta": + yield DeltaTableDatabase(root / "delta") + elif name == "SQLite": + yield ConnectorArrowDatabase(SQLiteConnector(str(root / "store.db"))) + elif name == "SpiralDB": + from tests.test_databases import fake_pyspiral + + with fake_pyspiral.install(root / "spiral"): + fake_pyspiral.FakeSpiral().project("p") + yield ConnectorArrowDatabase(SpiralDBConnector("p")) + elif name == "PostgreSQL": + with patch("psycopg.connect") as connect: + connect.return_value = MagicMock() + yield ConnectorArrowDatabase( + PostgreSQLConnector("postgresql://localhost/m") + ) + else: + raise AssertionError(name) + + +def _names_a_column(error: BaseException) -> bool: + text = str(error) + return any(f"'{c}'" in text or f'"{c}"' in text for c in ("x", "y")) + + +def _expected_field(field: "pa.Field[Any]") -> "pa.Field[Any]": + return field.with_type(normalize_to_large_types(field.type, keep_null=True)) + + +def _describe(field: "pa.Field[Any]") -> str: + nested = _nested_flags(field.type) + return f"{field.type}{'' if field.nullable else ' not null'}{nested}" + + +def _nested_flags(arrow_type: pa.DataType) -> str: + """The non-null nested fields, which ``str(type)`` may not show.""" + flags = [] + for i in range(getattr(arrow_type, "num_fields", 0)): + child = arrow_type.field(i) + if not child.nullable: + flags.append(child.name) + inner = _nested_flags(child.type) + if inner: + flags.append(f"{child.name}{inner}") + return f" [non-null: {', '.join(flags)}]" if flags else "" + + +def _same_field(a: "pa.Field[Any]", b: "pa.Field[Any]") -> bool: + return ( + a.name == b.name + and a.nullable == b.nullable + and a.type == b.type + and _nested_flags(a.type) == _nested_flags(b.type) + ) + + +def measure(row: Row, database: str, root: Path) -> Cell: + """Write ``row``'s table to ``database`` and say what came back.""" + root.mkdir(parents=True, exist_ok=True) + try: + written = build_table(row, root) + except Exception as exc: # noqa: BLE001 # a row Orcapod cannot build is reported + return Cell(SILENT, f"cannot build the column: {type(exc).__name__}: {exc}") + with _database(database, root) as db: + path = ("matrix", "t") + if database == "PostgreSQL": + try: + db.require_storable(written.schema) + db._connector.validate_records(written) # pyright: ignore[reportPrivateUsage] + except Exception as exc: # noqa: BLE001 + if _names_a_column(exc): + return Cell(REFUSED, f"{type(exc).__name__}") + return Cell( + SILENT, + f"refused without naming the column: {type(exc).__name__}: {exc}", + ) + return Cell(KEPT_BY_RULE, "storability rule only (no server)") + try: + db.add_records(path, written, record_id_column="id", flush=True) + except Exception as exc: # noqa: BLE001 + if _names_a_column(exc): + return Cell(REFUSED, f"{type(exc).__name__}") + return Cell( + SILENT, + f"write failed without naming the column: {type(exc).__name__}: {str(exc)[:160]}", + ) + try: + back = db.get_all_records(path, record_id_column="id") + except Exception as exc: # noqa: BLE001 + return Cell( + SILENT, f"written, read failed: {type(exc).__name__}: {str(exc)[:160]}" + ) + if back is None: + return Cell(SILENT, "written, read back nothing") + back = back.sort_by("id") + problems = [] + for name in ("x", "y"): + exact = written.schema.field(name) + got = back.schema.field(name) + # The type written, or its large variant (every Orcapod table is large). + if _same_field(exact, got): + want = exact + else: + want = _expected_field(exact) + if not _same_field(want, got): + problems.append(f"{name}: {_describe(exact)} -> {_describe(got)}") + continue + expected = written.column(name) + if want.type != exact.type: + expected = expected.cast(want.type) + if not back.column(name).combine_chunks().equals(expected.combine_chunks()): + problems.append(f"{name}: values differ") + if problems: + return Cell(SILENT, "; ".join(problems)) + if database == "Delta" and _is_recorded(written.schema.field("x").type): + return Cell(RECORDED) + return Cell(KEPT) + + +def measure_all(root: Path) -> dict[tuple[str, str], Cell]: + """Every cell of the matrix, keyed by (row label, database).""" + out: dict[tuple[str, str], Cell] = {} + for i, row in enumerate(ROWS): + for database in DATABASES: + out[(row.label, database)] = measure( + row, database, root / f"r{i}" / database + ) + return out + + +# --------------------------------------------------------------------------- +# The page +# --------------------------------------------------------------------------- + +PAGE = Path(__file__).resolve().parents[2] / "docs" / "reference" / "database-types.md" + +_CELL_TEXT = { + KEPT: "kept", + RECORDED: "kept (recorded type)", + KEPT_BY_RULE: "kept (by rule)", + REFUSED: "refused", + SILENT: "**not kept**", +} + +_INTRODUCTION = """\ +# Data types per database + + + +Each database Orcapod stores into keeps some Arrow types exactly and refuses the others. +None of them gives a column back as another type: a type a database cannot keep is +refused, with an error naming the column, before anything of the table is written. This +page lists every type for every database. It is generated from a test that writes and +reads each type through each database, so it cannot drift from the code. + +What a cell says: + +- **kept**: read back exactly, with its Arrow type (nested field names and nullability + included) and its values. Text, binary and list columns may come back in their large + variants (`large_string`, `large_binary`, `large_list`), the types every Orcapod table + uses. +- **kept (recorded type)**: kept by `DeltaTableDatabase` through a recorded type. Delta Lake + has no column type for it, so the column's Arrow type is recorded in its field metadata, + its values are written in a form Delta keeps (an integer form, `float32` for + `float16`, a `large_list` for a fixed-size list) and the type is restored on read. +- **kept (by rule)**: PostgreSQL stores the column, by the connector's own rule. No + PostgreSQL server is used to build this page, so this cell is the rule, not a measured + read. +- **refused**: writing the column raises an error naming it (`UnstorableColumnError` for + a connector database), and nothing of the table is written. + +How it is measured: a table holding two columns of the type (the second nullable, with a +null row) is written with `add_records`, flushed and read back with `get_all_records`. +The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which +models what SpiralDB does to a column (no SpiralDB is used). No database tells tag +columns from data columns, so a type is kept or refused the same way in either role. +The library value types (NumPy, pandas, Polars, torch) are +[provisional](../concepts/arrays.md): their stored form may change in a later release. + +The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and +`ConnectorArrowDatabase` over `SQLiteConnector`, `PostgreSQLConnector` and +`SpiralDBConnector`. See [The database](../concepts/pipeline-job.md#the-database) for how a +job uses one. + +Three refusals depend on the values as well as the type: + +- SpiralDB cannot store a null struct, so a struct column with a null row is refused + (the rows below have one); a struct column with no null row is kept. +- Delta has no `null` type: a new column holding only nulls with no type is refused (the + `null` row below), while a `null`-typed value is kept in a column the table already + stores with a type. +- A fixed-size list or fixed-size binary read back by Delta with another length or width + than its type is refused on read, never padded or cut. +""" + + +def render(cells: dict[tuple[str, str], Cell]) -> str: + """The page: the introduction, then one table per group of rows.""" + lines = [_INTRODUCTION] + groups: dict[str, list[Row]] = {} + for row in ROWS: + groups.setdefault(row.group, []).append(row) + header = "| Type | " + " | ".join(DATABASES) + " |" + rule = "|---|" + "---|" * len(DATABASES) + for group, rows in groups.items(): + lines.append(f"## {group[0].upper()}{group[1:]}\n") + lines.append(header) + lines.append(rule) + for row in rows: + label = f"`{row.label}`" + (" (provisional)" if row.provisional else "") + texts = [_CELL_TEXT[cells[(row.label, db)].kind] for db in DATABASES] + lines.append(f"| {label} | " + " | ".join(texts) + " |") + lines.append("") + return "\n".join(lines).rstrip("\n") + "\n" diff --git a/tests/test_pipeline/test_function_node_stored_values.py b/tests/test_pipeline/test_function_node_stored_values.py index d741512fb..21e5c98fb 100644 --- a/tests/test_pipeline/test_function_node_stored_values.py +++ b/tests/test_pipeline/test_function_node_stored_values.py @@ -141,7 +141,6 @@ def _lists(values: Column) -> Column: "decimal256(76,40)", "large_list", "struct", - "float16 -0.0", } ORCHESTRATORS: dict[str, Callable[[], Any]] = { @@ -150,17 +149,6 @@ def _lists(values: Column) -> Column: } -# Delta Lake stores fixed_size_binary as large_binary: a reused node's tag comes back -# with another type, so a node over it records new entries (ITL-999; also on main; not -# this read path). -DELTA_CHANGES_TYPE = pytest.mark.xfail( - strict=True, - reason="ITL-999: Delta Lake stores fixed_size_binary as large_binary, so the " - + "downstream node's entries repeat on a reuse run (a type the database does not " - + "keep, not the Polars read)", -) - - def _cases() -> list[Any]: params = [] for name in TYPES: @@ -168,8 +156,6 @@ def _cases() -> list[Any]: marks = [] if database == "delta" and name in NOT_IN_DELTA: marks = [pytest.mark.skip(reason="Delta Lake cannot store this type")] - elif database == "delta" and name == "fixed_size_binary(3)": - marks = [DELTA_CHANGES_TYPE] params.append( pytest.param(name, database, id=f"{name}-{database}", marks=marks) ) From 15bfd8311af8a5b9aafabb2a93ce231c6af62b09 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 03:01:34 -0800 Subject: [PATCH 02/13] fix(databases): evolved structs keep values by name; an exact matrix; nested nulls, zero-width lists Codex review of PR 471: - BLOCKER: an append that evolves a struct (fields reordered, omitted or added) swapped or dropped values. Delta's MERGE matches struct fields by position (also for structs with no recorded type: pre-existing on main), so appended rows are given the stored layout by name first (an omitted field filled with nulls, an omitted non-nullable one refused); a recorded column's record describes the merged column (merged_type); and a read rebuilds every nested type, matching struct fields by name. - The matrix compares exactly: names, nullability and metadata of every nested field, a map's keys_sorted, and values bit for bit. New rows: -0.0 and NaN floats, a renamed list item with metadata, struct child metadata, sorted maps (default and renamed fields), field metadata, a zero-width fixed-size list. What the stricter matrix found: Delta renames every list item and drops map keys_sorted, so every list and map is now recorded; Arrow IPC (Delta's record, the SpiralDB fake) renames map key/item fields, so such maps are refused on Delta and SpiralDB; SQLite reads NaN as NULL and -0.0 as 0.0, so a double column holding one is refused. A refusal must leave the table empty. - A null-typed part at a nested path nothing stored gives a type is refused naming the column and the path, before anything is buffered. - A zero-width fixed-size list keeps its row count on read. - SQLite and PostgreSQL give a column the stored NOT NULL only for a direct projection of its table (is_direct_projection); a join or an aggregate reads it nullable. Refs ITL-1334 Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1334.md | 38 ++- docs/concepts/pipeline-job.md | 13 +- docs/reference/database-types.md | 66 ++-- src/orcapod/databases/delta_arrow_types.py | 210 +++++++++---- src/orcapod/databases/delta_lake_databases.py | 291 +++++++++++++++++- src/orcapod/databases/postgresql_connector.py | 9 +- src/orcapod/databases/spiraldb_connector.py | 8 +- src/orcapod/databases/sqlite_connector.py | 41 ++- src/orcapod/databases/utils.py | 36 +++ src/orcapod/utils/arrow_utils.py | 27 ++ .../test_delta_arrow_type_roundtrip.py | 9 + .../test_delta_native_fs_read.py | 5 +- .../test_delta_struct_evolution.py | 244 +++++++++++++++ .../test_postgresql_connector.py | 31 ++ tests/test_databases/test_sqlite_connector.py | 52 ++++ tests/test_databases/type_matrix.py | 259 +++++++++++++--- 16 files changed, 1170 insertions(+), 169 deletions(-) create mode 100644 tests/test_databases/test_delta_struct_evolution.py diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index 3943792e8..10c1d636c 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -7,36 +7,50 @@ every Orcapod logical type and the library value types) for every database (in-memory, Delta Lake, SQLite, PostgreSQL, SpiralDB): kept, kept through a recorded type, or refused. It is generated from a test that writes and reads each type through each - database, and that fails if any database gives a column back as another type without an - error. (ITL-1334) + database, and that fails if any database gives a column back other than exactly (type + with every nested field's name, nullability and metadata, and values bit for bit) + without an error. (ITL-1334) - **`DeltaTableDatabase` keeps more types:** `float16` (written as `float32`, which holds every `float16` exactly), fixed-size lists, also nested and with null rows (written as a `large_list`; a fixed-size list used to read back as a `large_list`, and with a null row could not be read back at all), fixed-size binary (read back as `large_binary` before) - and lists with non-null items (their item field was renamed `element`), all through the - recorded-type mechanism already used for unsigned integers and nanosecond timestamps. + every list (its item was renamed `element` and lost its metadata) and every map (it lost + `keys_sorted`), all through the recorded-type mechanism already used for unsigned + integers and nanosecond timestamps. A restore never pads, cuts or rounds: stored rows that cannot be what was written raise, naming the column. (ITL-1275, ITL-1283, ITL-1334) ### Changed - **`DeltaTableDatabase` refuses what Delta cannot hold, naming the column:** a - `decimal256` or an interval column (as Delta's own writer decides), and a new column - holding only nulls with no type, raise `UnstorableColumnError` when added, before - anything is buffered, and a job refuses such a column up front (`require_storable`). They - used to fail the flush with an error that named no column. A `null`-typed value in a - column the table already stores with a type is still kept. (ITL-1334) + `decimal256` or an interval column (as Delta's own writer decides), a map whose key or + item field is not named `key` / `value`, and a new column or nested field holding only + nulls with no type, raise `UnstorableColumnError` when added, before anything is + buffered, and a job refuses such a column up front (`require_storable`). They used to + fail the flush with an error that named no column. A `null`-typed value where the table + already stores a type is still kept. (ITL-1334) - **The SQLite and PostgreSQL connectors read a non-null column back non-null:** the - column is created `NOT NULL`, and the read now gives the field that flag; it read back - nullable before. (ITL-1276) + column is created `NOT NULL`, and a read that projects the table's columns directly now + gives the field that flag; it read back nullable before. Any other query (a join, an + aggregate) reads every column nullable. (ITL-1276) +- **`SQLiteConnector` refuses a `double` column holding a NaN or `-0.0`:** SQLite reads a + NaN back as NULL and `-0.0` as `0.0`. (ITL-1334) - **`SpiralDBConnector` refuses a logical (extension) type:** `File`, `Directory`, `Path`, `UPath`, `UUID`, `list[T]` and `set[T]` of them, user classes and the library value types read back from SpiralDB as their plain storage type (SpiralDB drops the field metadata that names them). They are refused with `UnstorableColumnError` before - anything is written. (ITL-1334) + anything is written, as is a map whose key or item field is not named `key` / `value`. + (ITL-1334) ### Fixed +- **An append to a Delta table that evolves a struct keeps every value under its name:** + Delta's MERGE matches struct fields by position, so rows appended with the fields in + another order stored each value under another field's name. The rows are now given the + stored layout by name first (an omitted field reads as null, an omitted non-nullable + field is refused), and a recorded column's record describes the merged column. + (ITL-1334) + - **`SpiralDBConnector` reads back a fixed-size list with non-null items and a null row:** the read cast every column to the restored schema, and pyarrow refuses that cast when a null row hides null item slots; only columns whose type changes are cast now. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 4eda01f0d..1c5465a4b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -109,10 +109,11 @@ Any Orcapod database can hold a job's results. Two are used most: for experiments and tests. - **`DeltaTableDatabase("some/directory")`** writes [Delta Lake](https://delta.io/) tables under a directory, and is what makes results survive between sessions. It keeps every - type Orcapod uses: where Delta has no column type (an unsigned integer, a nanosecond - timestamp, `float16`, a fixed-size list), the column's Arrow type is recorded and - restored on read. It refuses, naming the column, the few types Delta cannot hold at all - (`decimal256`, an interval) and a new column holding only nulls with no type. + type Orcapod uses: where Delta has no column type or would change it (an unsigned + integer, a nanosecond timestamp, `float16`, a fixed-size list, a list's item name), the + column's Arrow type is recorded and restored on read. It refuses, naming the column, the + few types Delta cannot hold at all (`decimal256`, an interval), a map whose key or item + field is not named `key` / `value`, and a new column holding only nulls with no type. No database gives a column back as another type: each keeps a type exactly or refuses it before anything of the table is written. [Data types per database](../reference/database-types.md) @@ -142,7 +143,9 @@ and binary columns come back as `large_string` and `large_binary`, the types Orc | `SQLiteConnector` | `bool`, `int64`, `double`, `large_string`, `large_binary` | | `PostgreSQLConnector` | `bool`, `int32`, `int64`, `float`, `double`, `large_string`, `large_binary`, `date32`, `timestamp[us]`, `timestamp[us, tz=UTC]` | -A non-null column is created `NOT NULL` and reads back non-null. Any other type (lists, +A non-null column is created `NOT NULL` and reads back non-null. SQLite refuses a +`double` column holding a NaN or `-0.0`, which it would read back as NULL and `0.0`. Any +other type (lists, structs, dates or timestamps on SQLite, narrower integers and floats, logical types) is refused. PostgreSQL also refuses a column name or a table name longer than 63 bytes, which it would truncate (`UnstorableTableNameError` for a table). `SpiralDBConnector` stores other types as written, except a diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index d17371391..68fdfe368 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -7,24 +7,31 @@ this page and the measurements differ. Do not edit by hand. --> Each database Orcapod stores into keeps some Arrow types exactly and refuses the others. -None of them gives a column back as another type: a type a database cannot keep is -refused, with an error naming the column, before anything of the table is written. This -page lists every type for every database. It is generated from a test that writes and -reads each type through each database, so it cannot drift from the code. +For every type on this page, each database either gives the column back exactly or refuses +it, with an error naming the column, before anything of the table is written: none gives +it back as another type. The page is generated from a test that writes and reads each +type through each database, so it cannot drift from the code. The rows are +representative, not every Arrow type: dictionary-encoded columns are refused by every +stream before they reach a database, and union, run-end-encoded and list-view types are +not covered. What a cell says: -- **kept**: read back exactly, with its Arrow type (nested field names and nullability - included) and its values. Text, binary and list columns may come back in their large +- **kept**: read back exactly: the Arrow type with the name, nullability and metadata of + the column and of every nested field (a list's item, a struct's children, a map's key + and item, and whether its keys are sorted), and the values bit for bit (a float's + `-0.0` and NaN included). Text, binary and list columns may come back in their large variants (`large_string`, `large_binary`, `large_list`), the types every Orcapod table uses. -- **kept (recorded type)**: kept by `DeltaTableDatabase` through a recorded type. Delta Lake - has no column type for it, so the column's Arrow type is recorded in its field metadata, - its values are written in a form Delta keeps (an integer form, `float32` for - `float16`, a `large_list` for a fixed-size list) and the type is restored on read. +- **kept (recorded type)**: kept by `DeltaTableDatabase` through a recorded type. Delta + Lake has no column type for it, or gives it back changed (it names every list item + `element` and drops a map's sorted keys), so the column's Arrow type is recorded in its + field metadata, its values are written in a form Delta keeps (an integer form, + `float32` for `float16`, a `large_list` for a fixed-size list) and the type is restored + on read, nested fields matched by name. - **kept (by rule)**: PostgreSQL stores the column, by the connector's own rule. No PostgreSQL server is used to build this page, so this cell is the rule, not a measured - read. + read: it does not show that the server keeps every value (a NaN, a time zone). - **refused**: writing the column raises an error naming it (`UnstorableColumnError` for a connector database), and nothing of the table is written. @@ -41,16 +48,24 @@ The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta) `SpiralDBConnector`. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. -Three refusals depend on the values as well as the type: +Some refusals depend on the values or names as well as the type: - SpiralDB cannot store a null struct, so a struct column with a null row is refused (the rows below have one); a struct column with no null row is kept. -- Delta has no `null` type: a new column holding only nulls with no type is refused (the - `null` row below), while a `null`-typed value is kept in a column the table already - stores with a type. +- SQLite reads a NaN back as NULL and `-0.0` as `0.0`, so a `double` column holding one + is refused (the float rows below hold both); one without them is kept. +- Delta has no `null` type: a new column, or a new nested field, holding only nulls with + no type is refused (the `null` row below), while a `null`-typed value is kept where the + table already stores a type. +- Delta and SpiralDB give a map's key and item fields back as `key` and `value`, so a map + with other names is refused. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. +Appending to a Delta table may evolve a struct column (fields added, omitted or in +another order): every value keeps its field's name, and an omitted field reads as null +in the appended rows. + ## Integer | Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | @@ -70,7 +85,7 @@ Three refusals depend on the values as well as the type: |---|---|---|---|---|---| | `halffloat (float16)` | kept | kept (recorded type) | refused | refused | kept | | `float (float32)` | kept | kept | refused | kept (by rule) | kept | -| `double (float64)` | kept | kept | kept | kept (by rule) | kept | +| `double (float64)` | kept | kept | refused | kept (by rule) | kept | ## Decimal @@ -134,13 +149,14 @@ Three refusals depend on the values as well as the type: | Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | |---|---|---|---|---|---| -| `list` | kept | kept | refused | refused | kept | +| `list` | kept | kept (recorded type) | refused | refused | kept | | `list` | kept | kept (recorded type) | refused | refused | kept | -| `large_list` | kept | kept | refused | refused | kept | +| `large_list` | kept | kept (recorded type) | refused | refused | kept | | `large_list` | kept | kept (recorded type) | refused | refused | kept | | `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | kept | | `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | kept | | `large_list` | kept | kept (recorded type) | refused | refused | kept | +| `fixed_size_list[0]` | kept | kept (recorded type) | refused | refused | kept | ## Struct and map @@ -148,7 +164,17 @@ Three refusals depend on the values as well as the type: |---|---|---|---|---|---| | `struct` | kept | kept | refused | refused | refused | | `struct[2]>` | kept | kept (recorded type) | refused | refused | refused | -| `map` | kept | kept | refused | refused | kept | +| `map` | kept | kept (recorded type) | refused | refused | kept | + +## Names and metadata + +| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | +|---|---|---|---|---|---| +| `large_list` | kept | kept (recorded type) | refused | refused | kept | +| `struct` | kept | kept | refused | refused | refused | +| `map, keys sorted` | kept | kept (recorded type) | refused | refused | kept | +| `map, keys sorted` | kept | refused | refused | refused | refused | +| `int64 {unit: s} (field metadata)` | kept | kept | refused | refused | kept | ## Nullability @@ -169,7 +195,7 @@ Three refusals depend on the values as well as the type: | `list[Path]` | kept | kept | refused | refused | refused | | `set[int]` | kept | kept | refused | refused | refused | | `set[uuid.UUID]` | kept | kept | refused | refused | refused | -| `dict[str, int]` | kept | kept | refused | refused | kept | +| `dict[str, int]` | kept | kept (recorded type) | refused | refused | kept | | `user class, exact (dataclass)` | kept | kept | refused | refused | refused | | `user class, structural (orcapod.dataclass)` | kept | kept | refused | refused | refused | diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index 7c1010235..5663ff3c8 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -7,39 +7,43 @@ maximum; every timestamp to microseconds, dropping nanosecond digits; a zone to UTC; a fixed-size binary to ``large_binary``; a fixed-size list to a list, which reads back as ``large_list`` and, with a null row, cannot be read back as a fixed-size list at all), -renames the item field of a list whose items are non-null (``item`` to ``element``), and -cannot store the others. +names every list item ``element`` and drops its field metadata, drops a map's +``keys_sorted``, and cannot store the others. A Delta database must give back the type it was given: a tag read back with another type changes every record id computed from it. So before a write, a column whose type Delta -would not keep is recorded in its top-level field metadata (``ARROW_TYPE_KEY``: the -column's whole Arrow type, IPC-serialized; Delta keeps top-level field metadata but not -that of nested fields), and the values Delta cannot hold losslessly are written as -their integer form: +would not keep, or holds a list or a map, is recorded in its top-level field metadata +(``ARROW_TYPE_KEY``: the column's whole Arrow type, IPC-serialized; Delta keeps +top-level field metadata), and the values Delta cannot hold losslessly are written in +another form: * an unsigned integer as the signed integer of the same width, bit for bit; * ``timestamp[ns]``, ``date64``, ``time32``, ``time64`` and ``duration`` as their integer value (``int64``, or ``int32`` for ``time32``); * ``float16`` as ``float32``, which holds every ``float16`` value exactly; * a fixed-size list as a ``large_list`` of the same items (ITL-1275, ITL-1283); -* a fixed-size binary as ``large_binary``, and a list with non-null items as it is (its - item field's name is restored from the record; ITL-1334). +* a fixed-size binary as ``large_binary``; a list or a map as it is (its item names, + item metadata and ``keys_sorted`` come back from the record; ITL-1334). What Delta cannot hold even so (``decimal256``, an interval) is refused before anything is written: ``DeltaTableDatabase.require_storable`` asks the Delta writer's own -conversion about the column as it is written (``written_field``). A ``null``-typed value -is not recorded: it fits a column already stored with a type (the append check leaves it -out), and a column with no stored type yet is refused by ``add_records``. +conversion about the column as it is written (``written_field``). So is a map whose key +or item field is not named ``key`` / ``value``: the record goes through Arrow IPC, which +renames them. A ``null``-typed value is not recorded: it fits where the table already +stores a type (the append check leaves it out), and a ``null`` part with no stored type +at its path is refused by ``add_records``. ``timestamp[s]``, ``timestamp[ms]`` and a zone other than UTC are left to Delta's own -conversion, which is lossless. A read casts each recorded column back to its recorded -type (large-normalized), at every depth, because the whole column type is recorded: a -fixed-size list is rebuilt from the list Delta gives back (a null row comes back with no -items, which a cast cannot fill), refusing a row of another length; a ``float16`` is -checked to hold exactly the ``float32`` value read; and a fixed-size binary to hold -values of its width. A column whose type has an -extension (logical) type anywhere is left as it is: its type is restored from its -extension metadata. +conversion, which is lossless. A read restores each recorded column to its recorded type +(large-normalized), at every depth, because the whole column type is recorded: every +nested type is rebuilt with the recorded field names, nullability and metadata, struct +fields matched by NAME (an append may evolve a struct, and the record then describes the +merged column: ``merged_type``); a fixed-size list is rebuilt from the list Delta gives +back (a null row comes back with no items, which a cast cannot fill), refusing a row of +another length; a ``float16`` is checked to hold exactly the ``float32`` value read; and a +fixed-size binary to hold values of its width. A column whose type has an extension +(logical) type anywhere is left as it is: its type is restored from its extension +metadata. A table written before this existed has no recorded type and reads back with Delta's types; such a database must be rebuilt. @@ -142,8 +146,9 @@ def _is_recorded(arrow_type: pa.DataType) -> bool: It does when it has, at any depth, a part Delta would not give back: an unsigned integer, a timestamp in another unit than microseconds or with a zone other than - UTC, a ``date64``, ``time``, ``duration``, ``float16`` or fixed-size binary, - a fixed-size list, or a list whose items are non-null (Delta renames its item field). + UTC, a ``date64``, ``time``, ``duration``, ``float16`` or fixed-size binary, or + any list or map: Delta names every list item ``element`` and drops its metadata, + and drops a map's ``keys_sorted`` (ITL-1334). """ t = pa.types if ( @@ -154,10 +159,9 @@ def _is_recorded(arrow_type: pa.DataType) -> bool: or t.is_float16(arrow_type) or t.is_fixed_size_binary(arrow_type) or t.is_fixed_size_list(arrow_type) - ): - return True - if (t.is_list(arrow_type) or t.is_large_list(arrow_type)) and not ( - arrow_type.value_field.nullable + or t.is_list(arrow_type) + or t.is_large_list(arrow_type) + or t.is_map(arrow_type) ): return True if t.is_timestamp(arrow_type): @@ -231,48 +235,52 @@ def from_delta_layout(table: pa.Table) -> pa.Table: return table -def _needs_rebuild(arrow_type: pa.DataType) -> bool: - """Whether ``arrow_type`` has, at any depth, a part a cast cannot restore exactly - (a fixed-size list, which a null row breaks) or must check (a ``float16``).""" - t = pa.types - if t.is_fixed_size_list(arrow_type) or t.is_float16(arrow_type): - return True - return any( - _needs_rebuild(arrow_type.field(i).type) for i in range(arrow_type.num_fields) - ) +def _is_nested(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` has child fields (a struct, a list of any kind, a map).""" + return arrow_type.num_fields > 0 or pa.types.is_fixed_size_list(arrow_type) def _restore(array: Any, target: Any) -> Any: """Return ``array``, as read from Delta, with the type ``target`` it was written as. - Values were written from ``target``, so a cast restores them, except where - ``_needs_rebuild``: a fixed-size list is rebuilt from the list read, and a - ``float16`` is checked to hold exactly the value read. Containers holding one are - rebuilt around their restored children. + Every nested type is rebuilt around its restored children, so each child field + gets the recorded name, nullability and metadata (Arrow's own type equality ignores + them, so no nested type is taken as already restored): a struct's children are + matched by NAME, never by position, since an append that evolves the struct may + store them in another order; a fixed-size list is rebuilt from the list read; a map + gets its recorded key and item fields and ``keys_sorted``. A leaf is cast (values + were written from its type, so the cast back is exact), and a ``float16`` is checked + to hold exactly the value read. Raises: - ValueError: A list row has another length than its fixed size, a value is not - a ``float16`` value, or a fixed-size binary has another width: the stored - rows are not what was written. + ValueError: The stored rows are not what was written: a list row has another + length than its fixed size, a value is not a ``float16`` value, a + fixed-size binary has another width, or a struct has other fields than + recorded. """ - if array.type == target: - return array t = pa.types - if not _needs_rebuild(target): - # Values were written from this type, so the cast back is exact. - return array.cast(target, safe=False) - mask = array.is_null() if array.null_count else None - if t.is_float16(target): + if not _is_nested(target): + if array.type == target: + return array restored = array.cast(target, safe=False) - if not _same_floats(restored.cast(array.type), array): + if t.is_float16(target) and not _same_floats(restored.cast(array.type), array): raise ValueError("a value is not a float16 value") return restored + mask = array.is_null() if array.null_count else None if t.is_fixed_size_list(target): return _fixed_size_list(array, target) if t.is_struct(target): + if not t.is_struct(array.type): + raise ValueError(f"a struct is stored as {array.type}") + stored = {array.type.field(i).name: i for i in range(array.type.num_fields)} + recorded = [field.name for field in target] + if set(stored) != set(recorded): + raise ValueError( + f"the stored struct fields {sorted(stored)} are not the recorded " + f"{sorted(recorded)}" + ) children = [ - _restore(array.field(i), target.field(i).type) - for i in range(target.num_fields) + _restore(array.field(stored[field.name]), field.type) for field in target ] return pa.StructArray.from_arrays(children, fields=list(target), mask=mask) if t.is_map(target): @@ -283,15 +291,14 @@ def _restore(array: Any, target: Any) -> Any: type=cast(Any, target), # pyarrow's stubs type ``type`` too narrowly mask=mask, ) - if t.is_large_list(target) or t.is_list(target): - array_class = pa.LargeListArray if t.is_large_list(target) else pa.ListArray - return array_class.from_arrays( - array.offsets, - _restore(array.values, target.value_type), - type=target, - mask=mask, - ) - raise ValueError(f"no restore for {target}") # pragma: no cover # every kind above + large = t.is_large_list(target) + array_class = pa.LargeListArray if large else pa.ListArray + return array_class.from_arrays( + array.offsets.cast(pa.int64() if large else pa.int32()), + _restore(array.values, target.value_type), + type=target, + mask=mask, + ) def _same_floats(a: Any, b: Any) -> bool: @@ -321,11 +328,19 @@ def _fixed_size_list(array: Any, target: Any) -> Any: raise ValueError(f"a list row does not hold {size} items") indices = np.repeat(offsets[:-1], size) + np.tile(np.arange(size), rows) filled = np.repeat(valid | (lengths == size), size) - values = array.values.take(pa.array(indices, pa.int64(), mask=~filled)) - return pa.FixedSizeListArray.from_arrays( - _restore(values, target.value_type), - type=target, - mask=None if valid.all() else pa.array(~valid), + values = _restore( + array.values.take(pa.array(indices, pa.int64(), mask=~filled)), + target.value_type, + ) + # Built from buffers, so a zero-width list keeps its row count (from_arrays would + # take the count from the items, of which it has none). + validity = None if valid.all() else pa.array(valid, pa.bool_()).buffers()[1] + return pa.Array.from_buffers( + target, + rows, + cast(Any, [validity]), # the stubs do not allow an absent (None) buffer + null_count=int((~valid).sum()), + children=[values], ) @@ -391,3 +406,68 @@ def written_field(field: "pa.Field[Any]") -> "pa.Field[Any]": if _has_extension_type(field.type) or not _is_recorded(field.type): return field return _stored_field(field) + + +def merged_type(stored: pa.DataType, incoming: pa.DataType) -> pa.DataType: + """The type a column holds once rows of ``incoming`` are appended to ``stored``. + + An append may evolve a struct (schema evolution): Delta keeps the stored fields + and adds the new ones, so the merged struct has the stored fields, in their order, + each merged with the incoming field of the same name, then the incoming fields the + stored struct does not have. Lists, fixed-size lists and maps merge their items. + Any other type is the stored one: the append check (``_types_conflict``) has + already refused an incoming type that changes it. + + Args: + stored: The column's type as stored (its recorded type, else its stored type). + incoming: The type of the rows appended. + + Returns: + The column's type after the append, to be recorded (ITL-1334). + """ + t = pa.types + if t.is_struct(stored) and t.is_struct(incoming): + incoming_fields = {field.name: field for field in incoming} + stored_names = {field.name for field in stored} + fields = [ + field.with_type(merged_type(field.type, incoming_fields[field.name].type)) + if field.name in incoming_fields + else field + for field in stored + ] + [field for field in incoming if field.name not in stored_names] + return pa.struct(fields) + if t.is_map(stored) and t.is_map(incoming): + return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields + stored.key_field.with_type(merged_type(stored.key_type, incoming.key_type)), + stored.item_field.with_type( + merged_type(stored.item_type, incoming.item_type) + ), + keys_sorted=stored.keys_sorted, + ) + if ( + (t.is_large_list(stored) and t.is_large_list(incoming)) + or (t.is_list(stored) and t.is_list(incoming)) + or ( + t.is_fixed_size_list(stored) + and t.is_fixed_size_list(incoming) + and stored.list_size == incoming.list_size + ) + ): + value_field = stored.value_field.with_type( + merged_type(stored.value_type, incoming.value_type) + ) + if t.is_large_list(stored): + return pa.large_list(value_field) + if t.is_list(stored): + return pa.list_(value_field) + return pa.list_(value_field, stored.list_size) + return stored + + +def with_recorded_type( + field: "pa.Field[Any]", arrow_type: pa.DataType +) -> "pa.Field[Any]": + """Return ``field`` with ``arrow_type`` recorded in its metadata (``ARROW_TYPE_KEY``).""" + metadata = dict(field.metadata or {}) + metadata[ARROW_TYPE_KEY] = _serialize(arrow_type) + return field.with_metadata(cast(Any, metadata)) # the stubs type keys too narrowly diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 2e9dac5c3..fe9e608f1 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -27,8 +27,10 @@ from orcapod.databases.delta_arrow_types import ( first_column_out_of_stored_range, from_delta_layout, + merged_type, recorded_type, to_delta_layout, + with_recorded_type, written_field, ) from orcapod.databases.delta_statistics import statistics_configuration @@ -262,6 +264,237 @@ def _as_delta_writer_stores(schema: pa.Schema) -> pa.Schema: ) +def _conformed_to_stored( + delta_table: deltalake.DeltaTable, written: pa.Table, table_uri: str +) -> pa.Table: + """Return ``written`` with each struct, at every depth, in the stored layout. + + Delta's MERGE matches the fields of a struct by POSITION, so a struct appended with + its fields in another order would store each value under another field's name. Each + column the table stores is given the stored struct layout, by name: the stored + fields in their order (a field the rows omit is filled with nulls), then the rows' + new fields (schema evolution), at every depth of lists and maps. Logical + (extension) columns, whose layout their type fixes, are left as they are. + + Args: + delta_table: The loaded stored table. + written: The rows about to be appended, as written (``to_delta_layout``). + table_uri: The table, for the error message. + + Returns: + ``written`` in the stored layout. + + Raises: + InputValidationError: The rows omit a struct field the table stores as + non-nullable. + """ + stored = _stored_arrow_schema(delta_table) + for index, field in enumerate(written.schema): + position = stored.get_field_index(field.name) + if position < 0 or isinstance(field.type, pa.ExtensionType): + continue + column = written.column(index) + try: + conformed = pa.chunked_array( + [ + _conformed_array(chunk, stored.field(position).type) + for chunk in column.chunks + ] + ) + except ValueError as exc: + raise InputValidationError( + f"Cannot append to the stored table {table_uri!r}: column " + f"{field.name!r}: {exc}. The stored rows are unchanged and nothing " + "was written." + ) from exc + if conformed.type != column.type or _struct_orders(conformed.type) != ( + _struct_orders(column.type) + ): + written = written.set_column( + index, field.with_type(conformed.type), conformed + ) + return written + + +def _struct_orders(arrow_type: pa.DataType) -> tuple[Any, ...]: + """The field names of every struct in ``arrow_type``, in order (Arrow's type + equality compares them, but this states the intent).""" + if pa.types.is_struct(arrow_type): + return tuple((f.name, _struct_orders(f.type)) for f in arrow_type) + return tuple( + _struct_orders(arrow_type.field(i).type) for i in range(arrow_type.num_fields) + ) + + +def _conformed_array(array: Any, stored: Any) -> Any: + """Return ``array`` with every struct in the stored layout (``_conformed_to_stored``). + + Raises: + ValueError: The array omits a struct field ``stored`` has as non-nullable. + """ + t = pa.types + mask = array.is_null() if array.null_count else None + if t.is_struct(array.type) and t.is_struct(stored): + own = {array.type.field(i).name: i for i in range(array.type.num_fields)} + fields, children = [], [] + for stored_field in stored: + if stored_field.name in own: + i = own[stored_field.name] + child = _conformed_array(array.field(i), stored_field.type) + fields.append(array.type.field(i).with_type(child.type)) + children.append(child) + elif stored_field.nullable: + fields.append(stored_field) + children.append(pa.nulls(len(array), stored_field.type)) + else: + raise ValueError( + f"the rows omit the struct field {stored_field.name!r}, stored as " + "non-nullable" + ) + stored_names = {f.name for f in stored} + for i in range(array.type.num_fields): + own_field = array.type.field(i) + if own_field.name not in stored_names: + fields.append(own_field) + children.append(array.field(i)) + return pa.StructArray.from_arrays(children, fields=fields, mask=mask) + if t.is_map(array.type) and t.is_map(stored): + keys = _conformed_array(array.keys, stored.key_type) + items = _conformed_array(array.items, stored.item_type) + return pa.MapArray.from_arrays( + array.offsets, + keys, + items, + type=cast( + Any, + pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes fields + array.type.key_field.with_type(keys.type), + array.type.item_field.with_type(items.type), + keys_sorted=array.type.keys_sorted, + ), + ), + mask=mask, + ) + # A fixed-size list is written as a large_list (``to_delta_layout``), so only the + # variable-size lists appear here. + lists = (t.is_list, t.is_large_list) + if any(k(array.type) for k in lists) and any(k(stored) for k in lists): + # cast: the type guards above narrow the types in the stubs' terms. + list_type: Any = array.type + values = _conformed_array(array.values, cast(Any, stored).value_type) + if values.type == list_type.value_type and _struct_orders(values.type) == ( + _struct_orders(list_type.value_type) + ): + return array + value_field = list_type.value_field.with_type(values.type) + if t.is_large_list(array.type): + return pa.LargeListArray.from_arrays( + array.offsets, values, type=pa.large_list(value_field), mask=mask + ) + return pa.ListArray.from_arrays( + array.offsets, values, type=pa.list_(value_field), mask=mask + ) + return array + + +def _with_merged_records( + delta_table: deltalake.DeltaTable, original: pa.Table, written: pa.Table +) -> pa.Table: + """Return ``written`` with each recorded column's record describing the column + after the append (ITL-1334). + + A column recorded on either side (stored or incoming) is recorded as the merge of + its stored type (its record, else its stored type) and the incoming rows' type + (``merged_type``): an append that evolves a struct (a field added, omitted or in + another order) keeps every stored field and its values, which a read then matches + by name. Columns the stored table does not have, and logical (extension) columns, + are left as they are. + + Args: + delta_table: The loaded stored table. + original: The rows about to be appended, with their own types. + written: ``original`` as it is written (``to_delta_layout``). + + Returns: + ``written`` with the merged records. + """ + stored = _stored_arrow_schema(delta_table) + stored_records = { + f.name: recorded_type(f.metadata) for f in delta_table.schema().fields + } + for index, field in enumerate(written.schema): + position = stored.get_field_index(field.name) + own = original.schema.field(field.name).type + if position < 0 or isinstance(own, pa.ExtensionType): + continue + stored_record = stored_records.get(field.name) + incoming_record = recorded_type(field.metadata) + if stored_record is None and incoming_record is None: + continue + base = ( + stored_record + if stored_record is not None + else arrow_utils.normalize_to_large_types(stored.field(position).type) + ) + incoming = ( + incoming_record + if incoming_record is not None + else arrow_utils.normalize_to_large_types(own) + ) + written = written.set_column( + index, + with_recorded_type(field, merged_type(base, incoming)), + written.column(index), + ) + return written + + +def _untyped_null_path(incoming: Any, given: Any, path: str) -> str | None: + """The first path where ``incoming`` is ``null``-typed and ``given`` has no type. + + ``given`` is what the stored table (or a pending batch) has at ``path``, or ``None`` + when it has nothing there; a stored ``null`` type gives no type either. Struct + fields are matched by name, and list items, map keys and items followed. + + Returns: + The dotted path (``x.b``, ``x[]``), or ``None`` when every ``null`` part of + ``incoming`` has a typed counterpart. + """ + t = pa.types + if given is not None and t.is_null(given): + given = None + if t.is_null(incoming): + return path if given is None else None + if t.is_struct(incoming): + known = ( + {f.name: f.type for f in given} + if given is not None and t.is_struct(given) + else {} + ) + for field in incoming: + found = _untyped_null_path( + field.type, known.get(field.name), f"{path}.{field.name}" + ) + if found is not None: + return found + return None + if t.is_map(incoming): + is_map = given is not None and t.is_map(given) + return _untyped_null_path( + incoming.key_type, given.key_type if is_map else None, f"{path}.key" + ) or _untyped_null_path( + incoming.item_type, given.item_type if is_map else None, f"{path}.item" + ) + if incoming.num_fields or t.is_fixed_size_list(incoming): + is_list = given is not None and ( + t.is_list(given) or t.is_large_list(given) or t.is_fixed_size_list(given) + ) + return _untyped_null_path( + incoming.value_type, given.value_type if is_list else None, f"{path}[]" + ) + return None + + def _holds_null_type(arrow_type: pa.DataType) -> bool: """Whether ``arrow_type`` is or nests a ``null`` type (Delta has none; ITL-1334).""" if pa.types.is_null(arrow_type): @@ -290,6 +523,9 @@ def _delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: Delta's reason (``Invalid data type for Delta Lake: Decimal256(40, 2)``), or ``None`` when Delta holds the column. """ + if arrow_utils.holds_renamed_map(field.type): + # The recorded type goes through Arrow IPC, which renames them (ITL-1334). + return "a map's key and item fields read back as 'key' and 'value'" written = written_field(field) reduced = _without_null_types(written.type) if reduced is None: @@ -1084,40 +1320,46 @@ def require_storable(self, schema: pa.Schema) -> None: def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: - """Refuse a column with ``null``-typed parts that no stored column types (ITL-1334). + """Refuse a ``null``-typed part that nothing stored gives a type (ITL-1334). - Delta has no ``null`` type. A ``null``-typed value fits a column the stored - table (or a batch pending for it) already has with a type, and the append - check leaves it out; a column no stored or pending batch gives a type cannot be - written, so it is refused here, before anything is buffered, instead of failing - the flush without naming it. + Delta has no ``null`` type. A ``null``-typed value, at any depth, fits where + the stored table (or a batch pending for it) already has a typed column or + nested field at the same path, and the append check leaves it out. A ``null`` + part at a path nothing gives a type (a new column, a new struct field, the items + of a new list) cannot be written, so it is refused here, before anything is + buffered, instead of failing the flush without naming it. Args: record_path: The table the rows are for. schema: The schema of the rows about to be added. Raises: - UnstorableColumnError: For the first such column. + UnstorableColumnError: For the first such column, naming the path. """ untyped = [f for f in schema if _holds_null_type(f.type)] if not untyped: return - typed: set[str] = set() delta_table = self._get_delta_table(record_path) - if delta_table is not None: - typed.update(_stored_arrow_schema(delta_table).names) + stored = _stored_arrow_schema(delta_table) if delta_table is not None else None pending = self._pending_batches.get(self._get_record_key(record_path)) - if pending is not None: - typed.update(f.name for f in pending.schema if not _holds_null_type(f.type)) for field in untyped: - if field.name not in typed: + known = [ + given.field(given.get_field_index(field.name)).type + for given in (stored, pending.schema if pending is not None else None) + if given is not None and given.get_field_index(field.name) >= 0 + ] + paths = [_untyped_null_path(field.type, t, field.name) for t in known] + path = _untyped_null_path(field.type, None, field.name) + if paths: + path = next((p for p in paths if p is None), paths[0]) + if path is not None: raise UnstorableColumnError( database_kind=type(self).__name__, column=field.name, arrow_type=field.type, reason=( - "Delta has no null type, and no stored column gives this " - "all-null column a type" + f"Delta has no null type, and nothing stored gives {path!r} a " + "type" ), ) @@ -1931,6 +2173,16 @@ def _flush_by_key(self, record_key: str) -> None: "cannot hold. The stored rows are unchanged and nothing was " "written; rebuild the database." ) + # Delta's MERGE matches struct fields by position: the rows are given + # the stored struct layout by name first, so an evolved struct (fields + # reordered, omitted or added) keeps every value under its name; and a + # recorded column's record describes the column after this append + # (ITL-1334). + combined_table = _with_merged_records( + delta_table, + original_table, + _conformed_to_stored(delta_table, combined_table, table_uri), + ) base = self._snapshot_for_commit( record_key, delta_table, table_uri, abs_path_components ) @@ -2053,6 +2305,15 @@ def _stores_as_is(delta_table: deltalake.DeltaTable, batch: pa.Table) -> bool: except Exception: # A type Delta cannot store directly (null): leave it to the MERGE. return False + # A changed recorded type must reach the log: the MERGE writes it (ITL-1334). + stored_records = { + f.name: recorded_type(f.metadata) for f in delta_table.schema().fields + } + if any( + recorded_type(f.metadata) != stored_records.get(f.name) + for f in batch.schema + ): + return False return incoming.equals(_stored_arrow_schema(delta_table), check_metadata=False) @classmethod diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index b41e1397e..f60013de7 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -22,6 +22,7 @@ from collections.abc import Iterator from typing import TYPE_CHECKING, Any +from orcapod.databases.utils import is_direct_projection from orcapod.errors import UnstorableTableNameError from orcapod.types import ColumnInfo from orcapod.utils.lazy_module import LazyModule @@ -595,10 +596,14 @@ def iter_batches( infos[n].arrow_type if n in infos else _pa.large_string() for n in col_names ] - # A column created NOT NULL reads back non-null (ITL-1276). + # A column created NOT NULL reads back non-null (ITL-1276), only as a + # direct projection of its table (an outer join can give it nulls). + direct = is_direct_projection(query) schema = _pa.schema( [ - _pa.field(n, t, infos[n].nullable if n in infos else True) + _pa.field( + n, t, infos[n].nullable or not direct if n in infos else True + ) for n, t in zip(col_names, arrow_types) ] ) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 57a1a565f..8a55d425e 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1034,7 +1034,9 @@ def unstorable_column_reason( back as another type and is refused. It drops Arrow field metadata, so an extension (logical) type at any depth (``File``, ``Path``, ``UUID``, a user class, ``set[int]``, a NumPy array) would read back as its storage type and - is refused (ITL-1334; keeping it is a follow-up). + is refused (ITL-1334; keeping it is a follow-up). A map whose key or item + field has another name than ``key`` / ``value`` reads back with those names, + and is refused too. Args: name: The column's name. @@ -1063,6 +1065,10 @@ def unstorable_column_reason( "SpiralDB drops Arrow field metadata, so a logical (extension) type " "reads back as its storage type" ) + if arrow_utils.holds_renamed_map(arrow_type): + return ( + "SpiralDB gives a map's key and item fields back as 'key' and 'value'" + ) return None def unstorable_table_name_reason(self, table_name: str) -> str | None: diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index b462bb893..5f56aed8f 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -21,6 +21,7 @@ from collections.abc import Iterator from typing import TYPE_CHECKING, Any +from orcapod.databases.utils import is_direct_projection from orcapod.types import ColumnInfo if TYPE_CHECKING: @@ -140,6 +141,38 @@ def _sqlite_unstorable_reason(arrow_type: pa.DataType) -> str | None: return None +def _refuse_lost_floats(records: pa.Table) -> None: + """Refuse a ``double`` column holding a value SQLite does not keep (ITL-1334). + + SQLite stores a NaN as NULL and ``-0.0`` as ``0.0``, so a column holding either + would read back with other values; it is refused before anything is written. + + Args: + records: The rows about to be written. + + Raises: + UnstorableColumnError: For the first such column. + """ + import numpy as np # noqa: PLC0415 + + from orcapod.errors import UnstorableColumnError # noqa: PLC0415 + + for field in records.schema: + if not pa.types.is_floating(field.type): + continue + # Nulls dropped first: to_numpy would give them as NaN. + values = records.column(field.name).drop_null().to_numpy(zero_copy_only=False) + if values.dtype.kind != "f": + continue + if np.isnan(values).any() or (np.signbit(values) & (values == 0)).any(): + raise UnstorableColumnError( + database_kind="SQLiteConnector", + column=field.name, + arrow_type=field.type, + reason="SQLite reads a NaN back as NULL and -0.0 as 0.0", + ) + + def _coerce_column(values: list[Any], arrow_type: pa.DataType) -> list[Any]: """Coerce raw SQLite Python values to match the target Arrow type. @@ -349,9 +382,12 @@ def iter_batches( table_match = _re.search(r"FROM\s+(\w+)", query, _re.IGNORECASE) if table_match: queried_table = table_match.group(1) + # The stored NOT NULL holds for a column only as a direct projection + # of its table (an outer join can give it nulls). + direct = is_direct_projection(query) for ci in self.get_column_info(queried_table): type_lookup[ci.name] = ci.arrow_type - nullable_lookup[ci.name] = ci.nullable + nullable_lookup[ci.name] = ci.nullable or not direct # rowid is an implicit SQLite integer column; it does not appear in # PRAGMA table_info, so it would otherwise fall back to large_string. @@ -504,9 +540,12 @@ def validate_records(self, records: pa.Table) -> None: records: Arrow table to validate. Raises: + UnstorableColumnError: If a ``double`` column holds a NaN or ``-0.0``, + which SQLite reads back as NULL and ``0.0`` (ITL-1334). ValueError: If any field (or any nested child field) carries metadata, or if the schema itself carries metadata. """ + _refuse_lost_floats(records) problem_fields = [f.name for f in records.schema if _field_has_metadata(f)] has_schema_meta = bool(records.schema.metadata) if problem_fields or has_schema_meta: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 62c9b34a5..cb0789cfe 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -2,6 +2,7 @@ from __future__ import annotations +import re from typing import TYPE_CHECKING, cast if TYPE_CHECKING: @@ -53,3 +54,38 @@ def as_table_committing(database: object) -> TableCommittingDatabaseProtocol | N if not callable(flush_batch): return None return cast("TableCommittingDatabaseProtocol", database) + + +_IDENTIFIER = r'(?:"[^"]+"|\w+)' +_DIRECT_PROJECTION = re.compile( + rf"^\s*SELECT\s+(?:\*|{_IDENTIFIER}(?:\s*,\s*{_IDENTIFIER})*)\s+" + rf"FROM\s+{_IDENTIFIER}\s*(?P.*?)\s*;?\s*$", + re.IGNORECASE | re.DOTALL, +) +# After the table: nothing, or a clause that only chooses or orders rows. +_ROW_CLAUSE = re.compile(r"^(?:$|(?:WHERE|ORDER\s+BY|LIMIT|OFFSET)\b)", re.IGNORECASE) +_NOT_DIRECT = re.compile( + r"\b(?:JOIN|UNION|INTERSECT|EXCEPT|GROUP\s+BY|HAVING|SELECT)\b", re.IGNORECASE +) + + +def is_direct_projection(query: str) -> bool: + """Whether ``query`` gives rows of one table's columns unchanged (ITL-1334). + + That is ``SELECT *`` or a list of plain column names ``FROM`` one table, followed + by nothing but a ``WHERE``, ``ORDER BY``, ``LIMIT`` or ``OFFSET``. Only then does a + result column have the stored column's nullability: an outer join, an aggregate, + an expression or a union can give nulls in a column stored ``NOT NULL``. The test + is conservative: a query it does not recognize reads every column nullable. + + Args: + query: An SQL query. + + Returns: + Whether every result column is a stored column as it is stored. + """ + match = _DIRECT_PROJECTION.match(query) + if match is None: + return False + rest = match.group("rest") + return _ROW_CLAUSE.match(rest) is not None and _NOT_DIRECT.search(rest) is None diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 2021a2ec1..f2966c048 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -2187,3 +2187,30 @@ def _tag_order_by_polars(table: "pa.Table", keys: list[str]) -> "pa.Array[Any]": if __name__ == "__main__": test_schema_normalization() + + +def holds_renamed_map(arrow_type: "pa.DataType") -> bool: + """Whether ``arrow_type`` is or nests a map whose key or item field is not named + ``key`` / ``value``. + + Arrow IPC gives a map's key and item fields back under those names, so a store that + goes through IPC (SpiralDB, and Delta's recorded types) cannot keep other names; it + refuses such a column (ITL-1334). + + Args: + arrow_type: A column's Arrow type. + + Returns: + ``True`` for such a map at any depth of lists, structs, maps and extension + storage. + """ + if isinstance(arrow_type, pa.ExtensionType): + return holds_renamed_map(arrow_type.storage_type) + if pa.types.is_map(arrow_type) and ( + arrow_type.key_field.name != "key" or arrow_type.item_field.name != "value" + ): + return True + return any( + holds_renamed_map(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) diff --git a/tests/test_databases/test_delta_arrow_type_roundtrip.py b/tests/test_databases/test_delta_arrow_type_roundtrip.py index 81b4f9bf9..61e998369 100644 --- a/tests/test_databases/test_delta_arrow_type_roundtrip.py +++ b/tests/test_databases/test_delta_arrow_type_roundtrip.py @@ -84,6 +84,15 @@ pa.large_list(pa.list_(pa.uint8(), 3)), ), "fixed_size_binary[3]": pa.array([b"abc", None, b"\x00\x01\x02"], pa.binary(3)), + "fixed_size_list[0]": pa.array([[], None, []], pa.list_(pa.int16(), 0)), + "map, keys sorted": pa.array( + [[("a", 1), ("b", 2)], None, []], + pa.map_(pa.string(), pa.int64(), keys_sorted=True), # pyright: ignore[reportCallIssue] # the stubs lack keys_sorted + ), + "large_list": pa.array( + [[1], None, [2, None]], + pa.large_list(pa.field("named", pa.int16(), metadata={"unit": "m"})), + ), "large_list": pa.array( [[1], [], [2, 3]], pa.large_list(pa.field("item", pa.int64(), False)) ), diff --git a/tests/test_databases/test_delta_native_fs_read.py b/tests/test_databases/test_delta_native_fs_read.py index 9574fdeb5..99d60e75a 100644 --- a/tests/test_databases/test_delta_native_fs_read.py +++ b/tests/test_databases/test_delta_native_fs_read.py @@ -23,6 +23,7 @@ import orcapod as op from orcapod.databases import DeltaTableDatabase +from orcapod.databases.delta_arrow_types import from_delta_layout from orcapod.pipeline import AsyncPipelineOrchestrator, PipelineJob from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -139,7 +140,9 @@ def mixed(x: int) -> tuple[int | None, list[int]]: actual = fresh.get_all_records( record_path, record_id_column=DeltaTableDatabase.RECORD_ID_COLUMN ) - expected = _default_reader(table_dirs[record_path]) + # The default reader's rows with the recorded types restored, as Orcapod's + # read restores them (every list is recorded: ITL-1334). + expected = from_delta_layout(_default_reader(table_dirs[record_path])) assert actual is not None _assert_identical(actual, expected, sort_by=DeltaTableDatabase.RECORD_ID_COLUMN) compared += 1 diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py new file mode 100644 index 000000000..e09754047 --- /dev/null +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -0,0 +1,244 @@ +"""A struct appended with another field set keeps every value under its name (ITL-1334). + +Schema evolution is on by default: an append may add struct fields, omit some, or give +them in another order. Delta's MERGE matches struct fields by position, so the rows are +first given the stored struct layout by name (``_conformed_to_stored``), and a column +whose Arrow type is recorded has its record describe the merged column (``merged_type``), +which a read restores by name. Every read path, on a fresh database object, gives each +value under the name it was written with: never swapped, never dropped. + +A ``null``-typed part with nothing stored at its path (a new struct field, the items of a +new list) is refused naming the column and the path, before anything is buffered. +""" + +from __future__ import annotations + +import pathlib +import re +from collections.abc import Callable +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InputValidationError, UnstorableColumnError + +PATH = ("t",) + + +def _struct(*fields: tuple[str, Any]) -> pa.DataType: + return pa.struct([pa.field(name, arrow_type) for name, arrow_type in fields]) + + +def _rows(ids: list[bytes], **columns: tuple[list[Any], pa.DataType]) -> pa.Table: + return pa.table( + { + "id": pa.array(ids, pa.large_binary()), + **{n: pa.array(v, t) for n, (v, t) in columns.items()}, + } + ) + + +# Each read path, on a fresh database object: the rows of ids 1 and 2, in id order. +READS: dict[str, Callable[[DeltaTableDatabase], pa.Table | None]] = { + "get_all_records": lambda db: db.get_all_records(PATH, record_id_column="id"), + "get_records_by_ids": lambda db: db.get_records_by_ids( + PATH, [b"2", b"1"], record_id_column="id" + ), + "get_record_by_id": lambda db: pa.concat_tables( + [ + t + for t in ( + db.get_record_by_id(PATH, b"1", record_id_column="id"), + db.get_record_by_id(PATH, b"2", record_id_column="id"), + ) + if t is not None + ] + ), + "get_records_with_column_value": lambda db: db.get_records_with_column_value( + PATH, {"k": 7}, record_id_column="id" + ), +} + +F16, I64 = pa.float16(), pa.int64() + +# (first type, first values, appended type, appended values, expected values): +# recorded (float16, a fixed-size list) and unrecorded (int64) structs, at the top +# level and inside a list; two columns each. +CASES: dict[str, tuple[Any, list[Any], Any, list[Any], list[Any]]] = { + "reordered, recorded": ( + _struct(("a", F16), ("b", F16)), + [{"a": 1.0, "b": 2.0}], + _struct(("b", F16), ("a", F16)), + [{"b": 4.0, "a": 3.0}], + [{"a": 1.0, "b": 2.0}, {"a": 3.0, "b": 4.0}], + ), + "reordered, unrecorded": ( + _struct(("a", I64), ("b", I64)), + [{"a": 1, "b": 2}], + _struct(("b", I64), ("a", I64)), + [{"b": 4, "a": 3}], + [{"a": 1, "b": 2}, {"a": 3, "b": 4}], + ), + "omitted, recorded": ( + _struct(("a", F16), ("b", I64)), + [{"a": 1.0, "b": 2}], + _struct(("a", F16)), + [{"a": 3.0}], + [{"a": 1.0, "b": 2}, {"a": 3.0, "b": None}], + ), + "added, recorded": ( + _struct(("a", F16)), + [{"a": 1.0}], + _struct(("a", F16), ("c", pa.list_(pa.int16(), 2))), + [{"a": 3.0, "c": [5, 6]}], + [{"a": 1.0, "c": None}, {"a": 3.0, "c": [5, 6]}], + ), + "reordered and added, in a list": ( + pa.large_list(_struct(("a", pa.uint8()), ("b", I64))), + [[{"a": 1, "b": 2}]], + pa.large_list(_struct(("c", I64), ("b", I64), ("a", pa.uint8()))), + [[{"c": 9, "b": 4, "a": 3}]], + [[{"a": 1, "b": 2, "c": None}], [{"a": 3, "b": 4, "c": 9}]], + ), +} + + +@pytest.mark.parametrize("read", sorted(READS)) +@pytest.mark.parametrize("case", sorted(CASES)) +def test_an_evolved_struct_keeps_every_value_under_its_name( + tmp_path: pathlib.Path, case: str, read: str +) -> None: + first, first_values, appended, appended_values, expected = CASES[case] + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows( + [b"1"], + k=([7], pa.int64()), + x=(first_values, first), + y=(first_values, first), + ), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _rows( + [b"2"], + k=([7], pa.int64()), + y=(appended_values, appended), + x=(appended_values, appended), + ), + record_id_column="id", + flush=True, + ) + back = READS[read](DeltaTableDatabase(tmp_path)) + assert back is not None + back = back.sort_by("id") + for name in ("x", "y"): + assert back.column(name).to_pylist() == expected, name + + +def test_omitting_a_non_nullable_stored_field_is_refused( + tmp_path: pathlib.Path, +) -> None: + stored = pa.struct([pa.field("a", I64), pa.field("b", I64, nullable=False)]) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=([{"a": 1, "b": 2}], stored)), + record_id_column="id", + flush=True, + ) + with pytest.raises(InputValidationError, match="'x'.*'b'.*non-nullable"): + db.add_records( + PATH, + _rows([b"2"], x=([{"a": 3}], _struct(("a", I64)))), + record_id_column="id", + flush=True, + ) + + +@pytest.mark.parametrize( + ("stored", "stored_values", "incoming", "incoming_values", "path"), + [ + ( + _struct(("a", pa.int16())), + [{"a": 1}], + _struct(("a", pa.int16()), ("b", pa.null())), + [{"a": 2, "b": None}], + "x.b", + ), + ( + pa.large_list(_struct(("a", pa.int16()))), + [[{"a": 1}]], + pa.large_list(_struct(("a", pa.int16()), ("b", pa.null()))), + [[{"a": 2, "b": None}]], + "x[].b", + ), + ( + _struct(("a", pa.int16())), + [{"a": 1}], + _struct(("a", pa.int16()), ("l", pa.large_list(pa.null()))), + [{"a": 2, "l": [None]}], + "x.l[]", + ), + ], + ids=["new struct field", "new field in a list of structs", "items of a new list"], +) +def test_an_untyped_new_nested_null_part_is_refused_before_buffering( + tmp_path: pathlib.Path, + stored: Any, + stored_values: list[Any], + incoming: Any, + incoming_values: list[Any], + path: str, +) -> None: + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=(stored_values, stored)), + record_id_column="id", + flush=True, + ) + with pytest.raises(UnstorableColumnError, match=f"'x'.*'{re.escape(path)}'"): + db.add_records( + PATH, _rows([b"2"], x=(incoming_values, incoming)), record_id_column="id" + ) + db.flush() # nothing was buffered: the flush has nothing to fail on + back = db.get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.column("id").to_pylist() == [b"1"] + + +def test_a_null_value_at_a_typed_nested_path_appends(tmp_path: pathlib.Path) -> None: + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=([{"a": 1}], _struct(("a", pa.int16())))), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _rows([b"2"], x=([{"a": None}], _struct(("a", pa.null())))), + record_id_column="id", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").column("x").to_pylist() == [{"a": 1}, {"a": None}] + + +def test_a_map_with_renamed_fields_is_refused(tmp_path: pathlib.Path) -> None: + """The recorded type goes through Arrow IPC, which names them key and value.""" + renamed = pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes fields + pa.field("k", pa.string(), nullable=False), # pyright: ignore[reportArgumentType] + pa.field("v", I64), # pyright: ignore[reportArgumentType] + ) + with pytest.raises(UnstorableColumnError, match="'x'.*'key' and 'value'"): + DeltaTableDatabase(tmp_path).add_records( + PATH, _rows([b"1"], x=([[("a", 1)]], renamed)), record_id_column="id" + ) diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index ef0bc896b..900535e90 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -801,3 +801,34 @@ def test_iter_batches_reads_a_not_null_column_back_non_null() -> None: assert schema.field("required").nullable is False assert schema.field("optional").nullable is True assert batches[0].column("required").to_pylist() == [1, 2] + + +def test_iter_batches_reads_a_non_projected_column_nullable() -> None: + """Only a direct projection keeps the stored NOT NULL: an aggregate over one table + (whose column types are still looked up) reads nullable, since it can give nulls + (Codex review of PR 471). Unit level: no server.""" + from orcapod.types import ColumnInfo + + def batches_of(connector: PostgreSQLConnector, cursor: Any, query: str) -> Any: + cursor.fetchmany.side_effect = [[(None,)], []] + return list(connector.iter_batches(query)) + + with patch("psycopg.connect") as mock_connect: + mock_connect.return_value = MagicMock() + connector = PostgreSQLConnector("postgresql://localhost/test") + cursor = MagicMock() + cursor.description = [MagicMock()] + cursor.description[0].name = "required" + mock_connect.return_value.cursor.return_value = cursor + infos = [ColumnInfo(name="required", arrow_type=pa.int64(), nullable=False)] + with patch.object(PostgreSQLConnector, "get_column_info", return_value=infos): + direct = batches_of( + connector, cursor, 'SELECT "required" FROM "t" WHERE "required" > 0' + ) + aggregate = batches_of( + connector, cursor, 'SELECT max("required") AS "required" FROM "t"' + ) + connector._conn = None # skip actual close + assert direct[0].schema.field("required").nullable is False + assert aggregate[0].schema.field("required").type == pa.int64() + assert aggregate[0].schema.field("required").nullable is True diff --git a/tests/test_databases/test_sqlite_connector.py b/tests/test_databases/test_sqlite_connector.py index 1ce6ba693..d3ca2bcdd 100644 --- a/tests/test_databases/test_sqlite_connector.py +++ b/tests/test_databases/test_sqlite_connector.py @@ -588,3 +588,55 @@ def test_a_non_null_column_reads_back_non_null( assert back.schema.field("required").nullable is False assert back.schema.field("optional").nullable is True assert back.sort_by("id").column("required").to_pylist() == values + + +def test_an_outer_join_reads_a_not_null_column_nullable(tmp_path: Path) -> None: + """The stored NOT NULL holds only for a direct projection of the table: a LEFT JOIN + gives the right table's column nulls (Codex review of PR 471).""" + import sqlite3 + + path = str(tmp_path / "j.db") + with sqlite3.connect(path) as conn: + conn.execute("CREATE TABLE l (x INTEGER NOT NULL)") + conn.execute("CREATE TABLE r (x INTEGER NOT NULL)") + conn.executemany("INSERT INTO l VALUES (?)", [(1,), (2,)]) + conn.close() + connector = SQLiteConnector(path) + try: + (batch,) = connector.iter_batches("SELECT r.x FROM l LEFT JOIN r ON l.x = r.x") + assert batch.schema.field("x").nullable is True + assert batch.column("x").to_pylist() == [None, None] + (direct,) = connector.iter_batches('SELECT * FROM "l" WHERE x IN (1, 2)') + assert direct.schema.field("x").nullable is False + finally: + connector.close() + + +@pytest.mark.parametrize( + "values", [[float("nan"), 1.0], [1.0, -0.0]], ids=["NaN", "-0.0"] +) +def test_a_float_sqlite_does_not_keep_is_refused_naming_the_column( + tmp_path: Path, values: list[float] +) -> None: + """SQLite reads a NaN back as NULL and -0.0 as 0.0 (ITL-1334); a null is kept.""" + from orcapod.databases import ConnectorArrowDatabase + from orcapod.errors import UnstorableColumnError + + db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "f.db"))) + ids = pa.array([b"r1", b"r2"], pa.large_binary()) + with pytest.raises(UnstorableColumnError, match="'d'.*NaN"): + db.add_records( + ("t",), + pa.table({"id": ids, "d": pa.array(values, pa.float64())}), + record_id_column="id", + flush=True, + ) + db.add_records( + ("u",), + pa.table({"id": ids, "d": pa.array([1.5, None], pa.float64())}), + record_id_column="id", + flush=True, + ) + back = db.get_all_records(("u",), record_id_column="id") + assert back is not None + assert back.sort_by("id").column("d").to_pylist() == [1.5, None] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index e01aeb57e..ec1db7b12 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -102,15 +102,18 @@ class Row: def _plain( - arrow_type: pa.DataType, values: list[Any], nullable: bool = True + arrow_type: pa.DataType, + values: list[Any], + nullable: bool = True, + metadata: dict[str, str] | None = None, ) -> Callable[[Path], tuple[Any, Any, list[Any], list[Any]]]: """Two columns of ``arrow_type``; the second has a null in the middle if nullable.""" def build(_root: Path) -> tuple[Any, Any, list[Any], list[Any]]: second = [values[0], None, values[2]] if nullable else list(reversed(values)) return ( - pa.field("x", arrow_type, nullable=nullable), - pa.field("y", arrow_type, nullable=nullable), + pa.field("x", arrow_type, nullable=nullable, metadata=metadata), + pa.field("y", arrow_type, nullable=nullable, metadata=metadata), values, second, ) @@ -132,6 +135,7 @@ def build(root: Path) -> tuple[Any, Any, list[Any], list[Any]]: D = decimal.Decimal +_NAN = float("nan") _TS = [ dt.datetime(2026, 1, 1, 0, 0, 1), dt.datetime(2026, 1, 2), @@ -213,9 +217,10 @@ def _upaths(root: Path) -> list[Any]: Row(str(t), "integer", _plain(t, [1, 2, 200])) for t in (pa.uint8(), pa.uint16(), pa.uint32(), pa.uint64()) ), - Row("halffloat (float16)", "float", _plain(pa.float16(), [1.5, 2.0, 0.25])), - Row("float (float32)", "float", _plain(pa.float32(), [1.5, 2.0, 0.25])), - Row("double (float64)", "float", _plain(pa.float64(), [1.5, 2.0, 0.1])), + # -0.0 and NaN in both columns: values are compared bit for bit. + Row("halffloat (float16)", "float", _plain(pa.float16(), [-0.0, 2.0, _NAN])), + Row("float (float32)", "float", _plain(pa.float32(), [-0.0, 2.0, _NAN])), + Row("double (float64)", "float", _plain(pa.float64(), [-0.0, 0.1, _NAN])), Row( "decimal128(10, 2)", "decimal", @@ -353,6 +358,52 @@ def _upaths(root: Path) -> list[Any]: pa.map_(pa.string(), pa.int64()), [[("a", 1)], [], [("b", 2), ("c", None)]] ), ), + Row( + "fixed_size_list[0]", + "list", + _plain(pa.list_(pa.int16(), 0), [[], [], []]), + ), + Row( + "large_list", + "names and metadata", + _plain( + pa.large_list(pa.field("named", pa.int16(), metadata={"unit": "m"})), + [[1, 2], [], [3, None]], + ), + ), + Row( + "struct", + "names and metadata", + _plain( + pa.struct([pa.field("a", pa.int32(), metadata={"unit": "s"})]), + [{"a": 1}, {"a": None}, {"a": 3}], + ), + ), + Row( + "map, keys sorted", + "names and metadata", + _plain( + pa.map_(pa.string(), pa.int64(), keys_sorted=True), # pyright: ignore[reportCallIssue] # the stubs lack keys_sorted + [[("a", 1), ("b", 2)], [], [("c", None)]], + ), + ), + Row( + "map, keys sorted", + "names and metadata", + _plain( + pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields + pa.field("k", pa.string(), nullable=False), + pa.field("v", pa.int64()), + keys_sorted=True, + ), + [[("a", 1), ("b", 2)], [], [("c", None)]], + ), + ), + Row( + "int64 {unit: s} (field metadata)", + "names and metadata", + _plain(pa.int64(), [1, 2, 3], metadata={"unit": "s"}), + ), Row("int64 not null", "nullability", _plain(pa.int64(), [1, 2, 3], nullable=False)), Row( "string not null", @@ -536,31 +587,122 @@ def _expected_field(field: "pa.Field[Any]") -> "pa.Field[Any]": return field.with_type(normalize_to_large_types(field.type, keep_null=True)) -def _describe(field: "pa.Field[Any]") -> str: - nested = _nested_flags(field.type) - return f"{field.type}{'' if field.nullable else ' not null'}{nested}" +def _field_difference(a: "pa.Field[Any]", b: "pa.Field[Any]", path: str) -> str | None: + """The first difference between two fields, at any depth, or ``None``. + + Everything that makes a field counts: its name, nullability and metadata, and its + type's kind and parameters, with every child field compared the same way (a list's + item, a struct's children, a map's key and item and whether its keys are sorted). + Arrow's own type equality ignores child names and metadata, so it is not used. + """ + if a.name != b.name: + return f"{path}: name {a.name!r} -> {b.name!r}" + if a.nullable != b.nullable: + return f"{path}: nullable {a.nullable} -> {b.nullable}" + if dict(a.metadata or {}) != dict(b.metadata or {}): + return f"{path}: metadata {dict(a.metadata or {})} -> {dict(b.metadata or {})}" + return _type_difference(a.type, b.type, path) + + +def _type_difference(a: Any, b: Any, path: str) -> str | None: + t = pa.types + if isinstance(a, pa.ExtensionType) or isinstance(b, pa.ExtensionType): + if not ( + isinstance(a, pa.ExtensionType) + and isinstance(b, pa.ExtensionType) + and a.extension_name == b.extension_name + and a.__arrow_ext_serialize__() == b.__arrow_ext_serialize__() + ): + return f"{path}: {a} -> {b}" + return _type_difference(a.storage_type, b.storage_type, path) + kinds = ( + t.is_struct, + t.is_map, + t.is_fixed_size_list, + t.is_large_list, + t.is_list, + ) + kind_a = next((k for k in kinds if k(a)), None) + kind_b = next((k for k in kinds if k(b)), None) + if kind_a is not kind_b or (kind_a is None and a != b): + return f"{path}: {a} -> {b}" + if kind_a is None: + return None + if t.is_map(a): + if a.keys_sorted != b.keys_sorted: + return f"{path}: keys_sorted {a.keys_sorted} -> {b.keys_sorted}" + return _field_difference(a.key_field, b.key_field, f"{path}.key") or ( + _field_difference(a.item_field, b.item_field, f"{path}.item") + ) + if t.is_fixed_size_list(a) and a.list_size != b.list_size: + return f"{path}: list size {a.list_size} -> {b.list_size}" + if t.is_struct(a): + if a.num_fields != b.num_fields: + return f"{path}: {a} -> {b}" + for i in range(a.num_fields): + found = _field_difference( + a.field(i), b.field(i), f"{path}.{a.field(i).name}" + ) + if found: + return found + return None + return _field_difference(a.value_field, b.value_field, f"{path}[]") + +def _lengths(array: Any) -> list[int]: + """The item count of each non-null row of a list or map array (from its offsets: + pyarrow's ``list_value_length`` has no kernel for a map).""" + import numpy as np -def _nested_flags(arrow_type: pa.DataType) -> str: - """The non-null nested fields, which ``str(type)`` may not show.""" - flags = [] - for i in range(getattr(arrow_type, "num_fields", 0)): - child = arrow_type.field(i) - if not child.nullable: - flags.append(child.name) - inner = _nested_flags(child.type) - if inner: - flags.append(f"{child.name}{inner}") - return f" [non-null: {', '.join(flags)}]" if flags else "" + counts = np.diff(array.offsets.to_numpy(zero_copy_only=False)) + return counts[array.is_valid().to_numpy(zero_copy_only=False)].tolist() -def _same_field(a: "pa.Field[Any]", b: "pa.Field[Any]") -> bool: - return ( - a.name == b.name - and a.nullable == b.nullable - and a.type == b.type - and _nested_flags(a.type) == _nested_flags(b.type) +def _items(array: Any) -> list[Any]: + """The items of the non-null rows of a list or map array, in row order: the values + of a list, the keys and the items of a map (whose arrays have no ``flatten``).""" + import numpy as np + + offsets = array.offsets.to_numpy(zero_copy_only=False) + rows = np.flatnonzero(array.is_valid().to_numpy(zero_copy_only=False)) + indices = pa.array( + np.concatenate( + [np.arange(offsets[r], offsets[r + 1]) for r in rows] or [np.zeros(0)] + ).astype(np.int64) ) + if pa.types.is_map(array.type): + return [array.keys.take(indices), array.items.take(indices)] + return [array.values.take(indices)] + + +def _same_values(a: Any, b: Any) -> bool: + """Whether two arrays of one type hold the same values, bit for bit. + + Nulls must be in the same rows. A float is compared by its bits (``-0.0`` is not + ``0.0``, a NaN equals the same NaN); nested values are compared child by child, and + an extension array by its storage. + """ + if isinstance(a, pa.ChunkedArray): + a = a.combine_chunks() + if isinstance(b, pa.ChunkedArray): + b = b.combine_chunks() + if len(a) != len(b) or not a.is_null().equals(b.is_null()): + return False + t = pa.types + if isinstance(a.type, pa.ExtensionType): + return _same_values(a.storage, b.storage) + if t.is_floating(a.type): + bits = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[a.type.bit_width] + return a.view(bits).equals(b.view(bits)) + if t.is_struct(a.type): + return all(_same_values(x, y) for x, y in zip(a.flatten(), b.flatten())) + if t.is_list(a.type) or t.is_large_list(a.type) or t.is_map(a.type): + return _lengths(a) == _lengths(b) and all( + _same_values(x, y) for x, y in zip(_items(a), _items(b)) + ) + if t.is_fixed_size_list(a.type): + return _same_values(a.flatten(), b.flatten()) + return a.equals(b) def measure(row: Row, database: str, root: Path) -> Cell: @@ -588,6 +730,14 @@ def measure(row: Row, database: str, root: Path) -> Cell: db.add_records(path, written, record_id_column="id", flush=True) except Exception as exc: # noqa: BLE001 if _names_a_column(exc): + # A refusal writes nothing: the table still reads back empty. + try: + db.flush() + stored = db.get_all_records(path, record_id_column="id") + except Exception as read_exc: # noqa: BLE001 + return Cell(SILENT, f"refused, then unreadable: {read_exc}") + if stored is not None and stored.num_rows: + return Cell(SILENT, "refused, but rows were stored") return Cell(REFUSED, f"{type(exc).__name__}") return Cell( SILENT, @@ -607,17 +757,17 @@ def measure(row: Row, database: str, root: Path) -> Cell: exact = written.schema.field(name) got = back.schema.field(name) # The type written, or its large variant (every Orcapod table is large). - if _same_field(exact, got): - want = exact - else: + want = exact + difference = _field_difference(exact, got, name) + if difference is not None: want = _expected_field(exact) - if not _same_field(want, got): - problems.append(f"{name}: {_describe(exact)} -> {_describe(got)}") + if _field_difference(want, got, name) is not None: + problems.append(difference) continue expected = written.column(name) if want.type != exact.type: expected = expected.cast(want.type) - if not back.column(name).combine_chunks().equals(expected.combine_chunks()): + if not _same_values(back.column(name), expected): problems.append(f"{name}: values differ") if problems: return Cell(SILENT, "; ".join(problems)) @@ -661,24 +811,31 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: --> Each database Orcapod stores into keeps some Arrow types exactly and refuses the others. -None of them gives a column back as another type: a type a database cannot keep is -refused, with an error naming the column, before anything of the table is written. This -page lists every type for every database. It is generated from a test that writes and -reads each type through each database, so it cannot drift from the code. +For every type on this page, each database either gives the column back exactly or refuses +it, with an error naming the column, before anything of the table is written: none gives +it back as another type. The page is generated from a test that writes and reads each +type through each database, so it cannot drift from the code. The rows are +representative, not every Arrow type: dictionary-encoded columns are refused by every +stream before they reach a database, and union, run-end-encoded and list-view types are +not covered. What a cell says: -- **kept**: read back exactly, with its Arrow type (nested field names and nullability - included) and its values. Text, binary and list columns may come back in their large +- **kept**: read back exactly: the Arrow type with the name, nullability and metadata of + the column and of every nested field (a list's item, a struct's children, a map's key + and item, and whether its keys are sorted), and the values bit for bit (a float's + `-0.0` and NaN included). Text, binary and list columns may come back in their large variants (`large_string`, `large_binary`, `large_list`), the types every Orcapod table uses. -- **kept (recorded type)**: kept by `DeltaTableDatabase` through a recorded type. Delta Lake - has no column type for it, so the column's Arrow type is recorded in its field metadata, - its values are written in a form Delta keeps (an integer form, `float32` for - `float16`, a `large_list` for a fixed-size list) and the type is restored on read. +- **kept (recorded type)**: kept by `DeltaTableDatabase` through a recorded type. Delta + Lake has no column type for it, or gives it back changed (it names every list item + `element` and drops a map's sorted keys), so the column's Arrow type is recorded in its + field metadata, its values are written in a form Delta keeps (an integer form, + `float32` for `float16`, a `large_list` for a fixed-size list) and the type is restored + on read, nested fields matched by name. - **kept (by rule)**: PostgreSQL stores the column, by the connector's own rule. No PostgreSQL server is used to build this page, so this cell is the rule, not a measured - read. + read: it does not show that the server keeps every value (a NaN, a time zone). - **refused**: writing the column raises an error naming it (`UnstorableColumnError` for a connector database), and nothing of the table is written. @@ -695,15 +852,23 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: `SpiralDBConnector`. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. -Three refusals depend on the values as well as the type: +Some refusals depend on the values or names as well as the type: - SpiralDB cannot store a null struct, so a struct column with a null row is refused (the rows below have one); a struct column with no null row is kept. -- Delta has no `null` type: a new column holding only nulls with no type is refused (the - `null` row below), while a `null`-typed value is kept in a column the table already - stores with a type. +- SQLite reads a NaN back as NULL and `-0.0` as `0.0`, so a `double` column holding one + is refused (the float rows below hold both); one without them is kept. +- Delta has no `null` type: a new column, or a new nested field, holding only nulls with + no type is refused (the `null` row below), while a `null`-typed value is kept where the + table already stores a type. +- Delta and SpiralDB give a map's key and item fields back as `key` and `value`, so a map + with other names is refused. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. + +Appending to a Delta table may evolve a struct column (fields added, omitted or in +another order): every value keeps its field's name, and an omitted field reads as null +in the appended rows. """ From 5f7789cbcca753150aea7e1d72e8713bc1386cc2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 10:34:22 -0800 Subject: [PATCH 03/13] fix(databases): refuse appends a Delta column cannot take; append in the matrix Second Codex review of PR 471: - Adding a non-nullable struct field (at any depth: top level, in a large_list, a fixed-size list, deeper) committed a table Delta could not read back: refused before buffering, naming the column and the field. A new nullable field with a non-nullable child still appends (the stored rows read it as null). - An append changing what a recorded column states about a nested field (a list item's name or metadata, a struct child's metadata, a map's keys_sorted) was accepted and described with the stored attributes: refused before buffering, in both orders. A nested field with metadata now makes a column recorded, so its record carries it. - Adding a struct field inside a map failed at flush with an unnamed error: refused before buffering (Delta's merge cannot add it). - The matrix appends a second batch of the same type to every cell. It found that a fixed-size list with non-null items and a null row could not be appended to: on Delta the null row's hidden items reached the writer, which panicked (a null row is now written as an empty list, _to_stored); the SpiralDB fake cast the whole table (now only changed columns, as the connector does). - The append check runs only for rows with a nested column, and leaves a stored table that cannot be loaded to the flush to report. Refs ITL-1334 Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1334.md | 10 ++ docs/reference/database-types.md | 11 +- src/orcapod/databases/delta_arrow_types.py | 68 +++++++- src/orcapod/databases/delta_lake_databases.py | 162 ++++++++++++++++- tests/test_databases/fake_pyspiral.py | 11 +- .../test_delta_struct_evolution.py | 164 ++++++++++++++++++ tests/test_databases/type_matrix.py | 33 +++- 7 files changed, 442 insertions(+), 17 deletions(-) diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index 10c1d636c..93b826482 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -42,8 +42,18 @@ anything is written, as is a map whose key or item field is not named `key` / `value`. (ITL-1334) +- **An append to a `DeltaTableDatabase` table is refused when the column cannot take it:** + adding a non-nullable struct field (the stored rows have no value for it, and Delta + could not read the table back), adding a struct field inside a map (Delta's merge + cannot), or changing a list item's name or metadata, a struct child's metadata or a + map's sorted keys raises `InputValidationError` naming the column and the field, before + anything is buffered. (ITL-1334) + ### Fixed +- **A fixed-size list with non-null items and a null row can be appended to on Delta:** + the null row's hidden items reached Delta's writer, which panicked; a null row is now + written as an empty list. (ITL-1334) - **An append to a Delta table that evolves a struct keeps every value under its name:** Delta's MERGE matches struct fields by position, so rows appended with the fields in another order stored each value under another field's name. The rows are now given the diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 68fdfe368..19b3d0a7b 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -36,7 +36,8 @@ What a cell says: a connector database), and nothing of the table is written. How it is measured: a table holding two columns of the type (the second nullable, with a -null row) is written with `add_records`, flushed and read back with `get_all_records`. +null row) is written with `add_records` and flushed, a second batch of the same type is +appended, and both are read back with `get_all_records`. The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which models what SpiralDB does to a column (no SpiralDB is used). No database tells tag columns from data columns, so a type is kept or refused the same way in either role. @@ -64,7 +65,11 @@ Some refusals depend on the values or names as well as the type: Appending to a Delta table may evolve a struct column (fields added, omitted or in another order): every value keeps its field's name, and an omitted field reads as null -in the appended rows. +in the appended rows. An append is refused, naming the column and the field, before +anything is written, when it would add a non-nullable struct field (the stored rows have +no value for it), add a struct field inside a map (Delta cannot), or change what the +column states about a nested field: a list item's name or metadata, a struct child's +metadata, a map's sorted keys. ## Integer @@ -171,7 +176,7 @@ in the appended rows. | Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | |---|---|---|---|---|---| | `large_list` | kept | kept (recorded type) | refused | refused | kept | -| `struct` | kept | kept | refused | refused | refused | +| `struct` | kept | kept (recorded type) | refused | refused | refused | | `map, keys sorted` | kept | kept (recorded type) | refused | refused | kept | | `map, keys sorted` | kept | refused | refused | refused | refused | | `int64 {unit: s} (field metadata)` | kept | kept | refused | refused | kept | diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index 5663ff3c8..48522f4d2 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -146,9 +146,9 @@ def _is_recorded(arrow_type: pa.DataType) -> bool: It does when it has, at any depth, a part Delta would not give back: an unsigned integer, a timestamp in another unit than microseconds or with a zone other than - UTC, a ``date64``, ``time``, ``duration``, ``float16`` or fixed-size binary, or - any list or map: Delta names every list item ``element`` and drops its metadata, - and drops a map's ``keys_sorted`` (ITL-1334). + UTC, a ``date64``, ``time``, ``duration``, ``float16`` or fixed-size binary, any + list or map (Delta names every list item ``element`` and drops its metadata, and + drops a map's ``keys_sorted``), or a nested field with metadata (ITL-1334). """ t = pa.types if ( @@ -166,8 +166,11 @@ def _is_recorded(arrow_type: pa.DataType) -> bool: return True if t.is_timestamp(arrow_type): return arrow_type.unit != "us" or arrow_type.tz not in (None, "UTC") + # A nested field with metadata: the record states it for every row, so an append + # cannot silently restate it (ITL-1334). return any( - _is_recorded(arrow_type.field(i).type) for i in range(arrow_type.num_fields) + _is_recorded(arrow_type.field(i).type) or bool(arrow_type.field(i).metadata) + for i in range(arrow_type.num_fields) ) @@ -187,9 +190,12 @@ def to_delta_layout(table: pa.Table) -> pa.Table: continue metadata = dict(field.metadata or {}) metadata[ARROW_TYPE_KEY] = _serialize(field.type) - stored_type = _stored_form(field.type) - # An integer view of the same values: a wrap-around cast keeps the bits. - column = table.column(index).cast(stored_type, safe=False) + # Any: pyarrow's stubs type ``chunked_array``'s ``type`` too narrowly. + stored_type: Any = _stored_form(field.type) + column = pa.chunked_array( + [_to_stored(chunk, field.type) for chunk in table.column(index).chunks], + type=stored_type, + ) table = table.set_column( index, pa.field(field.name, stored_type, field.nullable, metadata), @@ -235,6 +241,54 @@ def from_delta_layout(table: pa.Table) -> pa.Table: return table +def _to_stored(array: Any, original: Any) -> Any: + """Return ``array``, of type ``original``, in the form it is written (``_stored_form``). + + A leaf is cast: an integer view of the same values (a wrap-around cast keeps the + bits), ``float16`` widened to ``float32``. A nested type is rebuilt around its + converted children, so a fixed-size list's null row becomes an empty list: the + items a null row hides (null under a non-nullable item field) never reach Delta, + whose writer panics on them (ITL-1334). + """ + t = pa.types + stored: Any = _stored_form(original) # dispatched on below, as pyarrow allows + if not _is_nested(original): + return array.cast(stored, safe=False) + mask = array.is_null() if array.null_count else None + if t.is_fixed_size_list(original): + valid = ~array.is_null().to_numpy(zero_copy_only=False) + lengths = np.where(valid, original.list_size, 0) + offsets = np.concatenate([[0], np.cumsum(lengths)]).astype(np.int64) + # flatten() gives the items of the non-null rows only, in row order. + return pa.LargeListArray.from_arrays( + pa.array(offsets, pa.int64()), + _to_stored(array.flatten(), original.value_type), + type=stored, + mask=mask, + ) + if t.is_struct(original): + children = [ + _to_stored(array.field(i), original.field(i).type) + for i in range(original.num_fields) + ] + return pa.StructArray.from_arrays(children, fields=list(stored), mask=mask) + if t.is_map(original): + return pa.MapArray.from_arrays( + array.offsets, + _to_stored(array.keys, original.key_type), + _to_stored(array.items, original.item_type), + type=cast(Any, stored), # pyarrow's stubs type ``type`` too narrowly + mask=mask, + ) + array_class = pa.LargeListArray if t.is_large_list(original) else pa.ListArray + return array_class.from_arrays( + array.offsets, + _to_stored(array.values, original.value_type), + type=stored, + mask=mask, + ) + + def _is_nested(arrow_type: pa.DataType) -> bool: """Whether ``arrow_type`` has child fields (a struct, a list of any kind, a map).""" return arrow_type.num_fields > 0 or pa.types.is_fixed_size_list(arrow_type) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index fe9e608f1..ef0673666 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -449,6 +449,103 @@ def _with_merged_records( return written +def _append_change( + stored: Any, incoming: Any, path: str, *, recorded: bool, in_map: bool = False +) -> str | None: + """Say why rows of ``incoming`` cannot be appended to a column of ``stored``. + + Walks both types by struct field NAME and through lists and maps (ITL-1334): + + - a struct field ``incoming`` adds may not be non-nullable (the stored rows have + no value for it), nor be inside a map (Delta's merge cannot add it); + - where the column is recorded, a list item's name and metadata, a struct child's + metadata and a map's ``keys_sorted`` must be the stored ones: the record states + them for every row. + + A type conflict and a ``null`` part are left to their own checks + (``_incompatible_append_column``, ``_untyped_null_path``). + + Args: + stored: The column's stored type (its record, else its stored type). + incoming: The appended rows' type, large-normalized. + path: Where in the column this is, for the reason. + recorded: Whether the column's type is recorded. + in_map: Whether ``path`` is inside a map. + + Returns: + The reason, or ``None`` when the rows can be appended. + """ + t = pa.types + if t.is_struct(stored) and t.is_struct(incoming): + known = {f.name: f for f in stored} + for field in incoming: + here = f"{path}.{field.name}" + if field.name not in known: + if in_map: + return f"{here} is a new struct field inside a map, which Delta cannot add" + if not field.nullable: + return ( + f"{here} is a new non-nullable struct field, which the stored " + "rows have no value for" + ) + continue + if recorded and dict(field.metadata or {}) != dict( + known[field.name].metadata or {} + ): + return f"{here} has other field metadata than the stored column" + found = _append_change( + known[field.name].type, + field.type, + here, + recorded=recorded, + in_map=in_map, + ) + if found is not None: + return found + return None + if t.is_map(stored) and t.is_map(incoming): + if recorded and stored.keys_sorted != incoming.keys_sorted: + return ( + f"{path} has keys_sorted={incoming.keys_sorted}, the stored column " + f"{stored.keys_sorted}" + ) + return _append_change( + stored.key_type, + incoming.key_type, + f"{path}.key", + recorded=recorded, + in_map=True, + ) or _append_change( + stored.item_type, + incoming.item_type, + f"{path}.item", + recorded=recorded, + in_map=True, + ) + lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) + if any(k(stored) for k in lists) and any(k(incoming) for k in lists): + # cast: the type guards above narrow ``stored`` in the stubs' terms. + stored_item = cast(Any, stored).value_field + incoming_item = incoming.value_field + if recorded and stored_item.name != incoming_item.name: + return ( + f"{path}[] is named {incoming_item.name!r}, the stored column's item " + f"{stored_item.name!r}" + ) + if recorded and dict(stored_item.metadata or {}) != dict( + incoming_item.metadata or {} + ): + return f"{path}[] has other field metadata than the stored column's item" + return _append_change( + stored_item.type, + incoming_item.type, + f"{path}[]", + recorded=recorded, + in_map=in_map, + ) + return None + + def _untyped_null_path(incoming: Any, given: Any, path: str) -> str | None: """The first path where ``incoming`` is ``null``-typed and ``given`` has no type. @@ -1317,6 +1414,64 @@ def require_storable(self, schema: pa.Schema) -> None: reason=reason, ) + def _refuse_unmergeable_append( + self, record_path: tuple[str, ...], schema: pa.Schema + ) -> None: + """Refuse rows the stored table cannot take without a changed or broken column. + + Checked against the stored table, before anything is buffered (ITL-1334), by + ``_append_change``: an append may evolve a struct (fields added, omitted or + reordered: ``_conformed_to_stored``), but not add a non-nullable field (the + stored rows have no value for it, and Delta then cannot read the table), not + add a struct field inside a map (Delta's merge cannot), and not change what a + recorded column states about its nested fields (a list item's name or metadata, + a struct child's metadata, a map's ``keys_sorted``), which the record would + otherwise state wrongly for one side's rows. + + Args: + record_path: The table the rows are for. + schema: The schema of the rows about to be added. + + Only rows with a nested column are checked, and a stored table that cannot be + loaded is left to the flush, which reports it (``OrcapodDatabaseReadError``). + + Raises: + InputValidationError: For the first such column, naming it and the path. + """ + if not any(f.type.num_fields for f in schema): + return + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + return + if delta_table is None: + return + stored = _stored_arrow_schema(delta_table) + records = { + f.name: recorded_type(f.metadata) for f in delta_table.schema().fields + } + for field in schema: + position = stored.get_field_index(field.name) + if position < 0 or isinstance(field.type, pa.ExtensionType): + continue + record = records.get(field.name) + stored_type = ( + record + if record is not None + else arrow_utils.normalize_to_large_types(stored.field(position).type) + ) + change = _append_change( + stored_type, + arrow_utils.normalize_to_large_types(field.type, keep_null=True), + field.name, + recorded=record is not None, + ) + if change is not None: + raise InputValidationError( + f"Cannot append to the stored table at {record_path!r}: column " + f"{field.name!r}: {change}. Nothing was written." + ) + def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1339,7 +1494,11 @@ def _refuse_untyped_null_columns( untyped = [f for f in schema if _holds_null_type(f.type)] if not untyped: return - delta_table = self._get_delta_table(record_path) + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + # A stored table that cannot be loaded is left to the flush to report. + return stored = _stored_arrow_schema(delta_table) if delta_table is not None else None pending = self._pending_batches.get(self._get_record_key(record_path)) for field in untyped: @@ -1411,6 +1570,7 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) self._refuse_untyped_null_columns(record_path, records.schema) + self._refuse_unmergeable_append(record_path, records.schema) # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index d34caab80..df5572209 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -613,7 +613,16 @@ def write( raise ValueError( "fake SpiralDB: column set differs from existing table" ) - incoming = incoming.cast(existing.schema) + # Column by column, only where the type changes: pyarrow refuses to cast a + # fixed-size list with non-null items to its own type when a null row + # hides null item slots (ITL-1334). + incoming = pa.Table.from_arrays( + [ + column if column.type == field.type else column.cast(field.type) + for column, field in zip(incoming.columns, existing.schema) + ], + schema=existing.schema, + ) if not keys.names: incoming = pa.concat_tables([existing, incoming]) else: diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index e09754047..433222254 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -242,3 +242,167 @@ def test_a_map_with_renamed_fields_is_refused(tmp_path: pathlib.Path) -> None: DeltaTableDatabase(tmp_path).add_records( PATH, _rows([b"1"], x=([[("a", 1)]], renamed)), record_id_column="id" ) + + +# --------------------------------------------------------------------------- +# Appends the stored column cannot take: refused before buffering (ITL-1334) +# --------------------------------------------------------------------------- + + +def _new_non_null(inner: Any) -> Any: + """``struct`` wrapped by ``inner``.""" + return inner(pa.struct([pa.field("a", F16), pa.field("b", F16, nullable=False)])) + + +def _old(inner: Any) -> Any: + return inner(_struct(("a", F16))) + + +_WRAPPERS: dict[str, tuple[Any, Any, Any]] = { + # name: (wrap a type, wrap an old value, wrap a new value) + "top level": (lambda t: t, lambda v: v, lambda v: v), + "in a large_list": (pa.large_list, lambda v: [v], lambda v: [v]), + "in a fixed_size_list": ( + lambda t: pa.list_(t, 1), + lambda v: [v], + lambda v: [v], + ), + "in large_list>": ( + lambda t: pa.large_list(pa.struct([pa.field("s", pa.list_(t, 1))])), + lambda v: [{"s": [v]}], + lambda v: [{"s": [v]}], + ), +} + + +def _assert_refused_and_nothing_pending( + tmp_path: pathlib.Path, first: pa.Table, second: pa.Table, match: str +) -> None: + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, first, record_id_column="id", flush=True) + with pytest.raises(InputValidationError, match=match): + db.add_records(PATH, second, record_id_column="id") + db.flush() # nothing was buffered: the flush has nothing to fail on + for reader in (db, DeltaTableDatabase(tmp_path)): + back = reader.get_all_records(PATH, record_id_column="id") + assert back is not None + # Values, not types: a read gives text in its large variant. + assert back.sort_by("id").to_pylist() == first.sort_by("id").to_pylist() + + +@pytest.mark.parametrize("where", sorted(_WRAPPERS)) +def test_adding_a_non_nullable_struct_field_is_refused( + tmp_path: pathlib.Path, where: str +) -> None: + """The stored rows have no value for it, and Delta could not read the table back.""" + wrap_type, wrap_old, wrap_new = _WRAPPERS[where] + first = _rows( + [b"1", b"2"], + x=([wrap_old({"a": 1.0}), wrap_old({"a": 2.0})], _old(wrap_type)), + y=([wrap_old({"a": 1.0}), wrap_old({"a": 2.0})], _old(wrap_type)), + ) + new = [wrap_new({"a": 3.0, "b": 4.0}), wrap_new({"a": 5.0, "b": 6.0})] + second = _rows( + [b"3", b"4"], + x=(new, _new_non_null(wrap_type)), + y=(new, _new_non_null(wrap_type)), + ) + _assert_refused_and_nothing_pending( + tmp_path, first, second, "'x'.*new non-nullable struct field" + ) + + +def test_adding_a_nullable_field_with_a_non_nullable_child_appends( + tmp_path: pathlib.Path, +) -> None: + """The stored rows read the new field as null, so its child needs no value.""" + added = pa.struct( + [pa.field("a", F16), pa.field("b", pa.struct([pa.field("c", F16, False)]))] + ) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=([{"a": 1.0}], _struct(("a", F16)))), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _rows([b"2"], x=([{"a": 2.0, "b": {"c": 3.0}}], added)), + record_id_column="id", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").column("x").to_pylist() == [ + {"a": 1.0, "b": None}, + {"a": 2.0, "b": {"c": 3.0}}, + ] + + +def _named(name: str, unit: str = "m") -> Any: + return pa.large_list(pa.field(name, I64, metadata={"unit": unit})) + + +def _child(unit: str) -> Any: + return pa.struct([pa.field("a", I64, metadata={"unit": unit})]) + + +# (first type, appended type, first value, appended value, reason): each change is +# tested in both orders. +_ATTRIBUTE_CHANGES: dict[str, tuple[Any, Any, Any, Any, str]] = { + "list item name": (_named("itemA"), _named("itemB"), [1], [2], "is named"), + "list item metadata": ( + _named("item", "m"), + _named("item", "s"), + [1], + [2], + "metadata", + ), + "struct child metadata": (_child("m"), _child("s"), {"a": 1}, {"a": 2}, "metadata"), + "map keys_sorted": ( + pa.map_(pa.string(), I64, keys_sorted=True), # pyright: ignore[reportCallIssue] # the stubs lack keys_sorted + pa.map_(pa.string(), I64, keys_sorted=False), # pyright: ignore[reportCallIssue] # the stubs lack keys_sorted + [("a", 1), ("z", 2)], + [("a", 3), ("b", 4)], + "keys_sorted", + ), +} + + +@pytest.mark.parametrize("order", ["forward", "reversed"]) +@pytest.mark.parametrize("change", sorted(_ATTRIBUTE_CHANGES)) +def test_an_append_changing_a_recorded_nested_attribute_is_refused( + tmp_path: pathlib.Path, change: str, order: str +) -> None: + """The record states these for every row: an append may not silently restate the + appended rows' (a sorted-keys flag over unsorted keys would be a false type).""" + first_type, second_type, first_value, second_value, reason = _ATTRIBUTE_CHANGES[ + change + ] + if order == "reversed": + first_type, second_type = second_type, first_type + first = _rows([b"1"], x=([first_value], first_type), y=([first_value], first_type)) + second = _rows( + [b"2"], x=([second_value], second_type), y=([second_value], second_type) + ) + _assert_refused_and_nothing_pending(tmp_path, first, second, f"'x'.*{reason}") + + +def test_adding_a_struct_field_inside_a_map_is_refused(tmp_path: pathlib.Path) -> None: + """Delta's merge cannot add it: refused by column before buffering, not at flush.""" + old = pa.map_(pa.large_string(), _struct(("a", F16))) + new = pa.map_(pa.large_string(), _struct(("a", F16), ("b", F16))) + first = _rows( + [b"1", b"2"], + x=([[("k", {"a": 1.0})], [("k", {"a": 2.0})]], old), + y=([[("k", {"a": 1.0})], [("k", {"a": 2.0})]], old), + ) + second = _rows( + [b"3", b"4"], + x=([[("k", {"a": 3.0, "b": 4.0})], [("k", {"a": 5.0, "b": None})]], new), + y=([[("k", {"a": 3.0, "b": 4.0})], [("k", {"a": 5.0, "b": None})]], new), + ) + _assert_refused_and_nothing_pending( + tmp_path, first, second, "'x'.*inside a map, which Delta cannot add" + ) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index ec1db7b12..85b5781cc 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -2,9 +2,11 @@ Every row is a column type, every column a database. A cell is measured, never declared: a table holding two columns of the type (the second with a null when the type is -nullable) is written with ``add_records``, flushed and read back with -``get_all_records``, then compared with what was written, up to the large variants every -Orcapod table uses (``arrow_utils.normalize_to_large_types``). The outcome is one of: +nullable) is written with ``add_records`` and flushed, a second batch of the same type is +appended, and both are read back with ``get_all_records``, then compared exactly with what +was written (every nested field's name, nullability and metadata, a map's +``keys_sorted``, values bit for bit), up to the large variants every Orcapod table uses +(``arrow_utils.normalize_to_large_types``). The outcome is one of: - ``KEPT``: read back equal, type (with nested nullability) and values. - ``KEPT VIA RECORDED TYPE``: read back equal through Delta's recorded-type mechanism @@ -743,6 +745,22 @@ def measure(row: Row, database: str, root: Path) -> Cell: SILENT, f"write failed without naming the column: {type(exc).__name__}: {str(exc)[:160]}", ) + # A second batch of the same type appended: the stored type must take it, and + # both batches read back exactly (on Delta, through the merged record). + appended = written.set_column( + 0, + written.schema.field("id"), + pa.array([b"s1", b"s2", b"s3"], pa.large_binary()), + ) + try: + db.add_records(path, appended, record_id_column="id", flush=True) + except Exception as exc: # noqa: BLE001 + return Cell( + SILENT, + f"first write kept, the same type appended failed: " + f"{type(exc).__name__}: {str(exc)[:160]}", + ) + written = pa.concat_tables([written, appended]) try: back = db.get_all_records(path, record_id_column="id") except Exception as exc: # noqa: BLE001 @@ -840,7 +858,8 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: a connector database), and nothing of the table is written. How it is measured: a table holding two columns of the type (the second nullable, with a -null row) is written with `add_records`, flushed and read back with `get_all_records`. +null row) is written with `add_records` and flushed, a second batch of the same type is +appended, and both are read back with `get_all_records`. The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which models what SpiralDB does to a column (no SpiralDB is used). No database tells tag columns from data columns, so a type is kept or refused the same way in either role. @@ -868,7 +887,11 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: Appending to a Delta table may evolve a struct column (fields added, omitted or in another order): every value keeps its field's name, and an omitted field reads as null -in the appended rows. +in the appended rows. An append is refused, naming the column and the field, before +anything is written, when it would add a non-nullable struct field (the stored rows have +no value for it), add a struct field inside a map (Delta cannot), or change what the +column states about a nested field: a list item's name or metadata, a struct child's +metadata, a map's sorted keys. """ From 25cd947a3538a61eb4998f8fe83ec7a883042ac9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 13:56:42 -0800 Subject: [PATCH 04/13] fix(databases): every database refuses an append with other field attributes; sliced rows write Third Codex review of PR 471 (ITL-1334). - Delta: a null list or map row at a nonzero slice offset failed the flush and stayed pending (Arrow takes no validity mask over sliced offsets). One helper, delta_arrow_types.rebased_offsets, is used by every list and map rebuild. - One comparison of the field tree, databases/utils.appended_field_change: the column's own field metadata and, at every depth, each nested field's name and metadata (struct children by name, list item, map key and item) and a map's keys_sorted. Applied before buffering, against the stored table and a pending batch, by Delta (recorded or not; a logical column's own metadata), the in-memory database and the connector database (stored schema read without rows through get_arrow_schema where the connector offers it). In-memory kept the first batch's metadata and SpiralDB the latest batch's for every row. - Nullability stays with each database's own rule (ITL-842); Delta's merged record marks a nested field nullable when either side is. - SpiralDB refuses a map whose key or item field has metadata, which its metadata record never kept. - Delta: an append adding a column went through a MERGE that dropped the other list columns' recorded type and a logical list's extension name (pre-existing); the MERGE source keeps each field's metadata. - The matrix appends sliced batches and attribute-changed batches to every cell; 0 of 405 cells silent (211 on the previous head). Two map-metadata rows added. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1334.md | 27 +- docs/reference/database-types.md | 28 +- .../databases/connector_arrow_database.py | 69 ++++- src/orcapod/databases/delta_arrow_types.py | 74 ++++-- src/orcapod/databases/delta_lake_databases.py | 243 ++++++++++-------- src/orcapod/databases/in_memory_databases.py | 23 +- src/orcapod/databases/spiraldb_connector.py | 27 ++ src/orcapod/databases/utils.py | 114 +++++++- .../data_tags/test_database_capability.py | 20 +- .../test_function_node_arrow_types.py | 7 +- .../test_appended_field_attributes.py | 169 ++++++++++++ .../test_delta_sliced_appends.py | 111 ++++++++ .../test_delta_struct_evolution.py | 50 ++++ tests/test_databases/type_matrix.py | 176 ++++++++++--- 14 files changed, 957 insertions(+), 181 deletions(-) create mode 100644 tests/test_databases/test_appended_field_attributes.py create mode 100644 tests/test_databases/test_delta_sliced_appends.py diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index 93b826482..bebcae391 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -42,12 +42,22 @@ anything is written, as is a map whose key or item field is not named `key` / `value`. (ITL-1334) +- **An append whose field attributes differ from the held column is refused, by every + database:** a table holds one type per column, so rows appended with other field + metadata (the column's own, or a struct child's, a list item's, a map key's or item's), + another nested field name or another `keys_sorted` than the stored rows or a pending + batch raise `InputValidationError` naming the column and the field, before anything is + buffered. `InMemoryArrowDatabase` used to give the appended rows the first batch's + metadata, the SpiralDB connector gave every row the latest batch's, and Delta kept the + stored metadata, whether or not the column's type was recorded. Nullability is left to + each database's own rule. (ITL-1334) - **An append to a `DeltaTableDatabase` table is refused when the column cannot take it:** adding a non-nullable struct field (the stored rows have no value for it, and Delta - could not read the table back), adding a struct field inside a map (Delta's merge - cannot), or changing a list item's name or metadata, a struct child's metadata or a - map's sorted keys raises `InputValidationError` naming the column and the field, before - anything is buffered. (ITL-1334) + could not read the table back) or a struct field inside a map (Delta's merge cannot) + raises `InputValidationError` naming the column and the field, before anything is + buffered. A nested field an append makes nullable reads back nullable. (ITL-1334) +- **`SpiralDBConnector` refuses a map whose key or item field has metadata:** its metadata + record does not cover a map's fields, so the metadata read back dropped. (ITL-1334) ### Fixed @@ -61,6 +71,15 @@ field is refused), and a recorded column's record describes the merged column. (ITL-1334) +- **A Delta append of rows sliced from a larger table writes:** a null list or map row + at a nonzero slice offset failed the flush ("Null bitmap with offsets slice not + supported") and stayed pending; every list and map Delta rebuilds now rebases its + offsets. (ITL-1334) +- **An append that adds a column to a Delta table keeps the other columns' types:** the + MERGE it goes through wrote each list column's field metadata from the rows, without + the recorded type or a logical column's extension name, so afterwards a list read back + with its item named `element`, and a logical list (`set[int]`, `list[Path]`) as its + plain storage type. (ITL-1334) - **`SpiralDBConnector` reads back a fixed-size list with non-null items and a null row:** the read cast every column to the restored schema, and pyarrow refuses that cast when a null row hides null item slots; only columns whose type changes are cast now. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 19b3d0a7b..b16380a4f 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -36,8 +36,11 @@ What a cell says: a connector database), and nothing of the table is written. How it is measured: a table holding two columns of the type (the second nullable, with a -null row) is written with `add_records` and flushed, a second batch of the same type is -appended, and both are read back with `get_all_records`. +null row) is written with `add_records` and flushed. The same type is then appended as +slices of a larger table (three rows over two chunks, then the null row alone), and the +same columns with other field metadata (the column's own, and a nested field's) are +appended, which every database must refuse, naming the column. Every batch written is read +back with `get_all_records`. The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which models what SpiralDB does to a column (no SpiralDB is used). No database tells tag columns from data columns, so a type is kept or refused the same way in either role. @@ -59,17 +62,24 @@ Some refusals depend on the values or names as well as the type: no type is refused (the `null` row below), while a `null`-typed value is kept where the table already stores a type. - Delta and SpiralDB give a map's key and item fields back as `key` and `value`, so a map - with other names is refused. + with other names is refused. SpiralDB does not keep metadata on a map's key or item + field, so a map with such metadata is refused there. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. +A table holds one type per column. An append whose columns differ from the held ones +(stored, or still pending) in field metadata (the column's own, or a nested field's: a +struct child, a list item, a map key or item), in a nested field's name, or in whether a +map's keys are sorted is refused by every database, naming the column and the field, +before anything is written: either side's rows would otherwise read back with the other +side's attributes. A change of nullability is left to each database's own rule. + Appending to a Delta table may evolve a struct column (fields added, omitted or in another order): every value keeps its field's name, and an omitted field reads as null -in the appended rows. An append is refused, naming the column and the field, before -anything is written, when it would add a non-nullable struct field (the stored rows have -no value for it), add a struct field inside a map (Delta cannot), or change what the -column states about a nested field: a list item's name or metadata, a struct child's -metadata, a map's sorted keys. +in the appended rows. An append is refused, naming the column and the field, when it +would add a non-nullable struct field (the stored rows have no value for it) or add a +struct field inside a map (Delta cannot). A nested field the append makes nullable reads +as nullable afterwards, as Delta stores it. ## Integer @@ -179,6 +189,8 @@ metadata, a map's sorted keys. | `struct` | kept | kept (recorded type) | refused | refused | refused | | `map, keys sorted` | kept | kept (recorded type) | refused | refused | kept | | `map, keys sorted` | kept | refused | refused | refused | refused | +| `map (item metadata)` | kept | kept (recorded type) | refused | refused | refused | +| `map (key metadata)` | kept | kept (recorded type) | refused | refused | refused | | `int64 {unit: s} (field metadata)` | kept | kept | refused | refused | kept | ## Nullability diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 205a108ac..e17ebeada 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -23,8 +23,15 @@ from collections.abc import Collection, Mapping from typing import TYPE_CHECKING, Any, cast -from orcapod.databases.utils import coerce_record_id -from orcapod.errors import UnstorableColumnError, UnstorableTableNameError +from orcapod.databases.utils import ( + coerce_record_id, + first_changed_column, +) +from orcapod.errors import ( + InputValidationError, + UnstorableColumnError, + UnstorableTableNameError, +) from orcapod.utils.arrow_utils import ( normalize_schema_to_large_types, normalize_table_to_large_types, @@ -90,6 +97,9 @@ def __init__( if _shared_pending_record_ids is not None else defaultdict(set) ) + # The schema each stored table was read with, for the append check + # (``_refuse_changed_columns``). + self._stored_schemas: dict[str, pa.Schema] = {} # Per-batch flag: True when the batch was added with skip_duplicates=True, # so flush() can pass skip_existing=True to the connector and let it use # native INSERT-OR-IGNORE semantics rather than Python-side prefiltering. @@ -397,8 +407,10 @@ def add_records( records = normalize_table_to_large_types(records, keep_null=True) self._connector.validate_records(records) - records = self._deduplicate_within_table(records) record_key = self._get_record_key(record_path) + self._refuse_changed_columns(record_path, records.schema) + + records = self._deduplicate_within_table(records) input_ids = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) if skip_duplicates: @@ -442,6 +454,57 @@ def add_records( if flush: self.flush() + def _refuse_changed_columns( + self, record_path: tuple[str, ...], schema: pa.Schema + ) -> None: + """Refuse rows whose columns would not read back as written (ITL-1334). + + The table holds one type per column, so an appended column must have the held + column's field metadata and nested field attributes (``appended_field_change``), + held by the stored table and by a batch pending for it: otherwise one side's + rows would read back with the other's. A connector that keeps no field + metadata refuses metadata and nested types itself, so only one that keeps it + is checked. The stored table's schema is read once per table + (``_read_stored_schema``): an append the check accepts does not change it. + + Raises: + InputValidationError: For the first such column, naming it and the path. + """ + if not self.keeps_field_metadata: + return + held: list[pa.Schema] = [] + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + held.append(pending.schema) + table_name = self._path_to_table_name(self._path_prefix + record_path) + stored = self._stored_schemas.get(table_name) + if stored is None and table_name in self._connector.get_table_names(): + stored = self._read_stored_schema(table_name) + if stored is not None: + self._stored_schemas[table_name] = stored + if stored is not None: + held.append(stored) + changed = first_changed_column(held, schema) + if changed is not None: + raise InputValidationError( + f"Cannot append to the table at {record_path!r}: column " + f"{changed[0]!r}: {changed[1]}. Nothing was written." + ) + + def _read_stored_schema(self, table_name: str) -> pa.Schema | None: + """The schema a read of the stored table gives, its field metadata included. + + Read without rows from a connector that offers ``get_arrow_schema`` + (``SpiralDBConnector``); from any other, the schema of its first batch. + """ + get_arrow_schema = getattr(self._connector, "get_arrow_schema", None) + if callable(get_arrow_schema): + return cast("pa.Schema", get_arrow_schema(table_name)) + first = next( + iter(self._connector.iter_batches(f'SELECT * FROM "{table_name}"')), None + ) + return None if first is None else first.schema + # ── base_path / at ──────────────────────────────────────────────────────── @property diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index 48522f4d2..87d054117 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -272,23 +272,47 @@ def _to_stored(array: Any, original: Any) -> Any: for i in range(original.num_fields) ] return pa.StructArray.from_arrays(children, fields=list(stored), mask=mask) + offsets, start, length = rebased_offsets(array) if t.is_map(original): return pa.MapArray.from_arrays( - array.offsets, - _to_stored(array.keys, original.key_type), - _to_stored(array.items, original.item_type), + offsets, + _to_stored(array.keys.slice(start, length), original.key_type), + _to_stored(array.items.slice(start, length), original.item_type), type=cast(Any, stored), # pyarrow's stubs type ``type`` too narrowly mask=mask, ) array_class = pa.LargeListArray if t.is_large_list(original) else pa.ListArray return array_class.from_arrays( - array.offsets, - _to_stored(array.values, original.value_type), + offsets, + _to_stored(array.values.slice(start, length), original.value_type), type=stored, mask=mask, ) +def rebased_offsets(array: Any) -> tuple[Any, int, int]: + """Return a list or map array's offsets from zero, and the child rows they index. + + The offsets of a sliced array start where its first row's items do, and Arrow's + ``from_arrays`` constructors take no validity mask over such offsets ("Null bitmap + with offsets slice not supported"). Rebased offsets over the child sliced to the + returned span index the same items, so a rebuilt array keeps every row, null or + not, of the slice (ITL-1334). + + Args: + array: A list, large list or map array, possibly sliced. + + Returns: + The offsets as a new array starting at zero, of the array's offset type; the + position of the first child row; the number of child rows. + """ + offsets = array.offsets + values = offsets.to_numpy(zero_copy_only=False) + start = int(values[0]) if len(values) else 0 + stop = int(values[-1]) if len(values) else 0 + return pa.array(values - start, offsets.type), start, stop - start + + def _is_nested(arrow_type: pa.DataType) -> bool: """Whether ``arrow_type`` has child fields (a struct, a list of any kind, a map).""" return arrow_type.num_fields > 0 or pa.types.is_fixed_size_list(arrow_type) @@ -337,19 +361,20 @@ def _restore(array: Any, target: Any) -> Any: _restore(array.field(stored[field.name]), field.type) for field in target ] return pa.StructArray.from_arrays(children, fields=list(target), mask=mask) + offsets, start, length = rebased_offsets(array) if t.is_map(target): return pa.MapArray.from_arrays( - array.offsets, - _restore(array.keys, target.key_type), - _restore(array.items, target.item_type), + offsets, + _restore(array.keys.slice(start, length), target.key_type), + _restore(array.items.slice(start, length), target.item_type), type=cast(Any, target), # pyarrow's stubs type ``type`` too narrowly mask=mask, ) large = t.is_large_list(target) array_class = pa.LargeListArray if large else pa.ListArray return array_class.from_arrays( - array.offsets.cast(pa.int64() if large else pa.int32()), - _restore(array.values, target.value_type), + offsets.cast(pa.int64() if large else pa.int32()), + _restore(array.values.slice(start, length), target.value_type), type=target, mask=mask, ) @@ -469,8 +494,9 @@ def merged_type(stored: pa.DataType, incoming: pa.DataType) -> pa.DataType: and adds the new ones, so the merged struct has the stored fields, in their order, each merged with the incoming field of the same name, then the incoming fields the stored struct does not have. Lists, fixed-size lists and maps merge their items. - Any other type is the stored one: the append check (``_types_conflict``) has - already refused an incoming type that changes it. + A nested field is nullable when either side's is (``_merged_field``). Any other + type is the stored one: the append check (``_types_conflict``) has already refused + an incoming type that changes it. Args: stored: The column's type as stored (its recorded type, else its stored type). @@ -484,7 +510,7 @@ def merged_type(stored: pa.DataType, incoming: pa.DataType) -> pa.DataType: incoming_fields = {field.name: field for field in incoming} stored_names = {field.name for field in stored} fields = [ - field.with_type(merged_type(field.type, incoming_fields[field.name].type)) + _merged_field(field, incoming_fields[field.name]) if field.name in incoming_fields else field for field in stored @@ -492,10 +518,8 @@ def merged_type(stored: pa.DataType, incoming: pa.DataType) -> pa.DataType: return pa.struct(fields) if t.is_map(stored) and t.is_map(incoming): return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields - stored.key_field.with_type(merged_type(stored.key_type, incoming.key_type)), - stored.item_field.with_type( - merged_type(stored.item_type, incoming.item_type) - ), + _merged_field(stored.key_field, incoming.key_field), + _merged_field(stored.item_field, incoming.item_field), keys_sorted=stored.keys_sorted, ) if ( @@ -507,9 +531,7 @@ def merged_type(stored: pa.DataType, incoming: pa.DataType) -> pa.DataType: and stored.list_size == incoming.list_size ) ): - value_field = stored.value_field.with_type( - merged_type(stored.value_type, incoming.value_type) - ) + value_field = _merged_field(stored.value_field, incoming.value_field) if t.is_large_list(stored): return pa.large_list(value_field) if t.is_list(stored): @@ -518,6 +540,18 @@ def merged_type(stored: pa.DataType, incoming: pa.DataType) -> pa.DataType: return stored +def _merged_field( + stored: "pa.Field[Any]", incoming: "pa.Field[Any]" +) -> "pa.Field[Any]": + """A nested field once rows of ``incoming`` are appended where ``stored`` is held: + the stored field (its name and metadata, which the append check requires the rows + to share), of the merged type, nullable when either side is: Delta relaxes a + nested field so, and a record claiming non-null over appended nulls would be + false (whether such an append is refused belongs to ITL-842).""" + merged = stored.with_type(merged_type(stored.type, incoming.type)) + return merged.with_nullable(stored.nullable or incoming.nullable) + + def with_recorded_type( field: "pa.Field[Any]", arrow_type: pa.DataType ) -> "pa.Field[Any]": diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index ef0673666..31013eb54 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -16,7 +16,11 @@ matching_rows, rows_at, ) -from orcapod.databases.utils import coerce_record_id +from orcapod.databases.utils import ( + appended_field_change, + coerce_record_id, + metadata_bytes, +) from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, @@ -25,9 +29,11 @@ UnstorableColumnError, ) from orcapod.databases.delta_arrow_types import ( + ARROW_TYPE_KEY, first_column_out_of_stored_range, from_delta_layout, merged_type, + rebased_offsets, recorded_type, to_delta_layout, with_recorded_type, @@ -359,10 +365,11 @@ def _conformed_array(array: Any, stored: Any) -> Any: children.append(array.field(i)) return pa.StructArray.from_arrays(children, fields=fields, mask=mask) if t.is_map(array.type) and t.is_map(stored): - keys = _conformed_array(array.keys, stored.key_type) - items = _conformed_array(array.items, stored.item_type) + offsets, start, length = rebased_offsets(array) + keys = _conformed_array(array.keys.slice(start, length), stored.key_type) + items = _conformed_array(array.items.slice(start, length), stored.item_type) return pa.MapArray.from_arrays( - array.offsets, + offsets, keys, items, type=cast( @@ -381,7 +388,10 @@ def _conformed_array(array: Any, stored: Any) -> Any: if any(k(array.type) for k in lists) and any(k(stored) for k in lists): # cast: the type guards above narrow the types in the stubs' terms. list_type: Any = array.type - values = _conformed_array(array.values, cast(Any, stored).value_type) + offsets, start, length = rebased_offsets(array) + values = _conformed_array( + array.values.slice(start, length), cast(Any, stored).value_type + ) if values.type == list_type.value_type and _struct_orders(values.type) == ( _struct_orders(list_type.value_type) ): @@ -389,10 +399,10 @@ def _conformed_array(array: Any, stored: Any) -> Any: value_field = list_type.value_field.with_type(values.type) if t.is_large_list(array.type): return pa.LargeListArray.from_arrays( - array.offsets, values, type=pa.large_list(value_field), mask=mask + offsets, values, type=pa.large_list(value_field), mask=mask ) return pa.ListArray.from_arrays( - array.offsets, values, type=pa.list_(value_field), mask=mask + offsets, values, type=pa.list_(value_field), mask=mask ) return array @@ -449,31 +459,45 @@ def _with_merged_records( return written -def _append_change( - stored: Any, incoming: Any, path: str, *, recorded: bool, in_map: bool = False -) -> str | None: - """Say why rows of ``incoming`` cannot be appended to a column of ``stored``. +_EXTENSION_KEYS = (b"ARROW:extension:name", b"ARROW:extension:metadata") + + +def _metadata(metadata: Mapping[Any, Any] | None) -> dict[bytes, bytes]: + """A field's own metadata as bytes: without the record a Delta column carries + (``ARROW_TYPE_KEY``) and the extension name and metadata Delta keeps for a logical + column (they are its type).""" + as_bytes = metadata_bytes(metadata) + for key in (ARROW_TYPE_KEY, *_EXTENSION_KEYS): + as_bytes.pop(key, None) + return as_bytes - Walks both types by struct field NAME and through lists and maps (ITL-1334): - - a struct field ``incoming`` adds may not be non-nullable (the stored rows have - no value for it), nor be inside a map (Delta's merge cannot add it); - - where the column is recorded, a list item's name and metadata, a struct child's - metadata and a map's ``keys_sorted`` must be the stored ones: the record states - them for every row. +def _is_logical(field: "pa.Field[Any]") -> bool: + """Whether ``field`` is a logical (extension) column: as given, or as Delta stores + it (its storage type, with the extension name in its metadata).""" + return isinstance(field.type, pa.ExtensionType) or ( + _EXTENSION_KEYS[0] in metadata_bytes(field.metadata) + ) + - A type conflict and a ``null`` part are left to their own checks - (``_incompatible_append_column``, ``_untyped_null_path``). +def _added_field_change( + stored: Any, incoming: Any, path: str, *, in_map: bool = False +) -> str | None: + """Say why a struct field ``incoming`` adds cannot be appended (ITL-1334). + + Walks both types by struct field NAME and through lists and maps: a struct field + ``incoming`` adds may not be non-nullable (the stored rows have no value for it, + and Delta then cannot read the table), nor be inside a map (Delta's merge cannot + add it). A field it omits is filled with nulls (``_conformed_to_stored``). Args: - stored: The column's stored type (its record, else its stored type). + stored: The type the table holds, large-normalized. incoming: The appended rows' type, large-normalized. path: Where in the column this is, for the reason. - recorded: Whether the column's type is recorded. in_map: Whether ``path`` is inside a map. Returns: - The reason, or ``None`` when the rows can be appended. + The reason, or ``None``. """ t = pa.types if t.is_struct(stored) and t.is_struct(incoming): @@ -489,58 +513,25 @@ def _append_change( "rows have no value for" ) continue - if recorded and dict(field.metadata or {}) != dict( - known[field.name].metadata or {} - ): - return f"{here} has other field metadata than the stored column" - found = _append_change( - known[field.name].type, - field.type, - here, - recorded=recorded, - in_map=in_map, + found = _added_field_change( + known[field.name].type, field.type, here, in_map=in_map ) if found is not None: return found return None if t.is_map(stored) and t.is_map(incoming): - if recorded and stored.keys_sorted != incoming.keys_sorted: - return ( - f"{path} has keys_sorted={incoming.keys_sorted}, the stored column " - f"{stored.keys_sorted}" - ) - return _append_change( - stored.key_type, - incoming.key_type, - f"{path}.key", - recorded=recorded, - in_map=True, - ) or _append_change( - stored.item_type, - incoming.item_type, - f"{path}.item", - recorded=recorded, - in_map=True, + return _added_field_change( + stored.key_type, incoming.key_type, f"{path}.key", in_map=True + ) or _added_field_change( + stored.item_type, incoming.item_type, f"{path}.item", in_map=True ) lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) if any(k(stored) for k in lists) and any(k(incoming) for k in lists): # cast: the type guards above narrow ``stored`` in the stubs' terms. - stored_item = cast(Any, stored).value_field - incoming_item = incoming.value_field - if recorded and stored_item.name != incoming_item.name: - return ( - f"{path}[] is named {incoming_item.name!r}, the stored column's item " - f"{stored_item.name!r}" - ) - if recorded and dict(stored_item.metadata or {}) != dict( - incoming_item.metadata or {} - ): - return f"{path}[] has other field metadata than the stored column's item" - return _append_change( - stored_item.type, - incoming_item.type, + return _added_field_change( + cast(Any, stored).value_type, + incoming.value_type, f"{path}[]", - recorded=recorded, in_map=in_map, ) return None @@ -642,9 +633,10 @@ def _merge_source_in_stored_layout( Delta stores ``large_list`` as ``list``, and the MERGE cannot plan a ``CASE WHEN`` over the two (ITL-984). A list column, a logical list included, is therefore handed to the MERGE as its storage type cast to - the stored type. The values are unchanged and the stored field metadata stays - as it is; every other column, and a list column the table does not have yet, - is passed as it is. + the stored type. The values are unchanged, and the field keeps its metadata (the + recorded type, a logical column's extension name and metadata), which a MERGE + that evolves the schema writes to the table; every other column, and a list + column the table does not have yet, is passed as it is. Args: delta_table: The loaded stored table. @@ -671,9 +663,21 @@ def _merge_source_in_stored_layout( # More than the layout differs (a timestamp unit, a width, an evolved # struct): the MERGE decides, and no cast may change a value. continue + # The field keeps its metadata: a MERGE that evolves the schema takes each + # field's metadata from the source, so a dropped record or extension name + # would be dropped from the table (ITL-1334). + metadata = dict(field.metadata or {}) + if isinstance(field.type, pa.ExtensionType): + metadata[b"ARROW:extension:name"] = field.type.extension_name.encode() + metadata[b"ARROW:extension:metadata"] = field.type.__arrow_ext_serialize__() batch = batch.set_column( index, - pa.field(field.name, target, nullable=field.nullable), + pa.field( + field.name, + target, + nullable=field.nullable, + metadata=cast(Any, metadata) or None, + ), pa.chunked_array([plain]).cast(target) if isinstance(plain, pa.Array) else plain.cast(target), @@ -1417,60 +1421,87 @@ def require_storable(self, schema: pa.Schema) -> None: def _refuse_unmergeable_append( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: - """Refuse rows the stored table cannot take without a changed or broken column. + """Refuse rows that would not read back as written, or would break the table. - Checked against the stored table, before anything is buffered (ITL-1334), by - ``_append_change``: an append may evolve a struct (fields added, omitted or + Checked before anything is buffered (ITL-1334), against what the table holds + for each column: the stored table (a column's record, else its stored type and + field metadata) and a batch pending for it. A column's field metadata (beside + its record) and its whole nested field tree must be the held ones + (``appended_field_change``, ``_added_field_change``): an append may evolve a struct (fields added, omitted or reordered: ``_conformed_to_stored``), but not add a non-nullable field (the stored rows have no value for it, and Delta then cannot read the table), not - add a struct field inside a map (Delta's merge cannot), and not change what a - recorded column states about its nested fields (a list item's name or metadata, - a struct child's metadata, a map's ``keys_sorted``), which the record would - otherwise state wrongly for one side's rows. + add a struct field inside a map (Delta's merge cannot), and not change a nested + field's name, nullability or metadata, or a map's ``keys_sorted``: the table + holds one type per column, so either side's rows would read back with the + other's. A column's own nullability and type are left to the append check. Args: record_path: The table the rows are for. schema: The schema of the rows about to be added. - Only rows with a nested column are checked, and a stored table that cannot be - loaded is left to the flush, which reports it (``OrcapodDatabaseReadError``). + A stored table that cannot be loaded is left to the flush, which reports it + (``OrcapodDatabaseReadError``). Raises: InputValidationError: For the first such column, naming it and the path. """ - if not any(f.type.num_fields for f in schema): - return + held: list[dict[str, pa.Field[Any]]] = [] + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + held.append({f.name: f for f in pending.schema}) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: - return - if delta_table is None: - return - stored = _stored_arrow_schema(delta_table) - records = { - f.name: recorded_type(f.metadata) for f in delta_table.schema().fields - } - for field in schema: - position = stored.get_field_index(field.name) - if position < 0 or isinstance(field.type, pa.ExtensionType): - continue - record = records.get(field.name) - stored_type = ( - record - if record is not None - else arrow_utils.normalize_to_large_types(stored.field(position).type) - ) - change = _append_change( - stored_type, - arrow_utils.normalize_to_large_types(field.type, keep_null=True), - field.name, - recorded=record is not None, - ) - if change is not None: - raise InputValidationError( - f"Cannot append to the stored table at {record_path!r}: column " - f"{field.name!r}: {change}. Nothing was written." + delta_table = None + if delta_table is not None: + stored = _stored_arrow_schema(delta_table) + fields: dict[str, pa.Field[Any]] = {} + for delta_field in delta_table.schema().fields: + record = recorded_type(delta_field.metadata) + arrow_type = ( + record + if record is not None + else stored.field(stored.get_field_index(delta_field.name)).type ) + fields[delta_field.name] = pa.field( + delta_field.name, + arrow_type, + metadata=cast(Any, metadata_bytes(delta_field.metadata)) or None, + ) + held.append(fields) + for field in schema: + incoming = arrow_utils.normalize_to_large_types(field.type, keep_null=True) + for given in held: + if field.name not in given: + continue + held_field = given[field.name] + if _is_logical(field) or _is_logical(held_field): + # A logical column's type is its extension's, which the append + # check compares; its own field metadata is compared here. + change = ( + None + if _metadata(held_field.metadata) == _metadata(field.metadata) + else f"{field.name} has other field metadata than the stored " + "column" + ) + else: + change = appended_field_change( + held_field.with_metadata( + cast(Any, _metadata(held_field.metadata)) + ), + field.with_metadata(cast(Any, _metadata(field.metadata))), + ) or _added_field_change( + arrow_utils.normalize_to_large_types( + held_field.type, keep_null=True + ), + incoming, + field.name, + ) + if change is not None: + raise InputValidationError( + f"Cannot append to the stored table at {record_path!r}: column " + f"{field.name!r}: {change}. Nothing was written." + ) def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 7857c96fd..92fca521a 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -6,7 +6,8 @@ from typing import TYPE_CHECKING, Any, cast from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows -from orcapod.databases.utils import coerce_record_id +from orcapod.databases.utils import coerce_record_id, first_changed_column +from orcapod.errors import InputValidationError from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -252,11 +253,27 @@ def add_records( f"got {rid_type}. Encode the column to bytes before calling add_records()." ) + record_key = self._get_record_key(record_path) + # The table holds one type per column: rows whose field metadata or nested + # field attributes differ would read back with the held ones (ITL-1334). + held = [ + table.schema + for table in ( + self._tables.get(record_key), + self._pending_batches.get(record_key), + ) + if table is not None + ] + changed = first_changed_column(held, records.schema) + if changed is not None: + raise InputValidationError( + f"Cannot append to the table at {record_path!r}: column " + f"{changed[0]!r}: {changed[1]}. Nothing was written." + ) + # Deduplicate within the incoming batch (keep last) records = self._deduplicate_within_table(records) - record_key = self._get_record_key(record_path) - if skip_duplicates: records = self._filter_existing_records(record_key, records) if records.num_rows == 0: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 8a55d425e..576eed26f 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -414,6 +414,28 @@ def _holds_extension_type(arrow_type: pa.DataType) -> bool: ) +def _holds_map_field_metadata(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` is or nests a map whose key or item field has metadata. + + The connector's metadata record (``_serialize_field_meta_tree``) does not cover a + map's key and item fields, so such metadata would read back dropped (ITL-1334). + + Args: + arrow_type: The column's Arrow type. + + Returns: + ``True`` for such a map at any depth of lists, structs and maps. + """ + if pa.types.is_map(arrow_type) and ( + arrow_type.key_field.metadata or arrow_type.item_field.metadata + ): + return True + return any( + _holds_map_field_metadata(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + class SpiralDBConnector: """DBConnectorProtocol implementation backed by SpiralDB (pyspiral). @@ -1069,6 +1091,11 @@ def unstorable_column_reason( return ( "SpiralDB gives a map's key and item fields back as 'key' and 'value'" ) + if _holds_map_field_metadata(arrow_type): + return ( + "the connector does not keep the field metadata of a map's key and " + "item, so it would read back without it" + ) return None def unstorable_table_name_reason(self, table_name: str) -> str | None: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index cb0789cfe..8cd9f0018 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -3,10 +3,18 @@ from __future__ import annotations import re -from typing import TYPE_CHECKING, cast +from collections.abc import Iterable, Mapping +from typing import TYPE_CHECKING, Any, cast + +from orcapod.utils import arrow_utils +from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: + import pyarrow as pa + from orcapod.protocols.database_protocols import TableCommittingDatabaseProtocol +else: + pa = LazyModule("pyarrow") def coerce_record_id(record_id: str | bytes) -> bytes: @@ -89,3 +97,107 @@ def is_direct_projection(query: str) -> bool: return False rest = match.group("rest") return _ROW_CLAUSE.match(rest) is not None and _NOT_DIRECT.search(rest) is None + + +def metadata_bytes(metadata: Mapping[Any, Any] | None) -> dict[bytes, bytes]: + """Field metadata as bytes keys and values (pyarrow gives bytes, a Delta log text).""" + return { + (k.encode() if isinstance(k, str) else k): ( + v.encode() if isinstance(v, str) else v + ) + for k, v in (metadata or {}).items() + } + + +def appended_field_change( + held: "pa.Field[Any]", incoming: "pa.Field[Any]" +) -> str | None: + """Say why rows of ``incoming`` would not read back as written, appended to a + column a database holds as ``held`` (ITL-1334). + + A table holds one type per column, so an appended column must have the held + column's field metadata and, at every depth, each nested field's name and metadata + (a struct's children, matched by name; a list's item; a map's key and item) and a + map's ``keys_sorted``: otherwise one side's rows read back with the other side's + attributes. A struct field on one side only, and a difference in a type's kind or + parameters, are left to the database's own append rule (struct evolution, a type + conflict). Nullability, at any depth, is too: whether a nullability change is + refused belongs to the nullability audit (ITL-842). + + Args: + held: The column as the database holds it (stored or pending). + incoming: The column of the rows to append. + + Returns: + The reason, naming the path (``x``, ``x.a``, ``x[]``, ``x.key``), or ``None``. + """ + if metadata_bytes(held.metadata) != metadata_bytes(incoming.metadata): + return f"{incoming.name} has other field metadata than the stored column" + return _nested_change( + arrow_utils.normalize_to_large_types(held.type, keep_null=True), + arrow_utils.normalize_to_large_types(incoming.type, keep_null=True), + incoming.name, + ) + + +def _child_change( + held: "pa.Field[Any]", incoming: "pa.Field[Any]", path: str +) -> str | None: + if held.name != incoming.name: + return f"{path} is named {incoming.name!r}, the stored column's {held.name!r}" + if metadata_bytes(held.metadata) != metadata_bytes(incoming.metadata): + return f"{path} has other field metadata than the stored column" + return _nested_change(held.type, incoming.type, path) + + +def _nested_change(held: Any, incoming: Any, path: str) -> str | None: + t = pa.types + if t.is_struct(held) and t.is_struct(incoming): + known = {f.name: f for f in held} + for field in incoming: + if field.name in known: + found = _child_change(known[field.name], field, f"{path}.{field.name}") + if found is not None: + return found + return None + if t.is_map(held) and t.is_map(incoming): + if held.keys_sorted != incoming.keys_sorted: + return ( + f"{path} has keys_sorted={incoming.keys_sorted}, the stored column " + f"{held.keys_sorted}" + ) + return _child_change( + held.key_field, incoming.key_field, f"{path}.key" + ) or _child_change(held.item_field, incoming.item_field, f"{path}.item") + lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) + if any(k(held) for k in lists) and any(k(incoming) for k in lists): + # cast: the type guards above narrow the types in the stubs' terms. + return _child_change( + cast(Any, held).value_field, cast(Any, incoming).value_field, f"{path}[]" + ) + return None + + +def first_changed_column( + held: "Iterable[pa.Schema]", schema: "pa.Schema" +) -> tuple[str, str] | None: + """The first column of ``schema`` whose rows would not read back as written, + appended where a database holds the tables ``held`` (``appended_field_change``). + + Args: + held: The schemas the database holds for the table (stored, pending). + schema: The schema of the rows to append. + + Returns: + The column's name and the reason, or ``None``. + """ + held = list(held) + for field in schema: + for given in held: + index = given.get_field_index(field.name) + if index < 0: + continue + reason = appended_field_change(given.field(index), field) + if reason is not None: + return field.name, reason + return None diff --git a/tests/test_core/data_tags/test_database_capability.py b/tests/test_core/data_tags/test_database_capability.py index 76bad73fe..e33adaf88 100644 --- a/tests/test_core/data_tags/test_database_capability.py +++ b/tests/test_core/data_tags/test_database_capability.py @@ -324,7 +324,8 @@ def failing_set_metadata(self: Any, metadata: dict[str, bytes]) -> None: def test_spiraldb_write_of_stored_rows_keeps_the_stored_metadata(spiral: None) -> None: - """A write that stores no row never replaces a metadata entry already stored.""" + """A write with other field metadata never replaces a metadata entry already stored: + it is refused, naming the column, even when every row is already stored (ITL-1334).""" db = ConnectorArrowDatabase(SpiralDBConnector("p")) path = ("node", "table") db.add_records(path, _rows([1, 2]), record_id_column="rid", flush=True) @@ -340,21 +341,28 @@ def test_spiraldb_write_of_stored_rows_keeps_the_stored_metadata(spiral: None) - ] ) ) - db.add_records( - path, other, record_id_column="rid", skip_duplicates=True, flush=True - ) + with pytest.raises(InputValidationError, match="'unit'"): + db.add_records( + path, other, record_id_column="rid", skip_duplicates=True, flush=True + ) + db.flush() table = ConnectorArrowDatabase(SpiralDBConnector("p")).get_all_records(path) assert table is not None and stored_data_tags(table.schema) == ("unit",) def test_spiraldb_marks_no_stored_row_it_skips(spiral: None) -> None: - """Rows stored unmarked stay unmarked when the same ids are written marked.""" + """Rows stored unmarked stay unmarked when the same ids are written marked: the + write is refused, naming the column (ITL-1334).""" db = ConnectorArrowDatabase(SpiralDBConnector("p")) path = ("node", "table") rows = _rows([1, 2]) unmarked = rows.cast(pa.schema([field.remove_metadata() for field in rows.schema])) db.add_records(path, unmarked, record_id_column="rid", flush=True) - db.add_records(path, rows, record_id_column="rid", skip_duplicates=True, flush=True) + with pytest.raises(InputValidationError, match="'unit'"): + db.add_records( + path, rows, record_id_column="rid", skip_duplicates=True, flush=True + ) + db.flush() table = ConnectorArrowDatabase(SpiralDBConnector("p")).get_all_records(path) assert table is not None and stored_data_tags(table.schema) == () diff --git a/tests/test_core/function_pod/test_function_node_arrow_types.py b/tests/test_core/function_pod/test_function_node_arrow_types.py index 6886d8715..3dc4e70e8 100644 --- a/tests/test_core/function_pod/test_function_node_arrow_types.py +++ b/tests/test_core/function_pod/test_function_node_arrow_types.py @@ -268,7 +268,10 @@ def test_store_read_back_keeps_tag_type( def _as_written_before_the_fix(root: pathlib.Path) -> None: """Rewrite every Delta table under ``root`` as a build before ITL-928 left it. - Such a build stored a ``uint32`` column as Delta's ``int32`` with no recorded type. + Such a build stored a ``uint32`` column as Delta's ``int32`` with no recorded type: + the record is removed from the tag ``k`` only. (Every other column keeps its record: + an append to a list column stored without one is refused, ITL-1334, which is not + what this test is about.) """ import deltalake @@ -281,6 +284,8 @@ def _as_written_before_the_fix(root: pathlib.Path) -> None: f.with_metadata( {k: v for k, v in (f.metadata or {}).items() if k != ARROW_TYPE_KEY} ) + if f.name == "k" + else f for f in table.schema ] deltalake.write_deltalake( diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py new file mode 100644 index 000000000..c8a230910 --- /dev/null +++ b/tests/test_databases/test_appended_field_attributes.py @@ -0,0 +1,169 @@ +"""An append whose field attributes differ from the held column is refused (ITL-1334). + +A table holds one type per column. Rows appended with other field metadata (the +column's own, or a nested field's: a struct child, a list item, a map key or item), +another nested field name or another ``keys_sorted`` would read back with the held +column's attributes, or the held rows with theirs. Every database that keeps such +attributes (in-memory, Delta, SpiralDB) refuses the append before anything is buffered, +naming the column and the path, against the stored table and against a batch still +pending; the held rows read back unchanged. Nullability is left out: whether a +nullability change is refused belongs to the nullability audit (ITL-842). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.errors import InputValidationError, UnstorableColumnError +from tests.test_databases.type_matrix import map_of_fields, open_database + +PATH = ("t",) +I64 = pa.int64() +DATABASES = ("in-memory", "Delta", "SpiralDB") + + +def _meta(unit: str | None) -> dict[str, str] | None: + return None if unit is None else {"unit": unit} + + +def _column(unit: str | None) -> Any: + """The column ``x`` itself carries the metadata.""" + return pa.field("x", I64, metadata=_meta(unit)) + + +def _struct_child(unit: str | None) -> Any: + return pa.field("x", pa.struct([pa.field("a", I64, metadata=_meta(unit))])) + + +def _list_item(unit: str | None) -> Any: + return pa.field("x", pa.large_list(pa.field("item", I64, metadata=_meta(unit)))) + + +def _map_key(unit: str | None) -> Any: + key = pa.field("key", pa.large_string(), nullable=False, metadata=_meta(unit)) + return pa.field("x", map_of_fields(key, pa.field("value", I64))) + + +def _map_item(unit: str | None) -> Any: + key = pa.field("key", pa.large_string(), nullable=False) + return pa.field( + "x", map_of_fields(key, pa.field("value", I64, metadata=_meta(unit))) + ) + + +# (field builder, the path the refusal names, values of the first and second batch) +WHERE: dict[str, tuple[Any, str, list[Any], list[Any]]] = { + "column": (_column, "x has", [1, 2], [3, 4]), + "struct child": ( + _struct_child, + "x.a has", + [{"a": 1}, {"a": 2}], + [{"a": 3}, {"a": 4}], + ), + "list item": (_list_item, r"x\[\] has", [[1], [2, 3]], [[4], [5, 6]]), + "map key": ( + _map_key, + "x.key has", + [[("k", 1)], [("l", 2)]], + [[("m", 3)], [("n", 4)]], + ), + "map item": ( + _map_item, + "x.item has", + [[("k", 1)], [("l", 2)]], + [[("m", 3)], [("n", 4)]], + ), +} + +# (first metadata, appended metadata): absent to present, present to absent, A to B and +# B to A. +CHANGES = { + "absent -> present": (None, "m"), + "present -> absent": ("m", None), + "m -> s": ("m", "s"), + "s -> m": ("s", "m"), +} + + +def _refuses_the_type(database: str, where: str, unit: str | None) -> bool: + """SpiralDB refuses metadata on a map's key or item field: its connector would + not keep it (``spiraldb_connector._holds_map_field_metadata``).""" + return database == "SpiralDB" and where.startswith("map") and unit is not None + + +def _rows(ids: list[bytes], field: Any, values: list[Any]) -> pa.Table: + """Two columns, ``x`` and ``y``, of ``field``'s type, attributes and values.""" + array = pa.array(values, field.type) + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), array, array], + schema=pa.schema( + [pa.field("id", pa.large_binary()), field, field.with_name("y")] + ), + ) + + +def _values(table: pa.Table | None) -> list[dict[str, Any]]: + assert table is not None + return table.sort_by("id").select(["id", "x", "y"]).to_pylist() + + +@pytest.mark.parametrize("pending", [False, True], ids=["stored", "pending"]) +@pytest.mark.parametrize("change", sorted(CHANGES)) +@pytest.mark.parametrize("where", sorted(WHERE)) +@pytest.mark.parametrize("database", DATABASES) +def test_an_append_with_other_field_attributes_is_refused( + tmp_path: Path, database: str, where: str, change: str, pending: bool +) -> None: + build, path, first_values, second_values = WHERE[where] + first_unit, second_unit = CHANGES[change] + first = _rows([b"1", b"2"], build(first_unit), first_values) + second = _rows([b"3", b"4"], build(second_unit), second_values) + with open_database(database, tmp_path) as db: + if _refuses_the_type(database, where, first_unit): + with pytest.raises(UnstorableColumnError, match="'x'"): + db.add_records(PATH, first, record_id_column="id", flush=not pending) + return + db.add_records(PATH, first, record_id_column="id", flush=not pending) + if _refuses_the_type(database, where, second_unit): + with pytest.raises(UnstorableColumnError, match="'x'"): + db.add_records(PATH, second, record_id_column="id") + else: + with pytest.raises(InputValidationError, match=f"'x': {path}"): + db.add_records(PATH, second, record_id_column="id") + db.flush() # nothing of the refused rows was buffered + back = db.get_all_records(PATH, record_id_column="id") + assert _values(back) == _values(first) + assert back is not None + assert back.schema.field("x").equals( + first.schema.field("x").with_type(back.schema.field("x").type), + check_metadata=True, + ) + if database == "Delta": + with open_database(database, tmp_path) as fresh: + assert _values(fresh.get_all_records(PATH, record_id_column="id")) == ( + _values(first) + ) + + +@pytest.mark.parametrize("database", DATABASES) +def test_an_append_with_the_same_field_attributes_is_kept( + tmp_path: Path, database: str +) -> None: + """The control: the same attributes append, and both batches read back.""" + for where in sorted(WHERE): + build, _, first_values, second_values = WHERE[where] + first = _rows([b"1", b"2"], build("m"), first_values) + second = _rows([b"3", b"4"], build("m"), second_values) + with open_database(database, tmp_path / where) as db: + if _refuses_the_type(database, where, "m"): + with pytest.raises(UnstorableColumnError, match="'x'"): + db.add_records(PATH, first, record_id_column="id", flush=True) + continue + db.add_records(PATH, first, record_id_column="id", flush=True) + db.add_records(PATH, second, record_id_column="id", flush=True) + back = db.get_all_records(PATH, record_id_column="id") + assert _values(back) == _values(first) + _values(second), where diff --git a/tests/test_databases/test_delta_sliced_appends.py b/tests/test_databases/test_delta_sliced_appends.py new file mode 100644 index 000000000..34378b01e --- /dev/null +++ b/tests/test_databases/test_delta_sliced_appends.py @@ -0,0 +1,111 @@ +"""Rows given as a slice of a larger array append and read back exactly (ITL-1334). + +A slice's list offsets start where its first row's items do, and Arrow's list and map +constructors take no validity mask over such offsets. Every list or map Delta rebuilds +(written in its stored form, conformed to the stored struct layout, restored on read) +rebases the offsets and slices the child (``delta_arrow_types.rebased_offsets``), so a +null or non-null row at any slice offset, alone or among others, in one chunk or several, +reads back as written through every read path on a fresh database object. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import DeltaTableDatabase +from orcapod.utils.arrow_utils import normalize_to_large_types +from tests.test_databases.test_delta_struct_evolution import PATH, READS + +I64 = pa.int64() + +# Each column type with four rows, the second null: [v0, None, v2, v3]. +SOURCES: dict[str, tuple[Any, list[Any]]] = { + "large_list": (pa.large_list(pa.int16()), [[1], None, [3, 4], []]), + "list": (pa.list_(pa.int32()), [[1, 2], None, [], [5]]), + "list, non-null items": ( + pa.large_list(pa.field("item", I64, nullable=False)), + [[1], None, [3], [4, 5]], + ), + "map": ( + pa.map_(pa.large_string(), I64), + [[("a", 1)], None, [("c", 3), ("d", 4)], []], + ), + "large_list": ( + pa.large_list(pa.list_(I64, 2)), + [[[1, 2]], None, [[3, 4], None], [[5, 6]]], + ), + "large_list": ( + pa.large_list(pa.large_list(I64)), + [[[1], None], None, [[2, 3]], [[]]], + ), + "struct": ( + pa.struct([pa.field("l", pa.large_list(I64))]), + [{"l": [1]}, None, {"l": None}, {"l": [4, 5]}], + ), + "map": ( + pa.map_(pa.large_string(), pa.large_list(I64)), + [[("a", [1])], None, [("c", None)], [("d", [4, 5])]], + ), + "struct (unrecorded)": ( + pa.struct([pa.field("a", I64)]), + [{"a": 1}, None, {"a": None}, {"a": 4}], + ), +} + + +def _batch(ids: list[bytes], x: Any, y: Any) -> pa.Table: + return pa.table( + { + "id": pa.array(ids, pa.large_binary()), + "k": pa.array([7] * len(ids)), + "x": x, + "y": y, + } + ) + + +def _batches(arrow_type: Any, values: list[Any]) -> list[pa.Table]: + """Four appends of slices: one row at offset 0, the null row alone at offset 1, two + rows at offset 2, and three rows over two chunks (a sliced chunk, then another).""" + source = pa.array(values, arrow_type) + # ``y`` holds the rows in reverse, so its null is at another offset. + reverse = pa.array(list(reversed(values)), arrow_type) + return [ + _batch([b"1"], source.slice(0, 1), reverse.slice(0, 1)), + _batch([b"2"], source.slice(1, 1), reverse.slice(1, 1)), + _batch([b"3", b"4"], source.slice(2, 2), reverse.slice(2, 2)), + _batch( + [b"5", b"6", b"7"], + pa.chunked_array([source.slice(1, 2), source.slice(3, 1)]), + pa.chunked_array([reverse.slice(1, 2), reverse.slice(3, 1)]), + ), + ] + + +@pytest.mark.parametrize("read", sorted(READS)) +@pytest.mark.parametrize("kind", sorted(SOURCES)) +def test_sliced_rows_append_and_read_back(tmp_path: Path, kind: str, read: str) -> None: + arrow_type, values = SOURCES[kind] + batches = _batches(arrow_type, values) + db = DeltaTableDatabase(tmp_path) + for batch in batches: + db.add_records(PATH, batch, record_id_column="id", flush=True) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] # nothing failed + expected = pa.concat_tables(batches).sort_by("id") + if read in ("get_record_by_id", "get_records_by_ids"): + # These shared reads give the rows of ids 1 and 2. + expected = expected.slice(0, 2) + back = READS[read](DeltaTableDatabase(tmp_path)) + assert back is not None + back = back.sort_by("id") + for name in ("x", "y"): + # Every Orcapod table is large: a ``list`` reads back as ``large_list``. + want = normalize_to_large_types(expected.schema.field(name).type) + got = back.schema.field(name).type + assert got == want, name + assert str(got) == str(want), name # the item names too + assert back.column(name).to_pylist() == expected.column(name).to_pylist(), name diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index 433222254..ffa65ad94 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -406,3 +406,53 @@ def test_adding_a_struct_field_inside_a_map_is_refused(tmp_path: pathlib.Path) - _assert_refused_and_nothing_pending( tmp_path, first, second, "'x'.*inside a map, which Delta cannot add" ) + + +def _with_new_column_rows(ids: list[bytes], *, added: bool) -> pa.Table: + """A recorded list, a recorded ``uint8`` and two logical lists; ``added`` adds a + column the stored table does not have.""" + import pathlib as _pathlib + + from orcapod.contexts import get_default_context + + logical = get_default_context().type_converter.python_dicts_to_arrow_table( + [{"s": {1, 2}, "p": [_pathlib.Path("/a")]} for _ in ids], + python_schema={"s": set[int], "p": list[_pathlib.Path]}, + ) + table = _rows( + ids, + items=( + [[1, 2]] * len(ids), + pa.large_list(pa.field("item", I64, nullable=False)), + ), + u=([200] * len(ids), pa.uint8()), + ) + table = table.append_column("k", pa.array([7] * len(ids), I64)) + table = table.append_column(logical.schema.field("s"), logical.column("s")) + table = table.append_column(logical.schema.field("p"), logical.column("p")) + if added: + table = table.append_column("added", pa.array(["a"] * len(ids))) + return table + + +@pytest.mark.parametrize("read", sorted(READS)) +def test_a_new_column_keeps_every_other_columns_type( + tmp_path: pathlib.Path, read: str +) -> None: + """An append adding a column goes through a MERGE that writes each field's metadata + from the rows: a list column handed to it keeps its record and a logical list its + extension name, so neither reads back as Delta's plain list (ITL-1334).""" + first = _with_new_column_rows([b"1"], added=False) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, first, record_id_column="id", flush=True) + db.add_records( + PATH, + _with_new_column_rows([b"2"], added=True), + record_id_column="id", + flush=True, + ) + back = READS[read](DeltaTableDatabase(tmp_path)) + assert back is not None + for name in ("items", "u", "s", "p"): + assert str(back.schema.field(name).type) == str(first.schema.field(name).type) + assert back.sort_by("id").column("added").to_pylist() == [None, "a"] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 85b5781cc..4834858b6 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -2,9 +2,11 @@ Every row is a column type, every column a database. A cell is measured, never declared: a table holding two columns of the type (the second with a null when the type is -nullable) is written with ``add_records`` and flushed, a second batch of the same type is -appended, and both are read back with ``get_all_records``, then compared exactly with what -was written (every nested field's name, nullability and metadata, a map's +nullable) is written with ``add_records`` and flushed; the same type is appended as slices +of a larger table (three rows over two chunks, then the null row alone at a nonzero +offset); the same columns with other field metadata (the column's own, and a nested +field's) are appended, which must be refused naming the column; and every batch is read +back with ``get_all_records``, then compared exactly with what was written (every nested field's name, nullability and metadata, a map's ``keys_sorted``, values bit for bit), up to the large variants every Orcapod table uses (``arrow_utils.normalize_to_large_types``). The outcome is one of: @@ -35,7 +37,7 @@ import uuid from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, cast from unittest.mock import MagicMock, patch import pyarrow as pa @@ -136,6 +138,9 @@ def build(root: Path) -> tuple[Any, Any, list[Any], list[Any]]: return build +# ``pa.map_`` with key and item fields (which pyarrow takes; its stubs take types only). +map_of_fields: Any = pa.map_ + D = decimal.Decimal _NAN = float("nan") _TS = [ @@ -401,6 +406,28 @@ def _upaths(root: Path) -> list[Any]: [[("a", 1), ("b", 2)], [], [("c", None)]], ), ), + Row( + "map (item metadata)", + "names and metadata", + _plain( + map_of_fields( + pa.field("key", pa.string(), nullable=False), + pa.field("value", pa.int64(), metadata={"unit": "m"}), + ), + [[("a", 1), ("b", 2)], [], [("c", None)]], + ), + ), + Row( + "map (key metadata)", + "names and metadata", + _plain( + map_of_fields( + pa.field("key", pa.string(), nullable=False, metadata={"unit": "m"}), + pa.field("value", pa.int64()), + ), + [[("a", 1), ("b", 2)], [], [("c", None)]], + ), + ), Row( "int64 {unit: s} (field metadata)", "names and metadata", @@ -557,7 +584,8 @@ def build_table(row: Row, root: Path) -> pa.Table: @contextlib.contextmanager -def _database(name: str, root: Path) -> Iterator[Any]: +def open_database(name: str, root: Path) -> Iterator[Any]: + """The database ``name`` (one of ``DATABASES``), its files under ``root``.""" if name == "in-memory": yield InMemoryArrowDatabase() elif name == "Delta": @@ -707,6 +735,65 @@ def _same_values(a: Any, b: Any) -> bool: return a.equals(b) +_CHANGED = {b"orcapod:matrix": b"changed"} + + +def _with_changed_metadata(field: "pa.Field[Any]") -> "pa.Field[Any]": + return field.with_metadata(cast(Any, {**(field.metadata or {}), **_CHANGED})) + + +def _nested_changed(arrow_type: Any) -> Any: + """``arrow_type`` with its first nested field's metadata changed, or ``None``.""" + t = pa.types + if isinstance(arrow_type, pa.ExtensionType): + return None + if t.is_struct(arrow_type): + fields = list(arrow_type) + return pa.struct([_with_changed_metadata(fields[0]), *fields[1:]]) + if t.is_map(arrow_type): + return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields + arrow_type.key_field, + _with_changed_metadata(arrow_type.item_field), + keys_sorted=arrow_type.keys_sorted, + ) + if t.is_large_list(arrow_type): + return pa.large_list(_with_changed_metadata(arrow_type.value_field)) + if t.is_list(arrow_type): + return pa.list_(_with_changed_metadata(arrow_type.value_field)) + if t.is_fixed_size_list(arrow_type): + return pa.list_( + _with_changed_metadata(arrow_type.value_field), arrow_type.list_size + ) + return None + + +def _attribute_changes(rows: pa.Table) -> list[tuple[str, pa.Table]]: + """``rows`` (new ids) with other field attributes on ``x`` and ``y``: the columns' + own metadata, then, for a nested type, its first nested field's metadata.""" + ids = pa.array([b"c1", b"c2", b"c3"], pa.large_binary()) + rows = rows.set_column(0, rows.schema.field("id"), ids) + out = [] + own = rows + for name in ("x", "y"): + index = own.schema.get_field_index(name) + own = own.set_column( + index, _with_changed_metadata(own.schema.field(name)), own.column(index) + ) + out.append(("column metadata", own)) + nested = rows + for name in ("x", "y"): + index = nested.schema.get_field_index(name) + field = nested.schema.field(name) + changed = _nested_changed(field.type) + if changed is None: + return out + # Built from the values: the append must be refused, so they are never read. + column = pa.array(nested.column(index).to_pylist(), changed) + nested = nested.set_column(index, field.with_type(changed), column) + out.append(("nested field metadata", nested)) + return out + + def measure(row: Row, database: str, root: Path) -> Cell: """Write ``row``'s table to ``database`` and say what came back.""" root.mkdir(parents=True, exist_ok=True) @@ -714,7 +801,7 @@ def measure(row: Row, database: str, root: Path) -> Cell: written = build_table(row, root) except Exception as exc: # noqa: BLE001 # a row Orcapod cannot build is reported return Cell(SILENT, f"cannot build the column: {type(exc).__name__}: {exc}") - with _database(database, root) as db: + with open_database(database, root) as db: path = ("matrix", "t") if database == "PostgreSQL": try: @@ -745,22 +832,43 @@ def measure(row: Row, database: str, root: Path) -> Cell: SILENT, f"write failed without naming the column: {type(exc).__name__}: {str(exc)[:160]}", ) - # A second batch of the same type appended: the stored type must take it, and - # both batches read back exactly (on Delta, through the merged record). - appended = written.set_column( - 0, - written.schema.field("id"), - pa.array([b"s1", b"s2", b"s3"], pa.large_binary()), - ) - try: - db.add_records(path, appended, record_id_column="id", flush=True) - except Exception as exc: # noqa: BLE001 - return Cell( - SILENT, - f"first write kept, the same type appended failed: " - f"{type(exc).__name__}: {str(exc)[:160]}", + # The same type appended as slices (a list's offsets then start past zero): + # three rows over two chunks, then the null row alone at a nonzero offset. The + # stored type must take them, and every batch reads back exactly (on Delta, + # through the merged record). + doubled = pa.concat_tables([written, written]) + for ids, rows in ( + ([b"s1", b"s2", b"s3"], doubled.slice(1, 3)), + ([b"s4"], doubled.slice(4, 1)), + ): + appended = rows.set_column( + 0, written.schema.field("id"), pa.array(ids, pa.large_binary()) ) - written = pa.concat_tables([written, appended]) + try: + db.add_records(path, appended, record_id_column="id", flush=True) + except Exception as exc: # noqa: BLE001 + return Cell( + SILENT, + f"first write kept, the same type appended as a slice failed: " + f"{type(exc).__name__}: {str(exc)[:160]}", + ) + written = pa.concat_tables([written, appended]) + # The same columns with other field attributes appended: the table holds one + # type per column, so the append must be refused naming the column (the rows + # read back below are then those already written). + for where, changed in _attribute_changes(written.slice(0, 3)): + try: + db.add_records(path, changed, record_id_column="id", flush=True) + except Exception as exc: # noqa: BLE001 + if not _names_a_column(exc): + return Cell( + SILENT, + f"an append with other {where} failed without naming the " + f"column: {type(exc).__name__}: {str(exc)[:160]}", + ) + db.flush() + continue + return Cell(SILENT, f"an append with other {where} was accepted") try: back = db.get_all_records(path, record_id_column="id") except Exception as exc: # noqa: BLE001 @@ -858,8 +966,11 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: a connector database), and nothing of the table is written. How it is measured: a table holding two columns of the type (the second nullable, with a -null row) is written with `add_records` and flushed, a second batch of the same type is -appended, and both are read back with `get_all_records`. +null row) is written with `add_records` and flushed. The same type is then appended as +slices of a larger table (three rows over two chunks, then the null row alone), and the +same columns with other field metadata (the column's own, and a nested field's) are +appended, which every database must refuse, naming the column. Every batch written is read +back with `get_all_records`. The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which models what SpiralDB does to a column (no SpiralDB is used). No database tells tag columns from data columns, so a type is kept or refused the same way in either role. @@ -881,17 +992,24 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: no type is refused (the `null` row below), while a `null`-typed value is kept where the table already stores a type. - Delta and SpiralDB give a map's key and item fields back as `key` and `value`, so a map - with other names is refused. + with other names is refused. SpiralDB does not keep metadata on a map's key or item + field, so a map with such metadata is refused there. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. +A table holds one type per column. An append whose columns differ from the held ones +(stored, or still pending) in field metadata (the column's own, or a nested field's: a +struct child, a list item, a map key or item), in a nested field's name, or in whether a +map's keys are sorted is refused by every database, naming the column and the field, +before anything is written: either side's rows would otherwise read back with the other +side's attributes. A change of nullability is left to each database's own rule. + Appending to a Delta table may evolve a struct column (fields added, omitted or in another order): every value keeps its field's name, and an omitted field reads as null -in the appended rows. An append is refused, naming the column and the field, before -anything is written, when it would add a non-nullable struct field (the stored rows have -no value for it), add a struct field inside a map (Delta cannot), or change what the -column states about a nested field: a list item's name or metadata, a struct child's -metadata, a map's sorted keys. +in the appended rows. An append is refused, naming the column and the field, when it +would add a non-nullable struct field (the stored rows have no value for it) or add a +struct field inside a map (Delta cannot). A nested field the append makes nullable reads +as nullable afterwards, as Delta stores it. """ From 876f3eb2132a39247ca596c300f71b0e27f3d584 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 14:35:39 -0800 Subject: [PATCH 05/13] docs(delta_lake_databases): the append guard checks no nullability (ITL-1334) The docstring of _refuse_unmergeable_append promised refusing a nested field's nullability change; nullability is left to the append check, Delta and the nullability audit (ITL-842). Behaviour unchanged. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 31013eb54..dae360657 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1426,22 +1426,24 @@ def _refuse_unmergeable_append( Checked before anything is buffered (ITL-1334), against what the table holds for each column: the stored table (a column's record, else its stored type and field metadata) and a batch pending for it. A column's field metadata (beside - its record) and its whole nested field tree must be the held ones - (``appended_field_change``, ``_added_field_change``): an append may evolve a struct (fields added, omitted or - reordered: ``_conformed_to_stored``), but not add a non-nullable field (the - stored rows have no value for it, and Delta then cannot read the table), not - add a struct field inside a map (Delta's merge cannot), and not change a nested - field's name, nullability or metadata, or a map's ``keys_sorted``: the table - holds one type per column, so either side's rows would read back with the - other's. A column's own nullability and type are left to the append check. + its record) and its nested field tree must be the held ones + (``appended_field_change``, ``_added_field_change``): an append may evolve a + struct (fields added, omitted or reordered: ``_conformed_to_stored``), but not + add a non-nullable field (the stored rows have no value for it, and Delta then + cannot read the table), not add a struct field inside a map (Delta's merge + cannot), and not change a nested field's name or metadata, or a map's + ``keys_sorted``: the table holds one type per column, so either side's rows + would read back with the other's. Nullability, of the column and of a nested + field, is not checked here: the append check and Delta decide it, and whether a + change is refused belongs to the nullability audit (ITL-842); the merged record + marks a nested field nullable when either side is (``merged_type``). A + column's type is left to the append check. A stored table that cannot be + loaded is left to the flush, which reports it (``OrcapodDatabaseReadError``). Args: record_path: The table the rows are for. schema: The schema of the rows about to be added. - A stored table that cannot be loaded is left to the flush, which reports it - (``OrcapodDatabaseReadError``). - Raises: InputValidationError: For the first such column, naming it and the path. """ From c43d144ff924201a1d01e4add76ea5b8b0668a80 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 14:57:18 -0800 Subject: [PATCH 06/13] test(arrow_schema_identity): a type-changing store is simulated now that Delta keeps fixed-size lists PR 454's three refusal tests used Delta reading a fixed-size list back as large_list (ITL-1275), which this branch fixes. They now skip Delta's recorded-type restore (a fixture), keeping what they test: a stored or cached read of another type is refused, naming the column. The exact-read test runs on Delta too. Co-Authored-By: Claude Opus 5.5 --- .../test_arrow_schema_identity.py | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/tests/test_hashing/test_arrow_schema_identity.py b/tests/test_hashing/test_arrow_schema_identity.py index 814e2e942..915cbf83b 100644 --- a/tests/test_hashing/test_arrow_schema_identity.py +++ b/tests/test_hashing/test_arrow_schema_identity.py @@ -261,8 +261,19 @@ def test_as_source_keeps_its_identity_when_rows_arrive( assert after.as_table().schema.field("g").type == pa.int64() +@pytest.fixture() +def delta_without_restore(monkeypatch: pytest.MonkeyPatch) -> None: + """A store that gives a column back as another type: Delta with its recorded-type + restore skipped, so a fixed-size list reads back as Delta's ``large_list``, as it + did before ITL-1275 (fixed by ITL-1334).""" + from orcapod.databases import delta_lake_databases + + monkeypatch.setattr(delta_lake_databases, "from_delta_layout", lambda table: table) + + +@pytest.mark.usefixtures("delta_without_restore") def test_a_stored_read_of_another_type_is_refused(tmp_path: Path) -> None: - """Delta reads a fixed_size_list back as large_list (ITL-1275): refused, named.""" + """A store reading a fixed_size_list back as large_list: refused, named.""" fixed, _ = DIFFERENT["fixed_size_list/large_list"] node = _logged_map(DeltaTableDatabase(tmp_path / "delta"), _source(_table(fixed))) with pytest.raises(InputValidationError, match=r"'z' reads back as large_list"): @@ -598,8 +609,9 @@ def test_a_cached_source_reads_its_declared_types(kind: str, tmp_path: Path) -> assert first.arrow_schemas == typed_arrow_schemas(_source(table)) +@pytest.mark.usefixtures("delta_without_restore") def test_a_cached_read_of_another_type_is_refused(tmp_path: Path) -> None: - """Delta reads a fixed-size list back as a list (ITL-1275): refused, naming it.""" + """A store reading a fixed-size list back as a list: refused, naming it.""" table = _table(FIXED_SIZE) database = _databases(tmp_path)["delta"] with pytest.raises( @@ -610,9 +622,11 @@ def test_a_cached_read_of_another_type_is_refused(tmp_path: Path) -> None: _cached(table, database).as_table() -def test_a_cached_fixed_size_list_in_memory_is_exact(tmp_path: Path) -> None: +@pytest.mark.parametrize("kind", ["memory", "delta"]) +def test_a_cached_fixed_size_list_is_exact(kind: str, tmp_path: Path) -> None: + """Delta keeps a fixed-size list through its recorded type (ITL-1275, ITL-1334).""" table = _table(FIXED_SIZE) - database = _databases(tmp_path)["memory"] + database = _databases(tmp_path)[kind] for _ in range(2): read = _cached(table, database).as_table() assert read.schema.field("x").type == pa.list_(pa.int8(), 2) @@ -624,6 +638,7 @@ def test_a_cached_fixed_size_list_in_memory_is_exact(tmp_path: Path) -> None: ) +@pytest.mark.usefixtures("delta_without_restore") def test_get_all_records_refuses_a_cached_read_of_another_type(tmp_path: Path) -> None: """Every read of the cache's rows is checked (fourth Codex review of PR 454): ``get_all_records()`` after an ``as_table()`` refusal, and on a fresh wrapper over From 71f30b14b813e6b40ad7bddc65cbf8b526e4da06 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 15:53:51 -0800 Subject: [PATCH 07/13] fix(databases): what a Delta flush would refuse is refused when rows are added CodeRabbit on PR 471 (ITL-1334), reviews of 25cd947a and c43d144f. - One rule, _append_refusal, checked by add_records against the stored table before buffering and again by the flush against the version it loads: field attributes and struct evolution (now also an omitted non-nullable struct field, at any depth), a non-nullable column omitted or holding a null, a type conflict (used to be refused only at flush) and an unsigned value an unrecorded column cannot hold. Rows the flush refuses leave the queue, with a note; other flush failures keep their batch as before. - _incompatible_append_column compares column by column: new columns are not compared; float16 is compared as it is (refused by a float32 column). - require_storable refuses a struct with no fields at any depth. - A null-typed part at a path the table types is written as typed nulls (Delta's MERGE panicked on a null child of an evolving struct; pre-existing), and a null part is typed by the stored table or a pending batch, per path. - SpiralDB refuses Arrow's canonical extension types (BaseExtensionType) and field metadata at any depth below a map. - UnstorableColumnError suggests only InMemoryArrowDatabase and points to the database-types page (a per-type check would import Delta into errors.py). - Matrix: sub-unit ticks in every temporal row; rows for an empty struct, Arrow's canonical uuid and metadata inside a map item: 0 of 420 silent. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1334.md | 34 +- docs/concepts/pipeline-job.md | 2 +- docs/reference/database-types.md | 3 + src/orcapod/databases/delta_lake_databases.py | 404 +++++++++++------- src/orcapod/databases/spiraldb_connector.py | 32 +- src/orcapod/errors.py | 11 +- .../test_appended_field_attributes.py | 30 +- .../test_delta_append_preflight.py | 313 ++++++++++++++ .../test_delta_arrow_type_roundtrip.py | 80 ++-- .../test_delta_read_failures.py | 12 +- .../test_delta_read_your_writes.py | 38 +- .../test_delta_struct_evolution.py | 4 +- .../test_spiraldb_connector_fake.py | 50 +++ .../test_databases/test_unstorable_columns.py | 5 +- tests/test_databases/type_matrix.py | 83 +++- 15 files changed, 857 insertions(+), 244 deletions(-) create mode 100644 tests/test_databases/test_delta_append_preflight.py diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index bebcae391..d4694e05b 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -51,13 +51,30 @@ metadata, the SpiralDB connector gave every row the latest batch's, and Delta kept the stored metadata, whether or not the column's type was recorded. Nullability is left to each database's own rule. (ITL-1334) -- **An append to a `DeltaTableDatabase` table is refused when the column cannot take it:** - adding a non-nullable struct field (the stored rows have no value for it, and Delta - could not read the table back) or a struct field inside a map (Delta's merge cannot) - raises `InputValidationError` naming the column and the field, before anything is - buffered. A nested field an append makes nullable reads back nullable. (ITL-1334) -- **`SpiralDBConnector` refuses a map whose key or item field has metadata:** its metadata - record does not cover a map's fields, so the metadata read back dropped. (ITL-1334) +- **What a `DeltaTableDatabase` flush would refuse is refused when the rows are added:** + before anything is buffered, `add_records` checks the rows against the stored table and + raises `InputValidationError` naming the column and the field. The rows are refused + when they would: + - add a non-nullable struct field (the stored rows have no value for it, and Delta could + not read the table back), or add a struct field inside a map (Delta's merge cannot); + - omit a struct field or a column stored as non-nullable, or hold a null in such a + column; + - give a column another type than the stored one, a `float16` into a `float32` column + included. + + These used to fail the flush and stay queued, so every later flush failed again. The + flush repeats the check against the version it loads, since another writer may commit + in between; rows it refuses are dropped from the queue, and the error says so. A nested + field an append makes nullable reads back nullable. (ITL-1334) +- **`DeltaTableDatabase` refuses a struct with no fields at any depth:** a Parquet file + stores values in leaf columns only, so the flush failed. (ITL-1334) +- **`SpiralDBConnector` refuses field metadata below a map, and Arrow's canonical extension + types:** its metadata record does not descend into a map, so metadata on a map's key or + item, or inside them, read back dropped. A `uuid` or `json` column (Arrow's own extension + types) read back as its storage type. (ITL-1334) +- **`UnstorableColumnError` suggests only `InMemoryArrowDatabase`:** it suggested + `DeltaTableDatabase` for types Delta refuses too (`decimal256`). The message now points + to `docs/reference/database-types.md` for what each database keeps. (ITL-1334) ### Fixed @@ -71,6 +88,9 @@ field is refused), and a recorded column's record describes the merged column. (ITL-1334) +- **A `null`-typed part of a Delta append is written as typed nulls:** a `null` child of a + struct that also gained a field made Delta's MERGE panic. A `null` part needs a type at + its path from either the stored table or a pending batch. (ITL-1334) - **A Delta append of rows sliced from a larger table writes:** a null list or map row at a nonzero slice offset failed the flush ("Null bitmap with offsets slice not supported") and stayed pending; every list and map Delta rebuilds now rebases its diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 495f799c6..625400b73 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -186,7 +186,7 @@ try: compute_bmi.pod(mice(cohort_a), label="bmi") except UnstorableColumnError as exc: print(exc) -# node 'bmi': a SQLiteConnector database cannot store column '__pf_exec_executor_info' of Arrow type large_list<...>: SQLite has no column type for it. Use an InMemoryArrowDatabase or a DeltaTableDatabase instead. +# node 'bmi': a SQLiteConnector database cannot store column '__pf_exec_executor_info' of Arrow type large_list<...>: SQLite has no column type for it. Use an InMemoryArrowDatabase instead; docs/reference/database-types.md lists what each database keeps. ``` ## What a re-run computes diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index b16380a4f..1b668112e 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -178,6 +178,8 @@ as nullable afterwards, as Delta stores it. | Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | |---|---|---|---|---|---| | `struct` | kept | kept | refused | refused | refused | +| `struct<> (no fields)` | kept | refused | refused | refused | refused | +| `uuid (Arrow's canonical extension type)` | kept | refused | refused | refused | refused | | `struct[2]>` | kept | kept (recorded type) | refused | refused | refused | | `map` | kept | kept (recorded type) | refused | refused | kept | @@ -191,6 +193,7 @@ as nullable afterwards, as Delta stores it. | `map, keys sorted` | kept | refused | refused | refused | refused | | `map (item metadata)` | kept | kept (recorded type) | refused | refused | refused | | `map (key metadata)` | kept | kept (recorded type) | refused | refused | refused | +| `map> (metadata inside the item)` | kept | kept (recorded type) | refused | refused | refused | | `int64 {unit: s} (field metadata)` | kept | kept | refused | refused | kept | ## Nullability diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index dae360657..4a7b705f8 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -339,6 +339,10 @@ def _conformed_array(array: Any, stored: Any) -> Any: ValueError: The array omits a struct field ``stored`` has as non-nullable. """ t = pa.types + if t.is_null(array.type) and not t.is_null(stored): + # A ``null``-typed part where the table stores a type: typed nulls, since + # Delta's MERGE panics on a ``null`` child of an evolving struct (ITL-1334). + return pa.nulls(len(array), stored) mask = array.is_null() if array.null_count else None if t.is_struct(array.type) and t.is_struct(stored): own = {array.type.field(i).name: i for i in range(array.type.num_fields)} @@ -480,15 +484,16 @@ def _is_logical(field: "pa.Field[Any]") -> bool: ) -def _added_field_change( +def _evolution_change( stored: Any, incoming: Any, path: str, *, in_map: bool = False ) -> str | None: - """Say why a struct field ``incoming`` adds cannot be appended (ITL-1334). + """Say why a struct of ``incoming`` cannot evolve the stored one (ITL-1334). Walks both types by struct field NAME and through lists and maps: a struct field ``incoming`` adds may not be non-nullable (the stored rows have no value for it, and Delta then cannot read the table), nor be inside a map (Delta's merge cannot - add it). A field it omits is filled with nulls (``_conformed_to_stored``). + add it); a field it omits is filled with nulls (``_conformed_to_stored``), so it + may not be one stored as non-nullable. Args: stored: The type the table holds, large-normalized. @@ -502,6 +507,13 @@ def _added_field_change( t = pa.types if t.is_struct(stored) and t.is_struct(incoming): known = {f.name: f for f in stored} + given = {f.name for f in incoming} + for field in stored: + if field.name not in given and not field.nullable: + return ( + f"{path}.{field.name} is stored as non-nullable, and the rows " + "omit it" + ) for field in incoming: here = f"{path}.{field.name}" if field.name not in known: @@ -513,22 +525,22 @@ def _added_field_change( "rows have no value for" ) continue - found = _added_field_change( + found = _evolution_change( known[field.name].type, field.type, here, in_map=in_map ) if found is not None: return found return None if t.is_map(stored) and t.is_map(incoming): - return _added_field_change( + return _evolution_change( stored.key_type, incoming.key_type, f"{path}.key", in_map=True - ) or _added_field_change( + ) or _evolution_change( stored.item_type, incoming.item_type, f"{path}.item", in_map=True ) lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) if any(k(stored) for k in lists) and any(k(incoming) for k in lists): # cast: the type guards above narrow ``stored`` in the stubs' terms. - return _added_field_change( + return _evolution_change( cast(Any, stored).value_type, incoming.value_type, f"{path}[]", @@ -537,50 +549,174 @@ def _added_field_change( return None -def _untyped_null_path(incoming: Any, given: Any, path: str) -> str | None: - """The first path where ``incoming`` is ``null``-typed and ``given`` has no type. +def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: + """Say why rows of column ``field`` cannot be appended where ``held`` is held. + + The column's own field metadata and its nested field tree must be the held ones + (``appended_field_change``): the table holds one type per column, so either + side's rows would read back with the other's. A struct may evolve, within + ``_evolution_change``. A logical column's type is its extension's, which the type + check compares; its own field metadata is compared here. Nullability is not + compared: the append check and Delta decide it, and whether a change is refused + belongs to the nullability audit (ITL-842). + + Args: + held: The column as the table holds it (its record, else its stored type, + with its field metadata; or a pending batch's column). + field: The column of the rows to append. + + Returns: + The reason, naming the path, or ``None``. + """ + if _is_logical(field) or _is_logical(held): + if _metadata(held.metadata) == _metadata(field.metadata): + return None + return f"{field.name} has other field metadata than the stored column" + return appended_field_change( + held.with_metadata(cast(Any, _metadata(held.metadata))), + field.with_metadata(cast(Any, _metadata(field.metadata))), + ) or _evolution_change( + arrow_utils.normalize_to_large_types(held.type, keep_null=True), + arrow_utils.normalize_to_large_types(field.type, keep_null=True), + field.name, + ) + + +def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any]"]: + """Each stored column as the table holds it: its recorded type, else its stored + type, with its field metadata as stored. Read from the log; no data is read.""" + stored = _stored_arrow_schema(delta_table) + fields: dict[str, pa.Field[Any]] = {} + for delta_field in delta_table.schema().fields: + record = recorded_type(delta_field.metadata) + fields[delta_field.name] = pa.field( + delta_field.name, + record + if record is not None + else stored.field(stored.get_field_index(delta_field.name)).type, + nullable=delta_field.nullable, + metadata=cast(Any, metadata_bytes(delta_field.metadata)) or None, + ) + return fields + + +def _append_refusal( + delta_table: deltalake.DeltaTable, rows: pa.Table +) -> tuple[str, str] | None: + """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). + + One rule for what an append is refused for, checked before the rows are buffered + and again at flush against the version then loaded: + + - a column change (``_column_change``): other field attributes, a struct that + adds a non-nullable field or one inside a map, or omits a non-nullable one; + - a column stored as non-nullable that the rows omit or hold a null in (Delta + refuses the commit); + - a type the stored column does not have (``_incompatible_append_column``); + - a value a column stored without a recorded type cannot hold + (``first_column_out_of_stored_range``). + + Args: + delta_table: The loaded stored table. + rows: The rows to append, with their own types. + + Returns: + ``(column, reason)``, or ``None`` when the rows can be appended. + """ + held = _held_columns(delta_table) + for field in rows.schema: + if field.name in held: + change = _column_change(held[field.name], field) + if change is not None: + return field.name, change + for name, field in held.items(): + if field.nullable: + continue + index = rows.schema.get_field_index(name) + if index < 0: + return name, f"{name} is stored as non-nullable, and the rows omit it" + if rows.column(index).null_count: + return name, f"{name} is stored as non-nullable, and the rows hold a null" + written = pa.schema([written_field(f) for f in rows.schema]) + mismatch = DeltaTableDatabase._incompatible_append_column( + delta_table, rows.schema, written + ) + if mismatch is not None: + column, stored_type, incoming_type = mismatch + return column, ( + f"it is stored as {stored_type} but the new rows have {incoming_type} " + f"(input type {rows.schema.field(column).type})" + ) + overflowing = first_column_out_of_stored_range( + rows, [name for name, f in held.items() if recorded_type(f.metadata) is None] + ) + if overflowing is not None: + return overflowing, ( + "it is stored as a signed integer with no recorded Arrow type (a table " + "written before ITL-928), and the new rows have " + f"{rows.schema.field(overflowing).type} values it cannot hold; rebuild " + "the database" + ) + return None + + +def _untyped_null_paths(incoming: Any, given: Any, path: str) -> list[str]: + """Every path where ``incoming`` is ``null``-typed and ``given`` has no type. ``given`` is what the stored table (or a pending batch) has at ``path``, or ``None`` when it has nothing there; a stored ``null`` type gives no type either. Struct fields are matched by name, and list items, map keys and items followed. Returns: - The dotted path (``x.b``, ``x[]``), or ``None`` when every ``null`` part of - ``incoming`` has a typed counterpart. + The dotted paths (``x.b``, ``x[]``), in field order; empty when every ``null`` + part of ``incoming`` has a typed counterpart. """ t = pa.types if given is not None and t.is_null(given): given = None if t.is_null(incoming): - return path if given is None else None + return [path] if given is None else [] if t.is_struct(incoming): known = ( {f.name: f.type for f in given} if given is not None and t.is_struct(given) else {} ) - for field in incoming: - found = _untyped_null_path( + return [ + found + for field in incoming + for found in _untyped_null_paths( field.type, known.get(field.name), f"{path}.{field.name}" ) - if found is not None: - return found - return None + ] if t.is_map(incoming): is_map = given is not None and t.is_map(given) - return _untyped_null_path( + return _untyped_null_paths( incoming.key_type, given.key_type if is_map else None, f"{path}.key" - ) or _untyped_null_path( + ) + _untyped_null_paths( incoming.item_type, given.item_type if is_map else None, f"{path}.item" ) if incoming.num_fields or t.is_fixed_size_list(incoming): is_list = given is not None and ( t.is_list(given) or t.is_large_list(given) or t.is_fixed_size_list(given) ) - return _untyped_null_path( + return _untyped_null_paths( incoming.value_type, given.value_type if is_list else None, f"{path}[]" ) - return None + return [] + + +def _holds_empty_struct(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` is or nests a struct with no fields, which a Parquet file + cannot store (it stores values in leaf columns only; ITL-1334).""" + if isinstance(arrow_type, pa.BaseExtensionType): + return _holds_empty_struct(arrow_type.storage_type) + if pa.types.is_struct(arrow_type) and arrow_type.num_fields == 0: + return True + return any( + _holds_empty_struct(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) def _holds_null_type(arrow_type: pa.DataType) -> bool: @@ -592,7 +728,7 @@ def _holds_null_type(arrow_type: pa.DataType) -> bool: ) -def _delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: +def delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: """Say why Delta cannot hold a column, even through a recorded type, or ``None``. The column as it is written (``written_field``) goes through the Delta writer's @@ -614,6 +750,8 @@ def _delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: if arrow_utils.holds_renamed_map(field.type): # The recorded type goes through Arrow IPC, which renames them (ITL-1334). return "a map's key and item fields read back as 'key' and 'value'" + if _holds_empty_struct(field.type): + return "a struct with no fields has no leaf column for a Parquet file to store" written = written_field(field) reduced = _without_null_types(written.type) if reduced is None: @@ -1409,7 +1547,7 @@ def require_storable(self, schema: pa.Schema) -> None: column, its Arrow type and Delta's reason. """ for field in schema: - reason = _delta_unstorable_reason(field) + reason = delta_unstorable_reason(field) if reason is not None: raise UnstorableColumnError( database_kind=type(self).__name__, @@ -1419,91 +1557,50 @@ def require_storable(self, schema: pa.Schema) -> None: ) def _refuse_unmergeable_append( - self, record_path: tuple[str, ...], schema: pa.Schema + self, record_path: tuple[str, ...], records: pa.Table ) -> None: - """Refuse rows that would not read back as written, or would break the table. - - Checked before anything is buffered (ITL-1334), against what the table holds - for each column: the stored table (a column's record, else its stored type and - field metadata) and a batch pending for it. A column's field metadata (beside - its record) and its nested field tree must be the held ones - (``appended_field_change``, ``_added_field_change``): an append may evolve a - struct (fields added, omitted or reordered: ``_conformed_to_stored``), but not - add a non-nullable field (the stored rows have no value for it, and Delta then - cannot read the table), not add a struct field inside a map (Delta's merge - cannot), and not change a nested field's name or metadata, or a map's - ``keys_sorted``: the table holds one type per column, so either side's rows - would read back with the other's. Nullability, of the column and of a nested - field, is not checked here: the append check and Delta decide it, and whether a - change is refused belongs to the nullability audit (ITL-842); the merged record - marks a nested field nullable when either side is (``merged_type``). A - column's type is left to the append check. A stored table that cannot be - loaded is left to the flush, which reports it (``OrcapodDatabaseReadError``). + """Refuse, before anything is buffered, rows a flush would refuse (ITL-1334). + + Checked against a batch pending for the table (``_column_change``) and against + the stored table (``_append_refusal``, which the flush repeats against the + version it loads): what would not read back as written, would break the + table, or the Delta writer would reject. A stored table that cannot be loaded + is left to the flush, which reports it (``OrcapodDatabaseReadError``). Args: record_path: The table the rows are for. - schema: The schema of the rows about to be added. + records: The rows about to be added. Raises: InputValidationError: For the first such column, naming it and the path. """ - held: list[dict[str, pa.Field[Any]]] = [] pending = self._pending_batches.get(self._get_record_key(record_path)) + refusal = None if pending is not None: - held.append({f.name: f for f in pending.schema}) - try: - delta_table = self._get_delta_table(record_path) - except OrcapodDatabaseReadError: - delta_table = None - if delta_table is not None: - stored = _stored_arrow_schema(delta_table) - fields: dict[str, pa.Field[Any]] = {} - for delta_field in delta_table.schema().fields: - record = recorded_type(delta_field.metadata) - arrow_type = ( - record - if record is not None - else stored.field(stored.get_field_index(delta_field.name)).type - ) - fields[delta_field.name] = pa.field( - delta_field.name, - arrow_type, - metadata=cast(Any, metadata_bytes(delta_field.metadata)) or None, - ) - held.append(fields) - for field in schema: - incoming = arrow_utils.normalize_to_large_types(field.type, keep_null=True) - for given in held: - if field.name not in given: - continue - held_field = given[field.name] - if _is_logical(field) or _is_logical(held_field): - # A logical column's type is its extension's, which the append - # check compares; its own field metadata is compared here. - change = ( - None - if _metadata(held_field.metadata) == _metadata(field.metadata) - else f"{field.name} has other field metadata than the stored " - "column" - ) - else: - change = appended_field_change( - held_field.with_metadata( - cast(Any, _metadata(held_field.metadata)) - ), - field.with_metadata(cast(Any, _metadata(field.metadata))), - ) or _added_field_change( - arrow_utils.normalize_to_large_types( - held_field.type, keep_null=True - ), - incoming, - field.name, - ) - if change is not None: - raise InputValidationError( - f"Cannot append to the stored table at {record_path!r}: column " - f"{field.name!r}: {change}. Nothing was written." - ) + held = {f.name: f for f in pending.schema} + refusal = next( + ( + (f.name, change) + for f in records.schema + if f.name in held + and (change := _column_change(held[f.name], f)) is not None + ), + None, + ) + if refusal is None: + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + delta_table = None + if delta_table is not None: + refusal = _append_refusal(delta_table, records) + if refusal is not None: + column, reason = refusal + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: column {column!r}: {reason}. " + "The stored rows are unchanged and nothing was written." + ) def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema @@ -1540,18 +1637,22 @@ def _refuse_untyped_null_columns( for given in (stored, pending.schema if pending is not None else None) if given is not None and given.get_field_index(field.name) >= 0 ] - paths = [_untyped_null_path(field.type, t, field.name) for t in known] - path = _untyped_null_path(field.type, None, field.name) - if paths: - path = next((p for p in paths if p is None), paths[0]) - if path is not None: + # A ``null`` part is typed when the stored table or the pending batch + # types its path; the flush writes it as typed nulls (``_conformed_array``). + unresolved = _untyped_null_paths(field.type, None, field.name) + for given_type in known: + typed_here = set(unresolved) - set( + _untyped_null_paths(field.type, given_type, field.name) + ) + unresolved = [p for p in unresolved if p not in typed_here] + if unresolved: raise UnstorableColumnError( database_kind=type(self).__name__, column=field.name, arrow_type=field.type, reason=( - f"Delta has no null type, and nothing stored gives {path!r} a " - "type" + "Delta has no null type, and nothing stored gives " + f"{', '.join(repr(p) for p in unresolved)} a type" ), ) @@ -1603,7 +1704,7 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) self._refuse_untyped_null_columns(record_path, records.schema) - self._refuse_unmergeable_append(record_path, records.schema) + self._refuse_unmergeable_append(record_path, records) # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) @@ -2336,35 +2437,15 @@ def _flush_by_key(self, record_key: str) -> None: f"Created new Delta table for {record_key} with {len(combined_table)} records" ) else: - mismatch = self._incompatible_append_column( - delta_table, original_table, combined_table - ) - if mismatch is not None: - column, stored_type, incoming_type = mismatch - raise InputValidationError( - f"Cannot append to the stored table {table_uri!r}: column " - f"{column!r} is stored as {stored_type} but the new rows have " - f"{incoming_type} (input type " - f"{original_table.schema.field(column).type}). " - "The stored rows are unchanged and nothing was written." - ) - overflowing = first_column_out_of_stored_range( - original_table, - [ - f.name - for f in delta_table.schema().fields - if recorded_type(f.metadata) is None - ], - ) - if overflowing is not None: + # The add-time check, against the version just loaded: another + # writer may have committed since the rows were buffered (ITL-1334). + refusal = _append_refusal(delta_table, original_table) + if refusal is not None: + column, reason = refusal raise InputValidationError( f"Cannot append to the stored table {table_uri!r}: column " - f"{overflowing!r} is stored as a signed integer with no " - "recorded Arrow type (a table written before ITL-928), and " - "the new rows have " - f"{original_table.schema.field(overflowing).type} values it " - "cannot hold. The stored rows are unchanged and nothing was " - "written; rebuild the database." + f"{column!r}: {reason}. The stored rows are unchanged and " + "nothing was written." ) # Delta's MERGE matches struct fields by position: the rows are given # the stored struct layout by name first, so an evolved struct (fields @@ -2410,6 +2491,17 @@ def _flush_by_key(self, record_key: str) -> None: f"Appended batch of {len(combined_table)} records to {record_key}" ) + except InputValidationError as e: + # The stored table refuses these rows (``_append_refusal``, + # ``_conformed_to_stored``): they would be refused by every later flush + # too, so they leave the queue, as rows refused when added never enter + # it (ITL-1334). + logger.error(f"Refused batch for {record_key}: {e}") + e.add_note( + f"The {pending_batch.num_rows} rows queued for this table were not " + "written and are no longer queued." + ) + raise except Exception as e: logger.error(f"Error flushing batch for {record_key}: {e}") # Put the tables back in the pending queue @@ -2710,7 +2802,7 @@ def _append_rows( @staticmethod def _incompatible_append_column( - delta_table: deltalake.DeltaTable, batch: pa.Table, written: pa.Table + delta_table: deltalake.DeltaTable, batch: pa.Schema, written: pa.Schema ) -> tuple[str, pa.DataType, pa.DataType] | None: """Find a column whose type in ``batch`` differs from the stored table's. @@ -2735,10 +2827,16 @@ def _incompatible_append_column( (``written``) must be the stored type, so a ``timestamp[ns]`` batch, now written as ``int64``, is refused by a column stored as ``timestamp[us]``. + A column the stored table does not have is not compared (schema evolution). A + type the Delta writer does not convert (``float16``) is compared as it is, so + a ``float16`` column is refused by a stored ``float32`` one, not failed by the + conversion. + Args: delta_table: The loaded stored table. - batch: The rows about to be merged into it, with their own types. - written: ``batch`` as it is written (``to_delta_layout(batch)``). + batch: The schema of the rows about to be merged into it, with their own + types. + written: ``batch`` as it is written (``written_field`` of each column). Returns: ``(column, stored_type, incoming_type)`` for the first column whose @@ -2757,25 +2855,29 @@ def comparable(arrow_type: pa.DataType) -> pa.DataType: def conflict( stored_schema: pa.Schema, rows: pa.Schema ) -> tuple[str, pa.DataType, pa.DataType] | None: - compared = [ - (f.name, _without_null_types(_comparable_storage_type(f.type))) - for f in rows - if recorded.get(f.name) is None - ] - incoming = _as_delta_writer_stores( - pa.schema([pa.field(name, t) for name, t in compared if t is not None]) - ) - for field in incoming: - index = stored_schema.get_field_index(field.name) - if index < 0: + for f in rows: + index = stored_schema.get_field_index(f.name) + if index < 0 or recorded.get(f.name) is not None: + continue + reduced = _without_null_types(_comparable_storage_type(f.type)) + if reduced is None: continue + try: + converted = ( + _as_delta_writer_stores(pa.schema([pa.field(f.name, reduced)])) + .field(0) + .type + ) + except Exception: # noqa: BLE001 # deltalake raises a bare Exception + # A type the writer does not take as it is (float16). + converted = reduced stored_type = comparable(stored_schema.field(index).type) - incoming_type = comparable(field.type) + incoming_type = comparable(converted) if _types_conflict(stored_type, incoming_type): - return field.name, stored_type, incoming_type + return f.name, stored_type, incoming_type return None - for field in batch.schema: + for field in batch: stored_original = recorded.get(field.name) if stored_original is None: continue @@ -2784,7 +2886,7 @@ def conflict( comparable(stored_original), reduced ): return field.name, stored_original, field.type - return conflict(stored, batch.schema) or conflict(stored, written.schema) + return conflict(stored, batch) or conflict(stored, written) @property def base_path(self) -> tuple[str, ...]: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 576eed26f..fca171069 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -406,7 +406,8 @@ def _holds_extension_type(arrow_type: pa.DataType) -> bool: Returns: ``True`` for an extension type at any depth of lists, structs and maps. """ - if isinstance(arrow_type, pa.ExtensionType): + # BaseExtensionType: Python-defined types and Arrow's canonical ones (uuid, json). + if isinstance(arrow_type, pa.BaseExtensionType): return True return any( _holds_extension_type(arrow_type.field(i).type) @@ -415,10 +416,11 @@ def _holds_extension_type(arrow_type: pa.DataType) -> bool: def _holds_map_field_metadata(arrow_type: pa.DataType) -> bool: - """Whether ``arrow_type`` is or nests a map whose key or item field has metadata. + """Whether ``arrow_type`` is or nests a map with field metadata at any depth below + it: on its key or item field, or on a field inside them. - The connector's metadata record (``_serialize_field_meta_tree``) does not cover a - map's key and item fields, so such metadata would read back dropped (ITL-1334). + The connector's metadata record (``_serialize_field_meta_tree``) does not descend + into a map, so such metadata would read back dropped (ITL-1334). Args: arrow_type: The column's Arrow type. @@ -426,16 +428,26 @@ def _holds_map_field_metadata(arrow_type: pa.DataType) -> bool: Returns: ``True`` for such a map at any depth of lists, structs and maps. """ - if pa.types.is_map(arrow_type) and ( - arrow_type.key_field.metadata or arrow_type.item_field.metadata - ): - return True + if pa.types.is_map(arrow_type): + return any( + field.metadata or _holds_nested_field_metadata(field.type) + for field in (arrow_type.key_field, arrow_type.item_field) + ) return any( _holds_map_field_metadata(arrow_type.field(i).type) for i in range(arrow_type.num_fields) ) +def _holds_nested_field_metadata(arrow_type: pa.DataType) -> bool: + """Whether a field nested in ``arrow_type``, at any depth, has metadata.""" + return any( + arrow_type.field(i).metadata + or _holds_nested_field_metadata(arrow_type.field(i).type) + for i in range(arrow_type.num_fields) + ) + + class SpiralDBConnector: """DBConnectorProtocol implementation backed by SpiralDB (pyspiral). @@ -1093,8 +1105,8 @@ def unstorable_column_reason( ) if _holds_map_field_metadata(arrow_type): return ( - "the connector does not keep the field metadata of a map's key and " - "item, so it would read back without it" + "the connector does not keep field metadata below a map (on its key " + "or item, or inside them), so it would read back without it" ) return None diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index f7e858160..9004fac66 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -277,16 +277,13 @@ def add_context(self, node_label: str | None = None) -> None: def __str__(self) -> str: node = f"node {self.node_label!r}: " if self.node_label is not None else "" - # Delta refuses only what no database but the in-memory one keeps (ITL-1334). - instead = ( - "an InMemoryArrowDatabase" - if self.database_kind == "DeltaTableDatabase" - else "an InMemoryArrowDatabase or a DeltaTableDatabase" - ) return ( f"{node}a {self.database_kind} database cannot store column " f"{self.column!r} of Arrow type {self.arrow_type}: {self.reason}. " - f"Use {instead} instead." + # The in-memory database keeps every type; which others keep this one is + # on the generated page (ITL-1334), so no hint names one that refuses it. + "Use an InMemoryArrowDatabase instead; docs/reference/database-types.md " + "lists what each database keeps." ) diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index c8a230910..bcb5f2fd3 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -19,7 +19,12 @@ import pytest from orcapod.errors import InputValidationError, UnstorableColumnError -from tests.test_databases.type_matrix import map_of_fields, open_database +from tests.test_databases.type_matrix import ( + expected_field, + field_difference, + map_of_fields, + open_database, +) PATH = ("t",) I64 = pa.int64() @@ -138,15 +143,24 @@ def test_an_append_with_other_field_attributes_is_refused( back = db.get_all_records(PATH, record_id_column="id") assert _values(back) == _values(first) assert back is not None - assert back.schema.field("x").equals( - first.schema.field("x").with_type(back.schema.field("x").type), - check_metadata=True, - ) + _assert_kept_field(first, back) if database == "Delta": with open_database(database, tmp_path) as fresh: - assert _values(fresh.get_all_records(PATH, record_id_column="id")) == ( - _values(first) - ) + again = fresh.get_all_records(PATH, record_id_column="id") + assert _values(again) == _values(first) + assert again is not None + _assert_kept_field(first, again) + + +def _assert_kept_field(written: pa.Table, back: pa.Table) -> None: + """``x`` reads back as written (every nested name, nullability and metadata, a + map's ``keys_sorted``), or as its large variant, compared field by field.""" + exact = written.schema.field("x") + got = back.schema.field("x") + assert ( + field_difference(exact, got, "x") is None + or field_difference(expected_field(exact), got, "x") is None + ), field_difference(expected_field(exact), got, "x") @pytest.mark.parametrize("database", DATABASES) diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py new file mode 100644 index 000000000..95ed7407a --- /dev/null +++ b/tests/test_databases/test_delta_append_preflight.py @@ -0,0 +1,313 @@ +"""What a Delta flush would refuse is refused when the rows are added (ITL-1334). + +``add_records`` checks the rows against the stored table before buffering anything +(``_append_refusal``): the refusal names the column, nothing is queued, and the stored +rows read back unchanged. The flush repeats the check against the version it loads, +since another writer may commit in between; rows it refuses leave the queue, so no +later flush fails on them again. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InputValidationError, UnstorableColumnError +from tests.test_databases.type_matrix import map_of_fields + +PATH = ("t",) +I64 = pa.int64() + + +def _rows(ids: list[bytes], **columns: tuple[Any, list[Any]]) -> pa.Table: + """``id`` then each column, given as (type or field, values).""" + fields = [pa.field("id", pa.large_binary())] + arrays = [pa.array(ids, pa.large_binary())] + for name, (kind, values) in columns.items(): + field = ( + kind.with_name(name) if isinstance(kind, pa.Field) else pa.field(name, kind) + ) + fields.append(field) + arrays.append(pa.array(values, field.type)) + return pa.Table.from_arrays(arrays, schema=pa.schema(fields)) + + +def _struct(*fields: Any) -> Any: + return pa.struct(list(fields)) + + +A_NOT_NULL = pa.field("a", I64, nullable=False) +B = pa.field("b", I64) + +# (stored rows, appended rows, what the refusal names): two columns where it matters. +REFUSED: dict[str, tuple[pa.Table, pa.Table, str]] = { + "a non-nullable struct field omitted": ( + _rows([b"1", b"2"], x=(_struct(A_NOT_NULL, B), [{"a": 1, "b": 2}] * 2)), + _rows([b"3", b"4"], x=(_struct(B), [{"b": 3}, {"b": None}])), + r"'x': x\.a is stored as non-nullable, and the rows omit it", + ), + "a non-nullable struct field omitted in a list": ( + _rows([b"1"], x=(pa.large_list(_struct(A_NOT_NULL, B)), [[{"a": 1, "b": 2}]])), + _rows([b"3"], x=(pa.large_list(_struct(B)), [[{"b": 3}]])), + r"'x': x\[\]\.a is stored as non-nullable", + ), + "a non-nullable struct field omitted in a map item": ( + _rows( + [b"1"], + x=( + pa.map_(pa.large_string(), _struct(A_NOT_NULL, B)), + [[("k", {"a": 1, "b": 2})]], + ), + ), + _rows([b"3"], x=(pa.map_(pa.large_string(), _struct(B)), [[("k", {"b": 3})]])), + r"'x': x\.item\.a is stored as non-nullable", + ), + "a non-nullable column omitted": ( + _rows( + [b"1", b"2"], + x=(pa.field("x", I64, nullable=False), [1, 2]), + y=(I64, [1, 2]), + ), + _rows([b"3", b"4"], y=(I64, [3, 4])), + r"'x': x is stored as non-nullable, and the rows omit it", + ), + "a null in a non-nullable column": ( + _rows( + [b"1", b"2"], + x=(pa.field("x", I64, nullable=False), [1, 2]), + y=(I64, [1, 2]), + ), + _rows([b"3", b"4"], x=(I64, [3, None]), y=(I64, [3, 4])), + r"'x': x is stored as non-nullable, and the rows hold a null", + ), + "another type": ( + _rows([b"1", b"2"], x=(I64, [1, 2]), y=(I64, [1, 2])), + _rows([b"3", b"4"], x=(pa.float64(), [3.0, 4.0]), y=(I64, [3, 4])), + r"'x': it is stored as int64 but the new rows have double", + ), + "float16 into a float32 column": ( + _rows([b"1", b"2"], x=(pa.float32(), [1.0, 2.0])), + _rows([b"3", b"4"], x=(pa.float16(), [3.0, 4.0])), + r"'x': it is stored as float but the new rows have halffloat", + ), +} + + +@pytest.mark.parametrize("case", sorted(REFUSED)) +def test_an_append_the_flush_would_refuse_is_refused_when_added( + tmp_path: Path, case: str +) -> None: + first, second, match = REFUSED[case] + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, first, record_id_column="id", flush=True) + with pytest.raises(InputValidationError, match=match): + db.add_records(PATH, second, record_id_column="id") + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] # nothing queued + db.flush() + for reader in (db, DeltaTableDatabase(tmp_path)): + back = reader.get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").to_pylist() == first.sort_by("id").to_pylist() + + +# The controls: what the flush takes is not refused. +KEPT: dict[str, tuple[pa.Table, pa.Table]] = { + "a nullable struct field omitted": ( + _rows([b"1"], x=(_struct(pa.field("a", I64), B), [{"a": 1, "b": 2}])), + _rows([b"3"], x=(_struct(B), [{"b": 3}])), + ), + "a nullable column omitted": ( + _rows([b"1"], x=(I64, [1]), y=(I64, [1])), + _rows([b"3"], y=(I64, [3])), + ), + "a nullable type without nulls into a non-nullable column": ( + _rows([b"1"], x=(pa.field("x", I64, nullable=False), [1])), + _rows([b"3"], x=(I64, [3])), + ), + "a new float16 column": ( + _rows([b"1"], y=(I64, [1])), + _rows([b"3"], y=(I64, [3]), x=(pa.float16(), [None])), + ), +} + + +@pytest.mark.parametrize("case", sorted(KEPT)) +def test_an_append_the_flush_takes_is_kept(tmp_path: Path, case: str) -> None: + first, second = KEPT[case] + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, first, record_id_column="id", flush=True) + db.add_records(PATH, second, record_id_column="id", flush=True) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None and back.num_rows == 2 + if case == "a new float16 column": + assert back.schema.field("x").type == pa.float16() + + +@pytest.mark.parametrize( + "arrow_type", + [ + pa.struct([]), + pa.struct([pa.field("e", pa.struct([]))]), + pa.large_list(pa.struct([])), + map_of_fields( + pa.field("key", pa.large_string(), False), pa.field("value", pa.struct([])) + ), + ], + ids=["top level", "in a struct", "in a list", "in a map item"], +) +def test_a_struct_with_no_fields_is_refused_before_buffering( + tmp_path: Path, arrow_type: Any +) -> None: + """A Parquet file stores values in leaf columns only, so Delta cannot write it.""" + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match="'x'.*a struct with no fields"): + db.add_records( + PATH, + pa.table( + { + "id": pa.array([b"1"], pa.large_binary()), + "x": pa.nulls(1, arrow_type), + } + ), + record_id_column="id", + ) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize( + "conflicting", + [ + _rows([b"9"], x=(pa.float64(), [9.0])), + _rows([b"9"], x=(pa.field("x", I64, metadata={"unit": "s"}), [9])), + ], + ids=["another type", "other field metadata"], +) +def test_the_flush_refuses_rows_another_writer_made_conflict( + tmp_path: Path, conflicting: pa.Table +) -> None: + """Rows queued while nothing was stored; another writer then stores the column + otherwise. The flush refuses them against the version it loads, drops them from + the queue, and says so; the other writer's rows stand.""" + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _rows([b"1", b"2"], x=(I64, [1, 2])), record_id_column="id") + DeltaTableDatabase(tmp_path).add_records( + PATH, conflicting, record_id_column="id", flush=True + ) + with pytest.raises(InputValidationError, match="'x'") as raised: + db.flush() + refusal = raised.value + assert any("no longer queued" in note for note in getattr(refusal, "__notes__", [])) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # nothing left to refuse + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None and back.column("id").to_pylist() == [b"9"] + + +def test_null_parts_typed_partly_by_each_schema_append(tmp_path: Path) -> None: + """A ``null`` part needs a type from the stored table or a pending batch, not every + part from one of them; each is written as typed nulls.""" + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=(_struct(pa.field("a", I64)), [{"a": 1}])), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _rows([b"2"], x=(_struct(pa.field("a", pa.null()), B), [{"a": None, "b": 2}])), + record_id_column="id", + ) + db.add_records( + PATH, + _rows( + [b"3"], + x=( + _struct(pa.field("a", pa.null()), pa.field("b", pa.null())), + [{"a": None, "b": None}], + ), + ), + record_id_column="id", + schema_handling="merge", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.schema.field("x").type == _struct(pa.field("a", I64), B) + assert back.sort_by("id").column("x").to_pylist() == [ + {"a": 1, "b": None}, + {"a": None, "b": 2}, + {"a": None, "b": None}, + ] + + +@pytest.mark.parametrize( + "appended", + [ + _struct(pa.field("a", pa.null()), B), + pa.large_list(_struct(pa.field("a", pa.null()), B)), + ], + ids=["top level", "in a list"], +) +def test_a_null_child_of_an_evolving_struct_appends( + tmp_path: Path, appended: Any +) -> None: + """Delta's MERGE panicked on a ``null`` child of a struct that gains a field + (pre-existing); the child is written as typed nulls of its stored type.""" + stored_type = _struct(pa.field("a", I64)) + in_list = pa.types.is_large_list(appended) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows( + [b"1"], + x=( + pa.large_list(stored_type) if in_list else stored_type, + [[{"a": 1}]] if in_list else [{"a": 1}], + ), + ), + record_id_column="id", + flush=True, + ) + value = {"a": None, "b": 2} + db.add_records( + PATH, + _rows([b"2"], x=(appended, [[value]] if in_list else [value])), + record_id_column="id", + flush=True, + ) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + rows: list[Any] = back.sort_by("id").column("x").to_pylist() + if in_list: + rows = [cast(list[Any], r)[0] for r in rows] + assert rows == [{"a": 1, "b": None}, {"a": None, "b": 2}] + + +def test_a_null_path_no_schema_types_is_refused_naming_every_path( + tmp_path: Path, +) -> None: + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=(_struct(pa.field("a", I64)), [{"a": 1}])), + record_id_column="id", + flush=True, + ) + with pytest.raises(UnstorableColumnError, match=r"'x\.b', 'x\.c'"): + db.add_records( + PATH, + _rows( + [b"2"], + x=( + _struct(*(pa.field(n, pa.null()) for n in "abc")), + [{"a": None, "b": None, "c": None}], + ), + ), + record_id_column="id", + ) diff --git a/tests/test_databases/test_delta_arrow_type_roundtrip.py b/tests/test_databases/test_delta_arrow_type_roundtrip.py index 61e998369..f6d014abc 100644 --- a/tests/test_databases/test_delta_arrow_type_roundtrip.py +++ b/tests/test_databases/test_delta_arrow_type_roundtrip.py @@ -425,14 +425,14 @@ def test_nanoseconds_cannot_be_appended_to_a_table_written_before_the_fix( pa.table({"__record_id": pa.array([b"a"], pa.large_binary()), "c": column}), ) store = DeltaTableDatabase(tmp_path) - store.add_records( - ("t",), - pa.table({"id": pa.array([b"b"], pa.large_binary()), "c": column}), - record_id_column="id", - ) - + # Refused when added, before anything is queued (ITL-1334). with pytest.raises(InputValidationError, match="'c'"): - store.flush() + store.add_records( + ("t",), + pa.table({"id": pa.array([b"b"], pa.large_binary()), "c": column}), + record_id_column="id", + ) + store.flush() @pytest.mark.parametrize( @@ -456,14 +456,14 @@ def test_an_append_of_another_type_is_refused( record_id_column="id", flush=True, ) - store.add_records( - ("t",), - pa.table({"id": pa.array([b"b"], pa.large_binary()), "c": incoming}), - record_id_column="id", - ) - + # Refused when added, before anything is queued (ITL-1334). with pytest.raises(InputValidationError, match="'c'"): - store.flush() + store.add_records( + ("t",), + pa.table({"id": pa.array([b"b"], pa.large_binary()), "c": incoming}), + record_id_column="id", + ) + store.flush() def test_unsigned_rows_append_to_a_signed_column_without_a_recorded_type( @@ -517,19 +517,19 @@ def test_an_unsigned_value_beyond_an_unrecorded_signed_column_is_refused( ), ) store = DeltaTableDatabase(tmp_path) - store.add_records( - ("t",), - pa.table( - { - "id": pa.array([b"b"], pa.large_binary()), - "c": pa.array([3_000_000_000], pa.uint32()), - } - ), - record_id_column="id", - ) - + # Refused when added, before anything is queued (ITL-1334). with pytest.raises(InputValidationError, match="'c'"): - store.flush() + store.add_records( + ("t",), + pa.table( + { + "id": pa.array([b"b"], pa.large_binary()), + "c": pa.array([3_000_000_000], pa.uint32()), + } + ), + record_id_column="id", + ) + store.flush() read = DeltaTableDatabase(tmp_path).get_all_records(("t",)) assert read is not None assert read.column("c").to_pylist() == [1] @@ -661,3 +661,31 @@ def test_a_new_all_null_column_is_refused_naming_it( ) with pytest.raises(UnstorableColumnError, match="'n'"): db.add_records(("t",), table, record_id_column="id") + + +@pytest.mark.parametrize( + "arrow_type", + [pa.decimal256(40, 2), pa.struct([]), pa.large_list(pa.int64())], + ids=["decimal256", "empty struct", "large_list"], +) +def test_a_refusal_suggests_only_the_database_that_keeps_every_type( + arrow_type: pa.DataType, +) -> None: + """A refusal never suggests a database that refuses the same column (CodeRabbit + on PR 471): it names the in-memory database, which keeps every type, and the page + that says what each other database keeps.""" + from orcapod.errors import UnstorableColumnError + + message = str( + UnstorableColumnError( + database_kind="ConnectorArrowDatabase", + column="x", + arrow_type=arrow_type, + reason="r", + ) + ) + assert message.endswith( + "Use an InMemoryArrowDatabase instead; docs/reference/database-types.md " + "lists what each database keeps." + ) + assert "DeltaTableDatabase" not in message diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 04de1c824..84bf01eab 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -263,6 +263,10 @@ def test_store_read_error_is_raised_with_a_note_per_other_failed_batch( ): """The ``OrcapodDatabaseReadError`` is raised and the refused batch is noted on it.""" other = ("results", "u") + db = DeltaTableDatabase(base_path=base) + # Queued first, while nothing is stored at ``other``; then another writer + # stores x as int64 there, so the flush refuses these rows (ITL-1334). + db.add_records(other, rows([b"b"], pa.array([2.0])), record_id_column="rid") stored.add_records( other, rows([b"a"], pa.array([1], pa.int64())), @@ -270,9 +274,6 @@ def test_store_read_error_is_raised_with_a_note_per_other_failed_batch( flush=True, ) unsupported_reader_feature(base) - db = DeltaTableDatabase(base_path=base) - # Queued first: refused at flush, because x is stored as int64. - db.add_records(other, rows([b"b"], pa.array([2.0])), record_id_column="rid") # Queued second: its table's log cannot be loaded. db.add_records( PATH, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" @@ -288,7 +289,10 @@ def test_store_read_error_is_raised_with_a_note_per_other_failed_batch( assert len(notes) == 1 assert "results/u" in notes[0] assert "InputValidationError" in notes[0] - # Both failed batches stay queued, so the next flush fails the same way. + # The batch the stored table refuses leaves the queue (every later flush + # would refuse it too); the one whose table cannot be read stays queued, so + # the next flush fails the same way (ITL-1334). + assert db._pending_batches.keys() == {"results/t"} # pyright: ignore[reportPrivateUsage] with pytest.raises(OrcapodDatabaseReadError): db.flush() diff --git a/tests/test_databases/test_delta_read_your_writes.py b/tests/test_databases/test_delta_read_your_writes.py index fd0ee7e12..841276d4f 100644 --- a/tests/test_databases/test_delta_read_your_writes.py +++ b/tests/test_databases/test_delta_read_your_writes.py @@ -17,7 +17,11 @@ import pytest from orcapod.databases import DeltaTableDatabase -from orcapod.errors import OrcapodDatabaseReadError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) PATH = ("table",) SCOPE = "scope" @@ -403,30 +407,48 @@ def test_read_before_flush_matches_read_after_flush_across_schema_change( assert before.to_pylist() == after.to_pylist() +@pytest.mark.parametrize("method", list(READS_AC)) +def test_read_of_stored_and_pending_rows_with_different_types_raises( + tmp_path: Path, method: str +) -> None: + """A column whose stored and pending types differ is never widened: the read raises. + + Delta stores both timestamp units as microseconds, so the add accepts the rows. + """ + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _table("a", pa.array([1], pa.timestamp("us"))), flush=True) + db.add_records(PATH, _table("c", pa.array([3], pa.timestamp("ms")))) + + with pytest.raises(pa.ArrowTypeError, match="Field x has incompatible types"): + _ = READS_AC[method](db) + + @pytest.mark.parametrize( ("stored_x", "pending_x"), [ (pa.array([1], pa.int64()), pa.array([3], pa.int32())), (pa.array([1], pa.int64()), pa.array(["t"], pa.large_string())), - (pa.array([1], pa.timestamp("us")), pa.array([3], pa.timestamp("ms"))), ( pa.array([1], pa.decimal128(10, 2)), pa.array([3], pa.decimal128(12, 2)), ), ], - ids=["int64_vs_int32", "int64_vs_string", "timestamp_unit", "decimal_precision"], + ids=["int64_vs_int32", "int64_vs_string", "decimal_precision"], ) @pytest.mark.parametrize("method", list(READS_AC)) -def test_read_of_stored_and_pending_rows_with_different_types_raises( +def test_rows_of_another_type_than_the_stored_column_are_refused_when_added( tmp_path: Path, method: str, stored_x: pa.Array[Any], pending_x: pa.Array[Any] ) -> None: - """A column whose stored and pending types differ is never widened: the read raises.""" + """They used to be queued, make reads raise and fail the flush; now nothing is + queued, and the read gives the stored rows as stored (ITL-1334).""" db = DeltaTableDatabase(tmp_path) db.add_records(PATH, _table("a", stored_x), flush=True) - db.add_records(PATH, _table("c", pending_x)) + with pytest.raises(InputValidationError, match="'x': it is stored as"): + db.add_records(PATH, _table("c", pending_x)) - with pytest.raises(pa.ArrowTypeError, match="Field x has incompatible types"): - _ = READS_AC[method](db) + back = READS_AC[method](db) + assert back is not None and back.num_rows == 1 + assert back.schema.field("x").type == stored_x.type def test_a_new_null_typed_column_is_refused_before_it_is_pending( diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index ffa65ad94..877b1b32f 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -152,7 +152,9 @@ def test_omitting_a_non_nullable_stored_field_is_refused( record_id_column="id", flush=True, ) - with pytest.raises(InputValidationError, match="'x'.*'b'.*non-nullable"): + with pytest.raises( + InputValidationError, match=r"'x': x\.b is stored as non-nullable" + ): db.add_records( PATH, _rows([b"2"], x=([{"a": 3}], _struct(("a", I64)))), diff --git a/tests/test_databases/test_spiraldb_connector_fake.py b/tests/test_databases/test_spiraldb_connector_fake.py index fb8475594..a40568ff4 100644 --- a/tests/test_databases/test_spiraldb_connector_fake.py +++ b/tests/test_databases/test_spiraldb_connector_fake.py @@ -29,6 +29,7 @@ from orcapod.utils import arrow_utils from orcapod.sources import ArrowTableSource, SpiralDBTableSource from tests.test_databases import fake_pyspiral +from tests.test_databases.type_matrix import map_of_fields _NESTED = pa.schema( [ @@ -639,3 +640,52 @@ def test_a_fixed_size_list_with_non_null_items_and_a_null_row_reads_back( assert back is not None assert back.schema.field("f").type == pa.list_(item, 2) assert back.sort_by("id").column("f").to_pylist() == [[1, 2], None, [5, 6]] + + @pytest.mark.parametrize( + "arrow_type", + [ + pa.uuid(), + pa.json_(), + pa.large_list(pa.uuid()), + pa.struct([pa.field("j", pa.json_())]), + ], + ids=["uuid", "json", "list of uuid", "struct of json"], + ) + def test_an_arrow_canonical_extension_type_is_refused(self, database, arrow_type): + """Arrow's own extension types (``BaseExtensionType``, not ``ExtensionType``) + would read back as their storage type too (CodeRabbit on PR 471).""" + from orcapod.errors import UnstorableColumnError + + table = pa.table( + {"id": pa.array([b"a"], pa.large_binary()), "v": pa.nulls(1, arrow_type)} + ) + with pytest.raises(UnstorableColumnError, match="'v'.*storage type"): + database.add_records(("t",), table, record_id_column="id", flush=True) + + @pytest.mark.parametrize( + "item", + [ + pa.field("value", pa.int64(), metadata={"unit": "m"}), + pa.field( + "value", pa.struct([pa.field("a", pa.int64(), metadata={"u": "m"})]) + ), + pa.field( + "value", + pa.large_list(pa.field("item", pa.int64(), metadata={"u": "m"})), + ), + ], + ids=["on the item", "inside an item struct", "inside an item list"], + ) + def test_field_metadata_below_a_map_is_refused(self, database, item): + """The connector's metadata record does not descend into a map, so such + metadata would read back dropped (CodeRabbit on PR 471).""" + from orcapod.errors import UnstorableColumnError + + map_type: Any = map_of_fields( + pa.field("key", pa.large_string(), nullable=False), item + ) + table = pa.table( + {"id": pa.array([b"a"], pa.large_binary()), "m": pa.nulls(1, map_type)} + ) + with pytest.raises(UnstorableColumnError, match="'m'.*below a map"): + database.add_records(("t",), table, record_id_column="id", flush=True) diff --git a/tests/test_databases/test_unstorable_columns.py b/tests/test_databases/test_unstorable_columns.py index 7fbb557ca..4619b9de8 100644 --- a/tests/test_databases/test_unstorable_columns.py +++ b/tests/test_databases/test_unstorable_columns.py @@ -103,7 +103,8 @@ def test_function_node_on_sqlite_refused_before_anything_runs( assert "SQLiteConnector" in message assert EXECUTOR_INFO in message assert "InMemoryArrowDatabase" in message - assert "DeltaTableDatabase" in message + # Only the database that keeps every type is suggested (CodeRabbit on PR 471). + assert "docs/reference/database-types.md" in message # Nothing ran and nothing was written. assert CALLS == [] assert database.list_table_paths() == [] @@ -384,7 +385,7 @@ def test_function_node_refused_before_anything_runs(self, spiral_database): assert err.database_kind == "SpiralDBConnector" assert err.column == "__input_data_hash" assert "'__' prefix" in err.reason - assert "DeltaTableDatabase" in str(err) + assert "InMemoryArrowDatabase" in str(err) assert CALLS == [] assert spiral_database.list_table_paths() == [] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 4834858b6..ce00684e8 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -148,10 +148,24 @@ def build(root: Path) -> tuple[Any, Any, list[Any], list[Any]]: dt.datetime(2026, 1, 2), dt.datetime(2026, 3, 4), ] -_TSZ = [t.replace(tzinfo=dt.timezone.utc) for t in _TS] _DATES = [dt.date(2026, 1, 1), dt.date(2026, 1, 2), dt.date(1999, 12, 31)] _TIMES = [dt.time(1, 2, 3), dt.time(4, 5, 6), dt.time(23, 59, 59)] _DURATIONS = [dt.timedelta(seconds=1), dt.timedelta(seconds=2), dt.timedelta(days=1)] +_PER_SECOND = {"s": 1, "ms": 1_000, "us": 1_000_000, "ns": 1_000_000_000} + + +def _ticks(unit: str, seconds: list[int]) -> list[int]: + """``seconds`` as integer ticks of ``unit``, each off the whole second by a + different number of ticks (the last ``unit`` digit included), so a conversion + that loses precision (nanoseconds to microseconds) changes a value.""" + per_second = _PER_SECOND[unit] + offsets = [0, 0, 0] if unit == "s" else [1, per_second // 3 + 7, per_second - 1] + return [s * per_second + o for s, o in zip(seconds, offsets)] + + +_TS_SECONDS = [int(t.replace(tzinfo=dt.timezone.utc).timestamp()) for t in _TS] +_TIME_SECONDS = [t.hour * 3600 + t.minute * 60 + t.second for t in _TIMES] +_DURATION_SECONDS = [int(d.total_seconds()) for d in _DURATIONS] def _files(root: Path) -> list[Any]: @@ -258,19 +272,23 @@ def _upaths(root: Path) -> list[Any]: Row("null", "null", _plain(pa.null(), [None, None, None])), Row("date32", "temporal", _plain(pa.date32(), _DATES)), Row("date64", "temporal", _plain(pa.date64(), _DATES)), - Row("time32[s]", "temporal", _plain(pa.time32("s"), _TIMES)), - Row("time32[ms]", "temporal", _plain(pa.time32("ms"), _TIMES)), - Row("time64[us]", "temporal", _plain(pa.time64("us"), _TIMES)), - Row("time64[ns]", "temporal", _plain(pa.time64("ns"), _TIMES)), + Row("time32[s]", "temporal", _plain(pa.time32("s"), _ticks("s", _TIME_SECONDS))), + Row("time32[ms]", "temporal", _plain(pa.time32("ms"), _ticks("ms", _TIME_SECONDS))), + Row("time64[us]", "temporal", _plain(pa.time64("us"), _ticks("us", _TIME_SECONDS))), + Row("time64[ns]", "temporal", _plain(pa.time64("ns"), _ticks("ns", _TIME_SECONDS))), *( - Row(f"timestamp[{u}]", "temporal", _plain(pa.timestamp(u), _TS)) + Row( + f"timestamp[{u}]", + "temporal", + _plain(pa.timestamp(u), _ticks(u, _TS_SECONDS)), + ) for u in ("s", "ms", "us", "ns") ), *( Row( f"timestamp[{u}, tz=UTC]", "temporal", - _plain(pa.timestamp(u, tz="UTC"), _TSZ), + _plain(pa.timestamp(u, tz="UTC"), _ticks(u, _TS_SECONDS)), ) for u in ("s", "ms", "us", "ns") ), @@ -278,12 +296,16 @@ def _upaths(root: Path) -> list[Any]: Row( f"timestamp[{u}, tz=Europe/Berlin]", "temporal", - _plain(pa.timestamp(u, tz="Europe/Berlin"), _TSZ), + _plain(pa.timestamp(u, tz="Europe/Berlin"), _ticks(u, _TS_SECONDS)), ) for u in ("s", "ms", "us", "ns") ), *( - Row(f"duration[{u}]", "temporal", _plain(pa.duration(u), _DURATIONS)) + Row( + f"duration[{u}]", + "temporal", + _plain(pa.duration(u), _ticks(u, _DURATION_SECONDS)), + ) for u in ("s", "ms", "us", "ns") ), Row("string", "string and binary", _plain(pa.string(), ["a", "bc", ""])), @@ -350,6 +372,16 @@ def _upaths(root: Path) -> list[Any]: [{"a": 1, "b": "x"}, {"a": None, "b": "y"}, {"a": 3, "b": ""}], ), ), + Row( + "struct<> (no fields)", + "struct and map", + _plain(pa.struct([]), [{}, {}, {}]), + ), + Row( + "uuid (Arrow's canonical extension type)", + "struct and map", + _plain(pa.uuid(), [uuid.UUID(int=i + 1).bytes for i in range(3)]), + ), Row( "struct[2]>", "struct and map", @@ -428,6 +460,17 @@ def _upaths(root: Path) -> list[Any]: [[("a", 1), ("b", 2)], [], [("c", None)]], ), ), + Row( + "map> (metadata inside the item)", + "names and metadata", + _plain( + pa.map_( + pa.string(), + pa.struct([pa.field("a", pa.int64(), metadata={"unit": "m"})]), + ), + [[("a", {"a": 1})], [], [("c", {"a": None})]], + ), + ), Row( "int64 {unit: s} (field metadata)", "names and metadata", @@ -613,11 +656,11 @@ def _names_a_column(error: BaseException) -> bool: return any(f"'{c}'" in text or f'"{c}"' in text for c in ("x", "y")) -def _expected_field(field: "pa.Field[Any]") -> "pa.Field[Any]": +def expected_field(field: "pa.Field[Any]") -> "pa.Field[Any]": return field.with_type(normalize_to_large_types(field.type, keep_null=True)) -def _field_difference(a: "pa.Field[Any]", b: "pa.Field[Any]", path: str) -> str | None: +def field_difference(a: "pa.Field[Any]", b: "pa.Field[Any]", path: str) -> str | None: """The first difference between two fields, at any depth, or ``None``. Everything that makes a field counts: its name, nullability and metadata, and its @@ -661,8 +704,8 @@ def _type_difference(a: Any, b: Any, path: str) -> str | None: if t.is_map(a): if a.keys_sorted != b.keys_sorted: return f"{path}: keys_sorted {a.keys_sorted} -> {b.keys_sorted}" - return _field_difference(a.key_field, b.key_field, f"{path}.key") or ( - _field_difference(a.item_field, b.item_field, f"{path}.item") + return field_difference(a.key_field, b.key_field, f"{path}.key") or ( + field_difference(a.item_field, b.item_field, f"{path}.item") ) if t.is_fixed_size_list(a) and a.list_size != b.list_size: return f"{path}: list size {a.list_size} -> {b.list_size}" @@ -670,13 +713,13 @@ def _type_difference(a: Any, b: Any, path: str) -> str | None: if a.num_fields != b.num_fields: return f"{path}: {a} -> {b}" for i in range(a.num_fields): - found = _field_difference( + found = field_difference( a.field(i), b.field(i), f"{path}.{a.field(i).name}" ) if found: return found return None - return _field_difference(a.value_field, b.value_field, f"{path}[]") + return field_difference(a.value_field, b.value_field, f"{path}[]") def _lengths(array: Any) -> list[int]: @@ -745,10 +788,12 @@ def _with_changed_metadata(field: "pa.Field[Any]") -> "pa.Field[Any]": def _nested_changed(arrow_type: Any) -> Any: """``arrow_type`` with its first nested field's metadata changed, or ``None``.""" t = pa.types - if isinstance(arrow_type, pa.ExtensionType): + if isinstance(arrow_type, pa.BaseExtensionType): return None if t.is_struct(arrow_type): fields = list(arrow_type) + if not fields: + return None return pa.struct([_with_changed_metadata(fields[0]), *fields[1:]]) if t.is_map(arrow_type): return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields @@ -884,10 +929,10 @@ def measure(row: Row, database: str, root: Path) -> Cell: got = back.schema.field(name) # The type written, or its large variant (every Orcapod table is large). want = exact - difference = _field_difference(exact, got, name) + difference = field_difference(exact, got, name) if difference is not None: - want = _expected_field(exact) - if _field_difference(want, got, name) is not None: + want = expected_field(exact) + if field_difference(want, got, name) is not None: problems.append(difference) continue expected = written.column(name) From 146a2f17b7e94c0b6ae38173d4758f036f0417ec Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 17:33:46 -0800 Subject: [PATCH 08/13] fix(databases): Delta compares each column's own type; checks the rows actually queued CodeRabbit on PR 471 (ITL-1334), review of 71f30b14. - _incompatible_append_column: one rule, each column's own type against the type the table holds (record, else stored type); a writer conversion is no longer agreement, so timestamp[ms] rows are refused by a timestamp[us] column (they read back as microseconds). Null-typed parts take the held type at their path (_with_nulls_resolved), so a map's int64 key beside null items is refused (it was written as text). A dictionary compares as its values. Kept: unsigned into a pre-ITL-928 signed column without a record. - The stored-table check runs on the rows that are queued: after duplicates, skip_duplicates and the requested schema_handling (coerce appends again). - A flush refusal drops the handle's cached table and row snapshot. - flush() documents which failed batches stay queued. - Tests: preflight cases for each item; successful appends compare values (float16 with a null); docstrings. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1334.md | 18 +- src/orcapod/databases/delta_lake_databases.py | 196 +++++++++++------- .../test_delta_append_preflight.py | 164 ++++++++++++++- .../test_delta_read_your_writes.py | 25 +-- 4 files changed, 302 insertions(+), 101 deletions(-) diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index d4694e05b..79d47eef3 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -59,13 +59,19 @@ not read the table back), or add a struct field inside a map (Delta's merge cannot); - omit a struct field or a column stored as non-nullable, or hold a null in such a column; - - give a column another type than the stored one, a `float16` into a `float32` column - included. + - give a column another type than the one the table holds, compared by the rows' own + type, not the form Delta's writer converts it to. So `float16` rows are refused by a + `float32` column, `timestamp[ms]` rows by a `timestamp[us]` one (they read back in + microseconds), and a map's keys are compared even beside `null` items (an `int64` key + was written as text). - These used to fail the flush and stay queued, so every later flush failed again. The - flush repeats the check against the version it loads, since another writer may commit - in between; rows it refuses are dropped from the queue, and the error says so. A nested - field an append makes nullable reads back nullable. (ITL-1334) + The check runs on the rows that are queued: after duplicates are dropped, rows + `skip_duplicates` skips, and the requested `schema_handling`. These rows used to fail the + flush and stay queued, so every later flush failed again. The flush repeats the check + against the version it loads, since another writer may commit in between. Rows it + refuses are dropped from the queue, the error says so, and the handle drops what it + had cached of the table. Rows failing for any other reason stay queued. A nested field + an append makes nullable reads back nullable. (ITL-1334) - **`DeltaTableDatabase` refuses a struct with no fields at any depth:** a Parquet file stores values in leaf columns only, so the flush failed. (ITL-1334) - **`SpiralDBConnector` refuses field metadata below a map, and Arrow's canonical extension diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 4a7b705f8..6f7883dc4 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -148,8 +148,8 @@ def _allows_http(storage_options: Mapping[str, str]) -> bool: def _comparable_storage_type(arrow_type: pa.DataType) -> pa.DataType: """Return ``arrow_type`` reduced to what the append check compares. - Extension types are replaced by their storage type and every nested field is - made nullable, at every depth. The result is used only to compare a batch + Extension types are replaced by their storage type, a dictionary by its value + type, and every nested field is made nullable, at every depth. The result is used only to compare a batch with a stored table (ITL-884); it is never stored, so dropping nested non-null flags here changes no schema or hash. @@ -161,6 +161,11 @@ def _comparable_storage_type(arrow_type: pa.DataType) -> pa.DataType: """ if isinstance(arrow_type, pa.ExtensionType): return _comparable_storage_type(arrow_type.storage_type) + if pa.types.is_dictionary(arrow_type): + # The Delta writer decodes a dictionary: its values are what is stored. + return _comparable_storage_type( + arrow_utils.normalize_to_large_types(arrow_type.value_type) + ) if pa.types.is_struct(arrow_type): return pa.struct( [pa.field(f.name, _comparable_storage_type(f.type)) for f in arrow_type] @@ -192,7 +197,8 @@ def _without_null_types(arrow_type: pa.DataType) -> pa.DataType | None: """Return ``arrow_type`` without the parts typed ``null``, or ``None`` if none is left. A ``null``-typed value fits a column of any type, and Delta has no ``null`` - type to compare it with, so the append check leaves it out at every depth: a + type, so the storability check (``delta_unstorable_reason``) leaves it out at + every depth: a ``null`` struct field is dropped (its siblings are still compared, inside lists and maps too), and a type that is ``null``, or whose list items or map keys or values are entirely ``null``, is not compared. @@ -660,6 +666,59 @@ def _append_refusal( return None +def _with_nulls_resolved(incoming: Any, held: Any) -> Any: + """``incoming`` with each ``null``-typed part replaced by the type ``held`` has at + the same path, so the parts beside it are still compared (ITL-1334). + + Struct fields are matched by name; list items and map keys and items followed. + A ``null`` part at a path ``held`` has no type for stays ``null`` (refused by + ``add_records`` before this is reached). + + Args: + incoming: A type reduced by ``_comparable_storage_type``. + held: The type the table holds, reduced the same way, or ``None``. + + Returns: + ``incoming``, its ``null`` parts resolved. + """ + t = pa.types + if held is None: + return incoming + if t.is_null(incoming): + return held + if t.is_struct(incoming) and t.is_struct(held): + known = {f.name: f.type for f in held} + return pa.struct( + [ + f.with_type(_with_nulls_resolved(f.type, known.get(f.name))) + for f in incoming + ] + ) + if t.is_map(incoming) and t.is_map(held): + return pa.map_( # pyright: ignore[reportCallIssue] # pyarrow takes key/item fields + incoming.key_field.with_type( + _with_nulls_resolved(incoming.key_type, held.key_type) + ), + incoming.item_field.with_type( + _with_nulls_resolved(incoming.item_type, held.item_type) + ), + keys_sorted=incoming.keys_sorted, + ) + lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) + if any(k(incoming) for k in lists) and any(k(held) for k in lists): + # cast: the type guards above narrow the types in the stubs' terms. + list_type: Any = incoming + item = list_type.value_field.with_type( + _with_nulls_resolved(list_type.value_type, cast(Any, held).value_type) + ) + if t.is_large_list(list_type): + return pa.large_list(item) + if t.is_list(list_type): + return pa.list_(item) + return pa.list_(item, list_type.list_size) + return incoming + + def _untyped_null_paths(incoming: Any, given: Any, path: str) -> list[str]: """Every path where ``incoming`` is ``null``-typed and ``given`` has no type. @@ -1704,7 +1763,6 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) self._refuse_untyped_null_columns(record_path, records.schema) - self._refuse_unmergeable_append(record_path, records) # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) @@ -1727,10 +1785,15 @@ def add_records( record_path, filtered_table, schema_handling ) - # Step 5: Add to pending batch (no overwrite logic needed) + # Step 5: what the flush would refuse is refused now, on the rows that are + # queued: after duplicates are dropped and any requested schema handling + # (ITL-1334). + self._refuse_unmergeable_append(record_path, schema_compatible_table) + + # Step 6: Add to pending batch (no overwrite logic needed) self._add_to_pending_batch(record_path, schema_compatible_table) - # Step 6: Flush if asked to; otherwise commit this table alone once its + # Step 7: Flush if asked to; otherwise commit this table alone once its # pending batch reaches batch_size. Only the full table: committing every # pending table here would commit another table's rows, such as pipeline # records whose results are still pending, out of their writer's order @@ -2307,16 +2370,24 @@ def keeps_field_metadata(self) -> bool: def flush(self) -> None: """Flush all pending batches. - Every pending batch is attempted, even after one fails. A batch that fails - stays queued, so a later flush tries it again, and each failure is logged. + Every pending batch is attempted, even after one fails, and each failure is + logged. What happens to a failed batch depends on why it failed: + + - Refused by its stored table (``InputValidationError``): the table, as + another writer committed it after the rows were queued, cannot take them + (``_append_refusal``). The batch is dropped from the queue, since every later + flush would refuse it too; the error says how many rows were not written. + Correct the rows and add them again (ITL-1334). + - Any other failure (a table that cannot be loaded, a failed write): the batch + stays queued, so a later flush tries it again. Raises: OrcapodDatabaseReadError: If a batch's existing table could not be loaded. It is raised as itself; every other batch that failed in this flush is added to it as a note. InputValidationError: If no batch failed with ``OrcapodDatabaseReadError`` but a - batch's column types differ from its stored table's. Other failed - batches are added to it as notes. + batch was refused by its stored table (dropped from the queue, above). + Other failed batches are added to it as notes. RuntimeError: If batches failed with other errors only, naming the failed batches, with the first failure as its ``__cause__``. """ @@ -2497,6 +2568,11 @@ def _flush_by_key(self, record_key: str) -> None: # too, so they leave the queue, as rows refused when added never enter # it (ITL-1334). logger.error(f"Refused batch for {record_key}: {e}") + # The refusal was decided against a version this handle may not have + # cached: what it cached of the table is dropped, so its next read loads + # the version another writer committed. + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) e.add_note( f"The {pending_batch.num_rows} rows queued for this table were not " "written and are no longer queued." @@ -2804,33 +2880,27 @@ def _append_rows( def _incompatible_append_column( delta_table: deltalake.DeltaTable, batch: pa.Schema, written: pa.Schema ) -> tuple[str, pa.DataType, pa.DataType] | None: - """Find a column whose type in ``batch`` differs from the stored table's. - - Delta's merge either casts such a batch to the stored type (``int32`` or - ``float64`` rows into an ``int64`` column) or, when an extension type is - involved, writes data files the table can no longer read. ``null``-typed - parts of the batch fit any stored type and are not compared (see - ``_without_null_types``). The batch's types - are first converted exactly as the Delta writer converts them (see - ``_as_delta_writer_stores``), then both sides are compared with extension - types reduced to storage, large-normalized and nullability ignored, so a - type Delta stores differently (``uint64`` as ``int64``, ``timestamp[ns]`` - as ``timestamp[us]``) is not reported. Columns and nested - struct fields present on only one side are allowed (schema evolution); - see ``_types_conflict``. The stored schema comes from the loaded log; no - data is read. - - A stored column whose Arrow type is recorded (ITL-928, see - ``delta_arrow_types``) is compared by that type with the batch's own type - instead. A stored column without one was written before types were - recorded: besides the check above, the form the batch is written in - (``written``) must be the stored type, so a ``timestamp[ns]`` batch, now - written as ``int64``, is refused by a column stored as ``timestamp[us]``. - - A column the stored table does not have is not compared (schema evolution). A - type the Delta writer does not convert (``float16``) is compared as it is, so - a ``float16`` column is refused by a stored ``float32`` one, not failed by the - conversion. + """Find a column whose type in ``batch`` is not the type the table holds. + + One rule (ITL-1334): each column the stored table has is compared by its own + type with the type the table holds for it, its recorded type or else its + stored type (a column without a record holds a type Delta keeps exactly, so + its stored type is what was written). A conversion the Delta writer would make + is never taken as agreement: ``timestamp[ms]`` rows are refused by a + ``timestamp[us]`` column, whose read would give them back as microseconds. + Both sides are compared with extension types reduced to storage, + large-normalized and nested nullability ignored; struct fields are matched + by name, and a field on one side only is schema evolution + (``_types_conflict``). A ``null``-typed part takes the held type at its path + (``_with_nulls_resolved``), so its typed siblings, a map's keys beside + ``null`` items included, are still compared. + + One exception keeps tables written before types were recorded (ITL-928) + appendable: an unsigned integer column into a column without a record that + holds its written form (the signed integer of the same width), its values + then checked by ``first_column_out_of_stored_range``. + + The stored schema comes from the loaded log; no data is read. Args: delta_table: The loaded stored table. @@ -2839,7 +2909,7 @@ def _incompatible_append_column( written: ``batch`` as it is written (``written_field`` of each column). Returns: - ``(column, stored_type, incoming_type)`` for the first column whose + ``(column, held_type, incoming_type)`` for the first column whose compared types differ, or ``None`` when the batch can be appended. """ stored = _stored_arrow_schema(delta_table) @@ -2852,41 +2922,25 @@ def comparable(arrow_type: pa.DataType) -> pa.DataType: arrow_utils.normalize_to_large_types(arrow_type, keep_null=True) ) - def conflict( - stored_schema: pa.Schema, rows: pa.Schema - ) -> tuple[str, pa.DataType, pa.DataType] | None: - for f in rows: - index = stored_schema.get_field_index(f.name) - if index < 0 or recorded.get(f.name) is not None: - continue - reduced = _without_null_types(_comparable_storage_type(f.type)) - if reduced is None: - continue - try: - converted = ( - _as_delta_writer_stores(pa.schema([pa.field(f.name, reduced)])) - .field(0) - .type - ) - except Exception: # noqa: BLE001 # deltalake raises a bare Exception - # A type the writer does not take as it is (float16). - converted = reduced - stored_type = comparable(stored_schema.field(index).type) - incoming_type = comparable(converted) - if _types_conflict(stored_type, incoming_type): - return f.name, stored_type, incoming_type - return None - for field in batch: - stored_original = recorded.get(field.name) - if stored_original is None: + index = stored.get_field_index(field.name) + if index < 0: + continue # a new column: schema evolution + record = recorded.get(field.name) + held = comparable( + record if record is not None else stored.field(index).type + ) + incoming = _with_nulls_resolved(comparable(field.type), held) + if not _types_conflict(held, incoming): continue - reduced = _without_null_types(comparable(field.type)) - if reduced is not None and _types_conflict( - comparable(stored_original), reduced - ): - return field.name, stored_original, field.type - return conflict(stored, batch) or conflict(stored, written) + if record is None and pa.types.is_unsigned_integer(field.type): + as_written = _with_nulls_resolved( + comparable(written.field(field.name).type), held + ) + if not _types_conflict(held, as_written): + continue + return field.name, held, incoming + return None @property def base_path(self) -> tuple[str, ...]: diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index 95ed7407a..b77944b33 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -9,6 +9,7 @@ from __future__ import annotations +import datetime as dt from pathlib import Path from typing import Any, cast @@ -37,6 +38,8 @@ def _rows(ids: list[bytes], **columns: tuple[Any, list[Any]]) -> pa.Table: def _struct(*fields: Any) -> Any: + """A struct of exactly the fields given, in their order, each with its own name, + type, nullability and metadata.""" return pa.struct(list(fields)) @@ -89,6 +92,17 @@ def _struct(*fields: Any) -> Any: _rows([b"3", b"4"], x=(pa.float64(), [3.0, 4.0]), y=(I64, [3, 4])), r"'x': it is stored as int64 but the new rows have double", ), + "a timestamp unit the stored column does not have": ( + _rows([b"1", b"2"], x=(pa.timestamp("us"), [1, 2])), + _rows([b"3", b"4"], x=(pa.timestamp("ms"), [3, 4])), + r"'x': it is stored as timestamp\[us\] but the new rows have timestamp\[ms\]", + ), + "a map key type beside null items": ( + _rows([b"1"], x=(pa.map_(pa.large_string(), I64), [[("a", 1)]])), + _rows([b"3"], x=(pa.map_(I64, pa.null()), [[(5, None)]])), + r"'x': it is stored as map but the new rows have " + r"map", + ), "float16 into a float32 column": ( _rows([b"1", b"2"], x=(pa.float32(), [1.0, 2.0])), _rows([b"3", b"4"], x=(pa.float16(), [3.0, 4.0])), @@ -101,6 +115,9 @@ def _struct(*fields: Any) -> Any: def test_an_append_the_flush_would_refuse_is_refused_when_added( tmp_path: Path, case: str ) -> None: + """The refusal names the column (and the field), nothing is queued, a later flush + has nothing to fail on, and the stored rows read back unchanged, on the same and + on a fresh database object.""" first, second, match = REFUSED[case] db = DeltaTableDatabase(tmp_path) db.add_records(PATH, first, record_id_column="id", flush=True) @@ -114,35 +131,62 @@ def test_an_append_the_flush_would_refuse_is_refused_when_added( assert back.sort_by("id").to_pylist() == first.sort_by("id").to_pylist() -# The controls: what the flush takes is not refused. -KEPT: dict[str, tuple[pa.Table, pa.Table]] = { +# The controls: what the flush takes is not refused. (stored rows, appended rows, the +# columns compared, the rows read back in id order.) +KEPT: dict[str, tuple[pa.Table, pa.Table, list[str], list[dict[str, Any]]]] = { "a nullable struct field omitted": ( _rows([b"1"], x=(_struct(pa.field("a", I64), B), [{"a": 1, "b": 2}])), _rows([b"3"], x=(_struct(B), [{"b": 3}])), + ["x"], + [{"x": {"a": 1, "b": 2}}, {"x": {"a": None, "b": 3}}], ), "a nullable column omitted": ( _rows([b"1"], x=(I64, [1]), y=(I64, [1])), _rows([b"3"], y=(I64, [3])), + ["x", "y"], + [{"x": 1, "y": 1}, {"x": None, "y": 3}], ), "a nullable type without nulls into a non-nullable column": ( _rows([b"1"], x=(pa.field("x", I64, nullable=False), [1])), _rows([b"3"], x=(I64, [3])), + ["x"], + [{"x": 1}, {"x": 3}], ), "a new float16 column": ( _rows([b"1"], y=(I64, [1])), - _rows([b"3"], y=(I64, [3]), x=(pa.float16(), [None])), + _rows([b"3", b"4"], y=(I64, [3, 4]), x=(pa.float16(), [1.5, None])), + ["x", "y"], + [{"x": None, "y": 1}, {"x": 1.5, "y": 3}, {"x": None, "y": 4}], + ), + "a null item of a map takes its type from the stored map": ( + _rows([b"1"], x=(pa.map_(pa.large_string(), I64), [[("a", 1)]])), + _rows([b"3"], x=(pa.map_(pa.large_string(), pa.null()), [[("b", None)]])), + ["x"], + [{"x": [("a", 1)]}, {"x": [("b", None)]}], + ), + "the same timestamp unit": ( + _rows([b"1"], x=(pa.timestamp("us"), [1])), + _rows([b"3"], x=(pa.timestamp("us"), [3])), + ["x"], + [ + {"x": dt.datetime(1970, 1, 1, 0, 0, 0, 1)}, + {"x": dt.datetime(1970, 1, 1, 0, 0, 0, 3)}, + ], ), } @pytest.mark.parametrize("case", sorted(KEPT)) def test_an_append_the_flush_takes_is_kept(tmp_path: Path, case: str) -> None: - first, second = KEPT[case] + """Both batches read back on a fresh object, value for value (a null kept as a + null), with the stored column's type: a new ``float16`` column as ``float16``.""" + first, second, columns, expected = KEPT[case] db = DeltaTableDatabase(tmp_path) db.add_records(PATH, first, record_id_column="id", flush=True) db.add_records(PATH, second, record_id_column="id", flush=True) back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") - assert back is not None and back.num_rows == 2 + assert back is not None + assert back.sort_by("id").select(columns).to_pylist() == expected if case == "a new float16 column": assert back.schema.field("x").type == pa.float16() @@ -292,6 +336,8 @@ def test_a_null_child_of_an_evolving_struct_appends( def test_a_null_path_no_schema_types_is_refused_naming_every_path( tmp_path: Path, ) -> None: + """Every ``null`` part no schema types is named (``x.b``, ``x.c``), not only the + first; ``x.a``, which the stored table types, is not.""" db = DeltaTableDatabase(tmp_path) db.add_records( PATH, @@ -311,3 +357,111 @@ def test_a_null_path_no_schema_types_is_refused_naming_every_path( ), record_id_column="id", ) + + +def test_the_check_runs_on_the_rows_coerced_to_the_pending_batch( + tmp_path: Path, +) -> None: + """``schema_handling="coerce"`` casts the rows to the pending batch's types before + they are checked against the stored table, so ``int32`` rows behind a stored and a + pending ``int64`` column append; without it, the same rows are refused.""" + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _rows([b"1"], x=(I64, [1])), record_id_column="id", flush=True) + db.add_records(PATH, _rows([b"2"], x=(I64, [2])), record_id_column="id") + with pytest.raises(ValueError, match="Schema mismatch"): + db.add_records(PATH, _rows([b"3"], x=(pa.int32(), [3])), record_id_column="id") + db.add_records( + PATH, + _rows([b"3"], x=(pa.int32(), [3])), + record_id_column="id", + schema_handling="coerce", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.schema.field("x").type == I64 + assert back.sort_by("id").column("x").to_pylist() == [1, 2, 3] + + +@pytest.mark.parametrize( + ("values", "kept"), + [([None, 7], 7), ([7, None], None)], + ids=["null first", "null last"], +) +def test_values_are_checked_on_the_rows_kept_after_duplicates( + tmp_path: Path, values: list[Any], kept: Any +) -> None: + """A repeated id keeps its last row: a null in a dropped row is not refused, a null + in the kept row is, before anything is queued.""" + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=(pa.field("x", I64, nullable=False), [1])), + record_id_column="id", + flush=True, + ) + repeated = _rows([b"2", b"2"], x=(I64, values)) + if kept is None: + with pytest.raises(InputValidationError, match="'x'.*hold a null"): + db.add_records(PATH, repeated, record_id_column="id") + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + expected = [1] + else: + db.add_records(PATH, repeated, record_id_column="id", flush=True) + expected = [1, kept] + db.flush() + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").column("x").to_pylist() == expected + + +def test_rows_skip_duplicates_skips_are_not_checked(tmp_path: Path) -> None: + """``skip_duplicates=True`` skips a stored id; its null is never written, so it is + not refused.""" + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=(pa.field("x", I64, nullable=False), [1])), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _rows([b"1", b"2"], x=(I64, [None, 2])), + record_id_column="id", + skip_duplicates=True, + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").column("x").to_pylist() == [1, 2] + + +def test_a_flush_refusal_drops_what_the_handle_cached_of_the_table( + tmp_path: Path, +) -> None: + """A handle that read the table, then had its queued rows refused against a + version another writer committed, reads that version afterwards: its rows and + its new column, not the version it had cached.""" + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _rows([b"1"], x=(I64, [1])), record_id_column="id", flush=True) + assert db.get_all_records(PATH, record_id_column="id") is not None # cached + db.add_records( + PATH, + _rows([b"2"], x=(I64, [2]), y=(pa.float64(), [2.0])), + record_id_column="id", + ) + DeltaTableDatabase(tmp_path).add_records( + PATH, + _rows([b"9"], x=(I64, [9]), y=(I64, [9])), + record_id_column="id", + flush=True, + ) + with pytest.raises(InputValidationError, match="'y'"): + db.flush() + back = db.get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").select(["x", "y"]).to_pylist() == [ + {"x": 1, "y": None}, + {"x": 9, "y": 9}, + ] diff --git a/tests/test_databases/test_delta_read_your_writes.py b/tests/test_databases/test_delta_read_your_writes.py index 841276d4f..235f30681 100644 --- a/tests/test_databases/test_delta_read_your_writes.py +++ b/tests/test_databases/test_delta_read_your_writes.py @@ -407,40 +407,27 @@ def test_read_before_flush_matches_read_after_flush_across_schema_change( assert before.to_pylist() == after.to_pylist() -@pytest.mark.parametrize("method", list(READS_AC)) -def test_read_of_stored_and_pending_rows_with_different_types_raises( - tmp_path: Path, method: str -) -> None: - """A column whose stored and pending types differ is never widened: the read raises. - - Delta stores both timestamp units as microseconds, so the add accepts the rows. - """ - db = DeltaTableDatabase(tmp_path) - db.add_records(PATH, _table("a", pa.array([1], pa.timestamp("us"))), flush=True) - db.add_records(PATH, _table("c", pa.array([3], pa.timestamp("ms")))) - - with pytest.raises(pa.ArrowTypeError, match="Field x has incompatible types"): - _ = READS_AC[method](db) - - @pytest.mark.parametrize( ("stored_x", "pending_x"), [ (pa.array([1], pa.int64()), pa.array([3], pa.int32())), (pa.array([1], pa.int64()), pa.array(["t"], pa.large_string())), + (pa.array([1], pa.timestamp("us")), pa.array([3], pa.timestamp("ms"))), ( pa.array([1], pa.decimal128(10, 2)), pa.array([3], pa.decimal128(12, 2)), ), ], - ids=["int64_vs_int32", "int64_vs_string", "decimal_precision"], + ids=["int64_vs_int32", "int64_vs_string", "timestamp_unit", "decimal_precision"], ) @pytest.mark.parametrize("method", list(READS_AC)) def test_rows_of_another_type_than_the_stored_column_are_refused_when_added( tmp_path: Path, method: str, stored_x: pa.Array[Any], pending_x: pa.Array[Any] ) -> None: - """They used to be queued, make reads raise and fail the flush; now nothing is - queued, and the read gives the stored rows as stored (ITL-1334).""" + """They used to be queued, make reads of stored and pending rows raise and fail + the flush; now nothing is queued, and the read gives the stored rows as stored + (ITL-1334). A timestamp unit counts: Delta stores ``ms`` as ``us``, which would + give the rows back in another unit.""" db = DeltaTableDatabase(tmp_path) db.add_records(PATH, _table("a", stored_x), flush=True) with pytest.raises(InputValidationError, match="'x': it is stored as"): From 49223e28fbee0b6809eed6a16ff526d772966823 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 17:59:01 -0800 Subject: [PATCH 09/13] fix(delta_lake_databases): a refused merge append leaves the queued rows unchanged CodeRabbit on PR 471 (ITL-1334), review of 146a2f17: with schema_handling="merge", _handle_schema_compatibility replaced the pending batch with its unified form before the stored-table check ran, so a refused append still re-typed the queued rows (a null-typed x became double), and the next flush refused and dropped them. The unified pending batch is now staged: the new rows and the re-typed queued rows are both checked against the stored table, and the staged batch is queued only when both pass. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 52 +++++++++++++------ .../test_delta_append_preflight.py | 21 ++++++++ 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 6f7883dc4..ddd428382 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1616,7 +1616,10 @@ def require_storable(self, schema: pa.Schema) -> None: ) def _refuse_unmergeable_append( - self, record_path: tuple[str, ...], records: pa.Table + self, + record_path: tuple[str, ...], + records: pa.Table, + pending: pa.Table | None = None, ) -> None: """Refuse, before anything is buffered, rows a flush would refuse (ITL-1334). @@ -1629,11 +1632,15 @@ def _refuse_unmergeable_append( Args: record_path: The table the rows are for. records: The rows about to be added. + pending: The batch pending for the table as it would be queued with them + (``schema_handling="merge"`` re-types it), or ``None`` for the one + queued now. Raises: InputValidationError: For the first such column, naming it and the path. """ - pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is None: + pending = self._pending_batches.get(self._get_record_key(record_path)) refusal = None if pending is not None: held = {f.name: f for f in pending.schema} @@ -1780,15 +1787,21 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table - # Step 4: Handle schema compatibility - schema_compatible_table = self._handle_schema_compatibility( + # Step 4: Handle schema compatibility (the pending batch is only staged) + schema_compatible_table, staged_pending = self._handle_schema_compatibility( record_path, filtered_table, schema_handling ) # Step 5: what the flush would refuse is refused now, on the rows that are - # queued: after duplicates are dropped and any requested schema handling - # (ITL-1334). - self._refuse_unmergeable_append(record_path, schema_compatible_table) + # queued: after duplicates are dropped and any requested schema handling, the + # rows already queued included when a merge re-types them. Nothing queued + # changes unless both pass (ITL-1334). + self._refuse_unmergeable_append( + record_path, schema_compatible_table, staged_pending + ) + 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 # Step 6: Add to pending batch (no overwrite logic needed) self._add_to_pending_batch(record_path, schema_compatible_table) @@ -1880,16 +1893,24 @@ def _check_all_conflicts( def _handle_schema_compatibility( self, record_path: tuple[str, ...], table: pa.Table, schema_handling: str - ) -> pa.Table: - """Handle schema differences between input and pending batch.""" + ) -> tuple[pa.Table, pa.Table | None]: + """Handle schema differences between input and pending batch. + + Nothing queued is changed here: a ``"merge"`` returns the pending batch cast to + the unified schema, for the caller to queue once the rows are accepted. + + Returns: + The input as it is to be queued, and the re-typed pending batch (``None`` + when the pending batch stays as it is). + """ record_key = self._get_record_key(record_path) pending_batch = self._pending_batches.get(record_key) if pending_batch is None: - return table + return table, None if pending_batch.schema.equals(table.schema): # TODO: perform more careful check - return table + return table, None if schema_handling == "error": raise ValueError( @@ -1900,18 +1921,15 @@ def _handle_schema_compatibility( # Unify schemas and cast both input table and pending batch unified_schema = pa.unify_schemas([pending_batch.schema, table.schema]) - # Cast the pending batch to unified schema (excluding tracking columns) - self._pending_batches[record_key] = pending_batch.cast(unified_schema) - - # Cast and return the input table - return table.cast(unified_schema) + # The input and the pending batch, cast to the unified schema. + return table.cast(unified_schema), pending_batch.cast(unified_schema) except Exception as e: # TODO: perform more careful error check raise ValueError(f"Cannot merge schemas: {e}") elif schema_handling == "coerce": try: # Coerce input table to match existing pending batch schema - return table.cast(pending_batch.schema) + return table.cast(pending_batch.schema), None except Exception as e: raise ValueError(f"Cannot coerce schema: {e}") else: diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index b77944b33..338c19bd3 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -465,3 +465,24 @@ def test_a_flush_refusal_drops_what_the_handle_cached_of_the_table( {"x": 1, "y": None}, {"x": 9, "y": 9}, ] + + +def test_a_refused_merge_leaves_the_queued_rows_as_they_were(tmp_path: Path) -> None: + """``schema_handling="merge"`` re-types the queued rows only when the new rows are + accepted: a refused merge leaves them as queued, so the flush writes them.""" + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _rows([b"1"], x=(I64, [1])), record_id_column="id", flush=True) + db.add_records(PATH, _rows([b"2"], x=(pa.null(), [None])), record_id_column="id") + with pytest.raises(InputValidationError, match="'x': it is stored as int64"): + db.add_records( + PATH, + _rows([b"3"], x=(pa.float64(), [3.0])), + record_id_column="id", + schema_handling="merge", + ) + pending = db._pending_batches["t"] # pyright: ignore[reportPrivateUsage] + assert pending.schema.field("x").type == pa.null() + db.flush() + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").column("x").to_pylist() == [1, None] From d2266737acdd456f312e85478eaecde38a032d25 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 18:55:10 -0800 Subject: [PATCH 10/13] fix(delta_lake_databases): compare field attributes before schema handling casts CodeRabbit on PR 471 (ITL-1334), review of 49223e28: schema_handling "coerce" and "merge" cast the rows to the pending batch's schema before the field-attribute check, which gave them the pending columns' metadata: x with unit=s was queued and stored as unit=m. add_records now compares each column's field tree (_column_change) as given, against the pending batch and the stored table, before any schema handling (_refuse_changed_attributes); the type and value checks still run on the rows as queued, so a coercion of types still appends. The in-memory and connector databases have no schema handling and already compare the rows as given. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 56 +++++++++++++++++-- .../test_appended_field_attributes.py | 49 ++++++++++++++++ 2 files changed, 101 insertions(+), 4 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index ddd428382..4bbbe1d4f 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1668,6 +1668,49 @@ def _refuse_unmergeable_append( "The stored rows are unchanged and nothing was written." ) + def _refuse_changed_attributes( + self, record_path: tuple[str, ...], schema: pa.Schema + ) -> None: + """Refuse rows whose field attributes differ from the held columns', compared + before any ``schema_handling`` casts them (ITL-1334). + + A ``"merge"`` or ``"coerce"`` casts the rows to the pending batch's schema, + which would give them the pending columns' field metadata and nested + attributes: the rows would then be stored, and read back, with another + column's attributes. So the field tree of each column (``_column_change``) is + compared as given, against the pending batch and the stored table, in every + mode, as an append without schema handling is. + + Args: + record_path: The table the rows are for. + schema: The schema of the rows as given. + + Raises: + InputValidationError: For the first such column, naming it and the path. + """ + held: list[dict[str, pa.Field[Any]]] = [] + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + held.append({f.name: f for f in pending.schema}) + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + delta_table = None + if delta_table is not None: + held.append(_held_columns(delta_table)) + for given in held: + for field in schema: + if field.name not in given: + continue + change = _column_change(given[field.name], field) + if change is not None: + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: column " + f"{field.name!r}: {change}. The stored rows are unchanged and " + "nothing was written." + ) + def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1787,12 +1830,17 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table - # Step 4: Handle schema compatibility (the pending batch is only staged) + # Step 4: the rows' field attributes, compared as given: a merge or a + # coercion casts them to the pending batch's schema, which would give them + # its field metadata and nested attributes instead (ITL-1334). + self._refuse_changed_attributes(record_path, filtered_table.schema) + + # Step 5: Handle schema compatibility (the pending batch is only staged) schema_compatible_table, staged_pending = self._handle_schema_compatibility( record_path, filtered_table, schema_handling ) - # Step 5: what the flush would refuse is refused now, on the rows that are + # Step 6: what the flush would refuse is refused now, on the rows that are # queued: after duplicates are dropped and any requested schema handling, the # rows already queued included when a merge re-types them. Nothing queued # changes unless both pass (ITL-1334). @@ -1803,10 +1851,10 @@ def add_records( self._refuse_unmergeable_append(record_path, staged_pending, staged_pending) self._pending_batches[self._get_record_key(record_path)] = staged_pending - # Step 6: Add to pending batch (no overwrite logic needed) + # Step 7: Add to pending batch (no overwrite logic needed) self._add_to_pending_batch(record_path, schema_compatible_table) - # Step 7: Flush if asked to; otherwise commit this table alone once its + # Step 8: Flush if asked to; otherwise commit this table alone once its # pending batch reaches batch_size. Only the full table: committing every # pending table here would commit another table's rows, such as pipeline # records whose results are still pending, out of their writer's order diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index bcb5f2fd3..e3f03511b 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -181,3 +181,52 @@ def test_an_append_with_the_same_field_attributes_is_kept( db.add_records(PATH, second, record_id_column="id", flush=True) back = db.get_all_records(PATH, record_id_column="id") assert _values(back) == _values(first) + _values(second), where + + +def _cast_leaf(field: Any, leaf: Any) -> Any: + """``field`` with its int64 leaf (the column, or the struct child ``a``) of type + ``leaf``, its attributes kept.""" + if pa.types.is_struct(field.type): + return field.with_type(pa.struct([field.type.field(0).with_type(leaf)])) + return field.with_type(leaf) + + +@pytest.mark.parametrize("stored", [False, True], ids=["pending", "stored and pending"]) +@pytest.mark.parametrize("change", sorted(CHANGES)) +@pytest.mark.parametrize("where", ["column", "struct child"]) +@pytest.mark.parametrize("mode", ["coerce", "merge"]) +def test_delta_compares_attributes_before_schema_handling_casts( + tmp_path: Path, mode: str, where: str, change: str, stored: bool +) -> None: + """A ``"coerce"`` or ``"merge"`` casts the rows to the pending batch's schema, + which gave them its field metadata: ``unit=s`` rows were queued and stored as + ``unit=m`` (CodeRabbit on PR 471). The rows' attributes are compared as given, + so the append is refused and nothing queued changes. Each case casts: ``int32`` + rows coerced to ``int64``, ``null``-typed rows merged with ``int64``.""" + build, path, first_values, _ = WHERE[where] + first_unit, second_unit = CHANGES[change] + first = _rows([b"1", b"2"], build(first_unit), first_values) + leaf = pa.int32() if mode == "coerce" else pa.null() + values = ( + ([3, 4] if where == "column" else [{"a": 3}, {"a": 4}]) + if mode == "coerce" + else ([None, None] if where == "column" else [{"a": None}, {"a": None}]) + ) + second = _rows([b"3", b"4"], _cast_leaf(build(second_unit), leaf), values) + with open_database("Delta", tmp_path) as db: + db.add_records(PATH, first, record_id_column="id", flush=stored) + queued = first + if stored: + queued = _rows([b"5", b"6"], build(first_unit), first_values) + db.add_records(PATH, queued, record_id_column="id") + with pytest.raises(InputValidationError, match=f"'x': {path}"): + db.add_records(PATH, second, record_id_column="id", schema_handling=mode) + pending = db._pending_batches["t"] # pyright: ignore[reportPrivateUsage] + assert pending.schema.field("x").equals( + queued.schema.field("x"), check_metadata=True + ) + db.flush() + with open_database("Delta", tmp_path) as fresh: + back = fresh.get_all_records(PATH, record_id_column="id") + assert back is not None + _assert_kept_field(first, back) From 842e3334426fd3693214e8cf55db6b8eb256f0ef Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 19:50:32 -0800 Subject: [PATCH 11/13] test(databases): refusal tests compare the queued and the stored rows CodeRabbit nitpick on PR 471 (ITL-1334), review of d2266737: the coerce/merge refusal test also compares the pending batch's rows with the rows queued before the refusal, and, after the reopen, the stored rows with the rows written before it (rows 5 and 6 included in the stored case). The sibling refusal tests get the same checks: the cross-database attribute test checks the queue after each refusal, and the refused-merge test the queued row's values. Co-Authored-By: Claude Opus 5.5 --- .../test_appended_field_attributes.py | 21 +++++++++++++++++++ .../test_delta_append_preflight.py | 3 +++ 2 files changed, 24 insertions(+) diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index e3f03511b..04fe9f7ad 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -116,6 +116,18 @@ def _values(table: pa.Table | None) -> list[dict[str, Any]]: return table.sort_by("id").select(["id", "x", "y"]).to_pylist() +def _queued_values(db: Any) -> list[dict[str, Any]]: + """The rows queued for the table, as ``_values`` gives them (``[]`` for none).""" + queued = db._pending_batches.get("t") # the queue is the subject here + if queued is None: + return [] + return _values( + queued.rename_columns( + ["id" if n == db.RECORD_ID_COLUMN else n for n in queued.column_names] + ) + ) + + @pytest.mark.parametrize("pending", [False, True], ids=["stored", "pending"]) @pytest.mark.parametrize("change", sorted(CHANGES)) @pytest.mark.parametrize("where", sorted(WHERE)) @@ -139,6 +151,9 @@ def test_an_append_with_other_field_attributes_is_refused( else: with pytest.raises(InputValidationError, match=f"'x': {path}"): db.add_records(PATH, second, record_id_column="id") + # The queue holds exactly what it held before: the first rows when they + # were not flushed, nothing otherwise. + assert _queued_values(db) == (_values(first) if pending else []) db.flush() # nothing of the refused rows was buffered back = db.get_all_records(PATH, record_id_column="id") assert _values(back) == _values(first) @@ -225,8 +240,14 @@ def test_delta_compares_attributes_before_schema_handling_casts( assert pending.schema.field("x").equals( queued.schema.field("x"), check_metadata=True ) + # The queued rows are the ones queued before the refusal, value for value. + assert _queued_values(db) == _values(queued) db.flush() + # Read back: exactly the rows written before the refusal (rows 5 and 6 with + # the stored rows 1 and 2), with their attributes. + written = pa.concat_tables([first, queued]) if stored else first with open_database("Delta", tmp_path) as fresh: back = fresh.get_all_records(PATH, record_id_column="id") assert back is not None + assert _values(back) == _values(written) _assert_kept_field(first, back) diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index 338c19bd3..77762c690 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -482,6 +482,9 @@ def test_a_refused_merge_leaves_the_queued_rows_as_they_were(tmp_path: Path) -> ) pending = db._pending_batches["t"] # pyright: ignore[reportPrivateUsage] assert pending.schema.field("x").type == pa.null() + assert pending.select(["__record_id", "x"]).to_pylist() == [ + {"__record_id": b"2", "x": None} + ] db.flush() back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") assert back is not None From 45495f13b81f30db1f042310edc82a4b3ff62d07 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 20:39:38 -0800 Subject: [PATCH 12/13] fix(delta_lake_databases): discard notices survive aggregation; legacy dictionary unsigned; nulls against pending Fifth Codex review of PR 471 (ITL-1334), three Majors: - A batch the flush refuses carries its discard notice (row count, table) in its own message, so the log and the note flush() puts on another batch's error keep it; that note also carries the other error's notes. - Regression: the legacy unsigned exception (unsigned rows into a pre-ITL-928 signed column) applies to a dictionary's decoded type, and the range check decodes a dictionary, so in-range dictionary rows append again and out-of-range ones are refused. - The null check runs against a pending batch (as it will be queued) and the rows' own declaration, not only a stored table: rows holding a null in a column declared non-nullable no longer poison the queue, in every schema_handling mode, and a first batch doing so is refused too. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1334.md | 10 +- src/orcapod/databases/delta_arrow_types.py | 7 +- src/orcapod/databases/delta_lake_databases.py | 94 ++++++++++--- .../test_delta_append_preflight.py | 129 +++++++++++++++++- .../test_delta_read_failures.py | 18 ++- 5 files changed, 229 insertions(+), 29 deletions(-) diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index 79d47eef3..8c05dec81 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -57,8 +57,9 @@ when they would: - add a non-nullable struct field (the stored rows have no value for it, and Delta could not read the table back), or add a struct field inside a map (Delta's merge cannot); - - omit a struct field or a column stored as non-nullable, or hold a null in such a - column; + - omit a struct field or a column stored as non-nullable, or hold a null in a column + the stored table, a pending batch or the rows themselves declare non-nullable (with no + table stored yet, such rows used to fail the write of every row queued with them); - give a column another type than the one the table holds, compared by the rows' own type, not the form Delta's writer converts it to. So `float16` rows are refused by a `float32` column, `timestamp[ms]` rows by a `timestamp[us]` one (they read back in @@ -69,8 +70,9 @@ `skip_duplicates` skips, and the requested `schema_handling`. These rows used to fail the flush and stay queued, so every later flush failed again. The flush repeats the check against the version it loads, since another writer may commit in between. Rows it - refuses are dropped from the queue, the error says so, and the handle drops what it - had cached of the table. Rows failing for any other reason stay queued. A nested field + refuses are dropped from the queue; the error, the log and the note on another batch's + error raised instead all say how many rows of which table were not written. The handle + drops what it had cached of the table. Rows failing for any other reason stay queued. A nested field an append makes nullable reads back nullable. (ITL-1334) - **`DeltaTableDatabase` refuses a struct with no fields at any depth:** a Parquet file stores values in leaf columns only, so the flush failed. (ITL-1334) diff --git a/src/orcapod/databases/delta_arrow_types.py b/src/orcapod/databases/delta_arrow_types.py index 87d054117..2a50baae6 100644 --- a/src/orcapod/databases/delta_arrow_types.py +++ b/src/orcapod/databases/delta_arrow_types.py @@ -463,10 +463,15 @@ def first_column_out_of_stored_range( if index < 0: continue arrow_type = table.schema.field(index).type + column = table.column(index) + if pa.types.is_dictionary(arrow_type): + # The writer decodes a dictionary: its values are what is written. + arrow_type = arrow_type.value_type + column = column.cast(arrow_type) if _has_extension_type(arrow_type) or not _is_recorded(arrow_type): continue try: - table.column(index).cast(_stored_form(arrow_type), safe=True) + column.cast(_stored_form(arrow_type), safe=True) except pa.ArrowInvalid: return name return None diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 4bbbe1d4f..fb53d318f 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -606,6 +606,31 @@ def _held_columns(delta_table: deltalake.DeltaTable) -> dict[str, "pa.Field[Any] return fields +def _non_null_violation( + held: Mapping[str, "pa.Field[Any]"], rows: pa.Table +) -> tuple[str, bool] | None: + """The first column ``held`` declares non-nullable that ``rows`` omit or hold a + null in: Delta's writer refuses such a batch (ITL-1334). + + Args: + held: Columns by name: a stored table's, a pending batch's, or the rows' own. + rows: The rows to append. + + Returns: + ``(column, omitted)``: ``omitted`` is ``True`` when the rows lack the column, + ``False`` when they hold a null in it; ``None`` when there is no such column. + """ + for name, field in held.items(): + if field.nullable: + continue + index = rows.schema.get_field_index(name) + if index < 0: + return name, True + if rows.column(index).null_count: + return name, False + return None + + def _append_refusal( delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: @@ -635,14 +660,13 @@ def _append_refusal( change = _column_change(held[field.name], field) if change is not None: return field.name, change - for name, field in held.items(): - if field.nullable: - continue - index = rows.schema.get_field_index(name) - if index < 0: - return name, f"{name} is stored as non-nullable, and the rows omit it" - if rows.column(index).null_count: - return name, f"{name} is stored as non-nullable, and the rows hold a null" + violation = _non_null_violation(held, rows) + if violation is not None: + name, omitted = violation + return name, ( + f"{name} is stored as non-nullable, and the rows " + f"{'omit it' if omitted else 'hold a null'}" + ) written = pa.schema([written_field(f) for f in rows.schema]) mismatch = DeltaTableDatabase._incompatible_append_column( delta_table, rows.schema, written @@ -1642,7 +1666,15 @@ def _refuse_unmergeable_append( if pending is None: pending = self._pending_batches.get(self._get_record_key(record_path)) refusal = None - if pending is not None: + # The rows' own declaration: a column they declare non-nullable and hold a + # null in fails the write, a first one included. + own = _non_null_violation({f.name: f for f in records.schema}, records) + if own is not None: + refusal = ( + own[0], + f"{own[0]} is declared non-nullable, and the rows hold a null", + ) + if refusal is None and pending is not None: held = {f.name: f for f in pending.schema} refusal = next( ( @@ -1653,6 +1685,16 @@ def _refuse_unmergeable_append( ), None, ) + # A pending column declared non-nullable fails the write of the batch + # the rows join, whether or not a table is stored yet. + violation = _non_null_violation(held, records) if refusal is None else None + if violation is not None: + name, omitted = violation + refusal = ( + name, + f"{name} is queued as non-nullable, and the rows " + f"{'omit it' if omitted else 'hold a null'}", + ) if refusal is None: try: delta_table = self._get_delta_table(record_path) @@ -2475,6 +2517,9 @@ def flush(self) -> None: database_error.add_note( f"Another batch also failed to flush ({record_key}): " f"{type(other).__name__}: {other}" + + "".join( + f" {note}" for note in getattr(other, "__notes__", []) + ) ) raise database_error failed_keys = [k for k, _ in errors] @@ -2633,17 +2678,21 @@ def _flush_by_key(self, record_key: str) -> None: # ``_conformed_to_stored``): they would be refused by every later flush # too, so they leave the queue, as rows refused when added never enter # it (ITL-1334). - logger.error(f"Refused batch for {record_key}: {e}") # The refusal was decided against a version this handle may not have # cached: what it cached of the table is dropped, so its next read loads # the version another writer committed. self._delta_table_cache.pop(record_key, None) self._snapshots.pop(record_key, None) - e.add_note( - f"The {pending_batch.num_rows} rows queued for this table were not " - "written and are no longer queued." + # The discard notice is part of the message, so it survives wherever the + # error is reported: the log, and the note ``flush`` puts on another + # batch's error when that one is raised instead. + refused = InputValidationError( + f"{e} The {pending_batch.num_rows} rows queued for table " + f"{record_key!r} were not written and are no longer queued: correct " + "them and add them again." ) - raise + logger.error(f"Refused batch for {record_key}: {refused}") + raise refused from e except Exception as e: logger.error(f"Error flushing batch for {record_key}: {e}") # Put the tables back in the pending queue @@ -2962,9 +3011,10 @@ def _incompatible_append_column( ``null`` items included, are still compared. One exception keeps tables written before types were recorded (ITL-928) - appendable: an unsigned integer column into a column without a record that - holds its written form (the signed integer of the same width), its values - then checked by ``first_column_out_of_stored_range``. + appendable: an unsigned integer column, dictionary-encoded or not, into a + column without a record that holds its written form (the signed integer of + the same width), its values then checked by + ``first_column_out_of_stored_range``. The stored schema comes from the loaded log; no data is read. @@ -2999,9 +3049,15 @@ def comparable(arrow_type: pa.DataType) -> pa.DataType: incoming = _with_nulls_resolved(comparable(field.type), held) if not _types_conflict(held, incoming): continue - if record is None and pa.types.is_unsigned_integer(field.type): + decoded = ( + field.type.value_type + if pa.types.is_dictionary(field.type) + else field.type + ) + if record is None and pa.types.is_unsigned_integer(decoded): as_written = _with_nulls_resolved( - comparable(written.field(field.name).type), held + comparable(written_field(pa.field(field.name, decoded)).type), + held, ) if not _types_conflict(held, as_written): continue diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index 77762c690..784949532 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -244,7 +244,10 @@ def test_the_flush_refuses_rows_another_writer_made_conflict( with pytest.raises(InputValidationError, match="'x'") as raised: db.flush() refusal = raised.value - assert any("no longer queued" in note for note in getattr(refusal, "__notes__", [])) + assert ( + "2 rows queued for table 't' were not written and are no longer queued" + in str(refusal) + ) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() # nothing left to refuse back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") @@ -489,3 +492,127 @@ def test_a_refused_merge_leaves_the_queued_rows_as_they_were(tmp_path: Path) -> back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") assert back is not None assert back.sort_by("id").column("x").to_pylist() == [1, None] + + +def _legacy_int32_table(root: Path) -> None: + """A table as a build before ITL-928 wrote it: ``uint32`` columns ``x`` and ``y`` + stored as Delta's ``int32``, with no recorded type.""" + import deltalake + + deltalake.write_deltalake( + str(root / "t"), + pa.table( + { + "__record_id": pa.array([b"1", b"2"], pa.large_binary()), + "x": pa.array([1, 2], pa.int32()), + "y": pa.array([1, 2], pa.int32()), + } + ), + ) + + +def _dictionary_rows(values: list[int]) -> pa.Table: + encoded = pa.array(values, pa.uint32()).dictionary_encode() + return pa.table( + {"id": pa.array([b"3", b"4"], pa.large_binary()), "x": encoded, "y": encoded} + ) + + +def test_dictionary_unsigned_rows_in_range_append_to_a_legacy_signed_column( + tmp_path: Path, +) -> None: + """The legacy exception (unsigned rows into a pre-ITL-928 signed column) applies + to the decoded type of a dictionary too: it appended before this round's type rule + (fifth Codex review of PR 471).""" + _legacy_int32_table(tmp_path) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _dictionary_rows([3, 4]), record_id_column="id", flush=True) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").select(["x", "y"]).to_pylist() == [ + {"x": 1, "y": 1}, + {"x": 2, "y": 2}, + {"x": 3, "y": 3}, + {"x": 4, "y": 4}, + ] + + +def test_dictionary_unsigned_rows_out_of_range_are_refused(tmp_path: Path) -> None: + """The range check decodes a dictionary: a value the signed column cannot hold is + refused, naming the column, before anything is queued.""" + _legacy_int32_table(tmp_path) + db = DeltaTableDatabase(tmp_path) + with pytest.raises(InputValidationError, match="'x'.*cannot hold"): + db.add_records( + PATH, _dictionary_rows([3_000_000_000, 4]), record_id_column="id" + ) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None and back.num_rows == 2 + + +_NOT_NULL = pa.schema( + [ + pa.field("id", pa.large_binary()), + pa.field("x", I64, nullable=False), + pa.field("y", I64, nullable=False), + ] +) + + +def _not_null_rows(ids: list[bytes], x: list[Any], y: list[Any]) -> pa.Table: + """Rows of ``x`` and ``y`` declared non-nullable, holding what is given.""" + return pa.Table.from_arrays( + [pa.array(ids, pa.large_binary()), pa.array(x, I64), pa.array(y, I64)], + schema=_NOT_NULL, + ) + + +@pytest.mark.parametrize("column", ["x", "y"]) +@pytest.mark.parametrize("mode", ["error", "merge", "coerce"]) +def test_nulls_in_a_column_a_pending_batch_declares_non_nullable_are_refused( + tmp_path: Path, mode: str, column: str +) -> None: + """With no table stored yet, rows holding a null in a column the pending batch + declares non-nullable would fail the write of the whole batch, the valid queued + rows with it (fifth Codex review of PR 471). They are refused before buffering, in + every ``schema_handling`` mode, and the queued rows are written.""" + db = DeltaTableDatabase(tmp_path) + queued = _not_null_rows([b"1", b"2"], [1, 2], [1, 2]) + db.add_records(PATH, queued, record_id_column="id") + x, y = ([None, 3], [3, 4]) if column == "x" else ([3, 4], [3, None]) + with pytest.raises(InputValidationError, match=f"'{column}'.*non-nullable"): + db.add_records( + PATH, + _not_null_rows([b"3", b"4"], x, y), + record_id_column="id", + schema_handling=cast(Any, mode), # one of the three literals + ) + pending = db._pending_batches["t"] # pyright: ignore[reportPrivateUsage] + assert ( + pending.select(["x", "y"]).to_pylist() == queued.select(["x", "y"]).to_pylist() + ) + db.flush() + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").select(["x", "y"]).to_pylist() == [ + {"x": 1, "y": 1}, + {"x": 2, "y": 2}, + ] + + +@pytest.mark.parametrize("column", ["x", "y"]) +def test_a_first_batch_holding_a_null_it_declares_non_nullable_is_refused( + tmp_path: Path, column: str +) -> None: + """The rows' own declaration counts too: Delta's writer refuses a batch whose + non-nullable column holds a null, a first one included.""" + db = DeltaTableDatabase(tmp_path) + x, y = ([None, 2], [1, 2]) if column == "x" else ([1, 2], [1, None]) + with pytest.raises( + InputValidationError, match=f"'{column}'.*declared non-nullable" + ): + db.add_records(PATH, _not_null_rows([b"1", b"2"], x, y), record_id_column="id") + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + assert db.get_all_records(PATH, record_id_column="id") is None diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 84bf01eab..8948b9db8 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -259,14 +259,18 @@ class TestFlushRaisesStoreErrorsThemselves: """``flush`` raises database errors as themselves, with the other failures noted.""" def test_store_read_error_is_raised_with_a_note_per_other_failed_batch( - self, base, stored + self, base, stored, caplog ): - """The ``OrcapodDatabaseReadError`` is raised and the refused batch is noted on it.""" + """The ``OrcapodDatabaseReadError`` is raised and the refused batch is noted on + it, with its discard notice: how many rows of which table were not written and + are no longer queued, in the raised error and in the log (ITL-1334).""" other = ("results", "u") db = DeltaTableDatabase(base_path=base) # Queued first, while nothing is stored at ``other``; then another writer # stores x as int64 there, so the flush refuses these rows (ITL-1334). - db.add_records(other, rows([b"b"], pa.array([2.0])), record_id_column="rid") + db.add_records( + other, rows([b"b", b"d"], pa.array([2.0, 4.0])), record_id_column="rid" + ) stored.add_records( other, rows([b"a"], pa.array([1], pa.int64())), @@ -279,7 +283,7 @@ def test_store_read_error_is_raised_with_a_note_per_other_failed_batch( PATH, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" ) - with pytest.raises(OrcapodDatabaseReadError) as info: + with caplog.at_level("ERROR"), pytest.raises(OrcapodDatabaseReadError) as info: db.flush() # The OrcapodDatabaseReadError wins over the earlier refusal, because it is the one @@ -289,6 +293,12 @@ def test_store_read_error_is_raised_with_a_note_per_other_failed_batch( assert len(notes) == 1 assert "results/u" in notes[0] assert "InputValidationError" in notes[0] + discarded = ( + "The 2 rows queued for table 'results/u' were not written and are no " + "longer queued" + ) + assert discarded in notes[0] + assert any(discarded in record.getMessage() for record in caplog.records) # The batch the stored table refuses leaves the queue (every later flush # would refuse it too); the one whose table cannot be read stays queued, so # the next flush fails the same way (ITL-1334). From 3c406f505b84fc0a626bad8a31ddadc6de5ea3b6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 21:17:54 -0800 Subject: [PATCH 13/13] fix(delta_lake_databases): check the rows' own non-nullable declaration before schema handling CodeRabbit on PR 471 (ITL-1334), review of 45495f13: with "coerce" or "merge", the rows were cast to a nullable pending column before the null check, which then could not see that the rows declare the column non-nullable; rows holding a null there were queued. The check (_refuse_declared_nulls) now runs on the rows as given, before schema handling, and again on the rows as they will be queued. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 39 +++++++++++---- .../test_delta_append_preflight.py | 49 +++++++++++++++++++ 2 files changed, 79 insertions(+), 9 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index fb53d318f..827d78ea5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1665,16 +1665,9 @@ def _refuse_unmergeable_append( """ if pending is None: pending = self._pending_batches.get(self._get_record_key(record_path)) + self._refuse_declared_nulls(record_path, records) refusal = None - # The rows' own declaration: a column they declare non-nullable and hold a - # null in fails the write, a first one included. - own = _non_null_violation({f.name: f for f in records.schema}, records) - if own is not None: - refusal = ( - own[0], - f"{own[0]} is declared non-nullable, and the rows hold a null", - ) - if refusal is None and pending is not None: + if pending is not None: held = {f.name: f for f in pending.schema} refusal = next( ( @@ -1710,6 +1703,33 @@ def _refuse_unmergeable_append( "The stored rows are unchanged and nothing was written." ) + def _refuse_declared_nulls( + self, record_path: tuple[str, ...], rows: pa.Table + ) -> None: + """Refuse rows holding a null in a column they declare non-nullable (ITL-1334). + + Delta's writer refuses such a batch, a first one included, so every row + queued with them would fail. ``add_records`` checks the rows as given, before + any ``schema_handling`` casts them (a cast to a nullable pending column would + hide the declaration), and again as they will be queued. + + Args: + record_path: The table the rows are for. + rows: The rows. + + Raises: + InputValidationError: For the first such column, naming it. + """ + violation = _non_null_violation({f.name: f for f in rows.schema}, rows) + if violation is not None: + name = violation[0] + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: column {name!r}: {name} is " + "declared non-nullable, and the rows hold a null. The stored rows are " + "unchanged and nothing was written." + ) + def _refuse_changed_attributes( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1876,6 +1896,7 @@ def add_records( # coercion casts them to the pending batch's schema, which would give them # its field metadata and nested attributes instead (ITL-1334). self._refuse_changed_attributes(record_path, filtered_table.schema) + self._refuse_declared_nulls(record_path, filtered_table) # Step 5: Handle schema compatibility (the pending batch is only staged) schema_compatible_table, staged_pending = self._handle_schema_compatibility( diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index 784949532..d37919f53 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -616,3 +616,52 @@ def test_a_first_batch_holding_a_null_it_declares_non_nullable_is_refused( assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() assert db.get_all_records(PATH, record_id_column="id") is None + + +@pytest.mark.parametrize( + "pending_nullable", [True, False], ids=["pending nullable", "pending non-nullable"] +) +@pytest.mark.parametrize("column", ["x", "y"]) +@pytest.mark.parametrize("mode", ["coerce", "merge"]) +def test_the_rows_own_non_nullable_declaration_is_checked_before_schema_handling( + tmp_path: Path, mode: str, column: str, pending_nullable: bool +) -> None: + """A ``"coerce"`` or ``"merge"`` casts the rows to the pending batch's schema; a + nullable pending column then hid that the rows declare theirs non-nullable and hold + a null (CodeRabbit on PR 471). The rows are checked as given, so they are refused + in both modes, whatever the pending batch declares, and the queue is unchanged.""" + pending_schema = pa.schema( + [ + pa.field("id", pa.large_binary()), + pa.field("x", I64, nullable=pending_nullable), + pa.field("y", I64, nullable=pending_nullable), + ] + ) + queued = pa.Table.from_arrays( + [pa.array([b"1", b"2"], pa.large_binary()), pa.array([1, 2]), pa.array([1, 2])], + schema=pending_schema, + ) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, queued, record_id_column="id") + x, y = ([None, 3], [3, 4]) if column == "x" else ([3, 4], [3, None]) + with pytest.raises( + InputValidationError, match=f"'{column}': {column} is declared non-nullable" + ): + db.add_records( + PATH, + _not_null_rows([b"3", b"4"], x, y), + record_id_column="id", + schema_handling=cast(Any, mode), # one of the two literals + ) + pending = db._pending_batches["t"] # pyright: ignore[reportPrivateUsage] + assert ( + pending.select(["x", "y"]).to_pylist() == queued.select(["x", "y"]).to_pylist() + ) + assert pending.schema.field("x").nullable is pending_nullable + db.flush() + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.sort_by("id").select(["x", "y"]).to_pylist() == [ + {"x": 1, "y": 1}, + {"x": 2, "y": 2}, + ]