From e98f8b4fd500598937c41616682fbfc067281a8f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:47:17 -0800 Subject: [PATCH 1/5] fix(mappers): MapTags(drop_unmapped=True) predicts the system tags it keeps (ITL-1363) (#484) MapTags' and MapData's schema predictions filtered the whole schema by the names of name_map, so with drop_unmapped the system-tag columns (named by no name_map, kept by the table) were missing under system_tags=True/all_info=True. One rule, mappers._plan_group, now decides renames and drops over the input's user columns only; MapTags, MapData and MapColumns use it. No row, column, hash or stored path changes. Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- changelog.d/ITL-1363.md | 8 + docs/dev/design_issues/ITL-1363-MT1.md | 25 +++ src/orcapod/core/operators/mappers.py | 64 ++++-- .../test_mapper_schema_prediction.py | 202 ++++++++++++++++++ .../test_zero_row_column_order.py | 20 +- 5 files changed, 300 insertions(+), 19 deletions(-) create mode 100644 changelog.d/ITL-1363.md create mode 100644 docs/dev/design_issues/ITL-1363-MT1.md create mode 100644 tests/test_core/operators/test_mapper_schema_prediction.py diff --git a/changelog.d/ITL-1363.md b/changelog.d/ITL-1363.md new file mode 100644 index 000000000..6c19c1187 --- /dev/null +++ b/changelog.d/ITL-1363.md @@ -0,0 +1,8 @@ +### Fixed + +- **`MapTags(drop_unmapped=True)` predicts the system-tag columns it keeps** — its + predicted output schema (`output_schema(columns={"system_tags": True})`, + `output_schema(all_info=True)`) left out the system-tag columns, which the computed table + keeps, so the prediction and the rows disagreed. Every mapper (`MapTags`, `MapData`, + `MapColumns`) now renames and drops only user columns, in its prediction as in its result; + no row, column, hash or stored path changes. (ITL-1363) diff --git a/docs/dev/design_issues/ITL-1363-MT1.md b/docs/dev/design_issues/ITL-1363-MT1.md new file mode 100644 index 000000000..6e36f8bda --- /dev/null +++ b/docs/dev/design_issues/ITL-1363-MT1.md @@ -0,0 +1,25 @@ +## Cross-cutting + +### MT1 — `MapTags(drop_unmapped=True)` predicted no system-tag columns +**Status:** resolved +**Severity:** high +**Issue:** ITL-1363 + +`MapTags.unary_output_schema` kept a tag-schema key only when it was a key of `name_map` or +`drop_unmapped` was false. Under `columns={"system_tags": True}` or `all_info=True` the tag +schema holds the system-tag columns, which no `name_map` names, so the prediction left them +out while the computed table keeps them: a node, a stored table or a downstream operator +that reads the prediction expects columns the rows do not match. `MapData`'s prediction +filtered its data schema the same way (by the names of `name_map`, not by the input's user +columns); no column the data schema can hold today was affected, but the rule was the same. +The ITL-1135 sweep missed it: it had no `drop_unmapped` step. + +**Fix:** one rule, `mappers._plan_group`: only a user column (a tag, or a data column that +is not meta) is renamed or, with `drop_unmapped`, dropped; a system tag, source info, the +context or a meta column never is. `MapTags`' and `MapData`'s predictions and +`MapColumns._plan` use it. No row, column, hash or stored path changes. The ITL-1135 sweep +(`tests/test_pipeline/test_zero_row_column_order.py`) has `drop_unmapped` steps for the +three mappers and `MapColumns` steps, and +`tests/test_core/operators/test_mapper_schema_prediction.py` checks every column +configuration over every arrangement of a source with three tags and three data columns, +on the sync and the async path. diff --git a/src/orcapod/core/operators/mappers.py b/src/orcapod/core/operators/mappers.py index c4c7e4ee9..93ea6ee77 100644 --- a/src/orcapod/core/operators/mappers.py +++ b/src/orcapod/core/operators/mappers.py @@ -54,6 +54,32 @@ def _with_other_group_note( return InputValidationError(f"{error}{note}") +def _plan_group( + columns: Collection[str], name_map: Mapping[str, str], drop_unmapped: bool +) -> tuple[dict[str, str], list[str]]: + """Return the renames and the dropped columns of one group's user columns. + + The one rule every mapper's schema prediction and result follow (ITL-1363): + only a user column (a tag, or a data column that is not meta) is renamed or, + with ``drop_unmapped``, dropped. A column outside ``columns`` (a system tag, + source info, the context or a meta column) is never renamed and never + dropped, whatever ``name_map`` holds, so a prediction must not filter a whole + schema by the names of ``name_map``. + + Args: + columns: The input's user columns of the group, in order. + name_map: The mapper's renames. + drop_unmapped: Whether the user columns not in ``name_map`` are dropped. + + Returns: + The renames of the user columns ``name_map`` names, and the user columns + dropped (none without ``drop_unmapped``), in input order. + """ + renames = {c: name_map[c] for c in columns if c in name_map} + dropped = [c for c in columns if c not in name_map] if drop_unmapped else [] + return renames, dropped + + class MapData(UnaryOperator): """Rename data columns. @@ -250,12 +276,16 @@ def unary_output_schema( columns=columns, all_info=all_info ) - # Create new data schema with renamed keys + # Only the user data columns are renamed or dropped (``_plan_group``). + renames, dropped = _plan_group( + [c for c in stream.keys()[1] if not is_meta_column(c)], + self.name_map, + self.drop_unmapped, + ) new_data_schema = { - self.name_map.get(k, k): v + renames.get(k, k): v for k, v in data_schema.items() - if not k.startswith(constants.META_PREFIX) - and (k in self.name_map or not self.drop_unmapped) + if not k.startswith(constants.META_PREFIX) and k not in dropped } return tag_schema, Schema(new_data_schema) @@ -518,17 +548,20 @@ def unary_output_schema( columns=columns, all_info=all_info ) + # Only the user tags are renamed or dropped: the system tags the + # table keeps are kept here too (``_plan_group``, ITL-1363). + renames, dropped = _plan_group( + stream.keys()[0], self.name_map, self.drop_unmapped + ) new_tag_schema = { - self.name_map.get(k, k): v - for k, v in tag_schema.items() - if k in self.name_map or not self.drop_unmapped + renames.get(k, k): v for k, v in tag_schema.items() if k not in dropped } if not self.tag_only: # A data-tag's data column is renamed with it (one column). data_tags = set(stream_data_tags(stream)) data_schema = Schema( { - self.name_map.get(k, k) if k in data_tags else k: v + renames.get(k, k) if k in data_tags else k: v for k, v in data_schema.items() } ) @@ -686,16 +719,13 @@ def _plan( tag_columns: The input's tag columns, in order. data_columns: The input's user data columns, in order (no meta column). """ - tag_renames = {c: self.name_map[c] for c in tag_columns if c in self.name_map} - data_renames = {c: self.name_map[c] for c in data_columns if c in self.name_map} - if not self.drop_unmapped: - return tag_renames, data_renames, [], [] - return ( - tag_renames, - data_renames, - [c for c in tag_columns if c not in self.name_map], - [c for c in data_columns if c not in self.name_map], + tag_renames, tags_dropped = _plan_group( + tag_columns, self.name_map, self.drop_unmapped + ) + data_renames, data_dropped = _plan_group( + data_columns, self.name_map, self.drop_unmapped ) + return tag_renames, data_renames, tags_dropped, data_dropped def _validate_columns( self, tag_columns: Collection[str], data_columns: Collection[str] diff --git a/tests/test_core/operators/test_mapper_schema_prediction.py b/tests/test_core/operators/test_mapper_schema_prediction.py new file mode 100644 index 000000000..009871435 --- /dev/null +++ b/tests/test_core/operators/test_mapper_schema_prediction.py @@ -0,0 +1,202 @@ +"""A mapper's predicted schema keeps every column the result keeps (ITL-1363). + +``MapTags(drop_unmapped=True)`` used to filter its whole tag schema by the names of +``name_map``, so the system-tag columns, which no ``name_map`` names and the table +keeps, were missing from the prediction under ``system_tags=True`` or +``all_info=True``. Every mapper now renames and drops only user columns +(``mappers._plan_group``). The prediction is checked against +``static_process(...).output_schema(...)``, as CLAUDE.md asks, for every column +configuration, every arrangement of a source with three tags and three data +columns, both orders of a two-entry ``name_map``, with and without +``drop_unmapped``; the async rows carry the same system tags as the sync rows. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable +from typing import Any + +import pytest + +from orcapod import operators +from orcapod.core.operators import MapColumns, MapData, MapTags +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.errors import ProvisionalHashWarning +from orcapod.system_constants import constants + +from .several_items import ( + MAIN, + PLAIN, + Arrangement, + arrangements, + async_rows, + make_source, + rows_fingerprint, +) + +pytestmark = pytest.mark.filterwarnings( + f"ignore::{ProvisionalHashWarning.__module__}.{ProvisionalHashWarning.__name__}" +) + +# Every column configuration a schema can be asked for. +CONFIGS: tuple[dict[str, Any], ...] = ( + {}, + {"columns": {"system_tags": True}}, + {"columns": {"source": True}}, + {"columns": {"meta": True}}, + {"columns": {"context": True}}, + {"columns": {"content_hash": True}}, + {"columns": {"system_tags": True, "source": True, "meta": True}}, + {"all_info": True}, +) + + +def _orders(entries: tuple[tuple[str, str], ...]) -> list[dict[str, str]]: + return [dict(entries), dict(reversed(entries))] + + +TAG_MAP = (("t1", "u1"), ("t3", "u3")) +DATA_MAP = (("d1", "e1"), ("d3", "e3")) +COLUMN_MAP = (("t1", "u1"), ("d2", "e2")) + + +def _cases() -> list[Any]: + cases: list[Any] = [] + for drop in (False, True): + for i, name_map in enumerate(_orders(TAG_MAP)): + for tag_only in (False, True): + cases.append( + pytest.param( + ( + lambda m, d, t: ( + lambda: MapTags(m, drop_unmapped=d, tag_only=t) + ) + )(name_map, drop, tag_only), + None, + id=f"map_tags-order{i}-drop{drop}-tag_only{tag_only}", + ) + ) + for i, name_map in enumerate(_orders(DATA_MAP)): + cases.append( + pytest.param( + (lambda m, d: lambda: MapData(m, drop_unmapped=d))(name_map, drop), + None, + id=f"map_data-order{i}-drop{drop}", + ) + ) + for i, name_map in enumerate(_orders(COLUMN_MAP)): + # MapColumns is refused with data-tags (ITL-1022). + cases.append( + pytest.param( + (lambda m, d: lambda: MapColumns(m, drop_unmapped=d))( + name_map, drop + ), + (PLAIN,), + id=f"map_columns-order{i}-drop{drop}", + ) + ) + return cases + + +def _arrangement_params(roles: tuple[str, ...] | None) -> list[Arrangement]: + return arrangements(MAIN) if roles is None else arrangements(MAIN, roles) + + +def _system_tags(names: Any) -> list[str]: + return sorted(n for n in names if n.startswith(constants.SYSTEM_TAG_PREFIX)) + + +@pytest.mark.parametrize(("make", "roles"), _cases()) +def test_the_prediction_equals_the_result_schema_in_every_configuration( + make: Callable[[], StaticOutputOperatorPod], roles: tuple[str, ...] | None +) -> None: + for arrangement in _arrangement_params(roles): + source = make_source(MAIN, arrangement) + op = make() + predicted_stream = op(source) + computed = op.static_process(source) + for config in CONFIGS: + predicted = predicted_stream.output_schema(**config) + actual = computed.output_schema(**config) + label = f"{arrangement.id} {config}" + # Names and types; column order is presentation, and a source's own + # schema follows its table layout while its keys follow the tag order. + for p, a in zip(predicted, actual): + assert dict(p) == dict(a), label + # The table holds exactly the system tags the prediction lists. + predicted_tags = predicted_stream.output_schema(all_info=True)[0] + table = predicted_stream.as_table(all_info=True) + assert _system_tags(predicted_tags) == _system_tags(table.column_names) + assert len(_system_tags(predicted_tags)) == 2, arrangement.id + + +@pytest.mark.parametrize(("make", "roles"), _cases()) +def test_the_async_rows_keep_the_system_tags_of_the_sync_rows( + make: Callable[[], StaticOutputOperatorPod], roles: tuple[str, ...] | None +) -> None: + for arrangement in _arrangement_params(roles): + source = make_source(MAIN, arrangement) + op = make() + result = op(source) + sync = list(result.iter_data()) + rows = async_rows(op, source) + # Order-free: the data-column order of rows may differ between the paths. + assert rows_fingerprint(rows) == rows_fingerprint(sync) + predicted = _system_tags(result.output_schema(all_info=True)[0]) + for tag, _ in rows: + assert sorted(tag.system_tags()) == predicted, arrangement.id + + +def test_drop_unmapped_keeps_the_system_tags_in_the_prediction() -> None: + """The reported case: two tags, one renamed, the other dropped.""" + source = make_source(MAIN) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + stream = MapTags({"t2": "u2", "t1": "u1"}, drop_unmapped=True)(source) + tag_schema, _ = stream.output_schema(all_info=True) + system_tags = _system_tags(source.output_schema(all_info=True)[0]) + assert len(system_tags) == 2 + assert [n for n in tag_schema if n not in system_tags] == ["u1", "u2"] + assert _system_tags(tag_schema) == system_tags + assert _system_tags(stream.as_table(all_info=True).column_names) == system_tags + + +# ── every exported operator: predicted columns are the result's columns ────── + + +def _operator_streams() -> list[Any]: + """One case per exported operator, from the order-invariance cases.""" + from ..test_order_invariance import OPERATOR_CASES + + names = { + name + for name in operators.__all__ + if isinstance(obj := getattr(operators, name), type) + and issubclass(obj, StaticOutputOperatorPod) + } + assert names == set(OPERATOR_CASES) + return [ + pytest.param(case, id=case.label) + for cases in OPERATOR_CASES.values() + for case in cases + ] + + +@pytest.mark.parametrize("case", _operator_streams()) +def test_every_operator_predicts_the_columns_of_its_result(case: Any) -> None: + """Under every configuration the predicted column names (in order) are the + result's. Column TYPES are not compared here.""" + for role in case.roles: + sources = case.sources(role, 0, "tags_first") + op = case.build() + if not isinstance(op, StaticOutputOperatorPod): + # Rejoin's case is a function of the source: its branches are the inputs. + stream = op(*sources) + op, sources = stream.producer, list(stream.upstreams) + computed = op.static_process(*sources) + for config in CONFIGS: + predicted = op.output_schema(*sources, **config) + actual = computed.output_schema(**config) + for p, a in zip(predicted, actual): + assert list(p) == list(a), f"{case.label} {role} {config}" diff --git a/tests/test_pipeline/test_zero_row_column_order.py b/tests/test_pipeline/test_zero_row_column_order.py index dcf4e0d74..dd54ba2fa 100644 --- a/tests/test_pipeline/test_zero_row_column_order.py +++ b/tests/test_pipeline/test_zero_row_column_order.py @@ -37,6 +37,7 @@ GroupBy, Index, Join, + MapColumns, MapData, MapTags, MergeJoin, @@ -167,6 +168,17 @@ def _plus_one(x: int) -> int: "drop_columns": lambda a, g: DropColumns(["id", "l"])(a, label="op"), "map_tags": lambda a, g: MapTags({"id": "ident"})(a, label="op"), "map_data": lambda a, g: MapData({"x": "xx"})(a, label="op"), + # ``drop_unmapped`` drops user columns only, never a system tag (ITL-1363). + "map_tags_drop": lambda a, g: MapTags({"id": "ident"}, drop_unmapped=True)( + a, label="op" + ), + "map_data_drop": lambda a, g: MapData({"x": "xx", "l": "ll"}, drop_unmapped=True)( + a, label="op" + ), + "map_columns": lambda a, g: MapColumns({"id": "ident", "x": "xx"})(a, label="op"), + "map_columns_drop": lambda a, g: MapColumns( + {"id": "ident", "x": "xx"}, drop_unmapped=True + )(a, label="op"), "filter": lambda a, g: PolarsFilter(constraints={"id": 1})(a, label="op"), "drop_nulls": lambda a, g: DropNulls(["n"])(a, label="op"), "drop_nulls_all": lambda a, g: DropNulls()(a, label="op"), @@ -542,8 +554,12 @@ def test_job_node(self, step: str, pairs: int, config: str) -> None: # ── data-tags (ITL-1023) ───────────────────────────────────────────── -# Not supported with data-tags yet: MergeJoin (ITL-1018). -DATA_TAG_STEPS = [step for step in STEPS if step != "merge_join"] +# Not supported with data-tags yet: MergeJoin (ITL-1018), MapColumns (ITL-1022). +DATA_TAG_STEPS = [ + step + for step in STEPS + if step not in ("merge_join", "map_columns", "map_columns_drop") +] @pytest.fixture From 58f35c505c3c929be976eebe704e700318dba076 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:48:36 -0800 Subject: [PATCH 2/5] fix(streams): a stream's tag schema lists its tags in tag order, as keys() does (ITL-1365) (#486) * fix(streams): a stream's tag schema lists its tags in tag order, as keys() does (ITL-1365) ArrowTableStream built its tag and system-tag schemas in table-column order while keys() and the data schema follow the declared tag order. Every operator predicts from its input's output_schema(), so over a table not laid out in tag order a prediction listed the tags in another order than its result and rows (DropTagColumns(["a"]) over tags c, b, a: predicted (b, c), computed (c, b)). The schemas now follow the tag order. No row, table column order, stored table, stored path or hash changes; a job saved before loads with the same hashes (docs/dev/scripts/itl1365_tag_schema_order.py). Co-Authored-By: Claude Opus 5.5 * test(order): remove the ITL-1249 expected failures the tag-order fix resolves (ITL-1365) A declared name the table does not hold (a tag renamed into a system tag, a missing system tag) is left out of the tag schema, as before. Every unary operator's keys now equal its rows' keys, Join/SemiJoin/MergeJoin give sync and async rows one column order, and Batch presents its input's tag order: their strict xfails are removed. A demoted data-tag's placement stays expected-to-fail (ITL-1249). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- changelog.d/ITL-1365.md | 11 + docs/dev/design_issues/ITL-1365-TS1.md | 34 ++++ docs/dev/scripts/itl1365_tag_schema_order.py | 192 ++++++++++++++++++ .../core/streams/arrow_table_stream.py | 13 +- .../test_core/data_tags/test_several_items.py | 10 +- .../test_core/operators/test_several_items.py | 31 +-- tests/test_core/test_tag_schema_order.py | 192 ++++++++++++++++++ 7 files changed, 454 insertions(+), 29 deletions(-) create mode 100644 changelog.d/ITL-1365.md create mode 100644 docs/dev/design_issues/ITL-1365-TS1.md create mode 100644 docs/dev/scripts/itl1365_tag_schema_order.py create mode 100644 tests/test_core/test_tag_schema_order.py diff --git a/changelog.d/ITL-1365.md b/changelog.d/ITL-1365.md new file mode 100644 index 000000000..407db7a18 --- /dev/null +++ b/changelog.d/ITL-1365.md @@ -0,0 +1,11 @@ +### Fixed + +- **A stream lists its tags in one order** — for a table not laid out in tag order (a + source over columns `a, b, c, x` with `tag_columns=["c", "b", "a"]`), + `output_schema()` listed the tags in the table's column order while `keys()` and the + rows list them in tag order, so every operator over such a stream predicted its tags in + another order than it produced them (`DropTagColumns(["a"])` predicted `("b", "c")` and + produced `("c", "b")`). The tag schema now follows the tag order, so `output_schema()`, + `keys()`, predicted schemas and rows agree, and a saved job writes its tag schemas in + that order. No row, table column order, stored table, hash or stored path changes, and + a job saved before loads with the same hashes. (ITL-1365) diff --git a/docs/dev/design_issues/ITL-1365-TS1.md b/docs/dev/design_issues/ITL-1365-TS1.md new file mode 100644 index 000000000..5e6f8e9e9 --- /dev/null +++ b/docs/dev/design_issues/ITL-1365-TS1.md @@ -0,0 +1,34 @@ +## Cross-cutting + +### TS1 — A stream's tag schema followed its table layout, not its tag order +**Status:** resolved +**Severity:** medium +**Issue:** ITL-1365 + +`ArrowTableStream` built its tag schema (and its system-tag schema) from its table's +columns in table order, while its `keys()` list the tags in the declared tag order and its +data schema follows `keys()` too. For a table not laid out in tag order (a source over +columns `a, b, c, x` with `tag_columns=["c", "b", "a"]`), `output_schema()[0]` gave +`a, b, c` and `keys()[0]` gave `c, b, a`. Every operator predicts its schema from its +input's `output_schema()`, so its predicted `keys()` and `output_schema()` listed the +tags in another order than its computed result, its rows (sync and async) and its own +input: `DropTagColumns(["a"])` predicted `("b", "c")` and computed `("c", "b")` (192 of +1,536 cases of the reporter's sweep). It was not only `DropTagColumns`: on main almost +every unary operator's predicted keys disagreed with its rows in such a layout +(ITL-1249, symptom A). No value, row, stored table or hash differed: only the order. + +**Fix:** `ArrowTableStream.__init__` builds the tag and system-tag schemas from the tag +columns in tag order, as the data schema already followed the data columns. What +changes for a user: `output_schema()` lists the tags of such a stream (every source kind +over such a table) in tag order, and so does every prediction downstream; a saved job +writes those tag schemas in that order. What does not change, measured by +`docs/dev/scripts/itl1365_tag_schema_order.py` over every source kind and a job before +and after: rows, every table's column order, content and pipeline hashes, source ids, +stored paths and stored column order, and the golden values; a job saved before loads +with the same hashes and stored rows. Part of ITL-1249 is resolved with it, and its +strict expected failures removed: every unary operator's keys now equal its rows' keys, +`Join`, `SemiJoin` and `MergeJoin` give the sync and the async rows one column order, and +`Batch` presents its input's tag order. Left open (ITL-1249): a data-tag that loses its +tag role (`DropTagColumns`, `SelectTagColumns`, `MapTags` with `drop_unmapped` or +`tag_only`, a `GroupBy` non-key) is predicted, and sent on the async path, right after +the data-tags, but sits at its table position in the sync result. diff --git a/docs/dev/scripts/itl1365_tag_schema_order.py b/docs/dev/scripts/itl1365_tag_schema_order.py new file mode 100644 index 000000000..43fb7e81d --- /dev/null +++ b/docs/dev/scripts/itl1365_tag_schema_order.py @@ -0,0 +1,192 @@ +"""ITL-1365: what the tag-schema order fix changes, and what it does not. + +Run on two checkouts (before and after the fix) with the same output folder name in +two places, then compare the two ``summary.json`` files: + + uv run python docs/dev/scripts/itl1365_tag_schema_order.py + uv run python docs/dev/scripts/itl1365_tag_schema_order.py --load + +Every source kind is built over a table laid out ``a, b, c, x, y`` with the tags +declared ``c, b, a`` (``a`` and ``b`` data-tags), plus a raw ``ArrowTableStream``. +For each it records the keys, the ``output_schema`` order, the rows of +``as_table(all_info=True)`` (column names and values), the content and pipeline +hashes and the source id; then a job over it (``DropTagColumns``, ``MapTags`` and a +function pod, on a Delta database), run and saved: every node's hashes, every stored +table path with its column names, the saved job's text; and a standalone ``LOG`` +operator node: its stored table path and columns. With ``--load``, the job saved by +the other checkout is loaded here, against its own database, and its node hashes and +stored rows are recorded too. +""" + +from __future__ import annotations + +import json +import sqlite3 +import sys +import warnings +from pathlib import Path +from typing import Any + +import polars as pl +import pyarrow as pa +import pyarrow.csv as pacsv +from deltalake import write_deltalake + +from orcapod import function_pod +from orcapod.core.nodes import OperatorJobNode +from orcapod.core.operators import DropTagColumns, MapTags +from orcapod.core.sources import ( + ArrowTableSource, + CSVSource, + DataFrameSource, + DeltaTableSource, + DictSource, +) +from orcapod.core.sources.sqlite_table_source import SQLiteTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import DeltaTableDatabase +from orcapod.pipeline import PipelineJob +from orcapod.types import CacheMode + +warnings.simplefilter("ignore") + +TABLE = pa.table( + { + "a": pa.array([1, 2, 3], pa.int64()), + "b": pa.array(["p", "q", "r"], pa.large_string()), + "c": pa.array([7, 8, 9], pa.int64()), + "x": pa.array([0.5, 1.5, 2.5], pa.float64()), + "y": pa.array(["u", "v", "w"], pa.large_string()), + } +) +TAGS = ["c", "b", "a"] +TAG_ONLY = ["c"] + + +@function_pod(output_keys="z") +def double(x: float | None) -> float | None: + return None if x is None else 2 * x + + +def _sources(root: Path) -> dict[str, Any]: + root.mkdir(parents=True, exist_ok=True) + pacsv.write_csv(TABLE, root / "t.csv") + write_deltalake(str(root / "delta"), TABLE) + db = root / "t.sqlite" + with sqlite3.connect(db) as conn: + _ = conn.execute( + "CREATE TABLE t (a INTEGER PRIMARY KEY, b TEXT, c INTEGER, x REAL, y TEXT)" + ) + _ = conn.executemany("INSERT INTO t VALUES (:a,:b,:c,:x,:y)", TABLE.to_pylist()) + return { + "raw_stream": ArrowTableStream(TABLE, tag_columns=TAGS, data_tags=["a", "b"]), + "arrow_table": ArrowTableSource( + TABLE, tag_columns=TAGS, source_id="s", tag_only_columns=TAG_ONLY + ), + "dict": DictSource( + TABLE.to_pylist(), + tag_columns=TAGS, + source_id="s", + tag_only_columns=TAG_ONLY, + ), + "data_frame": DataFrameSource( + pl.from_arrow(TABLE), + tag_columns=TAGS, + source_id="s", + tag_only_columns=TAG_ONLY, + ), + "csv": CSVSource( + str(root / "t.csv"), + tag_columns=TAGS, + source_id="s", + schema=TABLE.schema, + tag_only_columns=TAG_ONLY, + ), + "delta": DeltaTableSource( + root / "delta", tag_columns=TAGS, source_id="s", tag_only_columns=TAG_ONLY + ), + "sqlite": SQLiteTableSource( + db, "t", tag_columns=TAGS, source_id="s", tag_only_columns=TAG_ONLY + ), + } + + +def _rows(table: pa.Table) -> dict[str, Any]: + return {"columns": table.column_names, "rows": [str(r) for r in table.to_pylist()]} + + +def _stored(database: DeltaTableDatabase) -> dict[str, Any]: + out = {} + for path in sorted(database.list_table_paths()): + table = database.get_all_records(path) + out["/".join(path)] = None if table is None else table.column_names + return out + + +def _job_nodes(job: PipelineJob) -> dict[str, Any]: + return { + label: [str(node.content_hash()), str(node.pipeline_hash())] + for label, node in sorted(job.nodes.items()) + } + + +def main(out: Path, load_from: Path | None) -> None: + summary: dict[str, Any] = {} + for kind, source in _sources(out / "inputs").items(): + entry: dict[str, Any] = { + "keys": source.keys(all_info=True), + "output_schema_order": [ + list(s) for s in source.output_schema(all_info=True) + ], + "table": _rows(source.as_table(all_info=True)), + "content_hash": str(source.content_hash()), + "pipeline_hash": str(source.pipeline_hash()), + "source_id": getattr(source, "source_id", None), + } + if kind != "raw_stream": + database = DeltaTableDatabase(out / "jobs" / kind / "db") + job = PipelineJob(name="itl1365", database=database) + with job: + dropped = DropTagColumns(["a"])(source, label="dropped") + mapped = MapTags({"b": "bb"})(dropped, label="mapped") + double.pod(mapped, label="doubled") + job.run() + job.save(out / "jobs" / kind / "job.json") + entry["job_nodes"] = _job_nodes(job) + entry["job_node_tables"] = { + label: _rows(node.as_table(all_info=True)) + for label, node in sorted(job.nodes.items()) + } + entry["stored"] = _stored(database) + entry["saved_job"] = json.loads( + (out / "jobs" / kind / "job.json").read_text() + ) + op_db = DeltaTableDatabase(out / "jobs" / kind / "opdb") + node = OperatorJobNode( + operator=DropTagColumns(["a"]), + input_streams=[source], + pipeline_database=op_db, + cache_mode=CacheMode.LOG, + ) + node.run() + entry["operator_node"] = [ + str(node.content_hash()), + str(node.pipeline_hash()), + ] + entry["operator_stored"] = _stored(op_db) + if load_from is not None: + other = load_from / "jobs" / kind + loaded = PipelineJob.load( + other / "job.json", database=DeltaTableDatabase(other / "db") + ) + entry["loaded_other_job_nodes"] = _job_nodes(loaded) + entry["loaded_other_stored_rows"] = _rows( + loaded.nodes["doubled"].as_source().as_table(all_info=True) + ) + summary[kind] = entry + (out / "summary.json").write_text(json.dumps(summary, indent=1, default=str)) + + +if __name__ == "__main__": + load = Path(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[2] == "--load" else None + main(Path(sys.argv[1]), load) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index ddac12f03..2fdc1fec6 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -197,11 +197,20 @@ def __init__( # Respect Arrow nullable flags as-is (after optional inference above): # nullable=True → T | None, nullable=False → T. + # The tag schema lists the tags in tag order, as ``keys()`` does and as the + # data schema follows ``_data_columns``; never in table layout (ITL-1365). + # A declared name the table does not hold (renamed into a system tag, or a + # system tag that is not there) is left out, as before. + names = set(self._table.column_names) tag_schema = pa.schema( - f for f in self._table.schema if f.name in self._tag_columns + self._table.schema.field(name) + for name in dict.fromkeys(self._tag_columns) + if name in names ) system_tag_schema = pa.schema( - f for f in self._table.schema if f.name in self._system_tag_columns + self._table.schema.field(name) + for name in dict.fromkeys(self._system_tag_columns) + if name in names ) all_tag_schema = arrow_utils.join_arrow_schemas(tag_schema, system_tag_schema) data_schema = pa.schema( diff --git a/tests/test_core/data_tags/test_several_items.py b/tests/test_core/data_tags/test_several_items.py index b2b5e4026..79706203d 100644 --- a/tests/test_core/data_tags/test_several_items.py +++ b/tests/test_core/data_tags/test_several_items.py @@ -145,8 +145,8 @@ def test_index_reads_a_list_valued_data_tag_as_a_data_column( first = [data[f"first_{column}"] for _, data in indexed.iter_data()] assert first == {"t1": ["b", "b"], "t3": [1, 2], "d1": [10, 40]}[column] # The data-tag itself is unchanged: still a tag and a data column, with its lists; - # Index keeps its input's tag order as its input presents it (that Batch presents - # the source's tag order is ITL-1249, below), and nothing else depends on the + # Index keeps its input's tag order as its input presents it (Batch presents + # the source's tag order, below), and nothing else depends on the # arrangement. assert presentation(indexed)[0] == presentation(batched)[0] control = Index(column, 0, out=f"first_{column}")( @@ -164,11 +164,7 @@ def test_index_reads_a_list_valued_data_tag_as_a_data_column( ) == rows_fingerprint(list(indexed.iter_data())) -@pytest.mark.xfail( - strict=True, - reason="ITL-1249: an operator presents its output tags in the input table's " - + "physical column order, not in the input stream's tag order", -) +# Resolved by ITL-1365: a stream's tag schema follows its tag order. @pytest.mark.parametrize("role", [DATA_TAGS, MIXED]) def test_batch_presents_its_input_streams_tag_order(role: str) -> None: """The source's tags are (t3, t2, t1); its table holds them as t1, t2, t3.""" diff --git a/tests/test_core/operators/test_several_items.py b/tests/test_core/operators/test_several_items.py index a24d863fd..3c7443897 100644 --- a/tests/test_core/operators/test_several_items.py +++ b/tests/test_core/operators/test_several_items.py @@ -68,7 +68,6 @@ from .several_items import ( DATA_FIRST_REVERSED, DATA_TAGS, - INTERLEAVED, LAYOUTS, MAIN, MIXED, @@ -205,8 +204,7 @@ def test_unary_async_rows_equal_sync_rows_in_every_arrangement( KEYS_XFAIL = pytest.mark.xfail( strict=True, reason=f"{COLUMN_ORDER_ISSUE}: with a table layout other than the tag order, the " - + "result's keys list the tags in the input table's physical order, its rows in " - + "tag order", + + "keys and the sync rows place a demoted data-tag differently", ) ASYNC_ORDER_XFAIL = pytest.mark.xfail( strict=True, @@ -232,12 +230,10 @@ def assert_async_column_order_equals_sync( ) -# Where the column order fails today (ITL-1249), per arrangement. In the reversed layout -# the tags sit in another order than the tag order: every unary result's keys follow -# the table (but ``DropTagColumns(["t3", "t1"])`` of plain tags leaves one tag). With -# data-tags, a tag demoted to data sits elsewhere in the sync rows than in the async -# rows, in the reversed and the interleaved layout. -KEYS_PASS = {("drop_tag_columns", PLAIN)} +# Where the column order fails today (ITL-1249), per arrangement. Since ITL-1365 a +# stream's tag schema follows its tag order, so every result's keys list the tags as its +# rows do. With data-tags, a tag demoted to data sits elsewhere in the sync rows than in +# the keys and the async rows, in the reversed and the interleaved layout. DEMOTED_DATA_TAG_CASES = { ("select_tag_columns", DATA_TAGS), ("drop_tag_columns", DATA_TAGS), @@ -249,9 +245,7 @@ def assert_async_column_order_equals_sync( def _keys_fail(label: str, role: str, layout: str) -> bool: - if layout == DATA_FIRST_REVERSED: - return (label, role) not in KEYS_PASS - return layout == INTERLEAVED and (label, role) in DEMOTED_DATA_TAG_CASES + return layout != TAGS_FIRST and (label, role) in DEMOTED_DATA_TAG_CASES def _async_order_fails(label: str, role: str, layout: str) -> bool: @@ -825,7 +819,7 @@ def _several_input_sources( return op, _sources(specs, order_index, layout, role, rows=rows) -def _several_input_params(fails_in_reversed_layout: bool) -> list[Any]: +def _several_input_params() -> list[Any]: """One parameter per several-input case, role, tag order and layout.""" return [ pytest.param( @@ -834,9 +828,6 @@ def _several_input_params(fails_in_reversed_layout: bool) -> list[Any]: order_index, layout, id=f"{label}/{role}/{order_index}/{layout}", - marks=[ASYNC_ORDER_XFAIL] - if fails_in_reversed_layout and layout == DATA_FIRST_REVERSED - else [], ) for label in SEVERAL_INPUT_CASES for role in ROLES @@ -846,7 +837,7 @@ def _several_input_params(fails_in_reversed_layout: bool) -> list[Any]: @pytest.mark.parametrize( - ("label", "role", "order_index", "layout"), _several_input_params(False) + ("label", "role", "order_index", "layout"), _several_input_params() ) def test_several_input_result_keys_equal_its_row_keys( label: str, role: str, order_index: int, layout: str @@ -855,10 +846,10 @@ def test_several_input_result_keys_equal_its_row_keys( assert_keys_equal_row_keys(op()(*sources)) -# In the reversed layout, Join, SemiJoin and MergeJoin give the sync rows the table's -# tag order and the async rows the tag order (ITL-1249). +# Join, SemiJoin and MergeJoin give the sync and the async rows one column order, also +# in the reversed layout (ITL-1249's case, resolved by ITL-1365). @pytest.mark.parametrize( - ("label", "role", "order_index", "layout"), _several_input_params(True) + ("label", "role", "order_index", "layout"), _several_input_params() ) def test_several_input_async_column_order_equals_sync( label: str, role: str, order_index: int, layout: str diff --git a/tests/test_core/test_tag_schema_order.py b/tests/test_core/test_tag_schema_order.py new file mode 100644 index 000000000..ee22a3e3e --- /dev/null +++ b/tests/test_core/test_tag_schema_order.py @@ -0,0 +1,192 @@ +"""A stream lists its tags in one order: ``keys()`` and ``output_schema()`` agree (ITL-1365). + +``ArrowTableStream`` built its tag schema in the order of its table's columns while its +``keys()`` (and its data schema) follow the declared tag order. Every operator's +predicted schema starts from its input's ``output_schema()``, so for a table not laid +out in tag order a prediction listed the tags in another order than the computed +result: ``DropTagColumns(["a"])`` over tags ``c, b, a`` predicted ``("b", "c")`` and +computed ``("c", "b")``. The tag schema now follows the tag order; no row, table, +stored column order or hash changes (``docs/dev/scripts/itl1365_tag_schema_order.py`` +compares a job before and after). + +The sweep runs every select, drop and map operator over a source with three tags and +three data columns, in every tag order and table layout, with every set of data-tags, +and compares the predicted ``keys()`` and ``output_schema()`` order with +``static_process(...)`` (CLAUDE.md's standing exception), and the tag order of the sync +and the async rows with the prediction. +""" + +from __future__ import annotations + +import itertools +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.operators import ( + DropColumns, + DropDataColumns, + DropTagColumns, + MapColumns, + MapData, + MapTags, + SelectColumns, + SelectDataColumns, + SelectTagColumns, +) +from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import ProvisionalHashWarning + +from .operators.several_items import MAIN, LAYOUTS, _layout, async_rows +from .test_order_invariance import STREAM_CASES, StreamCase + +pytestmark = [ + pytest.mark.filterwarnings( + f"ignore::{ProvisionalHashWarning.__module__}.{ProvisionalHashWarning.__name__}" + ), + pytest.mark.filterwarnings("ignore::UserWarning"), +] + +CONFIGS: tuple[dict[str, Any], ...] = ( + {}, + {"columns": {"system_tags": True}}, + {"columns": {"source": True, "meta": True, "context": True}}, + {"all_info": True}, +) + + +# ── every source and stream kind ───────────────────────────────────────────── + + +@pytest.mark.parametrize("case", STREAM_CASES, ids=lambda c: c.label) +def test_a_stream_lists_its_tags_in_keys_order( + case: StreamCase, tmp_path: Path +) -> None: + """``output_schema()[0]`` lists the tags in ``keys()[0]`` order, in every layout.""" + for n, (role, order, layout) in enumerate( + itertools.product(case.roles, range(3), LAYOUTS) + ): + folder = tmp_path / str(n) + folder.mkdir() + stream = case.build(role, order, layout, folder) + for config in CONFIGS: + label = f"{role}/{order}/{layout} {config}" + tag_keys = stream.keys(**config)[0] + assert tuple(stream.output_schema(**config)[0]) == tuple(tag_keys), label + + +def test_the_reported_case() -> None: + """Tags ``c, b, a`` over a table laid out ``a, b, c, x``; ``a`` and ``b`` data-tags.""" + table = pa.table({"a": [1, 2], "b": [3, 4], "c": [7, 8], "x": [5.0, 6.0]}) + stream = ArrowTableStream(table, tag_columns=["c", "b", "a"], data_tags=["a", "b"]) + assert tuple(stream.output_schema()[0]) == stream.keys()[0] == ("c", "b", "a") + op = DropTagColumns(["a"]) + assert op(stream).keys() == op.static_process(stream).keys() + assert op(stream).keys()[0] == ("c", "b") + + +# ── select, drop and map operators ─────────────────────────────────────────── + + +def _source(order: tuple[str, ...], layout: str, data_tags: tuple[str, ...]) -> Any: + names = _layout(MAIN, order, layout) + table = pa.table({name: MAIN.columns[name] for name in names}) + return ArrowTableSource( + table, + tag_columns=list(order), + source_id="s", + tag_only_columns=[t for t in order if t not in data_tags], + ) + + +OPERATORS: dict[str, Callable[[], StaticOutputOperatorPod]] = { + "select_tag_columns": lambda: SelectTagColumns(["t3", "t1"]), + "drop_tag_columns_one": lambda: DropTagColumns(["t1"]), + "drop_tag_columns_two": lambda: DropTagColumns(["t3", "t1"]), + "select_data_columns": lambda: SelectDataColumns(["d3", "d1"]), + "drop_data_columns": lambda: DropDataColumns(["d2"]), + "select_columns": lambda: SelectColumns(["t3", "d3", "t1", "d1"]), + "drop_columns": lambda: DropColumns(["d2", "t2"]), + "map_tags": lambda: MapTags({"t3": "u3", "t1": "u1"}), + "map_tags_drop": lambda: MapTags({"t3": "u3", "t1": "u1"}, drop_unmapped=True), + "map_tags_tag_only": lambda: MapTags({"t3": "u3", "t1": "u1"}, tag_only=True), + "map_data": lambda: MapData({"d3": "e3", "d1": "e1"}), + "map_data_drop": lambda: MapData({"d3": "e3", "d1": "e1"}, drop_unmapped=True), + "map_columns": lambda: MapColumns({"t3": "u3", "d1": "e1"}), + "map_columns_drop": lambda: MapColumns( + {"t3": "u3", "t1": "u1", "d1": "e1"}, drop_unmapped=True + ), +} +# MapColumns is refused with data-tags (ITL-1022). +PLAIN_ONLY = {"map_columns", "map_columns_drop"} + +DATA_TAG_SETS = [ + tuple(c) + for n in range(len(MAIN.tags) + 1) + for c in itertools.combinations(MAIN.tags, n) +] + + +def _demoted(stream: Any, result: Any) -> set[str]: + """Data-tags of ``stream`` that are data, but no tag, of ``result``.""" + tags, data = stream.keys() + out_tags, out_data = result.keys() + return {c for c in tags if c in data and c not in out_tags and c in out_data} + + +# MapTags(drop_unmapped=True) predicts no system tags (ITL-1363, fixed by PR 484): +# remove this mark when that fix is on main. +_ITL_1363 = pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1363: MapTags(drop_unmapped=True) predicts no system-tag columns", +) + + +@pytest.mark.parametrize( + "data_tags", DATA_TAG_SETS, ids=lambda d: "+".join(d) or "none" +) +@pytest.mark.parametrize( + "name", + [ + pytest.param(name, marks=_ITL_1363) if name == "map_tags_drop" else name + for name in OPERATORS + ], +) +def test_the_prediction_lists_the_columns_in_the_result_order( + name: str, data_tags: tuple[str, ...] +) -> None: + if name in PLAIN_ONLY and data_tags: + pytest.skip("MapColumns is refused with data-tags (ITL-1022)") + for order in MAIN.tag_orders(): + for layout in LAYOUTS: + source = _source(order, layout, data_tags) + op = OPERATORS[name]() + predicted = op(source) + computed = op.static_process(source) + label = f"{'-'.join(order)}/{layout}" + for config in CONFIGS: + p_tags, p_data = predicted.keys(**config) + c_tags, c_data = computed.keys(**config) + assert p_tags == c_tags, f"{label} {config}" + p_schema = predicted.output_schema(**config) + assert tuple(p_schema[0]) == c_tags, f"{label} {config}" + if _demoted(source, computed): + # A data-tag that loses its tag role keeps its data column at its + # table position in the result and right after the data-tags in + # the prediction (ITL-1249): the names agree here. + assert sorted(p_data) == sorted(c_data), f"{label} {config}" + else: + assert p_data == c_data, f"{label} {config}" + assert tuple(p_schema[1]) == c_data, f"{label} {config}" + # The rows, sync and async, list their tags in the predicted order. + tags = predicted.keys()[0] + for tag, _ in computed.iter_data(): + assert tuple(tag.keys()) == tags, label + for tag, _ in async_rows(op, source): + assert tuple(tag.keys()) == tags, label From fc1df4204c3332042b6138b424308c874d2a10c2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 16:50:25 -0800 Subject: [PATCH 3/5] fix(databases): every database matches an appended table's columns by name (ITL-1367) (#491) * 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 * 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 * 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 * 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 * 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 * 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 --------- Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- changelog.d/ITL-1367.md | 18 + docs/dev/design_issues/ITL-1367-CO1.md | 71 ++ .../scripts/itl_1367_stored_column_orders.py | 96 ++ .../dev/specs/itl-1367-stored-column-order.md | 163 +++ docs/reference/database-types.md | 17 + .../databases/connector_arrow_database.py | 91 +- src/orcapod/databases/delta_lake_databases.py | 9 + src/orcapod/databases/in_memory_databases.py | 16 +- src/orcapod/databases/utils.py | 137 ++- .../data_function/test_function_record.py | 46 +- tests/test_databases/fake_pyspiral.py | 10 +- tests/test_databases/test_append_by_name.py | 1079 +++++++++++++++++ .../test_spiraldb_connector_fake.py | 15 +- .../test_spiraldb_connector_integration.py | 81 ++ tests/test_databases/type_matrix.py | 17 + 15 files changed, 1838 insertions(+), 28 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..91d6d79ae --- /dev/null +++ b/changelog.d/ITL-1367.md @@ -0,0 +1,18 @@ +### Fixed + +- **An append matches columns by name in every database** — appending rows whose columns + are the table's columns in another order was refused by the in-memory database, by Delta + and SQLite while the earlier rows were still pending, and by the SpiralDB test fake, so a + job node that produced the same columns in another order than an earlier write could not + store them. Every database (in-memory, Delta, SQLite, PostgreSQL, SpiralDB) now puts such + rows in the order the table already has (the in-memory database: the rows still pending, + else the stored table; Delta: the rows still pending, since it already matched a stored + table by name; a connector database: the rows it has pending, and the stored table as it + is when it writes or reads them, after main's own check), after a flush and within one + pending batch alike. Only an append whose every field equals the held one is reordered + (the same type at every depth, the same logical type, the same field attributes); names + are matched exactly (`a` and `A` are two columns), and values are never matched by + position. A table keeps the column order its database gave the first write (SpiralDB + orders a table's columns its own way: the key columns, then the other columns by name). + An append that also adds, omits or retypes a column, and a struct whose fields are in + another order, keep each database's own rule. (ITL-1367) diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md new file mode 100644 index 000000000..40c7d996b --- /dev/null +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -0,0 +1,71 @@ +## `src/orcapod/databases/` — column order of appended tables + +### CO1 — Databases refuse an append whose columns are in another order than the stored or pending table +**Status:** resolved +**Severity:** medium +**Issue:** ITL-1367 + +An append whose columns were the table's columns in another order was handled differently +by each database (measured on main 321284ae: two rows `rid, a, c, b`, then two rows +`b, c, rid, a`, with `a` and `c` both `int64`). The in-memory database refused it, after a +flush and within one pending batch. Delta matched it by name after a flush and refused it +within a pending batch. The connector database over SQLite did the same as Delta. The +SpiralDB fake refused it in both cases. No database swapped values by position, but the +column order of a stored table was in effect part of its schema: a job node that produced +the same columns in another order than an earlier run, or than an earlier batch of the same +run, could not store them, although no hash depends on column order. + +Live SpiralDB was measured (2026-11-22): it accepts a write in another order and matches it +by name, and it keeps a column order of its own whatever the order written: the key +columns in key-schema order, then the value columns sorted by name (code point: `B`, `C`, +`a`), struct children sorted by name too. The fake refused what SpiralDB accepts and kept +the written order. + +**Fix:** one shared step, `databases/utils.in_held_column_order`. When rows have exactly +the held columns in another order, and each field equals the held field of its name, the +rows are put in the held order, by name. Equal is one rule (`_same_field`): the same type +at every depth in the large variants, a logical (extension) type equal only to its own +name and metadata at any depth, and no change the ITL-1334 append check reports +(`appended_field_change`: field metadata and nested field attributes). Names match exactly +(`a` and `A` are two columns). Anything else is left exactly as given, so each database's +own rule applies as before. + +Where it runs, and against what: + +- In-memory: when rows are queued, against the batch pending for the table, else the + stored table (main refused both). +- Delta: when rows are queued, against the batch pending for the table only (main refused + a permutation of a pending batch; a stored table already takes an append by name, + through delta-rs). The pending batch is left exactly as main would hold it, so main's + commit selection, schema handling and requeue run unchanged. +- The connector database (SQLite, PostgreSQL, SpiralDB): when rows are queued, against the + batch it has pending only. Nothing about a stored table is trusted across calls: a flush + looks the table up then (main's own lookup), checks the queued rows by exact name and + type as main does, and only then puts them in the stored order (the flush compares the + connector's column info, which carries no field metadata: a column with field metadata + stays in its queued order, which SpiralDB, the connector that keeps field metadata, + matches by name itself); a read that combines stored and queued rows matches them to + the rows it reads, and takes a column nullable when either side declares it nullable + (PostgreSQL reads its key back NOT NULL; arrays re-wrapped, never cast). A point + lookup of a queued row answers from memory, as main does. + +Pre-existing on main and out of scope: two Delta writers appending one new record id can +both store it through the fast-path append (ITL-1377). + +A table keeps the order its database gave the first write (SpiralDB: its own order). The +SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores +the key columns, then the value columns by name. Tests: +`tests/test_databases/test_append_by_name.py`; live: `TestColumnOrderLive` in +`tests/test_databases/test_spiraldb_connector_integration.py`. + +Pre-existing on main and equal here, not changed: another connection that changes a SQLite +table between the flush's check and its write (a DDL in that window) is not seen; a rename +of `a` to `A` then stores the value under `A`, since SQLite resolves names without case, as +on main. Through `ExtensionAwareDatabase`, rows of another logical type over the same +storage type in the SAME column order are accepted and read back as the held logical type +(ITL-1371). + +Not covered: the order of a struct's fields (a struct with its fields in another order is +another type here, and the fake keeps struct children as written): ITL-1368. A canonical +order for a new table is a proposal awaiting the developer's decision: +`docs/dev/specs/itl-1367-stored-column-order.md`. diff --git a/docs/dev/scripts/itl_1367_stored_column_orders.py b/docs/dev/scripts/itl_1367_stored_column_orders.py new file mode 100644 index 000000000..c5d882b6c --- /dev/null +++ b/docs/dev/scripts/itl_1367_stored_column_orders.py @@ -0,0 +1,96 @@ +"""ITL-1367: the column order of each stored table kind as main writes it today. + +A job over one source with two tags (``z_tag``, ``a_tag``, declared in that order) and two +data columns (``y``, ``b``) runs a function pod, an operator node that logs (a ``Join``), +a cached source and a side-effect pod against an in-memory database that records the column order of +every ``add_records`` call, by table path. Input for the step 2 proposal +(``docs/dev/specs/itl-1367-stored-column-order.md``). + +Run: ``uv run python docs/dev/scripts/itl_1367_stored_column_orders.py`` +""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import InMemoryArrowDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +SEEN: dict[tuple[str, ...], list[str]] = {} + + +_add_records = InMemoryArrowDatabase.add_records + + +def _recording_add_records( + self: InMemoryArrowDatabase, + record_path: tuple[str, ...], + records: pa.Table, + *args: Any, + **kwargs: Any, +) -> None: + """``add_records``, recording each table's column order as first written.""" + SEEN.setdefault(self.base_path + tuple(record_path), records.column_names) + _add_records(self, record_path, records, *args, **kwargs) + + +# Every view (``at``) of the database records too: the method is replaced on the class. +setattr(InMemoryArrowDatabase, "add_records", _recording_add_records) # noqa: B010 + + +def _source(name: str, data: list[str]) -> ArrowTableSource: + fields = [ + pa.field("z_tag", pa.large_string(), nullable=False), + pa.field("a_tag", pa.int64(), nullable=False), + *(pa.field(n, pa.float64(), nullable=False) for n in data), + ] + arrays = [ + pa.array(["s1", "s2"], pa.large_string()), + pa.array([1, 2], pa.int64()), + *(pa.array([1.0, 2.0], pa.float64()) for _ in data), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + source_id=name, + ) + + +@function_pod(output_keys=["w_out", "c_out"]) +def compute(y: float, b: float) -> tuple[float, float]: + return y + b, y - b + + +def notify(ctx: Any, y: float, b: float) -> None: + return None + + +def main() -> None: + database = InMemoryArrowDatabase() + job = PipelineJob(name="itl1367", database=database) + cached = CachedSource(_source("left", ["y", "b"]), cache_database=database) + with job: + left = cached + right = _source("right", ["x", "e"]) + compute.pod(left, label="fn") + Join()(left, right, label="joined") + SideEffectPod(notify)(left, label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + for path, names in sorted(SEEN.items()): + print("/".join(p[:40] for p in path)) + print(" ", names) + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md new file mode 100644 index 000000000..763b978df --- /dev/null +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -0,0 +1,163 @@ +# ITL-1367 step 2 (proposal): a canonical column order for a new stored table + +Status: **proposal, not implemented.** It changes the stored form of every table kind, so +the developer decides. Step 1 (ITL-1367, this pull request) is implemented: an append whose +columns are the held table's columns in another order is put in the held order by every +database, and a table keeps the order its database gave its first write. + +The developer's decision (2026-11-22): "We should always try to save to match the existing +database order if already present, but if not yet, then use canonicalized order for new +database." Step 1 is the first half. This document proposes the second half. + +## What main writes today + +Measured with `docs/dev/scripts/itl_1367_stored_column_orders.py`: a job over a source with +two tags declared `z_tag, a_tag` and two data columns `y, b`, running a function pod, a +logging `Join` node, a cached source and a side-effect pod. The order of each table's first +write (system-tag hashes shortened): + +| Table kind | Layout | Order written today | +|---|---|---| +| Function pipeline | `pdb_v1` | `__record_id`, `z_tag`, `a_tag`, `_tag_source_id::…`, `_tag_record_id::…`, `_source_y`, `_source_b`, `__data_id`, `__node_content_hash`, `__input_data_hash`, `__output_data_hash`, `__data_context`, `__computed`, `__is_ephemeral`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index` | +| Function result | `rdb_v1` | `__record_id`, `__input_data_hash`, `__pf_var_*` (6), `__pf_exec_*` (4), `w_out`, `c_out`, `_source_w_out`, `_source_c_out`, `__pod_ts`, `__data_context` | +| Side-effect log | `tdb_v1` | `__record_id`, `record_id_hash`, `pipeline_run_id`, `executed_at`, `__data_context` | +| Operator cache | `odb_v1` | `_record_hash`, `z_tag`, `a_tag`, system tags (input 0, then input 1), `y`, `b`, `x`, `e`, `_source_y`, `_source_b`, `_source_x`, `_source_e`, `__node_content_hash`, `__data_context` | +| Cached source | `sdb_v1` | `_record_hash`, `z_tag`, `a_tag`, `y`, `b`, system tags, `_source_y`, `_source_b`, `__data_context` | + +(The record id column is renamed to `__record_id` inside every database; `_record_hash` +is the caller's name for it.) + +Two things follow. The user columns follow the declared tag order and the table layout +(`z_tag` before `a_tag`), which the rule that order never counts (ITL-1271) allows only as +presentation; and the kinds disagree with each other (the cached source puts data before +the system tags, the operator cache after). SpiralDB stores none of these orders: it keeps +the key column, then the other columns by name. + +## SpiralDB already imposes an order + +Measured live (2026-11-22, workload account, throwaway tables, dropped): SpiralDB accepts a +write in any column order, matches it by name, and stores and reads the table as the key +columns in key-schema order, then the value columns sorted by name by code point (`B`, +`C`, `a`), whatever the order written. A later append in another order changes nothing; an +added column takes its place by name. Struct children are sorted by name too. + +The evidence, two live sessions as the agent workload on the test project, every table a +throwaway one dropped at the end (the final listing showed none left). Each probe wrote +with pyspiral's `Table.write` (or `SpiralDBConnector.upsert_records`), then read the +table's schema (`Table.schema()`) and its rows (`SELECT *` through the connector): + +| Probe | Written | Schema and rows read back | +|---|---|---| +| 1. one key `k`, then appends in other orders | first `k, z, a, m`; then `m, k, a, z`; then `b, k, z, a, m` (adds `b`) | `k, a, m, z` after the first write and after the reordered append, values by name (`z` = 1 and 11, `a` = 2 and 12); `k, a, b, m, z` after the append that adds `b` | +| 2. names in mixed case | `k, B, a, C` | `k, B, C, a`: code point order, uppercase first | +| 3. composite key declared `(k2, k1)` | `y, k1, b, k2` | `k2, k1, b, y`: the keys in key-schema order (not by name), then the values by name | +| 4. a struct column | `s: struct`, then an append with `s: struct` | `s: struct` both times; values by child name (`a` = 2 and 12, `z` = 1 and 11) | + +The first session also wrote `__record_id, a, c, b` and then, through the connector's own +`upsert_records` with no reordering by Orcapod, `b, c, __record_id, a`: accepted, read back +as `__record_id, a, b, c` with every value under its own name. Through +`ConnectorArrowDatabase` with step 1, three orders read back the same way. + +So an order Orcapod chooses cannot be what SpiralDB physically stores. "Canonical" can mean +two things per database: + +- **the order Orcapod writes** (the order of the first `add_records` that creates the + table): in-memory, Delta, SQLite and PostgreSQL store it as written, so for them it is + also the order a read returns; +- **the order a read returns**: for SpiralDB, always SpiralDB's own. + +The proposal below makes the two meanings coincide in all five databases. + +## The proposal + +**A new table's columns are written in this order: the record id column, then every other +column sorted by name, by code point.** No other rule. + +- **Where:** in the database, in the shared step of step 1 + (`databases/utils.in_held_column_order`): with no held table (`held is None`), it returns + the rows in the canonical order instead of as given. Its callers do not change. The + database is the one place that sees every write of every table kind, so no table kind can + be forgotten, and a future table kind gets the rule without doing anything. +- **Why not role groups (record id, user tags, system tags, data, source info, meta):** a + database does not know a tag from a data column, so a role-grouped order can only be + produced by each caller (five table kinds, each building its table its own way, plus every + future one). Within a group the order would still have to be by name, since the declared + tag order may not count. Prefix groups that a database could see (`_tag_`, `_source_`, + `__`) do not separate user tags from data. Sorting every column by name is the one order + every database can apply alone, and it is SpiralDB's order (the record id is SpiralDB's + only key column in every Orcapod table), so all five databases then store and read the + same order. +- **Code point:** Python's `sorted` on `str`, the order SpiralDB was measured to use + (uppercase before `_` before lowercase). Names that differ in case only are one + column to SQLite, which resolves names without case; the PostgreSQL connector quotes + every name, so it should keep them apart (not measured); the in-memory and Delta + databases keep them apart. Code point order is total, so the order is decided either + way. + +## Which stored tables change + +Every table **created** after the change, of every kind in the table above, in the +in-memory, Delta, SQLite and PostgreSQL databases: each is written in an order no table +kind uses today (the record id, then for example `__data_context`, `__input_data_hash`, +`__pf_exec_…`, `__pf_var_…`, `__pod_ts`, `_source_c_out`, `_source_w_out`, `c_out`, +`w_out` for a function result table). SpiralDB tables change in nothing: they are read in +that order already. + +A table **already stored** keeps its order: step 1 puts every later append in the held +order. Nothing is rewritten. + +## What else changes + +- **Readers that present stored rows in the stored order.** An operator node puts a stored + read in row order (`_in_row_order_on_read`). Others present the stored order as it is: + `CachedSource` (its stream is the cache read), `DerivedSource` (a node's stored records), + a function node's stored view and anything that calls `get_all_records`. Under the + proposal their column order would change (presentation only, but visible, and different + for a table created before the change and one created after). The proposal therefore + includes one helper that puts a stored read in row order (user tags, system tags, data, + source info; CLAUDE.md, "Important implementation details"), used by every reader, so + what a reader presents never depends on the stored order. On SpiralDB this is already + needed today. +- **The ITL-1347 differential** (`docs/dev/scripts/itl_1347/`, on the job-speed branch): + its `exact` mode compares stored tables column order included + (`compare.py`, `_schema_differences`: `column order: …`). A run of the branch against + pinned main would report every stored table created in the run. It would need stored + tables compared with columns matched by name (the `set` mode's `select(sorted(...))`, rows + still compared in order), while node tables (what a node keeps and presents) keep their + column order comparison, once the readers above present row order. +- **Golden values and paths:** none should move. No hash reads a stored table's column + order: a schema enters an identity through `hash_schema`, which ignores column order + (ITL-640); a row's hashes are built from its values by name; a path is built from + identities, never from a stored table's layout; record ids are built before a row is + written. The golden check (`generate_golden_hashes.py --check`) and the differential's + `set` mode are the evidence to collect when it is implemented. +- **Layout versions:** recommended none. A layout version moves when a table kind's + columns are added, renamed or retyped (CLAUDE.md, "Stored tables"), because a reader of + the old layout would misread the new one. Here no column changes, every read is by name, + and step 1 lets old and new tables take appends in any order. A table written in the old + order is read as current, as it would be by a SpiralDB read today. The developer may + still prefer a new marker so that a table's order tells its generation; it would move + every stored path, which nothing else here needs. +- **Data function type snapshots** (`src/orcapod/data_function_types/`) list a type's + record columns; the list is the declaration, not the stored order, and does not change. + +## Struct fields (input for ITL-1368) + +The same rule extends to struct fields at every depth: a new table's struct columns are +written with their children sorted by name (code point), recursively through lists, maps +and structs, which is again what SpiralDB was measured to store. An append would match a +struct's children by name, as step 1 matches top-level columns, so the recursive step +replaces `in_held_column_order` without changing its callers. `hash_table` and +`hash_schema` already leave struct field order out (`hashing/arrow_hashers.py`), but +`hash_table_ordered` (the pandas value hash, `arrow_ordered_v1`) includes it, and a struct +value may reach the semantic hasher in field order: ITL-1368 has to establish first +whether any hash depends on it, and a struct whose fields are reordered on write must read +back, and hash, as its type declares. + +## Decision needed + +1. Adopt the canonical order (record id, then every column by name, code point) for new + tables, in the database's shared step? Or a role-grouped order built by each caller? +2. Readers put stored reads in row order (one helper), so presentation never follows the + stored order? +3. No layout version change? diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 1b668112e..9819e3cfb 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,6 +81,23 @@ would add a non-nullable struct field (the stored rows have no value for it) or struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. +An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two +columns), never by position. Rows whose columns are the held table's columns in another +order, each field equal to the held one (the same type at every depth, the same logical +type, the same field attributes), are put in the held order, whether the table was +flushed in between or not. The in-memory database matches them to the rows still pending, +else the stored table; Delta to the rows still pending (it matches a stored table by name +itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, +and to the stored table when it writes or reads them, checking them first against the +table as it is then, by exact name and type (a column with field metadata stays in its +queued order at a flush; SpiralDB, which keeps field metadata, matches a write by name +itself). A table keeps the column +order the database gave its first write: the first write's order, except in SpiralDB, +which stores and reads a table's key columns first and then its other columns sorted by +name, whatever the order written (measured on SpiralDB itself). An append that also +adds, omits or retypes a column keeps each database's own rule. The order of a struct's +fields is not covered: a struct whose fields are in another order is another type here. + ## Integer | Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index e17ebeada..761486310 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -26,6 +26,7 @@ from orcapod.databases.utils import ( coerce_record_id, first_changed_column, + in_held_column_order, ) from orcapod.errors import ( InputValidationError, @@ -56,6 +57,36 @@ def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: ] +def _alike(parts: list[pa.Table]) -> list[pa.Table]: + """Stored and queued rows under one schema when they differ only in a column's + nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary + key) that the queued rows declare nullable. Each such field is nullable when + either side's is, and the arrays are re-wrapped under it, never cast. Any other + difference is left for ``pa.concat_tables`` to refuse, as before.""" + first = parts[0].schema + if any(part.schema.names != first.names for part in parts): + return parts + fields = [] + for i, field in enumerate(first): + others = [part.schema.field(i) for part in parts[1:]] + loose = field.with_nullable(True) + if not all( + other.with_nullable(True).equals(loose, check_metadata=True) + for other in others + ): + return parts + fields.append( + field.with_nullable(field.nullable or any(o.nullable for o in others)) + ) + schema = pa.schema(fields, metadata=cast(Any, first.metadata)) + return [ + part + if part.schema.equals(schema, check_metadata=True) + else pa.Table.from_arrays(part.columns, schema=schema) + for part in parts + ] + + class ConnectorArrowDatabase: """Generic ``ArrowDatabaseProtocol`` implementation backed by a ``DBConnectorProtocol``. @@ -408,6 +439,10 @@ def add_records( self._connector.validate_records(records) record_key = self._get_record_key(record_path) + # Columns match by name: rows with the held columns in another order are + # put in the held order, so the connector always receives the stored order + # (ITL-1367). + records = in_held_column_order(records, self._held_column_order(record_path)) self._refuse_changed_columns(record_path, records.schema) records = self._deduplicate_within_table(records) @@ -454,6 +489,36 @@ def add_records( if flush: self.flush() + def _held_column_order( + self, record_path: tuple[str, ...] + ) -> "list[pa.Field[Any]] | None": + """The columns of the batch pending for the table, in its order, or ``None``. + + An append is aligned when it is queued only to rows this handle queued + (ITL-1367): nothing about a stored table is trusted across calls, since + another connection may rename, add, drop, retype or create again a column + between two calls. The stored table is looked up fresh where queued and + stored rows meet, a flush (``_stored_columns``, main's own lookup) and a read + that combines them (the rows it reads), and the queued rows are matched to it + there, by name, after the flush's own check. A point lookup of a queued row + answers from memory, as main does. + """ + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + return list(pending.schema) + return None + + def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": + """The stored table's columns as the connector reports them now, in its order + (``get_column_info``, large-normalized types), or ``None`` when it does not + exist. Never remembered: each call asks the connector.""" + if table_name not in self._connector.get_table_names(): + return None + return [ + pa.field(c.name, normalize_to_large_types(c.arrow_type, keep_null=True)) + for c in self._connector.get_column_info(table_name) + ] + def _refuse_changed_columns( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -565,14 +630,13 @@ def flush(self) -> None: # names and Arrow types match before writing. Schema evolution is # intentionally out of scope; a clear ValueError is preferable to a # cryptic DB-level error or a silent partial write. - existing_table_names = self._connector.get_table_names() - if table_name in existing_table_names: + # Looked up now, as the check needs: nothing about the stored table is + # trusted from an earlier call (ITL-1367). + existing = self._stored_columns(table_name) + if existing is not None: # A connector reads text and binary back in their large variants, # which are the same types (ITL-1162). - existing_cols = { - c.name: normalize_to_large_types(c.arrow_type, keep_null=True) - for c in self._connector.get_column_info(table_name) - } + existing_cols = {f.name: f.type for f in existing} pending_cols = { c.name: normalize_to_large_types(c.arrow_type, keep_null=True) for c in columns @@ -593,6 +657,10 @@ def _fmt(cols: dict) -> str: "Schema evolution is not supported." ) + # Checked by exact name and type above: only then are the rows put + # in the stored order, by name (ITL-1367). + pending = in_held_column_order(pending, existing) + self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) @@ -646,11 +714,20 @@ def get_all_records( parts.append(committed) pending = self._pending_batches.get(record_key) if pending is not None and pending.num_rows > 0: + # Matched to the stored rows just read, by name (ITL-1367). + if committed is not None: + pending = in_held_column_order( + pending, + [ + f.with_type(normalize_to_large_types(f.type, keep_null=True)) + for f in committed.schema + ], + ) parts.append(pending) if not parts: return None - table = parts[0] if len(parts) == 1 else pa.concat_tables(parts) + table = parts[0] if len(parts) == 1 else pa.concat_tables(_alike(parts)) return self._handle_record_id_column(table, record_id_column) def get_records_by_ids( diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 827d78ea5..cbf6e2831 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -19,6 +19,7 @@ from orcapod.databases.utils import ( appended_field_change, coerce_record_id, + in_held_column_order, metadata_bytes, ) from orcapod.errors import ( @@ -1892,6 +1893,14 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table + # Columns match by name within a pending batch: rows with the pending + # batch's columns in another order, each field equal, are put in its order + # (ITL-1367). Only the pending batch: a stored table already takes an append + # by name (delta-rs), and the batch is left exactly as main holds it. + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is not None: + filtered_table = in_held_column_order(filtered_table, list(pending.schema)) + # Step 4: the rows' field attributes, compared as given: a merge or a # coercion casts them to the pending batch's schema, which would give them # its field metadata and nested attributes instead (ITL-1334). diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 92fca521a..3c78dd1e0 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -6,7 +6,11 @@ from typing import TYPE_CHECKING, Any, cast from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows -from orcapod.databases.utils import coerce_record_id, first_changed_column +from orcapod.databases.utils import ( + coerce_record_id, + first_changed_column, + in_held_column_order, +) from orcapod.errors import InputValidationError from orcapod.utils.lazy_module import LazyModule @@ -254,6 +258,16 @@ def add_records( ) record_key = self._get_record_key(record_path) + # Columns match by name: rows with the held columns in another order are + # put in the held order, the pending batch's, else the stored table's + # (ITL-1367). + held_table = self._pending_batches.get(record_key) + if held_table is None: + held_table = self._tables.get(record_key) + records = in_held_column_order( + records, + None if held_table is None else list(held_table.schema), + ) # The table holds one type per column: rows whose field metadata or nested # field attributes differ would read back with the held ones (ITL-1334). held = [ diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 8cd9f0018..17018eb43 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -3,7 +3,7 @@ from __future__ import annotations import re -from collections.abc import Iterable, Mapping +from collections.abc import Iterable, Mapping, Sequence from typing import TYPE_CHECKING, Any, cast from orcapod.utils import arrow_utils @@ -201,3 +201,138 @@ def first_changed_column( if reason is not None: return field.name, reason return None + + +def in_held_column_order( + records: "pa.Table", held: "Sequence[pa.Field[Any]] | None" +) -> "pa.Table": + """``records`` with its columns in the order the database holds them (ITL-1367). + + An append matches columns by name, never by position: when ``records`` has + exactly the held columns in another order, and each of its fields equals the held + field of its name, its columns are put in the held order. Equal is one rule + (``_same_field``): the same type at every depth (in the large variants, a logical + type with its own name and metadata, at any depth) and no change the append + check reports (``appended_field_change``: field metadata and nested field + attributes at every depth). Names are matched exactly, as Arrow matches them: + ``a`` and ``A`` are two columns. + + Anything else is returned exactly as given, so the database's own rule applies + as before: no held table, a column added or missing, a field that differs in any + way (a struct whose children are in another order included: ITL-1368), a name that + repeats. + + Args: + records: The rows to append, the record id column already named as held. + held: The held columns, in the held order, or ``None`` when nothing is held. + + Returns: + ``records``, reordered or as given. + """ + if held is None: + return records + names = records.column_names + held_names = [field.name for field in held] + if names == held_names: + return records + if len(set(names)) != len(names) or len(set(held_names)) != len(held_names): + return records + if set(names) != set(held_names): + return records + held_fields = {field.name: field for field in held} + if not all(_same_field(field, held_fields[field.name]) for field in records.schema): + return records + return records.select(held_names) + + +def _same_field(given: "pa.Field[Any]", held: "pa.Field[Any]") -> bool: + """Whether rows of ``given`` would be held as ``held`` holds them: the same type at + every depth, in the large variants (a logical type is equal only to itself: its + name, metadata and storage), and no change ``appended_field_change`` reports.""" + # Eligibility is decided on the types as given, before normalization turns a + # view type into its large variant. + if not (_handled(given.type) and _handled(held.type)): + return False + large = arrow_utils.normalize_to_large_types + if not _same_type( + large(given.type, keep_null=True), large(held.type, keep_null=True) + ): + return False + return appended_field_change(held, given) is None + + +def _handled(arrow_type: Any) -> bool: + """Whether every type in ``arrow_type``'s tree is one the comparison handles + (``_same_type``): a leaf kind of ``_LEAF_KINDS``, a struct, a map, a list, large + list or fixed-size list, or an extension type over those.""" + t = pa.types + if isinstance(arrow_type, pa.ExtensionType): + return _handled(arrow_type.storage_type) + if t.is_struct(arrow_type): + return all( + _handled(arrow_type.field(i).type) for i in range(arrow_type.num_fields) + ) + if t.is_map(arrow_type): + return _handled(arrow_type.key_type) and _handled(arrow_type.item_type) + if ( + t.is_list(arrow_type) + or t.is_large_list(arrow_type) + or t.is_fixed_size_list(arrow_type) + ): + return _handled(cast(Any, arrow_type).value_type) + return any(getattr(t, kind)(arrow_type) for kind in _LEAF_KINDS) + + +_LEAF_KINDS = ( + "is_null", + "is_boolean", + "is_integer", + "is_floating", + "is_decimal", + "is_string", + "is_large_string", + "is_binary", + "is_large_binary", + "is_fixed_size_binary", + "is_date", + "is_time", + "is_timestamp", + "is_duration", +) +"""The leaf types the comparison handles. Eligibility is positive: a type of any +other kind anywhere in a column's tree (a list view, a union, a dictionary, a +run-end-encoded type, an interval, a view type, anything pyarrow adds later) makes +the column not eligible, and the table is left as given for the database's own +rule (codex review of PR 491, round 4).""" + + +def _same_type(given: Any, held: Any) -> bool: + """Whether two Arrow types are equal at every depth, for a type tree the + comparison handles entirely: the leaf kinds of ``_LEAF_KINDS``, a struct, a map, + a list, large list or fixed-size list, and an extension type over those, equal + only to one of its own name and serialized metadata (pyarrow compares a Python + extension type by its class and storage, not by its metadata). Any other type + anywhere in either tree gives ``False``.""" + t = pa.types + if isinstance(given, pa.ExtensionType) or isinstance(held, pa.ExtensionType): + return ( + isinstance(given, pa.ExtensionType) + and isinstance(held, pa.ExtensionType) + and given.extension_name == held.extension_name + and given.__arrow_ext_serialize__() == held.__arrow_ext_serialize__() + and _same_type(given.storage_type, held.storage_type) + ) + if given != held: + return False + if t.is_struct(given): + return all( + _same_type(given.field(i).type, held.field(i).type) + for i in range(given.num_fields) + ) + if t.is_map(given): + return _same_type(given.key_type, held.key_type) and _same_type( + given.item_type, held.item_type + ) + if t.is_list(given) or t.is_large_list(given) or t.is_fixed_size_list(given): + return _same_type(cast(Any, given).value_type, cast(Any, held).value_type) + return any(getattr(t, kind)(given) for kind in _LEAF_KINDS) diff --git a/tests/test_core/data_function/test_function_record.py b/tests/test_core/data_function/test_function_record.py index 41a210e73..6c5819ad8 100644 --- a/tests/test_core/data_function/test_function_record.py +++ b/tests/test_core/data_function/test_function_record.py @@ -461,24 +461,21 @@ def test_a_function_without_source_works_in_a_job_and_stores_a_null( @pytest.mark.parametrize( - "database_kind", - [ - pytest.param( - "in_memory", - marks=pytest.mark.xfail( - strict=True, - reason="ITL-1263: InMemoryArrowDatabase refuses rows whose columns " - + "are in another order than the stored table", - ), - ), - "delta", - ], + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] ) +@pytest.mark.parametrize("database_kind", ["in_memory", "delta"]) @pytest.mark.parametrize("name", ["same2", "same3"]) def test_swapped_same_typed_keys_store_different_signature_hashes( - name: str, database_kind: str, tmp_path: Path + name: str, database_kind: str, orchestrator: type, tmp_path: Path ) -> None: - """One uri, one result table; each order's rows record their own signature.""" + """One uri, one result table; each order's rows record their own signature. + + The orders write the output columns (and their source-info columns) in other + orders into one result table: every database matches them by name (ITL-1263, + ITL-1367), on the sync and the async path. ``same3`` is written in three orders. + The connector databases cannot hold a result table (ITL-1162); they are covered + by ``tests/test_databases/test_append_by_name.py``. + """ fn, keys = FUNCTIONS[name] database = ( DeltaTableDatabase(tmp_path / "store") @@ -486,6 +483,8 @@ def test_swapped_same_typed_keys_store_different_signature_hashes( else InMemoryArrowDatabase() ) orders = [tuple(keys), tuple(reversed(keys))] + if len(keys) == 3: + orders.append((keys[1], keys[2], keys[0])) for index, order in enumerate(orders): job = PipelineJob(name="orders", database=database) with job: @@ -499,15 +498,30 @@ def test_swapped_same_typed_keys_store_different_signature_hashes( ), label="fn", ) - job.run() + job.run(orchestrator=orchestrator()) + assert len(list(job.nodes["fn"].iter_data())) == 1 result_paths = [p for p in database.list_table_paths() if "_result" in p] assert len(result_paths) == 1 stored = database.get_all_records(result_paths[0]) assert stored is not None signatures = stored.column("__pf_var_function_signature_hash").to_pylist() contents = stored.column("__pf_var_function_content_hash").to_pylist() - assert len(signatures) == 2 and len(set(signatures)) == 2 + assert len(signatures) == len(orders) and len(set(signatures)) == len(orders) assert len(set(contents)) == 1 + # Each row is its own order's: matched by that order's signature hash, it holds + # the function's values, for that order's input, under that order's keys. A row + # that took another row's signature, or an append that swapped two same-typed + # output columns, would fail here. + by_signature = { + row["__pf_var_function_signature_hash"]: row for row in stored.to_pylist() + } + for index, order in enumerate(orders): + expected_signature = _record(_build("from_fn", fn, list(order)))[ + "function_signature_hash" + ] + row = by_signature[expected_signature] + values = fn(index + 1, 2) + assert {key: row[key] for key in order} == dict(zip(order, values)), order _PRINT_RECORD = """ diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index df5572209..874ec8220 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -560,7 +560,8 @@ def write( ValueError: If a key column is missing, a column name is one SpiralDB reserves (a ``.`` anywhere, or a ``__`` prefix on a value column), a struct value is null without ``push_down_nulls``, or the column set - differs from the stored table. + differs from the stored table (live SpiralDB adds a new column: the + fake does not model it). """ b = self._store.behaviour keys = self.key_schema @@ -607,6 +608,13 @@ def write( fields.append(sf) arrays.append(_cast_storage(col, sf.type)) incoming = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) + # SpiralDB matches a write's columns by name and stores them in its own + # order, whatever the order written: the key columns in key-schema order, + # then the value columns sorted by name, by code point (observed live, + # ITL-1367). Struct children are sorted live too; the fake keeps them as + # written (struct field order: ITL-1368). + values = sorted(n for n in incoming.column_names if n not in keys.names) + incoming = incoming.select([*keys.names, *values]) existing = self._store.read(self._project_id, self._identifier) if existing is not None: if existing.schema.names != incoming.schema.names: diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py new file mode 100644 index 000000000..4fe75ba5d --- /dev/null +++ b/tests/test_databases/test_append_by_name.py @@ -0,0 +1,1079 @@ +"""An append matches columns by name, whatever their order (ITL-1367). + +Every database puts rows whose columns are the held table's columns in another order, +each field equal to the held one, into the held order: the in-memory database when the +rows are queued (the pending batch, else the stored table); Delta when they are queued, +against its pending batch only (it matches a stored table by name itself); a connector +database when they are queued, against its pending batch only, and at a flush or a +combined read, against the stored table read then. The table keeps the order its +database gave the first write. ``a`` and ``c`` are both ``int64``, so a positional match +would swap their values: every test reads the values back by name. Appends that add, +lack or retype a column, a field that differs in any way, and a name that repeats +exactly, keep the database's own rule. +""" + +from __future__ import annotations + +import os +import sqlite3 +import uuid +from collections.abc import Iterator +from contextlib import ExitStack +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import pyarrow as pa +import pytest + +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, + SpiralDBConnector, + SQLiteConnector, +) +from orcapod.databases.utils import in_held_column_order +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) +from tests.test_databases.type_matrix import open_database + +PATH = ("t",) +ID = "id" +TYPES: dict[str, Any] = { + ID: pa.large_binary(), + "a": pa.int64(), + "c": pa.int64(), + "b": pa.large_string(), +} +FIRST_ORDERS = { + "id a c b": [ID, "a", "c", "b"], + "b c id a": ["b", "c", ID, "a"], +} +SECOND_ORDERS = { + "c a b id": ["c", "a", "b", ID], + "id c a b": [ID, "c", "a", "b"], + "b id a c": ["b", ID, "a", "c"], +} +DATABASES = ("in-memory", "Delta", "SQLite", "SpiralDB") +DURABLE = ("Delta", "SQLite", "SpiralDB") + + +def _row(n: int) -> dict[str, Any]: + return {ID: f"r{n}".encode(), "a": n, "c": 100 + n, "b": f"b{n}"} + + +def _rows(order: list[str], ns: list[int]) -> pa.Table: + """Rows ``ns`` with the columns in ``order``; ``a`` is ``n``, ``c`` is ``100 + n``.""" + rows = [_row(n) for n in ns] + return pa.table( + {name: pa.array([r[name] for r in rows], TYPES[name]) for name in order} + ) + + +def _given_order(database: str, first: list[str], stored: bool = True) -> list[str]: + """The order a database gives a table first written in ``first``. + + The first write's order, except in SpiralDB once rows are stored: SpiralDB + stores and reads a table's columns in its own order, the key columns, then the + value columns sorted by name, whatever the order written (observed live, + ITL-1367; its fake does the same). Rows still pending keep the first write's. + """ + if database == "SpiralDB" and stored: + return [ID, *sorted(n for n in first if n != ID)] + return first + + +def _check(table: pa.Table | None, first: list[str], ns: list[int]) -> None: + """The rows ``ns``, read by name, in the order ``first``.""" + assert table is not None + assert table.column_names == first + got = sorted(table.select([ID, "a", "c", "b"]).to_pylist(), key=lambda r: r["a"]) + assert got == [_row(n) for n in ns] + + +def _add(db: Any, table: pa.Table, flush: bool = False) -> None: + db.add_records(PATH, table, record_id_column=ID, flush=flush) + + +@pytest.mark.parametrize("database", DATABASES) +@pytest.mark.parametrize("first", FIRST_ORDERS) +@pytest.mark.parametrize("second", SECOND_ORDERS) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_an_append_in_another_order_is_matched_by_name( + tmp_path: Path, database: str, first: str, second: str, when: str +) -> None: + first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] + with ExitStack() as stack: + db = stack.enter_context(open_database(database, tmp_path)) + _add(db, _rows(first_order, [1, 2]), flush=when == "after a flush") + _add(db, _rows(second_order, [3, 4])) + # Before the flush: the pending rows (and the stored ones) read by name. + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order(database, first_order, stored=when == "after a flush"), + [1, 2, 3, 4], + ) + db.flush() + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order(database, first_order), + [1, 2, 3, 4], + ) + + +@pytest.mark.parametrize("database", DURABLE) +@pytest.mark.parametrize("first", FIRST_ORDERS) +@pytest.mark.parametrize("second", SECOND_ORDERS) +def test_an_append_in_another_order_after_reopening_is_matched_by_name( + tmp_path: Path, database: str, first: str, second: str +) -> None: + first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] + with open_database(database, tmp_path) as db: + _add(db, _rows(first_order, [1, 2]), flush=True) + with open_database(database, tmp_path) as db: + _add(db, _rows(second_order, [3, 4])) + _add(db, _rows(first_order, [5])) + db.flush() + with open_database(database, tmp_path) as db: + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order(database, first_order), + [1, 2, 3, 4, 5], + ) + + +@pytest.mark.parametrize("database", DATABASES) +def test_a_new_table_keeps_the_order_the_database_gave_its_first_write( + tmp_path: Path, database: str +) -> None: + """The first write's order is kept, whichever order it is; nothing is sorted by + Orcapod (SpiralDB orders a table's columns its own way).""" + with open_database(database, tmp_path) as db: + for n, order in enumerate([["c", "b", "a", ID], [ID, "a", "b", "c"]]): + path = (f"t{n}",) + db.add_records(path, _rows(order, [1]), record_id_column=ID, flush=True) + table = db.get_all_records(path, record_id_column=ID) + assert table is not None + assert table.column_names == _given_order(database, order) + + +# Today's verdict for an append that is reordered AND retypes ``a`` (``int32`` where +# ``int64`` is held), measured on main 321284ae with the same fake: (where it is refused, +# the exception). The rows are not reordered (another type), so the verdict is the +# database's own; the stored rows are the first write's either way. +RETYPE_VERDICTS: dict[tuple[str, str], tuple[str, type[BaseException]]] = { + ("in-memory", "after a flush"): ("flush", pa.ArrowInvalid), + ("in-memory", "same pending batch"): ("add", pa.ArrowInvalid), + ("Delta", "after a flush"): ("add", InputValidationError), + ("Delta", "same pending batch"): ("add", ValueError), + ("SQLite", "after a flush"): ("add", UnstorableColumnError), + ("SQLite", "same pending batch"): ("add", UnstorableColumnError), + ("SpiralDB", "after a flush"): ("flush", ValueError), + ("SpiralDB", "same pending batch"): ("add", pa.ArrowInvalid), +} + + +@pytest.mark.parametrize("database", DATABASES) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_an_append_that_also_retypes_a_column_keeps_todays_rule( + tmp_path: Path, database: str, when: str +) -> None: + """Another type is not a reordering: the rows are left as given, and the + database's own rule refuses them where it does today; the stored rows stay.""" + stage, error = RETYPE_VERDICTS[(database, when)] + retyped = _rows(["c", "a", "b", ID], [3]).set_column( + 1, "a", pa.array([3], pa.int32()) + ) + with open_database(database, tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=when == "after a flush") + if stage == "add": + with pytest.raises(error): + _add(db, retyped) + db.flush() + else: + _add(db, retyped) + with pytest.raises(error): + db.flush() + table = db.get_all_records(PATH, record_id_column=ID) + assert table is not None + assert table.schema.field("a").type == pa.int64() + assert table.select([ID, "a", "c"]).to_pylist() == [ + {ID: b"r1", "a": 1, "c": 101} + ] + + +def test_a_table_created_again_in_another_order_is_read_as_it_is_now( + tmp_path: Path, +) -> None: + """A table dropped and created again in another order by another connection: + this handle's next append is matched to the new order by name, values right.""" + with open_database("SQLite", tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) + _add(db, _rows(["c", "a", "b", ID], [2]), flush=True) + with sqlite3.connect(tmp_path / "store.db") as other: + other.execute('DROP TABLE "t"') + other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) + _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) + _check( + db.get_all_records(PATH, record_id_column=ID), + ["b", ID, "c", "a"], + [3, 4], + ) + + +def test_rows_queued_before_a_table_is_created_again_are_read_with_it_by_name( + tmp_path: Path, +) -> None: + """Rows queued in the old stored order, then the table dropped and created again + in another order by another connection: a read before the flush, and the flush, + combine the queued rows with what is stored now, by name.""" + with open_database("SQLite", tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) + _add(db, _rows(["b", ID, "c", "a"], [2])) # queued as [id, a, c, b] + with sqlite3.connect(tmp_path / "store.db") as other: + other.execute('DROP TABLE "t"') + other_db = ConnectorArrowDatabase(SQLiteConnector(str(tmp_path / "store.db"))) + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) + _check( + db.get_all_records(PATH, record_id_column=ID), ["b", ID, "c", "a"], [2, 3] + ) + db.flush() + _check( + other_db.get_all_records(PATH, record_id_column=ID), + ["b", ID, "c", "a"], + [2, 3], + ) + + +def test_a_spiraldb_table_deleted_and_created_again_in_another_order( + tmp_path: Path, +) -> None: + with open_database("SpiralDB", tmp_path) as db: + _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) + db._connector.delete_table("t") # the connector's own drop + other_db = ConnectorArrowDatabase(SpiralDBConnector("p")) + _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) + _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) + _check( + db.get_all_records(PATH, record_id_column=ID), + _given_order("SpiralDB", ["b", ID, "c", "a"]), + [3, 4], + ) + + +# ── The shared step ──────────────────────────────────────────────────────────── + + +def _held(*names: str) -> list[Any]: + return [pa.field(n, pa.int64()) for n in names] + + +def _table(*names: str) -> pa.Table: + return pa.Table.from_arrays( + [pa.array([i], pa.int64()) for i in range(len(names))], names=list(names) + ) + + +def test_the_step_reorders_the_held_columns_by_name() -> None: + given = _table("c", "a", "b") + out = in_held_column_order(given, _held("a", "b", "c")) + assert out.column_names == ["a", "b", "c"] + assert out.to_pylist() == [{"a": 1, "b": 2, "c": 0}] + + +def test_the_step_keeps_the_given_fields() -> None: + """The rows are reordered and their fields kept as given: metadata, and a + nullability the held column does not have (the append checks judge it).""" + field = pa.field("c", pa.int64(), nullable=False, metadata={"unit": "m"}) + given = pa.Table.from_arrays( + [pa.array([1], pa.int64()), pa.array([2], pa.int64())], + schema=pa.schema([field, pa.field("a", pa.int64())]), + ) + held = [pa.field("a", pa.int64()), field.with_nullable(True)] + out = in_held_column_order(given, held) + assert out.column_names == ["a", "c"] + assert out.schema.field("c").equals(field, check_metadata=True) + + +def test_the_step_matches_names_exactly() -> None: + """``a`` and ``A`` are two columns, as Arrow matches names exactly.""" + out = in_held_column_order(_table("A", "a", "c"), _held("a", "c", "A")) + assert out.column_names == ["a", "c", "A"] + assert out.to_pylist() == [{"A": 0, "a": 1, "c": 2}] + + +def _annotated(name: str, ext_type: Any) -> Any: + """A field held as its storage type, annotated with its logical type (a stored + Delta column, a column the extension-aware wrapper encoded).""" + return pa.field( + name, + pa.string(), + metadata={ + b"ARROW:extension:name": ext_type.extension_name.encode(), + b"ARROW:extension:metadata": ext_type.__arrow_ext_serialize__(), + }, + ) + + +class _Unit(pa.ExtensionType): + """An extension type whose metadata is a unit: two units over ``int64`` are one + type to pyarrow's own equality, two types here.""" + + def __init__(self, unit: str) -> None: + self.unit = unit + super().__init__(pa.int64(), "test.itl1367.unit") + + def __arrow_ext_serialize__(self) -> bytes: + return self.unit.encode() + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(serialized.decode()) + + +def _unit_column(unit: str, nest: str) -> Any: + """``a``: an ``int64`` in ``unit``, at the top, in a struct or in a list.""" + array = pa.ExtensionArray.from_storage(_Unit(unit), pa.array([1], pa.int64())) + if nest == "struct": + return pa.StructArray.from_arrays([array], names=["m"]) + if nest == "list": + return pa.LargeListArray.from_arrays(pa.array([0, 1], pa.int64()), array) + return array + + +@pytest.mark.parametrize("nest", ["top", "struct", "list"]) +def test_the_step_matches_a_logical_type_only_to_itself_at_every_depth(nest: str): + """One rule for "may reorder": every field equal at every depth. A logical type + is equal only to its own name and metadata, also inside a struct or a list; an + annotation in field metadata only to the same annotation. Anything else is left + as given, so the database's own refusal applies (codex review of PR 491, round + 3).""" + held_table = pa.table({"b": [0], "a": _unit_column("m", nest)}) + held = list(held_table.schema) + same = pa.table({"a": _unit_column("m", nest), "b": [1]}) + assert in_held_column_order(same, held).column_names == ["b", "a"] + other = pa.table({"a": _unit_column("s", nest), "b": [1]}) + assert in_held_column_order(other, held) is other + + +def test_the_step_matches_a_field_annotation_only_to_itself() -> None: + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + _, one = _make_converter_with_type("test.itl1367.one") + _, two = _make_converter_with_type("test.itl1367.two") + a = pa.field("a", pa.int64()) + + def annotated(ext_type: Any) -> pa.Table: + return pa.Table.from_arrays( + [pa.array(["x"]), pa.array([1])], + schema=pa.schema([_annotated("text", ext_type), a]), + ) + + given = annotated(one) + held_one = [a, _annotated("text", one)] + assert in_held_column_order(given, held_one).column_names == ["a", "text"] + assert in_held_column_order(given, [a, _annotated("text", two)]) is given + assert in_held_column_order(given, [a, pa.field("text", pa.string())]) is given + live = pa.table( + { + "text": pa.ExtensionArray.from_storage( + one, pa.array(["x"], pa.large_string()) + ), + "a": [1], + } + ) + assert ( + in_held_column_order(live, held_one) is live + ) # a live type is not its storage + + +def test_the_step_compares_types_in_their_large_variants() -> None: + given = pa.table({"b": pa.array(["x"], pa.string()), "a": [1]}) + out = in_held_column_order( + given, [pa.field("a", pa.int64()), pa.field("b", pa.large_string())] + ) + assert out.column_names == ["a", "b"] + + +@pytest.mark.parametrize( + ("given", "held"), + [ + pytest.param(_table("c", "a"), None, id="nothing held"), + pytest.param(_table("c", "a"), _held("a", "b", "c"), id="a column missing"), + pytest.param(_table("c", "a", "b"), _held("a", "c"), id="a column added"), + pytest.param(_table("c", "A"), _held("a", "c"), id="a name in another case"), + pytest.param(_table("c", "a", "a"), _held("a", "c", "a"), id="a repeated name"), + pytest.param( + _table("c", "a"), + [pa.field("a", pa.int64()), pa.field("c", pa.int32())], + id="a type differs", + ), + pytest.param( + pa.table( + { + "s": pa.array( + [{"y": 1, "x": 2}], + pa.struct([("y", pa.int64()), ("x", pa.int64())]), + ), + "a": [1], + } + ), + [ + pa.field("a", pa.int64()), + pa.field("s", pa.struct([("x", pa.int64()), ("y", pa.int64())])), + ], + id="struct children in another order", + ), + ], +) +def test_the_step_leaves_anything_else_as_given( + given: pa.Table, held: list[Any] | None +) -> None: + assert in_held_column_order(given, held) is given + + +@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_names_differing_in_case_only_are_two_columns( + tmp_path: Path, database: str, when: str +) -> None: + """The in-memory and Delta databases hold ``a`` and ``A`` apart; an append of them + in another order is matched by exact name.""" + with open_database(database, tmp_path) as db: + _add(db, _table_with_id(b"r1", [ID, "a", "A"]), flush=when == "after a flush") + _add(db, _table_with_id(b"r2", ["A", ID, "a"])) + db.flush() + table = db.get_all_records(PATH, record_id_column=ID) + assert table is not None + assert sorted(table.select([ID, "a", "A"]).to_pylist(), key=str) == [ + {ID: b"r1", "a": 1, "A": 2}, + {ID: b"r2", "a": 1, "A": 2}, + ] + + +def _table_with_id(rid: bytes, order: list[str]) -> pa.Table: + columns = { + ID: pa.array([rid], pa.large_binary()), + "a": pa.array([1], pa.int64()), + "A": pa.array([2], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("stored", [True, False], ids=["committed", "pending"]) +def test_a_logical_column_is_matched_by_name_through_the_extension_database( + tmp_path: Path, stored: bool +) -> None: + """A logical column appended in another order through the extension-aware + wrapper, the held rows pending or committed: every value is read back by name + (Delta matches a stored table by name itself; a pending batch is aligned).""" + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + converter, ext_type = _make_converter_with_type("test.itl1367.extension") + + def rows(n: int, order: list[str]) -> pa.Table: + columns = { + ID: pa.array([bytes([n])], pa.large_binary()), + "text": pa.ExtensionArray.from_storage( + ext_type, pa.array([str(n)], pa.large_string()) + ), + "n": pa.array([n], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + db = ExtensionAwareDatabase(DeltaTableDatabase(tmp_path / "delta"), converter) + _add(db, rows(1, [ID, "text", "n"]), flush=stored) + _add(db, rows(2, ["n", ID, "text"])) + pending = db.get_record_by_id(PATH, bytes([2]), record_id_column=ID) + assert pending is not None + db.flush() + committed = db.get_record_by_id(PATH, bytes([2]), record_id_column=ID) + assert committed is not None + row = {ID: bytes([2]), "text": "2", "n": 2} + assert pending.select([ID, "text", "n"]).to_pylist() == [row] + assert committed.select([ID, "text", "n"]).to_pylist() == [row] + + +# ── Delta: the commit a reordered append takes ───────────────────────────────── + + +def _race_rows(n: int, value: int, order: tuple[str, ...]) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([value], pa.int64()), + "b": pa.array([1000 + value], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +@pytest.mark.parametrize("skip_duplicates", [True, False]) +@pytest.mark.parametrize( + ("stale_order", "other_order"), + [(("a", "b", "rid"), ("b", "rid", "a")), (("b", "rid", "a"), ("a", "b", "rid"))], +) +def test_a_reordered_append_is_committed_as_insert_if_missing_across_writers( + tmp_path: Path, + skip_duplicates: bool, + stale_order: tuple[str, ...], + other_order: tuple[str, ...], +) -> None: + """Two handles append the same new record id with different values, each in + another order than the stored table. The second commits after the first has + taken its snapshot of the stored ids. As on main (where rows in another order + than the stored table are committed by MERGE), the stale commit fails and the id + keeps one row: the reorder does not turn the commit into a blind append.""" + stale, other = DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path) + stale.add_records( + PATH, _race_rows(1, 10, ("rid", "a", "b")), record_id_column="rid", flush=True + ) + snapshot = stale._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + other.add_records( + PATH, + _race_rows(2, 20, other_order), + record_id_column="rid", + flush=True, + skip_duplicates=skip_duplicates, + ) + return taken + + with patch.object(stale, "_snapshot_for_commit", side_effect=interleave): + with pytest.raises(RuntimeError) as raised: + stale.add_records( + PATH, + _race_rows(2, 99, stale_order), + record_id_column="rid", + flush=True, + skip_duplicates=skip_duplicates, + ) + assert type(raised.value.__cause__).__name__ == "CommitFailedError" + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + assert sorted(table.select(["rid", "a"]).to_pylist(), key=str) == [ + {"rid": bytes([1]), "a": 10}, + {"rid": bytes([2]), "a": 20}, + ] + + +def test_an_all_duplicate_append_looks_up_no_order(tmp_path: Path) -> None: + """With ``skip_duplicates`` and nothing left to write, a stored table whose + recorded type cannot be read does not fail an append that writes nothing (Delta + looks no stored order up at all).""" + from deltalake import write_deltalake + + rows = _rows([ID, "a", "c", "b"], [1]).rename_columns( + ["__record_id", "a", "c", "b"] + ) + schema = rows.schema.set( + 2, rows.schema.field(2).with_metadata({b"orcapod:arrow_type": b"invalid"}) + ) + write_deltalake(tmp_path / "t", pa.Table.from_arrays(rows.columns, schema=schema)) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows(["b", ID, "c", "a"], [1]), + record_id_column=ID, + skip_duplicates=True, + flush=True, + ) + + +# ── Lookups ──────────────────────────────────────────────────────────────────── + + +def test_an_aligned_append_looks_the_stored_table_up_once(tmp_path: Path) -> None: + """The connector database looks a table up once per flushed append, at the + flush, as main does: an append looks nothing up when it is queued.""" + path = str(tmp_path / "store.db") + ConnectorArrowDatabase(SQLiteConnector(path)).add_records( + PATH, _rows([ID, "a", "c", "b"], [1]), record_id_column=ID, flush=True + ) + connector = SQLiteConnector(path) + db = ConnectorArrowDatabase(connector) + with ( + patch.object( + connector, "get_table_names", wraps=connector.get_table_names + ) as names, + patch.object( + connector, "get_column_info", wraps=connector.get_column_info + ) as info, + ): + _add(db, _rows([ID, "a", "c", "b"], [2]), flush=True) + assert (names.call_count, info.call_count) == (1, 1) + _add(db, _rows(["b", ID, "c", "a"], [3])) + assert (names.call_count, info.call_count) == (1, 1) + db.flush() + assert (names.call_count, info.call_count) == (2, 2) + _check( + db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3] + ) + + +# ── Nothing about a stored table is trusted across calls ─────────────────────── + + +def _abc(n: int, order: tuple[str, ...] = ("rid", "a", "b")) -> pa.Table: + columns = { + "rid": pa.array([bytes([n])], pa.large_binary()), + "a": pa.array([10 * n], pa.int64()), + "b": pa.array([100 * n], pa.int64()), + } + return pa.table({name: columns[name] for name in order}) + + +def _sqlite(path: Path) -> ConnectorArrowDatabase: + return ConnectorArrowDatabase(SQLiteConnector(str(path))) + + +def _recreate_with_text_a(path: Path) -> None: + with sqlite3.connect(path) as other: + other.execute('DROP TABLE "t"') + _sqlite(path).add_records( + PATH, + pa.table( + { + "rid": pa.array([bytes([1])], pa.large_binary()), + "a": pa.array(["10"], pa.large_string()), + "b": pa.array([100], pa.int64()), + } + ), + record_id_column="rid", + flush=True, + ) + + +CHANGES: dict[str, Any] = { + "rename": lambda c: c.execute('ALTER TABLE "t" RENAME COLUMN a TO A'), + "add": lambda c: c.execute('ALTER TABLE "t" ADD COLUMN extra INTEGER'), + "drop": lambda c: c.execute('ALTER TABLE "t" DROP COLUMN b'), +} + + +@pytest.mark.parametrize("change", [*CHANGES, "retype"]) +@pytest.mark.parametrize("order", [("rid", "a", "b"), ("b", "rid", "a")]) +def test_a_table_changed_between_queue_and_flush_is_refused_as_on_main( + tmp_path: Path, change: str, order: tuple[str, ...] +) -> None: + """Another connection renames, adds, drops or retypes a column after rows are + queued: the flush checks the table as it is then, by exact name and type, and + refuses as main does; the stored rows are untouched (codex review of PR 491, + round 2: a remembered table order let such rows through).""" + path = tmp_path / "store.db" + _sqlite(path).add_records(PATH, _abc(1), record_id_column="rid", flush=True) + db = _sqlite(path) + db.add_records(PATH, _abc(2, order), record_id_column="rid") + if change == "retype": + _recreate_with_text_a(path) + else: + with sqlite3.connect(path) as other: + CHANGES[change](other) + before = _sqlite(path).get_all_records(PATH, record_id_column="rid") + with pytest.raises(ValueError, match="Schema mismatch"): + db.flush() + after = _sqlite(path).get_all_records(PATH, record_id_column="rid") + assert before is not None and after is not None + assert after.equals(before) + assert after.num_rows == 1 + + +def test_a_table_dropped_and_written_again_by_the_same_handle_takes_the_new_order( + tmp_path: Path, +) -> None: + """The handle that wrote the dropped table writes the replacement in the order of + its new first write, as main does: nothing of the dropped table is remembered.""" + path = tmp_path / "store.db" + db = _sqlite(path) + db.add_records(PATH, _abc(1), record_id_column="rid", flush=True) + with sqlite3.connect(path) as other: + other.execute('DROP TABLE "t"') + db.add_records(PATH, _abc(2, ("b", "rid", "a")), record_id_column="rid", flush=True) + table = _sqlite(path).get_all_records(PATH, record_id_column="rid") + assert table is not None + assert table.column_names == ["b", "rid", "a"] + assert table.to_pylist() == [{"b": 200, "rid": bytes([2]), "a": 20}] + + +def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: + """A point lookup of a queued row answers from memory, in the order the row is + queued, with no lookup of the stored table (as main): the stored table is not + even listed. Presentation order is a reader's business (ITL-1370).""" + with open_database("SpiralDB", tmp_path) as db: + rows = pa.table( + { + "rid": pa.array([bytes([1])], pa.large_binary()), + "z": pa.array([10]), + "a": pa.array([100]), + } + ) + db.add_records(PATH, rows, record_id_column="rid", flush=True) + second = rows.set_column(0, "rid", pa.array([bytes([2])], pa.large_binary())) + db.add_records(PATH, second, record_id_column="rid") + with patch.object( + db._connector, "get_table_names", side_effect=AssertionError("listed") + ): + queued = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + assert queued is not None + assert queued.column_names == ["rid", "z", "a"] + db.flush() + committed = db.get_record_by_id(PATH, bytes([2]), record_id_column="rid") + assert committed is not None + assert committed.select(["rid", "z", "a"]).to_pylist() == queued.to_pylist() + + +@pytest.mark.parametrize("schema_handling", ["error", "merge", "coerce"]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +@pytest.mark.parametrize("race", [False, True], ids=["alone", "with another writer"]) +def test_a_refused_reordered_append_leaves_the_next_batch_on_mains_commit( + tmp_path: Path, schema_handling: str, skip_duplicates: bool, race: bool +) -> None: + """A reordered append the ITL-1334 check refuses (other field metadata) queues + nothing, and leaves nothing behind: the next aligned batch is committed as on + main, by append, also when another writer commits an unrelated id meanwhile.""" + from deltalake import DeltaTable + + db = DeltaTableDatabase(tmp_path) + kwargs: dict[str, Any] = { + "record_id_column": "rid", + "schema_handling": schema_handling, + "skip_duplicates": skip_duplicates, + } + db.add_records(PATH, _abc(1), flush=True, **kwargs) + bad = _abc(2, ("b", "rid", "a")) + bad = bad.set_column( + 2, bad.schema.field("a").with_metadata({"units": "wrong"}), bad["a"] + ) + with pytest.raises(InputValidationError): + db.add_records(PATH, bad, **kwargs) + if race: + snapshot = db._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + DeltaTableDatabase(tmp_path).add_records( + PATH, _abc(3), flush=True, **kwargs + ) + return taken + + with patch.object(db, "_snapshot_for_commit", side_effect=interleave): + db.add_records(PATH, _abc(2), flush=True, **kwargs) + else: + db.add_records(PATH, _abc(2), flush=True, **kwargs) + assert DeltaTable(tmp_path / "t").history()[0]["operation"] == "WRITE" + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + expected = [1, 2, 3] if race else [1, 2] + assert sorted(cast(list[int], table.column("a").to_pylist())) == [ + 10 * n for n in expected + ] + + +@pytest.mark.parametrize("backend", ["in-memory", "Delta"]) +@pytest.mark.parametrize("stored", [False, True], ids=["pending", "committed"]) +def test_two_logical_types_over_one_storage_type_are_not_reordered( + tmp_path: Path, backend: str, stored: bool +) -> None: + """Through the extension-aware wrapper, a column of one logical type held and a + permuted append of another logical type over the same storage type: not taken + for one, so refused as on main, never read back as the held logical type.""" + from tests.test_databases.test_extension_aware_database import ( + _make_converter_with_type, + ) + + one = _make_converter_with_type("test.itl1367.held") + two = _make_converter_with_type("test.itl1367.other") + + def rows(n: int, pair: Any, order: list[str]) -> pa.Table: + text = pa.ExtensionArray.from_storage( + pair[1], pa.array([str(n)], pa.large_string()) + ) + return _abc(n).append_column(pa.field("text", pair[1]), text).select(order) + + inner = ( + InMemoryArrowDatabase() + if backend == "in-memory" + else DeltaTableDatabase(tmp_path / "delta") + ) + ExtensionAwareDatabase(inner, one[0]).add_records( + PATH, + rows(1, one, ["rid", "a", "b", "text"]), + record_id_column="rid", + flush=stored, + ) + second = ExtensionAwareDatabase(inner, two[0]) + permuted = rows(2, two, ["text", "b", "rid", "a"]) + # Main's verdict, measured on main 321284ae, the same here. + if backend == "in-memory" and not stored: + with pytest.raises(pa.ArrowInvalid): + second.add_records(PATH, permuted, record_id_column="rid") + elif backend == "in-memory": + second.add_records(PATH, permuted, record_id_column="rid") + with pytest.raises(pa.ArrowInvalid): + second.flush() + elif not stored: + with pytest.raises(ValueError, match="Schema mismatch"): + second.add_records(PATH, permuted, record_id_column="rid") + else: + # Pre-existing on main and equal here (ITL-1371's family): Delta takes the + # rows by name and the stored table can no longer be read as one type. + second.add_records(PATH, permuted, record_id_column="rid", flush=True) + with pytest.raises(OrcapodDatabaseReadError): + inner.get_all_records(PATH, record_id_column="rid") + return + inner.flush() + stored_rows = inner.get_all_records(PATH, record_id_column="rid") + assert stored_rows is not None + assert stored_rows.column("rid").to_pylist() == [bytes([1])] + + +@pytest.mark.parametrize( + ("schema_handling", "a"), + [ + ("merge", pa.nulls(1)), + ("coerce", pa.nulls(1)), + ("coerce", pa.array([30], pa.int32())), + ], + ids=["merge null", "coerce null", "coerce int32"], +) +def test_a_delta_batch_queued_in_another_order_keeps_its_order( + tmp_path: Path, schema_handling: str, a: Any +) -> None: + """Delta aligns an append only to its own pending batch, never to the stored + table: a batch queued in another order than the stored table stays in its order, + so a later append in that order, relying on ``schema_handling`` to merge or coerce + a column, behaves as on main (codex review of PR 491, round 3).""" + db = DeltaTableDatabase(tmp_path) + kwargs: dict[str, Any] = { + "record_id_column": "rid", + "schema_handling": schema_handling, + } + db.add_records(PATH, _abc(1), flush=True, **kwargs) + db.add_records(PATH, _abc(2, ("b", "rid", "a")), **kwargs) + third = _abc(3, ("b", "rid", "a")).set_column(2, "a", a) + db.add_records(PATH, third, **kwargs) + db.flush() + table = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert table is not None + got = sorted(table.select(["rid", "a", "b"]).to_pylist(), key=str) + assert got == [ + {"rid": bytes([1]), "a": 10, "b": 100}, + {"rid": bytes([2]), "a": 20, "b": 200}, + {"rid": bytes([3]), "a": a.to_pylist()[0], "b": 300}, + ] + + +def test_a_delta_table_created_again_in_another_order_takes_mains_commit( + tmp_path: Path, +) -> None: + """A Delta table created again in another order while this handle holds the old + one: an aligned batch is committed by append as on main, also with another writer + committing an unrelated id meanwhile (no state of this PR forces a MERGE).""" + import shutil + + from deltalake import DeltaTable, write_deltalake + + order = ("b", "__record_id", "a") + + def rows(n: int) -> pa.Table: + return _abc(n).rename_columns(["__record_id", "a", "b"]).select(order) + + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + rows(1).select(["__record_id", "a", "b"]), + flush=True, + record_id_column="__record_id", + ) + shutil.rmtree(tmp_path / "t") + write_deltalake(tmp_path / "t", rows(1), mode="overwrite") + db.add_records(PATH, rows(2), record_id_column="__record_id") + snapshot = db._snapshot_for_commit + + def interleave(*args: Any) -> Any: + taken = snapshot(*args) + DeltaTableDatabase(tmp_path).add_records( + PATH, rows(3), flush=True, record_id_column="__record_id" + ) + return taken + + with patch.object(db, "_snapshot_for_commit", side_effect=interleave): + db.flush() + history = [entry["operation"] for entry in DeltaTable(tmp_path / "t").history()] + assert "MERGE" not in history + table = DeltaTableDatabase(tmp_path).get_all_records( + PATH, record_id_column="__record_id" + ) + assert table is not None + assert sorted(cast(list[int], table.column("a").to_pylist())) == [10, 20, 30] + + +def _extension_values(type_: Any) -> Any: + return pa.ExtensionArray.from_storage(type_, pa.array([1], pa.int64())) + + +def _container_columns() -> dict[str, tuple[Any, Any]]: + """A column of each container kind the comparison does not handle, held and + appended: the appended one holds an extension type with other metadata (or, for + a plain list view, an item field with other metadata).""" + held_ext, other_ext = _Unit("m"), _Unit("s") + offsets = pa.array([0], pa.int32()) + sizes = pa.array([1], pa.int32()) + + def list_view(value: Any, large: bool) -> Any: + kind: Any = pa.LargeListViewArray if large else pa.ListViewArray + return kind.from_arrays( + pa.array([0], pa.int64() if large else pa.int32()), + pa.array([1], pa.int64() if large else pa.int32()), + value, + ) + + def run_end() -> Any: + encoded: Any = pa.RunEndEncodedArray + return encoded.from_arrays(pa.array([1], pa.int32()), pa.array([1])) + + def view_struct() -> Any: + return pa.array([{"x": "a"}], pa.struct([("x", pa.string_view())])) + + def interval() -> Any: + return pa.array([(1, 0, 0)], pa.month_day_nano_interval()) + + def union(value: Any, mode: str) -> Any: + types = pa.array([0], pa.int8()) + if mode == "dense": + return pa.UnionArray.from_dense(types, pa.array([0], pa.int32()), [value]) + return pa.UnionArray.from_sparse(types, [value]) + + list_view_array: Any = pa.ListViewArray + plain_item = list_view_array.from_arrays(offsets, sizes, pa.array([1])) + marked_item = plain_item.cast( + pa.list_view(pa.field("item", pa.int64(), metadata={"unit": "s"})) + ) + return { + "list_view": ( + list_view(_extension_values(held_ext), False), + list_view(_extension_values(other_ext), False), + ), + "large_list_view": ( + list_view(_extension_values(held_ext), True), + list_view(_extension_values(other_ext), True), + ), + "dense union": ( + union(_extension_values(held_ext), "dense"), + union(_extension_values(other_ext), "dense"), + ), + "sparse union": ( + union(_extension_values(held_ext), "sparse"), + union(_extension_values(other_ext), "sparse"), + ), + "list view item metadata": (plain_item, marked_item), + "dictionary": ( + pa.array(["x"]).dictionary_encode(), + pa.array(["x"]).dictionary_encode(), + ), + "run-end encoded": (run_end(), run_end()), + "interval": (interval(), interval()), + # Equal on both sides: a view type is not eligible even though the large + # normalization would turn it into ``large_string`` (CodeRabbit on PR 491). + "string view in a struct": (view_struct(), view_struct()), + } + + +@pytest.mark.parametrize("kind", list(_container_columns())) +def test_a_column_of_a_type_the_comparison_does_not_handle_is_never_reordered( + kind: str, +) -> None: + """Eligibility is positive (codex review of PR 491, round 4): a column whose type + tree holds anything but the handled leaf types, structs, maps, the three list + kinds and extension types over those is not eligible, even when equal, so the + table is left as given and the database's own rule applies.""" + held_values, given_values = _container_columns()[kind] + held = list(pa.table({"b": [0], "a": held_values}).schema) + given = pa.table({"a": given_values, "b": [1]}) + assert in_held_column_order(given, held) is given + + +class _KeyNotNullSQLite(SQLiteConnector): + """A SQLite connector whose reads give the primary key ``NOT NULL``, as a + PostgreSQL connector does (the CI failure of PR 491's PostgreSQL job).""" + + def iter_batches(self, query: str, params: Any = None, batch_size: int = 1000): # type: ignore[override] + for batch in super().iter_batches(query, params, batch_size): + schema = batch.schema + index = schema.get_field_index("__record_id") + if index >= 0: + schema = schema.set(index, schema.field(index).with_nullable(False)) + yield pa.RecordBatch.from_arrays(batch.columns, schema=schema) + + +@pytest.mark.parametrize("order", [["id", "a", "c", "b"], ["b", "c", "id", "a"]]) +def test_queued_rows_combine_with_a_stored_key_read_back_not_null( + tmp_path: Path, order: list[str] +) -> None: + """A store reads its primary key back ``NOT NULL`` while the queued rows declare + it nullable: a read that combines them takes the column nullable, the arrays + unchanged, in either column order; a read before and after the flush give the + same rows (as the PostgreSQL CI job checks against a live server).""" + db = ConnectorArrowDatabase(_KeyNotNullSQLite(str(tmp_path / "store.db"))) + _add(db, _rows([ID, "a", "c", "b"], [1, 2]), flush=True) + _add(db, _rows(order, [3, 4])) + before = db.get_all_records(PATH, record_id_column=ID) + _check(before, [ID, "a", "c", "b"], [1, 2, 3, 4]) + db.flush() + _check( + db.get_all_records(PATH, record_id_column=ID), [ID, "a", "c", "b"], [1, 2, 3, 4] + ) + + +# ── PostgreSQL (a live server: the PostgreSQL CI job) ────────────────────────── + + +@pytest.fixture +def postgresql_database() -> Iterator[ConnectorArrowDatabase]: + psycopg = pytest.importorskip("psycopg") + from orcapod.databases import PostgreSQLConnector + + host = os.environ.get("PGHOST", "localhost") + port = os.environ.get("PGPORT", "5432") + dbname = os.environ.get("PGDATABASE", "testdb") + user = os.environ.get("PGUSER", "postgres") + password = os.environ.get("PGPASSWORD", "postgres") + base_dsn = ( + f"host={host} port={port} dbname={dbname} user={user} password={password}" + ) + schema = f"test_{uuid.uuid4().hex[:12]}" + with psycopg.connect(base_dsn, autocommit=True) as admin: + admin.execute(f"CREATE SCHEMA {schema}") + connector = PostgreSQLConnector(f"{base_dsn} options=-csearch_path={schema}") + try: + yield ConnectorArrowDatabase(connector) + finally: + connector.close() + with psycopg.connect(base_dsn, autocommit=True) as admin: + admin.execute(f"DROP SCHEMA IF EXISTS {schema} CASCADE") + + +@pytest.mark.postgres +@pytest.mark.parametrize("first", FIRST_ORDERS) +@pytest.mark.parametrize("second", SECOND_ORDERS) +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_postgresql_matches_an_append_in_another_order_by_name( + postgresql_database: ConnectorArrowDatabase, first: str, second: str, when: str +) -> None: + db = postgresql_database + first_order, second_order = FIRST_ORDERS[first], SECOND_ORDERS[second] + _add(db, _rows(first_order, [1, 2]), flush=when == "after a flush") + _add(db, _rows(second_order, [3, 4])) + _check(db.get_all_records(PATH, record_id_column=ID), first_order, [1, 2, 3, 4]) + db.flush() + _check(db.get_all_records(PATH, record_id_column=ID), first_order, [1, 2, 3, 4]) diff --git a/tests/test_databases/test_spiraldb_connector_fake.py b/tests/test_databases/test_spiraldb_connector_fake.py index a40568ff4..6d78530da 100644 --- a/tests/test_databases/test_spiraldb_connector_fake.py +++ b/tests/test_databases/test_spiraldb_connector_fake.py @@ -160,6 +160,14 @@ def hashes(source) -> list[str]: _TABLE = "p/default/t" +def _spiral_order(schema: pa.Schema, keys: list[str]) -> pa.Schema: + """``schema`` in the order SpiralDB stores and reads a table's columns, whatever + the order written: the key columns in key order, then the value columns sorted + by name (observed live, ITL-1367).""" + values = sorted(f.name for f in schema if f.name not in keys) + return pa.schema([schema.field(n) for n in [*keys, *values]]) + + def _rows(schema: pa.Schema = _RECORDED, **override) -> pa.Table: """Return three rows of ``schema`` (``override`` replaces whole columns).""" columns = { @@ -209,12 +217,14 @@ def test_first_write_records_and_both_read_paths_restore_it(self, fake): """The first write records nullability; get_column_info and iter_batches restore it.""" connector = SpiralDBConnector("p") connector.upsert_records("t", _rows(), id_column="k") + # In SpiralDB's order: the key column, then the value columns by name + # (ITL-1367). expected = pa.schema( [ pa.field( f.name, arrow_utils.normalize_to_large_types(f.type), f.nullable ) - for f in _RECORDED + for f in _spiral_order(_RECORDED, ["k"]) ] ) assert self._batches_schema(connector) == expected @@ -466,7 +476,8 @@ def test_results_read_back_with_the_written_schema(self, db): records = db.get_all_records(_PATH) assert records is not None assert records.num_rows == 2 - assert records.schema == _RESULT + # In SpiralDB's order: the value columns by name (ITL-1367). + assert records.schema == _spiral_order(_RESULT, []) def test_result_table_written_before_the_record_keeps_todays_behaviour( self, db, monkeypatch diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index de32f9f20..a6d88ff2a 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -460,3 +460,84 @@ def test_spiraldb_itself_refuses_the_names_the_connector_refuses( finally: if table in connector.get_table_names(): connector.delete_table(table) + + +def _ordered_rows(order: list[str], ns: list[int]) -> pa.Table: + """Rows ``ns`` with the columns in ``order``; ``a`` and ``c`` are both ``int64``, + so a positional match would swap them.""" + columns = { + "__record_id": pa.array([f"r{n}".encode() for n in ns], pa.large_binary()), + "a": pa.array(ns, pa.int64()), + "c": pa.array([100 + n for n in ns], pa.int64()), + "b": pa.array([f"b{n}" for n in ns], pa.large_string()), + } + return pa.table({name: columns[name] for name in order}) + + +def _by_name(table: pa.Table) -> list[dict[str, object]]: + return sorted( + table.select(["__record_id", "a", "c", "b"]).to_pylist(), key=lambda r: r["a"] + ) + + +class TestColumnOrderLive: + """SpiralDB matches a write's columns by name and keeps an order of its own: the + key columns, then the value columns sorted by name, whatever the order written + (ITL-1367; the fake does the same).""" + + def test_a_raw_write_in_another_order_is_matched_by_name(self, connector): + table = _unique_table("itl1367_raw") + try: + first = ["__record_id", "a", "c", "b"] + connector.create_table_if_not_exists( + table, + [ + ColumnInfo(n, _ordered_rows(first, [1]).schema.field(n).type) + for n in first + ], + pk_column="__record_id", + ) + connector.upsert_records(table, _ordered_rows(first, [1, 2]), "__record_id") + connector.upsert_records( + table, + _ordered_rows(["b", "c", "__record_id", "a"], [3, 4]), + "__record_id", + ) + read = pa.Table.from_batches( + list(connector.iter_batches(f'SELECT * FROM "{table}"')) + ) + assert read.column_names == ["__record_id", "a", "b", "c"] + assert _by_name(read) == _by_name(_ordered_rows(first, [1, 2, 3, 4])) + finally: + if table in connector.get_table_names(): + connector.delete_table(table) + + @pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) + def test_the_database_matches_an_append_in_another_order_by_name( + self, connector, when + ): + path = (_unique_table("itl1367_db"),) + db = ConnectorArrowDatabase(connector) + try: + first = ["__record_id", "a", "c", "b"] + db.add_records( + path, _ordered_rows(first, [1, 2]), flush=when == "after a flush" + ) + db.add_records( + path, + _ordered_rows(["b", "c", "__record_id", "a"], [3, 4]), + record_id_column="__record_id", + ) + db.add_records( + path, + _ordered_rows(["c", "__record_id", "b", "a"], [5]), + record_id_column="__record_id", + ) + db.flush() + read = db.get_all_records(path, record_id_column="__record_id") + assert read is not None + assert read.column_names == ["__record_id", "a", "b", "c"] + assert _by_name(read) == _by_name(_ordered_rows(first, [1, 2, 3, 4, 5])) + finally: + if path[0] in connector.get_table_names(): + connector.delete_table(path[0]) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index ce00684e8..a3c298224 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1055,6 +1055,23 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. + +An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two +columns), never by position. Rows whose columns are the held table's columns in another +order, each field equal to the held one (the same type at every depth, the same logical +type, the same field attributes), are put in the held order, whether the table was +flushed in between or not. The in-memory database matches them to the rows still pending, +else the stored table; Delta to the rows still pending (it matches a stored table by name +itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, +and to the stored table when it writes or reads them, checking them first against the +table as it is then, by exact name and type (a column with field metadata stays in its +queued order at a flush; SpiralDB, which keeps field metadata, matches a write by name +itself). A table keeps the column +order the database gave its first write: the first write's order, except in SpiralDB, +which stores and reads a table's key columns first and then its other columns sorted by +name, whatever the order written (measured on SpiralDB itself). An append that also +adds, omits or retypes a column keeps each database's own rule. The order of a struct's +fields is not covered: a struct whose fields are in another order is another type here. """ From 4d192bfcb85cccfe48251cd32679aa0a3c2532ae Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 17:27:14 -0800 Subject: [PATCH 4/5] test(order): drop the ITL-1363 expected-failure mark now that the fix is on main (#499) PR 484 (ITL-1363) and PR 486 (ITL-1365) are both merged, so the strict xfail on MapTags(drop_unmapped=True) in test_tag_schema_order.py XPASSes and fails main's test job. Remove the mark, its uses and its comment. Co-authored-by: Edgar Y. Walker Co-authored-by: Claude Opus 5.5 --- tests/test_core/test_tag_schema_order.py | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/tests/test_core/test_tag_schema_order.py b/tests/test_core/test_tag_schema_order.py index ee22a3e3e..2624592d6 100644 --- a/tests/test_core/test_tag_schema_order.py +++ b/tests/test_core/test_tag_schema_order.py @@ -139,25 +139,10 @@ def _demoted(stream: Any, result: Any) -> set[str]: return {c for c in tags if c in data and c not in out_tags and c in out_data} -# MapTags(drop_unmapped=True) predicts no system tags (ITL-1363, fixed by PR 484): -# remove this mark when that fix is on main. -_ITL_1363 = pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="ITL-1363: MapTags(drop_unmapped=True) predicts no system-tag columns", -) - - @pytest.mark.parametrize( "data_tags", DATA_TAG_SETS, ids=lambda d: "+".join(d) or "none" ) -@pytest.mark.parametrize( - "name", - [ - pytest.param(name, marks=_ITL_1363) if name == "map_tags_drop" else name - for name in OPERATORS - ], -) +@pytest.mark.parametrize("name", list(OPERATORS)) def test_the_prediction_lists_the_columns_in_the_result_order( name: str, data_tags: tuple[str, ...] ) -> None: From 4ede51d3ec19f63abd288380695f2582e7d76c76 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 18:02:04 -0800 Subject: [PATCH 5/5] test: expectations of main 4d192bfc after merging it into eywalker/job-speed (ITL-1347) The eight failures of the merge of main 4d192bfc into job-speed are tests that pinned main's behaviour before 4d192bfc; on each input the branch equals main 4d192bfc exactly (shown with main's own run): - test_declared_slot_one_data_tag (4) and test_rows_on_read's narrower-bind channel: ITL-1366's input, which raised "Duplicate column name" on main 321284ae, completes on main 4d192bfc (a tag schema in tag order, ITL-1365, #486); every arrangement gives the bound table's rows, sync and async, and the channel delivers the node's row-built table. - test_record_batch_channels (2): a slot over a source with tags declared k, j now lists them k, j (tag order, #486), as its rows do. - test_spiraldb_lookups[reversed]: the SpiralDB fake stores the key columns in key order, then the value columns by name (ITL-1367, #491). Co-Authored-By: Claude Opus 5.5 --- .../test_record_batch_channels.py | 12 +++++----- .../sources/test_spiraldb_lookups.py | 7 +++++- .../test_declared_slot_one_data_tag.py | 23 ++++++++----------- tests/test_pipeline/test_rows_on_read.py | 18 ++++++++++----- 4 files changed, 33 insertions(+), 27 deletions(-) diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index c9aafc50d..db215d986 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -164,8 +164,8 @@ def test_a_source_node_opens_a_channel_on_its_rows() -> None: def test_a_bound_source_node_sends_its_rows_in_their_own_column_order() -> None: """A source whose physical columns are x, j, k, y with tags declared k, j: the - node's batches have the column order of its own rows (``execute()``: k, j, ...), - not the slot's schema order.""" + node's batches have the column order of its own rows (``execute()``: k, j, ...). + Since ``main`` 4d192bfc the slot's schema lists the tags in tag order too (#486).""" stream = ArrowTableSource( pa.table( { @@ -180,7 +180,7 @@ def test_a_bound_source_node_sends_its_rows_in_their_own_column_order() -> None: source_id="ordered", ) node = SourceJobNode.from_stream(stream, name="ordered") - assert node.keys()[0] != stream.keys()[0] # the slot's order is another + assert node.keys()[0] == stream.keys()[0] == ("k", "j") # tag order (#486) rows = list(node.iter_data()) # the rows execute() returned before ITL-1347 stage 2 expected = StaticOutputOperatorPod._rows_to_table(rows)[0] batches = run(node.open_channel().collect) @@ -284,8 +284,8 @@ def test_a_rebind_before_the_first_read_is_read_whole() -> None: def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the stream - ``to_stream()`` makes keeps the columns in the order they were delivered - (the node's rows), though the node describes itself in the slot's order.""" + ``to_stream()`` makes keeps the columns in the order they were delivered (the + node's rows), which since ``main`` 4d192bfc is also the slot's (tag order, #486).""" stream = ArrowTableSource( pa.table( { @@ -300,7 +300,7 @@ def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: source_id="ordered", ) node = SourceJobNode.from_stream(stream, name="ordered") - assert node.keys()[0] == ("j", "k") # the slot's order + assert node.keys()[0] == ("k", "j") # the slot's order: tag order (#486) async def read() -> tuple[list[str], list[str]]: batches = await node.open_channel().collect() diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 314cfdaad..1b485b27b 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -203,7 +203,12 @@ def test_the_connector_getters_answer_as_the_handle_does( assert connector.get_arrow_schema("t").equals( table.arrow_schema(), check_metadata=True ) - assert table.arrow_schema().names == _ARRANGED["layout"] + # SpiralDB stores a table's columns in its own order, whatever the order written: + # the key columns in key order, then the value columns by name (ITL-1367; the + # fake models it since main 4d192bfc). + keys = _ARRANGED["keys"] + values = sorted(name for name in _ARRANGED["layout"] if name not in keys) + assert table.arrow_schema().names == [*keys, *values] assert connector.get_table_version("t") == table.version() diff --git a/tests/test_pipeline/test_declared_slot_one_data_tag.py b/tests/test_pipeline/test_declared_slot_one_data_tag.py index 88fcc4045..18892659f 100644 --- a/tests/test_pipeline/test_declared_slot_one_data_tag.py +++ b/tests/test_pipeline/test_declared_slot_one_data_tag.py @@ -2,12 +2,12 @@ A source slot declared from a source whose ``x`` is ``int | None``, bound to the same table with ``x: int`` (a narrower source, given as the declared schema), feeding an -operator. On ``main`` the run raises ``ValueError`` ("Duplicate column name") where the -source's rows are rebuilt for its successor, when exactly one of the two tags is a -data-tag and the tags are declared ``j, k`` (ITL-1366, a ``main`` bug fixed there -separately). A narrower bind hands on its rows as ``main`` gives them (``RowsOnRead``), -built where the successor reads them: the branch raises the same error at the same -point, on the sync and the async path, and completes every other arrangement. +operator. ``main`` before 4d192bfc raised ``ValueError`` ("Duplicate column name") where +the source's rows were rebuilt for its successor, when exactly one of the two tags was a +data-tag and the tags were declared ``j, k`` (ITL-1366); since a tag schema follows the +tag order (ITL-1365, #486), ``main`` completes every arrangement. A narrower bind hands on +its rows as ``main`` gives them (``RowsOnRead``): the branch completes every arrangement +with the bound table's rows, on the sync and the async path, as ``main`` 4d192bfc does. """ from __future__ import annotations @@ -73,15 +73,10 @@ def _rows(job: PipelineJob) -> list[dict[str, Any]]: def test_the_run_is_as_on_main( order: tuple[str, str], roles: str, asynchronous: bool ) -> None: - """Raises where ``main`` raises (ITL-1366), else gives the bound table's rows.""" + """Gives the bound table's rows in every arrangement, as ``main`` 4d192bfc does.""" job = _bound_job(order, ROLES[roles]) kwargs: dict[str, Any] = ( {"orchestrator": AsyncPipelineOrchestrator()} if asynchronous else {} ) - raises_on_main = order == ("j", "k") and roles in ("k_data_tag", "j_data_tag") - if raises_on_main: - with pytest.raises(ValueError, match="Duplicate column name"): - job.run(**kwargs) - else: - job.run(**kwargs) - assert _rows(job) == ROWS + job.run(**kwargs) + assert _rows(job) == ROWS diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index 2ffc76211..ccca3d63c 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -167,12 +167,15 @@ def source(nullable_x: bool) -> ArrowTableSource: assert set(node.keys()[0]) <= set(schema.names) -def test_a_narrower_bind_channel_raises_as_its_rows_do() -> None: - """The source node's channel carries its rows: ITL-1366's input raises as on main. +def test_a_narrower_bind_channel_delivers_its_rows() -> None: + """The source node's channel carries its rows: ITL-1366's input, which ``main`` + completes since 4d192bfc (a tag schema in tag order, #486). - ``open_channel()`` reads the node's output, the rows built when read, which raise - the duplicate-column error ``main``'s row path raises. + ``open_channel()`` reads the node's output, the rows built when read: the table of + the node's rows by ``main``'s row path. """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + import asyncio table = pa.table( @@ -199,8 +202,11 @@ def source(nullable_x: bool) -> ArrowTableSource: slot = next(label for label in job.nodes if label != "selected") job.bind(sources={slot: source(False)}) node: Any = job.nodes[slot] - with pytest.raises(ValueError, match="Duplicate column name"): - asyncio.run(node.open_channel().collect()) + batches = asyncio.run(node.open_channel().collect()) + delivered = pa.Table.from_batches(batches) + expected = StaticOutputOperatorPod._rows_to_table(list(node.iter_data()))[0] # pyright: ignore[reportPrivateUsage] # main's row path + assert delivered.column_names == expected.column_names + assert delivered.to_pylist() == expected.to_pylist() def _replay_job(database: InMemoryArrowDatabase, *, with_successor: bool) -> Any: