From a7ebd91f68fa1cde97e4b253c4928920eba95a10 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:10:07 -0800 Subject: [PATCH 1/6] fix(databases): every database matches an appended table's columns by name (ITL-1367) An append whose columns are the held table's columns in another order, each of the held type, is put in the held order (pending batch, else stored table) by one shared step, databases/utils.in_held_column_order, before any append check and before buffering: in-memory, Delta and the connector database (SQLite, PostgreSQL, SpiralDB). Anything else keeps each database's own rule. Live SpiralDB matches a write by name and keeps its own order (key columns, then value columns by name); the fake now mirrors that at the top level. The canonical order for a new table (step 2) is a proposal only: docs/dev/specs/itl-1367-stored-column-order.md. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1367.md | 13 + docs/dev/design_issues/ITL-1367-CO1.md | 40 ++ .../scripts/itl_1367_stored_column_orders.py | 96 +++++ .../dev/specs/itl-1367-stored-column-order.md | 161 ++++++++ docs/reference/database-types.md | 10 + .../databases/connector_arrow_database.py | 26 ++ src/orcapod/databases/delta_lake_databases.py | 25 ++ src/orcapod/databases/in_memory_databases.py | 18 +- src/orcapod/databases/utils.py | 50 ++- tests/test_databases/fake_pyspiral.py | 10 +- tests/test_databases/test_append_by_name.py | 343 ++++++++++++++++++ .../test_spiraldb_connector_fake.py | 15 +- .../test_spiraldb_connector_integration.py | 81 +++++ tests/test_databases/type_matrix.py | 10 + 14 files changed, 893 insertions(+), 5 deletions(-) create mode 100644 changelog.d/ITL-1367.md create mode 100644 docs/dev/design_issues/ITL-1367-CO1.md create mode 100644 docs/dev/scripts/itl_1367_stored_column_orders.py create mode 100644 docs/dev/specs/itl-1367-stored-column-order.md create mode 100644 tests/test_databases/test_append_by_name.py diff --git a/changelog.d/ITL-1367.md b/changelog.d/ITL-1367.md new file mode 100644 index 000000000..c18edacfd --- /dev/null +++ b/changelog.d/ITL-1367.md @@ -0,0 +1,13 @@ +### Fixed + +- **An append matches columns by name in every database** — appending rows whose columns + are the table's columns in another order was refused by the in-memory database, by Delta + and SQLite while the earlier rows were still pending, and by the SpiralDB test fake, so a + job node that produced the same columns in another order than an earlier write could not + store them. Every database (in-memory, Delta, SQLite, PostgreSQL, SpiralDB) now puts such + rows in the order the table already has (the rows still pending, else the stored table) + before anything is checked or written, after a flush and within one pending batch alike; + values are never matched by position. A table keeps the column order its database gave + the first write (SpiralDB orders a table's columns its own way: the key columns, then the + other columns by name). An append that also adds, omits or retypes a column, and a struct + whose fields are in another order, keep each database's own rule. (ITL-1367) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md new file mode 100644 index 000000000..3a7ca5d34 --- /dev/null +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -0,0 +1,40 @@ +## `src/orcapod/databases/` — column order of appended tables + +### CO1 — Databases refuse an append whose columns are in another order than the stored or pending table +**Status:** resolved +**Severity:** medium +**Issue:** ITL-1367 + +An append whose columns were the table's columns in another order was handled differently +by each database (measured on main 321284ae: two rows `rid, a, c, b`, then two rows +`b, c, rid, a`, with `a` and `c` both `int64`). The in-memory database refused it, after a +flush and within one pending batch. Delta matched it by name after a flush and refused it +within a pending batch. The connector database over SQLite did the same as Delta. The +SpiralDB fake refused it in both cases. No database swapped values by position, but the +column order of a stored table was in effect part of its schema: a job node that produced +the same columns in another order than an earlier run, or than an earlier batch of the same +run, could not store them, although no hash depends on column order. + +Live SpiralDB was measured (2026-11-22): it accepts a write in another order and matches it +by name, and it keeps a column order of its own whatever the order written: the key +columns in key-schema order, then the value columns sorted by name (code point: `B`, `C`, +`a`), struct children sorted by name too. The fake refused what SpiralDB accepts and kept +the written order. + +**Fix:** one shared step, `databases/utils.in_held_column_order`, called by every database +in `add_records` before any append check and before buffering (in-memory, Delta, +`ConnectorArrowDatabase` for SQLite, PostgreSQL and SpiralDB). Rows with exactly the held +columns in another order, each of the held type (compared in the large variants), are put +in the held order: the pending batch's, else the stored table's (the connector database +reads it from the connector on every append, so a table dropped and created again is read +as it is now). Anything else keeps the database's own rule: a column added or missing, a +type that differs, names that repeat or differ in case only. A table keeps the order its +database gave the first write (SpiralDB: its own order). The SpiralDB fake now mirrors +SpiralDB at the top level: it matches a write by name and stores the key columns, then the +value columns by name. Tests: `tests/test_databases/test_append_by_name.py`; live: +`TestColumnOrderLive` in `tests/test_databases/test_spiraldb_connector_integration.py`. + +Not covered: the order of a struct's fields (a struct with its fields in another order is +another type here, and the fake keeps struct children as written): ITL-1368. A canonical +order for a new table is a proposal awaiting the developer's decision: +`docs/dev/specs/itl-1367-stored-column-order.md`. diff --git a/docs/dev/scripts/itl_1367_stored_column_orders.py b/docs/dev/scripts/itl_1367_stored_column_orders.py new file mode 100644 index 000000000..c5d882b6c --- /dev/null +++ b/docs/dev/scripts/itl_1367_stored_column_orders.py @@ -0,0 +1,96 @@ +"""ITL-1367: the column order of each stored table kind as main writes it today. + +A job over one source with two tags (``z_tag``, ``a_tag``, declared in that order) and two +data columns (``y``, ``b``) runs a function pod, an operator node that logs (a ``Join``), +a cached source and a side-effect pod against an in-memory database that records the column order of +every ``add_records`` call, by table path. Input for the step 2 proposal +(``docs/dev/specs/itl-1367-stored-column-order.md``). + +Run: ``uv run python docs/dev/scripts/itl_1367_stored_column_orders.py`` +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import InMemoryArrowDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +SEEN: dict[tuple[str, ...], list[str]] = {} + + +_add_records = InMemoryArrowDatabase.add_records + + +def _recording_add_records( + self: InMemoryArrowDatabase, + record_path: tuple[str, ...], + records: pa.Table, + *args: Any, + **kwargs: Any, +) -> None: + """``add_records``, recording each table's column order as first written.""" + SEEN.setdefault(self.base_path + tuple(record_path), records.column_names) + _add_records(self, record_path, records, *args, **kwargs) + + +# Every view (``at``) of the database records too: the method is replaced on the class. +setattr(InMemoryArrowDatabase, "add_records", _recording_add_records) # noqa: B010 + + +def _source(name: str, data: list[str]) -> ArrowTableSource: + fields = [ + pa.field("z_tag", pa.large_string(), nullable=False), + pa.field("a_tag", pa.int64(), nullable=False), + *(pa.field(n, pa.float64(), nullable=False) for n in data), + ] + arrays = [ + pa.array(["s1", "s2"], pa.large_string()), + pa.array([1, 2], pa.int64()), + *(pa.array([1.0, 2.0], pa.float64()) for _ in data), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + source_id=name, + ) + + +@function_pod(output_keys=["w_out", "c_out"]) +def compute(y: float, b: float) -> tuple[float, float]: + return y + b, y - b + + +def notify(ctx: Any, y: float, b: float) -> None: + return None + + +def main() -> None: + database = InMemoryArrowDatabase() + job = PipelineJob(name="itl1367", database=database) + cached = CachedSource(_source("left", ["y", "b"]), cache_database=database) + with job: + left = cached + right = _source("right", ["x", "e"]) + compute.pod(left, label="fn") + Join()(left, right, label="joined") + SideEffectPod(notify)(left, label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + for path, names in sorted(SEEN.items()): + print("/".join(p[:40] for p in path)) + print(" ", names) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md new file mode 100644 index 000000000..8bd4ad635 --- /dev/null +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -0,0 +1,161 @@ +# ITL-1367 step 2 (proposal): a canonical column order for a new stored table + +Status: **proposal, not implemented.** It changes the stored form of every table kind, so +the developer decides. Step 1 (ITL-1367, this pull request) is implemented: an append whose +columns are the held table's columns in another order is put in the held order by every +database, and a table keeps the order its database gave its first write. + +The developer's decision (2026-11-22): "We should always try to save to match the existing +database order if already present, but if not yet, then use canonicalized order for new +database." Step 1 is the first half. This document proposes the second half. + +## What main writes today + +Measured with `docs/dev/scripts/itl_1367_stored_column_orders.py`: a job over a source with +two tags declared `z_tag, a_tag` and two data columns `y, b`, running a function pod, a +logging `Join` node, a cached source and a side-effect pod. The order of each table's first +write (system-tag hashes shortened): + +| Table kind | Layout | Order written today | +|---|---|---| +| Function pipeline | `pdb_v1` | `__record_id`, `z_tag`, `a_tag`, `_tag_source_id::…`, `_tag_record_id::…`, `_source_y`, `_source_b`, `__data_id`, `__node_content_hash`, `__input_data_hash`, `__output_data_hash`, `__data_context`, `__computed`, `__is_ephemeral`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index` | +| Function result | `rdb_v1` | `__record_id`, `__input_data_hash`, `__pf_var_*` (6), `__pf_exec_*` (4), `w_out`, `c_out`, `_source_w_out`, `_source_c_out`, `__pod_ts`, `__data_context` | +| Side-effect log | `tdb_v1` | `__record_id`, `record_id_hash`, `pipeline_run_id`, `executed_at`, `__data_context` | +| Operator cache | `odb_v1` | `_record_hash`, `z_tag`, `a_tag`, system tags (input 0, then input 1), `y`, `b`, `x`, `e`, `_source_y`, `_source_b`, `_source_x`, `_source_e`, `__node_content_hash`, `__data_context` | +| Cached source | `sdb_v1` | `_record_hash`, `z_tag`, `a_tag`, `y`, `b`, system tags, `_source_y`, `_source_b`, `__data_context` | + +(The record id column is renamed to `__record_id` inside every database; `_record_hash` +is the caller's name for it.) + +Two things follow. The user columns follow the declared tag order and the table layout +(`z_tag` before `a_tag`), which the rule that order never counts (ITL-1271) allows only as +presentation; and the kinds disagree with each other (the cached source puts data before +the system tags, the operator cache after). SpiralDB stores none of these orders: it keeps +the key column, then the other columns by name. + +## SpiralDB already imposes an order + +Measured live (2026-11-22, workload account, throwaway tables, dropped): SpiralDB accepts a +write in any column order, matches it by name, and stores and reads the table as the key +columns in key-schema order, then the value columns sorted by name by code point (`B`, +`C`, `a`), whatever the order written. A later append in another order changes nothing; an +added column takes its place by name. Struct children are sorted by name too. + +The evidence, two live sessions as the agent workload on the test project, every table a +throwaway one dropped at the end (the final listing showed none left). Each probe wrote +with pyspiral's `Table.write` (or `SpiralDBConnector.upsert_records`), then read the +table's schema (`Table.schema()`) and its rows (`SELECT *` through the connector): + +| Probe | Written | Schema and rows read back | +|---|---|---| +| 1. one key `k`, then appends in other orders | first `k, z, a, m`; then `m, k, a, z`; then `b, k, z, a, m` (adds `b`) | `k, a, m, z` after the first write and after the reordered append, values by name (`z` = 1 and 11, `a` = 2 and 12); `k, a, b, m, z` after the append that adds `b` | +| 2. names in mixed case | `k, B, a, C` | `k, B, C, a`: code point order, uppercase first | +| 3. composite key declared `(k2, k1)` | `y, k1, b, k2` | `k2, k1, b, y`: the keys in key-schema order (not by name), then the values by name | +| 4. a struct column | `s: struct`, then an append with `s: struct` | `s: struct` both times; values by child name (`a` = 2 and 12, `z` = 1 and 11) | + +The first session also wrote `__record_id, a, c, b` and then, through the connector's own +`upsert_records` with no reordering by Orcapod, `b, c, __record_id, a`: accepted, read back +as `__record_id, a, b, c` with every value under its own name. Through +`ConnectorArrowDatabase` with step 1, three orders read back the same way. + +So an order Orcapod chooses cannot be what SpiralDB physically stores. "Canonical" can mean +two things per database: + +- **the order Orcapod writes** (the order of the first `add_records` that creates the + table): in-memory, Delta, SQLite and PostgreSQL store it as written, so for them it is + also the order a read returns; +- **the order a read returns**: for SpiralDB, always SpiralDB's own. + +The proposal below makes the two meanings coincide in all five databases. + +## The proposal + +**A new table's columns are written in this order: the record id column, then every other +column sorted by name, by code point.** No other rule. + +- **Where:** in the database, in the shared step of step 1 + (`databases/utils.in_held_column_order`): with no held table (`held is None`), it returns + the rows in the canonical order instead of as given. Its callers do not change. The + database is the one place that sees every write of every table kind, so no table kind can + be forgotten, and a future table kind gets the rule without doing anything. +- **Why not role groups (record id, user tags, system tags, data, source info, meta):** a + database does not know a tag from a data column, so a role-grouped order can only be + produced by each caller (five table kinds, each building its table its own way, plus every + future one). Within a group the order would still have to be by name, since the declared + tag order may not count. Prefix groups that a database could see (`_tag_`, `_source_`, + `__`) do not separate user tags from data. Sorting every column by name is the one order + every database can apply alone, and it is SpiralDB's order (the record id is SpiralDB's + only key column in every Orcapod table), so all five databases then store and read the + same order. +- **Code point:** Python's `sorted` on `str`, the order SpiralDB was measured to use + (uppercase before `_` before lowercase). Names that differ in case only are refused by + SQLite and PostgreSQL already; the in-memory and Delta databases keep them apart, and + code point order is total, so the order is still decided. + +## Which stored tables change + +Every table **created** after the change, of every kind in the table above, in the +in-memory, Delta, SQLite and PostgreSQL databases: each is written in an order no table +kind uses today (the record id, then for example `__data_context`, `__input_data_hash`, +`__pf_exec_…`, `__pf_var_…`, `__pod_ts`, `_source_c_out`, `_source_w_out`, `c_out`, +`w_out` for a function result table). SpiralDB tables change in nothing: they are read in +that order already. + +A table **already stored** keeps its order: step 1 puts every later append in the held +order. Nothing is rewritten. + +## What else changes + +- **Readers that present stored rows in the stored order.** An operator node puts a stored + read in row order (`_in_row_order_on_read`). Others present the stored order as it is: + `CachedSource` (its stream is the cache read), `DerivedSource` (a node's stored records), + a function node's stored view and anything that calls `get_all_records`. Under the + proposal their column order would change (presentation only, but visible, and different + for a table created before the change and one created after). The proposal therefore + includes one helper that puts a stored read in row order (user tags, system tags, data, + source info; CLAUDE.md, "Important implementation details"), used by every reader, so + what a reader presents never depends on the stored order. On SpiralDB this is already + needed today. +- **The ITL-1347 differential** (`docs/dev/scripts/itl_1347/`, on the job-speed branch): + its `exact` mode compares stored tables column order included + (`compare.py`, `_schema_differences`: `column order: …`). A run of the branch against + pinned main would report every stored table created in the run. It would need stored + tables compared with columns matched by name (the `set` mode's `select(sorted(...))`, rows + still compared in order), while node tables (what a node keeps and presents) keep their + column order comparison, once the readers above present row order. +- **Golden values and paths:** none should move. No hash reads a stored table's column + order: a schema enters an identity through `hash_schema`, which ignores column order + (ITL-640); a row's hashes are built from its values by name; a path is built from + identities, never from a stored table's layout; record ids are built before a row is + written. The golden check (`generate_golden_hashes.py --check`) and the differential's + `set` mode are the evidence to collect when it is implemented. +- **Layout versions:** recommended none. A layout version moves when a table kind's + columns are added, renamed or retyped (CLAUDE.md, "Stored tables"), because a reader of + the old layout would misread the new one. Here no column changes, every read is by name, + and step 1 lets old and new tables take appends in any order. A table written in the old + order is read as current, as it would be by a SpiralDB read today. The developer may + still prefer a new marker so that a table's order tells its generation; it would move + every stored path, which nothing else here needs. +- **Data function type snapshots** (`src/orcapod/data_function_types/`) list a type's + record columns; the list is the declaration, not the stored order, and does not change. + +## Struct fields (input for ITL-1368) + +The same rule extends to struct fields at every depth: a new table's struct columns are +written with their children sorted by name (code point), recursively through lists, maps +and structs, which is again what SpiralDB was measured to store. An append would match a +struct's children by name, as step 1 matches top-level columns, so the recursive step +replaces `in_held_column_order` without changing its callers. `hash_table` and +`hash_schema` already leave struct field order out (`hashing/arrow_hashers.py`), but +`hash_table_ordered` (the pandas value hash, `arrow_ordered_v1`) includes it, and a struct +value may reach the semantic hasher in field order: ITL-1368 has to establish first +whether any hash depends on it, and a struct whose fields are reordered on write must read +back, and hash, as its type declares. + +## Decision needed + +1. Adopt the canonical order (record id, then every column by name, code point) for new + tables, in the database's shared step? Or a role-grouped order built by each caller? +2. Readers put stored reads in row order (one helper), so presentation never follows the + stored order? +3. No layout version change? diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 1b668112e..c24a7abab 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,6 +81,16 @@ would add a non-nullable struct field (the stored rows have no value for it) or struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. +An append matches columns by name, never by position. Rows whose columns are the held +table's columns in another order, each of the held type, are put in the held order (the +rows still pending, else the stored table) by every database before anything is checked +or written, whether the table was flushed in between or not. A table keeps the column +order the database gave its first write: the first write's order, except in SpiralDB, +which stores and reads a table's key columns first and then its other columns sorted by +name, whatever the order written (measured on SpiralDB itself). An append that also +adds, omits or retypes a column keeps each database's own rule. The order of a struct's +fields is not covered: a struct whose fields are in another order is another type here. + ## Integer | Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index e17ebeada..b2a435116 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -26,6 +26,7 @@ from orcapod.databases.utils import ( coerce_record_id, first_changed_column, + in_held_column_order, ) from orcapod.errors import ( InputValidationError, @@ -408,6 +409,10 @@ def add_records( self._connector.validate_records(records) record_key = self._get_record_key(record_path) + # Columns match by name: rows with the held columns in another order are + # put in the held order, so the connector always receives the stored order + # (ITL-1367). + records = in_held_column_order(records, self._held_column_order(record_path)) self._refuse_changed_columns(record_path, records.schema) records = self._deduplicate_within_table(records) @@ -454,6 +459,27 @@ def add_records( if flush: self.flush() + def _held_column_order( + self, record_path: tuple[str, ...] + ) -> list[tuple[str, pa.DataType]] | None: + """Each column the table holds, with its type, in the held order (ITL-1367). + + The pending batch's order when rows are pending, else the stored table's as + the connector reports it now (``get_column_info``, the types ``flush`` + compares), else ``None``. It is read on every call, never cached, so a table + dropped and created again in another order is read as it is now. + """ + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + return [(f.name, f.type) for f in pending.schema] + table_name = self._path_to_table_name(self._path_prefix + record_path) + if table_name not in self._connector.get_table_names(): + return None + return [ + (c.name, normalize_to_large_types(c.arrow_type, keep_null=True)) + for c in self._connector.get_column_info(table_name) + ] + def _refuse_changed_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 827d78ea5..5fc4dd3ff 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -18,6 +18,7 @@ ) from orcapod.databases.utils import ( appended_field_change, + in_held_column_order, coerce_record_id, metadata_bytes, ) @@ -1773,6 +1774,26 @@ def _refuse_changed_attributes( "nothing was written." ) + def _held_column_order( + self, record_path: tuple[str, ...] + ) -> list[tuple[str, pa.DataType]] | None: + """Each column the table holds, with its type, in the held order (ITL-1367). + + The pending batch's order when rows are pending, else the stored table's + (its log; no data is read), else ``None``. A stored table that cannot be + loaded gives ``None``: the append is then left to the flush to report. + """ + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + return [(f.name, f.type) for f in pending.schema] + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + return None + if delta_table is None: + return None + return [(name, f.type) for name, f in _held_columns(delta_table).items()] + def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1872,6 +1893,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) + # Columns match by name: rows with the held columns in another order are + # put in the held order (ITL-1367). + records = in_held_column_order(records, self._held_column_order(record_path)) + # 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) diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 92fca521a..34be934c2 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -6,7 +6,11 @@ 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, first_changed_column +from orcapod.databases.utils import ( + coerce_record_id, + first_changed_column, + in_held_column_order, +) from orcapod.errors import InputValidationError from orcapod.utils.lazy_module import LazyModule @@ -254,6 +258,18 @@ def add_records( ) record_key = self._get_record_key(record_path) + # Columns match by name: rows with the held columns in another order are + # put in the held order, the pending batch's, else the stored table's + # (ITL-1367). + held_table = self._pending_batches.get(record_key) + if held_table is None: + held_table = self._tables.get(record_key) + records = in_held_column_order( + records, + None + if held_table is None + else [(f.name, f.type) for f in held_table.schema], + ) # 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 = [ diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 8cd9f0018..4fb4c632e 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -3,7 +3,7 @@ from __future__ import annotations import re -from collections.abc import Iterable, Mapping +from collections.abc import Iterable, Mapping, Sequence from typing import TYPE_CHECKING, Any, cast from orcapod.utils import arrow_utils @@ -201,3 +201,51 @@ def first_changed_column( if reason is not None: return field.name, reason return None + + +def in_held_column_order( + records: "pa.Table", held: "Sequence[tuple[str, pa.DataType]] | None" +) -> "pa.Table": + """``records`` with its columns in the order the database holds them (ITL-1367). + + An append matches columns by name, never by position: when ``records`` has + exactly the held columns in another order, each with the held type, its columns + are put in the held order, so every database stores and buffers them as the + table already has them, and the table keeps the order of its first write. The + fields are kept as given (metadata, nullability): the append checks that follow + compare them by name. + + Anything else is returned as given, for the database's own append rule: no held + table, a column added or missing, a type that differs (a struct whose children + are in another order included: its type differs), and names that repeat or that + differ in case only, which a database matching names without case could pair + otherwise. + + Args: + records: The rows to append, the record id column already named as held. + held: Each held column's name and type, in the held order (the pending + batch, else the stored table), or ``None`` when the database holds no + such table. + + Returns: + ``records``, reordered or as given. + """ + if held is None: + return records + names = records.column_names + held_names = [name for name, _ in held] + if names == held_names: + return records + if len({n.casefold() for n in names}) != len(names): + return records + if len({n.casefold() for n in held_names}) != len(held_names): + return records + if set(names) != set(held_names): + return records + large = arrow_utils.normalize_to_large_types + held_types = dict(held) + for field in records.schema: + given = large(field.type, keep_null=True) + if given != large(held_types[field.name], keep_null=True): + return records + return records.select(held_names) diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index df5572209..874ec8220 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -560,7 +560,8 @@ def write( ValueError: If a key column is missing, a column name is one SpiralDB reserves (a ``.`` anywhere, or a ``__`` prefix on a value column), a struct value is null without ``push_down_nulls``, or the column set - differs from the stored table. + differs from the stored table (live SpiralDB adds a new column: the + fake does not model it). """ b = self._store.behaviour keys = self.key_schema @@ -607,6 +608,13 @@ def write( fields.append(sf) arrays.append(_cast_storage(col, sf.type)) incoming = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) + # SpiralDB matches a write's columns by name and stores them in its own + # order, whatever the order written: the key columns in key-schema order, + # then the value columns sorted by name, by code point (observed live, + # ITL-1367). Struct children are sorted live too; the fake keeps them as + # written (struct field order: ITL-1368). + values = sorted(n for n in incoming.column_names if n not in keys.names) + incoming = incoming.select([*keys.names, *values]) existing = self._store.read(self._project_id, self._identifier) if existing is not None: if existing.schema.names != incoming.schema.names: diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py new file mode 100644 index 000000000..54fac8c8d --- /dev/null +++ b/tests/test_databases/test_append_by_name.py @@ -0,0 +1,343 @@ +"""An append matches columns by name, whatever their order (ITL-1367). + +Every database puts rows whose columns are the held table's columns in another order +(each with the held type) into the held order before anything is checked or buffered: +the pending batch's order, else the stored table's. The table keeps the order of its +first write. ``a`` and ``c`` are both ``int64``, so a positional match would swap their +values: every test reads the values back by name. Appends that add, lack or retype a +column, and names that repeat or differ in case only, keep the database's own rule. +""" + +from __future__ import annotations + +import os +import sqlite3 +import uuid +from collections.abc import Iterator +from contextlib import ExitStack +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import ConnectorArrowDatabase +from orcapod.databases.utils import in_held_column_order +from tests.test_databases.type_matrix import open_database + +PATH = ("t",) +ID = "id" +TYPES: dict[str, Any] = { + ID: pa.large_binary(), + "a": pa.int64(), + "c": pa.int64(), + "b": pa.large_string(), +} +FIRST_ORDERS = { + "id a c b": [ID, "a", "c", "b"], + "b c id a": ["b", "c", ID, "a"], +} +SECOND_ORDERS = { + "c a b id": ["c", "a", "b", ID], + "id c a b": [ID, "c", "a", "b"], + "b id a c": ["b", ID, "a", "c"], +} +DATABASES = ("in-memory", "Delta", "SQLite", "SpiralDB") +DURABLE = ("Delta", "SQLite", "SpiralDB") + + +def _row(n: int) -> dict[str, Any]: + return {ID: f"r{n}".encode(), "a": n, "c": 100 + n, "b": f"b{n}"} + + +def _rows(order: list[str], ns: list[int]) -> pa.Table: + """Rows ``ns`` with the columns in ``order``; ``a`` is ``n``, ``c`` is ``100 + n``.""" + rows = [_row(n) for n in ns] + return pa.table( + {name: pa.array([r[name] for r in rows], TYPES[name]) for name in order} + ) + + +def _given_order(database: str, first: list[str], stored: bool = True) -> list[str]: + """The order a database gives a table first written in ``first``. + + The first write's order, except in SpiralDB once rows are stored: SpiralDB + stores and reads a table's columns in its own order, the key columns, then the + value columns sorted by name, whatever the order written (observed live, + ITL-1367; its fake does the same). Rows still pending keep the first write's. + """ + if database == "SpiralDB" and stored: + return [ID, *sorted(n for n in first if n != ID)] + return first + + +def _check(table: pa.Table | None, first: list[str], ns: list[int]) -> None: + """The rows ``ns``, read by name, in the order ``first``.""" + assert table is not None + assert table.column_names == first + got = sorted(table.select([ID, "a", "c", "b"]).to_pylist(), key=lambda r: r["a"]) + assert got == [_row(n) for n in ns] + + +def _add(db: Any, table: pa.Table, flush: bool = False) -> None: + db.add_records(PATH, table, record_id_column=ID, flush=flush) + + +@pytest.mark.parametrize("database", DATABASES) +@pytest.mark.parametrize("first", FIRST_ORDERS) +@pytest.mark.parametrize("second", SECOND_ORDERS) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_an_append_in_another_order_is_matched_by_name( + tmp_path: Path, database: str, first: str, second: str, when: str +) -> None: + first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] + with ExitStack() as stack: + db = stack.enter_context(open_database(database, tmp_path)) + _add(db, _rows(first_order, [1, 2]), flush=when == "after a flush") + _add(db, _rows(second_order, [3, 4])) + # Before the flush: the pending rows (and the stored ones) read by name. + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order(database, first_order, stored=when == "after a flush"), + [1, 2, 3, 4], + ) + db.flush() + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order(database, first_order), + [1, 2, 3, 4], + ) + + +@pytest.mark.parametrize("database", DURABLE) +@pytest.mark.parametrize("first", FIRST_ORDERS) +@pytest.mark.parametrize("second", SECOND_ORDERS) +def test_an_append_in_another_order_after_reopening_is_matched_by_name( + tmp_path: Path, database: str, first: str, second: str +) -> None: + first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] + with open_database(database, tmp_path) as db: + _add(db, _rows(first_order, [1, 2]), flush=True) + with open_database(database, tmp_path) as db: + _add(db, _rows(second_order, [3, 4])) + _add(db, _rows(first_order, [5])) + db.flush() + with open_database(database, tmp_path) as db: + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order(database, first_order), + [1, 2, 3, 4, 5], + ) + + +@pytest.mark.parametrize("database", DATABASES) +def test_a_new_table_keeps_the_order_the_database_gave_its_first_write( + tmp_path: Path, database: str +) -> None: + """The first write's order is kept, whichever order it is; nothing is sorted by + Orcapod (SpiralDB orders a table's columns its own way).""" + with open_database(database, tmp_path) as db: + for n, order in enumerate([["c", "b", "a", ID], [ID, "a", "b", "c"]]): + path = (f"t{n}",) + db.add_records(path, _rows(order, [1]), record_id_column=ID, flush=True) + table = db.get_all_records(path, record_id_column=ID) + assert table is not None + assert table.column_names == _given_order(database, order) + + +@pytest.mark.parametrize("database", DATABASES) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_an_append_that_also_retypes_a_column_keeps_todays_rule( + tmp_path: Path, database: str, when: str +) -> None: + """Another type is not a reordering: the rows are left as given, for the + database's own rule. Whatever that rule does, no value is matched by position.""" + retyped = _rows(["c", "a", "b", ID], [3]).set_column( + 1, "a", pa.array([3], pa.int32()) + ) + with open_database(database, tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=when == "after a flush") + try: + _add(db, retyped, flush=True) + except Exception: # noqa: BLE001 # today's rule refused it: nothing swapped + return + table = db.get_all_records(PATH, record_id_column=ID) + assert table is not None + got = sorted(table.select([ID, "a", "c"]).to_pylist(), key=lambda r: r["a"]) + assert got == [ + {ID: b"r1", "a": 1, "c": 101}, + {ID: b"r3", "a": 3, "c": 103}, + ] + + +def test_a_table_created_again_in_another_order_is_read_as_it_is_now( + tmp_path: Path, +) -> None: + """The connector database reads the stored order on every append, so a table + dropped and created again in another order is matched to its new order.""" + with open_database("SQLite", tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) + _add(db, _rows(["c", "a", "b", ID], [2]), flush=True) + with sqlite3.connect(tmp_path / "store.db") as other: + other.execute('DROP TABLE "t"') + _add(db, _rows(["b", ID, "c", "a"], [3]), flush=True) + _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) + _check( + db.get_all_records(PATH, record_id_column=ID), + ["b", ID, "c", "a"], + [3, 4], + ) + + +def test_a_spiraldb_table_deleted_and_created_again_in_another_order( + tmp_path: Path, +) -> None: + with open_database("SpiralDB", tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) + db._connector.delete_table("t") # the connector's own drop + _add(db, _rows(["b", ID, "c", "a"], [3]), flush=True) + _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order("SpiralDB", ["b", ID, "c", "a"]), + [3, 4], + ) + + +# ── The shared step ──────────────────────────────────────────────────────────── + + +def _held(*names: str) -> list[tuple[str, Any]]: + return [(n, pa.int64()) for n in names] + + +def _table(*names: str) -> pa.Table: + return pa.Table.from_arrays( + [pa.array([i], pa.int64()) for i in range(len(names))], names=list(names) + ) + + +def test_the_step_reorders_the_held_columns_by_name() -> None: + given = _table("c", "a", "b") + out = in_held_column_order(given, _held("a", "b", "c")) + assert out.column_names == ["a", "b", "c"] + assert out.to_pylist() == [{"a": 1, "b": 2, "c": 0}] + + +def test_the_step_keeps_the_given_fields() -> None: + """Metadata and nullability go on to the append checks as given.""" + field = pa.field("c", pa.int64(), nullable=False, metadata={"unit": "m"}) + given = pa.Table.from_arrays( + [pa.array([1], pa.int64()), pa.array([2], pa.int64())], + schema=pa.schema([field, pa.field("a", pa.int64())]), + ) + out = in_held_column_order(given, _held("a", "c")) + assert out.schema.field("c").equals(field, check_metadata=True) + + +def test_the_step_compares_types_in_their_large_variants() -> None: + given = pa.table({"b": pa.array(["x"], pa.string()), "a": [1]}) + out = in_held_column_order(given, [("a", pa.int64()), ("b", pa.large_string())]) + assert out.column_names == ["a", "b"] + + +@pytest.mark.parametrize( + ("given", "held"), + [ + pytest.param(_table("c", "a"), None, id="nothing held"), + pytest.param(_table("c", "a"), _held("a", "b", "c"), id="a column missing"), + pytest.param(_table("c", "a", "b"), _held("a", "c"), id="a column added"), + pytest.param(_table("c", "A"), _held("a", "c"), id="a name in another case"), + pytest.param( + _table("A", "a", "c"), _held("a", "c", "A"), id="names differing in case" + ), + pytest.param(_table("c", "a", "a"), _held("a", "c", "a"), id="a repeated name"), + pytest.param( + _table("c", "a"), + [("a", pa.int64()), ("c", pa.int32())], + id="a type differs", + ), + pytest.param( + pa.table( + { + "s": pa.array( + [{"y": 1, "x": 2}], + pa.struct([("y", pa.int64()), ("x", pa.int64())]), + ), + "a": [1], + } + ), + [ + ("a", pa.int64()), + ("s", pa.struct([("x", pa.int64()), ("y", pa.int64())])), + ], + id="struct children in another order", + ), + ], +) +def test_the_step_leaves_anything_else_as_given( + given: pa.Table, held: list[tuple[str, Any]] | None +) -> None: + assert in_held_column_order(given, held) is given + + +def test_names_differing_in_case_only_keep_todays_rule() -> None: + """The in-memory database holds ``a`` and ``A`` apart; a reordered append of them + is not reordered and is refused, as it is today.""" + with open_database("in-memory", Path(".")) as db: + _add(db, _table_with_id([ID, "a", "A"])) + with pytest.raises(pa.ArrowInvalid): + _add(db, _table_with_id(["A", ID, "a"])) + + +def _table_with_id(order: list[str]) -> pa.Table: + columns = { + ID: pa.array([uuid.uuid4().bytes], pa.large_binary()), + "a": pa.array([1], pa.int64()), + "A": pa.array([2], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +# ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── + + +@pytest.fixture +def postgresql_database() -> Iterator[ConnectorArrowDatabase]: + psycopg = pytest.importorskip("psycopg") + from orcapod.databases import PostgreSQLConnector + + host = os.environ.get("PGHOST", "localhost") + port = os.environ.get("PGPORT", "5432") + dbname = os.environ.get("PGDATABASE", "testdb") + user = os.environ.get("PGUSER", "postgres") + password = os.environ.get("PGPASSWORD", "postgres") + base_dsn = ( + f"host={host} port={port} dbname={dbname} user={user} password={password}" + ) + schema = f"test_{uuid.uuid4().hex[:12]}" + with psycopg.connect(base_dsn, autocommit=True) as admin: + admin.execute(f"CREATE SCHEMA {schema}") + connector = PostgreSQLConnector(f"{base_dsn} options=-csearch_path={schema}") + try: + yield ConnectorArrowDatabase(connector) + finally: + connector.close() + with psycopg.connect(base_dsn, autocommit=True) as admin: + admin.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE") + + +@pytest.mark.postgres +@pytest.mark.parametrize("first", FIRST_ORDERS) +@pytest.mark.parametrize("second", SECOND_ORDERS) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_postgresql_matches_an_append_in_another_order_by_name( + postgresql_database: ConnectorArrowDatabase, first: str, second: str, when: str +) -> None: + db = postgresql_database + first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] + _add(db, _rows(first_order, [1, 2]), flush=when == "after a flush") + _add(db, _rows(second_order, [3, 4])) + _check(db.get_all_records(PATH, record_id_column=ID), first_order, [1, 2, 3, 4]) + db.flush() + _check(db.get_all_records(PATH, record_id_column=ID), first_order, [1, 2, 3, 4]) diff --git a/tests/test_databases/test_spiraldb_connector_fake.py b/tests/test_databases/test_spiraldb_connector_fake.py index a40568ff4..6d78530da 100644 --- a/tests/test_databases/test_spiraldb_connector_fake.py +++ b/tests/test_databases/test_spiraldb_connector_fake.py @@ -160,6 +160,14 @@ def hashes(source) -> list[str]: _TABLE = "p/default/t" +def _spiral_order(schema: pa.Schema, keys: list[str]) -> pa.Schema: + """``schema`` in the order SpiralDB stores and reads a table's columns, whatever + the order written: the key columns in key order, then the value columns sorted + by name (observed live, ITL-1367).""" + values = sorted(f.name for f in schema if f.name not in keys) + return pa.schema([schema.field(n) for n in [*keys, *values]]) + + def _rows(schema: pa.Schema = _RECORDED, **override) -> pa.Table: """Return three rows of ``schema`` (``override`` replaces whole columns).""" columns = { @@ -209,12 +217,14 @@ def test_first_write_records_and_both_read_paths_restore_it(self, fake): """The first write records nullability; get_column_info and iter_batches restore it.""" connector = SpiralDBConnector("p") connector.upsert_records("t", _rows(), id_column="k") + # In SpiralDB's order: the key column, then the value columns by name + # (ITL-1367). expected = pa.schema( [ pa.field( f.name, arrow_utils.normalize_to_large_types(f.type), f.nullable ) - for f in _RECORDED + for f in _spiral_order(_RECORDED, ["k"]) ] ) assert self._batches_schema(connector) == expected @@ -466,7 +476,8 @@ def test_results_read_back_with_the_written_schema(self, db): records = db.get_all_records(_PATH) assert records is not None assert records.num_rows == 2 - assert records.schema == _RESULT + # In SpiralDB's order: the value columns by name (ITL-1367). + assert records.schema == _spiral_order(_RESULT, []) def test_result_table_written_before_the_record_keeps_todays_behaviour( self, db, monkeypatch diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index de32f9f20..a6d88ff2a 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -460,3 +460,84 @@ def test_spiraldb_itself_refuses_the_names_the_connector_refuses( finally: if table in connector.get_table_names(): connector.delete_table(table) + + +def _ordered_rows(order: list[str], ns: list[int]) -> pa.Table: + """Rows ``ns`` with the columns in ``order``; ``a`` and ``c`` are both ``int64``, + so a positional match would swap them.""" + columns = { + "__record_id": pa.array([f"r{n}".encode() for n in ns], pa.large_binary()), + "a": pa.array(ns, pa.int64()), + "c": pa.array([100 + n for n in ns], pa.int64()), + "b": pa.array([f"b{n}" for n in ns], pa.large_string()), + } + return pa.table({name: columns[name] for name in order}) + + +def _by_name(table: pa.Table) -> list[dict[str, object]]: + return sorted( + table.select(["__record_id", "a", "c", "b"]).to_pylist(), key=lambda r: r["a"] + ) + + +class TestColumnOrderLive: + """SpiralDB matches a write's columns by name and keeps an order of its own: the + key columns, then the value columns sorted by name, whatever the order written + (ITL-1367; the fake does the same).""" + + def test_a_raw_write_in_another_order_is_matched_by_name(self, connector): + table = _unique_table("itl1367_raw") + try: + first = ["__record_id", "a", "c", "b"] + connector.create_table_if_not_exists( + table, + [ + ColumnInfo(n, _ordered_rows(first, [1]).schema.field(n).type) + for n in first + ], + pk_column="__record_id", + ) + connector.upsert_records(table, _ordered_rows(first, [1, 2]), "__record_id") + connector.upsert_records( + table, + _ordered_rows(["b", "c", "__record_id", "a"], [3, 4]), + "__record_id", + ) + read = pa.Table.from_batches( + list(connector.iter_batches(f'SELECT * FROM "{table}"')) + ) + assert read.column_names == ["__record_id", "a", "b", "c"] + assert _by_name(read) == _by_name(_ordered_rows(first, [1, 2, 3, 4])) + finally: + if table in connector.get_table_names(): + connector.delete_table(table) + + @pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) + def test_the_database_matches_an_append_in_another_order_by_name( + self, connector, when + ): + path = (_unique_table("itl1367_db"),) + db = ConnectorArrowDatabase(connector) + try: + first = ["__record_id", "a", "c", "b"] + db.add_records( + path, _ordered_rows(first, [1, 2]), flush=when == "after a flush" + ) + db.add_records( + path, + _ordered_rows(["b", "c", "__record_id", "a"], [3, 4]), + record_id_column="__record_id", + ) + db.add_records( + path, + _ordered_rows(["c", "__record_id", "b", "a"], [5]), + record_id_column="__record_id", + ) + db.flush() + read = db.get_all_records(path, record_id_column="__record_id") + assert read is not None + assert read.column_names == ["__record_id", "a", "b", "c"] + assert _by_name(read) == _by_name(_ordered_rows(first, [1, 2, 3, 4, 5])) + finally: + if path[0] in connector.get_table_names(): + connector.delete_table(path[0]) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index ce00684e8..6d8a01c6b 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1055,6 +1055,16 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: 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. + +An append matches columns by name, never by position. Rows whose columns are the held +table's columns in another order, each of the held type, are put in the held order (the +rows still pending, else the stored table) by every database before anything is checked +or written, whether the table was flushed in between or not. A table keeps the column +order the database gave its first write: the first write's order, except in SpiralDB, +which stores and reads a table's key columns first and then its other columns sorted by +name, whatever the order written (measured on SpiralDB itself). An append that also +adds, omits or retypes a column keeps each database's own rule. The order of a struct's +fields is not covered: a struct whose fields are in another order is another type here. """ From a4d3cc0f45d4c64a72230fd6ad3ae72092692bf5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:40:41 -0800 Subject: [PATCH 2/6] fix(databases): append-by-name keeps main's Delta commit choice and matches queued rows at read and flush (ITL-1367) PR 491 review round (Codex): - a Delta append reordered by name is committed by MERGE (insert-if-missing), the commit main chose for rows in another order; never a blind append - the connector database matches queued rows to the stored table by name when it reads them with it or flushes them (one helper, _in_stored_order) - Delta looks the stored order up only for rows left after duplicates are dropped - names match exactly (no case-fold guard); a logical or dictionary type is compared by its storage type - the connector database remembers each table's order: one lookup per flushed append, as before - docs, changelog and design entry say where the step runs - the retype test asserts each database's verdict (as on main) - ITL-1263: the in-memory xfails of the swapped-output-keys test pass; the test runs on the sync and async path and in three orders Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1367.md | 8 +- docs/dev/design_issues/ITL-1367-CO1.md | 17 +- docs/reference/database-types.md | 13 +- .../databases/connector_arrow_database.py | 86 +++++- src/orcapod/databases/delta_lake_databases.py | 35 ++- src/orcapod/databases/utils.py | 33 +- .../data_function/test_function_record.py | 32 +- tests/test_databases/test_append_by_name.py | 289 ++++++++++++++++-- tests/test_databases/type_matrix.py | 13 +- 9 files changed, 435 insertions(+), 91 deletions(-) diff --git a/changelog.d/ITL-1367.md b/changelog.d/ITL-1367.md index c18edacfd..73da65c13 100644 --- a/changelog.d/ITL-1367.md +++ b/changelog.d/ITL-1367.md @@ -6,8 +6,12 @@ job node that produced the same columns in another order than an earlier write could not store them. Every database (in-memory, Delta, SQLite, PostgreSQL, SpiralDB) now puts such rows in the order the table already has (the rows still pending, else the stored table) - before anything is checked or written, after a flush and within one pending batch alike; - values are never matched by position. A table keeps the column order its database gave + before they are queued, after a flush and within one pending batch alike, and matches + rows still queued to the stored table by name again when they are read with it or + written; names are matched exactly (`a` and `A` are two columns) and values are never + matched by position. A reordered append to a Delta table is committed as an + insert-if-missing (MERGE), as before, so two writers appending one record id still + cannot both store it. A table keeps the column order its database gave the first write (SpiralDB orders a table's columns its own way: the key columns, then the other columns by name). An append that also adds, omits or retypes a column, and a struct whose fields are in another order, keep each database's own rule. (ITL-1367) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index 3a7ca5d34..841911a0a 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -22,13 +22,20 @@ columns in key-schema order, then the value columns sorted by name (code point: the written order. **Fix:** one shared step, `databases/utils.in_held_column_order`, called by every database -in `add_records` before any append check and before buffering (in-memory, Delta, +in `add_records` before the rows are queued and before the checks that compare them with +the held columns (the checks on the rows alone come first; Delta looks the order up only +for rows left after duplicates are dropped), in every database (in-memory, Delta, `ConnectorArrowDatabase` for SQLite, PostgreSQL and SpiralDB). Rows with exactly the held columns in another order, each of the held type (compared in the large variants), are put -in the held order: the pending batch's, else the stored table's (the connector database -reads it from the connector on every append, so a table dropped and created again is read -as it is now). Anything else keeps the database's own rule: a column added or missing, a -type that differs, names that repeat or differ in case only. A table keeps the order its +in the held order: the pending batch's, else the stored table's. Anything else keeps the database's own rule: a column added or missing, a +type that differs (a logical type is compared by its storage type), a name that repeats +exactly (names match exactly: `a` and `A` are two columns). The connector database +remembers each table's order from its own lookups, reads and writes (one lookup per +flushed append, as before), and matches queued rows to the stored table again, by name, +when it reads them with it or flushes them, so a table created again in another order by +another connection is combined correctly. A Delta append that was reordered is committed +by MERGE (insert-if-missing), the commit main chose for rows in another order, never a +blind append. A table keeps the order its database gave the first write (SpiralDB: its own order). The SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores the key columns, then the value columns by name. Tests: `tests/test_databases/test_append_by_name.py`; live: diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index c24a7abab..f0dde1d5a 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,10 +81,15 @@ would add a non-nullable struct field (the stored rows have no value for it) or struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. -An append matches columns by name, never by position. Rows whose columns are the held -table's columns in another order, each of the held type, are put in the held order (the -rows still pending, else the stored table) by every database before anything is checked -or written, whether the table was flushed in between or not. A table keeps the column +An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two +columns), never by position. Rows whose columns are the held table's columns in another +order, each of the held type (a logical type compared by its storage type), are put in +the held order (the rows still pending, else the stored table) by every database before +they are queued and before the checks that compare them with the held columns (field +attributes, declared nulls, schema compatibility), whether the table was flushed in +between or not; the checks that look at the rows alone (a storable type, the record id) +come first. Rows still queued are matched again, by name, to the stored table when they +are read with it or written. A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b2a435116..5761b8f09 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -101,6 +101,15 @@ def __init__( # The schema each stored table was read with, for the append check # (``_refuse_changed_columns``). self._stored_schemas: dict[str, pa.Schema] = {} + # Each stored table's columns (name and large-normalized type, in the stored + # order) as this handle last saw them: looked up by an append, read, or + # written by a flush; ``None`` for a table found absent (ITL-1367). An + # append to a table already seen looks nothing up; a read and a flush + # combine queued rows with what is stored now, by name. + self._known_columns: dict[str, list[tuple[str, pa.DataType]] | None] = {} + # A lookup an append made with nothing queued, for the flush of that batch + # to use instead of looking the table up again. + self._lookups_for_flush: dict[str, list[tuple[str, pa.DataType]] | None] = {} # 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. @@ -465,20 +474,49 @@ def _held_column_order( """Each column the table holds, with its type, in the held order (ITL-1367). The pending batch's order when rows are pending, else the stored table's as - the connector reports it now (``get_column_info``, the types ``flush`` - compares), else ``None``. It is read on every call, never cached, so a table - dropped and created again in another order is read as it is now. + this handle last saw it (its lookup, read or flush), else looked up now + (``get_column_info``, the types ``flush`` compares, shared with that flush), + else ``None``. A table another connection created again since may have + another order: a read and a flush match the queued rows to what is stored + then, by name (``_in_stored_order``). """ pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: return [(f.name, f.type) for f in pending.schema] table_name = self._path_to_table_name(self._path_prefix + record_path) + if table_name in self._known_columns: + return self._known_columns[table_name] + columns = self._look_up_columns(table_name) + self._lookups_for_flush[table_name] = columns + return columns + + def _look_up_columns(self, table_name: str) -> list[tuple[str, pa.DataType]] | None: + """The stored table's columns as the connector reports them now, in its order + (``get_column_info``, large-normalized types), or ``None`` when it does not + exist; remembered as the table's known columns.""" if table_name not in self._connector.get_table_names(): - return None - return [ - (c.name, normalize_to_large_types(c.arrow_type, keep_null=True)) - for c in self._connector.get_column_info(table_name) - ] + columns = None + else: + columns = [ + (c.name, normalize_to_large_types(c.arrow_type, keep_null=True)) + for c in self._connector.get_column_info(table_name) + ] + self._known_columns[table_name] = columns + return columns + + def _in_stored_order( + self, pending: pa.Table, stored: list[tuple[str, pa.DataType]] | None + ) -> pa.Table: + """Queued rows in the order of the stored table they are combined with. + + The one place queued and stored rows meet (a read, a flush): the rows were + put in the order known when they were queued, and another connection may + have created the table again since in another order, so they are matched to + what is stored now, by name (ITL-1367). + """ + if stored is None: + return pending + return in_held_column_order(pending, stored) def _refuse_changed_columns( self, record_path: tuple[str, ...], schema: pa.Schema @@ -591,14 +629,16 @@ def flush(self) -> None: # names and Arrow types match before writing. Schema evolution is # intentionally out of scope; a clear ValueError is preferable to a # cryptic DB-level error or a silent partial write. - existing_table_names = self._connector.get_table_names() - if table_name in existing_table_names: + # The lookup the batch's first append made, else one now. + existing = ( + self._lookups_for_flush.pop(table_name) + if table_name in self._lookups_for_flush + else self._look_up_columns(table_name) + ) + if existing is not None: # A connector reads text and binary back in their large variants, # which are the same types (ITL-1162). - existing_cols = { - c.name: normalize_to_large_types(c.arrow_type, keep_null=True) - for c in self._connector.get_column_info(table_name) - } + existing_cols = dict(existing) pending_cols = { c.name: normalize_to_large_types(c.arrow_type, keep_null=True) for c in columns @@ -619,6 +659,8 @@ def _fmt(cols: dict) -> str: "Schema evolution is not supported." ) + pending = self._in_stored_order(pending, existing) + self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) @@ -628,6 +670,11 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) + if existing is None: + self._known_columns[table_name] = [ + (f.name, normalize_to_large_types(f.type, keep_null=True)) + for f in pending.schema + ] # ── Read methods ────────────────────────────────────────────────────────── @@ -668,11 +715,20 @@ def get_all_records( parts: list[pa.Table] = [] committed = self._get_committed_table(record_path) + stored: list[tuple[str, pa.DataType]] | None = None + if committed is not None: + stored = [ + (f.name, normalize_to_large_types(f.type, keep_null=True)) + for f in committed.schema + ] + self._known_columns[ + self._path_to_table_name(self._path_prefix + record_path) + ] = stored if committed is not None and committed.num_rows > 0: parts.append(committed) pending = self._pending_batches.get(record_key) if pending is not None and pending.num_rows > 0: - parts.append(pending) + parts.append(self._in_stored_order(pending, stored)) if not parts: return None diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 5fc4dd3ff..7969b0941 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1089,6 +1089,7 @@ def __init__( _shared_snapshots: "dict[str, _CommittedSnapshot] | None" = None, _shared_pending_indexes: "dict[str, KeyIndex] | None" = None, _shared_absent_tables: "set[str] | None" = None, + _shared_reordered_keys: "set[str] | None" = None, ): self._root_uri, self._storage_options = parse_base_path( base_path, storage_options @@ -1148,11 +1149,18 @@ def __init__( self._absent_tables: set[str] = ( _shared_absent_tables if _shared_absent_tables is not None else set() ) + # Record keys whose pending rows include rows reordered by name to the held + # order (ITL-1367): committed by MERGE, as main commits rows given in another + # order than the stored table's. Family-wide like the pending batches. + self._reordered_keys: set[str] = ( + _shared_reordered_keys if _shared_reordered_keys is not None else set() + ) def _clear_pending(self): """Clear all pending state.""" self._pending_batches = {} self._pending_record_ids = defaultdict(set) + self._reordered_keys = set() # Note: next_row_index continues incrementing def _get_record_key(self, record_path: tuple[str, ...]) -> str: @@ -1893,10 +1901,6 @@ 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) - # Columns match by name: rows with the held columns in another order are - # put in the held order (ITL-1367). - records = in_held_column_order(records, self._held_column_order(record_path)) - # 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) @@ -1917,6 +1921,18 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table + # Columns match by name: rows with the held columns in another order are + # put in the held order (ITL-1367). Looked up only for rows that will be + # queued. A table whose rows were reordered is committed by MERGE, as main + # commits rows that are not in the stored layout: insert-if-missing against + # the version the commit loads, never a blind append. + given_order = filtered_table.column_names + filtered_table = in_held_column_order( + filtered_table, self._held_column_order(record_path) + ) + if filtered_table.column_names != given_order: + self._reordered_keys.add(self._get_record_key(record_path)) + # 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). @@ -2602,6 +2618,8 @@ def _flush_by_key(self, record_key: str) -> None: # Get all pending records pending_batch = self._pending_batches.pop(record_key) pending_ids = self._pending_record_ids.pop(record_key, set()) + reordered = record_key in self._reordered_keys + self._reordered_keys.discard(record_key) # Derive the absolute table URI directly from the key (already includes prefix). abs_path_components = tuple(record_key.split("/")) @@ -2691,8 +2709,10 @@ def _flush_by_key(self, record_key: str) -> None: assert base.ids is not None incoming_ids = self._non_null_ids(combined_table) inserted_ids = incoming_ids - base.ids - if len(inserted_ids) == len(incoming_ids) and self._stores_as_is( - delta_table, combined_table + if ( + not reordered + and len(inserted_ids) == len(incoming_ids) + and self._stores_as_is(delta_table, combined_table) ): # Every pending id is new in the version just loaded and the rows # have the stored schema: append (ITL-919). A MERGE reads the whole @@ -2744,6 +2764,8 @@ def _flush_by_key(self, record_key: str) -> None: # Put the tables back in the pending queue self._pending_batches[record_key] = pending_batch self._pending_record_ids[record_key] = pending_ids + if reordered: + self._reordered_keys.add(record_key) raise # The rows are committed: nothing below may put them back in the queue. @@ -3166,6 +3188,7 @@ def at(self, *path_components: str) -> "DeltaTableDatabase": _shared_snapshots=root_instance._snapshots, _shared_pending_indexes=root_instance._pending_indexes, _shared_absent_tables=root_instance._absent_tables, + _shared_reordered_keys=root_instance._reordered_keys, ) def list_sources(self) -> list[tuple[str, ...]]: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 4fb4c632e..479ac702a 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -215,11 +215,12 @@ def in_held_column_order( fields are kept as given (metadata, nullability): the append checks that follow compare them by name. - Anything else is returned as given, for the database's own append rule: no held - table, a column added or missing, a type that differs (a struct whose children - are in another order included: its type differs), and names that repeat or that - differ in case only, which a database matching names without case could pair - otherwise. + Types are compared as the database compares them: a logical (extension) type as + its storage type, in the large variants. Anything else is returned as given, for + the database's own append rule: no held table, a column added or missing, a type + that differs (a struct whose children are in another order included: its type + differs; ITL-1368), and a name that repeats exactly. Names are matched exactly, as + Arrow matches them: ``a`` and ``A`` are two columns. Args: records: The rows to append, the record id column already named as held. @@ -236,16 +237,26 @@ def in_held_column_order( held_names = [name for name, _ in held] if names == held_names: return records - if len({n.casefold() for n in names}) != len(names): - return records - if len({n.casefold() for n in held_names}) != len(held_names): + # Arrow matches names exactly: ``a`` and ``A`` are two columns. Only a name that + # repeats exactly cannot be matched. + if len(set(names)) != len(names) or len(set(held_names)) != len(held_names): return records if set(names) != set(held_names): return records - large = arrow_utils.normalize_to_large_types held_types = dict(held) for field in records.schema: - given = large(field.type, keep_null=True) - if given != large(held_types[field.name], keep_null=True): + if _stored_form(field.type) != _stored_form(held_types[field.name]): return records return records.select(held_names) + + +def _stored_form(arrow_type: "pa.DataType") -> "pa.DataType": + """``arrow_type`` as a database compares it: a logical (extension) type as its + storage type, a dictionary as its value type, in the large variants. A database + that holds such a column reports that type, so the comparison sees what the + database sees.""" + if isinstance(arrow_type, pa.ExtensionType): + arrow_type = arrow_type.storage_type + if pa.types.is_dictionary(arrow_type): + arrow_type = cast(Any, arrow_type).value_type + return arrow_utils.normalize_to_large_types(arrow_type, keep_null=True) diff --git a/tests/test_core/data_function/test_function_record.py b/tests/test_core/data_function/test_function_record.py index 41a210e73..a6ce0fd71 100644 --- a/tests/test_core/data_function/test_function_record.py +++ b/tests/test_core/data_function/test_function_record.py @@ -461,24 +461,21 @@ def test_a_function_without_source_works_in_a_job_and_stores_a_null( @pytest.mark.parametrize( - "database_kind", - [ - pytest.param( - "in_memory", - marks=pytest.mark.xfail( - strict=True, - reason="ITL-1263: InMemoryArrowDatabase refuses rows whose columns " - + "are in another order than the stored table", - ), - ), - "delta", - ], + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] ) +@pytest.mark.parametrize("database_kind", ["in_memory", "delta"]) @pytest.mark.parametrize("name", ["same2", "same3"]) def test_swapped_same_typed_keys_store_different_signature_hashes( - name: str, database_kind: str, tmp_path: Path + name: str, database_kind: str, orchestrator: type, tmp_path: Path ) -> None: - """One uri, one result table; each order's rows record their own signature.""" + """One uri, one result table; each order's rows record their own signature. + + The orders write the output columns (and their source-info columns) in other + orders into one result table: every database matches them by name (ITL-1263, + ITL-1367), on the sync and the async path. ``same3`` is written in three orders. + The connector databases cannot hold a result table (ITL-1162); they are covered + by ``tests/test_databases/test_append_by_name.py``. + """ fn, keys = FUNCTIONS[name] database = ( DeltaTableDatabase(tmp_path / "store") @@ -486,6 +483,8 @@ def test_swapped_same_typed_keys_store_different_signature_hashes( else InMemoryArrowDatabase() ) orders = [tuple(keys), tuple(reversed(keys))] + if len(keys) == 3: + orders.append((keys[1], keys[2], keys[0])) for index, order in enumerate(orders): job = PipelineJob(name="orders", database=database) with job: @@ -499,14 +498,15 @@ def test_swapped_same_typed_keys_store_different_signature_hashes( ), label="fn", ) - job.run() + job.run(orchestrator=orchestrator()) + assert len(list(job.nodes["fn"].iter_data())) == 1 result_paths = [p for p in database.list_table_paths() if "_result" in p] assert len(result_paths) == 1 stored = database.get_all_records(result_paths[0]) assert stored is not None signatures = stored.column("__pf_var_function_signature_hash").to_pylist() contents = stored.column("__pf_var_function_content_hash").to_pylist() - assert len(signatures) == 2 and len(set(signatures)) == 2 + assert len(signatures) == len(orders) and len(set(signatures)) == len(orders) assert len(set(contents)) == 1 diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 54fac8c8d..9cfe5ba75 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -5,7 +5,7 @@ the pending batch's order, else the stored table's. The table keeps the order of its first write. ``a`` and ``c`` are both ``int64``, so a positional match would swap their values: every test reads the values back by name. Appends that add, lack or retype a -column, and names that repeat or differ in case only, keep the database's own rule. +column, and a name that repeats exactly, keep the database's own rule. """ from __future__ import annotations @@ -17,12 +17,20 @@ from contextlib import ExitStack from pathlib import Path from typing import Any +from unittest.mock import patch import pyarrow as pa import pytest -from orcapod.databases import ConnectorArrowDatabase +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + ExtensionAwareDatabase, + SpiralDBConnector, + SQLiteConnector, +) from orcapod.databases.utils import in_held_column_order +from orcapod.errors import InputValidationError, UnstorableColumnError from tests.test_databases.type_matrix import open_database PATH = ("t",) @@ -145,42 +153,63 @@ def test_a_new_table_keeps_the_order_the_database_gave_its_first_write( assert table.column_names == _given_order(database, order) +# Today's verdict for an append that is reordered AND retypes ``a`` (``int32`` where +# ``int64`` is held), measured on main 321284ae with the same fake: (where it is refused, +# the exception). The rows are not reordered (another type), so the verdict is the +# database's own; the stored rows are the first write's either way. +RETYPE_VERDICTS: dict[tuple[str, str], tuple[str, type[BaseException]]] = { + ("in-memory", "after a flush"): ("flush", pa.ArrowInvalid), + ("in-memory", "same pending batch"): ("add", pa.ArrowInvalid), + ("Delta", "after a flush"): ("add", InputValidationError), + ("Delta", "same pending batch"): ("add", ValueError), + ("SQLite", "after a flush"): ("add", UnstorableColumnError), + ("SQLite", "same pending batch"): ("add", UnstorableColumnError), + ("SpiralDB", "after a flush"): ("flush", ValueError), + ("SpiralDB", "same pending batch"): ("add", pa.ArrowInvalid), +} + + @pytest.mark.parametrize("database", DATABASES) @pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) def test_an_append_that_also_retypes_a_column_keeps_todays_rule( tmp_path: Path, database: str, when: str ) -> None: - """Another type is not a reordering: the rows are left as given, for the - database's own rule. Whatever that rule does, no value is matched by position.""" + """Another type is not a reordering: the rows are left as given, and the + database's own rule refuses them where it does today; the stored rows stay.""" + stage, error = RETYPE_VERDICTS[(database, when)] retyped = _rows(["c", "a", "b", ID], [3]).set_column( 1, "a", pa.array([3], pa.int32()) ) with open_database(database, tmp_path) as db: _add(db, _rows([ID, "a", "c", "b"], [1]), flush=when == "after a flush") - try: - _add(db, retyped, flush=True) - except Exception: # noqa: BLE001 # today's rule refused it: nothing swapped - return + if stage == "add": + with pytest.raises(error): + _add(db, retyped) + db.flush() + else: + _add(db, retyped) + with pytest.raises(error): + db.flush() table = db.get_all_records(PATH, record_id_column=ID) assert table is not None - got = sorted(table.select([ID, "a", "c"]).to_pylist(), key=lambda r: r["a"]) - assert got == [ - {ID: b"r1", "a": 1, "c": 101}, - {ID: b"r3", "a": 3, "c": 103}, + assert table.schema.field("a").type == pa.int64() + assert table.select([ID, "a", "c"]).to_pylist() == [ + {ID: b"r1", "a": 1, "c": 101} ] def test_a_table_created_again_in_another_order_is_read_as_it_is_now( tmp_path: Path, ) -> None: - """The connector database reads the stored order on every append, so a table - dropped and created again in another order is matched to its new order.""" + """A table dropped and created again in another order by another connection: + this handle's next append is matched to the new order by name, values right.""" with open_database("SQLite", tmp_path) as db: _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) _add(db, _rows(["c", "a", "b", ID], [2]), flush=True) with sqlite3.connect(tmp_path / "store.db") as other: other.execute('DROP TABLE "t"') - _add(db, _rows(["b", ID, "c", "a"], [3]), flush=True) + other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) _check( db.get_all_records(PATH, record_id_column=ID), @@ -189,13 +218,38 @@ def test_a_table_created_again_in_another_order_is_read_as_it_is_now( ) +def test_rows_queued_before_a_table_is_created_again_are_read_with_it_by_name( + tmp_path: Path, +) -> None: + """Rows queued in the old stored order, then the table dropped and created again + in another order by another connection: a read before the flush, and the flush, + combine the queued rows with what is stored now, by name.""" + with open_database("SQLite", tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) + _add(db, _rows(["b", ID, "c", "a"], [2])) # queued as [id, a, c, b] + with sqlite3.connect(tmp_path / "store.db") as other: + other.execute('DROP TABLE "t"') + other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) + _check( + db.get_all_records(PATH, record_id_column=ID), ["b", ID, "c", "a"], [2, 3] + ) + db.flush() + _check( + other_db.get_all_records(PATH, record_id_column=ID), + ["b", ID, "c", "a"], + [2, 3], + ) + + def test_a_spiraldb_table_deleted_and_created_again_in_another_order( tmp_path: Path, ) -> None: with open_database("SpiralDB", tmp_path) as db: _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) db._connector.delete_table("t") # the connector's own drop - _add(db, _rows(["b", ID, "c", "a"], [3]), flush=True) + other_db = ConnectorArrowDatabase(SpiralDBConnector("p")) + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) _check( db.get_all_records(PATH, record_id_column=ID), @@ -235,6 +289,26 @@ def test_the_step_keeps_the_given_fields() -> None: assert out.schema.field("c").equals(field, check_metadata=True) +def test_the_step_matches_names_exactly() -> None: + """``a`` and ``A`` are two columns, as Arrow matches names exactly.""" + out = in_held_column_order(_table("A", "a", "c"), _held("a", "c", "A")) + assert out.column_names == ["a", "c", "A"] + assert out.to_pylist() == [{"A": 0, "a": 1, "c": 2}] + + +def test_the_step_compares_a_logical_type_by_its_storage() -> None: + """A database holding a logical column reports its storage type.""" + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + _, ext_type = _make_converter_with_type("test.itl1367.storage") + text = pa.ExtensionArray.from_storage(ext_type, pa.array(["x"], pa.large_string())) + given = pa.table({"text": text, "a": [1]}) + out = in_held_column_order(given, [("a", pa.int64()), ("text", pa.string())]) + assert out.column_names == ["a", "text"] + + def test_the_step_compares_types_in_their_large_variants() -> None: given = pa.table({"b": pa.array(["x"], pa.string()), "a": [1]}) out = in_held_column_order(given, [("a", pa.int64()), ("b", pa.large_string())]) @@ -248,9 +322,6 @@ def test_the_step_compares_types_in_their_large_variants() -> None: pytest.param(_table("c", "a"), _held("a", "b", "c"), id="a column missing"), pytest.param(_table("c", "a", "b"), _held("a", "c"), id="a column added"), pytest.param(_table("c", "A"), _held("a", "c"), id="a name in another case"), - pytest.param( - _table("A", "a", "c"), _held("a", "c", "A"), id="names differing in case" - ), pytest.param(_table("c", "a", "a"), _held("a", "c", "a"), id="a repeated name"), pytest.param( _table("c", "a"), @@ -281,24 +352,186 @@ def test_the_step_leaves_anything_else_as_given( assert in_held_column_order(given, held) is given -def test_names_differing_in_case_only_keep_todays_rule() -> None: - """The in-memory database holds ``a`` and ``A`` apart; a reordered append of them - is not reordered and is refused, as it is today.""" - with open_database("in-memory", Path(".")) as db: - _add(db, _table_with_id([ID, "a", "A"])) - with pytest.raises(pa.ArrowInvalid): - _add(db, _table_with_id(["A", ID, "a"])) +@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_names_differing_in_case_only_are_two_columns( + tmp_path: Path, database: str, when: str +) -> None: + """The in-memory and Delta databases hold ``a`` and ``A`` apart; an append of them + in another order is matched by exact name.""" + with open_database(database, tmp_path) as db: + _add(db, _table_with_id(b"r1", [ID, "a", "A"]), flush=when == "after a flush") + _add(db, _table_with_id(b"r2", ["A", ID, "a"])) + db.flush() + table = db.get_all_records(PATH, record_id_column=ID) + assert table is not None + assert sorted(table.select([ID, "a", "A"]).to_pylist(), key=str) == [ + {ID: b"r1", "a": 1, "A": 2}, + {ID: b"r2", "a": 1, "A": 2}, + ] -def _table_with_id(order: list[str]) -> pa.Table: +def _table_with_id(rid: bytes, order: list[str]) -> pa.Table: columns = { - ID: pa.array([uuid.uuid4().bytes], pa.large_binary()), + ID: pa.array([rid], pa.large_binary()), "a": pa.array([1], pa.int64()), "A": pa.array([2], pa.int64()), } return pa.table({name: columns[name] for name in order}) +@pytest.mark.parametrize("stored", [True, False], ids=["committed", "pending"]) +def test_a_logical_column_is_matched_by_name_through_the_extension_database( + tmp_path: Path, stored: bool +) -> None: + """Delta stores a logical column as its storage type; an append of it in another + order is put in the held order whether the held rows are committed or pending.""" + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + converter, ext_type = _make_converter_with_type("test.itl1367.extension") + + def rows(n: int, order: list[str]) -> pa.Table: + columns = { + ID: pa.array([bytes([n])], pa.large_binary()), + "text": pa.ExtensionArray.from_storage( + ext_type, pa.array([str(n)], pa.large_string()) + ), + "n": pa.array([n], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + db = ExtensionAwareDatabase(DeltaTableDatabase(tmp_path / "delta"), converter) + _add(db, rows(1, [ID, "text", "n"]), flush=stored) + _add(db, rows(2, ["n", ID, "text"])) + pending = db.get_record_by_id(PATH, bytes([2]), record_id_column=ID) + assert pending is not None + db.flush() + committed = db.get_record_by_id(PATH, bytes([2]), record_id_column=ID) + assert committed is not None + assert pending.column_names == committed.column_names + assert committed.to_pylist() == [{ID: bytes([2]), "text": "2", "n": 2}] + + +# ── Delta: the commit a reordered append takes ───────────────────────────────── + + +def _race_rows(n: int, value: int, order: tuple[str, ...]) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([value], pa.int64()), + "b": pa.array([1000 + value], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("skip_duplicates", [True, False]) +@pytest.mark.parametrize( + ("stale_order", "other_order"), + [(("a", "b", "rid"), ("b", "rid", "a")), (("b", "rid", "a"), ("a", "b", "rid"))], +) +def test_a_reordered_append_is_committed_as_insert_if_missing_across_writers( + tmp_path: Path, + skip_duplicates: bool, + stale_order: tuple[str, ...], + other_order: tuple[str, ...], +) -> None: + """Two handles append the same new record id with different values, each in + another order than the stored table. The second commits after the first has + taken its snapshot of the stored ids. As on main (where rows in another order + than the stored table are committed by MERGE), the stale commit fails and the id + keeps one row: the reorder does not turn the commit into a blind append.""" + stale, other = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + stale.add_records( + PATH, _race_rows(1, 10, ("rid", "a", "b")), record_id_column="rid", flush=True + ) + snapshot = stale._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + other.add_records( + PATH, + _race_rows(2, 20, other_order), + record_id_column="rid", + flush=True, + skip_duplicates=skip_duplicates, + ) + return taken + + with patch.object(stale, "_snapshot_for_commit", side_effect=interleave): + with pytest.raises(RuntimeError) as raised: + stale.add_records( + PATH, + _race_rows(2, 99, stale_order), + record_id_column="rid", + flush=True, + skip_duplicates=skip_duplicates, + ) + assert type(raised.value.__cause__).__name__ == "CommitFailedError" + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + assert sorted(table.select(["rid", "a"]).to_pylist(), key=str) == [ + {"rid": bytes([1]), "a": 10}, + {"rid": bytes([2]), "a": 20}, + ] + + +def test_an_all_duplicate_append_looks_up_no_order(tmp_path: Path) -> None: + """With ``skip_duplicates`` and nothing left to write, the stored order is not + looked up: a stored table whose recorded type cannot be read does not fail an + append that writes nothing.""" + from deltalake import write_deltalake + + rows = _rows([ID, "a", "c", "b"], [1]).rename_columns( + ["__record_id", "a", "c", "b"] + ) + schema = rows.schema.set( + 2, rows.schema.field(2).with_metadata({b"orcapod:arrow_type": b"invalid"}) + ) + write_deltalake(tmp_path / "t", pa.Table.from_arrays(rows.columns, schema=schema)) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows(["b", ID, "c", "a"], [1]), + record_id_column=ID, + skip_duplicates=True, + flush=True, + ) + + +# ── Lookups ──────────────────────────────────────────────────────────────────── + + +def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> None: + """The connector database looks a table up once per flushed append, as main + does: an append on a fresh handle shares its lookup with the flush, and an + append to a table the handle has seen looks nothing up before the flush.""" + path = str(tmp_path / "store.db") + ConnectorArrowDatabase(SQLiteConnector(path)).add_records( + PATH, _rows([ID, "a", "c", "b"], [1]), record_id_column=ID, flush=True + ) + connector = SQLiteConnector(path) + db = ConnectorArrowDatabase(connector) + with ( + patch.object( + connector, "get_table_names", wraps=connector.get_table_names + ) as names, + patch.object( + connector, "get_column_info", wraps=connector.get_column_info + ) as info, + ): + _add(db, _rows([ID, "a", "c", "b"], [2]), flush=True) + assert (names.call_count, info.call_count) == (1, 1) + _add(db, _rows(["b", ID, "c", "a"], [3])) + assert (names.call_count, info.call_count) == (1, 1) + db.flush() + assert (names.call_count, info.call_count) == (2, 2) + _check( + db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3] + ) + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 6d8a01c6b..19683b083 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1056,10 +1056,15 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. -An append matches columns by name, never by position. Rows whose columns are the held -table's columns in another order, each of the held type, are put in the held order (the -rows still pending, else the stored table) by every database before anything is checked -or written, whether the table was flushed in between or not. A table keeps the column +An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two +columns), never by position. Rows whose columns are the held table's columns in another +order, each of the held type (a logical type compared by its storage type), are put in +the held order (the rows still pending, else the stored table) by every database before +they are queued and before the checks that compare them with the held columns (field +attributes, declared nulls, schema compatibility), whether the table was flushed in +between or not; the checks that look at the rows alone (a storable type, the record id) +come first. Rows still queued are matched again, by name, to the stored table when they +are read with it or written. A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also From e8751e426d725cc23d12a2cbcba8bdc38a4dbba0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:03:43 -0800 Subject: [PATCH 3/6] fix(databases): append-by-name trusts nothing stored across calls and never merges two logical types (ITL-1367) PR 491 review round 2 (Codex): - the connector database no longer remembers a stored table's order: an append is aligned only to this handle's pending batch; a flush looks the table up then, checks the rows by exact name and type as main does, and only then puts them in the stored order; a read and a queued-row lookup match to the table read then - a Delta MERGE marker is set only for rows actually queued, so a refused append leaves the next aligned batch on main's commit path - the shared step takes fields and requires the same logical type (extension name and metadata, or the field's ARROW:extension annotation), not only the same storage type - tests: a table renamed, extended, narrowed or retyped between queue and flush (main's refusal, stored rows untouched), a replacement table written by the same handle, a SpiralDB queued-row lookup, a refused reordered Delta append in every mode, two logical types over one storage type Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1367.md | 18 +- docs/dev/design_issues/ITL-1367-CO1.md | 53 ++-- docs/reference/database-types.md | 16 +- .../databases/connector_arrow_database.py | 114 +++----- src/orcapod/databases/delta_lake_databases.py | 17 +- src/orcapod/databases/in_memory_databases.py | 4 +- src/orcapod/databases/utils.py | 65 +++-- tests/test_databases/test_append_by_name.py | 251 +++++++++++++++++- tests/test_databases/type_matrix.py | 16 +- 9 files changed, 398 insertions(+), 156 deletions(-) diff --git a/changelog.d/ITL-1367.md b/changelog.d/ITL-1367.md index 73da65c13..a189aab46 100644 --- a/changelog.d/ITL-1367.md +++ b/changelog.d/ITL-1367.md @@ -5,13 +5,13 @@ and SQLite while the earlier rows were still pending, and by the SpiralDB test fake, so a job node that produced the same columns in another order than an earlier write could not store them. Every database (in-memory, Delta, SQLite, PostgreSQL, SpiralDB) now puts such - rows in the order the table already has (the rows still pending, else the stored table) - before they are queued, after a flush and within one pending batch alike, and matches - rows still queued to the stored table by name again when they are read with it or - written; names are matched exactly (`a` and `A` are two columns) and values are never - matched by position. A reordered append to a Delta table is committed as an - insert-if-missing (MERGE), as before, so two writers appending one record id still - cannot both store it. A table keeps the column order its database gave - the first write (SpiralDB orders a table's columns its own way: the key columns, then the - other columns by name). An append that also adds, omits or retypes a column, and a struct + rows in the order the table already has (the rows still pending, else the stored table; + a connector database checks queued rows against the stored table as it is when it + writes or reads them, then puts them in its order), after a flush and within one + pending batch alike; names are matched exactly (`a` and `A` are two columns), a logical + type must be the held one, and values are never matched by position. A reordered append + to a Delta table is committed as an insert-if-missing (MERGE), as before, so two + writers appending one record id still cannot both store it. A table keeps the column + order its database gave the first write (SpiralDB orders a table's columns its own way: + the key columns, then the other columns by name). An append that also adds, omits or retypes a column, and a struct whose fields are in another order, keep each database's own rule. (ITL-1367) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index 841911a0a..1c6acdd90 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -21,25 +21,40 @@ columns in key-schema order, then the value columns sorted by name (code point: `a`), struct children sorted by name too. The fake refused what SpiralDB accepts and kept the written order. -**Fix:** one shared step, `databases/utils.in_held_column_order`, called by every database -in `add_records` before the rows are queued and before the checks that compare them with -the held columns (the checks on the rows alone come first; Delta looks the order up only -for rows left after duplicates are dropped), in every database (in-memory, Delta, -`ConnectorArrowDatabase` for SQLite, PostgreSQL and SpiralDB). Rows with exactly the held -columns in another order, each of the held type (compared in the large variants), are put -in the held order: the pending batch's, else the stored table's. Anything else keeps the database's own rule: a column added or missing, a -type that differs (a logical type is compared by its storage type), a name that repeats -exactly (names match exactly: `a` and `A` are two columns). The connector database -remembers each table's order from its own lookups, reads and writes (one lookup per -flushed append, as before), and matches queued rows to the stored table again, by name, -when it reads them with it or flushes them, so a table created again in another order by -another connection is combined correctly. A Delta append that was reordered is committed -by MERGE (insert-if-missing), the commit main chose for rows in another order, never a -blind append. A table keeps the order its -database gave the first write (SpiralDB: its own order). The SpiralDB fake now mirrors -SpiralDB at the top level: it matches a write by name and stores the key columns, then the -value columns by name. Tests: `tests/test_databases/test_append_by_name.py`; live: -`TestColumnOrderLive` in `tests/test_databases/test_spiraldb_connector_integration.py`. +**Fix:** one shared step, `databases/utils.in_held_column_order`, in every database +(in-memory, Delta, `ConnectorArrowDatabase` for SQLite, PostgreSQL and SpiralDB). Rows with +exactly the held columns in another order, each with the held column's type (compared in +the large variants, a logical type by its storage type) and the same logical type (an +extension type's name and metadata, or the `ARROW:extension` annotation of a field held +as its storage type), are put in the held order, by name. Names match exactly (`a` and +`A` are two columns). Anything else keeps the database's own rule: a column added or +missing, a type or logical type that differs, a name that repeats exactly. + +Where the step runs, and against what: + +- In-memory and Delta: when rows are queued, against the batch pending for the table, + else the stored table, after the checks on the rows alone and, in Delta, after + duplicates are dropped, before the checks that compare the rows with the held columns. + A Delta batch holding rows reordered this way is committed by MERGE (insert-if-missing), + the commit main chose for rows in another order; the marker is set only for rows + actually queued and leaves with them. +- The connector database: when rows are queued, only against the batch this handle has + pending for the table. Nothing about a stored table is trusted across calls (another + connection may rename, add, drop, retype or create a column again in between): a flush + looks the table up then, checks the queued rows against it by exact name and type as + main does, and only then puts them in the stored order; a read that combines stored and + queued rows, and a point lookup of a queued row, match them to the stored table read + then. + +A table keeps the order its database gave the first write (SpiralDB: its own order). The +SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores +the key columns, then the value columns by name. Tests: +`tests/test_databases/test_append_by_name.py`; live: `TestColumnOrderLive` in +`tests/test_databases/test_spiraldb_connector_integration.py`. + +Found in review, pre-existing on main and not changed here: through +`ExtensionAwareDatabase`, rows of another logical type over the same storage type, in the +SAME column order, are accepted and read back as the held logical type. Not covered: the order of a struct's fields (a struct with its fields in another order is another type here, and the fake keeps struct children as written): ITL-1368. A canonical diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index f0dde1d5a..7d65a13db 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -83,13 +83,15 @@ as nullable afterwards, as Delta stores it. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Rows whose columns are the held table's columns in another -order, each of the held type (a logical type compared by its storage type), are put in -the held order (the rows still pending, else the stored table) by every database before -they are queued and before the checks that compare them with the held columns (field -attributes, declared nulls, schema compatibility), whether the table was flushed in -between or not; the checks that look at the rows alone (a storable type, the record id) -come first. Rows still queued are matched again, by name, to the stored table when they -are read with it or written. A table keeps the column +order, each of the held type and logical type (a logical type held as its storage type +is compared by both), are put in the held order by every database, whether the table was +flushed in between or not. The in-memory and Delta databases do it when the rows are +queued (against the rows still pending, else the stored table), after the checks that +look at the rows alone and before the checks that compare them with the held columns. A +connector database (SQLite, PostgreSQL, SpiralDB) does it when the rows are queued only +against rows it has pending, and against the stored table when it writes or reads them: +the flush checks them against the table as it is then, by exact name and type, before +putting them in its order. A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 5761b8f09..6c16f6bf5 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -101,15 +101,6 @@ def __init__( # The schema each stored table was read with, for the append check # (``_refuse_changed_columns``). self._stored_schemas: dict[str, pa.Schema] = {} - # Each stored table's columns (name and large-normalized type, in the stored - # order) as this handle last saw them: looked up by an append, read, or - # written by a flush; ``None`` for a table found absent (ITL-1367). An - # append to a table already seen looks nothing up; a read and a flush - # combine queued rows with what is stored now, by name. - self._known_columns: dict[str, list[tuple[str, pa.DataType]] | None] = {} - # A lookup an append made with nothing queued, for the flush of that batch - # to use instead of looking the table up again. - self._lookups_for_flush: dict[str, list[tuple[str, pa.DataType]] | None] = {} # 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. @@ -470,53 +461,31 @@ def add_records( def _held_column_order( self, record_path: tuple[str, ...] - ) -> list[tuple[str, pa.DataType]] | None: - """Each column the table holds, with its type, in the held order (ITL-1367). - - The pending batch's order when rows are pending, else the stored table's as - this handle last saw it (its lookup, read or flush), else looked up now - (``get_column_info``, the types ``flush`` compares, shared with that flush), - else ``None``. A table another connection created again since may have - another order: a read and a flush match the queued rows to what is stored - then, by name (``_in_stored_order``). + ) -> "list[pa.Field[Any]] | None": + """The columns of the batch pending for the table, in its order, or ``None``. + + An append is aligned when it is queued only to rows this handle queued + (ITL-1367): nothing about a stored table is trusted across calls, since + another connection may rename, add, drop, retype or create again a column + between two calls. The stored table is looked up fresh where queued and + stored rows meet, a flush and a read (``_stored_columns``), and the queued + rows are matched to it there, by name, after the flush's own check. """ pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: - return [(f.name, f.type) for f in pending.schema] - table_name = self._path_to_table_name(self._path_prefix + record_path) - if table_name in self._known_columns: - return self._known_columns[table_name] - columns = self._look_up_columns(table_name) - self._lookups_for_flush[table_name] = columns - return columns + return list(pending.schema) + return None - def _look_up_columns(self, table_name: str) -> list[tuple[str, pa.DataType]] | None: + def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": """The stored table's columns as the connector reports them now, in its order (``get_column_info``, large-normalized types), or ``None`` when it does not - exist; remembered as the table's known columns.""" + exist. Never remembered: each call asks the connector.""" if table_name not in self._connector.get_table_names(): - columns = None - else: - columns = [ - (c.name, normalize_to_large_types(c.arrow_type, keep_null=True)) - for c in self._connector.get_column_info(table_name) - ] - self._known_columns[table_name] = columns - return columns - - def _in_stored_order( - self, pending: pa.Table, stored: list[tuple[str, pa.DataType]] | None - ) -> pa.Table: - """Queued rows in the order of the stored table they are combined with. - - The one place queued and stored rows meet (a read, a flush): the rows were - put in the order known when they were queued, and another connection may - have created the table again since in another order, so they are matched to - what is stored now, by name (ITL-1367). - """ - if stored is None: - return pending - return in_held_column_order(pending, stored) + return None + return [ + pa.field(c.name, normalize_to_large_types(c.arrow_type, keep_null=True)) + for c in self._connector.get_column_info(table_name) + ] def _refuse_changed_columns( self, record_path: tuple[str, ...], schema: pa.Schema @@ -629,16 +598,13 @@ def flush(self) -> None: # names and Arrow types match before writing. Schema evolution is # intentionally out of scope; a clear ValueError is preferable to a # cryptic DB-level error or a silent partial write. - # The lookup the batch's first append made, else one now. - existing = ( - self._lookups_for_flush.pop(table_name) - if table_name in self._lookups_for_flush - else self._look_up_columns(table_name) - ) + # Looked up now, as the check needs: nothing about the stored table is + # trusted from an earlier call (ITL-1367). + existing = self._stored_columns(table_name) if existing is not None: # A connector reads text and binary back in their large variants, # which are the same types (ITL-1162). - existing_cols = dict(existing) + existing_cols = {f.name: f.type for f in existing} pending_cols = { c.name: normalize_to_large_types(c.arrow_type, keep_null=True) for c in columns @@ -659,7 +625,9 @@ def _fmt(cols: dict) -> str: "Schema evolution is not supported." ) - pending = self._in_stored_order(pending, existing) + # Checked by exact name and type above: only then are the rows put + # in the stored order, by name (ITL-1367). + pending = in_held_column_order(pending, existing) self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN @@ -670,11 +638,6 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) - if existing is None: - self._known_columns[table_name] = [ - (f.name, normalize_to_large_types(f.type, keep_null=True)) - for f in pending.schema - ] # ── Read methods ────────────────────────────────────────────────────────── @@ -695,6 +658,13 @@ def get_record_by_id( pending = self._pending_batches[record_key] filtered = pending.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows > 0: + # In the stored table's order, as the row reads once committed: the + # rows were queued in the order of the batch (ITL-1367). + stored = self._stored_columns( + self._path_to_table_name(self._path_prefix + record_path) + ) + if stored is not None: + filtered = in_held_column_order(filtered, stored) return self._handle_record_id_column(filtered, record_id_column) # Check committed @@ -715,20 +685,20 @@ def get_all_records( parts: list[pa.Table] = [] committed = self._get_committed_table(record_path) - stored: list[tuple[str, pa.DataType]] | None = None - if committed is not None: - stored = [ - (f.name, normalize_to_large_types(f.type, keep_null=True)) - for f in committed.schema - ] - self._known_columns[ - self._path_to_table_name(self._path_prefix + record_path) - ] = stored if committed is not None and committed.num_rows > 0: parts.append(committed) pending = self._pending_batches.get(record_key) if pending is not None and pending.num_rows > 0: - parts.append(self._in_stored_order(pending, stored)) + # Matched to the stored rows just read, by name (ITL-1367). + if committed is not None: + pending = in_held_column_order( + pending, + [ + f.with_type(normalize_to_large_types(f.type, keep_null=True)) + for f in committed.schema + ], + ) + parts.append(pending) if not parts: return None diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 7969b0941..8ba1d7b61 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1784,8 +1784,8 @@ def _refuse_changed_attributes( def _held_column_order( self, record_path: tuple[str, ...] - ) -> list[tuple[str, pa.DataType]] | None: - """Each column the table holds, with its type, in the held order (ITL-1367). + ) -> "list[pa.Field[Any]] | None": + """The columns the table holds, in the held order (ITL-1367). The pending batch's order when rows are pending, else the stored table's (its log; no data is read), else ``None``. A stored table that cannot be @@ -1793,14 +1793,14 @@ def _held_column_order( """ pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: - return [(f.name, f.type) for f in pending.schema] + return list(pending.schema) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: return None if delta_table is None: return None - return [(name, f.type) for name, f in _held_columns(delta_table).items()] + return list(_held_columns(delta_table).values()) def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema @@ -1930,8 +1930,7 @@ def add_records( filtered_table = in_held_column_order( filtered_table, self._held_column_order(record_path) ) - if filtered_table.column_names != given_order: - self._reordered_keys.add(self._get_record_key(record_path)) + reordered = filtered_table.column_names != given_order # 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 @@ -1955,8 +1954,12 @@ 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 7: Add to pending batch (no overwrite logic needed) + # Step 7: Add to pending batch (no overwrite logic needed). The MERGE marker + # is set only now, for rows actually queued: rows refused above leave no + # trace, and the marker leaves with the rows (flush, refusal at commit). self._add_to_pending_batch(record_path, schema_compatible_table) + if reordered: + self._reordered_keys.add(self._get_record_key(record_path)) # Step 8: Flush if asked to; otherwise commit this table alone once its # pending batch reaches batch_size. Only the full table: committing every diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 34be934c2..3c78dd1e0 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -266,9 +266,7 @@ def add_records( held_table = self._tables.get(record_key) records = in_held_column_order( records, - None - if held_table is None - else [(f.name, f.type) for f in held_table.schema], + None if held_table is None else list(held_table.schema), ) # 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). diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 479ac702a..285d94d78 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -204,29 +204,32 @@ def first_changed_column( def in_held_column_order( - records: "pa.Table", held: "Sequence[tuple[str, pa.DataType]] | None" + records: "pa.Table", held: "Sequence[pa.Field[Any]] | None" ) -> "pa.Table": """``records`` with its columns in the order the database holds them (ITL-1367). An append matches columns by name, never by position: when ``records`` has - exactly the held columns in another order, each with the held type, its columns - are put in the held order, so every database stores and buffers them as the - table already has them, and the table keeps the order of its first write. The - fields are kept as given (metadata, nullability): the append checks that follow - compare them by name. - - Types are compared as the database compares them: a logical (extension) type as - its storage type, in the large variants. Anything else is returned as given, for - the database's own append rule: no held table, a column added or missing, a type - that differs (a struct whose children are in another order included: its type - differs; ITL-1368), and a name that repeats exactly. Names are matched exactly, as - Arrow matches them: ``a`` and ``A`` are two columns. + exactly the held columns in another order, each of the held column's type and + logical type, its columns are put in the held order, so every database stores + and buffers them as the table already has them, and the table keeps the order of + its first write. The fields are kept as given (metadata, nullability): the append + checks that follow compare them by name. + + A type is compared as the database compares it: a logical (extension) type as + its storage type, in the large variants; and the logical identity must be the + same too (``_logical_identity``: an extension type's name and metadata, or the + ``ARROW:extension`` annotation of a field stored as its storage type), so two + logical types over one storage type are never taken for one. Anything else is + returned as given, for the database's own append rule: no held table, a column + added or missing, a type or logical type that differs (a struct whose children + are in another order included: its type differs; ITL-1368), and a name that + repeats exactly. Names are matched exactly, as Arrow matches them: ``a`` and + ``A`` are two columns. Args: records: The rows to append, the record id column already named as held. - held: Each held column's name and type, in the held order (the pending - batch, else the stored table), or ``None`` when the database holds no - such table. + held: The held columns, in the held order (the pending batch, else the + stored table), or ``None`` when the database holds no such table. Returns: ``records``, reordered or as given. @@ -234,7 +237,7 @@ def in_held_column_order( if held is None: return records names = records.column_names - held_names = [name for name, _ in held] + held_names = [field.name for field in held] if names == held_names: return records # Arrow matches names exactly: ``a`` and ``A`` are two columns. Only a name that @@ -243,13 +246,37 @@ def in_held_column_order( return records if set(names) != set(held_names): return records - held_types = dict(held) + held_fields = {field.name: field for field in held} for field in records.schema: - if _stored_form(field.type) != _stored_form(held_types[field.name]): + given = held_fields[field.name] + if _stored_form(field.type) != _stored_form(given.type): + return records + if _logical_identity(field) != _logical_identity(given): return records return records.select(held_names) +_EXTENSION_NAME = b"ARROW:extension:name" +_EXTENSION_METADATA = b"ARROW:extension:metadata" + + +def _logical_identity(field: "pa.Field[Any]") -> tuple[bytes, bytes] | None: + """The logical type a column holds: an extension type's name and metadata, or + the ``ARROW:extension`` annotation of a field held as its storage type (a stored + Delta column, a column the extension-aware wrapper encoded); ``None`` for a plain + column.""" + if isinstance(field.type, pa.ExtensionType): + return ( + field.type.extension_name.encode(), + field.type.__arrow_ext_serialize__(), + ) + metadata = metadata_bytes(field.metadata) + name = metadata.get(_EXTENSION_NAME) + if name is None: + return None + return name, metadata.get(_EXTENSION_METADATA, b"") + + def _stored_form(arrow_type: "pa.DataType") -> "pa.DataType": """``arrow_type`` as a database compares it: a logical (extension) type as its storage type, a dictionary as its value type, in the large variants. A database diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 9cfe5ba75..3075f1177 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -16,7 +16,7 @@ from collections.abc import Iterator from contextlib import ExitStack from pathlib import Path -from typing import Any +from typing import Any, cast from unittest.mock import patch import pyarrow as pa @@ -26,6 +26,7 @@ ConnectorArrowDatabase, DeltaTableDatabase, ExtensionAwareDatabase, + InMemoryArrowDatabase, SpiralDBConnector, SQLiteConnector, ) @@ -261,8 +262,8 @@ def test_a_spiraldb_table_deleted_and_created_again_in_another_order( # ── The shared step ──────────────────────────────────────────────────────────── -def _held(*names: str) -> list[tuple[str, Any]]: - return [(n, pa.int64()) for n in names] +def _held(*names: str) -> list[Any]: + return [pa.field(n, pa.int64()) for n in names] def _table(*names: str) -> pa.Table: @@ -296,22 +297,50 @@ def test_the_step_matches_names_exactly() -> None: assert out.to_pylist() == [{"A": 0, "a": 1, "c": 2}] -def test_the_step_compares_a_logical_type_by_its_storage() -> None: - """A database holding a logical column reports its storage type.""" +def _annotated(name: str, ext_type: Any) -> Any: + """A field held as its storage type, annotated with its logical type (a stored + Delta column, a column the extension-aware wrapper encoded).""" + return pa.field( + name, + pa.string(), + metadata={ + b"ARROW:extension:name": ext_type.extension_name.encode(), + b"ARROW:extension:metadata": ext_type.__arrow_ext_serialize__(), + }, + ) + + +def test_the_step_compares_a_logical_type_by_its_storage_and_identity() -> None: + """A database holding a logical column reports its storage type, annotated with + the logical type: the same logical type is matched; another one over the same + storage type, or a plain column, is not (ITL-1367).""" from tests.test_databases.test_extension_aware_database import ( _make_converter_with_type, ) - _, ext_type = _make_converter_with_type("test.itl1367.storage") - text = pa.ExtensionArray.from_storage(ext_type, pa.array(["x"], pa.large_string())) + _, one = _make_converter_with_type("test.itl1367.one") + _, two = _make_converter_with_type("test.itl1367.two") + text = pa.ExtensionArray.from_storage(one, pa.array(["x"], pa.large_string())) given = pa.table({"text": text, "a": [1]}) - out = in_held_column_order(given, [("a", pa.int64()), ("text", pa.string())]) + a = pa.field("a", pa.int64()) + out = in_held_column_order(given, [a, _annotated("text", one)]) assert out.column_names == ["a", "text"] + assert in_held_column_order(given, [a, _annotated("text", two)]) is given + assert in_held_column_order(given, [a, pa.field("text", pa.string())]) is given + annotated = pa.Table.from_arrays( + [pa.array(["x"]), pa.array([1])], + schema=pa.schema([_annotated("text", two), a]), + ) + assert in_held_column_order(annotated, [a, _annotated("text", one)]) is annotated + held = [a, _annotated("text", two)] + assert in_held_column_order(annotated, held).column_names == ["a", "text"] def test_the_step_compares_types_in_their_large_variants() -> None: given = pa.table({"b": pa.array(["x"], pa.string()), "a": [1]}) - out = in_held_column_order(given, [("a", pa.int64()), ("b", pa.large_string())]) + out = in_held_column_order( + given, [pa.field("a", pa.int64()), pa.field("b", pa.large_string())] + ) assert out.column_names == ["a", "b"] @@ -325,7 +354,7 @@ def test_the_step_compares_types_in_their_large_variants() -> None: pytest.param(_table("c", "a", "a"), _held("a", "c", "a"), id="a repeated name"), pytest.param( _table("c", "a"), - [("a", pa.int64()), ("c", pa.int32())], + [pa.field("a", pa.int64()), pa.field("c", pa.int32())], id="a type differs", ), pytest.param( @@ -339,15 +368,15 @@ def test_the_step_compares_types_in_their_large_variants() -> None: } ), [ - ("a", pa.int64()), - ("s", pa.struct([("x", pa.int64()), ("y", pa.int64())])), + pa.field("a", pa.int64()), + pa.field("s", pa.struct([("x", pa.int64()), ("y", pa.int64())])), ], id="struct children in another order", ), ], ) def test_the_step_leaves_anything_else_as_given( - given: pa.Table, held: list[tuple[str, Any]] | None + given: pa.Table, held: list[Any] | None ) -> None: assert in_held_column_order(given, held) is given @@ -532,6 +561,202 @@ def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> Non ) +# ── Nothing about a stored table is trusted across calls ─────────────────────── + + +def _abc(n: int, order: tuple[str, ...] = ("rid", "a", "b")) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([10 * n], pa.int64()), + "b": pa.array([100 * n], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +def _sqlite(path: Path) -> ConnectorArrowDatabase: + return ConnectorArrowDatabase(SQLiteConnector(str(path))) + + +def _recreate_with_text_a(path: Path) -> None: + with sqlite3.connect(path) as other: + other.execute('DROP TABLE "t"') + _sqlite(path).add_records( + PATH, + pa.table( + { + "rid": pa.array([bytes([1])], pa.large_binary()), + "a": pa.array(["10"], pa.large_string()), + "b": pa.array([100], pa.int64()), + } + ), + record_id_column="rid", + flush=True, + ) + + +CHANGES: dict[str, Any] = { + "rename": lambda c: c.execute('ALTER TABLE "t" RENAME COLUMN a TO A'), + "add": lambda c: c.execute('ALTER TABLE "t" ADD COLUMN extra INTEGER'), + "drop": lambda c: c.execute('ALTER TABLE "t" DROP COLUMN b'), +} + + +@pytest.mark.parametrize("change", [*CHANGES, "retype"]) +@pytest.mark.parametrize("order", [("rid", "a", "b"), ("b", "rid", "a")]) +def test_a_table_changed_between_queue_and_flush_is_refused_as_on_main( + tmp_path: Path, change: str, order: tuple[str, ...] +) -> None: + """Another connection renames, adds, drops or retypes a column after rows are + queued: the flush checks the table as it is then, by exact name and type, and + refuses as main does; the stored rows are untouched (codex review of PR 491, + round 2: a remembered table order let such rows through).""" + path = tmp_path / "store.db" + _sqlite(path).add_records(PATH, _abc(1), record_id_column="rid", flush=True) + db = _sqlite(path) + db.add_records(PATH, _abc(2, order), record_id_column="rid") + if change == "retype": + _recreate_with_text_a(path) + else: + with sqlite3.connect(path) as other: + CHANGES[change](other) + before = _sqlite(path).get_all_records(PATH, record_id_column="rid") + with pytest.raises(ValueError, match="Schema mismatch"): + db.flush() + after = _sqlite(path).get_all_records(PATH, record_id_column="rid") + assert before is not None and after is not None + assert after.equals(before) + assert after.num_rows == 1 + + +def test_a_table_dropped_and_written_again_by_the_same_handle_takes_the_new_order( + tmp_path: Path, +) -> None: + """The handle that wrote the dropped table writes the replacement in the order of + its new first write, as main does: nothing of the dropped table is remembered.""" + path = tmp_path / "store.db" + db = _sqlite(path) + db.add_records(PATH, _abc(1), record_id_column="rid", flush=True) + with sqlite3.connect(path) as other: + other.execute('DROP TABLE "t"') + db.add_records(PATH, _abc(2, ("b", "rid", "a")), record_id_column="rid", flush=True) + table = _sqlite(path).get_all_records(PATH, record_id_column="rid") + assert table is not None + assert table.column_names == ["b", "rid", "a"] + assert table.to_pylist() == [{"b": 200, "rid": bytes([2]), "a": 20}] + + +def test_a_queued_row_reads_in_the_order_it_reads_once_committed( + tmp_path: Path, +) -> None: + """On SpiralDB (its own column order), a point lookup of a queued row and of the + same row once flushed give the same column order.""" + with open_database("SpiralDB", tmp_path) as db: + rows = pa.table( + { + "rid": pa.array([bytes([1])], pa.large_binary()), + "z": pa.array([10]), + "a": pa.array([100]), + } + ) + db.add_records(PATH, rows, record_id_column="rid", flush=True) + second = rows.set_column(0, "rid", pa.array([bytes([2])], pa.large_binary())) + db.add_records(PATH, second, record_id_column="rid") + queued = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + db.flush() + committed = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + assert queued is not None and committed is not None + assert queued.column_names == committed.column_names == ["rid", "a", "z"] + assert queued.to_pylist() == committed.to_pylist() + + +@pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("race", [False, True], ids=["alone", "with another writer"]) +def test_a_refused_reordered_append_leaves_the_next_batch_on_mains_commit( + tmp_path: Path, schema_handling: str, skip_duplicates: bool, race: bool +) -> None: + """A reordered append the ITL-1334 check refuses (other field metadata) queues + nothing, and leaves nothing behind: the next aligned batch is committed as on + main, by append, also when another writer commits an unrelated id meanwhile.""" + from deltalake import DeltaTable + + db = DeltaTableDatabase(tmp_path) + kwargs: dict[str, Any] = { + "record_id_column": "rid", + "schema_handling": schema_handling, + "skip_duplicates": skip_duplicates, + } + db.add_records(PATH, _abc(1), flush=True, **kwargs) + bad = _abc(2, ("b", "rid", "a")) + bad = bad.set_column( + 2, bad.schema.field("a").with_metadata({"units": "wrong"}), bad["a"] + ) + with pytest.raises(InputValidationError): + db.add_records(PATH, bad, **kwargs) + if race: + snapshot = db._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + DeltaTableDatabase(tmp_path).add_records( + PATH, _abc(3), flush=True, **kwargs + ) + return taken + + with patch.object(db, "_snapshot_for_commit", side_effect=interleave): + db.add_records(PATH, _abc(2), flush=True, **kwargs) + else: + db.add_records(PATH, _abc(2), flush=True, **kwargs) + assert DeltaTable(tmp_path / "t").history()[0]["operation"] == "WRITE" + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + expected = [1, 2, 3] if race else [1, 2] + assert sorted(cast(list[int], table.column("a").to_pylist())) == [ + 10 * n for n in expected + ] + + +@pytest.mark.parametrize("backend", ["in-memory", "Delta"]) +@pytest.mark.parametrize("stored", [False, True], ids=["pending", "committed"]) +def test_two_logical_types_over_one_storage_type_are_not_reordered( + tmp_path: Path, backend: str, stored: bool +) -> None: + """Through the extension-aware wrapper, a column of one logical type held and a + permuted append of another logical type over the same storage type: not taken + for one, so refused as on main, never read back as the held logical type.""" + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + one = _make_converter_with_type("test.itl1367.held") + two = _make_converter_with_type("test.itl1367.other") + + def rows(n: int, pair: Any, order: list[str]) -> pa.Table: + text = pa.ExtensionArray.from_storage( + pair[1], pa.array([str(n)], pa.large_string()) + ) + return _abc(n).append_column(pa.field("text", pair[1]), text).select(order) + + inner = ( + InMemoryArrowDatabase() + if backend == "in-memory" + else DeltaTableDatabase(tmp_path / "delta") + ) + ExtensionAwareDatabase(inner, one[0]).add_records( + PATH, + rows(1, one, ["rid", "a", "b", "text"]), + record_id_column="rid", + flush=stored, + ) + with pytest.raises(Exception): # noqa: B017, PT011 # main's own refusal, by backend + db2 = ExtensionAwareDatabase(inner, two[0]) + db2.add_records( + PATH, rows(2, two, ["text", "b", "rid", "a"]), record_id_column="rid" + ) + db2.flush() + inner.get_all_records(PATH, record_id_column="rid") + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 19683b083..33d7a2eb4 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1058,13 +1058,15 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Rows whose columns are the held table's columns in another -order, each of the held type (a logical type compared by its storage type), are put in -the held order (the rows still pending, else the stored table) by every database before -they are queued and before the checks that compare them with the held columns (field -attributes, declared nulls, schema compatibility), whether the table was flushed in -between or not; the checks that look at the rows alone (a storable type, the record id) -come first. Rows still queued are matched again, by name, to the stored table when they -are read with it or written. A table keeps the column +order, each of the held type and logical type (a logical type held as its storage type +is compared by both), are put in the held order by every database, whether the table was +flushed in between or not. The in-memory and Delta databases do it when the rows are +queued (against the rows still pending, else the stored table), after the checks that +look at the rows alone and before the checks that compare them with the held columns. A +connector database (SQLite, PostgreSQL, SpiralDB) does it when the rows are queued only +against rows it has pending, and against the stored table when it writes or reads them: +the flush checks them against the table as it is then, by exact name and type, before +putting them in its order. A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also From 50dc02e1faf288717dd13af3fb23cdda114866ef Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:36:37 -0800 Subject: [PATCH 4/6] refactor(databases): append-by-name does the minimum: Delta aligns to its pending batch only, one field-equality rule, no lookup on point reads (ITL-1367) PR 491 review round 3 (Codex), simplified as asked: - Delta: an append is aligned only to this handle's pending batch; a batch is never reordered to the stored order and no MERGE marker is kept, so main's commit selection, schema handling and requeue run unchanged (delta-rs already matches a stored table by name) - one rule for 'may reorder': every field equal at every depth (type in the large variants, an extension type equal only to its own name and metadata at any depth, and no change appended_field_change reports); anything else is left as given for the database's own rule - a point lookup of a queued row answers from memory, as main does - design entry states the residual SQLite race (a DDL between the flush's check and its write) as pre-existing and equal to main Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1367.md | 21 +- docs/dev/design_issues/ITL-1367-CO1.md | 56 +++--- docs/reference/database-types.md | 16 +- .../databases/connector_arrow_database.py | 13 +- src/orcapod/databases/delta_lake_databases.py | 64 +----- src/orcapod/databases/utils.py | 105 +++++----- tests/test_databases/test_append_by_name.py | 188 +++++++++++++++--- tests/test_databases/type_matrix.py | 16 +- 8 files changed, 282 insertions(+), 197 deletions(-) diff --git a/changelog.d/ITL-1367.md b/changelog.d/ITL-1367.md index a189aab46..91d6d79ae 100644 --- a/changelog.d/ITL-1367.md +++ b/changelog.d/ITL-1367.md @@ -5,13 +5,14 @@ and SQLite while the earlier rows were still pending, and by the SpiralDB test fake, so a job node that produced the same columns in another order than an earlier write could not store them. Every database (in-memory, Delta, SQLite, PostgreSQL, SpiralDB) now puts such - rows in the order the table already has (the rows still pending, else the stored table; - a connector database checks queued rows against the stored table as it is when it - writes or reads them, then puts them in its order), after a flush and within one - pending batch alike; names are matched exactly (`a` and `A` are two columns), a logical - type must be the held one, and values are never matched by position. A reordered append - to a Delta table is committed as an insert-if-missing (MERGE), as before, so two - writers appending one record id still cannot both store it. A table keeps the column - order its database gave the first write (SpiralDB orders a table's columns its own way: - the key columns, then the other columns by name). An append that also adds, omits or retypes a column, and a struct - whose fields are in another order, keep each database's own rule. (ITL-1367) + rows in the order the table already has (the in-memory database: the rows still pending, + else the stored table; Delta: the rows still pending, since it already matched a stored + table by name; a connector database: the rows it has pending, and the stored table as it + is when it writes or reads them, after main's own check), after a flush and within one + pending batch alike. Only an append whose every field equals the held one is reordered + (the same type at every depth, the same logical type, the same field attributes); names + are matched exactly (`a` and `A` are two columns), and values are never matched by + position. A table keeps the column order its database gave the first write (SpiralDB + orders a table's columns its own way: the key columns, then the other columns by name). + An append that also adds, omits or retypes a column, and a struct whose fields are in + another order, keep each database's own rule. (ITL-1367) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index 1c6acdd90..9b49b20f8 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -21,30 +21,29 @@ columns in key-schema order, then the value columns sorted by name (code point: `a`), struct children sorted by name too. The fake refused what SpiralDB accepts and kept the written order. -**Fix:** one shared step, `databases/utils.in_held_column_order`, in every database -(in-memory, Delta, `ConnectorArrowDatabase` for SQLite, PostgreSQL and SpiralDB). Rows with -exactly the held columns in another order, each with the held column's type (compared in -the large variants, a logical type by its storage type) and the same logical type (an -extension type's name and metadata, or the `ARROW:extension` annotation of a field held -as its storage type), are put in the held order, by name. Names match exactly (`a` and -`A` are two columns). Anything else keeps the database's own rule: a column added or -missing, a type or logical type that differs, a name that repeats exactly. - -Where the step runs, and against what: - -- In-memory and Delta: when rows are queued, against the batch pending for the table, - else the stored table, after the checks on the rows alone and, in Delta, after - duplicates are dropped, before the checks that compare the rows with the held columns. - A Delta batch holding rows reordered this way is committed by MERGE (insert-if-missing), - the commit main chose for rows in another order; the marker is set only for rows - actually queued and leaves with them. -- The connector database: when rows are queued, only against the batch this handle has - pending for the table. Nothing about a stored table is trusted across calls (another - connection may rename, add, drop, retype or create a column again in between): a flush - looks the table up then, checks the queued rows against it by exact name and type as - main does, and only then puts them in the stored order; a read that combines stored and - queued rows, and a point lookup of a queued row, match them to the stored table read - then. +**Fix:** one shared step, `databases/utils.in_held_column_order`. When rows have exactly +the held columns in another order, and each field equals the held field of its name, the +rows are put in the held order, by name. Equal is one rule (`_same_field`): the same type +at every depth in the large variants, a logical (extension) type equal only to its own +name and metadata at any depth, and no change the ITL-1334 append check reports +(`appended_field_change`: field metadata and nested field attributes). Names match exactly +(`a` and `A` are two columns). Anything else is left exactly as given, so each database's +own rule applies as before. + +Where it runs, and against what: + +- In-memory: when rows are queued, against the batch pending for the table, else the + stored table (main refused both). +- Delta: when rows are queued, against the batch pending for the table only (main refused + a permutation of a pending batch; a stored table already takes an append by name, + through delta-rs). The pending batch is left exactly as main would hold it, so main's + commit selection, schema handling and requeue run unchanged. +- The connector database (SQLite, PostgreSQL, SpiralDB): when rows are queued, against the + batch it has pending only. Nothing about a stored table is trusted across calls: a flush + looks the table up then (main's own lookup), checks the queued rows by exact name and + type as main does, and only then puts them in the stored order; a read that combines + stored and queued rows matches them to the rows it reads. A point lookup of a queued + row answers from memory, as main does. A table keeps the order its database gave the first write (SpiralDB: its own order). The SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores @@ -52,9 +51,12 @@ the key columns, then the value columns by name. Tests: `tests/test_databases/test_append_by_name.py`; live: `TestColumnOrderLive` in `tests/test_databases/test_spiraldb_connector_integration.py`. -Found in review, pre-existing on main and not changed here: through -`ExtensionAwareDatabase`, rows of another logical type over the same storage type, in the -SAME column order, are accepted and read back as the held logical type. +Pre-existing on main and equal here, not changed: another connection that changes a SQLite +table between the flush's check and its write (a DDL in that window) is not seen; a rename +of `a` to `A` then stores the value under `A`, since SQLite resolves names without case, as +on main. Through `ExtensionAwareDatabase`, rows of another logical type over the same +storage type in the SAME column order are accepted and read back as the held logical type +(ITL-1371). Not covered: the order of a struct's fields (a struct with its fields in another order is another type here, and the fake keeps struct children as written): ITL-1368. A canonical diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 7d65a13db..d9b2efd3d 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -83,15 +83,13 @@ as nullable afterwards, as Delta stores it. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Rows whose columns are the held table's columns in another -order, each of the held type and logical type (a logical type held as its storage type -is compared by both), are put in the held order by every database, whether the table was -flushed in between or not. The in-memory and Delta databases do it when the rows are -queued (against the rows still pending, else the stored table), after the checks that -look at the rows alone and before the checks that compare them with the held columns. A -connector database (SQLite, PostgreSQL, SpiralDB) does it when the rows are queued only -against rows it has pending, and against the stored table when it writes or reads them: -the flush checks them against the table as it is then, by exact name and type, before -putting them in its order. A table keeps the column +order, each field equal to the held one (the same type at every depth, the same logical +type, the same field attributes), are put in the held order, whether the table was +flushed in between or not. The in-memory database matches them to the rows still pending, +else the stored table; Delta to the rows still pending (it matches a stored table by name +itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, +and to the stored table when it writes or reads them, checking them first against the +table as it is then, by exact name and type. A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6c16f6bf5..2f549ddb8 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -468,8 +468,10 @@ def _held_column_order( (ITL-1367): nothing about a stored table is trusted across calls, since another connection may rename, add, drop, retype or create again a column between two calls. The stored table is looked up fresh where queued and - stored rows meet, a flush and a read (``_stored_columns``), and the queued - rows are matched to it there, by name, after the flush's own check. + stored rows meet, a flush (``_stored_columns``, main's own lookup) and a read + that combines them (the rows it reads), and the queued rows are matched to it + there, by name, after the flush's own check. A point lookup of a queued row + answers from memory, as main does. """ pending = self._pending_batches.get(self._get_record_key(record_path)) if pending is not None: @@ -658,13 +660,6 @@ def get_record_by_id( pending = self._pending_batches[record_key] filtered = pending.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows > 0: - # In the stored table's order, as the row reads once committed: the - # rows were queued in the order of the batch (ITL-1367). - stored = self._stored_columns( - self._path_to_table_name(self._path_prefix + record_path) - ) - if stored is not None: - filtered = in_held_column_order(filtered, stored) return self._handle_record_id_column(filtered, record_id_column) # Check committed diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 8ba1d7b61..cbf6e2831 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -18,8 +18,8 @@ ) from orcapod.databases.utils import ( appended_field_change, - in_held_column_order, coerce_record_id, + in_held_column_order, metadata_bytes, ) from orcapod.errors import ( @@ -1089,7 +1089,6 @@ def __init__( _shared_snapshots: "dict[str, _CommittedSnapshot] | None" = None, _shared_pending_indexes: "dict[str, KeyIndex] | None" = None, _shared_absent_tables: "set[str] | None" = None, - _shared_reordered_keys: "set[str] | None" = None, ): self._root_uri, self._storage_options = parse_base_path( base_path, storage_options @@ -1149,18 +1148,11 @@ def __init__( self._absent_tables: set[str] = ( _shared_absent_tables if _shared_absent_tables is not None else set() ) - # Record keys whose pending rows include rows reordered by name to the held - # order (ITL-1367): committed by MERGE, as main commits rows given in another - # order than the stored table's. Family-wide like the pending batches. - self._reordered_keys: set[str] = ( - _shared_reordered_keys if _shared_reordered_keys is not None else set() - ) def _clear_pending(self): """Clear all pending state.""" self._pending_batches = {} self._pending_record_ids = defaultdict(set) - self._reordered_keys = set() # Note: next_row_index continues incrementing def _get_record_key(self, record_path: tuple[str, ...]) -> str: @@ -1782,26 +1774,6 @@ def _refuse_changed_attributes( "nothing was written." ) - def _held_column_order( - self, record_path: tuple[str, ...] - ) -> "list[pa.Field[Any]] | None": - """The columns the table holds, in the held order (ITL-1367). - - The pending batch's order when rows are pending, else the stored table's - (its log; no data is read), else ``None``. A stored table that cannot be - loaded gives ``None``: the append is then left to the flush to report. - """ - pending = self._pending_batches.get(self._get_record_key(record_path)) - if pending is not None: - return list(pending.schema) - try: - delta_table = self._get_delta_table(record_path) - except OrcapodDatabaseReadError: - return None - if delta_table is None: - return None - return list(_held_columns(delta_table).values()) - def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1921,16 +1893,13 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table - # Columns match by name: rows with the held columns in another order are - # put in the held order (ITL-1367). Looked up only for rows that will be - # queued. A table whose rows were reordered is committed by MERGE, as main - # commits rows that are not in the stored layout: insert-if-missing against - # the version the commit loads, never a blind append. - given_order = filtered_table.column_names - filtered_table = in_held_column_order( - filtered_table, self._held_column_order(record_path) - ) - reordered = filtered_table.column_names != given_order + # Columns match by name within a pending batch: rows with the pending + # batch's columns in another order, each field equal, are put in its order + # (ITL-1367). Only the pending batch: a stored table already takes an append + # by name (delta-rs), and the batch is left exactly as main holds it. + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + filtered_table = in_held_column_order(filtered_table, list(pending.schema)) # 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 @@ -1954,12 +1923,8 @@ 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 7: Add to pending batch (no overwrite logic needed). The MERGE marker - # is set only now, for rows actually queued: rows refused above leave no - # trace, and the marker leaves with the rows (flush, refusal at commit). + # Step 7: Add to pending batch (no overwrite logic needed) self._add_to_pending_batch(record_path, schema_compatible_table) - if reordered: - self._reordered_keys.add(self._get_record_key(record_path)) # Step 8: Flush if asked to; otherwise commit this table alone once its # pending batch reaches batch_size. Only the full table: committing every @@ -2621,8 +2586,6 @@ def _flush_by_key(self, record_key: str) -> None: # Get all pending records pending_batch = self._pending_batches.pop(record_key) pending_ids = self._pending_record_ids.pop(record_key, set()) - reordered = record_key in self._reordered_keys - self._reordered_keys.discard(record_key) # Derive the absolute table URI directly from the key (already includes prefix). abs_path_components = tuple(record_key.split("/")) @@ -2712,10 +2675,8 @@ def _flush_by_key(self, record_key: str) -> None: assert base.ids is not None incoming_ids = self._non_null_ids(combined_table) inserted_ids = incoming_ids - base.ids - if ( - not reordered - and len(inserted_ids) == len(incoming_ids) - and self._stores_as_is(delta_table, combined_table) + if len(inserted_ids) == len(incoming_ids) and self._stores_as_is( + delta_table, combined_table ): # Every pending id is new in the version just loaded and the rows # have the stored schema: append (ITL-919). A MERGE reads the whole @@ -2767,8 +2728,6 @@ def _flush_by_key(self, record_key: str) -> None: # Put the tables back in the pending queue self._pending_batches[record_key] = pending_batch self._pending_record_ids[record_key] = pending_ids - if reordered: - self._reordered_keys.add(record_key) raise # The rows are committed: nothing below may put them back in the queue. @@ -3191,7 +3150,6 @@ def at(self, *path_components: str) -> "DeltaTableDatabase": _shared_snapshots=root_instance._snapshots, _shared_pending_indexes=root_instance._pending_indexes, _shared_absent_tables=root_instance._absent_tables, - _shared_reordered_keys=root_instance._reordered_keys, ) def list_sources(self) -> list[tuple[str, ...]]: diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 285d94d78..16db42020 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -209,27 +209,22 @@ def in_held_column_order( """``records`` with its columns in the order the database holds them (ITL-1367). An append matches columns by name, never by position: when ``records`` has - exactly the held columns in another order, each of the held column's type and - logical type, its columns are put in the held order, so every database stores - and buffers them as the table already has them, and the table keeps the order of - its first write. The fields are kept as given (metadata, nullability): the append - checks that follow compare them by name. - - A type is compared as the database compares it: a logical (extension) type as - its storage type, in the large variants; and the logical identity must be the - same too (``_logical_identity``: an extension type's name and metadata, or the - ``ARROW:extension`` annotation of a field stored as its storage type), so two - logical types over one storage type are never taken for one. Anything else is - returned as given, for the database's own append rule: no held table, a column - added or missing, a type or logical type that differs (a struct whose children - are in another order included: its type differs; ITL-1368), and a name that - repeats exactly. Names are matched exactly, as Arrow matches them: ``a`` and - ``A`` are two columns. + exactly the held columns in another order, and each of its fields equals the held + field of its name, its columns are put in the held order. Equal is one rule + (``_same_field``): the same type at every depth (in the large variants, a logical + type with its own name and metadata, at any depth) and no change the append + check reports (``appended_field_change``: field metadata and nested field + attributes at every depth). Names are matched exactly, as Arrow matches them: + ``a`` and ``A`` are two columns. + + Anything else is returned exactly as given, so the database's own rule applies + as before: no held table, a column added or missing, a field that differs in any + way (a struct whose children are in another order included: ITL-1368), a name that + repeats. Args: records: The rows to append, the record id column already named as held. - held: The held columns, in the held order (the pending batch, else the - stored table), or ``None`` when the database holds no such table. + held: The held columns, in the held order, or ``None`` when nothing is held. Returns: ``records``, reordered or as given. @@ -240,50 +235,54 @@ def in_held_column_order( held_names = [field.name for field in held] if names == held_names: return records - # Arrow matches names exactly: ``a`` and ``A`` are two columns. Only a name that - # repeats exactly cannot be matched. if len(set(names)) != len(names) or len(set(held_names)) != len(held_names): return records if set(names) != set(held_names): return records held_fields = {field.name: field for field in held} - for field in records.schema: - given = held_fields[field.name] - if _stored_form(field.type) != _stored_form(given.type): - return records - if _logical_identity(field) != _logical_identity(given): - return records + if not all(_same_field(field, held_fields[field.name]) for field in records.schema): + return records return records.select(held_names) -_EXTENSION_NAME = b"ARROW:extension:name" -_EXTENSION_METADATA = b"ARROW:extension:metadata" +def _same_field(given: "pa.Field[Any]", held: "pa.Field[Any]") -> bool: + """Whether rows of ``given`` would be held as ``held`` holds them: the same type at + every depth, in the large variants (a logical type is equal only to itself: its + name, metadata and storage), and no change ``appended_field_change`` reports.""" + large = arrow_utils.normalize_to_large_types + if not _same_type( + large(given.type, keep_null=True), large(held.type, keep_null=True) + ): + return False + return appended_field_change(held, given) is None -def _logical_identity(field: "pa.Field[Any]") -> tuple[bytes, bytes] | None: - """The logical type a column holds: an extension type's name and metadata, or - the ``ARROW:extension`` annotation of a field held as its storage type (a stored - Delta column, a column the extension-aware wrapper encoded); ``None`` for a plain - column.""" - if isinstance(field.type, pa.ExtensionType): +def _same_type(given: Any, held: Any) -> bool: + """Arrow type equality at every depth, with an extension type equal only to one + of its own name and serialized metadata: pyarrow compares a Python extension type + by its class and storage, not by its metadata (two units over ``int64`` are + equal to it).""" + t = pa.types + if isinstance(given, pa.ExtensionType) or isinstance(held, pa.ExtensionType): return ( - field.type.extension_name.encode(), - field.type.__arrow_ext_serialize__(), + isinstance(given, pa.ExtensionType) + and isinstance(held, pa.ExtensionType) + and given.extension_name == held.extension_name + and given.__arrow_ext_serialize__() == held.__arrow_ext_serialize__() + and _same_type(given.storage_type, held.storage_type) ) - metadata = metadata_bytes(field.metadata) - name = metadata.get(_EXTENSION_NAME) - if name is None: - return None - return name, metadata.get(_EXTENSION_METADATA, b"") - - -def _stored_form(arrow_type: "pa.DataType") -> "pa.DataType": - """``arrow_type`` as a database compares it: a logical (extension) type as its - storage type, a dictionary as its value type, in the large variants. A database - that holds such a column reports that type, so the comparison sees what the - database sees.""" - if isinstance(arrow_type, pa.ExtensionType): - arrow_type = arrow_type.storage_type - if pa.types.is_dictionary(arrow_type): - arrow_type = cast(Any, arrow_type).value_type - return arrow_utils.normalize_to_large_types(arrow_type, keep_null=True) + if given != held: + return False + if t.is_struct(given): + return all( + _same_type(given.field(i).type, held.field(i).type) + for i in range(given.num_fields) + ) + if t.is_map(given): + return _same_type(given.key_type, held.key_type) and _same_type( + given.item_type, held.item_type + ) + lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) + if any(kind(given) for kind in lists): + return _same_type(cast(Any, given).value_type, cast(Any, held).value_type) + return True diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 3075f1177..d881a5010 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -310,30 +310,78 @@ def _annotated(name: str, ext_type: Any) -> Any: ) -def test_the_step_compares_a_logical_type_by_its_storage_and_identity() -> None: - """A database holding a logical column reports its storage type, annotated with - the logical type: the same logical type is matched; another one over the same - storage type, or a plain column, is not (ITL-1367).""" +class _Unit(pa.ExtensionType): + """An extension type whose metadata is a unit: two units over ``int64`` are one + type to pyarrow's own equality, two types here.""" + + def __init__(self, unit: str) -> None: + self.unit = unit + super().__init__(pa.int64(), "test.itl1367.unit") + + def __arrow_ext_serialize__(self) -> bytes: + return self.unit.encode() + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized.decode()) + + +def _unit_column(unit: str, nest: str) -> Any: + """``a``: an ``int64`` in ``unit``, at the top, in a struct or in a list.""" + array = pa.ExtensionArray.from_storage(_Unit(unit), pa.array([1], pa.int64())) + if nest == "struct": + return pa.StructArray.from_arrays([array], names=["m"]) + if nest == "list": + return pa.LargeListArray.from_arrays(pa.array([0, 1], pa.int64()), array) + return array + + +@pytest.mark.parametrize("nest", ["top", "struct", "list"]) +def test_the_step_matches_a_logical_type_only_to_itself_at_every_depth(nest: str): + """One rule for "may reorder": every field equal at every depth. A logical type + is equal only to its own name and metadata, also inside a struct or a list; an + annotation in field metadata only to the same annotation. Anything else is left + as given, so the database's own refusal applies (codex review of PR 491, round + 3).""" + held_table = pa.table({"b": [0], "a": _unit_column("m", nest)}) + held = list(held_table.schema) + same = pa.table({"a": _unit_column("m", nest), "b": [1]}) + assert in_held_column_order(same, held).column_names == ["b", "a"] + other = pa.table({"a": _unit_column("s", nest), "b": [1]}) + assert in_held_column_order(other, held) is other + + +def test_the_step_matches_a_field_annotation_only_to_itself() -> None: from tests.test_databases.test_extension_aware_database import ( _make_converter_with_type, ) _, one = _make_converter_with_type("test.itl1367.one") _, two = _make_converter_with_type("test.itl1367.two") - text = pa.ExtensionArray.from_storage(one, pa.array(["x"], pa.large_string())) - given = pa.table({"text": text, "a": [1]}) a = pa.field("a", pa.int64()) - out = in_held_column_order(given, [a, _annotated("text", one)]) - assert out.column_names == ["a", "text"] + + def annotated(ext_type: Any) -> pa.Table: + return pa.Table.from_arrays( + [pa.array(["x"]), pa.array([1])], + schema=pa.schema([_annotated("text", ext_type), a]), + ) + + given = annotated(one) + held_one = [a, _annotated("text", one)] + assert in_held_column_order(given, held_one).column_names == ["a", "text"] assert in_held_column_order(given, [a, _annotated("text", two)]) is given assert in_held_column_order(given, [a, pa.field("text", pa.string())]) is given - annotated = pa.Table.from_arrays( - [pa.array(["x"]), pa.array([1])], - schema=pa.schema([_annotated("text", two), a]), + live = pa.table( + { + "text": pa.ExtensionArray.from_storage( + one, pa.array(["x"], pa.large_string()) + ), + "a": [1], + } ) - assert in_held_column_order(annotated, [a, _annotated("text", one)]) is annotated - held = [a, _annotated("text", two)] - assert in_held_column_order(annotated, held).column_names == ["a", "text"] + assert ( + in_held_column_order(live, held_one) is live + ) # a live type is not its storage def test_the_step_compares_types_in_their_large_variants() -> None: @@ -413,8 +461,9 @@ def _table_with_id(rid: bytes, order: list[str]) -> pa.Table: def test_a_logical_column_is_matched_by_name_through_the_extension_database( tmp_path: Path, stored: bool ) -> None: - """Delta stores a logical column as its storage type; an append of it in another - order is put in the held order whether the held rows are committed or pending.""" + """A logical column appended in another order through the extension-aware + wrapper, the held rows pending or committed: every value is read back by name + (Delta matches a stored table by name itself; a pending batch is aligned).""" from tests.test_databases.test_extension_aware_database import ( _make_converter_with_type, ) @@ -439,8 +488,9 @@ def rows(n: int, order: list[str]) -> pa.Table: db.flush() committed = db.get_record_by_id(PATH, bytes([2]), record_id_column=ID) assert committed is not None - assert pending.column_names == committed.column_names - assert committed.to_pylist() == [{ID: bytes([2]), "text": "2", "n": 2}] + row = {ID: bytes([2]), "text": "2", "n": 2} + assert pending.select([ID, "text", "n"]).to_pylist() == [row] + assert committed.select([ID, "text", "n"]).to_pylist() == [row] # ── Delta: the commit a reordered append takes ───────────────────────────────── @@ -645,11 +695,10 @@ def test_a_table_dropped_and_written_again_by_the_same_handle_takes_the_new_orde assert table.to_pylist() == [{"b": 200, "rid": bytes([2]), "a": 20}] -def test_a_queued_row_reads_in_the_order_it_reads_once_committed( - tmp_path: Path, -) -> None: - """On SpiralDB (its own column order), a point lookup of a queued row and of the - same row once flushed give the same column order.""" +def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: + """A point lookup of a queued row answers from memory, in the order the row is + queued, with no lookup of the stored table (as main): the stored table is not + even listed. Presentation order is a reader's business (ITL-1370).""" with open_database("SpiralDB", tmp_path) as db: rows = pa.table( { @@ -661,12 +710,16 @@ def test_a_queued_row_reads_in_the_order_it_reads_once_committed( db.add_records(PATH, rows, record_id_column="rid", flush=True) second = rows.set_column(0, "rid", pa.array([bytes([2])], pa.large_binary())) db.add_records(PATH, second, record_id_column="rid") - queued = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + with patch.object( + db._connector, "get_table_names", side_effect=AssertionError("listed") + ): + queued = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + assert queued is not None + assert queued.column_names == ["rid", "z", "a"] db.flush() committed = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") - assert queued is not None and committed is not None - assert queued.column_names == committed.column_names == ["rid", "a", "z"] - assert queued.to_pylist() == committed.to_pylist() + assert committed is not None + assert committed.select(["rid", "z", "a"]).to_pylist() == queued.to_pylist() @pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) @@ -757,6 +810,87 @@ def rows(n: int, pair: Any, order: list[str]) -> pa.Table: inner.get_all_records(PATH, record_id_column="rid") +@pytest.mark.parametrize( + ("schema_handling", "a"), + [ + ("merge", pa.nulls(1)), + ("coerce", pa.nulls(1)), + ("coerce", pa.array([30], pa.int32())), + ], + ids=["merge null", "coerce null", "coerce int32"], +) +def test_a_delta_batch_queued_in_another_order_keeps_its_order( + tmp_path: Path, schema_handling: str, a: Any +) -> None: + """Delta aligns an append only to its own pending batch, never to the stored + table: a batch queued in another order than the stored table stays in its order, + so a later append in that order, relying on ``schema_handling`` to merge or coerce + a column, behaves as on main (codex review of PR 491, round 3).""" + db = DeltaTableDatabase(tmp_path) + kwargs: dict[str, Any] = { + "record_id_column": "rid", + "schema_handling": schema_handling, + } + db.add_records(PATH, _abc(1), flush=True, **kwargs) + db.add_records(PATH, _abc(2, ("b", "rid", "a")), **kwargs) + third = _abc(3, ("b", "rid", "a")).set_column(2, "a", a) + db.add_records(PATH, third, **kwargs) + db.flush() + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + got = sorted(table.select(["rid", "a", "b"]).to_pylist(), key=str) + assert got == [ + {"rid": bytes([1]), "a": 10, "b": 100}, + {"rid": bytes([2]), "a": 20, "b": 200}, + {"rid": bytes([3]), "a": a.to_pylist()[0], "b": 300}, + ] + + +def test_a_delta_table_created_again_in_another_order_takes_mains_commit( + tmp_path: Path, +) -> None: + """A Delta table created again in another order while this handle holds the old + one: an aligned batch is committed by append as on main, also with another writer + committing an unrelated id meanwhile (no state of this PR forces a MERGE).""" + import shutil + + from deltalake import DeltaTable, write_deltalake + + order = ("b", "__record_id", "a") + + def rows(n: int) -> pa.Table: + return _abc(n).rename_columns(["__record_id", "a", "b"]).select(order) + + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + rows(1).select(["__record_id", "a", "b"]), + flush=True, + record_id_column="__record_id", + ) + shutil.rmtree(tmp_path / "t") + write_deltalake(tmp_path / "t", rows(1), mode="overwrite") + db.add_records(PATH, rows(2), record_id_column="__record_id") + snapshot = db._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + DeltaTableDatabase(tmp_path).add_records( + PATH, rows(3), flush=True, record_id_column="__record_id" + ) + return taken + + with patch.object(db, "_snapshot_for_commit", side_effect=interleave): + db.flush() + history = [entry["operation"] for entry in DeltaTable(tmp_path / "t").history()] + assert "MERGE" not in history + table = DeltaTableDatabase(tmp_path).get_all_records( + PATH, record_id_column="__record_id" + ) + assert table is not None + assert sorted(cast(list[int], table.column("a").to_pylist())) == [10, 20, 30] + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 33d7a2eb4..a99d785aa 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1058,15 +1058,13 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Rows whose columns are the held table's columns in another -order, each of the held type and logical type (a logical type held as its storage type -is compared by both), are put in the held order by every database, whether the table was -flushed in between or not. The in-memory and Delta databases do it when the rows are -queued (against the rows still pending, else the stored table), after the checks that -look at the rows alone and before the checks that compare them with the held columns. A -connector database (SQLite, PostgreSQL, SpiralDB) does it when the rows are queued only -against rows it has pending, and against the stored table when it writes or reads them: -the flush checks them against the table as it is then, by exact name and type, before -putting them in its order. A table keeps the column +order, each field equal to the held one (the same type at every depth, the same logical +type, the same field attributes), are put in the held order, whether the table was +flushed in between or not. The in-memory database matches them to the rows still pending, +else the stored table; Delta to the rows still pending (it matches a stored table by name +itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, +and to the stored table when it writes or reads them, checking them first against the +table as it is then, by exact name and type. A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also From c17236c83320ffa8a658388446a23f79866130ab Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:50:16 -0800 Subject: [PATCH 5/6] fix(databases): a column is reordered only if every type in its tree is one the comparison handles (ITL-1367) PR 491 review round 4 (Codex): eligibility is positive. A field may be put in the held order only when its whole type tree consists of the handled leaf types, structs, maps, the three list kinds and extension types over those; a list view, a union, a dictionary, a run-end-encoded type, an interval or any other kind anywhere in the tree leaves the table as given for the database's own rule. Docs: the proposal's sentence on case-only names corrected (PostgreSQL not measured); the append test module's docstring and comments describe where the step runs now. Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1367-stored-column-order.md | 8 +- src/orcapod/databases/utils.py | 38 +++++-- tests/test_databases/test_append_by_name.py | 106 ++++++++++++++++-- 3 files changed, 130 insertions(+), 22 deletions(-) diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md index 8bd4ad635..763b978df 100644 --- a/docs/dev/specs/itl-1367-stored-column-order.md +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -88,9 +88,11 @@ column sorted by name, by code point.** No other rule. only key column in every Orcapod table), so all five databases then store and read the same order. - **Code point:** Python's `sorted` on `str`, the order SpiralDB was measured to use - (uppercase before `_` before lowercase). Names that differ in case only are refused by - SQLite and PostgreSQL already; the in-memory and Delta databases keep them apart, and - code point order is total, so the order is still decided. + (uppercase before `_` before lowercase). Names that differ in case only are one + column to SQLite, which resolves names without case; the PostgreSQL connector quotes + every name, so it should keep them apart (not measured); the in-memory and Delta + databases keep them apart. Code point order is total, so the order is decided either + way. ## Which stored tables change diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 16db42020..117ae477a 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -257,11 +257,36 @@ def _same_field(given: "pa.Field[Any]", held: "pa.Field[Any]") -> bool: return appended_field_change(held, given) is None +_LEAF_KINDS = ( + "is_null", + "is_boolean", + "is_integer", + "is_floating", + "is_decimal", + "is_string", + "is_large_string", + "is_binary", + "is_large_binary", + "is_fixed_size_binary", + "is_date", + "is_time", + "is_timestamp", + "is_duration", +) +"""The leaf types the comparison handles. Eligibility is positive: a type of any +other kind anywhere in a column's tree (a list view, a union, a dictionary, a +run-end-encoded type, an interval, a view type, anything pyarrow adds later) makes +the column not eligible, and the table is left as given for the database's own +rule (codex review of PR 491, round 4).""" + + def _same_type(given: Any, held: Any) -> bool: - """Arrow type equality at every depth, with an extension type equal only to one - of its own name and serialized metadata: pyarrow compares a Python extension type - by its class and storage, not by its metadata (two units over ``int64`` are - equal to it).""" + """Whether two Arrow types are equal at every depth, for a type tree the + comparison handles entirely: the leaf kinds of ``_LEAF_KINDS``, a struct, a map, + a list, large list or fixed-size list, and an extension type over those, equal + only to one of its own name and serialized metadata (pyarrow compares a Python + extension type by its class and storage, not by its metadata). Any other type + anywhere in either tree gives ``False``.""" t = pa.types if isinstance(given, pa.ExtensionType) or isinstance(held, pa.ExtensionType): return ( @@ -282,7 +307,6 @@ def _same_type(given: Any, held: Any) -> bool: return _same_type(given.key_type, held.key_type) and _same_type( given.item_type, held.item_type ) - lists = (t.is_list, t.is_large_list, t.is_fixed_size_list) - if any(kind(given) for kind in lists): + if t.is_list(given) or t.is_large_list(given) or t.is_fixed_size_list(given): return _same_type(cast(Any, given).value_type, cast(Any, held).value_type) - return True + return any(getattr(t, kind)(given) for kind in _LEAF_KINDS) diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index d881a5010..3a5aa4a51 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -1,11 +1,15 @@ """An append matches columns by name, whatever their order (ITL-1367). -Every database puts rows whose columns are the held table's columns in another order -(each with the held type) into the held order before anything is checked or buffered: -the pending batch's order, else the stored table's. The table keeps the order of its -first write. ``a`` and ``c`` are both ``int64``, so a positional match would swap their -values: every test reads the values back by name. Appends that add, lack or retype a -column, and a name that repeats exactly, keep the database's own rule. +Every database puts rows whose columns are the held table's columns in another order, +each field equal to the held one, into the held order: the in-memory database when the +rows are queued (the pending batch, else the stored table); Delta when they are queued, +against its pending batch only (it matches a stored table by name itself); a connector +database when they are queued, against its pending batch only, and at a flush or a +combined read, against the stored table read then. The table keeps the order its +database gave the first write. ``a`` and ``c`` are both ``int64``, so a positional match +would swap their values: every test reads the values back by name. Appends that add, +lack or retype a column, a field that differs in any way, and a name that repeats +exactly, keep the database's own rule. """ from __future__ import annotations @@ -557,9 +561,9 @@ def interleave(*args: Any) -> Any: def test_an_all_duplicate_append_looks_up_no_order(tmp_path: Path) -> None: - """With ``skip_duplicates`` and nothing left to write, the stored order is not - looked up: a stored table whose recorded type cannot be read does not fail an - append that writes nothing.""" + """With ``skip_duplicates`` and nothing left to write, a stored table whose + recorded type cannot be read does not fail an append that writes nothing (Delta + looks no stored order up at all).""" from deltalake import write_deltalake rows = _rows([ID, "a", "c", "b"], [1]).rename_columns( @@ -583,9 +587,8 @@ def test_an_all_duplicate_append_looks_up_no_order(tmp_path: Path) -> None: def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> None: - """The connector database looks a table up once per flushed append, as main - does: an append on a fresh handle shares its lookup with the flush, and an - append to a table the handle has seen looks nothing up before the flush.""" + """The connector database looks a table up once per flushed append, at the + flush, as main does: an append looks nothing up when it is queued.""" path = str(tmp_path / "store.db") ConnectorArrowDatabase(SQLiteConnector(path)).add_records( PATH, _rows([ID, "a", "c", "b"], [1]), record_id_column=ID, flush=True @@ -891,6 +894,85 @@ def interleave(*args: Any) -> Any: assert sorted(cast(list[int], table.column("a").to_pylist())) == [10, 20, 30] +def _extension_values(type_: Any) -> Any: + return pa.ExtensionArray.from_storage(type_, pa.array([1], pa.int64())) + + +def _container_columns() -> dict[str, tuple[Any, Any]]: + """A column of each container kind the comparison does not handle, held and + appended: the appended one holds an extension type with other metadata (or, for + a plain list view, an item field with other metadata).""" + held_ext, other_ext = _Unit("m"), _Unit("s") + offsets = pa.array([0], pa.int32()) + sizes = pa.array([1], pa.int32()) + + def list_view(value: Any, large: bool) -> Any: + kind: Any = pa.LargeListViewArray if large else pa.ListViewArray + return kind.from_arrays( + pa.array([0], pa.int64() if large else pa.int32()), + pa.array([1], pa.int64() if large else pa.int32()), + value, + ) + + def run_end() -> Any: + encoded: Any = pa.RunEndEncodedArray + return encoded.from_arrays(pa.array([1], pa.int32()), pa.array([1])) + + def interval() -> Any: + return pa.array([(1, 0, 0)], pa.month_day_nano_interval()) + + def union(value: Any, mode: str) -> Any: + types = pa.array([0], pa.int8()) + if mode == "dense": + return pa.UnionArray.from_dense(types, pa.array([0], pa.int32()), [value]) + return pa.UnionArray.from_sparse(types, [value]) + + list_view_array: Any = pa.ListViewArray + plain_item = list_view_array.from_arrays(offsets, sizes, pa.array([1])) + marked_item = plain_item.cast( + pa.list_view(pa.field("item", pa.int64(), metadata={"unit": "s"})) + ) + return { + "list_view": ( + list_view(_extension_values(held_ext), False), + list_view(_extension_values(other_ext), False), + ), + "large_list_view": ( + list_view(_extension_values(held_ext), True), + list_view(_extension_values(other_ext), True), + ), + "dense union": ( + union(_extension_values(held_ext), "dense"), + union(_extension_values(other_ext), "dense"), + ), + "sparse union": ( + union(_extension_values(held_ext), "sparse"), + union(_extension_values(other_ext), "sparse"), + ), + "list view item metadata": (plain_item, marked_item), + "dictionary": ( + pa.array(["x"]).dictionary_encode(), + pa.array(["x"]).dictionary_encode(), + ), + "run-end encoded": (run_end(), run_end()), + "interval": (interval(), interval()), + } + + +@pytest.mark.parametrize("kind", list(_container_columns())) +def test_a_column_of_a_type_the_comparison_does_not_handle_is_never_reordered( + kind: str, +) -> None: + """Eligibility is positive (codex review of PR 491, round 4): a column whose type + tree holds anything but the handled leaf types, structs, maps, the three list + kinds and extension types over those is not eligible, even when equal, so the + table is left as given and the database's own rule applies.""" + held_values, given_values = _container_columns()[kind] + held = list(pa.table({"b": [0], "a": held_values}).schema) + given = pa.table({"a": given_values, "b": [1]}) + assert in_held_column_order(given, held) is given + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── From 5ac28f2d3ad8428e579521e8c55c5c55cefa9e9a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 15:26:34 -0800 Subject: [PATCH 6/6] fix(databases): a read combining stored and queued rows reconciles nullability; eligibility decided on the types as given (ITL-1367) PR 491 CodeRabbit round and the PostgreSQL CI failure: - a read that combines stored and queued rows takes a column nullable when either side declares it nullable (PostgreSQL reads its primary key back NOT NULL), only when names, types and attributes match; arrays re-wrapped, never cast. Pre-existing on main for an aligned read before a flush; tested with a SQLite connector double that reads the key NOT NULL - eligibility is checked on the type trees as given, before normalization turns a view type into its large variant - tests assert specific outcomes: the given fields survive a real reorder; each stored function-record row holds its own signature and values; the logical-type refusal is pinned per backend and stage as on main - docs: a connector flush leaves a column with field metadata in its queued order; the Delta fast-path append race is pre-existing (ITL-1377) Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1367-CO1.md | 13 ++- docs/reference/database-types.md | 4 +- .../databases/connector_arrow_database.py | 32 +++++++- src/orcapod/databases/utils.py | 26 ++++++ .../data_function/test_function_record.py | 14 ++++ tests/test_databases/test_append_by_name.py | 82 ++++++++++++++++--- tests/test_databases/type_matrix.py | 4 +- 7 files changed, 159 insertions(+), 16 deletions(-) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index 9b49b20f8..40c7d996b 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -41,9 +41,16 @@ Where it runs, and against what: - The connector database (SQLite, PostgreSQL, SpiralDB): when rows are queued, against the batch it has pending only. Nothing about a stored table is trusted across calls: a flush looks the table up then (main's own lookup), checks the queued rows by exact name and - type as main does, and only then puts them in the stored order; a read that combines - stored and queued rows matches them to the rows it reads. A point lookup of a queued - row answers from memory, as main does. + type as main does, and only then puts them in the stored order (the flush compares the + connector's column info, which carries no field metadata: a column with field metadata + stays in its queued order, which SpiralDB, the connector that keeps field metadata, + matches by name itself); a read that combines stored and queued rows matches them to + the rows it reads, and takes a column nullable when either side declares it nullable + (PostgreSQL reads its key back NOT NULL; arrays re-wrapped, never cast). A point + lookup of a queued row answers from memory, as main does. + +Pre-existing on main and out of scope: two Delta writers appending one new record id can +both store it through the fast-path append (ITL-1377). A table keeps the order its database gave the first write (SpiralDB: its own order). The SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index d9b2efd3d..9819e3cfb 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -89,7 +89,9 @@ flushed in between or not. The in-memory database matches them to the rows still else the stored table; Delta to the rows still pending (it matches a stored table by name itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, and to the stored table when it writes or reads them, checking them first against the -table as it is then, by exact name and type. A table keeps the column +table as it is then, by exact name and type (a column with field metadata stays in its +queued order at a flush; SpiralDB, which keeps field metadata, matches a write by name +itself). A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 2f549ddb8..761486310 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -57,6 +57,36 @@ def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: ] +def _alike(parts: list[pa.Table]) -> list[pa.Table]: + """Stored and queued rows under one schema when they differ only in a column's + nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary + key) that the queued rows declare nullable. Each such field is nullable when + either side's is, and the arrays are re-wrapped under it, never cast. Any other + difference is left for ``pa.concat_tables`` to refuse, as before.""" + first = parts[0].schema + if any(part.schema.names != first.names for part in parts): + return parts + fields = [] + for i, field in enumerate(first): + others = [part.schema.field(i) for part in parts[1:]] + loose = field.with_nullable(True) + if not all( + other.with_nullable(True).equals(loose, check_metadata=True) + for other in others + ): + return parts + fields.append( + field.with_nullable(field.nullable or any(o.nullable for o in others)) + ) + schema = pa.schema(fields, metadata=cast(Any, first.metadata)) + return [ + part + if part.schema.equals(schema, check_metadata=True) + else pa.Table.from_arrays(part.columns, schema=schema) + for part in parts + ] + + class ConnectorArrowDatabase: """Generic ``ArrowDatabaseProtocol`` implementation backed by a ``DBConnectorProtocol``. @@ -697,7 +727,7 @@ def get_all_records( if not parts: return None - table = parts[0] if len(parts) == 1 else pa.concat_tables(parts) + table = parts[0] if len(parts) == 1 else pa.concat_tables(_alike(parts)) return self._handle_record_id_column(table, record_id_column) def get_records_by_ids( diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 117ae477a..17018eb43 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -249,6 +249,10 @@ def _same_field(given: "pa.Field[Any]", held: "pa.Field[Any]") -> bool: """Whether rows of ``given`` would be held as ``held`` holds them: the same type at every depth, in the large variants (a logical type is equal only to itself: its name, metadata and storage), and no change ``appended_field_change`` reports.""" + # Eligibility is decided on the types as given, before normalization turns a + # view type into its large variant. + if not (_handled(given.type) and _handled(held.type)): + return False large = arrow_utils.normalize_to_large_types if not _same_type( large(given.type, keep_null=True), large(held.type, keep_null=True) @@ -257,6 +261,28 @@ def _same_field(given: "pa.Field[Any]", held: "pa.Field[Any]") -> bool: return appended_field_change(held, given) is None +def _handled(arrow_type: Any) -> bool: + """Whether every type in ``arrow_type``'s tree is one the comparison handles + (``_same_type``): a leaf kind of ``_LEAF_KINDS``, a struct, a map, a list, large + list or fixed-size list, or an extension type over those.""" + t = pa.types + if isinstance(arrow_type, pa.ExtensionType): + return _handled(arrow_type.storage_type) + if t.is_struct(arrow_type): + return all( + _handled(arrow_type.field(i).type) for i in range(arrow_type.num_fields) + ) + if t.is_map(arrow_type): + return _handled(arrow_type.key_type) and _handled(arrow_type.item_type) + if ( + t.is_list(arrow_type) + or t.is_large_list(arrow_type) + or t.is_fixed_size_list(arrow_type) + ): + return _handled(cast(Any, arrow_type).value_type) + return any(getattr(t, kind)(arrow_type) for kind in _LEAF_KINDS) + + _LEAF_KINDS = ( "is_null", "is_boolean", diff --git a/tests/test_core/data_function/test_function_record.py b/tests/test_core/data_function/test_function_record.py index a6ce0fd71..6c5819ad8 100644 --- a/tests/test_core/data_function/test_function_record.py +++ b/tests/test_core/data_function/test_function_record.py @@ -508,6 +508,20 @@ def test_swapped_same_typed_keys_store_different_signature_hashes( contents = stored.column("__pf_var_function_content_hash").to_pylist() assert len(signatures) == len(orders) and len(set(signatures)) == len(orders) assert len(set(contents)) == 1 + # Each row is its own order's: matched by that order's signature hash, it holds + # the function's values, for that order's input, under that order's keys. A row + # that took another row's signature, or an append that swapped two same-typed + # output columns, would fail here. + by_signature = { + row["__pf_var_function_signature_hash"]: row for row in stored.to_pylist() + } + for index, order in enumerate(orders): + expected_signature = _record(_build("from_fn", fn, list(order)))[ + "function_signature_hash" + ] + row = by_signature[expected_signature] + values = fn(index + 1, 2) + assert {key: row[key] for key in order} == dict(zip(order, values)), order _PRINT_RECORD = """ diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 3a5aa4a51..4fe75ba5d 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -35,7 +35,11 @@ SQLiteConnector, ) from orcapod.databases.utils import in_held_column_order -from orcapod.errors import InputValidationError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) from tests.test_databases.type_matrix import open_database PATH = ("t",) @@ -284,13 +288,16 @@ def test_the_step_reorders_the_held_columns_by_name() -> None: def test_the_step_keeps_the_given_fields() -> None: - """Metadata and nullability go on to the append checks as given.""" + """The rows are reordered and their fields kept as given: metadata, and a + nullability the held column does not have (the append checks judge it).""" field = pa.field("c", pa.int64(), nullable=False, metadata={"unit": "m"}) given = pa.Table.from_arrays( [pa.array([1], pa.int64()), pa.array([2], pa.int64())], schema=pa.schema([field, pa.field("a", pa.int64())]), ) - out = in_held_column_order(given, _held("a", "c")) + held = [pa.field("a", pa.int64()), field.with_nullable(True)] + out = in_held_column_order(given, held) + assert out.column_names == ["a", "c"] assert out.schema.field("c").equals(field, check_metadata=True) @@ -804,13 +811,30 @@ def rows(n: int, pair: Any, order: list[str]) -> pa.Table: record_id_column="rid", flush=stored, ) - with pytest.raises(Exception): # noqa: B017, PT011 # main's own refusal, by backend - db2 = ExtensionAwareDatabase(inner, two[0]) - db2.add_records( - PATH, rows(2, two, ["text", "b", "rid", "a"]), record_id_column="rid" - ) - db2.flush() - inner.get_all_records(PATH, record_id_column="rid") + second = ExtensionAwareDatabase(inner, two[0]) + permuted = rows(2, two, ["text", "b", "rid", "a"]) + # Main's verdict, measured on main 321284ae, the same here. + if backend == "in-memory" and not stored: + with pytest.raises(pa.ArrowInvalid): + second.add_records(PATH, permuted, record_id_column="rid") + elif backend == "in-memory": + second.add_records(PATH, permuted, record_id_column="rid") + with pytest.raises(pa.ArrowInvalid): + second.flush() + elif not stored: + with pytest.raises(ValueError, match="Schema mismatch"): + second.add_records(PATH, permuted, record_id_column="rid") + else: + # Pre-existing on main and equal here (ITL-1371's family): Delta takes the + # rows by name and the stored table can no longer be read as one type. + second.add_records(PATH, permuted, record_id_column="rid", flush=True) + with pytest.raises(OrcapodDatabaseReadError): + inner.get_all_records(PATH, record_id_column="rid") + return + inner.flush() + stored_rows = inner.get_all_records(PATH, record_id_column="rid") + assert stored_rows is not None + assert stored_rows.column("rid").to_pylist() == [bytes([1])] @pytest.mark.parametrize( @@ -918,6 +942,9 @@ def run_end() -> Any: encoded: Any = pa.RunEndEncodedArray return encoded.from_arrays(pa.array([1], pa.int32()), pa.array([1])) + def view_struct() -> Any: + return pa.array([{"x": "a"}], pa.struct([("x", pa.string_view())])) + def interval() -> Any: return pa.array([(1, 0, 0)], pa.month_day_nano_interval()) @@ -956,6 +983,9 @@ def union(value: Any, mode: str) -> Any: ), "run-end encoded": (run_end(), run_end()), "interval": (interval(), interval()), + # Equal on both sides: a view type is not eligible even though the large + # normalization would turn it into ``large_string`` (CodeRabbit on PR 491). + "string view in a struct": (view_struct(), view_struct()), } @@ -973,6 +1003,38 @@ def test_a_column_of_a_type_the_comparison_does_not_handle_is_never_reordered( assert in_held_column_order(given, held) is given +class _KeyNotNullSQLite(SQLiteConnector): + """A SQLite connector whose reads give the primary key ``NOT NULL``, as a + PostgreSQL connector does (the CI failure of PR 491's PostgreSQL job).""" + + def iter_batches(self, query: str, params: Any = None, batch_size: int = 1000): # type: ignore[override] + for batch in super().iter_batches(query, params, batch_size): + schema = batch.schema + index = schema.get_field_index("__record_id") + if index >= 0: + schema = schema.set(index, schema.field(index).with_nullable(False)) + yield pa.RecordBatch.from_arrays(batch.columns, schema=schema) + + +@pytest.mark.parametrize("order", [["id", "a", "c", "b"], ["b", "c", "id", "a"]]) +def test_queued_rows_combine_with_a_stored_key_read_back_not_null( + tmp_path: Path, order: list[str] +) -> None: + """A store reads its primary key back ``NOT NULL`` while the queued rows declare + it nullable: a read that combines them takes the column nullable, the arrays + unchanged, in either column order; a read before and after the flush give the + same rows (as the PostgreSQL CI job checks against a live server).""" + db = ConnectorArrowDatabase(_KeyNotNullSQLite(str(tmp_path / "store.db"))) + _add(db, _rows([ID, "a", "c", "b"], [1, 2]), flush=True) + _add(db, _rows(order, [3, 4])) + before = db.get_all_records(PATH, record_id_column=ID) + _check(before, [ID, "a", "c", "b"], [1, 2, 3, 4]) + db.flush() + _check( + db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3, 4] + ) + + # ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index a99d785aa..a3c298224 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1064,7 +1064,9 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: else the stored table; Delta to the rows still pending (it matches a stored table by name itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, and to the stored table when it writes or reads them, checking them first against the -table as it is then, by exact name and type. A table keeps the column +table as it is then, by exact name and type (a column with field metadata stays in its +queued order at a flush; SpiralDB, which keeps field metadata, matches a write by name +itself). A table keeps the column order the database gave its first write: the first write's order, except in SpiralDB, which stores and reads a table's key columns first and then its other columns sorted by name, whatever the order written (measured on SpiralDB itself). An append that also