diff --git a/changelog.d/ITL-1367.md b/changelog.d/ITL-1367.md new file mode 100644 index 000000000..91d6d79ae --- /dev/null +++ b/changelog.d/ITL-1367.md @@ -0,0 +1,18 @@ +### 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 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 new file mode 100644 index 000000000..40c7d996b --- /dev/null +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -0,0 +1,71 @@ +## `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`. 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 (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 +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`. + +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 +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..763b978df --- /dev/null +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -0,0 +1,163 @@ +# 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 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 + +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..9819e3cfb 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,6 +81,23 @@ 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, 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 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 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 +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..761486310 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, @@ -56,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``. @@ -408,6 +439,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 +489,36 @@ def add_records( if flush: self.flush() + def _held_column_order( + self, record_path: tuple[str, ...] + ) -> "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 (``_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: + return list(pending.schema) + return 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. Never remembered: each call asks the connector.""" + if table_name not in self._connector.get_table_names(): + 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 ) -> None: @@ -565,14 +630,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. - existing_table_names = self._connector.get_table_names() - if table_name in existing_table_names: + # 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 = { - c.name: normalize_to_large_types(c.arrow_type, keep_null=True) - for c in self._connector.get_column_info(table_name) - } + 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 @@ -593,6 +657,10 @@ def _fmt(cols: dict) -> str: "Schema evolution is not supported." ) + # 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 ) @@ -646,11 +714,20 @@ def get_all_records( parts.append(committed) pending = self._pending_batches.get(record_key) if pending is not None and pending.num_rows > 0: + # 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 - 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/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 827d78ea5..cbf6e2831 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -19,6 +19,7 @@ from orcapod.databases.utils import ( appended_field_change, coerce_record_id, + in_held_column_order, metadata_bytes, ) from orcapod.errors import ( @@ -1892,6 +1893,14 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table + # 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 # its field metadata and nested attributes instead (ITL-1334). diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 92fca521a..3c78dd1e0 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,16 @@ 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 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). held = [ diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 8cd9f0018..17018eb43 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,138 @@ 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[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, 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, or ``None`` when nothing is held. + + Returns: + ``records``, reordered or as given. + """ + if held is None: + return records + names = records.column_names + held_names = [field.name for field in held] + if names == held_names: + return records + 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} + if not all(_same_field(field, held_fields[field.name]) for field in records.schema): + return records + return records.select(held_names) + + +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) + ): + return False + 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", + "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: + """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 ( + 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) + ) + 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 + ) + 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 any(getattr(t, kind)(given) for kind in _LEAF_KINDS) diff --git a/tests/test_core/data_function/test_function_record.py b/tests/test_core/data_function/test_function_record.py index 41a210e73..6c5819ad8 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,15 +498,30 @@ 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 + # 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/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..4fe75ba5d --- /dev/null +++ b/tests/test_databases/test_append_by_name.py @@ -0,0 +1,1079 @@ +"""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 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 + +import os +import sqlite3 +import uuid +from collections.abc import Iterator +from contextlib import ExitStack +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import pyarrow as pa +import pytest + +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, + SpiralDBConnector, + SQLiteConnector, +) +from orcapod.databases.utils import in_held_column_order +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) +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) + + +# 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, 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") + 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 + 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: + """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"') + 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), + ["b", ID, "c", "a"], + [3, 4], + ) + + +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 + 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), + _given_order("SpiralDB", ["b", ID, "c", "a"]), + [3, 4], + ) + + +# ── The shared step ──────────────────────────────────────────────────────────── + + +def _held(*names: str) -> list[Any]: + return [pa.field(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: + """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())]), + ) + 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) + + +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 _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__(), + }, + ) + + +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") + a = pa.field("a", pa.int64()) + + 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 + live = pa.table( + { + "text": pa.ExtensionArray.from_storage( + one, pa.array(["x"], pa.large_string()) + ), + "a": [1], + } + ) + 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: + given = pa.table({"b": pa.array(["x"], pa.string()), "a": [1]}) + out = in_held_column_order( + given, [pa.field("a", pa.int64()), pa.field("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("c", "a", "a"), _held("a", "c", "a"), id="a repeated name"), + pytest.param( + _table("c", "a"), + [pa.field("a", pa.int64()), pa.field("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], + } + ), + [ + 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[Any] | None +) -> None: + assert in_held_column_order(given, held) is given + + +@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(rid: bytes, order: list[str]) -> pa.Table: + columns = { + 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: + """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, + ) + + 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 + 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 ───────────────────────────────── + + +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, 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( + ["__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, 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 + ) + 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] + ) + + +# ── 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_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( + { + "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") + 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 committed is not None + assert committed.select(["rid", "z", "a"]).to_pylist() == queued.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, + ) + 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( + ("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] + + +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 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()) + + 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()), + # 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()), + } + + +@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 + + +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) ────────────────────────── + + +@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..a3c298224 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1055,6 +1055,23 @@ 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, 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 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 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 +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. """