From a7ebd91f68fa1cde97e4b253c4928920eba95a10 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:10:07 -0800 Subject: [PATCH 01/22] 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 42843d41d4a0022d6a6b11acdeb5ada31a544c93 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:26:24 -0800 Subject: [PATCH 02/22] wip(databases): canonical order for a new table (ITL-1370) --- .../databases/connector_arrow_database.py | 6 +- src/orcapod/databases/delta_lake_databases.py | 7 ++- src/orcapod/databases/in_memory_databases.py | 3 +- src/orcapod/databases/utils.py | 62 ++++++++++++++----- 4 files changed, 57 insertions(+), 21 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b2a435116..624da3d0f 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -411,8 +411,10 @@ 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, so the connector always receives the stored order - # (ITL-1367). - records = in_held_column_order(records, self._held_column_order(record_path)) + # (ITL-1367); a new table is written in the canonical order (ITL-1370). + records = in_held_column_order( + records, self._held_column_order(record_path), self.RECORD_ID_COLUMN + ) self._refuse_changed_columns(record_path, records.schema) records = self._deduplicate_within_table(records) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 5fc4dd3ff..1ad20a54c 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1894,8 +1894,11 @@ def add_records( 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)) + # put in the held order (ITL-1367); a new table is written in the canonical + # order (ITL-1370). + records = in_held_column_order( + records, self._held_column_order(record_path), self.RECORD_ID_COLUMN + ) # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 34be934c2..bf29333f8 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -260,7 +260,7 @@ 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). + # (ITL-1367); a new table is written in the canonical order (ITL-1370). held_table = self._pending_batches.get(record_key) if held_table is None: held_table = self._tables.get(record_key) @@ -269,6 +269,7 @@ def add_records( None if held_table is None else [(f.name, f.type) for f in held_table.schema], + self.RECORD_ID_COLUMN, ) # 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 4fb4c632e..17ba93e3b 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -203,35 +203,65 @@ def first_changed_column( 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). +def canonical_column_order(records: "pa.Table", record_id_column: str) -> "pa.Table": + """``records`` with its columns in the canonical order of a new table (ITL-1370). - 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. + The record id column, then every other column sorted by name, by code point + (Python's ``sorted`` on ``str``): the order SpiralDB stores every table in, so all + five databases store and read one order. Nothing else depends on it: no hash, path + or record id reads a stored table's column order, and every reader presents its + rows in row order whatever the stored order (``utils.arrow_utils.in_presented_order``). + Names that repeat are returned as given, for the database's own rule. - 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 that create the table. + record_id_column: The record id column, as the database names it. + + Returns: + ``records``, reordered or as given. + """ + names = records.column_names + if len(set(names)) != len(names) or record_id_column not in names: + return records + order = [record_id_column, *sorted(n for n in names if n != record_id_column)] + if order == names: + return records + return records.select(order) + + +def in_held_column_order( + records: "pa.Table", + held: "Sequence[tuple[str, pa.DataType]] | None", + record_id_column: str, +) -> "pa.Table": + """``records`` with its columns in the order the database stores them (ITL-1367, + ITL-1370). + + A new table (``held`` is ``None``) is written in the canonical order + (``canonical_column_order``): the record id, then every other column by name. A + table the database already holds keeps its order: an append matches columns by + name, never by position, so when ``records`` has exactly the held columns in + another order, each with the held type, its columns are put in the held order (a + table written before ITL-1370, in another order, keeps it). 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: a column + added or missing, a type that differs (a struct whose children are in another + order included: its type differs; ITL-1368), 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. + record_id_column: The record id column, as the database names it. Returns: ``records``, reordered or as given. """ if held is None: - return records + return canonical_column_order(records, record_id_column) names = records.column_names held_names = [name for name, _ in held] if names == held_names: From a4d3cc0f45d4c64a72230fd6ad3ae72092692bf5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:40:41 -0800 Subject: [PATCH 03/22] 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 0b268cb7be7ff91c9366c77211d02c46e52c7ce6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 13:56:10 -0800 Subject: [PATCH 04/22] wip(ITL-1370): readers present row order; canonical order tests --- src/orcapod/core/cached_function_pod.py | 10 +- src/orcapod/core/data_function.py | 5 +- src/orcapod/core/nodes/function_node.py | 27 ++ src/orcapod/core/nodes/operator_node.py | 40 +-- src/orcapod/core/result_cache.py | 42 ++- src/orcapod/core/sources/cached_source.py | 9 +- src/orcapod/core/sources/derived_source.py | 12 +- src/orcapod/databases/delta_lake_databases.py | 7 +- src/orcapod/pipeline/logging_observer.py | 15 +- src/orcapod/pipeline/observability_reader.py | 18 +- src/orcapod/pipeline/status_observer.py | 22 +- src/orcapod/utils/arrow_utils.py | 46 +++ tests/test_databases/test_append_by_name.py | 85 +++-- .../test_canonical_stored_order.py | 302 ++++++++++++++++++ 14 files changed, 567 insertions(+), 73 deletions(-) create mode 100644 tests/test_databases/test_canonical_stored_order.py diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 5fa41bfdb..47ed9ed43 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -23,7 +23,11 @@ data_context_field, require_storable, ) -from orcapod.core.result_cache import ResultCache, pod_timestamp_type +from orcapod.core.result_cache import ( + ResultCache, + pod_timestamp_type, + result_table_layout, +) from orcapod.hooks import InvocationStatus from orcapod.protocols.core_protocols import ( FunctionPodProtocol, @@ -75,6 +79,10 @@ def __init__( # The uri holds no hash up to the function's name, which comes after # "side_effect_function" for a pod that takes the invocation context. name_path=self.uri[: 2 if function_pod.ctx_arg_name is not None else 1], + layout=result_table_layout( + function_pod.data_function.declaration, + tuple(function_pod.data_function.output_data_schema), + ), ) def require_storable_results(self) -> None: diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 6fc71c3dc..9d83dabb4 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -26,7 +26,7 @@ default_value_refused, hash_default_value, ) -from orcapod.core.result_cache import ResultCache +from orcapod.core.result_cache import ResultCache, result_table_layout from orcapod.errors import ( NoOutputsDeclaredError, OutputTypeError, @@ -1492,6 +1492,9 @@ def __init__( auto_flush=True, # The first uri component is the function's name; no hash before it. name_path=record_path_prefix + self.uri[:1], + layout=result_table_layout( + self.declaration, tuple(self.output_data_schema) + ), ) @property diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 117eb50b9..a4cd9c8de 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3406,6 +3406,10 @@ def _fetch_joined_records( stored_rows - taginfo.num_rows, ) + # Presented in the node's layout, whatever order the tables are stored in + # (ITL-1370). + layout = self._presented_layout() + taginfo = arrow_utils.in_presented_order(taginfo, layout) taginfo_columns = tuple(taginfo.column_names) taginfo_schema = taginfo.schema data_tags = self._stored_data_tags(taginfo_schema) @@ -3608,6 +3612,7 @@ def _fetch_joined_records( else (taginfo_schema, results_schema) ), ) + joined = arrow_utils.in_presented_order(joined, layout) # In memory, each row names its data context in the datagram context column. joined = joined.append_column( pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), @@ -3661,6 +3666,28 @@ def _stored_data_tags(self, taginfo_schema: "pa.Schema") -> tuple[str, ...]: ) return expected + def _presented_layout(self) -> list[str]: + """The columns of this node's rows in the order it presents them (ITL-1370). + + Its zero-row table (tags, system tags, data, context, source info) when its + input can say it; a loaded node's saved tags and data, each data column + followed by nothing else. Stored rows are put in this order on read, then + every other column by name (``arrow_utils.in_presented_order``), so what the + node presents never follows the stored order. + """ + if self._input_stream is not None: + zero = self._zero_row_output_table() + if zero is not None: + return zero.column_names + if self._function_pod is None: + tags, data = self.keys() + return [ + *tags, + *data, + *(f"{constants.SOURCE_PREFIX}{name}" for name in data), + ] + return [] + def _stored_tag_keys(self, fetched: _JoinedRecords) -> tuple[str, ...]: """Return the user tag columns of the records in *fetched*. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 12a19d954..de62d30f0 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1513,33 +1513,21 @@ def _read_current_context_records(self) -> "pa.Table | None": return self._in_row_order_on_read(records.drop([constants.DATA_CONTEXT_COL])) def _in_row_order_on_read(self, records: "pa.Table") -> "pa.Table": - """Put a stored table's user columns in row order; bookkeeping stays in place. - - A node run on its own stored its rows in its operator's column order before - ITL-1133 (a join lists its data before its system tags); every writer now - stores the row order (``StaticOutputOperatorPod._in_row_order``). Read in row - order, such a table gives the columns of every other path, and a table in row - order is returned unchanged. Only the order changes: no column is added, - dropped, renamed or retyped, and the bookkeeping columns (``__``, and - ``HASH_COLUMN_NAME``) keep their positions. + """Present a stored table in the node's row order, whatever order it is + stored in (ITL-1370). + + The record hash first, then the node's columns in row order (user tags, system + tags, data, source info: its zero-row table, ``_in_row_order``), then any other + column (the node content hash) by name (``arrow_utils.in_presented_order``). + A table is stored in the database's order: the canonical order for a table + created since ITL-1370, the order of its first write for an older one (a node + run on its own before ITL-1133 stored its operator's order). Only the order + changes: no column is added, dropped, renamed or retyped. """ - names = records.column_names - - def bookkeeping(name: str) -> bool: - return ( - name.startswith(constants.META_PREFIX) or name == self.HASH_COLUMN_NAME - ) - - user = [n for n in names if not bookkeeping(n)] - ordered = iter( - StaticOutputOperatorPod._in_row_order( - records.select(user), self.keys()[0] - ).column_names - ) - order = [n if bookkeeping(n) else next(ordered) for n in names] - if order == names: - return records - return records.select(order) + layout = StaticOutputOperatorPod._in_row_order( + self._make_empty_table(), self.keys()[0] + ).column_names + return arrow_utils.in_presented_order(records, [self.HASH_COLUMN_NAME, *layout]) def _make_empty_table(self) -> "pa.Table": """Build the zero-row table this node reads as when it holds no rows. diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index a3f544315..6b676b313 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -10,9 +10,10 @@ import logging import uuid from datetime import datetime, timezone +from collections.abc import Sequence from typing import TYPE_CHECKING, Any -from orcapod.core.data_function_types import StoredColumn +from orcapod.core.data_function_types import DataFunctionTypeDeclaration, StoredColumn from orcapod.errors import OrcapodDatabaseReadError, OrcapodDatabaseWriteError from orcapod.hashing.arrow_hashers import ARROW_HASH_LABEL from orcapod.contexts.stored import ( @@ -30,6 +31,7 @@ RESULT_DB_SCHEMA_VERSION, constants, ) +from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -85,6 +87,35 @@ def pod_timestamp_type() -> pa.DataType: """ +def result_table_layout( + declaration: "DataFunctionTypeDeclaration", output_keys: "Sequence[str]" +) -> tuple[str, ...]: + """The columns of a result table in the order they are presented (ITL-1370). + + The record id, the input data hash, the declared variation and execution + columns in declaration order, the outputs in declared order, their source-info + columns, the timestamp: the order ``ResultCache.store`` builds a row in. A stored + result table is in its database's order; ``get_all_records`` presents it in this + one. + + Args: + declaration: The data function type's declaration. + output_keys: The function's output names, in declared order. + + Returns: + The column names. + """ + return ( + constants.DATA_RECORD_ID, + constants.INPUT_DATA_HASH_COL, + *(f"{constants.PF_VARIATION_PREFIX}{c.name}" for c in declaration.variation), + *(f"{constants.PF_EXECUTION_PREFIX}{c.name}" for c in declaration.execution), + *output_keys, + *(f"{constants.SOURCE_PREFIX}{key}" for key in output_keys), + constants.POD_TIMESTAMP, + ) + + class ResultCache: """Shared result caching backed by an ``ArrowDatabaseProtocol``. @@ -114,6 +145,7 @@ def __init__( auto_flush: bool = True, delivers_side_effects: bool = False, name_path: tuple[str, ...] | None = None, + layout: "Sequence[str]" = (), ) -> None: """Create a result cache over one result table. @@ -133,6 +165,9 @@ def __init__( the part that holds no hash. Result tables written before v0.3 are looked for under it, whatever hashes their paths hold (ITL-954). ``None`` looks at the paths computed from ``record_path`` only. + layout: The result table's columns in the order ``get_all_records`` + presents them (``result_table_layout``), whatever order the table is + stored in (ITL-1370); other columns follow by name. """ self._result_database = result_database self._record_path = record_path @@ -140,6 +175,7 @@ def __init__( self._auto_flush = auto_flush self._delivers_side_effects = delivers_side_effects self._name_path = name_path + self._layout = tuple(layout) # Set once a read has reported the stored rows it skipped. self._skipped_rows_reported = False # Set once stored results of other generations have been accounted for. @@ -439,4 +475,6 @@ def get_all_records( ) if result_table.num_rows == 0: return None - return result_table.drop([constants.DATA_CONTEXT_COL]) + return arrow_utils.in_presented_order( + result_table.drop([constants.DATA_CONTEXT_COL]), self._layout + ) diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 4be081849..5d39a874c 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -39,7 +39,7 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import schema_utils +from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -524,8 +524,11 @@ def _build_merged_stream(self) -> ArrowTableStream: for h in stored.column(self.HASH_COLUMN_NAME).to_pylist() if h is not None } - all_records = stored.drop( - [self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL] + # Presented in the wrapped source's layout, whatever order the cache + # table is stored in (ITL-1370). + all_records = arrow_utils.in_presented_order( + stored.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]), + self._empty_table().column_names, ) tag_keys = self._source.keys()[0] diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 5b06672d2..169205f9e 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -34,7 +34,7 @@ from orcapod.errors import InputValidationError from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema -from orcapod.utils import schema_utils +from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.lazy_module import LazyModule from orcapod.utils.provisional import provisional_class_name @@ -487,7 +487,15 @@ def _origin_records(self) -> "pa.Table | None": ) records = without_tag_kind_marks(records) self._require_origin_types(records) - return records + # The origin's layout first, whatever order its tables are stored in: a node + # presents its rows so already, and this keeps a derived source's columns + # in the origin's order for any origin (ITL-1370). + layout = self._empty_origin_table().column_names + data = self._origin.keys()[1] + return arrow_utils.in_presented_order( + records, + [*layout, *(f"{constants.SOURCE_PREFIX}{name}" for name in data)], + ) def _require_origin_types(self, records: "pa.Table") -> None: """Refuse stored rows whose Arrow types are not the origin's (ITL-640). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c7d139927..2cbda28a4 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1923,9 +1923,10 @@ def add_records( # Columns match by name: rows with the held columns in another order are # put in the held order (ITL-1367); a new table is written in the - # canonical order (ITL-1370). 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. + # canonical order (ITL-1370). 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), self.RECORD_ID_COLUMN diff --git a/src/orcapod/pipeline/logging_observer.py b/src/orcapod/pipeline/logging_observer.py index 057f8c33e..5e9c55018 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -53,6 +53,7 @@ from orcapod.pipeline.logging_capture import install_capture_streams from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +from orcapod.utils import arrow_utils if TYPE_CHECKING: import pyarrow as pa @@ -64,6 +65,11 @@ # Default path (table name) within the database where log rows are stored. DEFAULT_LOG_PATH: tuple[str, ...] = ("execution_logs",) +LOG_COLUMNS: tuple[str, ...] = ("_log_id", "_log_run_id", "_log_timestamp") +"""The columns every log row has, in the order the observer presents them; the +captured fields and the tag columns follow, by name (ITL-1370: a stored table's +order is the database's, so a read is put in this order).""" + class DataLogger: """Context-bound logger created by `_ContextualizedLoggingObserver` per data. @@ -246,7 +252,12 @@ def get_logs(self) -> "pa.Table | None": try: sources = self._db.list_sources() except (AttributeError, NotImplementedError): - return self._db.get_all_records(DEFAULT_LOG_PATH) + table = self._db.get_all_records(DEFAULT_LOG_PATH) + return ( + None + if table is None + else arrow_utils.in_presented_order(table, LOG_COLUMNS) + ) parts = [] for src in sources: @@ -255,7 +266,7 @@ def get_logs(self) -> "pa.Table | None": if tbl is not None and tbl.num_rows > 0: if "__record_id" in tbl.schema.names: tbl = tbl.drop(["__record_id"]) - parts.append(tbl) + parts.append(arrow_utils.in_presented_order(tbl, LOG_COLUMNS)) if not parts: return None if len(parts) == 1: diff --git a/src/orcapod/pipeline/observability_reader.py b/src/orcapod/pipeline/observability_reader.py index acddcf44e..3c31701df 100644 --- a/src/orcapod/pipeline/observability_reader.py +++ b/src/orcapod/pipeline/observability_reader.py @@ -7,6 +7,10 @@ import polars as pl +from orcapod.pipeline.logging_observer import LOG_COLUMNS +from orcapod.pipeline.status_observer import STATUS_COLUMNS +from orcapod.utils import arrow_utils + if TYPE_CHECKING: from upath import UPath @@ -89,8 +93,11 @@ def _get_status_df(self) -> pl.DataFrame: df = pl.read_delta(str(table_dir)) df = df.with_columns(pl.lit(node_name).alias("node_label")) frames.append(df) - self._status_df = ( - pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + df = pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + # The columns in the observer's order, whatever order each table is + # stored in (ITL-1370). + self._status_df = df.select( + arrow_utils.presented_column_order(df.columns, STATUS_COLUMNS) ) return self._status_df @@ -103,8 +110,11 @@ def _get_logs_df(self) -> pl.DataFrame: df = pl.read_delta(str(table_dir)) df = df.with_columns(pl.lit(node_name).alias("node_label")) frames.append(df) - self._logs_df = ( - pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + df = pl.concat(frames, how="diagonal_relaxed") if frames else pl.DataFrame() + # The columns in the observer's order, whatever order each table is + # stored in (ITL-1370). + self._logs_df = df.select( + arrow_utils.presented_column_order(df.columns, LOG_COLUMNS) ) return self._logs_df diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index 58d9d5096..4967d62be 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -60,6 +60,7 @@ from orcapod.pipeline.observer import NoOpLogger from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +from orcapod.utils import arrow_utils from orcapod.types import SchemaLike if TYPE_CHECKING: @@ -72,6 +73,18 @@ # Default path within the database where status rows are stored. DEFAULT_STATUS_PATH: tuple[str, ...] = ("execution_status",) +STATUS_COLUMNS: tuple[str, ...] = ( + "_status_id", + "_status_run_id", + "_status_pipeline_uri", + "_status_state", + "_status_timestamp", + "_status_error_summary", +) +"""The columns every status row has, in the order the observer presents them; the +node's tag columns follow, by name (ITL-1370: a stored table's order is the +database's, so a read is put in this order).""" + _NOOP_LOGGER = NoOpLogger() @@ -199,7 +212,12 @@ def get_status(self) -> "pa.Table | None": sources = self._db.list_sources() except (AttributeError, NotImplementedError): # Fall back to direct read for DBs that don't implement list_sources - return self._db.get_all_records(DEFAULT_STATUS_PATH) + table = self._db.get_all_records(DEFAULT_STATUS_PATH) + return ( + None + if table is None + else arrow_utils.in_presented_order(table, STATUS_COLUMNS) + ) parts = [] for src in sources: @@ -208,7 +226,7 @@ def get_status(self) -> "pa.Table | None": if tbl is not None and tbl.num_rows > 0: if "__record_id" in tbl.schema.names: tbl = tbl.drop(["__record_id"]) - parts.append(tbl) + parts.append(arrow_utils.in_presented_order(tbl, STATUS_COLUMNS)) if not parts: return None if len(parts) == 1: diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index f2966c048..2259ea30b 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -695,6 +695,52 @@ def column_arrow_type(schema: pa.Schema, name: str) -> pa.DataType: return schema.types[index] +def presented_column_order( + names: "Sequence[str]", reference: "Sequence[str]" +) -> list[str]: + """The order a reader presents stored columns in, whatever order they are stored + in (ITL-1370). + + The names ``reference`` lists, in its order (the reader's own layout: the zero-row + table of the source or node it presents, or the columns its writer builds), then + every other name, sorted by name. A stored table's column order is the database's + (a new table is stored in the canonical order, an older one in the order it was + first written), so nothing a user sees may follow it: every reader of stored rows + puts them in this order (``in_presented_order``). + + Args: + names: The columns read. + reference: The reader's layout; names it lists that were not read are skipped. + + Returns: + ``names``, reordered. + """ + held = set(names) + leading = [name for name in dict.fromkeys(reference) if name in held] + placed = set(leading) + return leading + sorted(name for name in names if name not in placed) + + +def in_presented_order(table: "pa.Table", reference: "Sequence[str]") -> "pa.Table": + """``table`` (stored rows as read) with its columns in ``presented_column_order``. + + The one helper every reader of stored rows uses, so a table stored in the + canonical order and one stored in an older order present identically (ITL-1370). + Only the order changes: no column is added, dropped, renamed or retyped. + + Args: + table: Rows read from a database. + reference: The reader's layout. + + Returns: + ``table``, its columns reordered (``table`` itself when already in order). + """ + order = presented_column_order(table.column_names, reference) + if order == table.column_names: + return table + return table.select(order) + + def concat_tables_by_name(tables: "Sequence[pa.Table]") -> "pa.Table": """Vertically concatenate tables, matching columns by name rather than position. diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 9cfe5ba75..80149c2c5 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -14,7 +14,7 @@ import sqlite3 import uuid from collections.abc import Iterator -from contextlib import ExitStack +from contextlib import ExitStack, nullcontext from pathlib import Path from typing import Any from unittest.mock import patch @@ -22,6 +22,8 @@ import pyarrow as pa import pytest +import orcapod.databases.utils as database_utils + from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, @@ -66,16 +68,34 @@ def _rows(order: list[str], ns: list[int]) -> pa.Table: ) -def _given_order(database: str, first: list[str], stored: bool = True) -> list[str]: +GENERATIONS = ("canonical", "before ITL-1370") + + +def _first_write(generation: str) -> Any: + """The context a table's first write is made in: today's (the canonical order, + ITL-1370), or as before ITL-1370 (the order written), which a store may still + hold; the shared step's canonical order is switched off for that write.""" + if generation == "canonical": + return nullcontext() + return patch.object( + database_utils, "canonical_column_order", lambda records, record_id: records + ) + + +def _given_order( + database: str, first: list[str], generation: str = "canonical", 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. + A new table is written in the canonical order, the record id then every other + column by name (ITL-1370); a table written before ITL-1370 keeps the order of its + first write. SpiralDB stores and reads every table in its own order, the key + columns then the value columns by name, whatever the order written (observed + live, ITL-1367; its fake does the same): the canonical order. """ - if database == "SpiralDB" and stored: - return [ID, *sorted(n for n in first if n != ID)] + canonical = [ID, *sorted(n for n in first if n != ID)] + if generation == "canonical" or (database == "SpiralDB" and stored): + return canonical return first @@ -95,24 +115,28 @@ def _add(db: Any, table: pa.Table, flush: bool = False) -> None: @pytest.mark.parametrize("first", FIRST_ORDERS) @pytest.mark.parametrize("second", SECOND_ORDERS) @pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +@pytest.mark.parametrize("generation", GENERATIONS) def test_an_append_in_another_order_is_matched_by_name( - tmp_path: Path, database: str, first: str, second: str, when: str + tmp_path: Path, database: str, first: str, second: str, when: str, generation: 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") + with _first_write(generation): + _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"), + _given_order( + database, first_order, generation, 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), + _given_order(database, first_order, generation), [1, 2, 3, 4], ) @@ -120,11 +144,14 @@ def test_an_append_in_another_order_is_matched_by_name( @pytest.mark.parametrize("database", DURABLE) @pytest.mark.parametrize("first", FIRST_ORDERS) @pytest.mark.parametrize("second", SECOND_ORDERS) +@pytest.mark.parametrize("generation", GENERATIONS) def test_an_append_in_another_order_after_reopening_is_matched_by_name( - tmp_path: Path, database: str, first: str, second: str + tmp_path: Path, database: str, first: str, second: str, generation: str ) -> None: + """A store written before ITL-1370 (or after) is reopened by today's code: an + old-order table keeps its order and takes appends in any order (ITL-1367).""" first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] - with open_database(database, tmp_path) as db: + with open_database(database, tmp_path) as db, _first_write(generation): _add(db, _rows(first_order, [1, 2]), flush=True) with open_database(database, tmp_path) as db: _add(db, _rows(second_order, [3, 4])) @@ -133,17 +160,17 @@ def test_an_append_in_another_order_after_reopening_is_matched_by_name( with open_database(database, tmp_path) as db: _check( db.get_all_records(PATH, record_id_column=ID), - _given_order(database, first_order), + _given_order(database, first_order, generation), [1, 2, 3, 4, 5], ) @pytest.mark.parametrize("database", DATABASES) -def test_a_new_table_keeps_the_order_the_database_gave_its_first_write( +def test_a_new_table_is_written_in_the_canonical_order( 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).""" + """A new table is the record id, then every other column by name (ITL-1370), + whatever order its first write has, in every database.""" 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}",) @@ -209,7 +236,8 @@ def test_a_table_created_again_in_another_order_is_read_as_it_is_now( 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) + with _first_write("before ITL-1370"): # created again, another order + _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), @@ -230,7 +258,8 @@ def test_rows_queued_before_a_table_is_created_again_are_read_with_it_by_name( 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) + with _first_write("before ITL-1370"): # created again, another order + _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] ) @@ -273,7 +302,7 @@ def _table(*names: str) -> pa.Table: 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")) + out = in_held_column_order(given, _held("a", "b", "c"), "rid") assert out.column_names == ["a", "b", "c"] assert out.to_pylist() == [{"a": 1, "b": 2, "c": 0}] @@ -285,13 +314,13 @@ def test_the_step_keeps_the_given_fields() -> None: [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")) + out = in_held_column_order(given, _held("a", "c"), "rid") 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")) + out = in_held_column_order(_table("A", "a", "c"), _held("a", "c", "A"), "rid") assert out.column_names == ["a", "c", "A"] assert out.to_pylist() == [{"A": 0, "a": 1, "c": 2}] @@ -305,13 +334,15 @@ def test_the_step_compares_a_logical_type_by_its_storage() -> None: _, 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())]) + out = in_held_column_order(given, [("a", pa.int64()), ("text", pa.string())], "rid") 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())]) + out = in_held_column_order( + given, [("a", pa.int64()), ("b", pa.large_string())], "rid" + ) assert out.column_names == ["a", "b"] @@ -349,7 +380,7 @@ def test_the_step_compares_types_in_their_large_variants() -> None: 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 + assert in_held_column_order(given, held, "rid") is given @pytest.mark.parametrize("database", ["in-memory", "Delta"]) @@ -528,7 +559,7 @@ def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> Non 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] + db.get_all_records(PATH, record_id_column=ID), [ID, "a", "b", "c"], [1, 2, 3] ) diff --git a/tests/test_databases/test_canonical_stored_order.py b/tests/test_databases/test_canonical_stored_order.py new file mode 100644 index 000000000..7ac36b3e9 --- /dev/null +++ b/tests/test_databases/test_canonical_stored_order.py @@ -0,0 +1,302 @@ +"""A new stored table is written in the canonical column order (ITL-1370). + +The record id, then every other column by name: the order the shared step +(``databases/utils.in_held_column_order``) gives a table nothing holds yet. One job +writes every stored table kind: a function pipeline table (``pdb``), its result table +(``rdb``), a side-effect log (``tdb``), an operator cache (``odb``) and a cached +source (``sdb``). Each test runs it twice through the shared step's two modes: as +before ITL-1370 (the step's canonical order switched off, so a table keeps the order +of its first write) and today. Nothing that identifies anything moves (content and +pipeline hashes, stored paths, record ids), and every reader presents the two stores +identically. + +The connector databases (SQLite, PostgreSQL, SpiralDB) cannot hold Orcapod's own +stored tables yet (ITL-1162); their canonical order is tested on plain tables in +``test_append_by_name.py``. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import AbstractContextManager, contextmanager +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pyarrow as pa +import pytest + +import orcapod.databases.utils as database_utils +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 DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +DATABASES = ("in-memory", "Delta") +KINDS = ("pdb_v1", "rdb_v1", "tdb_v1", "odb_v1", "sdb_v1") +RECORD_ID = "__record_id" + + +def _database(kind: str, root: Path) -> Any: + return InMemoryArrowDatabase() if kind == "in-memory" else DeltaTableDatabase(root) + + +def _before_itl_1370() -> AbstractContextManager[Any]: + """Tables created in this context are written as before ITL-1370: in the order + of their first write.""" + return patch.object( + database_utils, "canonical_column_order", lambda records, record_id: records + ) + + +def _source(name: str, data: list[str], rows: list[int]) -> ArrowTableSource: + """Two tags declared ``z_tag, a_tag`` (not in name order) and ``data`` floats.""" + 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([f"s{n}" for n in rows], pa.large_string()), + pa.array(rows, pa.int64()), + *(pa.array([float(n) for n in rows]) for _ in data), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + record_id_columns=["a_tag"], + 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 + + +@function_pod(output_keys=["z_sum"]) +def total(y: float, b: float) -> float: + return y + b + + +def _notify(ctx: Any, y: float, b: float) -> None: + return None + + +@contextmanager +def _job( + database: Any, rows: list[int], extra_node: bool = False +) -> Iterator[tuple[PipelineJob, CachedSource]]: + job = PipelineJob(name="itl1370", database=database) + cached = CachedSource(_source("left", ["y", "b"], rows), cache_database=database) + with job: + compute.pod(cached, label="fn") + Join()(cached, _source("right", ["x", "e"], rows), label="joined") + SideEffectPod(_notify)(cached, label="notify") + if extra_node: + total.pod(cached, label="fn2") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + yield job, cached + + +def _table(table: pa.Table | None) -> tuple[list[str], list[str]] | None: + if table is None: + return None + return table.column_names, sorted(map(str, table.to_pylist())) + + +# Function result rows are named by a fresh uuid7 each run (``__data_id``, the result +# table's record id, and the source-info tokens of the outputs, which name it): not +# hashes, different in any two runs, so compared by column only. +_RUN_SCOPED = ("fn.as_table", "fn.get_all_records", "fn.as_source") + + +def _observe(database: Any) -> dict[str, Any]: + """Everything a user can see of the job, and everything that identifies it.""" + seen: dict[str, Any] = {} + with _job(database, [1, 2]) as (job, cached): + for label in ("fn", "joined", "notify"): + node = job.nodes[label] + seen[f"{label}.content_hash"] = node.content_hash().to_string() + seen[f"{label}.pipeline_hash"] = node.pipeline_hash().to_string() + seen[f"{label}.as_table"] = _table(node.as_table(all_info=True)) + seen[f"{label}.as_table plain"] = _table(node.as_table()) + for label in ("fn", "joined"): + node = job.nodes[label] + seen[f"{label}.get_all_records"] = _table( + node.get_all_records(all_info=True) + ) + source = node.as_source() + seen[f"{label}.as_source"] = _table(source.as_table(all_info=True)) + seen[f"{label}.as_source.content_hash"] = source.content_hash().to_string() + seen["cached.as_table"] = _table(cached.as_table(all_info=True)) + seen["cached.content_hash"] = cached.content_hash().to_string() + seen["cached outputs"] = _table( + job.nodes["fn"]._cached_function_pod.get_all_cached_outputs() # pyright: ignore[reportOptionalMemberAccess] # the node's own result cache + ) + paths = sorted(database.list_table_paths()) + seen["paths"] = paths + for path in paths: + stored = database.get_all_records(path, record_id_column=RECORD_ID) + assert stored is not None + seen[f"stored {path[-1]}"] = stored.column_names + if path[-1] != "rdb_v1": + seen[f"record ids {path[-1]}"] = sorted( + stored.column(RECORD_ID).to_pylist() + ) + return seen + + +@pytest.fixture(params=DATABASES) +def database_kind(request: pytest.FixtureRequest) -> str: + return request.param + + +@pytest.fixture +def both(database_kind: str, tmp_path: Path) -> tuple[dict[str, Any], dict[str, Any]]: + """The job observed with its tables written as before ITL-1370, and today.""" + with _before_itl_1370(): + before = _observe(_database(database_kind, tmp_path / "before")) + today = _observe(_database(database_kind, tmp_path / "today")) + return before, today + + +def test_every_table_kind_is_written(both: tuple[dict[str, Any], dict[str, Any]]): + _, today = both + assert sorted(path[-1] for path in today["paths"]) == sorted(KINDS) + + +def test_no_hash_record_id_or_stored_path_moves( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + before, today = both + identity = [ + key + for key in today + if key.endswith("hash") or key == "paths" or key.startswith("record ids") + ] + assert len([k for k in identity if k.startswith("record ids")]) == len(KINDS) - 1 + for key in identity: + assert before[key] == today[key], key + + +def test_every_reader_presents_both_stores_identically( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + """A table written before ITL-1370 (its first write's order) and one written + today (the canonical order) present the same columns, in the same order, with + the same rows.""" + before, today = both + for key, value in today.items(): + if key.startswith(("stored", "record ids")) or key.endswith("hash"): + continue + if key in _RUN_SCOPED: + assert before[key][0] == value[0], key + else: + assert before[key] == value, key + + +def test_the_stores_differ_only_in_their_stored_column_order( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + before, today = both + for key in (k for k in today if k.startswith("stored")): + assert set(before[key]) == set(today[key]), key + assert before[key] != today[key], key # the job's first writes are not sorted + + +def test_each_table_kind_is_stored_in_the_canonical_order( + both: tuple[dict[str, Any], dict[str, Any]], +) -> None: + """The record id, then every other column by name, for every table kind.""" + _, today = both + for kind in KINDS: + names = today[f"stored {kind}"] + assert names == [RECORD_ID, *sorted(n for n in names if n != RECORD_ID)], kind + # Pinned where no hash enters a column name. + assert today["stored tdb_v1"] == [ + RECORD_ID, + "__data_context", + "executed_at", + "pipeline_run_id", + "record_id_hash", + ] + assert today["stored rdb_v1"] == [ + RECORD_ID, + "__data_context", + "__input_data_hash", + "__pf_exec_executor_info", + "__pf_exec_executor_type", + "__pf_exec_extra_info", + "__pf_exec_python_version", + "__pf_var_function_content_hash", + "__pf_var_function_module", + "__pf_var_function_name", + "__pf_var_function_signature_hash", + "__pf_var_function_version", + "__pf_var_git_hash", + "__pod_ts", + "_source_c_out", + "_source_w_out", + "c_out", + "w_out", + ] + + +def test_a_store_written_before_takes_new_rows_and_new_tables( + database_kind: str, tmp_path: Path +) -> None: + """Mixed generations: a store whose tables were written before ITL-1370 is run + again by today's code with new rows and a new node. Every old table keeps its + order and takes the new rows by name (ITL-1367); the new node's tables are + canonical; the nodes present every row.""" + database = _database(database_kind, tmp_path) + with _before_itl_1370(), _job(database, [1, 2]): + pass + old_orders = { + path: database.get_all_records(path, record_id_column=RECORD_ID).column_names + for path in database.list_table_paths() + } + with _job(database, [1, 2, 3], extra_node=True) as (job, cached): + assert sorted(cached.as_table().column("a_tag").to_pylist()) == [1, 2, 3] + for label in ("fn", "joined", "fn2"): + records = job.nodes[label].get_all_records() + assert records is not None + assert sorted(records.column("a_tag").to_pylist()) == [1, 2, 3], label + assert records.column_names[:2] == ["z_tag", "a_tag"], label + fn = job.nodes["fn"].get_all_records() + assert fn is not None + assert sorted(zip(fn["a_tag"].to_pylist(), fn["w_out"].to_pylist())) == [ + (1, 2.0), + (2, 4.0), + (3, 6.0), + ] + for path in database.list_table_paths(): + names = database.get_all_records(path, record_id_column=RECORD_ID).column_names + if path in old_orders: + assert names == old_orders[path], path + else: + assert names == [RECORD_ID, *sorted(n for n in names if n != RECORD_ID)] + new_tables = set(database.list_table_paths()) - set(old_orders) + assert {path[-1] for path in new_tables} == {"pdb_v1", "rdb_v1"} + + +def test_the_before_context_is_the_identity(tmp_path: Path) -> None: + """The comparison's 'before' writes a table in its first write's order.""" + database = InMemoryArrowDatabase() + table = pa.table( + {"b": [1], RECORD_ID: pa.array([b"r"], pa.large_binary()), "a": [2]} + ) + with _before_itl_1370(): + database.add_records(("t",), table, flush=True, record_id_column=RECORD_ID) + stored = database.get_all_records(("t",), record_id_column=RECORD_ID) + assert stored is not None and stored.column_names == ["b", RECORD_ID, "a"] From e8751e426d725cc23d12a2cbcba8bdc38a4dbba0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:03:43 -0800 Subject: [PATCH 05/22] 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 dbb2d1ce40935492db972e0fae5a62ebbc4b81a5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:07:31 -0800 Subject: [PATCH 06/22] wip(ITL-1370): rule text, docs, tests for readers, loaded jobs and observers --- .zed/rules | 28 ++++++- CLAUDE.md | 28 ++++++- changelog.d/ITL-1370.md | 26 ++++++ docs/dev/design_issues/ITL-1367-CO1.md | 4 +- docs/dev/design_issues/ITL-1370-CO2.md | 28 +++++++ .../dev/specs/itl-1367-stored-column-order.md | 13 ++- docs/reference/database-types.md | 13 ++- src/orcapod/databases/utils.py | 3 +- .../test_canonical_stored_order.py | 83 ++++++++++++++++++- tests/test_databases/type_matrix.py | 13 ++- 10 files changed, 213 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1370.md create mode 100644 docs/dev/design_issues/ITL-1370-CO2.md diff --git a/.zed/rules b/.zed/rules index cca3287e3..1bfd1e23d 100644 --- a/.zed/rules +++ b/.zed/rules @@ -980,6 +980,25 @@ generation of hashing; rows of the current data context are the current entries. Operator cache — odb_v1 (OPERATOR_DB_SCHEMA_VERSION) Cached source — sdb_v1 (SOURCE_DB_SCHEMA_VERSION) +- Stored column order (developer, November 22, 2026, ITL-1367 and ITL-1370: "I agree + that this is indeed the simplest and ultimately the most consistent"): a stored table's + column order is the database's, never a writer's. A new table is written in the + canonical order, the record id then every other column by name (code point), by the one + shared step every database calls, databases/utils.in_held_column_order + (canonical_column_order); it is the order SpiralDB itself stores. A table that exists + keeps its order (one written before ITL-1370 keeps its first write's): an append is + matched to it by exact name, never by position, when its names, storage types and + logical types equal the held ones; anything else keeps the database's own rule. A + connector database trusts nothing about a stored table across calls: it aligns an append + only to its own pending batch and checks rows against the table read at flush and at a + read. No hash, record id, path or layout version follows a stored column order, and no + table is rewritten. Every reader of stored rows presents them in its own layout, + whatever order they are stored in, through one helper, arrow_utils.in_presented_order + (the reader's layout, then any other column by name): CachedSource, DerivedSource, + the function node's stored view (_presented_layout), the operator node's stored read + (_in_row_order_on_read), the result cache (result_table_layout), the status and log + observers and ObservabilityReader. A new reader of stored rows uses it too; never + present a stored table in its stored order. - The layout version is the last component of a table path. Every layout marker starts at v1 for the first release, 0.4.0 (developer, November 18, 2026, ITL-1259; 0.3.0 was withdrawn, so nothing released uses v2). A change to the common bookkeeping columns of a table kind @@ -1216,10 +1235,11 @@ data. The rules: order, user tags, system tags, data, source info, stated once in StaticOutputOperatorPod._in_row_order; a node that keeps a run with no rows keeps _zero_rows_in_row_order, and an operator's own empty result built from its input - goes through _as_row_built_table. An operator node keeps and stores the row order on every - path (_kept_output: a job run, sync or async, and node.run() on its own; ITL-1133), - and reads a stored operator cache in row order (_in_row_order_on_read). Never change - the order of any other populated table: stored tables depend on it. + goes through _as_row_built_table. An operator node keeps the row order on every path + (_kept_output: a job run, sync or async, and node.run() on its own; ITL-1133); what it + stores is in its database's order and is presented in row order on read + (_in_row_order_on_read; "Stored column order"). Never change the order of any other + populated table a user sees: presentation follows it (no hash and no stored table does). - Data-tags come first among the data columns (developer, November 17, 2026, ITL-1205): a stream lists its data-tags first in its data keys and data schema, in tag order, then its other data columns in table order. A table built from rows lays a data-tag out among diff --git a/CLAUDE.md b/CLAUDE.md index 3f2b6a347..f7887f26b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1009,6 +1009,25 @@ current data context are the current entries. | Operator cache | `odb_v1` | `OPERATOR_DB_SCHEMA_VERSION` | | Cached source | `sdb_v1` | `SOURCE_DB_SCHEMA_VERSION` | +- **Stored column order** (developer, November 22, 2026, ITL-1367 and ITL-1370: "I agree + that this is indeed the simplest and ultimately the most consistent"): a stored table's + column order is the database's, never a writer's. A new table is written in the + canonical order, the record id then every other column by name (code point), by the one + shared step every database calls, `databases/utils.in_held_column_order` + (`canonical_column_order`); it is the order SpiralDB itself stores. A table that exists + keeps its order (one written before ITL-1370 keeps its first write's): an append is + matched to it by exact name, never by position, when its names, storage types and + logical types equal the held ones; anything else keeps the database's own rule. A + connector database trusts nothing about a stored table across calls: it aligns an append + only to its own pending batch and checks rows against the table read at flush and at a + read. No hash, record id, path or layout version follows a stored column order, and no + table is rewritten. Every reader of stored rows presents them in its own layout, + whatever order they are stored in, through one helper, `arrow_utils.in_presented_order` + (the reader's layout, then any other column by name): `CachedSource`, `DerivedSource`, + the function node's stored view (`_presented_layout`), the operator node's stored read + (`_in_row_order_on_read`), the result cache (`result_table_layout`), the status and log + observers and `ObservabilityReader`. A new reader of stored rows uses it too; never + present a stored table in its stored order. - Every layout marker starts at `v1` for the first release, 0.4.0 (developer, November 18, 2026, ITL-1259; 0.3.0 was withdrawn, so nothing released uses `v2`). A change to the common bookkeeping columns of a table kind moves its layout version, so the table gets a new path. @@ -1260,10 +1279,11 @@ data. The rules: order, user tags, system tags, data, source info, stated once in `StaticOutputOperatorPod._in_row_order`; a node that keeps a run with no rows keeps `_zero_rows_in_row_order`, and an operator's own empty result built from its input - goes through `_as_row_built_table`. An operator node keeps and stores the row order on every - path (`_kept_output`: a job run, sync or async, and `node.run()` on its own; ITL-1133), - and reads a stored operator cache in row order (`_in_row_order_on_read`). Never change - the order of any other populated table: stored tables depend on it. + goes through `_as_row_built_table`. An operator node keeps the row order on every path + (`_kept_output`: a job run, sync or async, and `node.run()` on its own; ITL-1133); what it + stores is in its database's order and is presented in row order on read + (`_in_row_order_on_read`; "Stored column order"). Never change the order of any other + populated table a user sees: presentation follows it (no hash and no stored table does). - **Data-tags come first among the data columns** (developer, November 17, 2026, ITL-1205): a stream lists its data-tags first in its data keys and data schema, in tag order, then its other data columns in table order. A table built from rows lays a data-tag out among diff --git a/changelog.d/ITL-1370.md b/changelog.d/ITL-1370.md new file mode 100644 index 000000000..f20fc8103 --- /dev/null +++ b/changelog.d/ITL-1370.md @@ -0,0 +1,26 @@ +### Changed + +- **A new stored table is written in one canonical column order** — every table Orcapod + creates in a database (a function node's pipeline and result tables, a side-effect log, + an operator cache, a cached source, an observer's status and log tables), in every + database, now has the record id column first and every other column sorted by name (by + code point: upper case, then `_`, then lower case). It used to keep the order of its first + write, which depended on how that write happened to be built. The canonical order is the + one SpiralDB already stores every table in, so all five databases now store, and read + back, the same order. What you see: + - Reading a database directly (`database.get_all_records(path)`, a Delta table opened with + Polars or `deltalake`, a SQL `SELECT *`) shows a new table's columns in the canonical + order. + - A table stored before this change keeps its order and takes new rows in any order; a + store may hold both kinds side by side. + - What Orcapod shows of stored rows no longer follows the stored order at all: a job + node's `get_all_records()`, its stored view after a load, `as_source()`, a + `CachedSource`, `get_all_cached_outputs()`, `StatusObserver.get_status()`, + `LoggingObserver.get_logs()` and `ObservabilityReader` each present the columns in their + own layout (for a node: tags, system tags, data, source info), then any other column by + name. Two changes are visible: in a function node's `get_all_records(all_info=True)` the + bookkeeping columns (`__…`) and the input's source-info columns now follow the outputs, + by name; in an observer's tables the tag columns follow the observer's own columns by + name. + - No hash, record id, stored path or layout version changes, and nothing stored is + rewritten. (ITL-1370) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index 841911a0a..bf6549abb 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -42,6 +42,6 @@ value columns by name. Tests: `tests/test_databases/test_append_by_name.py`; liv `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: +another type here, and the fake keeps struct children as written): ITL-1368. A new table +is written in a canonical order since ITL-1370 (CO2), decided from `docs/dev/specs/itl-1367-stored-column-order.md`. diff --git a/docs/dev/design_issues/ITL-1370-CO2.md b/docs/dev/design_issues/ITL-1370-CO2.md new file mode 100644 index 000000000..45a5c9037 --- /dev/null +++ b/docs/dev/design_issues/ITL-1370-CO2.md @@ -0,0 +1,28 @@ +## `src/orcapod/databases/` — column order of appended tables + +### CO2 — A stored table's column order followed whichever write created it +**Status:** resolved +**Severity:** low +**Issue:** ITL-1370 + +Each stored table kept the column order of its first write, and each writer built its rows +its own way: the five table kinds disagreed (a cached source put data before its system +tags, an operator cache after them), the user columns followed the declared tag order, +which the rule that order never counts allows only as presentation, and SpiralDB stored +none of these orders (it keeps the key columns, then the value columns by name). Readers +presented a stored table in its stored order, so what a user saw depended on how the +table's first write happened to be built. + +**Fix:** a new table is written in the canonical order: the record id, then every other +column by name (code point), by the shared step every database calls +(`databases/utils.canonical_column_order`, from `in_held_column_order` when nothing is +held). It is SpiralDB's own order. A table that exists keeps its order and takes appends +by name (CO1, ITL-1367). Every reader of stored rows presents them in its own layout through +one helper, `arrow_utils.in_presented_order`: `CachedSource`, `DerivedSource`, the function +node's stored view (`_presented_layout`), the operator node's stored read, the result cache +(`result_table_layout`), the status and log observers and `ObservabilityReader`. No hash, +record id, stored path or layout version moves (golden check; and +`tests/test_databases/test_canonical_stored_order.py` runs one job writing every table +kind with the canonical order switched off and on and compares content and pipeline +hashes, paths, record ids and every reader). Decision and evidence: +`docs/dev/specs/itl-1367-stored-column-order.md`. diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md index 8bd4ad635..f1dd7806d 100644 --- a/docs/dev/specs/itl-1367-stored-column-order.md +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -1,9 +1,14 @@ # 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. +Status: **approved and implemented.** The developer approved the proposal on 2026-11-22: +"I agree that this is indeed the simplest and ultimately the most consistent", all three +decisions as recommended below (the canonical order in the database's shared step, readers +presenting their own layout through one helper, no layout version change). Step 1 +(ITL-1367) is implemented: an append whose columns are the held table's columns in another +order is put in the held order by every database. Step 2 is implemented by ITL-1370 +(`canonical_column_order`, `arrow_utils.in_presented_order`); the readers' layouts are +listed in `CLAUDE.md`, "Stored column order". Where this document says "proposal" below, +read "decision". 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 diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index f0dde1d5a..6a2e7eb19 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -89,10 +89,15 @@ they are queued and before the checks that compare them with the held columns (f 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 +are read with it or written. A new table is written in the canonical column order, in +every database: the record id, then every other column sorted by name (by code point, +so upper case before `_` before lower case). It is the order SpiralDB stores and reads +every table in, whatever the order written (measured on SpiralDB itself), so the order +written and the order read are the same in every database. A table written before +Orcapod used the canonical order keeps the order of its first write and takes appends in +any order. No hash, record id or stored path depends on a stored table's column order, +and what Orcapod shows of stored rows (a node, a cached or derived source, an observer) +is in the reader's own column order, whatever order they are stored in. 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. diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 6de01f8c7..f1f2d37ec 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -210,7 +210,8 @@ def canonical_column_order(records: "pa.Table", record_id_column: str) -> "pa.Ta (Python's ``sorted`` on ``str``): the order SpiralDB stores every table in, so all five databases store and read one order. Nothing else depends on it: no hash, path or record id reads a stored table's column order, and every reader presents its - rows in row order whatever the stored order (``utils.arrow_utils.in_presented_order``). + rows in its own layout whatever the stored order + (``utils.arrow_utils.in_presented_order``). Names that repeat are returned as given, for the database's own rule. Args: diff --git a/tests/test_databases/test_canonical_stored_order.py b/tests/test_databases/test_canonical_stored_order.py index 7ac36b3e9..d8bdd3cea 100644 --- a/tests/test_databases/test_canonical_stored_order.py +++ b/tests/test_databases/test_canonical_stored_order.py @@ -115,9 +115,10 @@ def _table(table: pa.Table | None) -> tuple[list[str], list[str]] | None: # Function result rows are named by a fresh uuid7 each run (``__data_id``, the result -# table's record id, and the source-info tokens of the outputs, which name it): not -# hashes, different in any two runs, so compared by column only. -_RUN_SCOPED = ("fn.as_table", "fn.get_all_records", "fn.as_source") +# table's record id, and the source-info tokens of the outputs, which name it) and +# carry the time they were computed (``__pod_ts``): not hashes, different in any two +# runs, so compared by column only. +_RUN_SCOPED = ("fn.as_table", "fn.get_all_records", "fn.as_source", "cached outputs") def _observe(database: Any) -> dict[str, Any]: @@ -300,3 +301,79 @@ def test_the_before_context_is_the_identity(tmp_path: Path) -> None: database.add_records(("t",), table, flush=True, record_id_column=RECORD_ID) stored = database.get_all_records(("t",), record_id_column=RECORD_ID) assert stored is not None and stored.column_names == ["b", RECORD_ID, "a"] + + +def _loaded_presentation(database: Any, root: Path) -> dict[str, Any]: + """What a loaded job's nodes present of their stored rows (no source bound).""" + with _job(database, [1, 2]) as (job, _): + job.save(str(root / "job.json")) + loaded = PipelineJob.load(str(root / "job.json"), database=database) + seen: dict[str, Any] = {} + fn = loaded.nodes["fn"].get_all_records() + assert fn is not None + seen["fn"] = fn.column_names + for label in ("fn", "joined"): + seen[f"{label} source"] = _table(loaded.nodes[label].as_source().as_table()) + return seen + + +@pytest.mark.filterwarnings("ignore") +def test_a_loaded_job_presents_both_stores_identically( + database_kind: str, tmp_path: Path +) -> None: + """A loaded node knows its columns from the saved job, not from a live input: + its stored rows present the same whatever order they are stored in.""" + (tmp_path / "before").mkdir() + (tmp_path / "today").mkdir() + with _before_itl_1370(): + before = _loaded_presentation( + _database(database_kind, tmp_path / "before" / "db"), tmp_path / "before" + ) + today = _loaded_presentation( + _database(database_kind, tmp_path / "today" / "db"), tmp_path / "today" + ) + assert ( + before["fn"] + == today["fn"] + == ["z_tag", "a_tag", "w_out", "c_out", "_context_key"] + ) + assert before["fn source"][0] == today["fn source"][0] + assert before["joined source"] == today["joined source"] + assert today["joined source"][0] == ["z_tag", "a_tag", "y", "b", "x", "e"] + + +def _observer_columns(database: Any) -> tuple[list[str], list[str]]: + from orcapod.pipeline.composite_observer import CompositeObserver + from orcapod.pipeline.logging_observer import LoggingObserver + from orcapod.pipeline.status_observer import StatusObserver + + job = PipelineJob(name="observed", database=InMemoryArrowDatabase()) + with job: + compute.pod(_source("left", ["y", "b"], [1, 2]), label="fn") + logs = LoggingObserver(log_database=database.at("observed", "_log")) + status = StatusObserver(status_database=database.at("observed", "_status")) + job.run(observer=CompositeObserver(logs, status)) + log_table, status_table = logs.get_logs(), status.get_status() + assert log_table is not None and status_table is not None + return log_table.column_names, status_table.column_names + + +def test_the_observers_present_both_stores_identically( + database_kind: str, tmp_path: Path +) -> None: + """The status and log tables an observer stores present in the observer's own + order (its fixed columns, then the rest by name), however they are stored.""" + with _before_itl_1370(): + before = _observer_columns(_database(database_kind, tmp_path / "before")) + today = _observer_columns(_database(database_kind, tmp_path / "today")) + assert before == today + logs, status = today + assert logs[:3] == ["_log_id", "_log_run_id", "_log_timestamp"] + assert status[:6] == [ + "_status_id", + "_status_run_id", + "_status_pipeline_uri", + "_status_state", + "_status_timestamp", + "_status_error_summary", + ] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 19683b083..22415506a 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1064,10 +1064,15 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: 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 +are read with it or written. A new table is written in the canonical column order, in +every database: the record id, then every other column sorted by name (by code point, +so upper case before `_` before lower case). It is the order SpiralDB stores and reads +every table in, whatever the order written (measured on SpiralDB itself), so the order +written and the order read are the same in every database. A table written before +Orcapod used the canonical order keeps the order of its first write and takes appends in +any order. No hash, record id or stored path depends on a stored table's column order, +and what Orcapod shows of stored rows (a node, a cached or derived source, an observer) +is in the reader's own column order, whatever order they are stored in. 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 50dc02e1faf288717dd13af3fb23cdda114866ef Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:36:37 -0800 Subject: [PATCH 07/22] 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 b8bf9dcd0ccc20cd5e4f51a76393b6ad6ae1f008 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:38:43 -0800 Subject: [PATCH 08/22] wip(ITL-1370): stored data-tags compared as sets; doc pages show the canonical stored order --- docs/concepts/data-tags.md | 4 ++-- docs/reference/data-function-types.md | 9 ++++++--- docs/tutorial/08-inspecting-and-tracing.md | 2 +- tests/test_core/data_tags/test_tag_by.py | 9 ++++++--- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index ec36be45d..44ead4e2a 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -372,8 +372,8 @@ pipeline_table = next( for path in database.list_table_paths() if "_result" not in path ) -print(stored_data_tags(pipeline_table.schema)) -# ('unit', 'time') +print(sorted(stored_data_tags(pipeline_table.schema))) +# ['time', 'unit'] ``` A node reads the binding back from its table, and refuses a table whose marker disagrees diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 8880c5432..d1095c6b8 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -135,14 +135,17 @@ Every result table has, besides its type's record: | `__pod_ts` | `timestamp[us, tz=UTC]` | yes | when the result was stored; the newest wins when two rows share an input | | `__data_context` | `large_string` | no | the data context that wrote the row (`std:v1:default`) | -The database keeps the row's record id, a UUID of 16 bytes, as its record id column. +The database keeps the row's record id, a UUID of 16 bytes, as its record id column. Like +every table Orcapod creates, the table is stored with its record id first and every other +column sorted by name (see [Data types per database](database-types.md)); the declared +order above is the order the function node presents them in. ```python stored = types_store.get_all_records(next(p for p in types_store.list_sources() if "_result" in p)) print([name for name in stored.column_names if not name.startswith("__pf_")]) -# ['__input_data_hash', 'total', 'label', '_source_total', '_source_label', '__pod_ts', '__data_context'] +# ['__data_context', '__input_data_hash', '__pod_ts', '_source_label', '_source_total', 'label', 'total'] print([name for name in stored.column_names if name.startswith("__pf_var_")]) -# ['__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash'] +# ['__pf_var_function_content_hash', '__pf_var_function_module', '__pf_var_function_name', '__pf_var_function_signature_hash', '__pf_var_function_version', '__pf_var_git_hash'] ``` ## Where it is declared, and how a released declaration is kept diff --git a/docs/tutorial/08-inspecting-and-tracing.md b/docs/tutorial/08-inspecting-and-tracing.md index e657f119e..3b42525e5 100644 --- a/docs/tutorial/08-inspecting-and-tracing.md +++ b/docs/tutorial/08-inspecting-and-tracing.md @@ -157,7 +157,7 @@ call. `get_all_records` returns them; ask for the `meta` columns to see the deta records = pl.from_arrow(job.nodes["rates"].get_all_records(columns={"meta": True})) meta = [c for c in records.columns if c.startswith("__")] print(meta) -# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts'] +# ['__computed', '__data_context', '__data_id', '__input_data_hash', '__input_data_hash_right', '__is_ephemeral', '__output_data_hash', '__pf_exec_executor_info', '__pf_exec_executor_type', '__pf_exec_extra_info', '__pf_exec_python_version', '__pf_var_function_content_hash', '__pf_var_function_module', '__pf_var_function_name', '__pf_var_function_signature_hash', '__pf_var_function_version', '__pf_var_git_hash', '__pod_ts'] ``` The ones you are most likely to want: diff --git a/tests/test_core/data_tags/test_tag_by.py b/tests/test_core/data_tags/test_tag_by.py index b549b8d11..673da09d7 100644 --- a/tests/test_core/data_tags/test_tag_by.py +++ b/tests/test_core/data_tags/test_tag_by.py @@ -422,12 +422,14 @@ def test_in_a_job_a_function_node_stores_the_new_tag_marked( (1, "s0", "s0s0"), (2, "s1", "s1s1"), ] + # A stored table's column order is the database's (ITL-1370): the marked + # data-tags are a set. marked = { - stored_data_tags(database.get_all_records(path).schema) # pyright: ignore[reportOptionalMemberAccess] # every listed table has records + frozenset(stored_data_tags(database.get_all_records(path).schema)) # pyright: ignore[reportOptionalMemberAccess] # every listed table has records for path in database.list_table_paths() if "_result" not in path } - assert ("unit", "session") in marked + assert frozenset({"unit", "session"}) in marked job.save(tmp_path / "job.json") loaded = PipelineJob.load(tmp_path / "job.json") @@ -459,4 +461,5 @@ def test_a_logged_tag_by_node_stores_its_new_tag_marked( assert len(paths) == 1 stored = database.get_all_records(paths[0]) assert stored is not None - assert stored_data_tags(stored.schema) == ("unit", "trial") + # A set: a stored table's column order is the database's (ITL-1370). + assert set(stored_data_tags(stored.schema)) == {"unit", "trial"} From c17236c83320ffa8a658388446a23f79866130ab Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 14:50:16 -0800 Subject: [PATCH 09/22] 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 10/22] 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 From a69b471d26b76f66d05ad3bee50c274a835fd367 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 15:29:10 -0800 Subject: [PATCH 11/22] wip(ITL-1370): Delta stats property in canonical order; commit-count measurement script --- docs/dev/scripts/itl_1370_delta_commits.py | 94 +++++++++++++++++++ .../test_delta_statistics_columns.py | 13 ++- 2 files changed, 102 insertions(+), 5 deletions(-) create mode 100644 docs/dev/scripts/itl_1370_delta_commits.py diff --git a/docs/dev/scripts/itl_1370_delta_commits.py b/docs/dev/scripts/itl_1370_delta_commits.py new file mode 100644 index 000000000..3fff5dd06 --- /dev/null +++ b/docs/dev/scripts/itl_1370_delta_commits.py @@ -0,0 +1,94 @@ +"""ITL-1370: the Delta commits of a job, by table kind: operation kinds and counts. + +One job writes every stored table kind (a function pipeline and result table, a +side-effect log, an operator cache, a cached source) on a new Delta store, three times: +the first run, a second run with new rows, and a run with ``commit_every_rows=2`` over +more rows. Each table's history is printed oldest first. Run it on main and on the +ITL-1370 branch: a job on new tables must commit the same kinds the same number of +times (condition (a) of the ITL-1370 review). + +Run: ``PYTHONPATH=src uv run python docs/dev/scripts/itl_1370_delta_commits.py`` +""" + +from __future__ import annotations + +import os +import sys +import tempfile +import warnings +from pathlib import Path +from typing import Any + +import deltalake +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 DeltaTableDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +warnings.simplefilter("ignore") + + +def _source(name: str, data: list[str], rows: list[int]) -> 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([f"s{n}" for n in rows], pa.large_string()), + pa.array(rows, pa.int64()), + *(pa.array([float(n) for n in rows]) for _ in data), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + record_id_columns=["a_tag"], + 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 _run(database: Any, rows: list[int], **run: Any) -> None: + job = PipelineJob(name="commits", database=database) + cached = CachedSource(_source("left", ["y", "b"], rows), cache_database=database) + with job: + compute.pod(cached, label="fn") + Join()(cached, _source("right", ["x", "e"], rows), label="joined") + SideEffectPod(_notify)(cached, label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run(**run) + + +def main() -> None: + root = Path(tempfile.mkdtemp()) + database = DeltaTableDatabase(root) + _run(database, [1, 2]) + _run(database, [1, 2, 3, 4]) + _run(database, list(range(1, 10)), commit_every_rows=2) + for log in sorted(root.rglob("_delta_log")): + table = log.parent + history = deltalake.DeltaTable(str(table)).history() + operations = [str(entry["operation"]) for entry in reversed(history)] + print(table.name, operations) + + +if __name__ == "__main__": + main() + sys.stdout.flush() + os._exit(0) diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index 87d368bd3..7e1c91ee2 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -198,7 +198,10 @@ def test_no_column_qualifies(self) -> None: class TestNewTableWritePaths: - """Every write path on a new table logs no statistics warning.""" + """Every write path on a new table logs no statistics warning. + + The property lists the columns in the table's column order, the canonical order + of a new table (ITL-1370): ``__data_context`` before ``v``.""" def test_create_append_merge_and_schema_evolution( self, tmp_path: Path, capfd: pytest.CaptureFixture[str] @@ -209,7 +212,7 @@ def test_create_append_merge_and_schema_evolution( db.add_records(PATH, rows(range(0, 10)), flush=True) assert stats_warnings(capfd) == [], "create" assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" + STATS_COLUMNS_PROPERTY: "`__data_context`,`v`" } db.add_records(PATH, rows(range(10, 20)), flush=True) @@ -228,7 +231,7 @@ def test_create_append_merge_and_schema_evolution( # The property is never changed: a column added later has no statistics. assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" + STATS_COLUMNS_PROPERTY: "`__data_context`,`v`" } assert all( stats == {"v", "__data_context"} @@ -390,7 +393,7 @@ def table(ids: range) -> pa.Table: db.add_records(PATH, table(range(3, 6)), flush=True) assert stats_warnings(capfd) == [] assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" + STATS_COLUMNS_PROPERTY: "`__data_context`,`v`" } assert len(stored_ids(db)) == 6 @@ -485,5 +488,5 @@ def test_plain_deltalake_appends_to_a_table_with_the_property( f"id{i}".encode() for i in range(20) ) assert configuration(tmp_path / "t") == { - STATS_COLUMNS_PROPERTY: "`v`,`__data_context`" + STATS_COLUMNS_PROPERTY: "`__data_context`,`v`" } From fb9ddf0c416fe7466368fb92f5eae564a8099bf0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 15:30:02 -0800 Subject: [PATCH 12/22] docs(ITL-1370): Delta queues canonical with nothing pending; the merge cost stated --- .zed/rules | 8 +++++--- CLAUDE.md | 8 +++++--- changelog.d/ITL-1370.md | 8 ++++++++ 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.zed/rules b/.zed/rules index 1bfd1e23d..9463589f8 100644 --- a/.zed/rules +++ b/.zed/rules @@ -989,9 +989,11 @@ generation of hashing; rows of the current data context are the current entries. keeps its order (one written before ITL-1370 keeps its first write's): an append is matched to it by exact name, never by position, when its names, storage types and logical types equal the held ones; anything else keeps the database's own rule. A - connector database trusts nothing about a stored table across calls: it aligns an append - only to its own pending batch and checks rows against the table read at flush and at a - read. No hash, record id, path or layout version follows a stored column order, and no + database with nothing pending for a table queues an append in the canonical order + (Delta then matches merge and coerce to the queued rows by name; a Delta table not in + canonical order commits by merge). A connector database trusts nothing about a stored + table across calls: it aligns an append only to its own pending batch and checks rows + against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no table is rewritten. Every reader of stored rows presents them in its own layout, whatever order they are stored in, through one helper, arrow_utils.in_presented_order (the reader's layout, then any other column by name): CachedSource, DerivedSource, diff --git a/CLAUDE.md b/CLAUDE.md index f7887f26b..2886c9abe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1018,9 +1018,11 @@ current data context are the current entries. keeps its order (one written before ITL-1370 keeps its first write's): an append is matched to it by exact name, never by position, when its names, storage types and logical types equal the held ones; anything else keeps the database's own rule. A - connector database trusts nothing about a stored table across calls: it aligns an append - only to its own pending batch and checks rows against the table read at flush and at a - read. No hash, record id, path or layout version follows a stored column order, and no + database with nothing pending for a table queues an append in the canonical order + (Delta then matches merge and coerce to the queued rows by name; a Delta table not in + canonical order commits by merge). A connector database trusts nothing about a stored + table across calls: it aligns an append only to its own pending batch and checks rows + against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no table is rewritten. Every reader of stored rows presents them in its own layout, whatever order they are stored in, through one helper, `arrow_utils.in_presented_order` (the reader's layout, then any other column by name): `CachedSource`, `DerivedSource`, diff --git a/changelog.d/ITL-1370.md b/changelog.d/ITL-1370.md index f20fc8103..3086123cb 100644 --- a/changelog.d/ITL-1370.md +++ b/changelog.d/ITL-1370.md @@ -22,5 +22,13 @@ bookkeeping columns (`__…`) and the input's source-info columns now follow the outputs, by name; in an observer's tables the tag columns follow the observer's own columns by name. + - Delta merges or coerces a batch to the rows still queued by column name (it matched by + position before, so a batch in another column order was refused). + - The one cost: a Delta table not in the canonical order (stored before this change, + or created by another writer in another order) now receives every batch in the + canonical order, so each commit is a merge instead of an append. A merge fails under + a concurrent write where an append succeeded; no row is ever wrong: the flush raises + and a retry writes it. A table Orcapod creates now is canonical and commits by append + exactly as before. - No hash, record id, stored path or layout version changes, and nothing stored is rewritten. (ITL-1370) From f4011e22f0f890aee758aebcf44182e89f29ab02 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 15:48:38 -0800 Subject: [PATCH 13/22] test(ITL-1370): typed read of a tag column --- tests/test_databases/test_canonical_stored_order.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_databases/test_canonical_stored_order.py b/tests/test_databases/test_canonical_stored_order.py index d8bdd3cea..ed939ec36 100644 --- a/tests/test_databases/test_canonical_stored_order.py +++ b/tests/test_databases/test_canonical_stored_order.py @@ -20,7 +20,7 @@ from collections.abc import Iterator from contextlib import AbstractContextManager, contextmanager from pathlib import Path -from typing import Any +from typing import Any, cast from unittest.mock import patch import pyarrow as pa @@ -268,7 +268,8 @@ def test_a_store_written_before_takes_new_rows_and_new_tables( for path in database.list_table_paths() } with _job(database, [1, 2, 3], extra_node=True) as (job, cached): - assert sorted(cached.as_table().column("a_tag").to_pylist()) == [1, 2, 3] + tags = cast(list[int], cached.as_table().column("a_tag").to_pylist()) + assert sorted(tags) == [1, 2, 3] for label in ("fn", "joined", "fn2"): records = job.nodes[label].get_all_records() assert records is not None From f47067d8c5bc56721063079f4038634b4271dae8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:06:23 -0800 Subject: [PATCH 14/22] test(ITL-1370): result-table and PostgreSQL tests expect the canonical stored order --- tests/test_data_function_types.py | 8 +++++--- tests/test_databases/test_append_by_name.py | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/test_data_function_types.py b/tests/test_data_function_types.py index d6cb3908e..8fe8a7477 100644 --- a/tests/test_data_function_types.py +++ b/tests/test_data_function_types.py @@ -92,7 +92,9 @@ def _expected_result_columns( """Every column of the result table, in stored order: (name, Arrow type, nullable). The record id, the common columns and the type's declared columns come from - their declarations; the outputs from the function's output schema. + their declarations; the outputs from the function's output schema. A new table is + stored in the canonical order (ITL-1370): the record id, then every other column + by name. """ common = {column.name: column for column in COMMON_RESULT_COLUMNS} declaration = data_function.declaration @@ -105,8 +107,7 @@ def entry(name: str, column: Any) -> tuple[str, str, bool]: data_function.output_data_schema ) ) - return [ - (RECORD_ID, "large_binary", True), + columns = [ entry(constants.INPUT_DATA_HASH_COL, common[constants.INPUT_DATA_HASH_COL]), *( entry(f"{constants.PF_VARIATION_PREFIX}{c.name}", c) @@ -124,6 +125,7 @@ def entry(name: str, column: Any) -> tuple[str, str, bool]: entry(constants.POD_TIMESTAMP, common[constants.POD_TIMESTAMP]), entry(constants.DATA_CONTEXT_COL, common[constants.DATA_CONTEXT_COL]), ] + return [(RECORD_ID, "large_binary", True), *sorted(columns)] def _stored_columns( diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 4f55a223e..dfbf20d6f 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -1143,6 +1143,7 @@ def test_postgresql_matches_an_append_in_another_order_by_name( 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]) + expected = _given_order("PostgreSQL", first_order) # canonical (ITL-1370) + _check(db.get_all_records(PATH, record_id_column=ID), expected, [1, 2, 3, 4]) db.flush() - _check(db.get_all_records(PATH, record_id_column=ID), first_order, [1, 2, 3, 4]) + _check(db.get_all_records(PATH, record_id_column=ID), expected, [1, 2, 3, 4]) From b885a6cc1069dbf2730df182ce75ce38f0d504c2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:53:47 -0800 Subject: [PATCH 15/22] fix(ITL-1370): keep main's Delta commit for non-canonical tables, cache-hit and cached-source order, observer tag union, unchanged writers with ineligible types Codex review of PR 496: - Delta puts a first batch in the canonical order only for a new or canonical table (the table its append checks already load); a table stored in another order (before ITL-1370, or by another writer) gets the rows as given, so append or MERGE is chosen exactly as on main (a main-created table with a __delta_rs_source column appends again) - a table with a type the append comparison does not handle keeps its first write's order, so an unchanged writer always matches itself - a cache hit presents its outputs through the result table's layout - CachedSource.get_all_records presents the source's layout - the observers order tags by name after the union of node tables - a competing record id on a canonical Delta table is a strict xfail naming ITL-1377 (developer decision) Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 9 +- CLAUDE.md | 9 +- changelog.d/ITL-1370.md | 12 +- docs/reference/database-types.md | 4 +- src/orcapod/core/result_cache.py | 7 +- src/orcapod/core/sources/cached_source.py | 7 +- src/orcapod/databases/delta_lake_databases.py | 66 ++++- src/orcapod/databases/utils.py | 10 +- src/orcapod/pipeline/logging_observer.py | 6 +- src/orcapod/pipeline/status_observer.py | 6 +- tests/test_databases/test_append_by_name.py | 19 +- .../test_canonical_order_review_496.py | 237 ++++++++++++++++++ .../test_canonical_stored_order.py | 1 + tests/test_databases/type_matrix.py | 4 +- 14 files changed, 358 insertions(+), 39 deletions(-) create mode 100644 tests/test_databases/test_canonical_order_review_496.py diff --git a/.zed/rules b/.zed/rules index 9463589f8..5b8698e8a 100644 --- a/.zed/rules +++ b/.zed/rules @@ -989,9 +989,12 @@ generation of hashing; rows of the current data context are the current entries. keeps its order (one written before ITL-1370 keeps its first write's): an append is matched to it by exact name, never by position, when its names, storage types and logical types equal the held ones; anything else keeps the database's own rule. A - database with nothing pending for a table queues an append in the canonical order - (Delta then matches merge and coerce to the queued rows by name; a Delta table not in - canonical order commits by merge). A connector database trusts nothing about a stored + database with nothing pending for a table queues an append in the canonical order; + Delta queues it as given and puts it in the canonical order at the commit only for a + new or canonical table, so a non-canonical Delta table (pre-1370 or foreign) commits + exactly as main (and Delta matches merge and coerce to the queued rows by name). A + table holding a type the append comparison does not handle keeps its first write's + order (`canonical_column_order`). A connector database trusts nothing about a stored table across calls: it aligns an append only to its own pending batch and checks rows against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no table is rewritten. Every reader of stored rows presents them in its own layout, diff --git a/CLAUDE.md b/CLAUDE.md index 2886c9abe..1406ab71e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1018,9 +1018,12 @@ current data context are the current entries. keeps its order (one written before ITL-1370 keeps its first write's): an append is matched to it by exact name, never by position, when its names, storage types and logical types equal the held ones; anything else keeps the database's own rule. A - database with nothing pending for a table queues an append in the canonical order - (Delta then matches merge and coerce to the queued rows by name; a Delta table not in - canonical order commits by merge). A connector database trusts nothing about a stored + database with nothing pending for a table queues an append in the canonical order; + Delta queues it as given and puts it in the canonical order at the commit only for a + new or canonical table, so a non-canonical Delta table (pre-1370 or foreign) commits + exactly as main (and Delta matches merge and coerce to the queued rows by name). A + table holding a type the append comparison does not handle keeps its first write's + order (`canonical_column_order`). A connector database trusts nothing about a stored table across calls: it aligns an append only to its own pending batch and checks rows against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no table is rewritten. Every reader of stored rows presents them in its own layout, diff --git a/changelog.d/ITL-1370.md b/changelog.d/ITL-1370.md index 3086123cb..49828389a 100644 --- a/changelog.d/ITL-1370.md +++ b/changelog.d/ITL-1370.md @@ -24,11 +24,11 @@ name. - Delta merges or coerces a batch to the rows still queued by column name (it matched by position before, so a batch in another column order was refused). - - The one cost: a Delta table not in the canonical order (stored before this change, - or created by another writer in another order) now receives every batch in the - canonical order, so each commit is a merge instead of an append. A merge fails under - a concurrent write where an append succeeded; no row is ever wrong: the flush raises - and a retry writes it. A table Orcapod creates now is canonical and commits by append - exactly as before. + - Delta commits as before: a table Orcapod creates now (canonical) takes each batch by + append, as an ordinary writer's table did; a table stored before this change, or + created by another writer in another order, gets every batch as given, so append or + merge is chosen exactly as before. + - A table whose rows hold a type the append comparison does not handle (a dictionary, + a view type, ...) keeps the column order of its first write. - No hash, record id, stored path or layout version changes, and nothing stored is rewritten. (ITL-1370) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 2ff48146f..c5cc973da 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -98,7 +98,9 @@ stores and reads every table in, whatever the order written (measured on SpiralD itself), so the order written and the order read are the same in every database; rows queued with nothing pending for their table are put in that order. A table written before Orcapod used the canonical order keeps the order of its first write and takes -appends in any order (Delta commits such a table's batches by merge). No hash, record id +appends in any order (Delta commits to it as before). A table holding a type the append +comparison does not handle (a dictionary, a view type) keeps its first write's order. No +hash, record id or stored path depends on a stored table's column order, and what Orcapod shows of stored rows (a node, a cached or derived source, an observer) is in the reader's own column order, whatever order they are stored in. An append that also diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 6b676b313..b314c60b9 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -339,7 +339,12 @@ def lookup( drop_cols = [RECORD_ID_COL] + [ c for c in constraints if c in result_table.column_names ] - result_table = result_table.drop_columns(drop_cols) + # In the result table's layout, whatever order the table is stored in, as + # every reader of stored rows (ITL-1370): a hit gives the outputs, their + # source info and the bookkeeping in the order the first call gave them. + result_table = arrow_utils.in_presented_order( + result_table.drop_columns(drop_cols), self._layout + ) return Data( result_table, diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 5d39a874c..c544c1e97 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -461,7 +461,12 @@ def _read_cached_records(self) -> "pa.Table | None": records = self._read_cached_records_with_hashes() if records is None: return None - return records.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]) + # In the wrapped source's layout, as ``as_table()`` presents them, whatever + # order the cache table is stored in (ITL-1370). + return arrow_utils.in_presented_order( + records.drop([self.HASH_COLUMN_NAME, constants.DATA_CONTEXT_COL]), + self._empty_table().column_names, + ) def _read_cached_records_with_hashes(self) -> "pa.Table | None": """Read the cached rows written under the current data context, as stored. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 790505ad0..b5120752f 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -4,7 +4,7 @@ import os import sys from collections import defaultdict -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast @@ -16,6 +16,7 @@ matching_rows, rows_at, ) +from orcapod.databases import utils as database_utils from orcapod.databases.utils import ( appended_field_change, coerce_record_id, @@ -589,6 +590,15 @@ def _column_change(held: "pa.Field[Any]", field: "pa.Field[Any]") -> str | None: ) +def _is_canonical(names: Sequence[str], record_id_column: str) -> bool: + """Whether a stored table's columns are in the canonical order (ITL-1370).""" + names = list(names) + return names == [ + record_id_column, + *sorted(n for n in names if n != record_id_column), + ] + + def _by_name(table: pa.Table, schema: pa.Schema) -> pa.Table: """``table`` with its columns in ``schema``'s order, matched by name, when it has exactly ``schema``'s names (a cast matches columns by position); otherwise as @@ -1784,6 +1794,18 @@ def _refuse_changed_attributes( "nothing was written." ) + def _takes_canonical_order(self, record_path: tuple[str, ...]) -> bool: + """Whether rows for this table are written in the canonical order (ITL-1370): + no table is stored, or it is stored in the canonical order. A table that + cannot be loaded is left to the flush to report; its rows keep their order.""" + try: + delta_table = self._get_delta_table(record_path) + except OrcapodDatabaseReadError: + return False + return delta_table is None or _is_canonical( + delta_table.schema().to_arrow().names, self.RECORD_ID_COLUMN + ) + def _refuse_untyped_null_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1905,16 +1927,21 @@ def add_records( # 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). With nothing pending, the batch is put in the canonical order - # (ITL-1370), the order a new table is written in, so a canonical stored - # table takes it by append as main takes an aligned batch. No stored table - # is looked up: delta-rs takes an append by name. + # (ITL-1367). The first batch of a pending batch is queued in the order it + # will be committed in (ITL-1370): the canonical order for a new table or a + # table stored in it; as given for a table stored in another order (written + # before ITL-1370, or by another writer), so its commit is chosen exactly as + # main chooses it. The stored table is the one the append checks below load + # anyway (``_refuse_changed_attributes``): no extra lookup. pending = self._pending_batches.get(self._get_record_key(record_path)) - filtered_table = in_held_column_order( - filtered_table, - None if pending is None else list(pending.schema), - self.RECORD_ID_COLUMN, - ) + if pending is not None: + filtered_table = in_held_column_order( + filtered_table, list(pending.schema), self.RECORD_ID_COLUMN + ) + elif self._takes_canonical_order(record_path): + filtered_table = database_utils.canonical_column_order( + filtered_table, self.RECORD_ID_COLUMN + ) # 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 @@ -2626,9 +2653,6 @@ def _flush_by_key(self, record_key: str) -> None: original_table = arrow_utils.normalize_table_view_types( pending_batch.combine_chunks() ) - # A column whose type Delta would not give back is written in its - # integer form with its type recorded (ITL-928). - combined_table = to_delta_layout(original_table) # Ensure parent directory exists (local only) if not self._is_cloud: @@ -2652,6 +2676,22 @@ def _flush_by_key(self, record_key: str) -> None: table_uri, abs_path_components ) from load_error + # The canonical order (ITL-1370), for a new table and for a table stored + # in it: a canonical table then takes the batch by append as main takes + # an aligned batch. A table stored in another order (written before + # ITL-1370, or by another writer) gets the rows as given, so the commit + # is chosen exactly as main chooses it (given order against stored + # order: append when they agree, MERGE otherwise). + if delta_table is None or _is_canonical( + delta_table.schema().to_arrow().names, self.RECORD_ID_COLUMN + ): + original_table = database_utils.canonical_column_order( + original_table, self.RECORD_ID_COLUMN + ) + # A column whose type Delta would not give back is written in its + # integer form with its type recorded (ITL-928). + combined_table = to_delta_layout(original_table) + # Set when the rows were appended through ``delta_table``, which the # writer then moves to the version it committed (ITL-1173). appended = False diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index d54c11956..9f076cf33 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -212,7 +212,9 @@ def canonical_column_order(records: "pa.Table", record_id_column: str) -> "pa.Ta or record id reads a stored table's column order, and every reader presents its rows in its own layout whatever the stored order (``utils.arrow_utils.in_presented_order``). Names that repeat, or rows without the - record id column, are returned as given, for the database's own rule. + record id column, or a column of a type the append comparison does not handle (a + dictionary, a view type, a union, ...: ``_handled``), are returned as given, for the + database's own rule: such a table keeps the order of its first write. Args: records: The rows that create the table. @@ -224,6 +226,12 @@ def canonical_column_order(records: "pa.Table", record_id_column: str) -> "pa.Ta names = records.column_names if len(set(names)) != len(names) or record_id_column not in names: return records + # A column whose type the append comparison does not handle (``_handled``) + # could not be matched by name later: the rows keep their order, so a writer + # that never changes its order always matches its own first write (codex review + # of PR 496). + if not all(_handled(field.type) for field in records.schema): + return records order = [record_id_column, *sorted(n for n in names if n != record_id_column)] if order == names: return records diff --git a/src/orcapod/pipeline/logging_observer.py b/src/orcapod/pipeline/logging_observer.py index 5e9c55018..48ba0183c 100644 --- a/src/orcapod/pipeline/logging_observer.py +++ b/src/orcapod/pipeline/logging_observer.py @@ -271,7 +271,11 @@ def get_logs(self) -> "pa.Table | None": return None if len(parts) == 1: return parts[0] - return pa.concat_tables(parts, promote_options="default") + # Ordered after the union: node tables carry different tags, and the + # concatenation lists them in the order the parts first name them (ITL-1370). + return arrow_utils.in_presented_order( + pa.concat_tables(parts, promote_options="default"), LOG_COLUMNS + ) # -- serialization -- diff --git a/src/orcapod/pipeline/status_observer.py b/src/orcapod/pipeline/status_observer.py index 4967d62be..97eeb4c7c 100644 --- a/src/orcapod/pipeline/status_observer.py +++ b/src/orcapod/pipeline/status_observer.py @@ -231,7 +231,11 @@ def get_status(self) -> "pa.Table | None": return None if len(parts) == 1: return parts[0] - return pa.concat_tables(parts, promote_options="default") + # Ordered after the union: node tables carry different tags, and the + # concatenation lists them in the order the parts first name them (ITL-1370). + return arrow_utils.in_presented_order( + pa.concat_tables(parts, promote_options="default"), STATUS_COLUMNS + ) # -- serialization -- diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index dfbf20d6f..dc3b36c73 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -142,7 +142,11 @@ def test_an_append_in_another_order_is_matched_by_name( ), [1, 2, 3, 4], ) - db.flush() + # Delta creates the table at the flush: as before ITL-1370 in that generation. + with ( + _first_write(generation) if when == "same pending batch" else nullcontext() + ): + db.flush() _check( db.get_all_records(PATH, record_id_column=ID), _given_order(database, first_order, generation), @@ -959,13 +963,14 @@ def interleave(*args: Any) -> Any: @pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) -def test_a_delta_table_stored_before_itl_1370_takes_batches_by_merge_with_right_rows( +def test_a_delta_table_stored_before_itl_1370_takes_mains_commits( tmp_path: Path, schema_handling: str ) -> None: - """The one cost of ITL-1370: a Delta table stored in a first-write order that is - not canonical receives batches queued in the canonical order, so each commit is a - MERGE (main's commit for rows in another order than the stored table) instead of - an append. Every row and record id is stored as on main.""" + """A Delta table stored in a first-write order that is not canonical (written + before ITL-1370, or by another writer) gets every batch as given, so each commit + is chosen exactly as main chooses it: an append for rows in the stored order, a + MERGE for rows in another order (codex review of PR 496). Every row and record + id is stored as on main.""" from deltalake import DeltaTable db = DeltaTableDatabase(tmp_path) @@ -978,7 +983,7 @@ def test_a_delta_table_stored_before_itl_1370_takes_batches_by_merge_with_right_ db.add_records(PATH, _abc(2, ("b", "rid", "a")), flush=True, **kwargs) db.add_records(PATH, _abc(3), flush=True, **kwargs) operations = [entry["operation"] for entry in DeltaTable(tmp_path / "t").history()] - assert operations == ["MERGE", "MERGE", "WRITE"] + assert operations == ["MERGE", "WRITE", "WRITE"] # newest first, as on main table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") assert table is not None assert table.column_names == ["b", "rid", "a"] diff --git a/tests/test_databases/test_canonical_order_review_496.py b/tests/test_databases/test_canonical_order_review_496.py new file mode 100644 index 000000000..59607f79b --- /dev/null +++ b/tests/test_databases/test_canonical_order_review_496.py @@ -0,0 +1,237 @@ +"""Cases from the independent review of PR 496 (ITL-1370), each against main's behaviour. + +Nothing a user can observe on main may differ except the canonical order of a new table +and the two presentation changes the developer approved. Each test pins one case the +review found; the reproducers are named in the PR. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pyarrow as pa +import pytest +from deltalake import DeltaTable, write_deltalake + +import orcapod.databases.utils as database_utils +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.datagrams import Data +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline.logging_observer import LoggingObserver +from orcapod.pipeline.status_observer import StatusObserver + +PATH = ("t",) + + +def _rows(n: int, order: tuple[str, ...], z_type: Any) -> pa.Table: + columns = { + "z": pa.array([str(n)], pa.large_string()).cast(z_type), + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([n], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize( + ("database", "z_type"), + [ + ("in-memory", pa.dictionary(pa.int32(), pa.string())), + ("in-memory", pa.string_view()), + ("Delta", pa.dictionary(pa.int32(), pa.string())), + ("Delta", pa.string_view()), + ], + ids=["in-memory dictionary", "in-memory view", "Delta dictionary", "Delta view"], +) +def test_a_writer_that_keeps_its_order_matches_itself( + tmp_path: Path, database: str, z_type: Any +) -> None: + """Two batches with the same column order and a type the append comparison does + not handle: both are written, as on main. Such rows are never sorted, so the + second batch meets the first as given (review finding 2).""" + db = ( + InMemoryArrowDatabase() + if database == "in-memory" + else DeltaTableDatabase(tmp_path) + ) + order = ("z", "rid", "a") + db.add_records(PATH, _rows(1, order, z_type), record_id_column="rid") + db.add_records(PATH, _rows(2, order, z_type), record_id_column="rid") + db.flush() + table = db.get_all_records(PATH, record_id_column="rid") + assert table is not None + assert sorted(table.column("a").to_pylist()) == [1, 2] # pyright: ignore[reportArgumentType] # int64 column + + +def test_a_delta_table_main_created_with_a_merge_reserved_name_still_appends( + tmp_path: Path, +) -> None: + """A Delta table created before ITL-1370 in a non-canonical order, with a column + named ``__delta_rs_source`` (which delta-rs's MERGE cannot handle): a batch in the + stored order is appended by WRITE, as main does (review finding 3).""" + + def rows(n: int) -> pa.Table: + return pa.table( + { + "z": [n], + "rid": pa.array([bytes([n])], pa.large_binary()), + "__delta_rs_source": [n + 10], + } + ) + + with patch.object( + database_utils, "canonical_column_order", lambda records, record_id: records + ): + DeltaTableDatabase(tmp_path).add_records( + PATH, rows(1), record_id_column="rid", flush=True + ) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, rows(2), record_id_column="rid", flush=True) + history = [entry["operation"] for entry in DeltaTable(tmp_path / "t").history()] + assert history == ["WRITE", "WRITE"] + table = db.get_all_records(PATH, record_id_column="rid") + assert table is not None + assert table.column_names == ["z", "rid", "__delta_rs_source"] + assert sorted(table.column("z").to_pylist()) == [1, 2] # pyright: ignore[reportArgumentType] # int64 column + + +def _outputs(x: int) -> tuple[int, int]: + return x + 1, x + 7 + + +def test_a_cache_hit_presents_the_outputs_as_the_first_call_does() -> None: + """A cached function declaring outputs ``z, a``: a hit gives the keys, values, + source info and table columns in the order the miss gave them, sync and async, + as main does (review finding 4).""" + fn = CachedDataFunction( + PythonDataFunction(_outputs, output_keys=["z", "a"]), # pyright: ignore[reportArgumentType] # a PythonDataFunction works at run time + result_database=InMemoryArrowDatabase(), + ) + + def view(data: Any) -> tuple[Any, ...]: + keys = tuple(data.keys()) + columns = data.as_table(columns={"source": True}).column_names + return keys, tuple(data[k] for k in keys), tuple(columns) + + for x in (1, 2): + item = Data({"x": x}) + miss, hit = fn.call(item), fn.call(item) + assert miss is not None and hit is not None + assert view(hit) == view(miss) + assert view(hit)[0] == ("z", "a") + + async def both() -> tuple[Any, Any]: + item = Data({"x": 3}) + return await fn.async_call(item), await fn.async_call(item) + + miss, hit = asyncio.run(both()) + assert miss is not None and hit is not None + assert view(hit) == view(miss) + + +@pytest.mark.parametrize("kind", ["logs", "status"]) +def test_an_observer_presents_the_tags_of_every_node_in_name_order(kind: str) -> None: + """Node tables with different tags: the combined table lists the observer's own + columns, then every tag by name, after the union (review finding 6).""" + db = InMemoryArrowDatabase() + name, id_column = ( + ("execution_logs", "_log_id") + if kind == "logs" + else ("execution_status", "_status_id") + ) + for node, tag in [("node1", "z"), ("node2", "a")]: + db.add_record( + (node, name), node.encode(), pa.table({id_column: [node], tag: [1]}) + ) + db.flush() + table = ( + LoggingObserver(log_database=db).get_logs() + if kind == "logs" + else StatusObserver(status_database=db).get_status() + ) + assert table is not None + assert table.column_names == [id_column, "a", "z"] + + +def test_an_external_empty_delta_table_presents_its_order_before_and_after_a_flush( + tmp_path: Path, +) -> None: + """An existing zero-row Delta table in the order ``z, rid, A``: rows queued in + that order read in that order before and after the flush, as on main (review + finding 7).""" + items = pa.table( + { + "z": [1, 2], + "rid": pa.array([b"\x01", b"\x02"], pa.large_binary()), + "A": [10, 20], + } + ) + write_deltalake( + str(tmp_path / "t"), items.rename_columns(["z", "__record_id", "A"]).slice(0, 0) + ) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, items, record_id_column="rid") + pending = db.get_all_records(PATH, record_id_column="rid") + db.flush() + committed = db.get_all_records(PATH, record_id_column="rid") + assert pending is not None and committed is not None + assert pending.column_names == committed.column_names == ["z", "rid", "A"] + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason=( + "ITL-1377: on a canonical Delta table a batch commits by plain append, as an " + "ordinary writer's batch does on main, so a competing writer's record id is " + "stored twice; ITL-1377 makes every Delta append conflict-safe (developer, " + "2026-11-22). PR 496 must not merge before ITL-1377's fix." + ), +) +@pytest.mark.parametrize("skip_duplicates", [True, False]) +def test_a_competing_record_id_on_a_canonical_delta_table_keeps_one_row( + tmp_path: Path, skip_duplicates: bool +) -> None: + def rows(n: int, value: int, order: tuple[str, ...]) -> pa.Table: + table = pa.table( + { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": [value], + "z": [100 + n], + } + ) + return table.select(list(order)) + + one, two = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + one.add_records( + PATH, rows(1, 10, ("rid", "a", "z")), record_id_column="rid", flush=True + ) + one.add_records( + PATH, + rows(2, 20, ("z", "rid", "a")), + record_id_column="rid", + skip_duplicates=skip_duplicates, + ) + snapshot = one._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + two.add_records( + PATH, + rows(2, 99, ("rid", "a", "z")), + record_id_column="rid", + skip_duplicates=skip_duplicates, + flush=True, + ) + return taken + + with patch.object(one, "_snapshot_for_commit", side_effect=interleave): + try: + one.flush() + except RuntimeError: + pass + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + assert sorted(table.column("rid").to_pylist()) == [bytes([1]), bytes([2])] # pyright: ignore[reportArgumentType] # binary column diff --git a/tests/test_databases/test_canonical_stored_order.py b/tests/test_databases/test_canonical_stored_order.py index ed939ec36..18042826e 100644 --- a/tests/test_databases/test_canonical_stored_order.py +++ b/tests/test_databases/test_canonical_stored_order.py @@ -140,6 +140,7 @@ def _observe(database: Any) -> dict[str, Any]: seen[f"{label}.as_source"] = _table(source.as_table(all_info=True)) seen[f"{label}.as_source.content_hash"] = source.content_hash().to_string() seen["cached.as_table"] = _table(cached.as_table(all_info=True)) + seen["cached.get_all_records"] = _table(cached.get_all_records()) seen["cached.content_hash"] = cached.content_hash().to_string() seen["cached outputs"] = _table( job.nodes["fn"]._cached_function_pod.get_all_cached_outputs() # pyright: ignore[reportOptionalMemberAccess] # the node's own result cache diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index cb4fccd64..200b23313 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1073,7 +1073,9 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: itself), so the order written and the order read are the same in every database; rows queued with nothing pending for their table are put in that order. A table written before Orcapod used the canonical order keeps the order of its first write and takes -appends in any order (Delta commits such a table's batches by merge). No hash, record id +appends in any order (Delta commits to it as before). A table holding a type the append +comparison does not handle (a dictionary, a view type) keeps its first write's order. No +hash, record id or stored path depends on a stored table's column order, and what Orcapod shows of stored rows (a node, a cached or derived source, an observer) is in the reader's own column order, whatever order they are stored in. An append that also From 3d97690bdffaf3921f6bd6d1cdebd310158d5cd2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 17:18:48 -0800 Subject: [PATCH 16/22] fix(ITL-1370): import the database utils module directly (no import cycle) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index b5120752f..af6fd2cbc 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -16,7 +16,7 @@ matching_rows, rows_at, ) -from orcapod.databases import utils as database_utils +import orcapod.databases.utils as database_utils from orcapod.databases.utils import ( appended_field_change, coerce_record_id, From b39b52be868633839c9d4ccde46c75af9dd7e26e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:40:28 -0800 Subject: [PATCH 17/22] test(ITL-1367, ITL-1370): every review finding has a regression test Ports the reviewers' reproducer scripts into the repository and covers each finding's class by parametrization: a logical type inside a struct or a list, every container the append comparison does not handle (dictionary, unions, list view, run-end encoded, a string view in a struct), the annotated form of two logical types over one storage type, the requeue form of a raced Delta flush, a queued row under a locked SQLite database, the pod wrapper's cache hit. Declined or documented findings are pinned as they stand (a rename between the flush check and the write, field metadata on SpiralDB, string against large_string in memory). The replacement-table test now uses a non-canonical dropped table, so it fails on the head the finding was raised on; the 'before ITL-1370' patch tolerates heads without the canonical order. Co-Authored-By: Claude Opus 5.5 --- tests/test_databases/test_append_by_name.py | 72 +++- .../test_append_by_name_review_ports.py | 380 ++++++++++++++++++ .../test_canonical_order_review_496.py | 5 +- .../test_canonical_stored_order.py | 5 +- 4 files changed, 457 insertions(+), 5 deletions(-) create mode 100644 tests/test_databases/test_append_by_name_review_ports.py diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index dc3b36c73..2964c9cd7 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -87,7 +87,10 @@ def _first_write(generation: str) -> Any: if generation == "canonical": return nullcontext() return patch.object( - database_utils, "canonical_column_order", lambda records, record_id: records + database_utils, + "canonical_column_order", + lambda records, record_id: records, + create=True, ) @@ -735,10 +738,15 @@ def test_a_table_dropped_and_written_again_by_the_same_handle_takes_the_new_orde tmp_path: Path, ) -> None: """The handle that wrote the dropped table writes the replacement as a new table: - in the canonical order (ITL-1370), nothing of the dropped table remembered.""" + in the canonical order (ITL-1370), nothing of the dropped table remembered. The + dropped table is stored in another order (``a, rid, b``, as before ITL-1370), so a + handle that remembered it would show it (PR 491 Codex round 2, finding 4).""" path = tmp_path / "store.db" db = _sqlite(path) - db.add_records(PATH, _abc(1), record_id_column="rid", flush=True) + with _first_write("before ITL-1370"): + db.add_records( + PATH, _abc(1, ("a", "rid", "b")), 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) @@ -880,6 +888,64 @@ def rows(n: int, pair: Any, order: list[str]) -> pa.Table: assert stored_rows.column("rid").to_pylist() == [bytes([1])] +@pytest.mark.parametrize("backend", ["in-memory", "Delta"]) +@pytest.mark.parametrize("stored", [False, True], ids=["pending", "committed"]) +def test_two_annotated_logical_types_over_one_storage_type_are_not_reordered( + tmp_path: Path, backend: str, stored: bool +) -> None: + """The annotated form of the case above (PR 491 Codex round 2, finding 3): the + column is held as its storage type with an ``ARROW:extension`` annotation, and a + permuted append carries another logical type's annotation. Refused as on main, + never read back under the held type (main's verdicts, measured on 321284ae).""" + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + one = _make_converter_with_type("test.itl1367.annotated.held") + two = _make_converter_with_type("test.itl1367.annotated.other") + + def rows(n: int, ext_type: Any, order: list[str]) -> pa.Table: + return ( + _abc(n) + .append_column( + _annotated("text", ext_type).with_type(pa.large_string()), + pa.array([str(n)], pa.large_string()), + ) + .select(order) + ) + + inner = ( + InMemoryArrowDatabase() + if backend == "in-memory" + else DeltaTableDatabase(tmp_path / "delta") + ) + ExtensionAwareDatabase(inner, one[0]).add_records( + PATH, + rows(1, one[1], ["rid", "a", "b", "text"]), + record_id_column="rid", + flush=stored, + ) + second = ExtensionAwareDatabase(inner, two[0]) + permuted = rows(2, two[1], ["text", "b", "rid", "a"]) + if backend == "in-memory": + with pytest.raises(InputValidationError, match="other field metadata"): + second.add_records(PATH, permuted, record_id_column="rid") + 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"), [ diff --git a/tests/test_databases/test_append_by_name_review_ports.py b/tests/test_databases/test_append_by_name_review_ports.py new file mode 100644 index 000000000..0a38815c8 --- /dev/null +++ b/tests/test_databases/test_append_by_name_review_ports.py @@ -0,0 +1,380 @@ +"""Review findings on PR 491 (ITL-1367) and PR 496 (ITL-1370), ported from the reviewers' +reproducer scripts so a regression of the same kind is caught here. + +Each test names its review round and finding. A finding that was declined or documented as +a limit is pinned as it stands (equal to main), so a later change is noticed. +""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import pyarrow as pa +import pytest + +from orcapod.core.cached_function_pod import CachedFunctionPod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.sources import DictSource +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SQLiteConnector, +) +from tests.test_databases.type_matrix import open_database + +PATH = ("t",) + + +# ── PR 491, Codex round 3, finding 1: a logical type inside a struct or a list ───── + + +class _Unit(pa.ExtensionType): + """An ``int64`` in a unit: two units are one type to pyarrow's own equality.""" + + def __init__(self, unit: str) -> None: + self.unit = unit + super().__init__(pa.int64(), "test.ports.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_rows(n: int, unit: str, nesting: str, order: tuple[str, ...]) -> pa.Table: + values: Any = pa.ExtensionArray.from_storage( + _Unit(unit), pa.array([10 * n], pa.int64()) + ) + if nesting == "struct": + values = pa.StructArray.from_arrays( + [values, pa.array([1000 * n])], names=["measure", "other"] + ) + elif nesting == "list": + values = pa.LargeListArray.from_arrays(pa.array([0, 1], pa.int64()), values) + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": values, + "b": pa.array([100 * n]), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("nesting", ["top", "struct", "list"]) +@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +def test_a_permuted_append_of_another_logical_type_is_refused_at_every_depth( + tmp_path: Path, database: str, nesting: str +) -> None: + """Held rows in metres, an append in seconds with the columns permuted: refused + as on main (in-memory: ``ArrowInvalid``; Delta: ``Schema mismatch``), never read + back as metres (PR 491 Codex round 3, finding 1).""" + db = ( + InMemoryArrowDatabase() + if database == "in-memory" + else DeltaTableDatabase(tmp_path) + ) + db.add_records( + PATH, _unit_rows(1, "m", nesting, ("rid", "a", "b")), record_id_column="rid" + ) + permuted = _unit_rows(2, "s", nesting, ("b", "rid", "a")) + error: type[BaseException] = ( + pa.ArrowInvalid if database == "in-memory" else ValueError + ) + with pytest.raises(error): + db.add_records(PATH, permuted, record_id_column="rid") + + +# ── PR 491, Codex round 4, finding 1, and CodeRabbit (utils.py:254) ───────────────── + + +def _contained(n: int, unit: str, kind: str) -> Any: + """An ``int64`` in ``unit`` inside a container the append comparison does not + handle, or a ``string_view`` inside a struct.""" + if kind == "string view in a struct": + return pa.array([{"x": str(n)}], pa.struct([("x", pa.string_view())])) + values = pa.ExtensionArray.from_storage(_Unit(unit), pa.array([10 * n], pa.int64())) + index = pa.array([0], pa.int8()) + if kind == "dictionary": + return pa.DictionaryArray.from_arrays(index, values) + if kind == "dense union": + return pa.UnionArray.from_dense( + index, pa.array([0], pa.int32()), [values], field_names=["measure"] + ) + if kind == "sparse union": + return pa.UnionArray.from_sparse(index, [values], field_names=["measure"]) + if kind == "list view": + list_view: Any = pa.ListViewArray + return list_view.from_arrays(pa.array([0]), pa.array([1]), values) + run_end: Any = pa.RunEndEncodedArray + return run_end.from_arrays(pa.array([1], pa.int32()), values) + + +@pytest.mark.parametrize("flushed", [False, True], ids=["pending", "committed"]) +@pytest.mark.parametrize( + "kind", + [ + "dictionary", + "dense union", + "sparse union", + "list view", + "run-end encoded", + "string view in a struct", + ], +) +def test_a_permuted_append_of_an_unhandled_type_is_refused_as_on_main( + kind: str, flushed: bool +) -> None: + """A column whose type tree holds a type the append comparison does not handle is + never reordered: a permuted append (here of another unit, or an equal + ``string_view`` struct) is refused as main refuses it, never read under the held + type (PR 491 Codex round 4, finding 1; CodeRabbit utils.py:254).""" + + def rows(n: int, unit: str, order: tuple[str, ...]) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": _contained(n, unit, kind), + "b": pa.array([100 * n]), + } + return pa.table({name: columns[name] for name in order}) + + db = InMemoryArrowDatabase() + db.add_records( + PATH, rows(1, "m", ("rid", "a", "b")), record_id_column="rid", flush=flushed + ) + with pytest.raises(pa.ArrowInvalid): + db.add_records(PATH, rows(2, "s", ("b", "rid", "a")), record_id_column="rid") + db.flush() + + +# ── PR 491, Codex round 3, finding 2 (requeue form) ─────────────────────────────── + + +def _abc(n: int, order: tuple[str, ...] = ("rid", "a", "b"), a: Any = None) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([10 * n]) if a is None else a, + "b": pa.array([100 * n]), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize( + ("schema_handling", "a"), + [ + ("merge", pa.nulls(1)), + ("merge", pa.array([30])), + ("coerce", pa.nulls(1)), + ("coerce", pa.array([30], pa.int32())), + ("coerce", pa.array([30])), + ], + ids=["merge null", "merge same", "coerce null", "coerce int32", "coerce same"], +) +def test_a_batch_after_a_raced_flush_is_stored_by_name( + tmp_path: Path, schema_handling: str, a: Any, skip_duplicates: bool +) -> None: + """A permuted batch whose flush races another writer, then a further permuted batch + relying on ``schema_handling``: every row stored is stored under its names (PR 491 + Codex round 3, finding 2, the requeue form). + + On a canonical table the raced batch commits by append (ITL-1377's decision; + main's MERGE failed and requeued it), so nothing is pending for the last batch: + an ``int32`` batch is then refused against the stored ``int64`` column, exactly as + main refuses it whenever nothing is pending (``coerce`` casts to the pending + batch only). Every other case stores every row, as main does.""" + from orcapod.errors import InputValidationError + + 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) + db.add_records(PATH, _abc(2, ("b", "rid", "a")), **kwargs) + snapshot = db._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + DeltaTableDatabase(tmp_path).add_records(PATH, _abc(4), flush=True, **kwargs) + return taken + + with patch.object(db, "_snapshot_for_commit", side_effect=interleave): + try: + db.flush() + except RuntimeError: + pass # main: the MERGE conflicts and the batch is requeued + expected = {1: (10, 100), 2: (20, 200), 4: (40, 400)} + third = _abc(3, ("b", "rid", "a"), a) + if a.type == pa.int32(): + with pytest.raises(InputValidationError, match="stored as int64"): + db.add_records(PATH, third, **kwargs) + else: + db.add_records(PATH, third, **kwargs) + expected[3] = (a.to_pylist()[0], 300) + db.flush() + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + rows = {row["rid"][0]: (row["a"], row["b"]) for row in table.to_pylist()} + assert rows == expected + + +# ── PR 491, Codex round 3, finding 4: a queued row under a locked database ─────────── + + +def test_a_queued_row_is_read_while_another_connection_locks_the_database( + tmp_path: Path, +) -> None: + """A point lookup of a queued row answers from memory, so another connection's + exclusive lock does not make it fail (PR 491 Codex round 3, finding 4).""" + path = tmp_path / "store.db" + db = ConnectorArrowDatabase(SQLiteConnector(str(path))) + db.add_records(PATH, _abc(1), record_id_column="rid", flush=True) + db.add_records(PATH, _abc(2, ("b", "rid", "a")), record_id_column="rid") + with sqlite3.connect(path) as other: + other.execute("BEGIN EXCLUSIVE") + row = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + other.rollback() + assert row is not None + assert row.select(["rid", "a", "b"]).to_pylist() == [ + {"rid": bytes([2]), "a": 20, "b": 200} + ] + + +# ── PR 491, Codex round 3, D: a schema change between the flush's check and its write ─ + + +def test_a_rename_between_the_flush_check_and_the_write_is_as_on_main( + tmp_path: Path, +) -> None: + """Documented limit, pre-existing and equal to main: another connection that + renames ``a`` to ``A`` after the flush checked the table and before it writes is + not seen; SQLite resolves the written ``a`` without case, so the value lands under + ``A`` (PR 491 Codex round 3, D). Pinned so a change is noticed.""" + path = tmp_path / "store.db" + ConnectorArrowDatabase(SQLiteConnector(str(path))).add_records( + PATH, _abc(1), record_id_column="rid", flush=True + ) + connector = SQLiteConnector(str(path)) + db = ConnectorArrowDatabase(connector) + db.add_records(PATH, _abc(2), record_id_column="rid") + upsert = connector.upsert_records + + def rename_then_write(*args: Any, **kwargs: Any) -> Any: + with sqlite3.connect(path) as other: + other.execute('ALTER TABLE "t" RENAME COLUMN a TO A') + return upsert(*args, **kwargs) + + with patch.object(connector, "upsert_records", side_effect=rename_then_write): + db.flush() + table = ConnectorArrowDatabase(SQLiteConnector(str(path))).get_all_records( + PATH, record_id_column="rid" + ) + assert table is not None + assert sorted(cast(list[int], table.column("A").to_pylist())) == [10, 20] + + +# ── PR 491, CodeRabbit (connector:488), declined ─────────────────────────────────── + + +def test_a_column_with_field_metadata_is_stored_by_name_on_spiraldb( + tmp_path: Path, +) -> None: + """Declined: a connector flush compares the connector's column info, which carries + no field metadata, so a column with field metadata is not reordered there; + SpiralDB matches the write by name itself. Pinned: every value under its name + (PR 491 CodeRabbit, connector_arrow_database.py:488).""" + field = pa.field("a", pa.int64(), metadata={"unit": "m"}) + + def rows(n: int, order: tuple[str, ...]) -> pa.Table: + table = pa.Table.from_arrays( + [ + pa.array([bytes([n])], pa.large_binary()), + pa.array([10 * n]), + pa.array([100 * n]), + ], + schema=pa.schema( + [pa.field("rid", pa.large_binary()), field, pa.field("b", pa.int64())] + ), + ) + return table.select(list(order)) + + with open_database("SpiralDB", tmp_path) as db: + db.add_records( + PATH, rows(1, ("rid", "a", "b")), record_id_column="rid", flush=True + ) + db.add_records( + PATH, rows(2, ("b", "rid", "a")), record_id_column="rid", flush=True + ) + table = db.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}, + ] + + +# ── PR 491, CodeRabbit (in_memory:270), declined ─────────────────────────────────── + + +@pytest.mark.parametrize("order", [("rid", "a", "b"), ("b", "rid", "a")]) +def test_a_string_append_to_a_large_string_batch_is_refused_in_memory_as_on_main( + order: tuple[str, ...], +) -> None: + """Declined: the in-memory database refuses a ``string`` append to a + ``large_string`` pending batch in any column order, as main does; the reorder + does not change that verdict (PR 491 CodeRabbit, in_memory_databases.py:270).""" + + def rows(n: int, text: Any, column_order: tuple[str, ...]) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([str(n)], text), + "b": pa.array([n]), + } + return pa.table({name: columns[name] for name in column_order}) + + db = InMemoryArrowDatabase() + db.add_records( + PATH, rows(1, pa.large_string(), ("rid", "a", "b")), record_id_column="rid" + ) + with pytest.raises(pa.ArrowInvalid): + db.add_records(PATH, rows(2, pa.string(), order), record_id_column="rid") + + +# ── PR 496, Codex, finding 4: the pod wrapper's cache hit ─────────────────────────── + + +def _outputs(x: int) -> tuple[int, int]: + return x + 1, x + 7 + + +def test_a_cached_pods_hit_presents_the_outputs_as_its_first_call_does() -> None: + """The pod wrapper uses the same per-input lookup as the cached data function: a + hit gives the outputs in the declared order ``z, a``, as the first call and main + do (PR 496 Codex, finding 4, the pod form).""" + database = InMemoryArrowDatabase() + pod = CachedFunctionPod( + FunctionPod.from_fn(_outputs, output_keys=["z", "a"]), # pyright: ignore[reportArgumentType] # a FunctionPod works at run time + result_database=database, + ) + source = DictSource( + data=[{"k": 1, "x": 1}, {"k": 2, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="src", + ) + first = [data for _, data in pod.process(source).iter_data()] + database.flush() + second = [data for _, data in pod.process(source).iter_data()] + assert all(d.get_meta_value(pod.RESULT_COMPUTED_FLAG) is False for d in second) + for miss, hit in zip(first, second, strict=True): + assert tuple(hit.keys()) == tuple(miss.keys()) == ("z", "a") + assert [hit[k] for k in hit.keys()] == [miss[k] for k in miss.keys()] + columns = hit.as_table(columns={"source": True}).column_names + assert columns == miss.as_table(columns={"source": True}).column_names diff --git a/tests/test_databases/test_canonical_order_review_496.py b/tests/test_databases/test_canonical_order_review_496.py index 59607f79b..839a6661a 100644 --- a/tests/test_databases/test_canonical_order_review_496.py +++ b/tests/test_databases/test_canonical_order_review_496.py @@ -82,7 +82,10 @@ def rows(n: int) -> pa.Table: ) with patch.object( - database_utils, "canonical_column_order", lambda records, record_id: records + database_utils, + "canonical_column_order", + lambda records, record_id: records, + create=True, ): DeltaTableDatabase(tmp_path).add_records( PATH, rows(1), record_id_column="rid", flush=True diff --git a/tests/test_databases/test_canonical_stored_order.py b/tests/test_databases/test_canonical_stored_order.py index 18042826e..5852a15be 100644 --- a/tests/test_databases/test_canonical_stored_order.py +++ b/tests/test_databases/test_canonical_stored_order.py @@ -50,7 +50,10 @@ def _before_itl_1370() -> AbstractContextManager[Any]: """Tables created in this context are written as before ITL-1370: in the order of their first write.""" return patch.object( - database_utils, "canonical_column_order", lambda records, record_id: records + database_utils, + "canonical_column_order", + lambda records, record_id: records, + create=True, ) From ccfc3ef8fbbb6bf4e93b2fddf9e00c8daf3a0b62 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:46:29 -0800 Subject: [PATCH 18/22] fix(databases): an extension type's storage field metadata counts in the append comparison (ITL-1370) CodeRabbit on PR 496: - utils.py:303: two extension types with one identifier over storage whose nested field metadata differs were taken for one, so a permuted append was accepted and its metadata replaced by the held one (introduced by ITL-1367); the comparison now checks the storage's nested names and metadata, and such an append is refused as before ITL-1367 - the PostgreSQL test fixture drops its schema also when the connector cannot be created or its close fails - function_node.py:3615 (declined, pinned): get_all_records keeps _context_key last, as main does - result_cache.py:485 and status_observer.py:229 were fixed by the Codex round Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/utils.py | 3 + tests/test_databases/test_append_by_name.py | 61 +++++++++- .../test_append_by_name_review_ports.py | 107 ++++++++++++++++++ 3 files changed, 165 insertions(+), 6 deletions(-) diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 9f076cf33..15ae39faf 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -363,6 +363,9 @@ def _same_type(given: Any, held: Any) -> bool: 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) + # The storage's nested field names and metadata too: the append check + # does not look inside an extension type (CodeRabbit on PR 496). + and _nested_change(held.storage_type, given.storage_type, "") is None ) if given != held: return False diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 2964c9cd7..fe26c24d8 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -18,7 +18,7 @@ import sqlite3 import uuid from collections.abc import Iterator -from contextlib import ExitStack, nullcontext +from contextlib import ExitStack, contextmanager, nullcontext from pathlib import Path from typing import Any, cast from unittest.mock import patch @@ -1194,14 +1194,63 @@ def postgresql_database() -> Iterator[ConnectorArrowDatabase]: 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() + + def drop() -> None: with psycopg.connect(base_dsn, autocommit=True) as admin: admin.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE") + with _dropped_after( + lambda: PostgreSQLConnector(f"{base_dsn} options=-csearch_path={schema}"), drop + ) as connector: + yield ConnectorArrowDatabase(connector) + + +@contextmanager +def _dropped_after(connect: Any, drop: Any) -> Iterator[Any]: + """The connector ``connect`` makes, closed if it was made; ``drop`` always runs + afterwards, also when ``connect`` or the close raises (CodeRabbit on PR 496: the + schema used to stay behind when the connector could not be created).""" + connector = None + try: + connector = connect() + yield connector + finally: + try: + if connector is not None: + connector.close() + finally: + drop() + + +class _Closing: + def __init__(self, fail: bool) -> None: + self.fail = fail + + def close(self) -> None: + if self.fail: + raise RuntimeError("close failed") + + +@pytest.mark.parametrize("failure", ["connect", "close", "none"]) +def test_the_postgresql_schema_is_dropped_whatever_fails(failure: str) -> None: + """The fixture's cleanup drops the schema when the connector cannot be created, + when closing it fails, and when nothing fails.""" + dropped: list[bool] = [] + + def connect() -> Any: + if failure == "connect": + raise RuntimeError("connect failed") + return _Closing(fail=failure == "close") + + if failure == "none": + with _dropped_after(connect, lambda: dropped.append(True)): + pass + else: + with pytest.raises(RuntimeError): + with _dropped_after(connect, lambda: dropped.append(True)): + pass + assert dropped == [True] + @pytest.mark.postgres @pytest.mark.parametrize("first", FIRST_ORDERS) diff --git a/tests/test_databases/test_append_by_name_review_ports.py b/tests/test_databases/test_append_by_name_review_ports.py index 0a38815c8..a14962f74 100644 --- a/tests/test_databases/test_append_by_name_review_ports.py +++ b/tests/test_databases/test_append_by_name_review_ports.py @@ -378,3 +378,110 @@ def test_a_cached_pods_hit_presents_the_outputs_as_its_first_call_does() -> None assert [hit[k] for k in hit.keys()] == [miss[k] for k in miss.keys()] columns = hit.as_table(columns={"source": True}).column_names assert columns == miss.as_table(columns={"source": True}).column_names + + +# ── PR 496, CodeRabbit (utils.py:303): metadata inside an extension type's storage ── + + +class _MarkedStorage(pa.ExtensionType): + """One identifier over a storage struct whose child carries a marker in its field + metadata: two markers are one type to pyarrow and to the identifier.""" + + def __init__(self, marker: bytes) -> None: + storage = pa.struct( + [pa.field("value", pa.int64(), metadata={b"marker": marker})] + ) + super().__init__(storage, "test.ports.storage_metadata") + + def __arrow_ext_serialize__(self) -> bytes: + return b"same-identifier" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(storage_type.field("value").metadata[b"marker"]) + + +def _marked_rows(n: int, marker: bytes, order: tuple[str, ...]) -> pa.Table: + ext_type = _MarkedStorage(marker) + values = pa.ExtensionArray.from_storage( + ext_type, pa.array([{"value": n}], ext_type.storage_type) + ) + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": values, + "b": pa.array([n]), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize( + ("database", "flushed", "error"), + [ + ("in-memory", False, pa.ArrowInvalid), + ("in-memory", True, pa.ArrowInvalid), + ("Delta", False, ValueError), + ], + ids=["in-memory pending", "in-memory committed", "Delta pending"], +) +def test_a_permuted_append_with_other_metadata_inside_an_extension_is_refused( + tmp_path: Path, database: str, flushed: bool, error: type[BaseException] +) -> None: + """An extension type whose storage struct child carries other field metadata: a + permuted append is not taken for the held column (its marker would be replaced by + the held one), so it is refused as main refused it before PR 491 (321284ae) + (PR 496 CodeRabbit, utils.py:303). A committed Delta table of such a type fails + to read on main too (pre-existing, not pinned here).""" + db = ( + InMemoryArrowDatabase() + if database == "in-memory" + else DeltaTableDatabase(tmp_path) + ) + db.add_records( + PATH, + _marked_rows(1, b"held", ("rid", "a", "b")), + record_id_column="rid", + flush=flushed, + ) + with pytest.raises(error): + db.add_records( + PATH, + _marked_rows(2, b"incoming", ("b", "rid", "a")), + record_id_column="rid", + ) + db.flush() + + +# ── PR 496, CodeRabbit (function_node.py:3615), declined ───────────────────────────── + + +def test_a_function_nodes_stored_rows_put_the_context_column_last_as_on_main() -> None: + """Declined: ``get_all_records`` puts ``_context_key`` last, after the source-info + columns, as main does; the node's ``as_table`` layout places it before them. + Moving it would change what a user sees beyond the two presentation changes the + developer approved. Pinned (PR 496 CodeRabbit, function_node.py:3615).""" + from orcapod import PipelineJob, function_pod + from orcapod.core.sources import ArrowTableSource + + fields = [ + pa.field(n, pa.int64(), nullable=False) for n in ["z_tag", "a_tag", "z", "a"] + ] + source = ArrowTableSource( + pa.Table.from_arrays([pa.array([1, 2])] * 4, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + source_id="src", + ) + + @function_pod(output_keys=["w_out", "c_out"]) + def outputs(z: int, a: int) -> tuple[int, int]: + return z + a, z - a + + job = PipelineJob(name="context", database=InMemoryArrowDatabase()) + with job: + outputs.pod(source, label="fn") + job.run() + node = job.nodes["fn"] + for config in ({"context": True}, {"context": True, "source": True}): + records = node.get_all_records(columns=config) + assert records is not None + assert records.column_names[-1] == "_context_key", config From 45210a300ae63022dbaca4d09c96178383200c78 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:56:36 -0800 Subject: [PATCH 19/22] revert(databases): storage field metadata of an extension stays uncompared on append; pin all eight cells (ITL-1415) Reverts the utils.py part of ccfc3ef8. Storage field metadata inside an extension type was never compared on append: on 321284ae the same-order append with other metadata is accepted too, and its another-order refusals were the column-order refusal ITL-1367 removed. The comparison refused only the another-order cells and made the two orders differ again. The question is ITL-1415 (backlog, with ITL-1371). The test now pins every cell (in-memory and Delta, pending and flushed, another and same order): accepted, held metadata read back. The PostgreSQL fixture cleanup and the other threads' tests stay. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/utils.py | 3 - .../test_append_by_name_review_ports.py | 67 ++++++++++++------- 2 files changed, 41 insertions(+), 29 deletions(-) diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 15ae39faf..9f076cf33 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -363,9 +363,6 @@ def _same_type(given: Any, held: Any) -> bool: 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) - # The storage's nested field names and metadata too: the append check - # does not look inside an extension type (CodeRabbit on PR 496). - and _nested_change(held.storage_type, given.storage_type, "") is None ) if given != held: return False diff --git a/tests/test_databases/test_append_by_name_review_ports.py b/tests/test_databases/test_append_by_name_review_ports.py index a14962f74..1d97f4db6 100644 --- a/tests/test_databases/test_append_by_name_review_ports.py +++ b/tests/test_databases/test_append_by_name_review_ports.py @@ -401,6 +401,9 @@ def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: return cls(storage_type.field("value").metadata[b"marker"]) +pa.register_extension_type(_MarkedStorage(b"registration")) # pyright: ignore[reportArgumentType] # the stubs name PyExtensionType; pyarrow takes any ExtensionType + + def _marked_rows(n: int, marker: bytes, order: tuple[str, ...]) -> pa.Table: ext_type = _MarkedStorage(marker) values = pa.ExtensionArray.from_storage( @@ -414,41 +417,53 @@ def _marked_rows(n: int, marker: bytes, order: tuple[str, ...]) -> pa.Table: return pa.table({name: columns[name] for name in order}) +@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +@pytest.mark.parametrize("flushed", [False, True], ids=["pending", "flushed"]) @pytest.mark.parametrize( - ("database", "flushed", "error"), - [ - ("in-memory", False, pa.ArrowInvalid), - ("in-memory", True, pa.ArrowInvalid), - ("Delta", False, ValueError), - ], - ids=["in-memory pending", "in-memory committed", "Delta pending"], + "order", + [("b", "rid", "a"), ("rid", "a", "b")], + ids=["another order", "same order"], ) -def test_a_permuted_append_with_other_metadata_inside_an_extension_is_refused( - tmp_path: Path, database: str, flushed: bool, error: type[BaseException] +def test_other_metadata_inside_an_extensions_storage_is_not_compared_on_append( + tmp_path: Path, database: str, flushed: bool, order: tuple[str, ...] ) -> None: - """An extension type whose storage struct child carries other field metadata: a - permuted append is not taken for the held column (its marker would be replaced by - the held one), so it is refused as main refused it before PR 491 (321284ae) - (PR 496 CodeRabbit, utils.py:303). A committed Delta table of such a type fails - to read on main too (pre-existing, not pinned here).""" - db = ( - InMemoryArrowDatabase() - if database == "in-memory" - else DeltaTableDatabase(tmp_path) - ) + """Pinned, not endorsed: an append whose extension column's storage struct child + carries other field metadata (``incoming`` against the held ``held``) is accepted + in either column order, and a fresh read reports the held metadata. Storage field + metadata was never compared on append (on 321284ae the same-order append is + accepted too; its another-order refusals were the column-order refusal ITL-1367 + removed), so the two orders now behave alike. Whether to refuse it is ITL-1415, + to be decided with ITL-1371; this pin makes that decision visible (PR 496 + CodeRabbit, utils.py:303). + + Delta, flushed, another order: on main a new table keeps its first write's order + and delta-rs takes the incoming metadata when the append arrives in another + order; here a new table is canonical and the append is committed in its order, + so the held metadata stays, as for an append in the same order. A table written + before ITL-1370 commits as on main.""" + + def fresh() -> Any: + if database == "in-memory": + return memory + return DeltaTableDatabase(tmp_path) + + memory = InMemoryArrowDatabase() + db = fresh() db.add_records( PATH, _marked_rows(1, b"held", ("rid", "a", "b")), record_id_column="rid", flush=flushed, ) - with pytest.raises(error): - db.add_records( - PATH, - _marked_rows(2, b"incoming", ("b", "rid", "a")), - record_id_column="rid", - ) - db.flush() + db.add_records(PATH, _marked_rows(2, b"incoming", order), record_id_column="rid") + db.flush() + + stored = fresh().get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(stored.column("b").to_pylist()) == [1, 2] + column_type = stored.schema.field("a").type + assert isinstance(column_type, _MarkedStorage) + assert column_type.storage_type.field(0).metadata == {b"marker": b"held"} # ── PR 496, CodeRabbit (function_node.py:3615), declined ───────────────────────────── From 5ba91f9ca6c630e4ba5317b890a3b1ac61e73291 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 00:59:18 -0800 Subject: [PATCH 20/22] fix(databases): report Delta user column collisions first --- src/orcapod/databases/delta_lake_databases.py | 24 +++++++++++++++---- .../test_delta_refused_before_queueing.py | 23 ++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 034b2e7e5..95fc04e0e 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -64,6 +64,7 @@ TypeIdentityError, UnstorableColumnError, ) +from orcapod.system_constants import constants from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -774,24 +775,37 @@ def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: ``int64``, so a collision deeper down is not seen there. The struct Delta refuses holds the pair, and the field is named by its path (``outer.right.ᲊ``) with its type. Names come from the schema, the longest one Delta's message quotes, so a - name holding a quote is named whole. ``(the reported text, null)`` when no struct - is refused. + name holding a quote is named whole. If Delta names a top-level source-info + column, the probe checks user columns first to find a user-facing collision. + ``(the reported text, null)`` when no struct is refused. """ messages = [str(seen) for seen in _error_chain(error)] + reported = _duplicate_name_in(error) or "" def quoted(field: "pa.Field[Any]") -> bool: return any(f"(case-insensitive): '{field.name}'" in m for m in messages) for prefix, children in _structs_of(schema): - probe = pa.schema([pa.field(c.name, pa.int64()) for c in children]) + prioritize_data = not prefix and reported.startswith(constants.SOURCE_PREFIX) + probe_fields = children + if prioritize_data: + probe_fields = sorted( + children, key=lambda c: c.name.startswith(constants.SOURCE_PREFIX) + ) + probe = pa.schema([pa.field(c.name, pa.int64()) for c in probe_fields]) try: deltalake.Schema.from_arrow(probe) except Exception as refused: # noqa: BLE001 # only a duplicate name is looked at - if _duplicate_name_in(refused) is None: + collision = _duplicate_name_in(refused) + if collision is None: continue named = [c for c in children if quoted(c)] if named: field = max(named, key=lambda c: len(c.name)) + if prioritize_data and not collision.startswith( + constants.SOURCE_PREFIX + ): + field = next((c for c in children if c.name == collision), field) return prefix + field.name, field.type # No struct of the batch is refused on its own: the pair is a batch column and a # stored column. Name the batch's column, with its type. @@ -799,7 +813,7 @@ def quoted(field: "pa.Field[Any]") -> bool: if top: field = max(top, key=lambda f: len(f.name)) return field.name, field.type - return _duplicate_name_in(error) or "", pa.null() + return reported, pa.null() def _structs_of(schema: pa.Schema) -> list[tuple[str, list["pa.Field[Any]"]]]: diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 6b7f7c767..0a747d547 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -34,6 +34,7 @@ OrcapodDatabaseReadError, UnstorableColumnError, ) +from orcapod.system_constants import constants PATH = ("t",) @@ -298,6 +299,28 @@ def test_names_folded_alike_only_by_delta_are_refused_once( assert not (tmp_path / "t" / "_delta_log").exists() +@pytest.mark.parametrize("include_data", [True, False], ids=["both", "source only"]) +def test_the_backstop_reports_the_data_column_first( + tmp_path: Path, include_data: bool +) -> None: + upper, lower = (name + "'q" for name in RUST_ONLY_FOLDS[0]) + source_prefix = constants.SOURCE_PREFIX + columns: dict[str, pa.Array[Any]] = { + f"{source_prefix}{upper}": pa.array(["first"]), + f"{source_prefix}{lower}": pa.array(["second"]), + } + if include_data: + columns[upper] = pa.array([1], pa.int32()) + columns[lower] = pa.array([2], pa.int32()) + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", **columns)) + with pytest.raises(UnstorableColumnError) as info: + db.flush() + assert info.value.column == (lower if include_data else f"{source_prefix}{lower}") + assert info.value.arrow_type == (pa.int32() if include_data else pa.string()) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + def test_a_storage_typed_column_carrying_another_extension_name(tmp_path: Path) -> None: """A logical identity given as ``ARROW:extension:*`` field metadata on a storage type (CodeRabbit on PR 504): another identifier, refused when added by ITL-1371's From 343fbc7c9d5705a75407422f1d5cd2de56da6f21 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 01:21:40 -0800 Subject: [PATCH 21/22] fix(databases): preserve reader layouts in fallback cases --- .zed/rules | 2 +- CLAUDE.md | 2 +- docs/reference/database-types.md | 4 +- src/orcapod/core/nodes/function_node.py | 22 +++++------ src/orcapod/utils/arrow_utils.py | 10 +++-- tests/test_databases/test_append_by_name.py | 37 +++++++++++++++++-- .../test_canonical_stored_order.py | 16 ++++++++ .../test_delta_refused_before_queueing.py | 3 +- tests/test_databases/type_matrix.py | 4 +- tests/test_utils/test_arrow_utils.py | 10 +++++ 10 files changed, 84 insertions(+), 26 deletions(-) diff --git a/.zed/rules b/.zed/rules index 184bddf9a..445b8326e 100644 --- a/.zed/rules +++ b/.zed/rules @@ -992,7 +992,7 @@ generation of hashing; rows of the current data context are the current entries. the backend preserves that type. Delta normalizes view types before queueing, matches merge and coerce to the queued rows by name, and uses a retrying MERGE for every commit to an existing table (ITL-1377). A connector database trusts nothing about a stored - table across calls: it aligns an append only to its own pending batch and checks rows + table across calls: it aligns incoming rows only with its own pending batch and checks rows against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no table is rewritten. Every reader of stored rows presents them in its own layout, whatever order they are stored in, through one helper, arrow_utils.in_presented_order diff --git a/CLAUDE.md b/CLAUDE.md index f62eea52b..2cb299980 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1021,7 +1021,7 @@ current data context are the current entries. the backend preserves that type. Delta normalizes view types before queueing, matches merge and coerce to the queued rows by name, and uses a retrying MERGE for every commit to an existing table (ITL-1377). A connector database trusts nothing about a stored - table across calls: it aligns an append only to its own pending batch and checks rows + table across calls: it aligns incoming rows only with its own pending batch and checks rows against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no table is rewritten. Every reader of stored rows presents them in its own layout, whatever order they are stored in, through one helper, `arrow_utils.in_presented_order` diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 30a864587..91cc706c0 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -140,8 +140,8 @@ column order, in every database: the record id, then every other column sorted b stores and reads every table in, whatever the order written (measured on SpiralDB itself), so the order written and the order read are the same in every database; rows queued with nothing pending for their table are put in that order. A table written -before Orcapod used the canonical order keeps the order of its first write and takes -appends in any order. Delta uses a conflict-safe MERGE with retry for each later commit. +before Orcapod used the canonical order keeps the order of its first write and accepts +new rows in any column order. Delta uses a conflict-safe MERGE with retry for each later commit. If the write schema contains a type the append comparison does not handle, the ordering helper leaves the columns in input order. Delta normalizes view types before ordering. Stored column order has no effect on hashes, record IDs or stored paths. What Orcapod shows of diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index cb6a31c51..aded202e3 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3936,24 +3936,20 @@ def _stored_data_tags(self, taginfo_schema: "pa.Schema") -> tuple[str, ...]: def _presented_layout(self) -> list[str]: """The columns of this node's rows in the order it presents them (ITL-1370). - Its zero-row table (tags, system tags, data, context, source info) when its - input can say it; a loaded node's saved tags and data, each data column - followed by nothing else. Stored rows are put in this order on read, then - every other column by name (``arrow_utils.in_presented_order``), so what the - node presents never follows the stored order. + Use the zero-row table when available. Otherwise use the node's declared + or saved tag and data keys, then the data columns' source info. Other stored + columns follow by name (``arrow_utils.in_presented_order``). """ if self._input_stream is not None: zero = self._zero_row_output_table() if zero is not None: return zero.column_names - if self._function_pod is None: - tags, data = self.keys() - return [ - *tags, - *data, - *(f"{constants.SOURCE_PREFIX}{name}" for name in data), - ] - return [] + tags, data = self.keys() + return [ + *tags, + *data, + *(f"{constants.SOURCE_PREFIX}{name}" for name in data), + ] def _stored_tag_keys(self, fetched: _JoinedRecords) -> tuple[str, ...]: """Return the user tag columns of the records in *fetched*. diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index cf05d3c6e..81aec178b 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -766,10 +766,14 @@ def in_presented_order(table: "pa.Table", reference: "Sequence[str]") -> "pa.Tab reference: The reader's layout. Returns: - ``table``, its columns reordered (``table`` itself when already in order). + ``table`` with its columns reordered, or the original table if already in + order or if its names repeat. """ - order = presented_column_order(table.column_names, reference) - if order == table.column_names: + names = table.column_names + if len(set(names)) != len(names): + return table + order = presented_column_order(names, reference) + if order == names: return table return table.select(order) diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 80b11c32a..74c27324d 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -21,7 +21,7 @@ from contextlib import ExitStack, contextmanager, nullcontext from pathlib import Path from typing import Any, cast -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pyarrow as pa import pytest @@ -1182,6 +1182,8 @@ def test_queued_rows_combine_with_a_stored_key_read_back_not_null( @pytest.fixture def postgresql_database() -> Iterator[ConnectorArrowDatabase]: psycopg = pytest.importorskip("psycopg") + from psycopg import sql + from orcapod.databases import PostgreSQLConnector host = os.environ.get("PGHOST", "localhost") @@ -1193,12 +1195,15 @@ def postgresql_database() -> Iterator[ConnectorArrowDatabase]: f"host={host} port={port} dbname={dbname} user={user} password={password}" ) schema = f"test_{uuid.uuid4().hex[:12]}" + identifier = sql.Identifier(schema) with psycopg.connect(base_dsn, autocommit=True) as admin: - admin.execute(f"CREATE SCHEMA {schema}") + admin.execute(sql.SQL("CREATE SCHEMA {}").format(identifier)) def drop() -> None: with psycopg.connect(base_dsn, autocommit=True) as admin: - admin.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE") + admin.execute( + sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(identifier) + ) with _dropped_after( lambda: PostgreSQLConnector(f"{base_dsn} options=-csearch_path={schema}"), drop @@ -1232,6 +1237,32 @@ def close(self) -> None: raise RuntimeError("close failed") +def test_the_postgresql_fixture_quotes_schema_identifiers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Setup and cleanup quote the same identifier, even if its name has a quote.""" + psycopg = pytest.importorskip("psycopg") + import orcapod.databases + + admin = MagicMock() + admin.__enter__.return_value = admin + monkeypatch.setattr(psycopg, "connect", lambda *_args, **_kwargs: admin) + monkeypatch.setattr(uuid, "uuid4", lambda: MagicMock(hex='quoted"name')) + monkeypatch.setattr( + orcapod.databases, "PostgreSQLConnector", lambda _: _Closing(False) + ) + + fixture = getattr(postgresql_database, "__wrapped__") + with contextmanager(fixture)(): + pass + + statements = [call.args[0].as_string() for call in admin.execute.call_args_list] + assert statements == [ + 'CREATE SCHEMA "test_quoted""name"', + 'DROP SCHEMA IF EXISTS "test_quoted""name" CASCADE', + ] + + @pytest.mark.parametrize("failure", ["connect", "close", "none"]) def test_the_postgresql_schema_is_dropped_whatever_fails(failure: str) -> None: """The fixture's cleanup drops the schema when the connector cannot be created, diff --git a/tests/test_databases/test_canonical_stored_order.py b/tests/test_databases/test_canonical_stored_order.py index 28ec0f194..5ac402224 100644 --- a/tests/test_databases/test_canonical_stored_order.py +++ b/tests/test_databases/test_canonical_stored_order.py @@ -117,6 +117,22 @@ def _table(table: pa.Table | None) -> tuple[list[str], list[str]] | None: return table.column_names, sorted(map(str, table.to_pylist())) +def test_live_function_presents_declared_keys_without_a_zero_row_layout() -> None: + """The stored reader preserves the live node's declared tag and output order.""" + with _job(InMemoryArrowDatabase(), [1, 2]) as (job, _): + node = job.nodes["fn"] + expected = node.get_all_records(all_info=True) + assert expected is not None + with patch.object(type(node), "_zero_row_output_table", return_value=None): + records = node.get_all_records(all_info=True) + assert records is not None + user_columns = ["z_tag", "a_tag", "w_out", "c_out"] + assert [ + name for name in records.column_names if name in user_columns + ] == user_columns + assert records.select(user_columns).equals(expected.select(user_columns)) + + # Function result rows are named by a fresh uuid7 each run (``__data_id``, the result # table's record id, and the source-info tokens of the outputs, which name it) and # carry the time they were computed (``__pod_ts``): not hashes, different in any two diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 0a747d547..19c32bb1d 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -303,7 +303,8 @@ def test_names_folded_alike_only_by_delta_are_refused_once( def test_the_backstop_reports_the_data_column_first( tmp_path: Path, include_data: bool ) -> None: - upper, lower = (name + "'q" for name in RUST_ONLY_FOLDS[0]) + """Exercise the flush check even if Python learns earlier Unicode case folds.""" + upper, lower = (name + "'q" for name in RUST_ONLY_FOLDS[-1]) source_prefix = constants.SOURCE_PREFIX columns: dict[str, pa.Array[Any]] = { f"{source_prefix}{upper}": pa.array(["first"]), diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 07963eda8..f3ffda21a 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1144,8 +1144,8 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: stores and reads every table in, whatever the order written (measured on SpiralDB itself), so the order written and the order read are the same in every database; rows queued with nothing pending for their table are put in that order. A table written -before Orcapod used the canonical order keeps the order of its first write and takes -appends in any order. Delta uses a conflict-safe MERGE with retry for each later commit. +before Orcapod used the canonical order keeps the order of its first write and accepts +new rows in any column order. Delta uses a conflict-safe MERGE with retry for each later commit. If the write schema contains a type the append comparison does not handle, the ordering helper leaves the columns in input order. Delta normalizes view types before ordering. Stored column order has no effect on hashes, record IDs or stored paths. What Orcapod shows of diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 26bbddda1..7f8c1f34e 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -10,6 +10,7 @@ column_arrow_type, concat_tables_by_name, decode_dictionaries, + in_presented_order, infer_schema_nullable, make_schema_non_nullable, normalize_extension_columns, @@ -20,6 +21,15 @@ ) +def test_in_presented_order_keeps_a_table_with_repeated_names() -> None: + """Both occurrences and their positions survive an ambiguous name projection.""" + table = pa.Table.from_arrays( + [pa.array([1]), pa.array([2]), pa.array([3])], + names=["repeated", "other", "repeated"], + ) + assert in_presented_order(table, ["other", "repeated"]) is table + + # --------------------------------------------------------------------------- # Minimal extension types for normalize_extension_columns tests. # These are self-contained and do not depend on the orcapod type-converter. From 317ff8b080b05bbeaba59e48b405149407f05c1a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 11:44:10 -0800 Subject: [PATCH 22/22] docs(databases): clarify canonical stored order exceptions --- .zed/rules | 30 ++++----- CLAUDE.md | 18 +++--- changelog.d/ITL-1370.md | 31 ++++----- docs/dev/design_issues/ITL-1367-CO1.md | 5 +- docs/dev/design_issues/ITL-1370-CO2.md | 5 +- .../dev/specs/itl-1367-stored-column-order.md | 63 +++++++++---------- docs/reference/data-function-types.md | 7 +-- docs/reference/database-types.md | 21 ++++--- tests/test_databases/type_matrix.py | 21 ++++--- 9 files changed, 105 insertions(+), 96 deletions(-) diff --git a/.zed/rules b/.zed/rules index 445b8326e..705db159c 100644 --- a/.zed/rules +++ b/.zed/rules @@ -982,24 +982,26 @@ generation of hashing; rows of the current data context are the current entries. Operator cache — odb_v1 (OPERATOR_DB_SCHEMA_VERSION) Cached source — sdb_v1 (SOURCE_DB_SCHEMA_VERSION) -- Stored column order (ITL-1367 and ITL-1370): a stored table's column order is - the database's. ITL-1370 proposes the record id first and every other column in - ascending code-point order for a new table, through the shared - databases/utils.canonical_column_order helper. SpiralDB uses the same order. - An existing table keeps its order. An append matches exact column names when its - storage and logical types match the held ones. A table whose write schema contains - a type the append comparison does not handle keeps its first write's order when - the backend preserves that type. Delta normalizes view types before queueing, - matches merge and coerce to the queued rows by name, and uses a retrying MERGE +- Stored column order (ITL-1367 and ITL-1370). A new table is written with the record id + first and every other column in ascending code-point order through the shared + `databases/utils.canonical_column_order` helper. SpiralDB uses the same order. + An existing table keeps its order. A new table keeps its entire first-write order if + any column has a type at any depth that the append comparison cannot handle + (dictionary-encoded, view, list view, union, interval, or run-end-encoded), a column + name repeats, or the record id column is absent. Matching a later append by name + requires the comparison to confirm every field. Reordering even part of such a table + could leave the writer's own next append unmatched. ITL-1529 tracks the follow-up. + Delta normalizes view types before queueing, matches batches to the queued rows by + column name, and uses a conflict-safe MERGE with retry for every commit to an existing table (ITL-1377). A connector database trusts nothing about a stored table across calls: it aligns incoming rows only with its own pending batch and checks rows against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no table is rewritten. Every reader of stored rows presents them in its own layout, - whatever order they are stored in, through one helper, arrow_utils.in_presented_order - (the reader's layout, then any other column by name): CachedSource, DerivedSource, - the function node's stored view (_presented_layout), the operator node's stored read - (_in_row_order_on_read), the result cache (result_table_layout), the status and log - observers and ObservabilityReader. A new reader of stored rows uses it too; never + whatever order they are stored in, through one helper, `arrow_utils.in_presented_order` + (the reader's layout, then any other column by name): `CachedSource`, `DerivedSource`, + the function node's stored view (`_presented_layout`), the operator node's stored read + (`_in_row_order_on_read`), the result cache (`result_table_layout`), the status and log + observers and `ObservabilityReader`. A new reader of stored rows uses it too; never present a stored table in its stored order. - The layout version is the last component of a table path. Every layout marker starts at v1 for the first release, 0.4.0 (developer, November 18, 2026, ITL-1259; 0.3.0 was withdrawn, diff --git a/CLAUDE.md b/CLAUDE.md index 2cb299980..63cb21963 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1011,15 +1011,17 @@ current data context are the current entries. | Operator cache | `odb_v1` | `OPERATOR_DB_SCHEMA_VERSION` | | Cached source | `sdb_v1` | `SOURCE_DB_SCHEMA_VERSION` | -- **Stored column order** (ITL-1367 and ITL-1370): a stored table's column order is - the database's. ITL-1370 proposes the record id first and every other column in - ascending code-point order for a new table, through the shared +- Stored column order (ITL-1367 and ITL-1370). A new table is written with the record id + first and every other column in ascending code-point order through the shared `databases/utils.canonical_column_order` helper. SpiralDB uses the same order. - An existing table keeps its order. An append matches exact column names when its - storage and logical types match the held ones. A table whose write schema contains - a type the append comparison does not handle keeps its first write's order when - the backend preserves that type. Delta normalizes view types before queueing, - matches merge and coerce to the queued rows by name, and uses a retrying MERGE + An existing table keeps its order. A new table keeps its entire first-write order if + any column has a type at any depth that the append comparison cannot handle + (dictionary-encoded, view, list view, union, interval, or run-end-encoded), a column + name repeats, or the record id column is absent. Matching a later append by name + requires the comparison to confirm every field. Reordering even part of such a table + could leave the writer's own next append unmatched. ITL-1529 tracks the follow-up. + Delta normalizes view types before queueing, matches batches to the queued rows by + column name, and uses a conflict-safe MERGE with retry for every commit to an existing table (ITL-1377). A connector database trusts nothing about a stored table across calls: it aligns incoming rows only with its own pending batch and checks rows against the table read at flush and at a read. No hash, record id, path or layout version follows a stored column order, and no diff --git a/changelog.d/ITL-1370.md b/changelog.d/ITL-1370.md index 385304da9..2be38c815 100644 --- a/changelog.d/ITL-1370.md +++ b/changelog.d/ITL-1370.md @@ -1,16 +1,14 @@ ### Changed -- **A new stored table is written in one canonical column order** — every table Orcapod - creates in a database (a function node's pipeline and result tables, a side-effect log, - an operator cache, a cached source, an observer's status and log tables), now has the - record id column first and every other column sorted by name (by - code point: upper case, then `_`, then lower case). It used to keep the order of its first - write, which depended on how that write happened to be built. The canonical order is the +- **New stored tables use a canonical column order by default.** Orcapod writes the + record id column first and sorts every other column by name in code-point order. This + applies to a function node's pipeline and result tables, a side-effect log, an operator + cache, a cached source, and an observer's status and log tables. Tables used to keep + the order of the first write, which depended on how it was built. The canonical order is the order SpiralDB already uses for tables with a single record-id key. The change affects databases Orcapod can write. - Reading a database directly (`database.get_all_records(path)`, a Delta table opened with - Polars or `deltalake`, a SQL `SELECT *`) shows a new table's columns in the canonical - order. + Polars or `deltalake`, a SQL `SELECT *`) shows the table's stored column order. - A table stored before this change keeps its order and takes new rows in any order; a store may hold both kinds side by side. - What Orcapod shows of stored rows no longer follows the stored order at all: a job @@ -22,12 +20,15 @@ bookkeeping columns (`__…`) and the input's source-info columns now follow the outputs, by name; in an observer's tables the tag columns follow the observer's own columns by name. - - Delta merges or coerces a batch to the rows still queued by column name (it matched by - position before, so a batch in another column order was refused). - - Delta creates tables in the canonical order and uses a conflict-safe MERGE - with retry on every commit to an existing table, whatever its column order. - - A table keeps its original column order when the backend preserves a type - the append comparison does not handle, such as a dictionary. Delta normalizes - view types before applying the column order. + - Delta now matches a batch to queued rows by column name. It previously refused a + batch in another column order. Delta commits to an existing table with a + conflict-safe MERGE with retry. + - A new table keeps its entire first-write order if any column at any depth has a + type the append comparison cannot handle (a dictionary-encoded type, a view type, + a list view, a union, an interval, or a run-end-encoded type), a column name repeats, + or the record id column is absent. Matching a later append by name requires the + comparison to confirm every field. Reordering even part of such a table could leave + the writer's own next append unmatched. Delta normalizes view types before checking + the schema. ITL-1529 tracks the follow-up. - No hash, record id, stored path or layout version changes, and nothing stored is rewritten. (ITL-1370) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index d258227f5..9c0ecb297 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -68,6 +68,5 @@ not over a Delta column with no identifier and no recorded Arrow type, such as o from a dictionary of extension values, where the identity rule abstains; ITL-1372). 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 new table -is written in a canonical order since ITL-1370 (CO2), decided from -`docs/dev/specs/itl-1367-stored-column-order.md`. +another type here, and the fake keeps struct children as written): ITL-1368. ITL-1370 (CO2) +sets the [default order for new tables and its exception](../specs/itl-1367-stored-column-order.md#the-approved-order). diff --git a/docs/dev/design_issues/ITL-1370-CO2.md b/docs/dev/design_issues/ITL-1370-CO2.md index 45a5c9037..ae0218b9c 100644 --- a/docs/dev/design_issues/ITL-1370-CO2.md +++ b/docs/dev/design_issues/ITL-1370-CO2.md @@ -13,10 +13,11 @@ none of these orders (it keeps the key columns, then the value columns by name). presented a stored table in its stored order, so what a user saw depended on how the table's first write happened to be built. -**Fix:** a new table is written in the canonical order: the record id, then every other +**Fix:** by default, a new table is written in the canonical order: the record id, then every other column by name (code point), by the shared step every database calls (`databases/utils.canonical_column_order`, from `in_held_column_order` when nothing is -held). It is SpiralDB's own order. A table that exists keeps its order and takes appends +held). It is SpiralDB's own order. The [approved order and its exception](../specs/itl-1367-stored-column-order.md#the-approved-order) +are in the spec. A table that exists keeps its order and takes appends by name (CO1, ITL-1367). Every reader of stored rows presents them in its own layout through one helper, `arrow_utils.in_presented_order`: `CachedSource`, `DerivedSource`, the function node's stored view (`_presented_layout`), the operator node's stored read, the result cache diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md index 237281710..1bc395229 100644 --- a/docs/dev/specs/itl-1367-stored-column-order.md +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -1,12 +1,13 @@ -# ITL-1367 step 2 (proposal): a canonical column order for a new stored table +# ITL-1367 step 2: a canonical column order for a new stored table Status: ITL-1367 is merged and ITL-1370 implements canonical writes and reader -layouts. The exact stored order is awaiting developer approval in PR #496. +layouts. The developer approved the exact stored order in PR #496 on 2026-11-22 +and confirmed it on 2026-11-24 and 2026-11-27. The reader layouts are listed in `CLAUDE.md` under “Stored column order”. 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. +database." Step 1 implements the first half. ITL-1370 implements the second half. ## What main writes today @@ -65,18 +66,26 @@ two things per database: 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 canonical order below matches the order SpiralDB reads for a table with one +record id key. -## The proposal +## The approved order -**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. +**By default, a new table is written with the record id column first and every other +column sorted by name in code-point order.** + +A new table keeps its entire first-write order if any column at any depth has a type +the append comparison cannot handle (a dictionary-encoded type, a view type, a list +view, a union, an interval, or a run-end-encoded type), a column name repeats, or the +record id column is absent. Matching a later append by name requires the comparison +to confirm every field. Reordering even part of such a table could leave the writer's +own next append unmatched. Delta normalizes view types before checking the schema. +ITL-1529 tracks the follow-up. - **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. + the rows in the canonical order when the schema qualifies. The shared step applies the + same rule to every table kind. - **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 @@ -95,12 +104,11 @@ column sorted by name, by code point.** No other rule. ## 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`, +The rule applies to qualifying tables of every kind **created** after the change in the +in-memory, Delta, SQLite and PostgreSQL databases. A qualifying function result table +starts with the record id, followed by `__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. +and `w_out`. SpiralDB already reads single-key tables in that order. A table **already stored** keeps its order: step 1 puts every later append in the held order. Nothing is rewritten. @@ -110,13 +118,10 @@ order. Nothing is rewritten. - **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. + a function node's stored view and anything that calls `get_all_records`. ITL-1370 uses + one helper to apply each reader's presentation order (see “Stored column order” in + `CLAUDE.md`). This gives readers the same presentation for tables created before and + after the change, including SpiralDB tables. - **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 @@ -130,13 +135,11 @@ order. Nothing is rewritten. 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 +- **Layout versions:** no change. 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. + order is read as current, as it would be by a SpiralDB read today. - **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. @@ -152,11 +155,3 @@ replaces `in_held_column_order` without changing its callers. `hash_table` and 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/data-function-types.md b/docs/reference/data-function-types.md index a13aec827..520ba35a7 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -138,10 +138,9 @@ Every result table has, besides its type's record: | `__pod_ts` | `timestamp[us, tz=UTC]` | yes | when the result was stored; the newest wins when two rows share an input | | `__data_context` | `large_string` | no | the data context that wrote the row (`std:v1:default`) | -The database keeps the row's record id, a UUID of 16 bytes, as its record id column. Like -every table Orcapod creates, the table is stored with its record id first and every other -column sorted by name (see [Data types per database](database-types.md)); the declared -order above is the order the function node presents them in. +The database keeps the row's record id, a UUID of 16 bytes, as its record id column. +The result table follows the [database's stored column order rule and its exception](database-types.md). +The function node presents these columns in the declared order above. ```python stored = types_store.get_all_records(next(p for p in types_store.list_sources() if "_result" in p)) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 9d20f38e1..1ea9753f5 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -129,17 +129,22 @@ else the stored table; Delta to the rows still pending (it matches a stored tabl itself); a connector database (SQLite, PostgreSQL) 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). A new table Orcapod writes puts the record id first and sorts -every other column by name in code-point order. SpiralDB reads +queued order at a flush). By default, a new table Orcapod writes puts the record id first +and sorts every other column by name in code-point order. SpiralDB reads its key columns first and its value columns in the same name order. Orcapod cannot write SpiralDB tables through spiral-sdk yet. -With no pending rows, a new batch takes the canonical order. Delta applies that order -to a new table or one already in canonical order, and uses a conflict-safe MERGE with -retry for later commits. A table written before this change keeps its first write's -order and accepts matching rows in any column order. If the write schema contains a -type the append comparison does not handle, the ordering helper leaves the columns -in input order. Delta normalizes view types before ordering. +A new table keeps its entire first-write order if any column at any depth has a type +the append comparison cannot handle (a dictionary-encoded type, a view type, a list +view, a union, an interval, or a run-end-encoded type), a column name repeats, or the +record id column is absent. Matching a later append by name requires the comparison +to confirm every field. Reordering even part of such a table could leave the writer's +own next append unmatched. ITL-1529 tracks the follow-up. + +Delta normalizes view types before checking the write schema. It matches batches to +queued rows by column name and uses a conflict-safe MERGE with retry for commits to an +existing table. A table written before this change keeps its first-write order and +accepts matching rows in any column order. Stored column order has no effect on hashes, record IDs or stored paths. Orcapod's nodes, cached and derived sources, and observers present columns in their own order. diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 32daeea17..d6022f602 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1125,17 +1125,22 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: itself); a connector database (SQLite, PostgreSQL) 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). A new table Orcapod writes puts the record id first and sorts -every other column by name in code-point order. SpiralDB reads +queued order at a flush). By default, a new table Orcapod writes puts the record id first +and sorts every other column by name in code-point order. SpiralDB reads its key columns first and its value columns in the same name order. Orcapod cannot write SpiralDB tables through spiral-sdk yet. -With no pending rows, a new batch takes the canonical order. Delta applies that order -to a new table or one already in canonical order, and uses a conflict-safe MERGE with -retry for later commits. A table written before this change keeps its first write's -order and accepts matching rows in any column order. If the write schema contains a -type the append comparison does not handle, the ordering helper leaves the columns -in input order. Delta normalizes view types before ordering. +A new table keeps its entire first-write order if any column at any depth has a type +the append comparison cannot handle (a dictionary-encoded type, a view type, a list +view, a union, an interval, or a run-end-encoded type), a column name repeats, or the +record id column is absent. Matching a later append by name requires the comparison +to confirm every field. Reordering even part of such a table could leave the writer's +own next append unmatched. ITL-1529 tracks the follow-up. + +Delta normalizes view types before checking the write schema. It matches batches to +queued rows by column name and uses a conflict-safe MERGE with retry for commits to an +existing table. A table written before this change keeps its first-write order and +accepts matching rows in any column order. Stored column order has no effect on hashes, record IDs or stored paths. Orcapod's nodes, cached and derived sources, and observers present columns in their own order.