From 81d00aa19aa8625485fc246f4755ac9d8f6b2876 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 18:21:50 -0800 Subject: [PATCH 01/12] build(deps): require deltalake>=1.6.6; refuse on Delta what deltalake 1.5+ refuses (ITL-1403) deltalake 1.6.6 makes a Delta MERGE 2-8x faster than 1.0.2 (ITL-1377). It also refuses two kinds of table 1.0.2 took; DeltaTableDatabase now refuses them before anything is queued: - two columns, or two fields of one struct, whose names differ only in case (Delta column names are case-insensitive; refused from 1.5.1); - an append that would change a stored column's recorded Arrow type (a field added to a recorded struct) or a logical column's type: deltalake 1.5+ does not let a commit change a column's field metadata. The lock changes deltalake only. docs/dev/scripts/itl_1403 holds the interop check (every stored table kind, both directions) and the premise check (no job reaches the record refusal on Orcapod's own tables). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 24 ++ docs/dev/scripts/itl_1403/compare.py | 69 +++++ docs/dev/scripts/itl_1403/interop.py | 137 +++++++++ docs/dev/scripts/itl_1403/interop.sh | 17 ++ docs/dev/scripts/itl_1403/premise.py | 260 ++++++++++++++++++ docs/reference/database-types.md | 13 +- docs/troubleshooting.md | 19 -- docs/tutorial/00-setup.md | 3 - docs/tutorial/05-pipeline-job.md | 2 - pyproject.toml | 2 +- src/orcapod/databases/delta_lake_databases.py | 219 +++++++++++++-- tests/test_databases/test_append_by_name.py | 44 ++- .../test_delta_append_preflight.py | 17 +- .../test_delta_read_failures.py | 17 +- .../test_delta_statistics_columns.py | 17 +- .../test_delta_struct_evolution.py | 125 ++++++++- tests/test_databases/type_matrix.py | 13 +- uv.lock | 19 +- 18 files changed, 927 insertions(+), 90 deletions(-) create mode 100644 changelog.d/ITL-1403.md create mode 100644 docs/dev/scripts/itl_1403/compare.py create mode 100644 docs/dev/scripts/itl_1403/interop.py create mode 100755 docs/dev/scripts/itl_1403/interop.sh create mode 100644 docs/dev/scripts/itl_1403/premise.py diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md new file mode 100644 index 000000000..a8c732215 --- /dev/null +++ b/changelog.d/ITL-1403.md @@ -0,0 +1,24 @@ +### Changed + +- Orcapod now requires deltalake 1.6.6 or newer (was 1.0.2). A commit to a Delta table is + faster with it: a one-row MERGE into a 10-million-row table took about 110 ms instead + of about 380 ms, and into a 5 GB table about 1.2 s instead of about 2.6 s. Tables written + by either version are read and appended to by the other, with identical rows, for every + stored table kind. New tables keep Delta protocol 1/2, with no table features. deltalake + 1.6 no longer logs `Skipping column ... because it's a binary field`. +- `DeltaTableDatabase` refuses two columns, or two fields of one struct, whose names + differ only in case (`a` and `A`), before anything is queued + (`UnstorableColumnError`, or `InputValidationError` for a column added beside a held or + queued one). Delta column names are case-insensitive, and deltalake 1.5.1 and later + refuses such a table. The in-memory and connector databases still hold such names as + two columns. +- `DeltaTableDatabase` refuses an append that would change a stored column's recorded + Arrow type (`InputValidationError` naming the column, before anything is queued). This + covers a field added to a struct whose type is recorded: every list and map column, + and every struct holding an unsigned integer, a non-microsecond time type, `float16` + or a fixed-size type. It also covers another logical type over a stored logical + column's storage type. deltalake 1.5 and later does not let a commit change a column's + field metadata, and the record is field metadata. A struct column without a record + still gains fields, a field may still be omitted or reordered, and a new column may + still be added. No job reaches the refusal on the tables Orcapod's own nodes write: a + changed column type changes the table's path. diff --git a/docs/dev/scripts/itl_1403/compare.py b/docs/dev/scripts/itl_1403/compare.py new file mode 100644 index 000000000..1066018db --- /dev/null +++ b/docs/dev/scripts/itl_1403/compare.py @@ -0,0 +1,69 @@ +"""ITL-1403: compare interop dumps: same tables, schemas and rows (run-dependent columns left out). + +usage: python compare.py A.json B.json [C.json ...] (exit 1 when any differs from A) +""" + +from __future__ import annotations + +import json +import sys +from typing import Any + +# Values a run makes, not the data: write times, run ids, row ids drawn at random. +VOLATILE = {"__pod_ts", "executed_at", "pipeline_run_id", "__data_id"} + + +def rows(name: str, table: dict[str, Any]) -> list[str]: + out = [] + for row in table["rows"]: + values = {k: v for k, v in json.loads(row).items() if k not in VOLATILE} + text = json.dumps(values, sort_keys=True) + if "/_result/" in name: + # A result row's record id is a uuid7 drawn when it is stored; the + # source-info tokens of its outputs repeat it. + text = text.replace(values["__record_id"], "") + out.append(text) + return sorted(out) + + +def load(path: str) -> dict[str, Any]: + data = json.load(open(path)) + # Table paths hold no version; compare them as they are. + return data + + +def main() -> int: + first, *others = sys.argv[1:] + a = load(first) + status = 0 + for other in others: + before = status + status = 0 + b = load(other) + if set(a["tables"]) != set(b["tables"]): + print( + f"{other}: tables differ: {sorted(set(a['tables']) ^ set(b['tables']))}" + ) + status = 1 + continue + for name in sorted(a["tables"]): + x, y = a["tables"][name], b["tables"][name] + if x["schema"] != y["schema"]: + print( + f"{other}: {name}: schema differs\n {x['schema']}\n {y['schema']}" + ) + status = 1 + if rows(name, x) != rows(name, y): + print( + f"{other}: {name}: rows differ ({len(x['rows'])} vs {len(y['rows'])})" + ) + status = 1 + print( + f"{first} vs {other}: {'equal' if status == 0 else 'DIFFERENT'} ({len(a['tables'])} tables)" + ) + status = max(status, before) + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/dev/scripts/itl_1403/interop.py b/docs/dev/scripts/itl_1403/interop.py new file mode 100644 index 000000000..e3642071a --- /dev/null +++ b/docs/dev/scripts/itl_1403/interop.py @@ -0,0 +1,137 @@ +"""ITL-1403: a Delta store written by one deltalake version, read and appended by another. + +One job writes every stored table kind into a ``DeltaTableDatabase``: a function pod +(result and pipeline tables), an operator node that logs (a ``Join``: the operator cache), +a cached source and a side-effect pod (its log). ``run`` runs the job over the rows of a +generation (``first``: two rows per source; ``second``: two more), so a second run appends +to every table the first created. ``dump`` writes every stored table, read back through +``DeltaTableDatabase``, with its rows sorted, plus each table's Delta protocol, as JSON. + + interop.py run STORE first + interop.py run STORE second # B reads and appends to A's tables + interop.py dump STORE OUT.json + +``interop.sh`` runs both directions and a single-version control and compares the dumps. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + +import deltalake +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import DeltaTableDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + +ROWS = { + "first": [("s1", 1), ("s2", 2)], + "second": [("s1", 1), ("s2", 2), ("s3", 3), ("s4", 4)], +} + + +def _source( + name: str, data: list[str], rows: list[tuple[str, int]] +) -> ArrowTableSource: + fields = [ + pa.field("z_tag", pa.large_string(), nullable=False), + pa.field("a_tag", pa.int64(), nullable=False), + *(pa.field(n, pa.float64(), nullable=False) for n in data), + ] + arrays = [ + pa.array([z for z, _ in rows], pa.large_string()), + pa.array([a for _, a in rows], pa.int64()), + *( + pa.array([float(a) * (k + 1) for _, a in rows], pa.float64()) + for k in range(len(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, + record_id_columns=["z_tag"], + ) + + +@function_pod(output_keys=["w_out", "c_out"]) +def compute(y: float, b: float) -> tuple[float, float]: + return y + b, y - b + + +def notify(ctx: Any, y: float, b: float) -> None: + return None + + +def run(store: Path, generation: str) -> None: + rows = ROWS[generation] + database = DeltaTableDatabase(store) + job = PipelineJob(name="itl1403", database=database) + cached = CachedSource(_source("left", ["y", "b"], rows), cache_database=database) + with job: + compute.pod(cached, label="fn") + Join()(cached, _source("right", ["x", "e"], rows), label="joined") + SideEffectPod(notify)(cached, label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + database.flush() + + +def _canonical(value: Any) -> Any: + if isinstance(value, bytes): + return value.hex() + if isinstance(value, dict): + return {k: _canonical(v) for k, v in value.items()} + if isinstance(value, list): + return [_canonical(v) for v in value] + return value + + +def dump(store: Path, out: Path) -> None: + database = DeltaTableDatabase(store) + tables: dict[str, Any] = {} + for path in sorted(database.list_table_paths()): + table = database.get_all_records(path, record_id_column="__record_id") + assert table is not None, path + rows = sorted( + ( + json.dumps(_canonical(row), sort_keys=True, default=str) + for row in table.to_pylist() + ) + ) + delta = deltalake.DeltaTable(str(store.joinpath(*path))) + protocol = delta.protocol() + tables["/".join(path)] = { + "schema": [f"{f.name}: {f.type}" for f in table.schema], + "rows": rows, + "protocol": { + "min_reader_version": protocol.min_reader_version, + "min_writer_version": protocol.min_writer_version, + "reader_features": protocol.reader_features, + "writer_features": protocol.writer_features, + }, + "operations": [h["operation"] for h in delta.history()][::-1], + } + out.write_text( + json.dumps({"deltalake": deltalake.__version__, "tables": tables}, indent=1) + ) + print(f"deltalake {deltalake.__version__}: {len(tables)} tables dumped to {out}") + + +if __name__ == "__main__": + if sys.argv[1] == "run": + run(Path(sys.argv[2]), sys.argv[3]) + print(f"deltalake {deltalake.__version__}: ran {sys.argv[3]} on {sys.argv[2]}") + else: + dump(Path(sys.argv[2]), Path(sys.argv[3])) diff --git a/docs/dev/scripts/itl_1403/interop.sh b/docs/dev/scripts/itl_1403/interop.sh new file mode 100755 index 000000000..adcb6f3a2 --- /dev/null +++ b/docs/dev/scripts/itl_1403/interop.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# ITL-1403: a store written by deltalake OLD, read and appended by NEW, the reverse, and a +# control written by OLD alone; every dump read by both versions; dumps compared. +# usage: interop.sh OLD_PYTHON NEW_PYTHON WORKDIR +set -euo pipefail +OLD="$1"; NEW="$2"; W="$3"; HERE="$(cd "$(dirname "$0")" && pwd)" +export RUST_LOG=off +rm -rf "$W"; mkdir -p "$W" +for case in old-new new-old old-old new-new; do + first=${case%-*}; second=${case#*-} + P1=$([ "$first" = old ] && echo "$OLD" || echo "$NEW"); P2=$([ "$second" = old ] && echo "$OLD" || echo "$NEW") + "$P1" "$HERE/interop.py" run "$W/$case" first + "$P2" "$HERE/interop.py" run "$W/$case" second + "$OLD" "$HERE/interop.py" dump "$W/$case" "$W/$case.read-by-old.json" + "$NEW" "$HERE/interop.py" dump "$W/$case" "$W/$case.read-by-new.json" +done +python3 "$HERE/compare.py" "$W/old-old.read-by-old.json" "$W"/*.json diff --git a/docs/dev/scripts/itl_1403/premise.py b/docs/dev/scripts/itl_1403/premise.py new file mode 100644 index 000000000..f923fcf4c --- /dev/null +++ b/docs/dev/scripts/itl_1403/premise.py @@ -0,0 +1,260 @@ +"""ITL-1403: can a job reach the refusal of a recorded type change on its own tables? + +The developer's premise: a table Orcapod's nodes write (function result, pipeline +records, operator cache, cached source, side-effect log) has its column definition fixed +by its path (a schema hash in the path), so no job can append rows whose recorded Arrow +type differs from the stored one. Each case below runs a job twice into one +``DeltaTableDatabase``, varying one thing between the runs, and reports whether the +second run was refused, and which stored tables it wrote: the same path (its rows had to +carry the same record) or a new one. + +Cases (each where the Python schema may be equal but the Arrow record could differ): + +- ``optional_fields``: a dataclass output whose instances leave an optional field + ``None`` in one run and set it in the other. +- ``list_item_nulls``: a ``list[int]`` output holding ``None`` items in one run only. +- ``class_gains_field``: a user class output gaining a field between the runs (the same + module and name, redefined). +- ``nullable_vs_not``: a source tag column ``T | None`` (nulls present) in one run, ``T`` + in the other. +- ``widths``: a source data column ``int32`` in one run, ``int64`` in the other. +- ``struct_gains_field``: a source data column, a struct with a recorded type + (``uint8``), gaining a field between the runs, through a cached source, a function + pod, an operator that logs and a side-effect pod. + +usage: uv run python docs/dev/scripts/itl_1403/premise.py WORKDIR +""" + +import os +import shutil +import subprocess +import sys +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +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 DeltaTableDatabase +from orcapod.side_effects import SideEffectPod +from orcapod.types import CacheMode + + +@dataclass +class Point: + x: float + label: str | None + + +# The same module path and name in both runs; the second run (another process) has a +# field more. +_SHAPE_EXTRA = os.environ.get("ITL1403_SHAPE_EXTRA") == "1" + + +@dataclass +class Shape: + x: float + if _SHAPE_EXTRA: + y: float = 0.0 + + +def _shape(v: float) -> Shape: + return Shape(v, v) if _SHAPE_EXTRA else Shape(v) + + +@function_pod(output_keys=["s"]) +def to_shape(v: float) -> Shape: + return _shape(v) + + +def _source( + name: str, columns: dict[str, "pa.Array[Any]"], tags: list[str] +) -> ArrowTableSource: + schema = pa.schema( + [pa.field(n, a.type, nullable=a.null_count > 0) for n, a in columns.items()] + ) + return ArrowTableSource( + pa.Table.from_arrays(list(columns.values()), schema=schema), + tag_columns=tags, + tag_only_columns=True, + source_id=name, + record_id_columns=["k"], + ) + + +def _keys(n: int) -> "pa.Array[Any]": + return pa.array([f"k{i}" for i in range(n)], pa.large_string()) + + +def notify(ctx: Any, v: Any) -> None: + return None + + +def _job(store: Path, source: ArrowTableSource, pod: Any, data: str) -> None: + """Every stored table kind over ``source``: cached source, function pod, a logging + operator node and a side-effect pod.""" + database = DeltaTableDatabase(store) + job = PipelineJob(name="premise", database=database) + cached = CachedSource(source, cache_database=database) + other = _source( + "other", {"k": _keys(2), "w": pa.array([1.0, 2.0], pa.float64())}, ["k"] + ) + with job: + pod(cached, label="fn") + Join()(cached, other, label="joined") + SideEffectPod(notify)(cached.select_data_columns([data]), label="notify") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + database.flush() + + +def _tables(store: Path) -> set[str]: + return {"/".join(p) for p in DeltaTableDatabase(store).list_table_paths()} + + +@function_pod(output_keys=["out"]) +def identity_v(v: Any) -> Any: # replaced per case with a typed pod + return v + + +def _case(store: Path, first: Callable[[], None], second: Callable[[], None]) -> str: + shutil.rmtree(store, ignore_errors=True) + first() + before = _tables(store) + try: + second() + except Exception as e: # noqa: BLE001 + return f"REFUSED on the second run: {type(e).__name__}: {str(e)[:300]}" + after = _tables(store) + new = sorted(after - before) + return ( + f"no refusal; {len(before)} tables after run 1, {len(new)} new after run 2" + + "".join(f"\n new: {t[:110]}" for t in new) + ) + + +def main(work: Path) -> None: + results: dict[str, str] = {} + + # optional_fields + @function_pod(output_keys=["p"]) + def to_point(v: float) -> Point: + return Point(v, None if v < 10 else f"p{v}") + + def run_points(values: list[float]) -> Callable[[], None]: + src = _source("s", {"k": _keys(2), "v": pa.array(values, pa.float64())}, ["k"]) + return lambda: _job(work / "optional_fields", src, to_point.pod, "v") + + results["optional_fields"] = _case( + work / "optional_fields", run_points([1.0, 2.0]), run_points([11.0, 12.0]) + ) + + # list_item_nulls + @function_pod(output_keys=["items"]) + def to_items(v: float) -> list[int | None]: + return [int(v), None] if v > 10 else [int(v)] + + def run_items(values: list[float]) -> Callable[[], None]: + src = _source("s", {"k": _keys(2), "v": pa.array(values, pa.float64())}, ["k"]) + return lambda: _job(work / "list_item_nulls", src, to_items.pod, "v") + + results["list_item_nulls"] = _case( + work / "list_item_nulls", run_items([1.0, 2.0]), run_items([11.0, 12.0]) + ) + + # class_gains_field: each run in its own process (see ``Shape``). + def run_shape(extra: bool) -> Callable[[], None]: + def go() -> None: + subprocess.run( + [sys.executable, __file__, "shape", str(work / "class_gains_field")], + env={**os.environ, "ITL1403_SHAPE_EXTRA": "1" if extra else "0"}, + check=True, + ) + + return go + + results["class_gains_field"] = _case( + work / "class_gains_field", run_shape(False), run_shape(True) + ) + + # nullable_vs_not: a tag T | None (nulls present), then T. + @function_pod(output_keys=["d"]) + def double(v: float) -> float: + return 2 * v + + def run_tag(nullable: bool) -> Callable[[], None]: + t = pa.array([1, None] if nullable else [1, 2], pa.int64()) + src = ArrowTableSource( + pa.Table.from_arrays( + [_keys(2), t, pa.array([1.0, 2.0], pa.float64())], + schema=pa.schema( + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("t", pa.int64(), nullable=nullable), + pa.field("v", pa.float64(), nullable=False), + ] + ), + ), + tag_columns=["k", "t"], + tag_only_columns=True, + source_id="s", + record_id_columns=["k"], + ) + return lambda: _job(work / "nullable_vs_not", src, double.pod, "v") + + results["nullable_vs_not"] = _case( + work / "nullable_vs_not", run_tag(True), run_tag(False) + ) + + # widths: an int32 data column, then int64. + @function_pod(output_keys=["d"]) + def widen(v: int) -> int: + return v + 1 + + def run_width(width: pa.DataType) -> Callable[[], None]: + src = _source("s", {"k": _keys(2), "v": pa.array([1, 2], width)}, ["k"]) + return lambda: _job(work / "widths", src, widen.pod, "v") + + results["widths"] = _case( + work / "widths", run_width(pa.int32()), run_width(pa.int64()) + ) + + # struct_gains_field: a recorded struct data column (uint8 inside) gaining a field. + @function_pod(output_keys=["n"]) + def count(v: Any) -> int: + return 1 + + def run_struct(extra: bool) -> Callable[[], None]: + fields = [pa.field("a", pa.uint8())] + ( + [pa.field("b", pa.uint8())] if extra else [] + ) + values = [{"a": 1, "b": 2}, {"a": 3, "b": 4}] if extra else [{"a": 1}, {"a": 3}] + src = _source( + "s", {"k": _keys(2), "v": pa.array(values, pa.struct(fields))}, ["k"] + ) + return lambda: _job(work / "struct_gains_field", src, count.pod, "v") + + results["struct_gains_field"] = _case( + work / "struct_gains_field", run_struct(False), run_struct(True) + ) + + for name, outcome in results.items(): + print(f"{name}: {outcome}") + + +if __name__ == "__main__": + if sys.argv[1] == "shape": + store = Path(sys.argv[2]) + src = _source( + "s", {"k": _keys(2), "v": pa.array([1.0, 2.0], pa.float64())}, ["k"] + ) + _job(store, src, to_shape.pod, "v") + else: + main(Path(sys.argv[1])) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 9819e3cfb..88021bf30 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -79,10 +79,19 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map +included) cannot gain a field: the record is the column's field metadata, which Delta +(deltalake 1.5 and later) does not let a commit change, so such an append is refused, +naming the column, before anything is queued. A struct column without a record still +gains fields, and an append may still add a new column. Another logical type over a +stored logical column's storage type is refused the same way. 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 +columns), never by position. Delta alone refuses two columns, or two fields of one +struct, whose names differ only in case: Delta column names are case-insensitive, so +such a table, or an append that would make one, is refused naming both, before anything +is queued. 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, diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6579a12e6..4d494707e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -302,25 +302,6 @@ a path to nothing. **Fix.** Delete output files and the database together, or bump the function's major version to regenerate them. -## Messages you can ignore - -- `WARN deltalake_core::writer::stats] Skipping column ... because it's a binary field.` - whenever a `DeltaTableDatabase` writes to a table that an earlier version of Orcapod - created: one line per binary column (record ids and hashes) per commit. The deltalake - library keeps no minimum and maximum statistics for binary columns and says so on every - write; nothing is wrong with the table. A table that `DeltaTableDatabase` creates now names - the columns it keeps statistics for (the `delta.dataSkippingStatsColumns` table property), - and writes to it log nothing. Orcapod never changes the property of an existing table. To - hide only this line for an older table, set `RUST_LOG` in the environment before Python - starts, keeping deltalake's other warnings: - - ``` - RUST_LOG="warn,deltalake_core::writer::stats=error" python my_pipeline.py - ``` - - deltalake reads `RUST_LOG` once, when it is first imported, so setting it later in the - same process (for example with `os.environ`) has no effect. - ## A script finishes its work but the process never exits **Symptom.** A Python script that used a Delta database prints all of its output and then hangs, diff --git a/docs/tutorial/00-setup.md b/docs/tutorial/00-setup.md index 6d2eebd92..7ab90205c 100644 --- a/docs/tutorial/00-setup.md +++ b/docs/tutorial/00-setup.md @@ -80,9 +80,6 @@ Depending on what else is installed, you may see these on your screen. They are - `UserWarning: Protobuf gencode version ... is exactly one major version older than the runtime version ...`, several times, when Orcapod is imported. -- `WARN deltalake_core::writer::stats] Skipping column ... because it's a binary field.`, - many times, whenever results are written to an on-disk database (from - [Part 5](05-pipeline-job.md) on). ## Get the dataset diff --git a/docs/tutorial/05-pipeline-job.md b/docs/tutorial/05-pipeline-job.md index 3291b904a..fb2d17fde 100644 --- a/docs/tutorial/05-pipeline-job.md +++ b/docs/tutorial/05-pipeline-job.md @@ -234,8 +234,6 @@ print(len(calls)) ``` This is a different, empty database, so everything was computed once more: 71 further calls. -(You will see many `WARN deltalake_core::writer::stats` lines while it writes. They are -harmless; see [Part 0](00-setup.md#messages-you-can-ignore).) Now do what a new Python session would do: make a new database object for the same directory, build the job, run it. diff --git a/pyproject.toml b/pyproject.toml index cd3e10a74..8913e2945 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ "polars>=1.36.0", "numpy>=1.26.4", "beartype>=0.21.0", - "deltalake>=1.0.2", + "deltalake>=1.6.6", "gitpython>=3.1.45", "universal-pathlib>=0.3.8", "starfix>=0.6.0,<0.7", diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index cbf6e2831..006725268 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -448,28 +448,100 @@ def _with_merged_records( own = original.schema.field(field.name).type if position < 0 or isinstance(own, pa.ExtensionType): continue - stored_record = stored_records.get(field.name) - incoming_record = recorded_type(field.metadata) - if stored_record is None and incoming_record is None: - continue - base = ( - stored_record - if stored_record is not None - else arrow_utils.normalize_to_large_types(stored.field(position).type) - ) - incoming = ( - incoming_record - if incoming_record is not None - else arrow_utils.normalize_to_large_types(own) + merged = _merged_record( + stored.field(position).type, stored_records.get(field.name), own, field ) + if merged is None: + continue written = written.set_column( - index, - with_recorded_type(field, merged_type(base, incoming)), - written.column(index), + index, with_recorded_type(field, merged), written.column(index) ) return written +def _merged_record( + stored_type: pa.DataType, + stored_record: pa.DataType | None, + own: pa.DataType, + written: "pa.Field[Any]", +) -> pa.DataType | None: + """The record a column has after an append, or ``None`` when it has none. + + A column recorded on either side (stored or incoming) is recorded as the merge of + its stored type (its record, else its stored type) and the incoming rows' type + (``merged_type``). + + Args: + stored_type: The column's type as Delta stores it. + stored_record: The column's stored record, or ``None``. + own: The incoming rows' own type for the column. + written: The incoming column as it is written (``to_delta_layout``). + + Returns: + The merged record, or ``None`` when neither side is recorded. + """ + incoming_record = recorded_type(written.metadata) + if stored_record is None and incoming_record is None: + return None + base = ( + stored_record + if stored_record is not None + else arrow_utils.normalize_to_large_types(stored_type) + ) + incoming = ( + incoming_record + if incoming_record is not None + else arrow_utils.normalize_to_large_types(own) + ) + return merged_type(base, incoming) + + +# Why Delta refuses names that differ only in case (ITL-1403). +_CASE_INSENSITIVE = ( + "Delta column names are case-insensitive, so a Delta table cannot hold both" +) + + +def _differ_only_in_case(names: list[str]) -> tuple[str, str] | None: + """The first two of ``names`` that differ only in case, or ``None``.""" + seen: dict[str, str] = {} + for name in names: + other = seen.setdefault(name.lower(), name) + if other != name: + return other, name + return None + + +def _nested_names_differing_in_case(arrow_type: pa.DataType) -> tuple[str, str] | None: + """Two field names of one struct inside ``arrow_type`` that differ only in case.""" + if isinstance(arrow_type, pa.ExtensionType): + return _nested_names_differing_in_case(arrow_type.storage_type) + if pa.types.is_struct(arrow_type): + found = _differ_only_in_case( + [arrow_type.field(i).name for i in range(arrow_type.num_fields)] + ) + if found is not None: + return found + for i in range(arrow_type.num_fields): + found = _nested_names_differing_in_case(arrow_type.field(i).type) + if found is not None: + return found + return None + + +def _case_reason(first: str, second: str, nested: bool = False) -> str: + where = "struct fields" if nested else "columns" + return f"{where} {first!r} and {second!r} differ only in case: {_CASE_INSENSITIVE}" + + +# Why a recorded column's record cannot change on Delta (ITL-1403). +_RECORD_CHANGE = ( + "the append would change the column's recorded Arrow type, and a recorded " + "column's type cannot change on a Delta table: deltalake refuses a commit that " + "changes a column's field metadata (deltalake 1.5 and later)" +) + + _EXTENSION_KEYS = (b"ARROW:extension:name", b"ARROW:extension:metadata") @@ -632,6 +704,74 @@ def _non_null_violation( return None +def _changed_record( + delta_table: deltalake.DeltaTable, rows: pa.Table +) -> tuple[str, str] | None: + """The first stored column whose record (or nested names) the append would change. + + deltalake (1.5 and later) refuses a commit that changes a column's field metadata, + and a recorded column's record is its field metadata: an append whose merged + record (``_merged_record``, what the commit would write) is not the stored one is + refused here, before anything is queued. An append that leaves the record as it + is, a column with no record on either side (a plain struct still evolves), and a + new column are not concerned. A struct evolution that would put two field names + differing only in case into one struct is refused too. + + Args: + delta_table: The loaded stored table. + rows: The rows to append, with their own types. + + Returns: + ``(column, reason)``, or ``None``. + """ + stored = _stored_arrow_schema(delta_table) + stored_metadata = {f.name: f.metadata for f in delta_table.schema().fields} + stored_records = { + name: recorded_type(metadata) for name, metadata in stored_metadata.items() + } + for field in rows.schema: + position = stored.get_field_index(field.name) + if position < 0: + continue + # A logical column's type is named in its field metadata: another logical + # type over the same storage type would change it. + stored_extension = stored_metadata[field.name].get("ARROW:extension:name") + incoming_extension = ( + field.type.extension_name + if isinstance(field.type, pa.ExtensionType) + else None + ) + if stored_extension != incoming_extension: + return field.name, ( + f"it is stored as logical type {stored_extension!r} and the rows hold " + f"{incoming_extension!r}: a column's field metadata cannot change on a " + "Delta table (deltalake 1.5 and later refuses such a commit)" + ) + if incoming_extension is not None: + continue + stored_type = stored.field(position).type + stored_record = stored_records.get(field.name) + merged = _merged_record( + stored_type, stored_record, field.type, written_field(field) + ) + if merged is not None and ( + stored_record is None + or not stored_record.equals(merged, check_metadata=True) + ): + return field.name, _RECORD_CHANGE + try: + evolved = merged_type( + arrow_utils.normalize_to_large_types(stored_type), + arrow_utils.normalize_to_large_types(field.type), + ) + except Exception: # noqa: BLE001 # a type change: the type check reports it + continue + nested = _nested_names_differing_in_case(evolved) + if nested is not None: + return field.name, _case_reason(*nested, nested=True) + return None + + def _append_refusal( delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: @@ -661,6 +801,13 @@ def _append_refusal( change = _column_change(held[field.name], field) if change is not None: return field.name, change + else: + clash = _differ_only_in_case([*held, field.name]) + if clash is not None: + return field.name, _case_reason(*clash) + changed = _changed_record(delta_table, rows) + if changed is not None: + return changed violation = _non_null_violation(held, rows) if violation is not None: name, omitted = violation @@ -831,6 +978,9 @@ def delta_unstorable_reason(field: "pa.Field[Any]") -> str | None: Delta's reason (``Invalid data type for Delta Lake: Decimal256(40, 2)``), or ``None`` when Delta holds the column. """ + nested = _nested_names_differing_in_case(field.type) + if nested is not None: + return _case_reason(*nested, nested=True) if arrow_utils.holds_renamed_map(field.type): # The recorded type goes through Arrow IPC, which renames them (ITL-1334). return "a map's key and item fields read back as 'key' and 'value'" @@ -1626,10 +1776,21 @@ def require_storable(self, schema: pa.Schema) -> None: Args: schema: The Arrow schema of a table this database is to hold. + Two columns whose names differ only in case are refused too: Delta column + names are case-insensitive (ITL-1403). + Raises: UnstorableColumnError: For the first column Delta cannot hold, naming the column, its Arrow type and Delta's reason. """ + clash = _differ_only_in_case(schema.names) + if clash is not None: + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=clash[1], + arrow_type=schema.field(clash[1]).type, + reason=_case_reason(*clash), + ) for field in schema: reason = delta_unstorable_reason(field) if reason is not None: @@ -1640,6 +1801,31 @@ def require_storable(self, schema: pa.Schema) -> None: reason=reason, ) + def _refuse_case_clash_with_pending( + self, record_path: tuple[str, ...], schema: pa.Schema + ) -> None: + """Refuse a column whose name differs only in case from a queued one (ITL-1403). + + Checked before the schema handling, which would otherwise report the queued + and the new columns as a mismatch. A stored table's columns are checked by + ``_append_refusal``. + + Raises: + InputValidationError: Naming both columns. + """ + pending = self._pending_batches.get(self._get_record_key(record_path)) + if pending is None: + return + queued = pending.schema.names + clash = _differ_only_in_case( + [*queued, *(n for n in schema.names if n not in queued)] + ) + if clash is not None: + raise InputValidationError( + f"Cannot add rows to {self._get_table_uri(record_path)!r}: column " + f"{clash[1]!r}: {_case_reason(*clash)}. Nothing was queued." + ) + def _refuse_unmergeable_append( self, record_path: tuple[str, ...], @@ -1875,6 +2061,7 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) + self._refuse_case_clash_with_pending(record_path, records.schema) self._refuse_untyped_null_columns(record_path, records.schema) # Step 2: Deduplicate within input table (keep last occurrence) diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 4fe75ba5d..ccacc5b7a 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -37,7 +37,6 @@ 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 @@ -440,13 +439,13 @@ def test_the_step_leaves_anything_else_as_given( assert in_held_column_order(given, held) is given -@pytest.mark.parametrize("database", ["in-memory", "Delta"]) +@pytest.mark.parametrize("database", ["in-memory"]) @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.""" + """The in-memory database holds ``a`` and ``A`` apart; an append of them in another + order is matched by exact name. (Delta refuses them: below.)""" 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"])) @@ -459,6 +458,31 @@ def test_names_differing_in_case_only_are_two_columns( ] +@pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) +def test_delta_refuses_names_differing_only_in_case(tmp_path: Path, when: str) -> None: + """Delta column names are case-insensitive (deltalake 1.5.1 and later refuses + such a table): ``a`` and ``A`` in one table are refused before anything is + queued, in one batch and as a column added beside a held one (ITL-1403).""" + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match="differ only in case") as info: + _add(db, _table_with_id(b"r1", [ID, "a", "A"])) + assert info.value.column == "A" + _add(db, _table_with_id(b"r1", [ID, "a"]), flush=when == "after a flush") + with pytest.raises(InputValidationError, match="'a' and 'A' differ only in case"): + # ``merge``: a new column beside a pending batch is otherwise refused by the + # schema check before the name is looked at. + db.add_records( + PATH, + _table_with_id(b"r2", ["A", ID]), + record_id_column=ID, + schema_handling="merge", + ) + db.flush() + table = db.get_all_records(PATH, record_id_column=ID) + assert table is not None + assert table.select([ID, "a"]).to_pylist() == [{ID: b"r1", "a": 1}] + + def _table_with_id(rid: bytes, order: list[str]) -> pa.Table: columns = { ID: pa.array([rid], pa.large_binary()), @@ -825,12 +849,12 @@ def rows(n: int, pair: Any, order: list[str]) -> pa.Table: 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 + # Delta refuses another logical type where one is stored, before anything is + # queued: deltalake 1.5 and later refuses the commit (ITL-1403). Before, Delta + # took the rows and the table could no longer be read as one type + # (ITL-1371's family). + with pytest.raises(InputValidationError, match="logical type"): + second.add_records(PATH, permuted, record_id_column="rid", flush=True) inner.flush() stored_rows = inner.get_all_records(PATH, record_id_column="rid") assert stored_rows is not None diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index d37919f53..27327206c 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -304,7 +304,8 @@ def test_a_null_child_of_an_evolving_struct_appends( tmp_path: Path, appended: Any ) -> None: """Delta's MERGE panicked on a ``null`` child of a struct that gains a field - (pre-existing); the child is written as typed nulls of its stored type.""" + (pre-existing); the child is written as typed nulls of its stored type. Inside a + list (a recorded column) the evolution is refused instead (ITL-1403).""" stored_type = _struct(pa.field("a", I64)) in_list = pa.types.is_large_list(appended) db = DeltaTableDatabase(tmp_path) @@ -321,9 +322,21 @@ def test_a_null_child_of_an_evolving_struct_appends( flush=True, ) value = {"a": None, "b": 2} + if in_list: + # A list column is recorded, and its record would change: refused on Delta + # before anything is buffered (ITL-1403). + with pytest.raises(InputValidationError, match="recorded Arrow type"): + db.add_records( + PATH, + _rows([b"2"], x=(appended, [[value]])), + record_id_column="id", + flush=True, + ) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + return db.add_records( PATH, - _rows([b"2"], x=(appended, [[value]] if in_list else [value])), + _rows([b"2"], x=(appended, [value])), record_id_column="id", flush=True, ) diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 8948b9db8..842d37d1c 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -469,24 +469,23 @@ def test_new_struct_field(self, base: Path) -> None: {"a": 2, "b": 3}, ] - def test_new_struct_field_inside_a_list(self, base: Path) -> None: - """An append that adds a field to a struct inside a list column succeeds.""" + def test_new_struct_field_inside_a_list_is_refused(self, base: Path) -> None: + """An append that adds a field to a struct inside a list column would change + the list column's recorded type: refused before anything is buffered, the + stored rows unchanged (deltalake refuses such a commit; ITL-1403).""" db = DeltaTableDatabase(base_path=base) stored_type = pa.large_list(pa.struct([("a", pa.int64())])) append(db, rows([b"a"], pa.array([[{"a": 1}]], stored_type))) evolved = pa.large_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) - append(db, rows([b"b"], pa.array([[{"a": 2, "b": 3}]], evolved))) + with pytest.raises(InputValidationError, match="recorded Arrow type"): + append(db, rows([b"b"], pa.array([[{"a": 2, "b": 3}]], evolved))) back = DeltaTableDatabase(base_path=base).get_all_records( PATH, record_id_column="rid" ) assert back is not None - back = back.sort_by("rid") - assert back.schema.field("x").type == evolved - assert back.column("x").to_pylist() == [ - [{"a": 1, "b": None}], - [{"a": 2, "b": 3}], - ] + assert back.schema.field("x").type == stored_type + assert back.column("x").to_pylist() == [[{"a": 1}]] def test_missing_column(self, base): """An append that omits a stored column succeeds.""" diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index 87d368bd3..e13b369d8 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -449,14 +449,18 @@ def test_a_listed_column_prunes_files(self, tmp_path: Path) -> None: .read_all() ) text = "\n".join(str(row) for row in plan.to_pylist()) - assert "files_pruned=2, files_scanned=1" in text, text + # The scan is given only the file whose statistics can hold the value: the + # other two are pruned before it (deltalake 1.6 lists the files it scans). + assert text.count(".parquet") == 1, text + assert "file_groups={1 group:" in text, text class TestTablesCreatedElsewhere: def test_existing_table_without_the_property_is_unaltered( self, tmp_path: Path, capfd: pytest.CaptureFixture[str] ) -> None: - """A table created before ITL-1187 keeps no property and keeps warning.""" + """A table created before ITL-1187 keeps no property: delta-rs keeps statistics + for every column it can, and none for a binary one.""" deltalake.write_deltalake(str(tmp_path / "t"), rows(range(0, 10))) db = DeltaTableDatabase(tmp_path) capfd.readouterr() @@ -464,9 +468,14 @@ def test_existing_table_without_the_property_is_unaltered( db.add_records(PATH, rows(range(10, 20)), flush=True) db.add_records(PATH, rows(range(15, 30)), skip_duplicates=False, flush=True) - # The capture works: this table has no property, so delta-rs warns. - assert stats_warnings(capfd) != [] + # deltalake 1.6 no longer logs the binary-column warning (1.0.2 did); what + # the property was about stays: no min/max is kept for a binary column. assert configuration(tmp_path / "t") == {} + added = pa.table( + deltalake.DeltaTable(str(tmp_path / "t")).get_add_actions(flatten=True) + ) + assert "min.v" in added.column_names + assert not any(n.startswith("min.h") for n in added.column_names) assert stored_ids(db) == sorted(f"id{i}".encode() for i in range(30)) def test_plain_deltalake_appends_to_a_table_with_the_property( diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index 877b1b32f..f5cbe037b 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -3,9 +3,14 @@ Schema evolution is on by default: an append may add struct fields, omit some, or give them in another order. Delta's MERGE matches struct fields by position, so the rows are first given the stored struct layout by name (``_conformed_to_stored``), and a column -whose Arrow type is recorded has its record describe the merged column (``merged_type``), -which a read restores by name. Every read path, on a fresh database object, gives each -value under the name it was written with: never swapped, never dropped. +whose Arrow type is recorded keeps its record, which a read restores by name. Every read +path, on a fresh database object, gives each value under the name it was written with: +never swapped, never dropped. + +An append that would CHANGE a recorded column's record (a field added to a recorded +struct) is refused before anything is buffered: deltalake 1.5 and later refuses a commit +that changes a column's field metadata, and the record is field metadata (ITL-1403). A +struct with no record still gains fields, and a new column is still added. A ``null``-typed part with nothing stored at its path (a new struct field, the items of a new list) is refused naming the column and the path, before anything is buffered. @@ -88,19 +93,28 @@ def _rows(ids: list[bytes], **columns: tuple[list[Any], pa.DataType]) -> pa.Tabl [{"a": 3.0}], [{"a": 1.0, "b": 2}, {"a": 3.0, "b": None}], ), + "added, unrecorded": ( + _struct(("a", I64)), + [{"a": 1}], + _struct(("a", I64), ("c", I64)), + [{"a": 3, "c": 5}], + [{"a": 1, "c": None}, {"a": 3, "c": 5}], + ), +} + +# Appends that would change a recorded column's record: refused (ITL-1403). +RECORD_CHANGES: dict[str, tuple[Any, list[Any], Any, list[Any]]] = { "added, recorded": ( _struct(("a", F16)), [{"a": 1.0}], _struct(("a", F16), ("c", pa.list_(pa.int16(), 2))), [{"a": 3.0, "c": [5, 6]}], - [{"a": 1.0, "c": None}, {"a": 3.0, "c": [5, 6]}], ), "reordered and added, in a list": ( pa.large_list(_struct(("a", pa.uint8()), ("b", I64))), [[{"a": 1, "b": 2}]], pa.large_list(_struct(("c", I64), ("b", I64), ("a", pa.uint8()))), [[{"c": 9, "b": 4, "a": 3}]], - [[{"a": 1, "b": 2, "c": None}], [{"a": 3, "b": 4, "c": 9}]], ), } @@ -141,6 +155,61 @@ def test_an_evolved_struct_keeps_every_value_under_its_name( assert back.column(name).to_pylist() == expected, name +@pytest.mark.parametrize("flush", [True, False], ids=["flushed", "queued"]) +@pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) +def test_an_append_changing_a_recorded_type_is_refused_before_buffering( + tmp_path: pathlib.Path, case: str, flush: bool +) -> None: + first, first_values, appended, appended_values = RECORD_CHANGES[case] + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], k=([7], pa.int64()), x=(first_values, first)), + record_id_column="id", + flush=True, + ) + with pytest.raises( + InputValidationError, + match=r"column 'x': the append would change the column's recorded Arrow type", + ): + db.add_records( + PATH, + _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)), + record_id_column="id", + flush=flush, + ) + db.flush() # nothing was queued + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.column("id").to_pylist() == [b"1"] + assert back.column("x").to_pylist() == first_values + + +def test_a_new_column_is_still_added(tmp_path: pathlib.Path) -> None: + """A column the table does not hold changes no stored record: it is added.""" + recorded = _struct(("a", F16)) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + _rows([b"1"], x=([{"a": 1.0}], recorded)), + record_id_column="id", + flush=True, + ) + db.add_records( + PATH, + _rows( + [b"2"], x=([{"a": 2.0}], recorded), z=([[1, 2]], pa.list_(pa.int16(), 2)) + ), + record_id_column="id", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + back = back.sort_by("id") + assert back.column("z").to_pylist() == [None, [1, 2]] + assert back.schema.field("z").type == pa.list_(pa.int16(), 2) + + def test_omitting_a_non_nullable_stored_field_is_refused( tmp_path: pathlib.Path, ) -> None: @@ -317,28 +386,31 @@ def test_adding_a_non_nullable_struct_field_is_refused( def test_adding_a_nullable_field_with_a_non_nullable_child_appends( tmp_path: pathlib.Path, ) -> None: - """The stored rows read the new field as null, so its child needs no value.""" + """The stored rows read the new field as null, so its child needs no value. + + An unrecorded struct (a recorded one cannot gain a field on Delta: ITL-1403). + """ added = pa.struct( - [pa.field("a", F16), pa.field("b", pa.struct([pa.field("c", F16, False)]))] + [pa.field("a", I64), pa.field("b", pa.struct([pa.field("c", I64, False)]))] ) db = DeltaTableDatabase(tmp_path) db.add_records( PATH, - _rows([b"1"], x=([{"a": 1.0}], _struct(("a", F16)))), + _rows([b"1"], x=([{"a": 1}], _struct(("a", I64)))), record_id_column="id", flush=True, ) db.add_records( PATH, - _rows([b"2"], x=([{"a": 2.0, "b": {"c": 3.0}}], added)), + _rows([b"2"], x=([{"a": 2, "b": {"c": 3}}], added)), record_id_column="id", flush=True, ) back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") assert back is not None assert back.sort_by("id").column("x").to_pylist() == [ - {"a": 1.0, "b": None}, - {"a": 2.0, "b": {"c": 3.0}}, + {"a": 1, "b": None}, + {"a": 2, "b": {"c": 3}}, ] @@ -458,3 +530,34 @@ def test_a_new_column_keeps_every_other_columns_type( for name in ("items", "u", "s", "p"): assert str(back.schema.field(name).type) == str(first.schema.field(name).type) assert back.sort_by("id").column("added").to_pylist() == [None, "a"] + + +def test_struct_fields_differing_only_in_case_are_refused( + tmp_path: pathlib.Path, +) -> None: + """Delta field names are case-insensitive at every depth (ITL-1403): a struct + holding ``x`` and ``X`` is refused, and so is an evolution that would add ``X`` + beside a stored ``x``, before anything is queued.""" + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError, match="'x' and 'X' differ only in case"): + db.add_records( + PATH, + _rows([b"1"], s=([{"x": 1, "X": 2}], _struct(("x", I64), ("X", I64)))), + record_id_column="id", + ) + db.add_records( + PATH, + _rows([b"1"], s=([{"x": 1}], _struct(("x", I64)))), + record_id_column="id", + flush=True, + ) + with pytest.raises(InputValidationError, match="'x' and 'X' differ only in case"): + db.add_records( + PATH, + _rows([b"2"], s=([{"X": 2}], _struct(("X", I64)))), + record_id_column="id", + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") + assert back is not None + assert back.column("s").to_pylist() == [{"x": 1}] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index a3c298224..8adab576c 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1054,10 +1054,19 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map +included) cannot gain a field: the record is the column's field metadata, which Delta +(deltalake 1.5 and later) does not let a commit change, so such an append is refused, +naming the column, before anything is queued. A struct column without a record still +gains fields, and an append may still add a new column. Another logical type over a +stored logical column's storage type is refused the same way. 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 +columns), never by position. Delta alone refuses two columns, or two fields of one +struct, whose names differ only in case: Delta column names are case-insensitive, so +such a table, or an append that would make one, is refused naming both, before anything +is queued. 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, diff --git a/uv.lock b/uv.lock index fe03d5d44..31a050573 100644 --- a/uv.lock +++ b/uv.lock @@ -793,20 +793,21 @@ wheels = [ [[package]] name = "deltalake" -version = "1.0.2" +version = "1.6.6" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "arro3-core" }, { name = "deprecated" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1e/c3/19cd8457243c41aa60562d28b66271ff958d896e3fd9373816d8fd781f1a/deltalake-1.0.2.tar.gz", hash = "sha256:fbe4cccde0af14c6e30b62cc3dd09e9a46777e8fd8e375ec809a6bf4edea756c", size = 5076074, upload-time = "2025-06-02T11:08:14.063Z" } +sdist = { url = "https://files.pythonhosted.org/packages/24/7e/817984d82cec757f6f3a3dbb84afcd85027e7ae02e0a354702c2127f6777/deltalake-1.6.6.tar.gz", hash = "sha256:91864d97adb429fa8b8748b4f68d69adab3d0417ffa9f100bdb85805890c997f", size = 5650031, upload-time = "2026-09-24T11:31:48.009Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/74/043f52f50cbda7f651d39465fb7c5a9e8880e9a332abbb4f64c4d0522306/deltalake-1.0.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e4f24cdbadaf8a4c32ae535a44b89d8bcafd5cb97897de33a4ec8609058a7d50", size = 41649942, upload-time = "2025-06-02T11:08:17.754Z" }, - { url = "https://files.pythonhosted.org/packages/f9/99/ced0f538deacdf0f1e78e28a14c30420d8df1c7d9ca30ff8f71a03a008a7/deltalake-1.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:43731c48657c16c1728c90270e5e7ae1f3fa1a5b6fb0cb0b55c88c5c8f23cc3f", size = 38590012, upload-time = "2025-06-02T11:09:07.48Z" }, - { url = "https://files.pythonhosted.org/packages/6f/f1/feee0df833eed13a27aafeedfac313c0b6bf7b0d712fa5892b1099a7a752/deltalake-1.0.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c921b47e4810a346650141dae30abc69564e57f26e00cce256f1837dd9c4b5fd", size = 40281750, upload-time = "2025-06-02T11:08:52.532Z" }, - { url = "https://files.pythonhosted.org/packages/dc/6f/4707d7511bd172f6c6504e87ea0bc43cdf7b5a4c85340ff61cee83170e37/deltalake-1.0.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59a3b403e5871d12920798d27f2b1e4b70f4e975381841066cb6733ccbc80071", size = 51273870, upload-time = "2025-06-02T11:08:10.194Z" }, - { url = "https://files.pythonhosted.org/packages/5c/2a/1dfc1f337f85d62141b4e70923b923d5faccbe666d4253b670c6d506d1bb/deltalake-1.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:67d3224ce7e569bbb6d5181f9ed2530b237a1cdc87f413e5ff0bc1227aab50d5", size = 40293966, upload-time = "2025-06-02T11:08:51.989Z" }, - { url = "https://files.pythonhosted.org/packages/78/a9/9014b804f947a505c21a6c0cbc87e2673cacb6cd82ac70be9a60f26a836b/deltalake-1.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:7a1606f535416d4a38ce554019f9fcad194aaec33d638328662b2de46af03059", size = 42567914, upload-time = "2025-06-02T11:23:49.313Z" }, + { url = "https://files.pythonhosted.org/packages/44/d5/fee90d565b32a166777a2c39ca7c77e1b8b8240a4ecfc9eeeabc2fb9fd63/deltalake-1.6.6-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:9b9883cc1236a44f62ed360abd1f39e564d892848b8a1aa5483871d12d23f74e", size = 50800766, upload-time = "2026-09-24T13:08:43.437Z" }, + { url = "https://files.pythonhosted.org/packages/bf/59/83e954337cb28173b5699a46f8350d8f76b15b20c6f055463b4d1ae343c0/deltalake-1.6.6-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:9e97c964ac768e104a58f147c3b41f281e9ed010825e02a3846d4a9c571a5d8a", size = 47072020, upload-time = "2026-09-24T12:58:11.229Z" }, + { url = "https://files.pythonhosted.org/packages/75/8f/07925ff4f54d8ce35f33961f27e224e3073b7286d9041b95f8e84549fe4a/deltalake-1.6.6-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:802db1ae734295c7b947bddd228b9e6b5df702846b085be91ad593840f72e36c", size = 52017042, upload-time = "2026-09-24T12:04:22.8Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e0/120f64cc7d3ccf4f28207e3bef566fcfcadab6887f8b18864eca16425d11/deltalake-1.6.6-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:25edf9373e6dd21f5db4792b1176a7b3e1780d2072e52e8d1433ba8f5e356c30", size = 50905121, upload-time = "2026-09-24T11:50:03.525Z" }, + { url = "https://files.pythonhosted.org/packages/23/46/35a59c6d24de9fdb3b68b41bc458ae9dc561a27b74e19d08137de1c8a695/deltalake-1.6.6-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:018e7b1d6a1098e365480cda810651b5570e38fad2236ea5f4a3e152457d8cc2", size = 50922944, upload-time = "2026-09-24T11:50:48.724Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ed/fd2cdf5edcea2ee90b75c5891f5a542b8564cf69bc92e174dab26b45819a/deltalake-1.6.6-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e2829c996dcf32bd6135e2eafe5b807f47ad40e84711c1453ee7b63f4548c034", size = 52029056, upload-time = "2026-09-24T12:03:08.689Z" }, + { url = "https://files.pythonhosted.org/packages/a4/a0/aa5d6643b85a9509b241e34df3b3e6720653279eb230e6025f7beee8eeb6/deltalake-1.6.6-cp310-abi3-win_amd64.whl", hash = "sha256:9a4d95a2c2ca70ef8b4f21e599850e2c21374bbde0fab3414388e5ef7d3f69e0", size = 55542042, upload-time = "2026-09-24T12:35:30.393Z" }, ] [[package]] @@ -2124,7 +2125,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "beartype", specifier = ">=0.21.0" }, - { name = "deltalake", specifier = ">=1.0.2" }, + { name = "deltalake", specifier = ">=1.6.6" }, { name = "gitpython", specifier = ">=3.1.45" }, { name = "ipywidgets", marker = "extra == 'all'", specifier = ">=8.1.7" }, { name = "ipywidgets", marker = "extra == 'ray'", specifier = ">=8.1.7" }, From c543f2a8c8ca163feef92b5f5640c2e168ff94e7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:26:37 -0800 Subject: [PATCH 02/12] fix(databases): refuse when added what deltalake 1.6 refuses at commit (ITL-1403 review) Review of PR 504 (seven findings, all reproduced): 1. A struct field differing in case from a QUEUED one is refused when added, on the merged pending and incoming type, at every depth. 2-3. The preflight computes the field metadata the commit would send, with the flush's own functions (to_delta_layout, _conformed_to_stored, _with_merged_records), and refuses a stored key given another value, as delta-rs try_merge_metadata does: the small-list record of an evolved struct, and a logical column's extension metadata (not only its name). 4. Delta folds case with Rust's to_lowercase; where Python's str.lower differs, the flush turns Delta's duplicate-name error into UnstorableColumnError once and drops the batch (every later flush would fail the same way). 5. An untyped null appended to a stored logical column claims no type: accepted. 6-7. Disclosed: an operator whose result type depends on its data now fails at the store (ITL-1410 will refuse it at the operator; kept in premise.py); a table written before deltalake 1.5.1 with 'a' and 'A' cannot be read on 1.6, and an append to it is refused when added, with nothing queued. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 60 ++++-- docs/dev/scripts/itl_1403/premise.py | 62 ++++++ docs/reference/database-types.md | 12 +- src/orcapod/databases/delta_lake_databases.py | 192 ++++++++++++++---- .../test_delta_refused_before_queueing.py | 178 ++++++++++++++++ tests/test_databases/type_matrix.py | 12 +- 6 files changed, 443 insertions(+), 73 deletions(-) create mode 100644 tests/test_databases/test_delta_refused_before_queueing.py diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index a8c732215..7c32c8d7f 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -1,24 +1,48 @@ +### Breaking changes and migration + +- A Delta table that holds two columns whose names differ only in case (`a` and `A`), + which `DeltaTableDatabase` stored before this release, can no longer be read with + deltalake 1.6 (`OrcapodDatabaseReadError`: Delta column names are case-insensitive). + An append to such a table is refused when the rows are added, naming the cause, with + nothing queued. Such a store is affected only if a table of it has two such names: + for example a function with output keys `a` and `A`, or a source with such columns. + Read it with Orcapod 0.3 (deltalake before 1.5.1) and write it again with distinct + names. + ### Changed - Orcapod now requires deltalake 1.6.6 or newer (was 1.0.2). A commit to a Delta table is faster with it: a one-row MERGE into a 10-million-row table took about 110 ms instead - of about 380 ms, and into a 5 GB table about 1.2 s instead of about 2.6 s. Tables written - by either version are read and appended to by the other, with identical rows, for every - stored table kind. New tables keep Delta protocol 1/2, with no table features. deltalake - 1.6 no longer logs `Skipping column ... because it's a binary field`. + of about 380 ms, and into a 5 GB table about 1.2 s instead of about 2.6 s. Every other + table written by either version is read and appended to by the other, with identical + rows, for every stored table kind. New tables keep Delta protocol 1/2, with no table + features. deltalake 1.6 no longer logs `Skipping column ... because it's a binary field`. - `DeltaTableDatabase` refuses two columns, or two fields of one struct, whose names differ only in case (`a` and `A`), before anything is queued - (`UnstorableColumnError`, or `InputValidationError` for a column added beside a held or - queued one). Delta column names are case-insensitive, and deltalake 1.5.1 and later - refuses such a table. The in-memory and connector databases still hold such names as - two columns. -- `DeltaTableDatabase` refuses an append that would change a stored column's recorded - Arrow type (`InputValidationError` naming the column, before anything is queued). This - covers a field added to a struct whose type is recorded: every list and map column, - and every struct holding an unsigned integer, a non-microsecond time type, `float16` - or a fixed-size type. It also covers another logical type over a stored logical - column's storage type. deltalake 1.5 and later does not let a commit change a column's - field metadata, and the record is field metadata. A struct column without a record - still gains fields, a field may still be omitted or reordered, and a new column may - still be added. No job reaches the refusal on the tables Orcapod's own nodes write: a - changed column type changes the table's path. + (`UnstorableColumnError`, or `InputValidationError` for a column or field added beside a + stored or queued one). Delta column names are case-insensitive, and deltalake 1.5.1 + and later refuses such a table. So a function job with output keys `a` and `A` now + stops at its first write, on the sync and the async path alike. Delta folds case as + Rust's `to_lowercase` does: for the few code points where Python's `str.lower` differs, + the refusal comes at the flush, once, as `UnstorableColumnError`, and the batch leaves + the queue. The in-memory and connector databases still hold such names as two columns. +- `DeltaTableDatabase` refuses an append that would change a stored column's field + metadata (`InputValidationError` naming the column, before anything is queued): + deltalake 1.5 and later refuses such a commit. Two cases: + - A column's recorded Arrow type: every list and map column, and every struct holding + an unsigned integer, a non-microsecond time type, `float16` or a fixed-size type. A + field added to such a struct changes it, in the small list form as in the large one, + and so does a change of nested nullability (a list's items becoming nullable). + - A logical column's identifier: another extension name, or the same name with other + extension metadata. + + Still accepted: a struct column without a record gaining fields, a field omitted or + reordered, a new column, and an untyped `null` column, which takes the stored type. + Tables Orcapod's own nodes write are not concerned: their column types are fixed by + their inputs' schemas, and a changed column type changes the table's path. The one + exception is an operator whose result type depends on its data rather than on its + input schemas, which is a bug of that operator. Example: a custom operator emitting + list items nullable only when a value exceeds 10, in an operator node that logs + (`CacheMode.LOG`). Such an operator now fails at the store when its result type + changes, instead of silently changing a table's recorded type (deltalake 1.0.2 stored + both). ITL-1410 is to refuse it earlier, at the operator. diff --git a/docs/dev/scripts/itl_1403/premise.py b/docs/dev/scripts/itl_1403/premise.py index f923fcf4c..8bed7b585 100644 --- a/docs/dev/scripts/itl_1403/premise.py +++ b/docs/dev/scripts/itl_1403/premise.py @@ -21,6 +21,15 @@ - ``struct_gains_field``: a source data column, a struct with a recorded type (``uint8``), gaining a field between the runs, through a cached source, a function pod, an operator that logs and a side-effect pod. +- ``operator_nested_nullability`` (the stated EXCEPTION, found by review): a custom + operator in a node that logs (``CacheMode.LOG``) whose result type depends on its + data, not on its input schemas: ``large_list`` with non-nullable items in one + run and nullable items in the next. Its declared and observed Python schemas are + equal and its cache path is the same, but the recorded type differs (nested + nullability is part of the record), so the second run fails at the store. On + deltalake 1.0.2 both runs were stored and the table's recorded type changed + silently. Such an operator is a bug of the operator (an operator's output schema is + fully determined by its inputs' schemas); ITL-1410 is to refuse it at the operator. usage: uv run python docs/dev/scripts/itl_1403/premise.py WORKDIR """ @@ -38,6 +47,8 @@ from orcapod import PipelineJob, function_pod from orcapod.core.operators import Join +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.sources import ArrowTableSource from orcapod.core.sources.cached_source import CachedSource from orcapod.databases import DeltaTableDatabase @@ -140,6 +151,50 @@ def _case(store: Path, first: Callable[[], None], second: Callable[[], None]) -> ) +class ShapeValues(UnaryOperator): + """Lists of one Python type whose items' Arrow nullability follows the values.""" + + def validate_unary_input(self, stream: Any) -> None: + pass + + def identity_structure(self) -> Any: + return ("itl1403-shape-values",) + + def unary_output_schema(self, stream: Any, **kwargs: Any) -> Any: + tags, _ = stream.output_schema(**kwargs) + values = pa.array([], type=pa.large_list(pa.field("item", pa.uint8()))) + _, data = ArrowTableStream(pa.table({"v": values})).output_schema(**kwargs) + return tags, data + + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns={"source": True, "system_tags": True}) + values = table["v"].to_pylist() + nullable = any(v > 10 for v in values) + shape = pa.large_list(pa.field("item", pa.uint8(), nullable=nullable)) + wrapped = pa.array([[v] for v in values], shape) + table = table.set_column(table.schema.get_field_index("v"), "v", wrapped) + return ArrowTableStream(table, tag_columns=stream.keys()[0]) + + +def _operator_job(store: Path, rerun: bool) -> None: + database = DeltaTableDatabase(store) + source = ArrowTableSource( + pa.table( + {"k": [3, 4] if rerun else [1, 2], "v": [11, 12] if rerun else [1, 2]} + ), + tag_columns=["k"], + tag_only_columns=True, + source_id="input", + record_id_columns=["k"], + ) + job = PipelineJob(name="premise-operator", database=database) + with job: + ShapeValues()(source, label="shape") + job.nodes["shape"].attach_databases(database, cache_mode=CacheMode.LOG) + job.run() + database.flush() + + def main(work: Path) -> None: results: dict[str, str] = {} @@ -245,6 +300,13 @@ def run_struct(extra: bool) -> Callable[[], None]: work / "struct_gains_field", run_struct(False), run_struct(True) ) + # The known exception: the second run is refused. + results["operator_nested_nullability (known exception)"] = _case( + work / "operator_nested_nullability", + lambda: _operator_job(work / "operator_nested_nullability", False), + lambda: _operator_job(work / "operator_nested_nullability", True), + ) + for name, outcome in results.items(): print(f"{name}: {outcome}") diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 88021bf30..e295ea606 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,11 +81,13 @@ 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. A column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field: the record is the column's field metadata, which Delta -(deltalake 1.5 and later) does not let a commit change, so such an append is refused, -naming the column, before anything is queued. A struct column without a record still -gains fields, and an append may still add a new column. Another logical type over a -stored logical column's storage type is refused the same way. +included) cannot gain a field, nor have a nested nullability change: the record is the +column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit +change, so such an append is refused, naming the column, before anything is queued. A +struct column without a record still gains fields, an append may still add a new column, +and an untyped `null` column takes the stored type. Another logical type over a stored +logical column (another extension name, or the same name with other extension metadata) +is refused the same way. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 006725268..3027e6558 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2,6 +2,7 @@ import logging import os +import re import sys from collections import defaultdict from collections.abc import Callable, Collection, Mapping @@ -41,6 +42,7 @@ written_field, ) from orcapod.databases.delta_statistics import statistics_configuration +from orcapod.logical_types.identifier import arrow_type_identifier from orcapod.databases.storage_utils import ( delta_to_pyarrow_dataset, is_cloud_uri, @@ -534,6 +536,21 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: return f"{where} {first!r} and {second!r} differ only in case: {_CASE_INSENSITIVE}" +# delta-rs reports two names equal under its case folding (Rust ``to_lowercase``). +_DUPLICATE_NAME = re.compile(r"Duplicate field name \(case-insensitive\): '([^']*)'") + + +def _duplicate_name_in(error: BaseException) -> str | None: + """The name delta-rs reports as a case-insensitive duplicate in ``error``'s chain.""" + seen: BaseException | None = error + while seen is not None: + match = _DUPLICATE_NAME.search(str(seen)) + if match is not None: + return match.group(1) + seen = seen.__cause__ or seen.__context__ + return None + + # Why a recorded column's record cannot change on Delta (ITL-1403). _RECORD_CHANGE = ( "the append would change the column's recorded Arrow type, and a recorded " @@ -704,18 +721,40 @@ def _non_null_violation( return None +def _metadata_sent(field: "pa.Field[Any]") -> dict[str, str]: + """The field metadata a commit sends to Delta for ``field``, as text. + + A logical column also carries its identifier as ``ARROW:extension:name`` and + ``ARROW:extension:metadata``, as the Arrow C interface hands it to delta-rs. + """ + sent = { + k.decode() if isinstance(k, bytes) else k: ( + v.decode(errors="replace") if isinstance(v, bytes) else v + ) + for k, v in (field.metadata or {}).items() + } + if isinstance(field.type, pa.ExtensionType): + identifier = arrow_type_identifier(field.type) + sent["ARROW:extension:name"] = identifier.name + sent["ARROW:extension:metadata"] = identifier.metadata.decode(errors="replace") + return sent + + def _changed_record( delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: - """The first stored column whose record (or nested names) the append would change. - - deltalake (1.5 and later) refuses a commit that changes a column's field metadata, - and a recorded column's record is its field metadata: an append whose merged - record (``_merged_record``, what the commit would write) is not the stored one is - refused here, before anything is queued. An append that leaves the record as it - is, a column with no record on either side (a plain struct still evolves), and a - new column are not concerned. A struct evolution that would put two field names - differing only in case into one struct is refused too. + """The first stored column whose field metadata (or nested names) the append changes. + + deltalake (1.5 and later) refuses a commit that gives a stored column's field + metadata key another value (delta-rs ``try_merge_metadata``). That metadata holds a + recorded column's record (``orcapod:arrow_type``) and a logical column's identifier + (``ARROW:extension:name`` and ``ARROW:extension:metadata``). The metadata the + commit would send is computed here by the functions the flush uses + (``to_delta_layout``, ``_conformed_to_stored``, ``_with_merged_records``), so the + rows are refused when they are added, never left to fail at every flush. A new key + is accepted, as Delta adds it; so is a bare ``null`` column, which sends no + metadata and takes the stored type. A struct evolution that would put two field + names differing only in case into one struct is refused too. Args: delta_table: The loaded stored table. @@ -725,43 +764,41 @@ def _changed_record( ``(column, reason)``, or ``None``. """ stored = _stored_arrow_schema(delta_table) - stored_metadata = {f.name: f.metadata for f in delta_table.schema().fields} - stored_records = { - name: recorded_type(metadata) for name, metadata in stored_metadata.items() - } + stored_metadata = {f.name: dict(f.metadata) for f in delta_table.schema().fields} + empty = rows.slice(0, 0) + # ``_conformed_to_stored`` refuses a struct the stored table cannot take, as the + # flush would (``InputValidationError``). + sent_schema = _with_merged_records( + delta_table, + empty, + _conformed_to_stored( + delta_table, to_delta_layout(empty), delta_table.table_uri + ), + ).schema for field in rows.schema: position = stored.get_field_index(field.name) - if position < 0: + if position < 0 or pa.types.is_null(field.type): continue - # A logical column's type is named in its field metadata: another logical - # type over the same storage type would change it. - stored_extension = stored_metadata[field.name].get("ARROW:extension:name") - incoming_extension = ( - field.type.extension_name - if isinstance(field.type, pa.ExtensionType) - else None - ) - if stored_extension != incoming_extension: - return field.name, ( - f"it is stored as logical type {stored_extension!r} and the rows hold " - f"{incoming_extension!r}: a column's field metadata cannot change on a " - "Delta table (deltalake 1.5 and later refuses such a commit)" - ) - if incoming_extension is not None: - continue - stored_type = stored.field(position).type - stored_record = stored_records.get(field.name) - merged = _merged_record( - stored_type, stored_record, field.type, written_field(field) - ) - if merged is not None and ( - stored_record is None - or not stored_record.equals(merged, check_metadata=True) - ): + held = stored_metadata[field.name] + sent = _metadata_sent(sent_schema.field(field.name)) + changed = sorted(k for k, v in sent.items() if k in held and held[k] != v) + if changed: + if any(k.startswith("ARROW:extension:") for k in changed): + return field.name, ( + "it is stored as logical type " + f"{held.get('ARROW:extension:name')!r} " + f"({held.get('ARROW:extension:metadata')!r}) and the rows hold " + f"{sent.get('ARROW:extension:name')!r} " + f"({sent.get('ARROW:extension:metadata')!r}): a column's field " + "metadata cannot change on a Delta table (deltalake 1.5 and later " + "refuses such a commit)" + ) return field.name, _RECORD_CHANGE + if isinstance(field.type, pa.ExtensionType): + continue try: evolved = merged_type( - arrow_utils.normalize_to_large_types(stored_type), + arrow_utils.normalize_to_large_types(stored.field(position).type), arrow_utils.normalize_to_large_types(field.type), ) except Exception: # noqa: BLE001 # a type change: the type check reports it @@ -1160,16 +1197,18 @@ def _database_error_to_raise(errors: list[Exception]) -> Exception | None: A ``OrcapodDatabaseReadError`` is preferred, because it is the error that fails a run whatever the orchestrator's ``error_policy``; failing that, an - ``InputValidationError`` from a refused append. + ``InputValidationError`` from a refused append, then an ``UnstorableColumnError`` + from a batch Delta refused for its column names (ITL-1403). Args: errors: The error of every batch that failed, in flush order. Returns: - The first ``OrcapodDatabaseReadError``, else the first ``InputValidationError``, or - ``None`` when no batch failed with a database error. + The first ``OrcapodDatabaseReadError``, else the first ``InputValidationError``, + else the first ``UnstorableColumnError``, or ``None`` when no batch failed with + a database error. """ - for kind in (OrcapodDatabaseReadError, InputValidationError): + for kind in (OrcapodDatabaseReadError, InputValidationError, UnstorableColumnError): chosen = next((e for e in errors if isinstance(e, kind)), None) if chosen is not None: return chosen @@ -1825,6 +1864,27 @@ def _refuse_case_clash_with_pending( f"Cannot add rows to {self._get_table_uri(record_path)!r}: column " f"{clash[1]!r}: {_case_reason(*clash)}. Nothing was queued." ) + # A struct queued and a struct added, merged as the flush would merge them, + # must not hold two field names differing only in case, at any depth. + for field in schema: + if field.name not in queued: + continue + try: + merged = merged_type( + arrow_utils.normalize_to_large_types( + pending.schema.field(field.name).type + ), + arrow_utils.normalize_to_large_types(field.type), + ) + except Exception: # noqa: BLE001 # a type change: the schema check reports it + continue + nested = _nested_names_differing_in_case(merged) + if nested is not None: + raise InputValidationError( + f"Cannot add rows to {self._get_table_uri(record_path)!r}: column " + f"{field.name!r}: {_case_reason(*nested, nested=True)}, once " + "merged with the rows queued. Nothing was queued." + ) def _refuse_unmergeable_append( self, @@ -1878,7 +1938,20 @@ def _refuse_unmergeable_append( if refusal is None: try: delta_table = self._get_delta_table(record_path) - except OrcapodDatabaseReadError: + except OrcapodDatabaseReadError as unreadable: + duplicate = _duplicate_name_in(unreadable) + if duplicate is not None: + # Written before deltalake 1.5.1, which no longer reads it: every + # flush would fail the same way, so nothing is queued (ITL-1403). + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: it holds columns whose " + f"names differ only in case (one is {duplicate!r}), which " + "deltalake 1.5.1 and later cannot read: " + f"{_CASE_INSENSITIVE} of them. Nothing was queued. Rebuild the " + "table with distinct names, using a deltalake version before " + "1.5.1 to read it." + ) from unreadable delta_table = None if delta_table is not None: refusal = _append_refusal(delta_table, records) @@ -2713,6 +2786,9 @@ def flush(self) -> None: InputValidationError: If no batch failed with ``OrcapodDatabaseReadError`` but a batch was refused by its stored table (dropped from the queue, above). Other failed batches are added to it as notes. + UnstorableColumnError: If neither of the above, but Delta refused a batch + for two names equal under its case folding (dropped from the queue: + every later flush would refuse it too; ITL-1403). RuntimeError: If batches failed with other errors only, naming the failed batches, with the first failure as its ``__cause__``. """ @@ -2911,6 +2987,32 @@ def _flush_by_key(self, record_key: str) -> None: logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e except Exception as e: + duplicate = _duplicate_name_in(e) + if duplicate is not None: + # delta-rs folds case with Rust's ``to_lowercase``, which agrees with + # Python's ``str.lower`` (the check when rows are added) except for a + # few code points of newer Unicode versions. Every later flush would + # fail the same way, so the batch leaves the queue and nothing of it + # was written (ITL-1403). + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + arrow_type: Any = next( + (f.type for f in pending_batch.schema if f.name == duplicate), + pa.null(), + ) + refused = UnstorableColumnError( + database_kind=type(self).__name__, + column=duplicate, + arrow_type=arrow_type, + reason=( + "Delta reports its name as equal to another column's or " + f"struct field's under its case folding: {_CASE_INSENSITIVE}. " + f"The {pending_batch.num_rows} rows queued for table " + f"{record_key!r} were not written and are no longer queued" + ), + ) + logger.error(f"Refused batch for {record_key}: {refused}") + raise refused from e logger.error(f"Error flushing batch for {record_key}: {e}") # Put the tables back in the pending queue self._pending_batches[record_key] = pending_batch diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py new file mode 100644 index 000000000..1132c674d --- /dev/null +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -0,0 +1,178 @@ +"""What deltalake 1.6 refuses at commit, a ``DeltaTableDatabase`` refuses when rows are added. + +A flush that fails and puts its rows back in the queue fails at every later flush too. +So each case deltalake 1.5+ refuses is refused when the rows are added, with nothing +queued (ITL-1403, review of PR 504). The cases: + +- two struct fields differing only in case, one queued and one added; +- a recorded column whose record the append would change, in the small list form + (``pa.list_``) as in the large one; +- a logical column whose identifier (extension name AND metadata) would change; +- a stored table written before deltalake 1.5.1 with two names differing only in case, + which deltalake 1.6 cannot read; +- names equal only under Delta's case folding, which Python's ``str.lower`` does not + fold alike: refused at the flush, once, and the rows leave the queue. + +A bare ``null`` column appended to a stored logical column claims no type and is +stored. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, cast + +import deltalake +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InputValidationError, UnstorableColumnError + +PATH = ("t",) + + +def _rows(rid: bytes, **columns: Any) -> pa.Table: + return pa.table({"rid": pa.array([rid], pa.large_binary()), **columns}) + + +def _add(db: DeltaTableDatabase, table: pa.Table, **kwargs: Any) -> None: + db.add_records(PATH, table, record_id_column="rid", **kwargs) + + +def _stored_ids(root: Path) -> list[bytes]: + table = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="rid") + assert table is not None + return sorted(cast(list[bytes], table.column("rid").to_pylist())) + + +def test_a_struct_field_differing_in_case_from_a_queued_one(tmp_path: Path) -> None: + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", s=pa.array([{"x": 1}]))) + with pytest.raises(InputValidationError, match="'x' and 'X' differ only in case"): + _add(db, _rows(b"2", s=pa.array([{"X": 2}])), schema_handling="merge") + db.flush() # the first batch is intact and commits + assert _stored_ids(tmp_path) == [b"1"] + + +@pytest.mark.parametrize( + "make_list", [pa.list_, pa.large_list], ids=["list", "large_list"] +) +def test_a_recorded_list_of_structs_cannot_evolve( + tmp_path: Path, make_list: Any +) -> None: + db = DeltaTableDatabase(tmp_path) + _add( + db, + _rows( + b"1", x=pa.array([[{"a": 1}]], make_list(pa.struct([("a", pa.int64())]))) + ), + flush=True, + ) + evolved = make_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) + with pytest.raises(InputValidationError, match="recorded Arrow type"): + _add(db, _rows(b"2", x=pa.array([[{"a": 2, "b": 3}]], evolved))) + db.flush() # nothing was queued + assert _stored_ids(tmp_path) == [b"1"] + + +class _Unit(pa.ExtensionType): + def __init__(self, serial: bytes = b"x") -> None: + self.serial = serial + super().__init__(pa.int64(), "itl1403.review.unit") + + def __arrow_ext_serialize__(self) -> bytes: + return self.serial + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> "_Unit": + return cls(serialized) + + +@pytest.fixture +def unit_type() -> Any: + pa.register_extension_type(_Unit()) # pyright: ignore[reportArgumentType] # pyarrow's stub names only PyExtensionType; any ExtensionType registers + yield _Unit + pa.unregister_extension_type("itl1403.review.unit") + + +def test_a_logical_column_with_other_extension_metadata( + tmp_path: Path, unit_type: Any +) -> None: + """The same extension name and storage, other metadata: another logical type.""" + + def unit(value: int, serial: bytes) -> Any: + return pa.ExtensionArray.from_storage( + unit_type(serial), pa.array([value], pa.int64()) + ) + + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", x=unit(1, b"x")), flush=True) + with pytest.raises( + InputValidationError, match="logical type 'itl1403.review.unit'" + ): + _add(db, _rows(b"2", x=unit(2, b"y"))) + _add(db, _rows(b"3", x=unit(3, b"x")), flush=True) # the same identifier appends + assert _stored_ids(tmp_path) == [b"1", b"3"] + + +def test_a_bare_null_appended_to_a_logical_column_is_stored(tmp_path: Path) -> None: + converter = get_default_context().type_converter + logical = converter.python_dicts_to_arrow_table( + [{"x": Path("/a")}], python_schema={"x": Path | None} + ) + first = _rows(b"1").append_column(logical.schema.field("x"), logical.column("x")) + db = DeltaTableDatabase(tmp_path) + _add(db, first, flush=True) + _add(db, _rows(b"2", x=pa.nulls(1)), flush=True) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert back is not None + assert back.schema.field("x").type == logical.schema.field("x").type + assert back.sort_by("rid").column("x").to_pylist() == ["/a", None] + + +def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( + tmp_path: Path, +) -> None: + """A table with ``a`` and ``A``, as deltalake before 1.5.1 wrote it: an append of + ``a`` alone is refused when added, with nothing queued, not at every flush.""" + deltalake.write_deltalake( + str(tmp_path / "t"), + pa.table( + {"__record_id": pa.array([b"1"], pa.large_binary()), "a": [1], "b": [2]} + ), + ) + # Rename ``b`` to ``A`` in the log's schema: the table deltalake 1.0.2 would write. + log = tmp_path / "t" / "_delta_log" / "00000000000000000000.json" + lines = [json.loads(line) for line in log.read_text().splitlines()] + for action in lines: + if "metaData" in action: + schema = json.loads(action["metaData"]["schemaString"]) + schema["fields"][2]["name"] = "A" + action["metaData"]["schemaString"] = json.dumps(schema) + log.write_text("\n".join(json.dumps(action) for action in lines) + "\n") + + db = DeltaTableDatabase(tmp_path) + with pytest.raises( + InputValidationError, match="deltalake 1.5.1 and later cannot read" + ): + _add(db, _rows(b"2", a=pa.array([3]))) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + + +def test_names_folded_alike_only_by_delta_are_refused_once(tmp_path: Path) -> None: + """U+1C89 and U+1C8A: Delta's folding (Rust ``to_lowercase``) makes them one name, + Python's ``str.lower`` (3.12) does not. Whichever check sees it first refuses it + with ``UnstorableColumnError``, and nothing stays queued.""" + first, second = "Ᲊ", "ᲊ" + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError): + _add( + db, _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}), flush=True + ) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + assert not (tmp_path / "t" / "_delta_log").exists() diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 8adab576c..041417959 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1056,11 +1056,13 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: struct field inside a map (Delta cannot). A nested field the append makes nullable reads as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field: the record is the column's field metadata, which Delta -(deltalake 1.5 and later) does not let a commit change, so such an append is refused, -naming the column, before anything is queued. A struct column without a record still -gains fields, and an append may still add a new column. Another logical type over a -stored logical column's storage type is refused the same way. +included) cannot gain a field, nor have a nested nullability change: the record is the +column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit +change, so such an append is refused, naming the column, before anything is queued. A +struct column without a record still gains fields, an append may still add a new column, +and an untyped `null` column takes the stored type. Another logical type over a stored +logical column (another extension name, or the same name with other extension metadata) +is refused the same way. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one From 646b10bffd4cd10717d53332824170bb2c0a678b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:27:50 -0800 Subject: [PATCH 03/12] test(databases): a storage-typed column carrying another extension name is refused when added (ITL-1403) Co-Authored-By: Claude Opus 5.5 --- .../test_delta_refused_before_queueing.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 1132c674d..466c17cbf 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -176,3 +176,26 @@ def test_names_folded_alike_only_by_delta_are_refused_once(tmp_path: Path) -> No assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() assert not (tmp_path / "t" / "_delta_log").exists() + + +def test_a_storage_typed_column_carrying_another_extension_name(tmp_path: Path) -> None: + """A logical identity given as ``ARROW:extension:*`` field metadata on a storage + type is compared as an extension type's is: another name is refused when added.""" + + def rows(rid: bytes, name: str) -> pa.Table: + field = pa.field( + "x", + pa.int64(), + metadata={"ARROW:extension:name": name, "ARROW:extension:metadata": ""}, + ) + return pa.Table.from_arrays( + [pa.array([rid], pa.large_binary()), pa.array([1])], + schema=pa.schema([pa.field("rid", pa.large_binary()), field]), + ) + + db = DeltaTableDatabase(tmp_path) + _add(db, rows(b"1", "itl1403.one"), flush=True) + with pytest.raises(InputValidationError, match="'itl1403.two'"): + _add(db, rows(b"2", "itl1403.two")) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + assert _stored_ids(tmp_path) == [b"1"] From 2960b633e6ea3eb895b63a525b016cfda13fe62b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:35:04 -0800 Subject: [PATCH 04/12] test(databases): every review finding of PR 504 has a test, its class parametrized (ITL-1403) Co-Authored-By: Claude Opus 5.5 --- .../test_delta_refused_before_queueing.py | 201 +++++++++++++----- .../test_delta_refusals_in_jobs.py | 113 ++++++++++ 2 files changed, 266 insertions(+), 48 deletions(-) create mode 100644 tests/test_pipeline/test_delta_refusals_in_jobs.py diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 466c17cbf..354c4f4b7 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -29,7 +29,11 @@ from orcapod.contexts import get_default_context from orcapod.databases import DeltaTableDatabase -from orcapod.errors import InputValidationError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) PATH = ("t",) @@ -48,32 +52,76 @@ def _stored_ids(root: Path) -> list[bytes]: return sorted(cast(list[bytes], table.column("rid").to_pylist())) -def test_a_struct_field_differing_in_case_from_a_queued_one(tmp_path: Path) -> None: +def _struct(name: str, value: int) -> Any: + return pa.array([{name: value}]) + + +# (queued, added): two names differing only in case at each depth, in both orders. +NESTED_CASE_CLASHES: dict[str, tuple[Any, Any]] = { + "top struct, lower first": (_struct("x", 1), _struct("X", 2)), + "top struct, upper first": (_struct("X", 1), _struct("x", 2)), + "struct in a struct": ( + pa.array([{"t": {"x": 1}}]), + pa.array([{"t": {"X": 2}}]), + ), + "struct in a list": ( + pa.array([[{"x": 1}]], pa.large_list(pa.struct([("x", pa.int64())]))), + pa.array([[{"X": 2}]], pa.large_list(pa.struct([("X", pa.int64())]))), + ), +} + + +@pytest.mark.parametrize("case", sorted(NESTED_CASE_CLASHES)) +def test_a_struct_field_differing_in_case_from_a_queued_one( + tmp_path: Path, case: str +) -> None: + """Review of PR 504, finding 1 (and CodeRabbit): checked on the merged type.""" + queued, added = NESTED_CASE_CLASHES[case] db = DeltaTableDatabase(tmp_path) - _add(db, _rows(b"1", s=pa.array([{"x": 1}]))) - with pytest.raises(InputValidationError, match="'x' and 'X' differ only in case"): - _add(db, _rows(b"2", s=pa.array([{"X": 2}])), schema_handling="merge") + _add(db, _rows(b"1", s=queued)) + with pytest.raises(InputValidationError, match="differ only in case"): + _add(db, _rows(b"2", s=added), schema_handling="merge") db.flush() # the first batch is intact and commits assert _stored_ids(tmp_path) == [b"1"] -@pytest.mark.parametrize( - "make_list", [pa.list_, pa.large_list], ids=["list", "large_list"] -) -def test_a_recorded_list_of_structs_cannot_evolve( - tmp_path: Path, make_list: Any -) -> None: +def _list_of_structs(make_list: Any, *names: str) -> Any: + return make_list(pa.struct([(n, pa.int64()) for n in names])) + + +# (stored, appended): an append that changes a recorded column's record. +RECORD_CHANGES: dict[str, tuple[Any, Any]] = { + "list of structs gains a field": ( + pa.array([[{"a": 1}]], _list_of_structs(pa.list_, "a")), + pa.array([[{"a": 2, "b": 3}]], _list_of_structs(pa.list_, "a", "b")), + ), + "large list of structs gains a field": ( + pa.array([[{"a": 1}]], _list_of_structs(pa.large_list, "a")), + pa.array([[{"a": 2, "b": 3}]], _list_of_structs(pa.large_list, "a", "b")), + ), + "struct holding uint8 gains a field": ( + pa.array([{"a": 1}], pa.struct([("a", pa.uint8())])), + pa.array([{"a": 2, "b": 3}], pa.struct([("a", pa.uint8()), ("b", pa.int64())])), + ), + "list items become nullable": ( + pa.array([[1]], pa.large_list(pa.field("item", pa.uint8(), nullable=False))), + pa.array([[2]], pa.large_list(pa.field("item", pa.uint8(), nullable=True))), + ), + "struct child becomes nullable": ( + pa.array([{"a": 1}], pa.struct([pa.field("a", pa.uint8(), nullable=False)])), + pa.array([{"a": 2}], pa.struct([pa.field("a", pa.uint8(), nullable=True)])), + ), +} + + +@pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) +def test_a_recorded_column_whose_record_would_change(tmp_path: Path, case: str) -> None: + """Review of PR 504, findings 2 and 6: what the commit would send is compared.""" + stored, appended = RECORD_CHANGES[case] db = DeltaTableDatabase(tmp_path) - _add( - db, - _rows( - b"1", x=pa.array([[{"a": 1}]], make_list(pa.struct([("a", pa.int64())]))) - ), - flush=True, - ) - evolved = make_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) + _add(db, _rows(b"1", x=stored), flush=True) with pytest.raises(InputValidationError, match="recorded Arrow type"): - _add(db, _rows(b"2", x=pa.array([[{"a": 2, "b": 3}]], evolved))) + _add(db, _rows(b"2", x=appended)) db.flush() # nothing was queued assert _stored_ids(tmp_path) == [b"1"] @@ -98,10 +146,16 @@ def unit_type() -> Any: pa.unregister_extension_type("itl1403.review.unit") +@pytest.mark.parametrize( + ("first", "second"), + [(b"x", b"y"), (b"", b"y"), (b"x", b"")], + ids=["other metadata", "metadata added", "metadata dropped"], +) def test_a_logical_column_with_other_extension_metadata( - tmp_path: Path, unit_type: Any + tmp_path: Path, unit_type: Any, first: bytes, second: bytes ) -> None: - """The same extension name and storage, other metadata: another logical type.""" + """Review of PR 504, finding 3 (and CodeRabbit): the same extension name and + storage with other metadata is another logical type.""" def unit(value: int, serial: bytes) -> Any: return pa.ExtensionArray.from_storage( @@ -109,43 +163,55 @@ def unit(value: int, serial: bytes) -> Any: ) db = DeltaTableDatabase(tmp_path) - _add(db, _rows(b"1", x=unit(1, b"x")), flush=True) + _add(db, _rows(b"1", x=unit(1, first)), flush=True) with pytest.raises( InputValidationError, match="logical type 'itl1403.review.unit'" ): - _add(db, _rows(b"2", x=unit(2, b"y"))) - _add(db, _rows(b"3", x=unit(3, b"x")), flush=True) # the same identifier appends + _add(db, _rows(b"2", x=unit(2, second))) + _add(db, _rows(b"3", x=unit(3, first)), flush=True) # the same identifier appends assert _stored_ids(tmp_path) == [b"1", b"3"] -def test_a_bare_null_appended_to_a_logical_column_is_stored(tmp_path: Path) -> None: +def _path_column() -> Any: converter = get_default_context().type_converter - logical = converter.python_dicts_to_arrow_table( + table = converter.python_dicts_to_arrow_table( [{"x": Path("/a")}], python_schema={"x": Path | None} ) - first = _rows(b"1").append_column(logical.schema.field("x"), logical.column("x")) + return table.schema.field("x"), table.column("x"), "/a" + + +def _unit_column() -> Any: + array = pa.ExtensionArray.from_storage(_Unit(b"x"), pa.array([7], pa.int64())) + return pa.field("x", array.type), array, 7 + + +@pytest.mark.parametrize( + "make", [_path_column, _unit_column], ids=["orcapod.path", "extension"] +) +def test_a_bare_null_appended_to_a_logical_column_is_stored( + tmp_path: Path, unit_type: Any, make: Any +) -> None: + """Review of PR 504, finding 5 (and CodeRabbit): a bare null claims no type.""" + field, column, value = make() db = DeltaTableDatabase(tmp_path) - _add(db, first, flush=True) + _add(db, _rows(b"1").append_column(field, column), flush=True) _add(db, _rows(b"2", x=pa.nulls(1)), flush=True) back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") assert back is not None - assert back.schema.field("x").type == logical.schema.field("x").type - assert back.sort_by("rid").column("x").to_pylist() == ["/a", None] + assert back.schema.field("x").type == field.type + assert back.sort_by("rid").column("x").to_pylist() == [value, None] -def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( - tmp_path: Path, -) -> None: - """A table with ``a`` and ``A``, as deltalake before 1.5.1 wrote it: an append of - ``a`` alone is refused when added, with nothing queued, not at every flush.""" +def _legacy_case_only_table(root: Path) -> None: + """A table with ``a`` and ``A``, as deltalake before 1.5.1 wrote it.""" deltalake.write_deltalake( - str(tmp_path / "t"), + str(root / "t"), pa.table( {"__record_id": pa.array([b"1"], pa.large_binary()), "a": [1], "b": [2]} ), ) - # Rename ``b`` to ``A`` in the log's schema: the table deltalake 1.0.2 would write. - log = tmp_path / "t" / "_delta_log" / "00000000000000000000.json" + # Rename ``b`` to ``A`` in the log's schema (deltalake 1.6 cannot write it). + log = root / "t" / "_delta_log" / "00000000000000000000.json" lines = [json.loads(line) for line in log.read_text().splitlines()] for action in lines: if "metaData" in action: @@ -154,25 +220,64 @@ def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( action["metaData"]["schemaString"] = json.dumps(schema) log.write_text("\n".join(json.dumps(action) for action in lines) + "\n") + +def test_a_stored_table_with_case_only_names_cannot_be_read(tmp_path: Path) -> None: + """Review of PR 504, finding 7, the stated limit: deltalake 1.6 reads no such + table (the release note says so).""" + _legacy_case_only_table(tmp_path) + with pytest.raises(OrcapodDatabaseReadError): + DeltaTableDatabase(tmp_path).get_all_records(PATH) + + +@pytest.mark.parametrize( + "columns", + [{"a": [3]}, {"b": [3]}, {"a": [3], "c": [4]}], + ids=["a held name", "a new name", "a held and a new name"], +) +def test_a_stored_table_deltalake_can_no_longer_read_refuses_at_once( + tmp_path: Path, columns: dict[str, list[int]] +) -> None: + """Review of PR 504, finding 7: an append is refused when added, with nothing + queued, never left to fail at every flush.""" + _legacy_case_only_table(tmp_path) db = DeltaTableDatabase(tmp_path) with pytest.raises( InputValidationError, match="deltalake 1.5.1 and later cannot read" ): - _add(db, _rows(b"2", a=pa.array([3]))) + _add(db, _rows(b"2", **{k: pa.array(v) for k, v in columns.items()})) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() -def test_names_folded_alike_only_by_delta_are_refused_once(tmp_path: Path) -> None: - """U+1C89 and U+1C8A: Delta's folding (Rust ``to_lowercase``) makes them one name, - Python's ``str.lower`` (3.12) does not. Whichever check sees it first refuses it - with ``UnstorableColumnError``, and nothing stays queued.""" - first, second = "Ᲊ", "ᲊ" +# Pairs Delta's case folding (Rust ``to_lowercase``) makes one name and Python 3.12's +# ``str.lower`` does not (found by the review of PR 504, finding 4). +RUST_ONLY_FOLDS = [ + ("\u1c89", "\u1c8a"), + ("\ua7cb", "\u0264"), + ("\ua7cc", "\ua7cd"), + ("\ua7da", "\ua7db"), + ("\ua7ce", "\ua7cf"), + ("\U00016ea0", "\U00016ebb"), +] + + +@pytest.mark.parametrize("nested", [False, True], ids=["columns", "struct fields"]) +@pytest.mark.parametrize( + "pair", RUST_ONLY_FOLDS, ids=[ascii(a) for a, _ in RUST_ONLY_FOLDS] +) +def test_names_folded_alike_only_by_delta_are_refused_once( + tmp_path: Path, pair: tuple[str, str], nested: bool +) -> None: + """Whichever check sees it first (``str.lower`` when added, Delta's error at the + flush) refuses it with ``UnstorableColumnError``, and nothing stays queued.""" + first, second = pair + if nested: + rows = _rows(b"1", s=pa.array([{first: 1, second: 2}])) + else: + rows = _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}) db = DeltaTableDatabase(tmp_path) with pytest.raises(UnstorableColumnError): - _add( - db, _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}), flush=True - ) + _add(db, rows, flush=True) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() assert not (tmp_path / "t" / "_delta_log").exists() diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py new file mode 100644 index 000000000..b98c8b886 --- /dev/null +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -0,0 +1,113 @@ +"""Jobs that reach a ``DeltaTableDatabase`` refusal of deltalake 1.5+ (ITL-1403). + +Pins the behaviour disclosed in the review of PR 504, so that a change to it is noticed: + +- finding 6: an operator whose result TYPE depends on its data (list items nullable only + when a value exceeds 10) in an operator node that logs (``CacheMode.LOG``): the run + whose result type differs from the stored one fails at the store, instead of + silently changing the table's recorded type. Such an operator is a bug of the + operator; ITL-1410 is to refuse it at the operator. +- a function with output keys ``a`` and ``A`` (legal before) stops at its first write: + Delta column names are case-insensitive. + +Both on the sync and the async orchestrator. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import OrcapodDatabaseWriteError, UnstorableColumnError +from orcapod.types import CacheMode + + +class _ItemNullabilityFromValues(UnaryOperator): + """Lists whose items' Arrow nullability follows the values (a buggy operator).""" + + def validate_unary_input(self, stream: Any) -> None: + pass + + def identity_structure(self) -> Any: + return ("itl1403-item-nullability-from-values",) + + def unary_output_schema(self, stream: Any, **kwargs: Any) -> Any: + tags, _ = stream.output_schema(**kwargs) + values = pa.array([], type=pa.large_list(pa.field("item", pa.uint8()))) + _, data = ArrowTableStream(pa.table({"v": values})).output_schema(**kwargs) + return tags, data + + def unary_static_process(self, stream: Any) -> Any: + table = stream.as_table(columns={"source": True, "system_tags": True}) + values = table["v"].to_pylist() + nullable = any(v > 10 for v in values) + shape = pa.large_list(pa.field("item", pa.uint8(), nullable=nullable)) + wrapped = pa.array([[v] for v in values], shape) + table = table.set_column(table.schema.get_field_index("v"), "v", wrapped) + return ArrowTableStream(table, tag_columns=stream.keys()[0]) + + +def _source(keys: list[int], values: list[int]) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"k": keys, "v": values}), + tag_columns=["k"], + tag_only_columns=True, + source_id="input", + record_id_columns=["k"], + ) + + +def _run(job: PipelineJob, use_async: bool) -> None: + if use_async: + asyncio.run(job.run_async()) + else: + job.run() + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_an_operator_whose_result_type_follows_its_data_fails_at_the_store( + tmp_path: Path, use_async: bool +) -> None: + def run(keys: list[int], values: list[int]) -> None: + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1403", database=database) + with job: + _ItemNullabilityFromValues()(_source(keys, values), label="shape") + job.nodes["shape"].attach_databases(database, cache_mode=CacheMode.LOG) + _run(job, use_async) + database.flush() + + run([1, 2], [1, 2]) # items non-nullable: stored + with pytest.raises(OrcapodDatabaseWriteError) as info: + run([3, 4], [11, 12]) # items nullable: the recorded type would change + assert "recorded Arrow type" in str( + info.value.__cause__ + ) or "recorded Arrow type" in str(info.value) + + +@function_pod(output_keys=["a", "A"]) +def _pair(v: int | None) -> tuple[int, int]: + return v or 0, (v or 0) + 10 + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_a_function_with_output_keys_differing_in_case_stops( + tmp_path: Path, use_async: bool +) -> None: + # Refused when the job attaches the database to the node, before anything runs. + with pytest.raises(UnstorableColumnError, match="differ only in case"): + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1403", database=database) + with job: + _pair.pod(_source([1, 2], [1, 2]), label="fn") + _run(job, use_async) + assert not (tmp_path / "itl1403").exists() From 6ba68ce4805d14814ac2e489b6286c1e54b6f2fe Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:54:33 -0800 Subject: [PATCH 05/12] fix(databases): refuse only what the commit would refuse; second review of PR 504 (ITL-1403) N2: a record or logical identifier that decodes to the stored one is sent as stored (Delta compares the strings); a real change is refused only on a route that sends it: a MERGE that evolves the schema, or an append (the flush's own _stores_as_is, and no stored id among the rows). A MERGE without schema evolution keeps the stored schema and commits, as main did. N3: a null column carrying a logical identifier the stored type reads is written under the stored identifier; any other is checked like any column. N4: names are checked against the queued rows after duplicates are skipped. N5: the flush backstop names the batch's own field, also with a quote in it. N1: the dangling pipeline records after a dropped result batch are ITL-1412's; a strict xfail test names it, sync and async. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 234 +++++++++++++++--- .../test_delta_refused_before_queueing.py | 212 ++++++++++++++++ .../test_dropped_result_batch.py | 62 +++++ 3 files changed, 478 insertions(+), 30 deletions(-) create mode 100644 tests/test_pipeline/test_dropped_result_batch.py diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 3027e6558..149debef4 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -53,6 +53,10 @@ if TYPE_CHECKING: import deltalake + + from orcapod.logical_types.protocols import ( + TypeConverterProtocol as LogicalTypeConverterProtocol, + ) import polars as pl import pyarrow as pa import pyarrow.compute as pc @@ -442,25 +446,96 @@ def _with_merged_records( ``written`` with the merged records. """ stored = _stored_arrow_schema(delta_table) - stored_records = { - f.name: recorded_type(f.metadata) for f in delta_table.schema().fields - } + stored_metadata = {f.name: dict(f.metadata) for f in delta_table.schema().fields} for index, field in enumerate(written.schema): position = stored.get_field_index(field.name) own = original.schema.field(field.name).type - if position < 0 or isinstance(own, pa.ExtensionType): + if position < 0: continue - merged = _merged_record( - stored.field(position).type, stored_records.get(field.name), own, field - ) + held = stored_metadata[field.name] + if pa.types.is_null(own): + # A null column claiming a logical identity the stored column reads is + # written under the stored identifier: it holds no value to read + # otherwise, and Delta refuses another identifier string (ITL-1403). + if _null_reads_as_stored(held, field.metadata): + identifier = { + key.encode(): str(held[key]).encode() + for key in _EXTENSION_TEXT_KEYS + if key in held + } + written = written.set_column( + index, + field.with_metadata({**dict(field.metadata or {}), **identifier}), + written.column(index), + ) + continue + if isinstance(own, pa.ExtensionType): + continue + stored_record = recorded_type(held) + merged = _merged_record(stored.field(position).type, stored_record, own, field) if merged is None: continue - written = written.set_column( - index, with_recorded_type(field, merged), written.column(index) - ) + recorded = with_recorded_type(field, merged) + if stored_record is not None and stored_record.equals( + merged, check_metadata=True + ): + # The same record: sent as stored, byte for byte. Delta compares the + # metadata strings, and a record that decodes to the same type may be + # serialized otherwise (ITL-1403). + recorded = recorded.with_metadata( + { + **dict(recorded.metadata or {}), + ARROW_TYPE_KEY: str(held[ARROW_TYPE_KEY.decode()]).encode(), + } + ) + written = written.set_column(index, recorded, written.column(index)) return written +# The field metadata keys that hold a logical column's identifier, as Delta keeps them. +_EXTENSION_TEXT_KEYS = ("ARROW:extension:name", "ARROW:extension:metadata") + + +def _null_reads_as_stored(held: Mapping[str, Any], metadata: Any) -> bool: + """Whether a null column's identifier is one the stored logical column reads. + + Args: + held: The stored column's field metadata, as Delta keeps it. + metadata: The null column's field metadata (bytes keys), or ``None``. + + Returns: + ``True`` when the null column names the stored extension, with the stored + extension metadata or one the registered logical type reads + (``readable_extension_metadata``). + """ + incoming = { + (k.decode() if isinstance(k, bytes) else str(k)): v + for k, v in (metadata or {}).items() + } + name = incoming.get("ARROW:extension:name") + stored_name = held.get("ARROW:extension:name") + if name is None or stored_name is None: + return False + if (name.decode() if isinstance(name, bytes) else str(name)) != stored_name: + return False + raw = incoming.get("ARROW:extension:metadata", b"") + raw = raw if isinstance(raw, bytes) else str(raw).encode() + if raw == str(held.get("ARROW:extension:metadata", "")).encode(): + return True + from orcapod.contexts import get_default_context + + # The context's converter implements the logical-type lookup of + # ``logical_types.protocols.TypeConverterProtocol``. + converter = cast( + "LogicalTypeConverterProtocol", + cast(object, get_default_context().type_converter), + ) + logical_type = converter.get_logical_type_by_arrow_extension_name(stored_name) + return ( + logical_type is not None and raw in logical_type.readable_extension_metadata() + ) + + def _merged_record( stored_type: pa.DataType, stored_record: pa.DataType | None, @@ -551,6 +626,46 @@ def _duplicate_name_in(error: BaseException) -> str | None: return None +def _all_fields(schema: pa.Schema) -> list["pa.Field[Any]"]: + """Every field of ``schema``: top-level columns and struct fields at any depth.""" + found: list[pa.Field[Any]] = [] + + def visit(field: "pa.Field[Any]") -> None: + found.append(field) + arrow_type = field.type + if isinstance(arrow_type, pa.ExtensionType): + arrow_type = arrow_type.storage_type + for i in range(arrow_type.num_fields): + visit(arrow_type.field(i)) + + for field in schema: + visit(field) + return found + + +def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: + """The field of ``schema`` delta-rs names as a duplicate in ``error``'s chain. + + The name is taken from the schema, the longest one Delta's message quotes, so a + name holding a quote is named whole. ``(the reported text, null)`` when no field + matches. + """ + messages: list[str] = [] + seen: BaseException | None = error + while seen is not None: + messages.append(str(seen)) + seen = seen.__cause__ or seen.__context__ + quoted = [ + f + for f in _all_fields(schema) + if any(f"(case-insensitive): '{f.name}'" in m for m in messages) + ] + if quoted: + field = max(quoted, key=lambda f: len(f.name)) + return field.name, field.type + return _duplicate_name_in(error) or "", pa.null() + + # Why a recorded column's record cannot change on Delta (ITL-1403). _RECORD_CHANGE = ( "the append would change the column's recorded Arrow type, and a recorded " @@ -741,7 +856,10 @@ def _metadata_sent(field: "pa.Field[Any]") -> dict[str, str]: def _changed_record( - delta_table: deltalake.DeltaTable, rows: pa.Table + delta_table: deltalake.DeltaTable, + rows: pa.Table, + schema_evolution: bool, + may_append: Callable[[], bool], ) -> tuple[str, str] | None: """The first stored column whose field metadata (or nested names) the append changes. @@ -753,12 +871,22 @@ def _changed_record( (``to_delta_layout``, ``_conformed_to_stored``, ``_with_merged_records``), so the rows are refused when they are added, never left to fail at every flush. A new key is accepted, as Delta adds it; so is a bare ``null`` column, which sends no - metadata and takes the stored type. A struct evolution that would put two field - names differing only in case into one struct is refused too. + metadata and takes the stored type. A record or identifier that decodes to the + stored one is sent as stored (``_with_merged_records``), so only a real change + remains, and it is refused only on a commit route that sends the metadata: a + MERGE that evolves the schema, or an append (``_stores_as_is``, the flush's own + decision). A MERGE without schema evolution keeps the stored schema and commits. + A struct evolution that would put two field names differing only in case into one + struct is refused too. Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. + schema_evolution: Whether the database's MERGE evolves the stored schema + (``allow_schema_evolution``). + may_append: Whether the commit may still be an append rather than a MERGE: + no id of the rows to commit is stored. Asked only when a real change is + found and the schema does not evolve. Returns: ``(column, reason)``, or ``None``. @@ -768,21 +896,25 @@ def _changed_record( empty = rows.slice(0, 0) # ``_conformed_to_stored`` refuses a struct the stored table cannot take, as the # flush would (``InputValidationError``). - sent_schema = _with_merged_records( + sent_table = _with_merged_records( delta_table, empty, _conformed_to_stored( delta_table, to_delta_layout(empty), delta_table.table_uri ), - ).schema + ) + sent_schema = sent_table.schema + # The flush appends rows whose ids are all new and that it stores as they are; + # every other batch is a MERGE, which sends its schema only when it evolves it. + as_is = DeltaTableDatabase._stores_as_is(delta_table, sent_table) for field in rows.schema: position = stored.get_field_index(field.name) - if position < 0 or pa.types.is_null(field.type): + if position < 0: continue held = stored_metadata[field.name] sent = _metadata_sent(sent_schema.field(field.name)) - changed = sorted(k for k, v in sent.items() if k in held and held[k] != v) - if changed: + changed = sorted(k for k, v in sent.items() if k in held and str(held[k]) != v) + if changed and (schema_evolution or (as_is and may_append())): if any(k.startswith("ARROW:extension:") for k in changed): return field.name, ( "it is stored as logical type " @@ -794,7 +926,7 @@ def _changed_record( "refuses such a commit)" ) return field.name, _RECORD_CHANGE - if isinstance(field.type, pa.ExtensionType): + if isinstance(field.type, pa.ExtensionType) or pa.types.is_null(field.type): continue try: evolved = merged_type( @@ -810,7 +942,10 @@ def _changed_record( def _append_refusal( - delta_table: deltalake.DeltaTable, rows: pa.Table + delta_table: deltalake.DeltaTable, + rows: pa.Table, + schema_evolution: bool, + may_append: Callable[[], bool], ) -> tuple[str, str] | None: """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). @@ -828,6 +963,9 @@ def _append_refusal( Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. + schema_evolution: Whether the database's MERGE evolves the stored schema + (``_changed_record``). + may_append: Whether the commit may still be an append (``_changed_record``). Returns: ``(column, reason)``, or ``None`` when the rows can be appended. @@ -842,7 +980,7 @@ def _append_refusal( clash = _differ_only_in_case([*held, field.name]) if clash is not None: return field.name, _case_reason(*clash) - changed = _changed_record(delta_table, rows) + changed = _changed_record(delta_table, rows, schema_evolution, may_append) if changed is not None: return changed violation = _non_null_violation(held, rows) @@ -1840,6 +1978,18 @@ def require_storable(self, schema: pa.Schema) -> None: reason=reason, ) + def _holds_a_stored_id( + self, record_path: tuple[str, ...], records: pa.Table + ) -> bool: + """Whether the rows queued for the table, or ``records``, hold a stored id. + + Such a batch is committed by a MERGE whatever is added later (ITL-1403). + """ + ids = self._non_null_ids(records) | set( + self._pending_record_ids.get(self._get_record_key(record_path), ()) + ) + return bool(ids & self._stored_ids(record_path)) + def _refuse_case_clash_with_pending( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -1954,7 +2104,12 @@ def _refuse_unmergeable_append( ) from unreadable delta_table = None if delta_table is not None: - refusal = _append_refusal(delta_table, records) + refusal = _append_refusal( + delta_table, + records, + self.allow_schema_evolution, + lambda: not self._holds_a_stored_id(record_path, records), + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -2134,7 +2289,6 @@ def add_records( # A column Delta cannot hold is refused before anything is buffered (ITL-1334). self.require_storable(records.schema) - self._refuse_case_clash_with_pending(record_path, records.schema) self._refuse_untyped_null_columns(record_path, records.schema) # Step 2: Deduplicate within input table (keep last occurrence) @@ -2153,6 +2307,10 @@ def add_records( # self._check_all_conflicts(record_path, deduplicated_table) filtered_table = deduplicated_table + # Against the rows queued, on the rows that remain once duplicates are + # skipped: an all-duplicate add queues nothing and is not refused (ITL-1403). + self._refuse_case_clash_with_pending(record_path, filtered_table.schema) + # 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 @@ -2914,7 +3072,25 @@ def _flush_by_key(self, record_key: str) -> None: else: # The add-time check, against the version just loaded: another # writer may have committed since the rows were buffered (ITL-1334). - refusal = _append_refusal(delta_table, original_table) + refusal = _append_refusal( + delta_table, + original_table, + self.allow_schema_evolution, + lambda: ( + not ( + self._non_null_ids(original_table) + & ( + self._snapshot_for_commit( + record_key, + delta_table, + table_uri, + abs_path_components, + ).ids + or set() + ) + ) + ), + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -2987,8 +3163,10 @@ def _flush_by_key(self, record_key: str) -> None: logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e except Exception as e: - duplicate = _duplicate_name_in(e) - if duplicate is not None: + reported = _duplicate_name_in(e) + if reported is not None: + # The batch's own name, not the message's: a name may hold a quote. + duplicate, arrow_type = _reported_field(e, pending_batch.schema) # delta-rs folds case with Rust's ``to_lowercase``, which agrees with # Python's ``str.lower`` (the check when rows are added) except for a # few code points of newer Unicode versions. Every later flush would @@ -2996,10 +3174,6 @@ def _flush_by_key(self, record_key: str) -> None: # was written (ITL-1403). self._delta_table_cache.pop(record_key, None) self._snapshots.pop(record_key, None) - arrow_type: Any = next( - (f.type for f in pending_batch.schema if f.name == duplicate), - pa.null(), - ) refused = UnstorableColumnError( database_kind=type(self).__name__, column=duplicate, diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 354c4f4b7..a0a40c82c 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -304,3 +304,215 @@ def rows(rid: bytes, name: str) -> pa.Table: _add(db, rows(b"2", "itl1403.two")) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] assert _stored_ids(tmp_path) == [b"1"] + + +# ── Second review of PR 504 (N2-N5): refuse only what the commit would refuse ────── + +ROUTES = { + "append route (every id new)": [b"2"], + "MERGE route (a stored id among them)": [b"1", b"2"], +} + + +def _with_record_rewritten(root: Path, column: str, rewrite: Any) -> None: + """Rewrite one column's field metadata in the table's first log entry.""" + log = root / "t" / "_delta_log" / "00000000000000000000.json" + actions = [json.loads(line) for line in log.read_text().splitlines()] + for action in actions: + if "metaData" in action: + schema = json.loads(action["metaData"]["schemaString"]) + for field in schema["fields"]: + if field["name"] == column: + rewrite(field["metadata"]) + action["metaData"]["schemaString"] = json.dumps(schema) + log.write_text("\n".join(json.dumps(action) for action in actions) + "\n") + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +@pytest.mark.parametrize("route", sorted(ROUTES)) +def test_a_record_that_decodes_to_the_stored_type_is_not_a_change( + tmp_path: Path, route: str, evolution: bool +) -> None: + """N2: a stored record serialized otherwise (a trailing newline in its base64) + decodes to the same ``uint8``: the append is accepted and sent as stored, on every + commit route, as main stored it.""" + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1", x=pa.array([1], pa.uint8())), flush=True) + + def add_newline(metadata: dict[str, Any]) -> None: + metadata["orcapod:arrow_type"] += "\n" + + _with_record_rewritten(tmp_path, "x", add_newline) + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + ids = ROUTES[route] + db.add_records( + PATH, + pa.table( + { + "rid": pa.array(ids, pa.large_binary()), + "x": pa.array(list(range(1, len(ids) + 1)), pa.uint8()), + } + ), + record_id_column="rid", + skip_duplicates=len(ids) == 1, + flush=True, + ) + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert back is not None + assert back.schema.field("x").type == pa.uint8() + assert sorted(cast(list[bytes], back.column("rid").to_pylist())) == [b"1", b"2"] + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +@pytest.mark.parametrize("route", sorted(ROUTES)) +def test_a_real_record_change_is_refused_only_where_the_commit_sends_it( + tmp_path: Path, route: str, evolution: bool +) -> None: + """N2: list items widening to nullable (non-null values). A MERGE that evolves the + schema sends the new record, which deltalake refuses: refused when added. Without + schema evolution the MERGE keeps the stored schema and commits, as main did.""" + stored = pa.large_list(pa.field("item", pa.uint8(), nullable=False)) + wider = pa.large_list(pa.field("item", pa.uint8(), nullable=True)) + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1", x=pa.array([[1]], stored)), flush=True) + ids = ROUTES[route] + rows = pa.table( + { + "rid": pa.array(ids, pa.large_binary()), + "x": pa.array([[n] for n in range(len(ids))], wider), + } + ) + + def add() -> None: + db.add_records( + PATH, + rows, + record_id_column="rid", + skip_duplicates=len(ids) == 1, + flush=True, + ) + + if evolution: + with pytest.raises(InputValidationError, match="recorded Arrow type"): + add() + assert _stored_ids(tmp_path) == [b"1"] + else: + add() + assert _stored_ids(tmp_path) == [b"1", b"2"] + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +@pytest.mark.parametrize("route", sorted(ROUTES)) +@pytest.mark.parametrize( + "variant", + [ + "no metadata", + "the stored identifier", + "a readable older identifier", + "another name", + ], +) +def test_a_null_column_is_checked_like_any_column( + tmp_path: Path, variant: str, route: str, evolution: bool +) -> None: + """N3: a null column with no metadata takes the stored type; one carrying an + identifier the stored logical type reads is written under the stored identifier; + one carrying another type's identifier is refused when added wherever the commit + would send it (an evolving MERGE, or an append of new ids only), and stored where + the MERGE keeps the stored schema. Nothing reaches a flush that Delta refuses.""" + field, column, _ = _path_column() + path_type = field.type + identifiers: dict[str, dict[str, Any] | None] = { + "no metadata": None, + "the stored identifier": { + "ARROW:extension:name": path_type.extension_name, + "ARROW:extension:metadata": path_type.__arrow_ext_serialize__(), + }, + "a readable older identifier": { + "ARROW:extension:name": path_type.extension_name, + "ARROW:extension:metadata": b"", + }, + "another name": { + "ARROW:extension:name": "itl1403.not.a.path", + "ARROW:extension:metadata": b"", + }, + } + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1").append_column(field, column), flush=True) + ids = ROUTES[route] + null_field = pa.field("x", pa.null(), metadata=identifiers[variant]) + rows = pa.table({"rid": pa.array(ids, pa.large_binary())}).append_column( + null_field, pa.nulls(len(ids)) + ) + + def add() -> None: + db.add_records( + PATH, + rows, + record_id_column="rid", + skip_duplicates=len(ids) == 1, + flush=True, + ) + + sends = evolution or len(ids) == 1 + if variant == "another name" and sends: + with pytest.raises(InputValidationError, match="itl1403.not.a.path"): + add() + assert _stored_ids(tmp_path) == [b"1"] + else: + add() + back = DeltaTableDatabase(tmp_path).get_all_records( + PATH, record_id_column="rid" + ) + assert back is not None + assert back.schema.field("x").type == path_type + assert back.sort_by("rid").column("x").to_pylist() == ["/a", None] + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize("nested", [False, True], ids=["column", "struct field"]) +def test_an_all_duplicate_add_is_skipped_not_refused( + tmp_path: Path, nested: bool +) -> None: + """N4: names are checked against the queued rows after duplicates are skipped: a + row whose id is stored, skipped with ``skip_duplicates``, queues nothing, whatever + its names.""" + db = DeltaTableDatabase(tmp_path) + + def add(name: str, rid: bytes, flush: bool = False) -> None: + data = {"s": pa.array([{name: 1}])} if nested else {name: pa.array([1])} + db.add_records( + PATH, + _rows(rid, **data), + record_id_column="rid", + schema_handling="merge", + skip_duplicates=True, + flush=flush, + ) + + add("a", b"stored", flush=True) + add("a", b"pending") + add("A", b"stored") # a stored id: skipped, not refused + db.flush() + assert _stored_ids(tmp_path) == [b"pending", b"stored"] + + +@pytest.mark.parametrize("suffix", ["'q", " space", '"dq', "(x)", "::y"]) +def test_the_backstop_names_the_column_whole(tmp_path: Path, suffix: str) -> None: + """N5: the column named by the flush's case-folding refusal is the batch's own + field, with its type, also when its name holds a quote.""" + first, second = RUST_ONLY_FOLDS[0][0] + suffix, RUST_ONLY_FOLDS[0][1] + suffix + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError) as info: + _add( + db, _rows(b"1", **{first: pa.array([1]), second: pa.array([2])}), flush=True + ) + assert info.value.column in (first, second) + assert "int64" in str(info.value) diff --git a/tests/test_pipeline/test_dropped_result_batch.py b/tests/test_pipeline/test_dropped_result_batch.py new file mode 100644 index 000000000..93b1e2178 --- /dev/null +++ b/tests/test_pipeline/test_dropped_result_batch.py @@ -0,0 +1,62 @@ +"""A result batch the store refuses at a flush leaves no pipeline record behind. + +Review of PR 504 (second round, N1): when ``DeltaTableDatabase`` drops a result batch +at the flush (names Delta folds alike only by its own case folding, U+1C89 and U+1C8A), +the job's failure-time flush still committed the node's pipeline records, which then +name results that were never stored. The invariant (no pipeline record without its +result) is fixed for every cause under ITL-1412, which PR 504 waits for. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.system_constants import constants + +UPPER, LOWER = "Ᲊ", "ᲊ" + + +@function_pod(output_keys=[UPPER, LOWER]) +def _pair(x: int | None) -> tuple[int, int]: + return x or 0, (x or 0) + 10 + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="ITL-1412: the failure-time flush commits pipeline records of a dropped result batch", +) +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_no_pipeline_record_names_a_dropped_result( + tmp_path: Path, use_async: bool +) -> None: + source = ArrowTableSource( + pa.table({"k": [1, 2], "x": [3, 4]}), + tag_columns=["k"], + tag_only_columns=True, + record_id_columns=["k"], + source_id="s", + ) + database = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="itl1403", database=database) + with job: + _pair.pod(source, label="pair") + with pytest.raises(Exception): # noqa: B017 # the run fails: the result batch is dropped + if use_async: + asyncio.run(job.run_async()) + else: + job.run() + fresh = DeltaTableDatabase(tmp_path) + referenced: list[object] = [] + for path in fresh.list_table_paths(): + table = fresh.get_all_records(path, record_id_column="__record_id") + if table is not None and constants.DATA_RECORD_ID in table.column_names: + referenced += table[constants.DATA_RECORD_ID].to_pylist() + assert [r for r in referenced if r is not None] == [] From d0a2363d5116df8a5ea2a93863f227dceaad4766 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:06:21 -0800 Subject: [PATCH 06/12] fix(databases): the Delta flush is the point of truth; refuse when added only what is certain (ITL-1403) The developer's decision (2026-11-22): no prediction of what deltalake will do at commit. When rows are added only exact checks remain: names differing only in case (top level and nested, also a struct evolution that would put two such names into one struct), a stored table deltalake cannot read, and the logical identifier of a typed column against the stored one. The record/metadata-change preflight (_changed_record, the route prediction, the stored-id lookup) is gone. At the flush a failed commit is classified (_permanent_commit_failure): SchemaMismatchError, the duplicate-name error and a DeltaError starting with one of PERMANENT_DELTA_ERROR_PREFIXES ('type_coercion', 'Invalid data found', 'Unsupported CAST') are raised once, naming the table, Delta's reason and the rows not written, and the batch leaves the queue; CommitFailedError and every other failure keep main's behaviour. The duplicate-name backstop locates the colliding field with Delta's own schema check. Tests: each permanent form provoked with deltalake itself; a storage failure keeps its rows queued; the review sweep as a property test (Orcapod refuses nothing Delta stores; nothing stays queued); every review finding asserts the flush behaviour where the add-time check was removed. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 37 ++- docs/reference/database-types.md | 26 +- docs/troubleshooting.md | 23 ++ src/orcapod/databases/delta_lake_databases.py | 296 ++++++++---------- .../test_delta_add_time_property.py | 185 +++++++++++ .../test_delta_append_preflight.py | 8 +- .../test_delta_commit_failures.py | 186 +++++++++++ .../test_delta_read_failures.py | 7 +- .../test_delta_refused_before_queueing.py | 162 +++++++--- .../test_delta_struct_evolution.py | 19 +- tests/test_databases/type_matrix.py | 26 +- .../test_delta_refusals_in_jobs.py | 21 +- 12 files changed, 751 insertions(+), 245 deletions(-) create mode 100644 tests/test_databases/test_delta_add_time_property.py create mode 100644 tests/test_databases/test_delta_commit_failures.py diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index 7c32c8d7f..fb9d91d2f 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -26,19 +26,30 @@ Rust's `to_lowercase` does: for the few code points where Python's `str.lower` differs, the refusal comes at the flush, once, as `UnstorableColumnError`, and the batch leaves the queue. The in-memory and connector databases still hold such names as two columns. -- `DeltaTableDatabase` refuses an append that would change a stored column's field - metadata (`InputValidationError` naming the column, before anything is queued): - deltalake 1.5 and later refuses such a commit. Two cases: - - A column's recorded Arrow type: every list and map column, and every struct holding - an unsigned integer, a non-microsecond time type, `float16` or a fixed-size type. A - field added to such a struct changes it, in the small list form as in the large one, - and so does a change of nested nullability (a list's items becoming nullable). - - A logical column's identifier: another extension name, or the same name with other - extension metadata. - - Still accepted: a struct column without a record gaining fields, a field omitted or - reordered, a new column, and an untyped `null` column, which takes the stored type. - Tables Orcapod's own nodes write are not concerned: their column types are fixed by +- On Delta the commit is the point of truth. When rows are added, `DeltaTableDatabase` + refuses only what it can tell for certain: names differing only in case (above), a + stored table deltalake cannot read, another logical type + (another extension name, or the same name with other extension metadata) over a stored + logical column, and a struct evolution that would put two names differing only in case + into one struct. Telling more rules up front is ITL-1418. +- What deltalake refuses at the commit for the rows themselves is raised by the flush + once, as `InputValidationError` ("Delta refused the commit to table ...") naming the + table, Delta's reason and the number of rows not written. Those rows leave the queue, + the other tables of the same flush still commit, and a second flush does nothing. A + job fails with `OrcapodDatabaseWriteError` and that cause. The permanent refusals are + `SchemaMismatchError`, the duplicate-name error, and a `DeltaError` whose message starts + with one of `PERMANENT_DELTA_ERROR_PREFIXES` (`type_coercion`, `Invalid data found`, + `Unsupported CAST`). Any other failure keeps its rows queued as before, so nothing is + dropped on a guess. Until ITL-1412, a job whose result batch is dropped this way can + keep pipeline records naming those results. +- This narrows what a Delta table takes from deltalake 1.5 on: a stored column's field + metadata cannot change in a commit. So a column whose Arrow type is recorded cannot + gain a struct field, or have a nested nullability change, when schema evolution is on. + A recorded column is every list and map column, and every struct holding an unsigned + integer, a non-microsecond time type, `float16` or a fixed-size type. A struct column + without a record still gains fields, a field may be omitted or reordered, a new column + may be added, and an untyped `null` column takes the stored type. +- Tables Orcapod's own nodes write are not concerned: their column types are fixed by their inputs' schemas, and a changed column type changes the table's path. The one exception is an operator whose result type depends on its data rather than on its input schemas, which is a bug of that operator. Example: a custom operator emitting diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index e295ea606..983ecb2c4 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -79,15 +79,23 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps -through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field, nor have a nested nullability change: the record is the -column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit -change, so such an append is refused, naming the column, before anything is queued. A -struct column without a record still gains fields, an append may still add a new column, -and an untyped `null` column takes the stored type. Another logical type over a stored -logical column (another extension name, or the same name with other extension metadata) -is refused the same way. +as nullable afterwards, as Delta stores it. + +On Delta, the commit is the point of truth. When rows are added, only what is certain is +refused, before anything is queued: two names differing only in case, a stored table +deltalake cannot read, another logical type (another +extension name or other extension metadata) over a stored logical column, and a struct +evolution that would put two names differing only in case into one struct. What +deltalake refuses at the commit for the rows themselves (a changed field metadata, a type +it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, +naming the table, Delta's reason and the rows not written; those rows leave the queue, +and the other tables of the flush still commit. Any other failure keeps its rows queued. +So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" +cells below, every list and map included) cannot gain a field when schema evolution is +on, nor have a nested nullability change: the record is the column's field metadata, +which deltalake 1.5 and later does not let a commit change. A struct column without a +record still gains fields, an append may still add a new column, and an untyped `null` +column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 4d494707e..e2dcebf95 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -205,6 +205,29 @@ the names of your functions, not their code. `loaded.run(load_only=True)` to fill the nodes from the database (bind in-memory sources first). To compute, run the script that defines the pipeline. +### `InputValidationError: Delta refused the commit to table ...` + +**Symptom.** A flush, or a job's commit (`OrcapodDatabaseWriteError` with this error as +its cause), fails with `Delta refused the commit to table '...': . The N +rows queued for it were not written and are no longer queued`. `UnstorableColumnError` +saying that Delta reports a name as equal to another's under its case folding is the same +kind of failure. + +**Cause.** A `DeltaTableDatabase` refuses only what it can tell for certain when rows are +added (names that differ only in case, a stored table deltalake cannot read, another logical type over a stored logical column). Everything +else is decided by deltalake when it commits. The refusals that would happen again at +every flush are raised once: a changed field metadata, which deltalake 1.5 and later +refuses (a struct with a recorded type gaining a field, a list's items becoming +nullable), a type DataFusion cannot insert or cast into the stored one, or a null in a +non-nullable column. The rows are dropped from the queue so that the next flush is not +refused the same way; other tables of the same flush still commit. A failure that may +pass, such as a storage error, keeps its rows queued, and the next flush tries them +again. + +**Fix.** Read Delta's reason, correct the rows (or their declared types) and add them +again. In a job, running it again computes the same rows and fails the same way until +then. [Data types per database](reference/database-types.md) lists what each database stores. + ## Problems that give no error ### I edited my function and the results did not change diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 149debef4..cf36ad012 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -617,61 +617,117 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: def _duplicate_name_in(error: BaseException) -> str | None: """The name delta-rs reports as a case-insensitive duplicate in ``error``'s chain.""" - seen: BaseException | None = error - while seen is not None: + for seen in _error_chain(error): match = _DUPLICATE_NAME.search(str(seen)) if match is not None: return match.group(1) - seen = seen.__cause__ or seen.__context__ return None -def _all_fields(schema: pa.Schema) -> list["pa.Field[Any]"]: - """Every field of ``schema``: top-level columns and struct fields at any depth.""" - found: list[pa.Field[Any]] = [] +def _error_chain(error: BaseException) -> list[BaseException]: + """``error`` and its causes and contexts, each once: a chain may loop. - def visit(field: "pa.Field[Any]") -> None: - found.append(field) - arrow_type = field.type - if isinstance(arrow_type, pa.ExtensionType): - arrow_type = arrow_type.storage_type - for i in range(arrow_type.num_fields): - visit(arrow_type.field(i)) + It does when an error is raised again inside the handler of an error that wraps + it (a lost commit's retry gives up with the error it lost to; ITL-1377). + """ + chain: list[BaseException] = [] + seen: BaseException | None = error + while seen is not None and all(seen is not e for e in chain): + chain.append(seen) + seen = seen.__cause__ or seen.__context__ + return chain + + +# The forms of a plain ``DeltaError`` that are permanent: DataFusion cannot insert the +# rows into the stored schema, cannot cast them to it, or the rows break a constraint of +# the stored table (a null in a non-nullable column). Every later flush would fail the +# same way. +# ``DeltaError`` is also how deltalake reports a storage failure, which may pass, so +# only these message forms are taken as permanent (deltalake 1.6.6; ITL-1403). +PERMANENT_DELTA_ERROR_PREFIXES = ( + "Generic DeltaTable error: type_coercion", + "Generic DeltaTable error: External error: Invalid data found", + "Generic DeltaTable error: This feature is not implemented: Unsupported CAST", +) - for field in schema: - visit(field) - return found + +def _permanent_commit_failure(error: BaseException) -> bool: + """Whether a failed commit would fail the same way at every later flush. + + Permanent: ``SchemaMismatchError`` (Delta refuses the rows' schema or field + metadata), the duplicate-name error (two names equal under Delta's case folding, + a bare ``Exception``), and a ``DeltaError`` whose message starts with one of + ``PERMANENT_DELTA_ERROR_PREFIXES``. Not permanent: ``CommitFailedError`` (another + writer committed first) and everything else, which keeps its rows queued. + """ + from deltalake.exceptions import ( + CommitFailedError, + DeltaError, + SchemaMismatchError, + ) + + if isinstance(error, CommitFailedError): + return False + if isinstance(error, SchemaMismatchError): + return True + if type(error) is Exception and _DUPLICATE_NAME.search(str(error)): + return True + if isinstance(error, DeltaError): + return str(error).startswith(PERMANENT_DELTA_ERROR_PREFIXES) + return False def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: """The field of ``schema`` delta-rs names as a duplicate in ``error``'s chain. - The name is taken from the schema, the longest one Delta's message quotes, so a + Delta's own schema check locates it: a column whose schema Delta refuses on its own + holds the colliding struct fields, and the field is named by its path in that + column (``s.ᲊ``) with its type; otherwise the collision is between top-level + columns. Names come from the schema, the longest one Delta's message quotes, so a name holding a quote is named whole. ``(the reported text, null)`` when no field matches. """ - messages: list[str] = [] - seen: BaseException | None = error - while seen is not None: - messages.append(str(seen)) - seen = seen.__cause__ or seen.__context__ - quoted = [ - f - for f in _all_fields(schema) - if any(f"(case-insensitive): '{f.name}'" in m for m in messages) - ] - if quoted: - field = max(quoted, key=lambda f: len(f.name)) + messages = [str(seen) for seen in _error_chain(error)] + + def quoted(field: "pa.Field[Any]") -> bool: + return any(f"(case-insensitive): '{field.name}'" in m for m in messages) + + for column in schema: + try: + deltalake.Schema.from_arrow(pa.schema([column])) + except Exception as refused: # noqa: BLE001 # only a duplicate name is looked at + if _duplicate_name_in(refused) is None: + continue + nested = [ + (path, field) + for path, field in _field_paths(column) + if path != column.name and quoted(field) + ] + if nested: + path, field = max(nested, key=lambda item: len(item[1].name)) + return path, field.type + top = [field for field in schema if quoted(field)] + if top: + field = max(top, key=lambda f: len(f.name)) return field.name, field.type return _duplicate_name_in(error) or "", pa.null() -# Why a recorded column's record cannot change on Delta (ITL-1403). -_RECORD_CHANGE = ( - "the append would change the column's recorded Arrow type, and a recorded " - "column's type cannot change on a Delta table: deltalake refuses a commit that " - "changes a column's field metadata (deltalake 1.5 and later)" -) +def _field_paths(column: "pa.Field[Any]") -> list[tuple[str, "pa.Field[Any]"]]: + """``column`` and every struct field inside it, each with its dotted path.""" + found: list[tuple[str, pa.Field[Any]]] = [] + + def visit(path: str, field: "pa.Field[Any]") -> None: + found.append((path, field)) + arrow_type = field.type + if isinstance(arrow_type, pa.ExtensionType): + arrow_type = arrow_type.storage_type + for i in range(arrow_type.num_fields): + child = arrow_type.field(i) + visit(f"{path}.{child.name}", child) + + visit(column.name, column) + return found _EXTENSION_KEYS = (b"ARROW:extension:name", b"ARROW:extension:metadata") @@ -836,97 +892,50 @@ def _non_null_violation( return None -def _metadata_sent(field: "pa.Field[Any]") -> dict[str, str]: - """The field metadata a commit sends to Delta for ``field``, as text. - - A logical column also carries its identifier as ``ARROW:extension:name`` and - ``ARROW:extension:metadata``, as the Arrow C interface hands it to delta-rs. - """ - sent = { - k.decode() if isinstance(k, bytes) else k: ( - v.decode(errors="replace") if isinstance(v, bytes) else v - ) - for k, v in (field.metadata or {}).items() - } - if isinstance(field.type, pa.ExtensionType): - identifier = arrow_type_identifier(field.type) - sent["ARROW:extension:name"] = identifier.name - sent["ARROW:extension:metadata"] = identifier.metadata.decode(errors="replace") - return sent - - -def _changed_record( - delta_table: deltalake.DeltaTable, - rows: pa.Table, - schema_evolution: bool, - may_append: Callable[[], bool], +def _exact_refusal( + delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: - """The first stored column whose field metadata (or nested names) the append changes. - - deltalake (1.5 and later) refuses a commit that gives a stored column's field - metadata key another value (delta-rs ``try_merge_metadata``). That metadata holds a - recorded column's record (``orcapod:arrow_type``) and a logical column's identifier - (``ARROW:extension:name`` and ``ARROW:extension:metadata``). The metadata the - commit would send is computed here by the functions the flush uses - (``to_delta_layout``, ``_conformed_to_stored``, ``_with_merged_records``), so the - rows are refused when they are added, never left to fail at every flush. A new key - is accepted, as Delta adds it; so is a bare ``null`` column, which sends no - metadata and takes the stored type. A record or identifier that decodes to the - stored one is sent as stored (``_with_merged_records``), so only a real change - remains, and it is refused only on a commit route that sends the metadata: a - MERGE that evolves the schema, or an append (``_stores_as_is``, the flush's own - decision). A MERGE without schema evolution keeps the stored schema and commits. - A struct evolution that would put two field names differing only in case into one - struct is refused too. + """What Orcapod can tell for certain about an append to ``delta_table`` (ITL-1403). + + The commit itself is the point of truth: what deltalake refuses for any other + reason is refused at the flush, once (``_permanent_commit_failure``). Only two + things are refused here, both certain: + + - a typed logical column whose identifier (extension name and metadata) is not + the stored column's: another logical type, whose values must not be read as + the stored one's; + - a struct evolution that would put two field names differing only in case into + one struct, which Delta refuses whatever the commit route. Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. - schema_evolution: Whether the database's MERGE evolves the stored schema - (``allow_schema_evolution``). - may_append: Whether the commit may still be an append rather than a MERGE: - no id of the rows to commit is stored. Asked only when a real change is - found and the schema does not evolve. Returns: ``(column, reason)``, or ``None``. """ stored = _stored_arrow_schema(delta_table) - stored_metadata = {f.name: dict(f.metadata) for f in delta_table.schema().fields} - empty = rows.slice(0, 0) - # ``_conformed_to_stored`` refuses a struct the stored table cannot take, as the - # flush would (``InputValidationError``). - sent_table = _with_merged_records( - delta_table, - empty, - _conformed_to_stored( - delta_table, to_delta_layout(empty), delta_table.table_uri - ), - ) - sent_schema = sent_table.schema - # The flush appends rows whose ids are all new and that it stores as they are; - # every other batch is a MERGE, which sends its schema only when it evolves it. - as_is = DeltaTableDatabase._stores_as_is(delta_table, sent_table) + held = {f.name: dict(f.metadata) for f in delta_table.schema().fields} for field in rows.schema: position = stored.get_field_index(field.name) if position < 0: continue - held = stored_metadata[field.name] - sent = _metadata_sent(sent_schema.field(field.name)) - changed = sorted(k for k, v in sent.items() if k in held and str(held[k]) != v) - if changed and (schema_evolution or (as_is and may_append())): - if any(k.startswith("ARROW:extension:") for k in changed): + if isinstance(field.type, pa.ExtensionType): + stored_name = held[field.name].get("ARROW:extension:name") + if stored_name is None: + continue + incoming = arrow_type_identifier(field.type) + stored_metadata = str(held[field.name].get("ARROW:extension:metadata", "")) + if (incoming.name, incoming.metadata.decode(errors="replace")) != ( + stored_name, + stored_metadata, + ): return field.name, ( - "it is stored as logical type " - f"{held.get('ARROW:extension:name')!r} " - f"({held.get('ARROW:extension:metadata')!r}) and the rows hold " - f"{sent.get('ARROW:extension:name')!r} " - f"({sent.get('ARROW:extension:metadata')!r}): a column's field " - "metadata cannot change on a Delta table (deltalake 1.5 and later " - "refuses such a commit)" + f"it is stored as logical type {stored_name!r} " + f"({stored_metadata!r}) and the rows hold {incoming.name!r} " + f"({incoming.metadata.decode(errors='replace')!r}): another " + "logical type" ) - return field.name, _RECORD_CHANGE - if isinstance(field.type, pa.ExtensionType) or pa.types.is_null(field.type): continue try: evolved = merged_type( @@ -942,10 +951,7 @@ def _changed_record( def _append_refusal( - delta_table: deltalake.DeltaTable, - rows: pa.Table, - schema_evolution: bool, - may_append: Callable[[], bool], + delta_table: deltalake.DeltaTable, rows: pa.Table ) -> tuple[str, str] | None: """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). @@ -963,9 +969,6 @@ def _append_refusal( Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. - schema_evolution: Whether the database's MERGE evolves the stored schema - (``_changed_record``). - may_append: Whether the commit may still be an append (``_changed_record``). Returns: ``(column, reason)``, or ``None`` when the rows can be appended. @@ -980,9 +983,9 @@ def _append_refusal( clash = _differ_only_in_case([*held, field.name]) if clash is not None: return field.name, _case_reason(*clash) - changed = _changed_record(delta_table, rows, schema_evolution, may_append) - if changed is not None: - return changed + exact = _exact_refusal(delta_table, rows) + if exact is not None: + return exact violation = _non_null_violation(held, rows) if violation is not None: name, omitted = violation @@ -1978,18 +1981,6 @@ def require_storable(self, schema: pa.Schema) -> None: reason=reason, ) - def _holds_a_stored_id( - self, record_path: tuple[str, ...], records: pa.Table - ) -> bool: - """Whether the rows queued for the table, or ``records``, hold a stored id. - - Such a batch is committed by a MERGE whatever is added later (ITL-1403). - """ - ids = self._non_null_ids(records) | set( - self._pending_record_ids.get(self._get_record_key(record_path), ()) - ) - return bool(ids & self._stored_ids(record_path)) - def _refuse_case_clash_with_pending( self, record_path: tuple[str, ...], schema: pa.Schema ) -> None: @@ -2104,12 +2095,7 @@ def _refuse_unmergeable_append( ) from unreadable delta_table = None if delta_table is not None: - refusal = _append_refusal( - delta_table, - records, - self.allow_schema_evolution, - lambda: not self._holds_a_stored_id(record_path, records), - ) + refusal = _append_refusal(delta_table, records) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -3072,25 +3058,7 @@ def _flush_by_key(self, record_key: str) -> None: else: # The add-time check, against the version just loaded: another # writer may have committed since the rows were buffered (ITL-1334). - refusal = _append_refusal( - delta_table, - original_table, - self.allow_schema_evolution, - lambda: ( - not ( - self._non_null_ids(original_table) - & ( - self._snapshot_for_commit( - record_key, - delta_table, - table_uri, - abs_path_components, - ).ids - or set() - ) - ) - ), - ) + refusal = _append_refusal(delta_table, original_table) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -3163,6 +3131,20 @@ def _flush_by_key(self, record_key: str) -> None: logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e except Exception as e: + if _permanent_commit_failure(e) and _duplicate_name_in(e) is None: + # Refused by Delta for the rows themselves: every later flush would be + # refused the same way, so the batch leaves the queue, and nothing of + # it was written (ITL-1403). The flush is the point of truth. + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + refused = InputValidationError( + f"Delta refused the commit to table {record_key!r}: " + f"{str(e).rstrip('.')}. The " + f"{pending_batch.num_rows} rows queued for it were not written " + "and are no longer queued: correct them and add them again." + ) + logger.error(f"Refused batch for {record_key}: {refused}") + raise refused from e reported = _duplicate_name_in(e) if reported is not None: # The batch's own name, not the message's: a name may hold a quote. diff --git a/tests/test_databases/test_delta_add_time_property.py b/tests/test_databases/test_delta_add_time_property.py new file mode 100644 index 000000000..37d513f98 --- /dev/null +++ b/tests/test_databases/test_delta_add_time_property.py @@ -0,0 +1,185 @@ +"""The property of a ``DeltaTableDatabase`` append: Orcapod refuses nothing Delta stores. + +The developer's decision for ITL-1403 (2026-11-22): the flush is the point of truth. +When rows are added, only what Orcapod can tell for certain is refused; everything else +is left to the commit, whose refusal the flush raises once, without keeping the rows +queued. This file is the review of PR 504's sweep, as a test: every stored type (same +schema, as written), every record change, struct evolution, null and layout case and +logical-type case, with schema evolution on and off, and with the commit an append +(every id new) or a MERGE (a stored id among the rows). For each: + +- what Orcapod refuses when the rows are added, Delta refuses too: the same rows given + to the database with Orcapod's add-time checks switched off are not stored (the one + exception is the logical-type rule, an Orcapod rule by design: another logical type's + values must not be read as the stored one's); +- nothing fails forever: after the flush, no row is still queued. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from itertools import product +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases as dld +from tests.test_databases import test_delta_append_types as append_types +from tests.test_databases import test_delta_refused_before_queueing as refused +from tests.test_databases import test_delta_struct_evolution as evolution + +PATH = ("t",) + + +def _variants() -> Iterator[tuple[str, Any, Any, Any, Any]]: + for param in append_types.all_types(): + name, arrow_type, nullable = param.values + if name in append_types.NOT_STORABLE: + continue + column = append_types.column(arrow_type) + field = pa.field("x", arrow_type, nullable=nullable) + yield f"same {param.id}", column, column, field, field + for label, (a, b) in refused.RECORD_CHANGES.items(): + yield f"record {label}", a, b, None, None + for label, (at, av, bt, bv, _) in evolution.CASES.items(): + yield f"evolution {label}", pa.array(av, at), pa.array(bv, bt), None, None + for label, (a, b) in { + "simple null": (pa.array([1]), pa.nulls(1)), + "null struct field": ( + pa.array([{"a": 1}]), + pa.array([{"a": None}], pa.struct([("a", pa.null())])), + ), + "null list item": ( + pa.array([[1]], pa.large_list(pa.int64())), + pa.array([[None]], pa.large_list(pa.null())), + ), + "null into recorded unsigned": (pa.array([1], pa.uint8()), pa.nulls(1)), + "null into recorded list": (pa.array([[1]], pa.list_(pa.int64())), pa.nulls(1)), + "plain field becomes nullable": ( + pa.array( + [{"a": 1}], pa.struct([pa.field("a", pa.int64(), nullable=False)]) + ), + pa.array([{"a": None}], pa.struct([("a", pa.int64())])), + ), + "small list then large": ( + pa.array([[1]], pa.list_(pa.int64())), + pa.array([[2]], pa.large_list(pa.int64())), + ), + }.items(): + yield f"null/layout {label}", a, b, None, None + field, column, _ = refused._path_column() # pyright: ignore[reportPrivateUsage] + stored = column.combine_chunks() if isinstance(column, pa.ChunkedArray) else column + for label, ext in { + "bare": None, + "current": field.type.__arrow_ext_serialize__(), + "readable old": b"", + "unknown": b"bogus", + }.items(): + metadata = ( + None + if ext is None + else { + b"ARROW:extension:name": field.type.extension_name.encode(), + b"ARROW:extension:metadata": ext, + } + ) + yield ( + f"path null {label}", + stored, + pa.nulls(1), + field, + pa.field("x", pa.null(), metadata=metadata), + ) + for label, a, b in [ + ("same", b"x", b"x"), + ("changed", b"x", b"y"), + ("empty to value", b"", b"y"), + ("value to empty", b"x", b""), + ]: + units = [ + pa.ExtensionArray.from_storage(refused._Unit(v), pa.array([1])) # pyright: ignore[reportPrivateUsage] + for v in (a, b) + ] + yield f"logical {label}", units[0], units[1], None, None + + +VARIANTS = {label: rest for label, *rest in _variants()} +LOGICAL_RULE = {"logical changed", "logical empty to value", "logical value to empty"} + + +def _rows(column: Any, ids: list[bytes], field: Any = None) -> pa.Table: + values = pa.concat_arrays([column] * len(ids)) if len(ids) > 1 else column + return pa.table( + [pa.array(ids, pa.large_binary()), values], + schema=pa.schema( + [ + pa.field("rid", pa.large_binary(), nullable=False), + field or pa.field("x", column.type), + ] + ), + ) + + +def _run( + root: Path, initial: pa.Table, incoming: pa.Table, evolve: bool +) -> tuple[str, bool]: + """``(outcome, rows still queued)``: ``stored``, ``refused when added``, or + ``refused at flush``.""" + db = DeltaTableDatabase(root, allow_schema_evolution=evolve) + db.add_records(PATH, initial, record_id_column="rid", flush=True) + try: + db.add_records(PATH, incoming, record_id_column="rid") + except Exception: # noqa: BLE001 # the outcome is the subject + return "refused when added", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] + try: + db.flush() + except Exception: # noqa: BLE001 + return "refused at flush", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] + return "stored", False + + +@pytest.fixture(autouse=True) +def _unit_registered(unit_type: Any) -> None: + """The logical cases use a registered extension type.""" + + +unit_type = refused.unit_type + + +@pytest.mark.parametrize( + "seen", [False, True], ids=["append (every id new)", "MERGE (a stored id)"] +) +@pytest.mark.parametrize("evolve", [False, True], ids=["evolution off", "evolution on"]) +@pytest.mark.parametrize("label", sorted(VARIANTS)) +def test_orcapod_refuses_nothing_delta_stores( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + label: str, + evolve: bool, + seen: bool, +) -> None: + a, b, field_a, field_b = VARIANTS[label] + initial = _rows(a, [b"1"], field_a) + incoming = _rows(b, [b"1", b"2"] if seen else [b"2"], field_b) + + live, queued = _run(tmp_path / "live", initial, incoming, evolve) + assert not queued, f"{label}: rows still queued after the flush ({live})" + + if live == "refused when added" and label not in LOGICAL_RULE: + # Delta's own verdict: the same rows with Orcapod's add-time checks off. + monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) + monkeypatch.setattr( + DeltaTableDatabase, "_refuse_case_clash_with_pending", lambda *args: None + ) + raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw != "stored", f"{label}: Orcapod refused rows Delta stores" + + +def test_the_sweep_covers_every_kind() -> None: + kinds = {label.split(" ")[0] for label in VARIANTS} + assert kinds == {"same", "record", "evolution", "null/layout", "path", "logical"} + assert len(VARIANTS) > 100 + _ = product # the sweep is the product of the three parameters above diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index 27327206c..6309da989 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -305,7 +305,7 @@ def test_a_null_child_of_an_evolving_struct_appends( ) -> None: """Delta's MERGE panicked on a ``null`` child of a struct that gains a field (pre-existing); the child is written as typed nulls of its stored type. Inside a - list (a recorded column) the evolution is refused instead (ITL-1403).""" + list (a recorded column) Delta refuses the evolution, once, at the flush (ITL-1403).""" stored_type = _struct(pa.field("a", I64)) in_list = pa.types.is_large_list(appended) db = DeltaTableDatabase(tmp_path) @@ -323,9 +323,9 @@ def test_a_null_child_of_an_evolving_struct_appends( ) value = {"a": None, "b": 2} if in_list: - # A list column is recorded, and its record would change: refused on Delta - # before anything is buffered (ITL-1403). - with pytest.raises(InputValidationError, match="recorded Arrow type"): + # A list column is recorded, and its record would change: Delta refuses the + # commit; the flush raises once and the batch leaves the queue (ITL-1403). + with pytest.raises(InputValidationError, match="Delta refused the commit"): db.add_records( PATH, _rows([b"2"], x=(appended, [[value]])), diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py new file mode 100644 index 000000000..25a15d368 --- /dev/null +++ b/tests/test_databases/test_delta_commit_failures.py @@ -0,0 +1,186 @@ +"""How a failed Delta commit is classified at the flush (ITL-1403). + +The flush is the point of truth: a commit deltalake refuses for the rows themselves +would be refused the same way at every later flush, so it is raised once and the batch +leaves the queue; anything else keeps its rows queued, so nothing is dropped on a guess. + +Each permanent form is provoked here with deltalake itself, so an upgrade that changes +an exception type or one of ``PERMANENT_DELTA_ERROR_PREFIXES`` fails this file. +""" + +from __future__ import annotations + +import os +import stat +import sys +from collections.abc import Callable +from pathlib import Path +from typing import Any, cast + +import deltalake +import pyarrow as pa +import pytest + +from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases as dld +from orcapod.errors import InputValidationError + +PATH = ("t",) + + +def _raised(action: Callable[[], Any]) -> BaseException: + try: + action() + except Exception as error: # noqa: BLE001 # the error is the subject + return error + raise AssertionError("deltalake did not refuse") + + +def _merge(table: deltalake.DeltaTable, rows: pa.Table, evolve: bool = True) -> Any: + return ( + table.merge( + rows, + "t.id = s.id", + source_alias="s", + target_alias="t", + merge_schema=evolve, + ) + .when_not_matched_insert_all() + .execute() + ) + + +def _metadata_change(root: Path) -> BaseException: + def table(value: str) -> pa.Table: + field = pa.field("x", pa.int64(), metadata={"k": value}) + return pa.Table.from_arrays( + [pa.array([1]), pa.array([1])], + schema=pa.schema([pa.field("id", pa.int64()), field]), + ) + + deltalake.write_deltalake(str(root), table("1")) + return _raised(lambda: _merge(deltalake.DeltaTable(str(root)), table("2"))) + + +def _type_coercion(root: Path) -> BaseException: + deltalake.write_deltalake( + str(root), pa.table({"id": [1], "s": pa.array([{"x": 1}])}) + ) + grown = pa.table({"id": [2], "s": pa.array([{"x": 2, "y": 3}])}) + return _raised(lambda: _merge(deltalake.DeltaTable(str(root)), grown, evolve=False)) + + +def _invalid_data(root: Path) -> BaseException: + schema = pa.schema( + [pa.field("id", pa.int64()), pa.field("v", pa.int64(), nullable=False)] + ) + deltalake.write_deltalake( + str(root), pa.Table.from_arrays([pa.array([1]), pa.array([1])], schema=schema) + ) + nulls = pa.table({"id": [2], "v": pa.array([None], pa.int64())}) + return _raised(lambda: _merge(deltalake.DeltaTable(str(root)), nulls)) + + +def _unsupported_cast(root: Path) -> BaseException: + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("s", pa.struct([pa.field("a", pa.int64(), nullable=False)])), + ] + ) + deltalake.write_deltalake( + str(root), + pa.Table.from_arrays( + [pa.array([1]), pa.array([{"a": 1}], schema.field("s").type)], schema=schema + ), + ) + loosened = pa.table( + {"id": [2], "s": pa.array([{"a": None}], pa.struct([("a", pa.int64())]))} + ) + return _raised( + lambda: _merge(deltalake.DeltaTable(str(root)), loosened, evolve=False) + ) + + +def _duplicate_name(root: Path) -> BaseException: + return _raised( + lambda: deltalake.write_deltalake( + str(root), pa.table({"id": [1], "a": [1], "A": [2]}) + ) + ) + + +PERMANENT: dict[str, Callable[[Path], BaseException]] = { + "SchemaMismatchError (field metadata)": _metadata_change, + "DeltaError 'type_coercion' (DataFusion cannot insert)": _type_coercion, + "DeltaError 'Invalid data found' (a null in a non-nullable column)": _invalid_data, + "DeltaError 'Unsupported CAST' (a nested field loosened, no evolution)": _unsupported_cast, + "Exception 'Duplicate field name' (case-insensitive names)": _duplicate_name, +} + + +@pytest.mark.parametrize("case", sorted(PERMANENT)) +def test_each_permanent_form_of_deltalake_is_classified_permanent( + tmp_path: Path, case: str +) -> None: + error = PERMANENT[case](tmp_path / "t") + assert dld._permanent_commit_failure(error), (type(error), str(error)) # pyright: ignore[reportPrivateUsage] + + +def test_the_prefixes_are_the_documented_three() -> None: + assert dld.PERMANENT_DELTA_ERROR_PREFIXES == ( + "Generic DeltaTable error: type_coercion", + "Generic DeltaTable error: External error: Invalid data found", + "Generic DeltaTable error: This feature is not implemented: Unsupported CAST", + ) + + +def test_a_concurrent_commit_is_not_permanent(tmp_path: Path) -> None: + from deltalake.exceptions import CommitFailedError + + root = str(tmp_path / "t") + deltalake.write_deltalake(root, pa.table({"id": [1]})) + stale = deltalake.DeltaTable(root) + _merge(deltalake.DeltaTable(root), pa.table({"id": [2]})) + error = _raised(lambda: _merge(stale, pa.table({"id": [3]}))) + assert isinstance(error, CommitFailedError) + assert not dld._permanent_commit_failure(error) # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="permissions") +def test_a_storage_failure_keeps_the_rows_queued(tmp_path: Path) -> None: + """A failure that may pass (here an unwritable table directory) is not dropped: + the rows stay queued, and a later flush, once the store is writable, commits them.""" + db = DeltaTableDatabase(tmp_path) + rows = lambda rid: pa.table({"rid": pa.array([rid], pa.large_binary()), "v": [1]}) # noqa: E731 + db.add_records(PATH, rows(b"1"), record_id_column="rid", flush=True) + db.add_records(PATH, rows(b"2"), record_id_column="rid", skip_duplicates=True) + table_dir = tmp_path / "t" + os.chmod(table_dir, stat.S_IRUSR | stat.S_IXUSR) + try: + with pytest.raises(Exception) as info: # noqa: B017 # main's error, unchanged + db.flush() + assert not isinstance(info.value, InputValidationError) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + finally: + os.chmod(table_dir, stat.S_IRWXU) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("rid").to_pylist())) == [b"1", b"2"] + + +def test_a_type_coercion_refusal_is_raised_once_through_orcapod(tmp_path: Path) -> None: + """A struct gaining a field with schema evolution off: accepted when added (nothing + Orcapod can tell for certain), refused by Delta at the commit, raised once.""" + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=False) + rows = lambda rid, value: pa.table( # noqa: E731 + {"rid": pa.array([rid], pa.large_binary()), "s": pa.array([value])} + ) + db.add_records(PATH, rows(b"1", {"x": 1}), record_id_column="rid", flush=True) + db.add_records(PATH, rows(b"2", {"x": 2, "y": 3}), record_id_column="rid") + with pytest.raises(InputValidationError, match="type_coercion") as info: + db.flush() + assert "1 rows queued for it were not written" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 842d37d1c..4af6e7292 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -471,14 +471,15 @@ def test_new_struct_field(self, base: Path) -> None: def test_new_struct_field_inside_a_list_is_refused(self, base: Path) -> None: """An append that adds a field to a struct inside a list column would change - the list column's recorded type: refused before anything is buffered, the - stored rows unchanged (deltalake refuses such a commit; ITL-1403).""" + the list column's recorded type: Delta refuses the commit, the flush raises + once and the batch leaves the queue, the stored rows unchanged (ITL-1403).""" db = DeltaTableDatabase(base_path=base) stored_type = pa.large_list(pa.struct([("a", pa.int64())])) append(db, rows([b"a"], pa.array([[{"a": 1}]], stored_type))) evolved = pa.large_list(pa.struct([("a", pa.int64()), ("b", pa.int64())])) - with pytest.raises(InputValidationError, match="recorded Arrow type"): + with pytest.raises(InputValidationError, match="Delta refused the commit"): append(db, rows([b"b"], pa.array([[{"a": 2, "b": 3}]], evolved))) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] back = DeltaTableDatabase(base_path=base).get_all_records( PATH, record_id_column="rid" diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index a0a40c82c..a2f86940c 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -52,6 +52,19 @@ def _stored_ids(root: Path) -> list[bytes]: return sorted(cast(list[bytes], table.column("rid").to_pylist())) +def _refused_once_at_flush(db: DeltaTableDatabase) -> InputValidationError: + """The flush is the point of truth (ITL-1403): the rows were accepted when added; + Delta refuses the commit, and the flush raises once, naming the table, Delta's + reason and the rows not written; nothing stays queued; a second flush is a no-op.""" + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + with pytest.raises(InputValidationError, match="Delta refused the commit") as info: + db.flush() + assert "were not written and are no longer queued" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op + return info.value + + def _struct(name: str, value: int) -> Any: return pa.array([{name: value}]) @@ -115,14 +128,16 @@ def _list_of_structs(make_list: Any, *names: str) -> Any: @pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) -def test_a_recorded_column_whose_record_would_change(tmp_path: Path, case: str) -> None: - """Review of PR 504, findings 2 and 6: what the commit would send is compared.""" +def test_a_recorded_column_whose_record_changes_is_refused_once_at_flush( + tmp_path: Path, case: str +) -> None: + """Review of PR 504, findings 2 and 6: Delta refuses the changed record; the flush + raises once and the batch leaves the queue.""" stored, appended = RECORD_CHANGES[case] db = DeltaTableDatabase(tmp_path) _add(db, _rows(b"1", x=stored), flush=True) - with pytest.raises(InputValidationError, match="recorded Arrow type"): - _add(db, _rows(b"2", x=appended)) - db.flush() # nothing was queued + _add(db, _rows(b"2", x=appended)) # accepted when added + _refused_once_at_flush(db) assert _stored_ids(tmp_path) == [b"1"] @@ -285,7 +300,8 @@ def test_names_folded_alike_only_by_delta_are_refused_once( def test_a_storage_typed_column_carrying_another_extension_name(tmp_path: Path) -> None: """A logical identity given as ``ARROW:extension:*`` field metadata on a storage - type is compared as an extension type's is: another name is refused when added.""" + type (CodeRabbit on PR 504): Delta refuses another name at the commit; the flush + raises once and the batch leaves the queue.""" def rows(rid: bytes, name: str) -> pa.Table: field = pa.field( @@ -300,9 +316,8 @@ def rows(rid: bytes, name: str) -> pa.Table: db = DeltaTableDatabase(tmp_path) _add(db, rows(b"1", "itl1403.one"), flush=True) - with pytest.raises(InputValidationError, match="'itl1403.two'"): - _add(db, rows(b"2", "itl1403.two")) - assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + _add(db, rows(b"2", "itl1403.two")) # accepted when added + assert "ARROW:extension:name" in str(_refused_once_at_flush(db)) assert _stored_ids(tmp_path) == [b"1"] @@ -369,7 +384,7 @@ def add_newline(metadata: dict[str, Any]) -> None: "evolution", [False, True], ids=["evolution off", "evolution on"] ) @pytest.mark.parametrize("route", sorted(ROUTES)) -def test_a_real_record_change_is_refused_only_where_the_commit_sends_it( +def test_a_real_record_change_is_refused_at_flush_only_where_delta_refuses_it( tmp_path: Path, route: str, evolution: bool ) -> None: """N2: list items widening to nullable (non-null values). A MERGE that evolves the @@ -387,21 +402,14 @@ def test_a_real_record_change_is_refused_only_where_the_commit_sends_it( } ) - def add() -> None: - db.add_records( - PATH, - rows, - record_id_column="rid", - skip_duplicates=len(ids) == 1, - flush=True, - ) - + db.add_records( + PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + ) # accepted when added, on every route if evolution: - with pytest.raises(InputValidationError, match="recorded Arrow type"): - add() + _refused_once_at_flush(db) assert _stored_ids(tmp_path) == [b"1"] else: - add() + db.flush() assert _stored_ids(tmp_path) == [b"1", b"2"] assert not db._pending_batches # pyright: ignore[reportPrivateUsage] @@ -452,22 +460,16 @@ def test_a_null_column_is_checked_like_any_column( null_field, pa.nulls(len(ids)) ) - def add() -> None: - db.add_records( - PATH, - rows, - record_id_column="rid", - skip_duplicates=len(ids) == 1, - flush=True, - ) - - sends = evolution or len(ids) == 1 - if variant == "another name" and sends: - with pytest.raises(InputValidationError, match="itl1403.not.a.path"): - add() + db.add_records( + PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + ) # accepted when added: the flush is the point of truth + # Delta sends another type's identifier, and refuses it, on an append (every id + # new) and on a MERGE that evolves the schema. + if variant == "another name" and (evolution or len(ids) == 1): + _refused_once_at_flush(db) assert _stored_ids(tmp_path) == [b"1"] else: - add() + db.flush() back = DeltaTableDatabase(tmp_path).get_all_records( PATH, record_id_column="rid" ) @@ -516,3 +518,91 @@ def test_the_backstop_names_the_column_whole(tmp_path: Path, suffix: str) -> Non ) assert info.value.column in (first, second) assert "int64" in str(info.value) + + +# ── Third review of PR 504: the flush is the point of truth ──────────────────────── + + +@pytest.mark.parametrize( + "evolution", [False, True], ids=["evolution off", "evolution on"] +) +def test_a_null_with_a_foreign_identifier_after_a_queued_bare_null_is_stored( + tmp_path: Path, evolution: bool +) -> None: + """Third review: the batch the flush commits is what counts. A bare null queued, + then a null carrying a foreign identifier: the concatenated batch keeps the first + field's metadata, so Delta stores all rows; nothing is refused when added.""" + field, column, _ = _path_column() + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolution) + _add(db, _rows(b"1").append_column(field, column), flush=True) + _add(db, _rows(b"2").append_column(pa.field("x", pa.null()), pa.nulls(1))) + foreign = pa.field( + "x", + pa.null(), + metadata={ + "ARROW:extension:name": "review.different", + "ARROW:extension:metadata": b"", + }, + ) + _add(db, _rows(b"3").append_column(foreign, pa.nulls(1))) + db.flush() + back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert back is not None + assert back.schema.field("x").type == field.type + assert back.sort_by("rid").column("x").to_pylist() == ["/a", None, None] + + +def test_the_backstop_names_the_nested_field_beside_a_column_of_the_same_name( + tmp_path: Path, +) -> None: + """Third review: Delta's own schema check locates the collision, so the field named + is the nested one, with its type, not a top-level column of the same name.""" + upper, lower = RUST_ONLY_FOLDS[0] + db = DeltaTableDatabase(tmp_path) + for rid, name in ((b"1", upper), (b"2", lower)): + table = pa.table( + { + "rid": pa.array([rid], pa.large_binary()), + lower: [1], + "s": pa.array([{name: "value"}], pa.struct([(name, pa.string())])), + } + ) + db.add_records(PATH, table, record_id_column="rid", schema_handling="merge") + with pytest.raises(UnstorableColumnError) as info: + db.flush() + assert info.value.column == f"s.{lower}" + assert "string" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize( + "change", ["another writer deletes a stored row", "schema evolution turned on"] +) +def test_what_changes_between_add_and_flush_is_decided_at_the_flush( + tmp_path: Path, change: str +) -> None: + """Third review: the commit route can change after the rows are added. Nulls + carrying another logical name, with a stored id among them and schema evolution off, + are a MERGE that keeps the stored schema; when another writer deletes the stored row, + or schema evolution is turned on, the commit sends the foreign identifier and Delta + refuses it. The flush raises once; nothing stays queued.""" + field, column, _ = _path_column() + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=False) + _add(db, _rows(b"1").append_column(field, column), flush=True) + foreign = pa.field( + "x", + pa.null(), + metadata={ + "ARROW:extension:name": "review.different", + "ARROW:extension:metadata": b"", + }, + ) + rows = pa.table({"rid": pa.array([b"1", b"2"], pa.large_binary())}).append_column( + foreign, pa.nulls(2) + ) + db.add_records(PATH, rows, record_id_column="rid") # accepted when added + if change == "another writer deletes a stored row": + deltalake.DeltaTable(str(tmp_path / "t")).delete("__record_id = X'31'") + else: + db.allow_schema_evolution = True + _refused_once_at_flush(db) diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index f5cbe037b..210fbdc06 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -8,8 +8,9 @@ never swapped, never dropped. An append that would CHANGE a recorded column's record (a field added to a recorded -struct) is refused before anything is buffered: deltalake 1.5 and later refuses a commit -that changes a column's field metadata, and the record is field metadata (ITL-1403). A +struct) is refused by Delta at the commit: deltalake 1.5 and later refuses a commit that +changes a column's field metadata, and the record is field metadata. The flush raises it +once and the batch leaves the queue (ITL-1403: the flush is the point of truth). A struct with no record still gains fields, and a new column is still added. A ``null``-typed part with nothing stored at its path (a new struct field, the items of a @@ -157,9 +158,12 @@ def test_an_evolved_struct_keeps_every_value_under_its_name( @pytest.mark.parametrize("flush", [True, False], ids=["flushed", "queued"]) @pytest.mark.parametrize("case", sorted(RECORD_CHANGES)) -def test_an_append_changing_a_recorded_type_is_refused_before_buffering( +def test_an_append_changing_a_recorded_type_is_refused_once_at_flush( tmp_path: pathlib.Path, case: str, flush: bool ) -> None: + """Accepted when added; Delta refuses the changed record at the commit; the flush + raises once, the batch leaves the queue, and a second flush is a no-op (ITL-1403: + the flush is the point of truth).""" first, first_values, appended, appended_values = RECORD_CHANGES[case] db = DeltaTableDatabase(tmp_path) db.add_records( @@ -168,17 +172,16 @@ def test_an_append_changing_a_recorded_type_is_refused_before_buffering( record_id_column="id", flush=True, ) - with pytest.raises( - InputValidationError, - match=r"column 'x': the append would change the column's recorded Arrow type", - ): + with pytest.raises(InputValidationError, match="Delta refused the commit"): db.add_records( PATH, _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)), record_id_column="id", flush=flush, ) - db.flush() # nothing was queued + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") assert back is not None assert back.column("id").to_pylist() == [b"1"] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 041417959..c62f11e09 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1054,15 +1054,23 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. A column whose Arrow type Delta keeps -through a recorded type (the "(recorded type)" cells below, every list and map -included) cannot gain a field, nor have a nested nullability change: the record is the -column's field metadata, which Delta (deltalake 1.5 and later) does not let a commit -change, so such an append is refused, naming the column, before anything is queued. A -struct column without a record still gains fields, an append may still add a new column, -and an untyped `null` column takes the stored type. Another logical type over a stored -logical column (another extension name, or the same name with other extension metadata) -is refused the same way. +as nullable afterwards, as Delta stores it. + +On Delta, the commit is the point of truth. When rows are added, only what is certain is +refused, before anything is queued: two names differing only in case, a stored table +deltalake cannot read, another logical type (another +extension name or other extension metadata) over a stored logical column, and a struct +evolution that would put two names differing only in case into one struct. What +deltalake refuses at the commit for the rows themselves (a changed field metadata, a type +it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, +naming the table, Delta's reason and the rows not written; those rows leave the queue, +and the other tables of the flush still commit. Any other failure keeps its rows queued. +So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" +cells below, every list and map included) cannot gain a field when schema evolution is +on, nor have a nested nullability change: the record is the column's field metadata, +which deltalake 1.5 and later does not let a commit change. A struct column without a +record still gains fields, an append may still add a new column, and an untyped `null` +column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/tests/test_pipeline/test_delta_refusals_in_jobs.py b/tests/test_pipeline/test_delta_refusals_in_jobs.py index b98c8b886..6387cb5bb 100644 --- a/tests/test_pipeline/test_delta_refusals_in_jobs.py +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -4,8 +4,9 @@ - finding 6: an operator whose result TYPE depends on its data (list items nullable only when a value exceeds 10) in an operator node that logs (``CacheMode.LOG``): the run - whose result type differs from the stored one fails at the store, instead of - silently changing the table's recorded type. Such an operator is a bug of the + whose result type differs from the stored one fails at the store, where Delta + refuses the commit (the flush raises it once), instead of silently changing the + table's recorded type. Such an operator is a bug of the operator; ITL-1410 is to refuse it at the operator. - a function with output keys ``a`` and ``A`` (legal before) stops at its first write: Delta column names are case-insensitive. @@ -27,7 +28,11 @@ from orcapod.core.sources import ArrowTableSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase -from orcapod.errors import OrcapodDatabaseWriteError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseWriteError, + UnstorableColumnError, +) from orcapod.types import CacheMode @@ -89,9 +94,13 @@ def run(keys: list[int], values: list[int]) -> None: run([1, 2], [1, 2]) # items non-nullable: stored with pytest.raises(OrcapodDatabaseWriteError) as info: run([3, 4], [11, 12]) # items nullable: the recorded type would change - assert "recorded Arrow type" in str( - info.value.__cause__ - ) or "recorded Arrow type" in str(info.value) + # The flush is the point of truth (ITL-1403): Delta refuses the commit, and the + # flush raises it once, as the write error's cause; nothing stays queued. + cause = info.value.__cause__ + assert isinstance(cause, InputValidationError), repr(cause) + assert "Delta refused the commit" in str(cause) + with pytest.raises(OrcapodDatabaseWriteError): + run([3, 4], [11, 12]) # the same rows fail the same way again, never queued @function_pod(output_keys=["a", "A"]) From fef80e1f1ebe2668f6b54ce8484b94c565b40fdf Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:36:56 -0800 Subject: [PATCH 07/12] fix(databases): round-four review of PR 504 (ITL-1403) 2. A duplicate-name refusal is only deltalake's own error, matched where its message starts: a storage error whose path holds the words keeps its rows. 3. A name differing only in case from a stored column is refused only when schema evolution is on; without it Delta leaves the unknown column out. 7. The duplicate backstop locates the colliding struct by its direct children. 1, 5 (pinned) and 4, 6 (documentation): a failed CHECK constraint is taken as permanent; deltalake 1.6 refuses a null in a non-nullable nested field (a narrowing); only the listed refusals are raised once, everything else keeps its rows queued; the add-time unreadable-table refusal is the case-name one. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 23 +++-- docs/reference/database-types.md | 38 ++++--- docs/troubleshooting.md | 21 ++-- src/orcapod/databases/delta_lake_databases.py | 99 ++++++++++++------- .../test_delta_add_time_property.py | 25 +++++ .../test_delta_commit_failures.py | 91 +++++++++++++++++ .../test_delta_refused_before_queueing.py | 27 +++++ tests/test_databases/type_matrix.py | 38 ++++--- 8 files changed, 281 insertions(+), 81 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index fb9d91d2f..69c16555c 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -20,7 +20,8 @@ - `DeltaTableDatabase` refuses two columns, or two fields of one struct, whose names differ only in case (`a` and `A`), before anything is queued (`UnstorableColumnError`, or `InputValidationError` for a column or field added beside a - stored or queued one). Delta column names are case-insensitive, and deltalake 1.5.1 + queued one, or beside a stored one when schema evolution is on: without evolution Delta + leaves an unknown column out, as before). Delta column names are case-insensitive, and deltalake 1.5.1 and later refuses such a table. So a function job with output keys `a` and `A` now stops at its first write, on the sync and the async path alike. Delta folds case as Rust's `to_lowercase` does: for the few code points where Python's `str.lower` differs, @@ -28,19 +29,25 @@ the queue. The in-memory and connector databases still hold such names as two columns. - On Delta the commit is the point of truth. When rows are added, `DeltaTableDatabase` refuses only what it can tell for certain: names differing only in case (above), a - stored table deltalake cannot read, another logical type + stored table deltalake cannot read because two of its names differ only in case, + another logical type (another extension name, or the same name with other extension metadata) over a stored logical column, and a struct evolution that would put two names differing only in case into one struct. Telling more rules up front is ITL-1418. -- What deltalake refuses at the commit for the rows themselves is raised by the flush - once, as `InputValidationError` ("Delta refused the commit to table ...") naming the +- Four kinds of refusal by deltalake at the commit are raised by the flush once, as + `InputValidationError` ("Delta refused the commit to table ...") naming the table, Delta's reason and the number of rows not written. Those rows leave the queue, the other tables of the same flush still commit, and a second flush does nothing. A job fails with `OrcapodDatabaseWriteError` and that cause. The permanent refusals are `SchemaMismatchError`, the duplicate-name error, and a `DeltaError` whose message starts with one of `PERMANENT_DELTA_ERROR_PREFIXES` (`type_coercion`, `Invalid data found`, - `Unsupported CAST`). Any other failure keeps its rows queued as before, so nothing is - dropped on a guess. Until ITL-1412, a job whose result batch is dropped this way can + `Unsupported CAST`): a changed field metadata, two names equal under Delta's case + folding, a type DataFusion cannot insert or cast, and a row Delta finds invalid (a null + in a non-nullable column, a failed CHECK constraint; a constraint whose verdict changes + by chance would have accepted the rows later, and Orcapod writes none). Any other + failure keeps its rows queued as before, so nothing is dropped on a guess: a storage + error, a constraint whose evaluation itself fails, a table unreadable for another + reason. Until ITL-1412, a job whose result batch is dropped this way can keep pipeline records naming those results. - This narrows what a Delta table takes from deltalake 1.5 on: a stored column's field metadata cannot change in a commit. So a column whose Arrow type is recorded cannot @@ -49,6 +56,10 @@ integer, a non-microsecond time type, `float16` or a fixed-size type. A struct column without a record still gains fields, a field may be omitted or reordered, a new column may be added, and an untyped `null` column takes the stored type. +- deltalake 1.6 also refuses, with schema evolution on, a null in a struct field stored + non-nullable, also in a struct without a record: 1.0.2 stored it and made the field + nullable. An append that makes such a field nullable while holding no null in it is + still stored, and the field reads as nullable afterwards. - Tables Orcapod's own nodes write are not concerned: their column types are fixed by their inputs' schemas, and a changed column type changes the table's path. The one exception is an operator whose result type depends on its data rather than on its diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 983ecb2c4..477568fd5 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -79,23 +79,31 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a +null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit +(1.0.2 stored it and made the field nullable). On Delta, the commit is the point of truth. When rows are added, only what is certain is -refused, before anything is queued: two names differing only in case, a stored table -deltalake cannot read, another logical type (another -extension name or other extension metadata) over a stored logical column, and a struct -evolution that would put two names differing only in case into one struct. What -deltalake refuses at the commit for the rows themselves (a changed field metadata, a type -it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, -naming the table, Delta's reason and the rows not written; those rows leave the queue, -and the other tables of the flush still commit. Any other failure keeps its rows queued. -So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" -cells below, every list and map included) cannot gain a field when schema evolution is -on, nor have a nested nullability change: the record is the column's field metadata, -which deltalake 1.5 and later does not let a commit change. A struct column without a -record still gains fields, an append may still add a new column, and an untyped `null` -column takes the stored type. +refused, before anything is queued: two names differing only in case (a name differing +only in case from a stored column only when schema evolution is on, the only case in +which it would enter the stored schema), a stored table deltalake cannot read because two +of its names differ only in case, another logical type (another extension name or other +extension metadata) over a stored logical column, and a struct evolution that would put +two names differing only in case into one struct. Four kinds of refusal by deltalake at +the commit are raised by the flush once, naming the table, Delta's reason and the rows +not written, and those rows leave the queue (the other tables of the flush still commit): +a changed field metadata (`SchemaMismatchError`), two names equal under Delta's case +folding, a type DataFusion cannot insert or cast into the stored one, and a row Delta +finds invalid (a null in a non-nullable column, a failed CHECK constraint). A CHECK +constraint whose verdict changes by chance would accept such rows on a later try; +Orcapod writes none. Any other failure keeps its rows queued and is raised again by the +next flush, as before: a storage error, a constraint whose evaluation itself fails, a +stored table unreadable for another reason. So a column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map included) +cannot gain a field when schema evolution is on, nor have a nested nullability change: +the record is the column's field metadata, which deltalake 1.5 and later does not let a +commit change. A struct column without a record still gains fields, an append may still +add a new column, and an untyped `null` column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index e2dcebf95..893a59e9f 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -214,15 +214,18 @@ saying that Delta reports a name as equal to another's under its case folding is kind of failure. **Cause.** A `DeltaTableDatabase` refuses only what it can tell for certain when rows are -added (names that differ only in case, a stored table deltalake cannot read, another logical type over a stored logical column). Everything -else is decided by deltalake when it commits. The refusals that would happen again at -every flush are raised once: a changed field metadata, which deltalake 1.5 and later -refuses (a struct with a recorded type gaining a field, a list's items becoming -nullable), a type DataFusion cannot insert or cast into the stored one, or a null in a -non-nullable column. The rows are dropped from the queue so that the next flush is not -refused the same way; other tables of the same flush still commit. A failure that may -pass, such as a storage error, keeps its rows queued, and the next flush tries them -again. +added (names that differ only in case, a stored table deltalake cannot read because two of +its names differ only in case, another logical type over a stored logical column). +Everything else is decided by deltalake when it commits. Four kinds of refusal are raised +once, because every later flush would be refused the same way: a changed field metadata, +which deltalake 1.5 and later refuses (a struct with a recorded type gaining a field, a +list's items becoming nullable); two names equal under Delta's case folding; a type +DataFusion cannot insert or cast into the stored one; and a row Delta finds invalid (a +null in a non-nullable column, a failed CHECK constraint). The rows are dropped from the +queue so that the next flush is not refused the same way; other tables of the same flush +still commit. Any other failure keeps its rows queued, and the next flush tries them +again, as before: a storage error, a constraint whose evaluation itself fails, a stored +table unreadable for another reason. **Fix.** Read Delta's reason, correct the rows (or their declared types) and add them again. In a job, running it again computes the same rows and fails the same way until diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index cf36ad012..56e209b59 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -612,13 +612,31 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: # delta-rs reports two names equal under its case folding (Rust ``to_lowercase``). -_DUPLICATE_NAME = re.compile(r"Duplicate field name \(case-insensitive\): '([^']*)'") +# Delta's duplicate-name refusal, as deltalake 1.6.6 words it: at the START of the +# message of deltalake's own error (a bare ``Exception`` or a ``DeltaError``), after +# its ``External error:`` / ``Kernel error:`` / ``Generic DeltaTable error:`` wrappers. +# Never matched inside other text: a table's path may contain the same words +# (review of PR 504, round four). +_DUPLICATE_NAME = re.compile( + r"^(?:(?:External|Kernel|Generic DeltaTable) error: )*" + r"Schema error: Duplicate field name \(case-insensitive\): '(.*)'" +) + + +def _is_delta_error(error: BaseException) -> bool: + """Whether ``error`` is one deltalake raised: a ``DeltaError``, or the bare + ``Exception`` its schema conversion raises.""" + from deltalake.exceptions import DeltaError + + return type(error) is Exception or isinstance(error, DeltaError) def _duplicate_name_in(error: BaseException) -> str | None: """The name delta-rs reports as a case-insensitive duplicate in ``error``'s chain.""" for seen in _error_chain(error): - match = _DUPLICATE_NAME.search(str(seen)) + if not _is_delta_error(seen): + continue + match = _DUPLICATE_NAME.match(str(seen)) if match is not None: return match.group(1) return None @@ -670,7 +688,7 @@ def _permanent_commit_failure(error: BaseException) -> bool: return False if isinstance(error, SchemaMismatchError): return True - if type(error) is Exception and _DUPLICATE_NAME.search(str(error)): + if type(error) is Exception and _DUPLICATE_NAME.match(str(error)): return True if isinstance(error, DeltaError): return str(error).startswith(PERMANENT_DELTA_ERROR_PREFIXES) @@ -680,53 +698,52 @@ def _permanent_commit_failure(error: BaseException) -> bool: def _reported_field(error: BaseException, schema: pa.Schema) -> tuple[str, Any]: """The field of ``schema`` delta-rs names as a duplicate in ``error``'s chain. - Delta's own schema check locates it: a column whose schema Delta refuses on its own - holds the colliding struct fields, and the field is named by its path in that - column (``s.ᲊ``) with its type; otherwise the collision is between top-level - columns. Names come from the schema, the longest one Delta's message quotes, so a - name holding a quote is named whole. ``(the reported text, null)`` when no field - matches. + Delta's own schema check locates it: each struct of the schema (the top level + included) is checked on its direct children alone, each child standing in as an + ``int64``, so a collision deeper down is not seen there. The struct Delta refuses + holds the pair, and the field is named by its path (``outer.right.ᲊ``) with its + type. Names come from the schema, the longest one Delta's message quotes, so a + name holding a quote is named whole. ``(the reported text, null)`` when no struct + is refused. """ messages = [str(seen) for seen in _error_chain(error)] def quoted(field: "pa.Field[Any]") -> bool: return any(f"(case-insensitive): '{field.name}'" in m for m in messages) - for column in schema: + for prefix, children in _structs_of(schema): + probe = pa.schema([pa.field(c.name, pa.int64()) for c in children]) try: - deltalake.Schema.from_arrow(pa.schema([column])) + deltalake.Schema.from_arrow(probe) except Exception as refused: # noqa: BLE001 # only a duplicate name is looked at if _duplicate_name_in(refused) is None: continue - nested = [ - (path, field) - for path, field in _field_paths(column) - if path != column.name and quoted(field) - ] - if nested: - path, field = max(nested, key=lambda item: len(item[1].name)) - return path, field.type - top = [field for field in schema if quoted(field)] - if top: - field = max(top, key=lambda f: len(f.name)) - return field.name, field.type + named = [c for c in children if quoted(c)] + if named: + field = max(named, key=lambda c: len(c.name)) + return prefix + field.name, field.type return _duplicate_name_in(error) or "", pa.null() -def _field_paths(column: "pa.Field[Any]") -> list[tuple[str, "pa.Field[Any]"]]: - """``column`` and every struct field inside it, each with its dotted path.""" - found: list[tuple[str, pa.Field[Any]]] = [] +def _structs_of(schema: pa.Schema) -> list[tuple[str, list["pa.Field[Any]"]]]: + """``(path prefix, direct children)`` of the top level and of every struct inside, + through lists, maps and logical types.""" + found: list[tuple[str, list[pa.Field[Any]]]] = [("", list(schema))] - def visit(path: str, field: "pa.Field[Any]") -> None: - found.append((path, field)) - arrow_type = field.type + def visit(prefix: str, arrow_type: pa.DataType) -> None: if isinstance(arrow_type, pa.ExtensionType): arrow_type = arrow_type.storage_type + if pa.types.is_struct(arrow_type): + children = [arrow_type.field(i) for i in range(arrow_type.num_fields)] + found.append((prefix, children)) + for child in children: + visit(f"{prefix}{child.name}.", child.type) + return for i in range(arrow_type.num_fields): - child = arrow_type.field(i) - visit(f"{path}.{child.name}", child) + visit(prefix, arrow_type.field(i).type) - visit(column.name, column) + for field in schema: + visit(f"{field.name}.", field.type) return found @@ -951,7 +968,7 @@ def _exact_refusal( def _append_refusal( - delta_table: deltalake.DeltaTable, rows: pa.Table + delta_table: deltalake.DeltaTable, rows: pa.Table, schema_evolution: bool ) -> tuple[str, str] | None: """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). @@ -969,6 +986,9 @@ def _append_refusal( Args: delta_table: The loaded stored table. rows: The rows to append, with their own types. + schema_evolution: Whether the database's MERGE evolves the stored schema: + only then does a new column name enter it, so only then is a name + differing only in case from a stored one refused. Returns: ``(column, reason)``, or ``None`` when the rows can be appended. @@ -979,7 +999,10 @@ def _append_refusal( change = _column_change(held[field.name], field) if change is not None: return field.name, change - else: + elif schema_evolution: + # A new name enters the stored schema only when the MERGE evolves it; + # without evolution Delta leaves an unknown column out, as main did + # (review of PR 504, round four). clash = _differ_only_in_case([*held, field.name]) if clash is not None: return field.name, _case_reason(*clash) @@ -2095,7 +2118,9 @@ def _refuse_unmergeable_append( ) from unreadable delta_table = None if delta_table is not None: - refusal = _append_refusal(delta_table, records) + refusal = _append_refusal( + delta_table, records, self.allow_schema_evolution + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -3058,7 +3083,9 @@ def _flush_by_key(self, record_key: str) -> None: else: # The add-time check, against the version just loaded: another # writer may have committed since the rows were buffered (ITL-1334). - refusal = _append_refusal(delta_table, original_table) + refusal = _append_refusal( + delta_table, original_table, self.allow_schema_evolution + ) if refusal is not None: column, reason = refusal raise InputValidationError( diff --git a/tests/test_databases/test_delta_add_time_property.py b/tests/test_databases/test_delta_add_time_property.py index 37d513f98..65ddf84cd 100644 --- a/tests/test_databases/test_delta_add_time_property.py +++ b/tests/test_databases/test_delta_add_time_property.py @@ -183,3 +183,28 @@ def test_the_sweep_covers_every_kind() -> None: assert kinds == {"same", "record", "evolution", "null/layout", "path", "logical"} assert len(VARIANTS) > 100 _ = product # the sweep is the product of the three parameters above + + +@pytest.mark.parametrize("evolve", [False, True], ids=["evolution off", "evolution on"]) +def test_a_name_differing_in_case_from_a_stored_column( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, evolve: bool +) -> None: + """Review of PR 504, round four, finding 3: ``A`` beside a stored ``a``. Without + schema evolution Delta's MERGE leaves the unknown column out and stores the row (as + main did): nothing is refused. With evolution the name would enter the stored + schema, which Delta refuses: refused when added, and Delta refuses it too.""" + initial = pa.table( + {"rid": pa.array([b"1"], pa.large_binary()), "anchor": [1], "a": [11]} + ) + incoming = pa.table( + {"rid": pa.array([b"2"], pa.large_binary()), "anchor": [2], "A": [22]} + ) + live, queued = _run(tmp_path / "live", initial, incoming, evolve) + assert not queued + if not evolve: + assert live == "stored" + return + assert live == "refused when added" + monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) + raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw != "stored" diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index 25a15d368..cd8216543 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -184,3 +184,94 @@ def test_a_type_coercion_refusal_is_raised_once_through_orcapod(tmp_path: Path) assert "1 rows queued for it were not written" in str(info.value) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() # a no-op + + +# ── Review of PR 504, round four ──────────────────────────────────────────────────── + + +def test_a_check_constraint_refusal_is_permanent(tmp_path: Path) -> None: + """Finding 1, the stated limit: deltalake reports a failed CHECK constraint as + ``Invalid data found``, which is taken as permanent: the rows are raised once and + leave the queue. A constraint whose verdict changes by chance (``random()``) would + have accepted them on a later try; Orcapod writes no CHECK constraint, and the error + says the rows were not written.""" + db = DeltaTableDatabase(tmp_path) + rows = lambda rid, x: pa.table( # noqa: E731 + {"rid": pa.array([rid], pa.large_binary()), "x": pa.array([x], pa.int64())} + ) + db.add_records(PATH, rows(b"1", 1), record_id_column="rid", flush=True) + deltalake.DeltaTable(str(tmp_path / "t")).alter.add_constraint( + {"positive": "x > 0"} + ) + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, rows(b"2", 0), record_id_column="rid") + with pytest.raises(InputValidationError, match="Invalid data found"): + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="permissions") +def test_a_storage_failure_whose_path_names_a_duplicate_is_not_dropped( + tmp_path: Path, +) -> None: + """Finding 2: only deltalake's own duplicate-name error counts, by where its message + starts. A permission error whose PATH holds the same words keeps its rows queued, + and a later flush, once the store is writable, commits them.""" + parent = tmp_path / "parent" + parent.mkdir() + path = ("parent", "Duplicate field name (case-insensitive): 'x'") + db = DeltaTableDatabase(tmp_path) + rows = pa.table({"rid": pa.array([b"1"], pa.large_binary()), "x": [11]}) + db.add_records(path, rows, record_id_column="rid") + parent.chmod(0o500) + try: + with pytest.raises(Exception) as info: # noqa: B017 # main's error, unchanged + db.flush() + assert not isinstance(info.value, InputValidationError) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + finally: + parent.chmod(0o700) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(path, record_id_column="rid") + assert stored is not None + assert stored.column("x").to_pylist() == [11] + + +@pytest.mark.parametrize("seen", [False, True], ids=["every id new", "a stored id"]) +def test_an_unrecorded_struct_child_loosened_to_nullable_is_refused_once( + tmp_path: Path, seen: bool +) -> None: + """Finding 5, a narrowing of deltalake 1.6: with schema evolution on, a null in a + struct child stored non-nullable (an unrecorded struct) is refused by Delta at the + commit (``Invalid data found``); deltalake 1.0.2 stored it and made the child + nullable. Raised once; nothing stays queued.""" + strict = pa.struct([pa.field("a", pa.int64(), nullable=False)]) + loose = pa.struct([pa.field("a", pa.int64())]) + db = DeltaTableDatabase(tmp_path) + db.add_records( + PATH, + pa.table( + { + "rid": pa.array([b"1"], pa.large_binary()), + "s": pa.array([{"a": 1}], strict), + } + ), + record_id_column="rid", + flush=True, + ) + ids = [b"1", b"2"] if seen else [b"2"] + db.add_records( + PATH, + pa.table( + { + "rid": pa.array(ids, pa.large_binary()), + "s": pa.array([{"a": None}] * len(ids), loose), + } + ), + record_id_column="rid", + ) + with pytest.raises(InputValidationError, match="Invalid data found"): + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() # a no-op diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index a2f86940c..bcb5b9cca 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -606,3 +606,30 @@ def test_what_changes_between_add_and_flush_is_decided_at_the_flush( else: db.allow_schema_evolution = True _refused_once_at_flush(db) + + +def test_the_backstop_names_the_struct_that_holds_the_pair(tmp_path: Path) -> None: + """Review of PR 504, round four, finding 7: two structs under one column, the + colliding pair in ``outer.right`` and an unrelated field of the same name in + ``outer.left``: the field named is the one in the struct Delta refuses.""" + upper, lower = RUST_ONLY_FOLDS[0] + db = DeltaTableDatabase(tmp_path) + for rid, name in ((b"1", upper), (b"2", lower)): + outer = pa.struct( + [ + ("left", pa.struct([(lower, pa.int64())])), + ("right", pa.struct([(name, pa.string())])), + ] + ) + table = pa.table( + { + "rid": pa.array([rid], pa.large_binary()), + "outer": pa.array([{"left": {lower: 1}, "right": {name: "v"}}], outer), + } + ) + db.add_records(PATH, table, record_id_column="rid", schema_handling="merge") + with pytest.raises(UnstorableColumnError) as info: + db.flush() + assert info.value.column == f"outer.right.{lower}" + assert "string" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index c62f11e09..7bb37f072 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1054,23 +1054,31 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it. +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a +null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit +(1.0.2 stored it and made the field nullable). On Delta, the commit is the point of truth. When rows are added, only what is certain is -refused, before anything is queued: two names differing only in case, a stored table -deltalake cannot read, another logical type (another -extension name or other extension metadata) over a stored logical column, and a struct -evolution that would put two names differing only in case into one struct. What -deltalake refuses at the commit for the rows themselves (a changed field metadata, a type -it cannot insert or cast, a null in a non-nullable column) is raised by the flush, once, -naming the table, Delta's reason and the rows not written; those rows leave the queue, -and the other tables of the flush still commit. Any other failure keeps its rows queued. -So a column whose Arrow type Delta keeps through a recorded type (the "(recorded type)" -cells below, every list and map included) cannot gain a field when schema evolution is -on, nor have a nested nullability change: the record is the column's field metadata, -which deltalake 1.5 and later does not let a commit change. A struct column without a -record still gains fields, an append may still add a new column, and an untyped `null` -column takes the stored type. +refused, before anything is queued: two names differing only in case (a name differing +only in case from a stored column only when schema evolution is on, the only case in +which it would enter the stored schema), a stored table deltalake cannot read because two +of its names differ only in case, another logical type (another extension name or other +extension metadata) over a stored logical column, and a struct evolution that would put +two names differing only in case into one struct. Four kinds of refusal by deltalake at +the commit are raised by the flush once, naming the table, Delta's reason and the rows +not written, and those rows leave the queue (the other tables of the flush still commit): +a changed field metadata (`SchemaMismatchError`), two names equal under Delta's case +folding, a type DataFusion cannot insert or cast into the stored one, and a row Delta +finds invalid (a null in a non-nullable column, a failed CHECK constraint). A CHECK +constraint whose verdict changes by chance would accept such rows on a later try; +Orcapod writes none. Any other failure keeps its rows queued and is raised again by the +next flush, as before: a storage error, a constraint whose evaluation itself fails, a +stored table unreadable for another reason. So a column whose Arrow type Delta keeps +through a recorded type (the "(recorded type)" cells below, every list and map included) +cannot gain a field when schema evolution is on, nor have a nested nullability change: +the record is the column's field metadata, which deltalake 1.5 and later does not let a +commit change. A struct column without a record still gains fields, an append may still +add a new column, and an untyped `null` column takes the stored type. An append matches columns by name, exactly as Arrow matches them (`a` and `A` are two columns), never by position. Delta alone refuses two columns, or two fields of one From 40df27894ff7d4702a0f24480d936becdb5cdf4f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:55:41 -0800 Subject: [PATCH 08/12] fix(databases): round-five review of PR 504 (ITL-1403) 1. A failed commit is classified on its own error and explicit causes only, never the caller's ambient __context__. 2. The duplicate-name pattern spans a newline in a name (still anchored). 3. A pair formed with a stored column names the batch's column and its type. 4. The troubleshooting page and changelog no longer promise that a CHECK refusal repeats, and name UnstorableColumnError for the duplicate case. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 5 ++- docs/troubleshooting.md | 13 +++--- src/orcapod/databases/delta_lake_databases.py | 18 ++++++--- .../test_delta_commit_failures.py | 40 ++++++++++++++++++- .../test_delta_refused_before_queueing.py | 20 +++++++++- 5 files changed, 81 insertions(+), 15 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index 69c16555c..e854ed960 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -35,8 +35,9 @@ logical column, and a struct evolution that would put two names differing only in case into one struct. Telling more rules up front is ITL-1418. - Four kinds of refusal by deltalake at the commit are raised by the flush once, as - `InputValidationError` ("Delta refused the commit to table ...") naming the - table, Delta's reason and the number of rows not written. Those rows leave the queue, + `InputValidationError` ("Delta refused the commit to table ...") naming the table, + Delta's reason and the number of rows not written, or, for two names equal under + Delta's case folding, as `UnstorableColumnError` naming the column. Those rows leave the queue, the other tables of the same flush still commit, and a second flush does nothing. A job fails with `OrcapodDatabaseWriteError` and that cause. The permanent refusals are `SchemaMismatchError`, the duplicate-name error, and a `DeltaError` whose message starts diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 893a59e9f..b3108ad17 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -216,20 +216,21 @@ kind of failure. **Cause.** A `DeltaTableDatabase` refuses only what it can tell for certain when rows are added (names that differ only in case, a stored table deltalake cannot read because two of its names differ only in case, another logical type over a stored logical column). -Everything else is decided by deltalake when it commits. Four kinds of refusal are raised -once, because every later flush would be refused the same way: a changed field metadata, +Everything else is decided by deltalake when it commits. Four kinds of refusal, which +deltalake makes for the rows themselves, are raised once: a changed field metadata, which deltalake 1.5 and later refuses (a struct with a recorded type gaining a field, a list's items becoming nullable); two names equal under Delta's case folding; a type DataFusion cannot insert or cast into the stored one; and a row Delta finds invalid (a null in a non-nullable column, a failed CHECK constraint). The rows are dropped from the -queue so that the next flush is not refused the same way; other tables of the same flush -still commit. Any other failure keeps its rows queued, and the next flush tries them +queue so that the next flush is not refused for them again; other tables of the same flush +still commit. A CHECK constraint whose verdict changes by chance might have accepted them +later; Orcapod writes no CHECK constraint. Any other failure keeps its rows queued, and the next flush tries them again, as before: a storage error, a constraint whose evaluation itself fails, a stored table unreadable for another reason. **Fix.** Read Delta's reason, correct the rows (or their declared types) and add them -again. In a job, running it again computes the same rows and fails the same way until -then. [Data types per database](reference/database-types.md) lists what each database stores. +again. In a job, running it again computes the same rows and is refused again until +then, except by a CHECK constraint whose verdict changes by chance. [Data types per database](reference/database-types.md) lists what each database stores. ## Problems that give no error diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 56e209b59..e363f9ba0 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -619,7 +619,8 @@ def _case_reason(first: str, second: str, nested: bool = False) -> str: # (review of PR 504, round four). _DUPLICATE_NAME = re.compile( r"^(?:(?:External|Kernel|Generic DeltaTable) error: )*" - r"Schema error: Duplicate field name \(case-insensitive\): '(.*)'" + r"Schema error: Duplicate field name \(case-insensitive\): '(.*)'", + re.DOTALL, # a name may hold a newline ) @@ -643,16 +644,17 @@ def _duplicate_name_in(error: BaseException) -> str | None: def _error_chain(error: BaseException) -> list[BaseException]: - """``error`` and its causes and contexts, each once: a chain may loop. + """``error`` and its explicit causes (``raise ... from``), each once. - It does when an error is raised again inside the handler of an error that wraps - it (a lost commit's retry gives up with the error it lost to; ITL-1377). + Never the implicit ``__context__``: that is whatever the caller was handling when + the commit failed, which says nothing about the commit (review of PR 504, round + five). Each error is taken once, so a chain that loops back ends. """ chain: list[BaseException] = [] seen: BaseException | None = error while seen is not None and all(seen is not e for e in chain): chain.append(seen) - seen = seen.__cause__ or seen.__context__ + seen = seen.__cause__ return chain @@ -722,6 +724,12 @@ def quoted(field: "pa.Field[Any]") -> bool: if named: field = max(named, key=lambda c: len(c.name)) return prefix + field.name, field.type + # No struct of the batch is refused on its own: the pair is a batch column and a + # stored column. Name the batch's column, with its type. + top = [field for field in schema if quoted(field)] + if top: + field = max(top, key=lambda f: len(f.name)) + return field.name, field.type return _duplicate_name_in(error) or "", pa.null() diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index cd8216543..6d1c64d4c 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -23,7 +23,7 @@ from orcapod.databases import DeltaTableDatabase from orcapod.databases import delta_lake_databases as dld -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, UnstorableColumnError PATH = ("t",) @@ -275,3 +275,41 @@ def test_an_unrecorded_struct_child_loosened_to_nullable_is_refused_once( db.flush() assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() # a no-op + + +# ── Review of PR 504, round five ──────────────────────────────────────────────────── + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="permissions") +def test_a_failure_inside_an_unrelated_handler_is_classified_on_its_own( + tmp_path: Path, +) -> None: + """Finding 1: a flush called while the caller handles an unrelated Delta + duplicate-name error fails on a permission error. Only the commit's own error and + its explicit causes are classified, never the ambient context: the valid rows stay + queued, and a later flush commits them.""" + parent = tmp_path / "parent" + parent.mkdir() + path = ("parent", "good") + db = DeltaTableDatabase(tmp_path) + rows = pa.table({"rid": pa.array([b"1"], pa.large_binary()), "x": [11]}) + db.add_records(path, rows, record_id_column="rid") + parent.chmod(0o500) + try: + try: + deltalake.Schema.from_arrow( + pa.schema([("x", pa.int64()), ("X", pa.int64())]) + ) + except Exception: # noqa: BLE001 # the unrelated error being handled + with pytest.raises(Exception) as info: # noqa: B017 # main's error + db.flush() + assert not isinstance( + info.value, (InputValidationError, UnstorableColumnError) + ) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + finally: + parent.chmod(0o700) + db.flush() + stored = DeltaTableDatabase(tmp_path).get_all_records(path, record_id_column="rid") + assert stored is not None + assert stored.column("x").to_pylist() == [11] diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index bcb5b9cca..860f71428 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -506,7 +506,9 @@ def add(name: str, rid: bytes, flush: bool = False) -> None: assert _stored_ids(tmp_path) == [b"pending", b"stored"] -@pytest.mark.parametrize("suffix", ["'q", " space", '"dq', "(x)", "::y"]) +@pytest.mark.parametrize( + "suffix", ["'q", " space", '"dq', "(x)", "::y", "\nsecond line"] +) def test_the_backstop_names_the_column_whole(tmp_path: Path, suffix: str) -> None: """N5: the column named by the flush's case-folding refusal is the batch's own field, with its type, also when its name holds a quote.""" @@ -633,3 +635,19 @@ def test_the_backstop_names_the_struct_that_holds_the_pair(tmp_path: Path) -> No assert info.value.column == f"outer.right.{lower}" assert "string" in str(info.value) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +def test_the_backstop_names_the_column_colliding_with_a_stored_one( + tmp_path: Path, +) -> None: + """Review of PR 504, round five, finding 3: the pair forms at the commit, between a + stored column and the batch's column (Delta's case folding only). The batch's own + column is named, with its type.""" + upper, lower = RUST_ONLY_FOLDS[0] + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", **{upper: pa.array([1])}), flush=True) + with pytest.raises(UnstorableColumnError) as info: + _add(db, _rows(b"2", **{lower: pa.array([2], pa.int32())}), flush=True) + assert info.value.column == lower + assert "int32" in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] From 8ce9ff7a3cc7ba59db93b212bb33616573e37ddb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 23:53:39 -0800 Subject: [PATCH 09/12] docs(databases): a null in a non-nullable struct field is refused; the table stays strict, no migration yet (ITL-1403) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 10 ++++++---- docs/reference/database-types.md | 8 +++++--- tests/test_databases/type_matrix.py | 8 +++++--- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index e854ed960..14e0506b9 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -57,10 +57,12 @@ integer, a non-microsecond time type, `float16` or a fixed-size type. A struct column without a record still gains fields, a field may be omitted or reordered, a new column may be added, and an untyped `null` column takes the stored type. -- deltalake 1.6 also refuses, with schema evolution on, a null in a struct field stored - non-nullable, also in a struct without a record: 1.0.2 stored it and made the field - nullable. An append that makes such a field nullable while holding no null in it is - still stored, and the field reads as nullable afterwards. +- A null in a struct field stored non-nullable, also in a struct without a record, is + refused at the commit (with schema evolution on), and those rows are not written: the + table stays strict to the type it was first declared with. deltalake 1.0.2 stored the + null and made the field nullable. Moving a stored table to a corrected type (a + migration) is not offered yet. An append that makes such a field nullable while + holding no null in it is still stored, and the field reads as nullable afterwards. - Tables Orcapod's own nodes write are not concerned: their column types are fixed by their inputs' schemas, and a changed column type changes the table's path. The one exception is an operator whose result type depends on its data rather than on its diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index e45a43ae3..0468ac5f7 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,9 +81,11 @@ another order): every value keeps its field's name, and an omitted field reads a in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a -null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit -(1.0.2 stored it and made the field nullable). +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it. A +null there, in a field stored non-nullable, is refused at the commit and those rows are +not written: the table stays strict to the type it was first declared with (deltalake +1.6; 1.0.2 stored the null and made the field nullable). Moving a stored table to a +corrected type is not offered yet. On Delta, the commit is the point of truth. When rows are added, only what is certain is refused, before anything is queued: two names differing only in case (a name differing diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 78f25ac03..246876cfa 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1085,9 +1085,11 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: in the appended rows. An append is refused, naming the column and the field, when it would add a non-nullable struct field (the stored rows have no value for it) or add a struct field inside a map (Delta cannot). A nested field the append makes nullable reads -as nullable afterwards, as Delta stores it, when the appended rows hold no null in it; a -null there, in a field stored non-nullable, is refused by deltalake 1.6 at the commit -(1.0.2 stored it and made the field nullable). +as nullable afterwards, as Delta stores it, when the appended rows hold no null in it. A +null there, in a field stored non-nullable, is refused at the commit and those rows are +not written: the table stays strict to the type it was first declared with (deltalake +1.6; 1.0.2 stored the null and made the field nullable). Moving a stored table to a +corrected type is not offered yet. On Delta, the commit is the point of truth. When rows are added, only what is certain is refused, before anything is queued: two names differing only in case (a name differing From 85aa36dbecb4f91fc9c3b461db810b90695cce58 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 09:04:17 -0800 Subject: [PATCH 10/12] fix(databases): a commit conflict or an unloadable table keeps its rows queued; a cached clash is checked again (ITL-1403) Review of PR 504, round seven (CodeRabbit on 8ce9ff7a): - Only an error deltalake raised for the write itself drops a batch for a duplicate name: a CommitFailedError, or a table that cannot be loaded at the flush (OrcapodDatabaseReadError), whose cause names one keeps its rows queued. - A refusal found against a cached handle of the stored table is checked again against the version stored now before the rows are refused. - The flush docstring lists the failures that drop a batch. - Tests: the property sweep reads stored ids back and runs Delta's comparison with every Orcapod check off (only a commit refusal counts); the queued struct-evolution case raises at the flush only; the probe test fails when deltalake accepts the pair; the dropped-result test requires the flush's UnstorableColumnError. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1403.md | 7 +- src/orcapod/databases/delta_lake_databases.py | 95 ++++++++++++---- .../test_delta_add_time_property.py | 99 +++++++++++++---- .../test_delta_commit_failures.py | 102 +++++++++++++++++- .../test_delta_refused_before_queueing.py | 47 ++++++++ .../test_delta_struct_evolution.py | 18 ++-- .../test_dropped_result_batch.py | 14 ++- 7 files changed, 325 insertions(+), 57 deletions(-) diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md index 14e0506b9..597ca4c0e 100644 --- a/changelog.d/ITL-1403.md +++ b/changelog.d/ITL-1403.md @@ -33,7 +33,9 @@ another logical type (another extension name, or the same name with other extension metadata) over a stored logical column, and a struct evolution that would put two names differing only in case - into one struct. Telling more rules up front is ITL-1418. + into one struct. A refusal found against a version of the table this database had + cached is checked again against the version stored now, so a name another writer has + since removed does not refuse the rows. Telling more rules up front is ITL-1418. - Four kinds of refusal by deltalake at the commit are raised by the flush once, as `InputValidationError` ("Delta refused the commit to table ...") naming the table, Delta's reason and the number of rows not written, or, for two names equal under @@ -48,7 +50,8 @@ by chance would have accepted the rows later, and Orcapod writes none). Any other failure keeps its rows queued as before, so nothing is dropped on a guess: a storage error, a constraint whose evaluation itself fails, a table unreadable for another - reason. Until ITL-1412, a job whose result batch is dropped this way can + reason, another writer committing first, and a table that cannot be loaded at the + flush, even when Delta's cause names two names equal under its case folding. Until ITL-1412, a job whose result batch is dropped this way can keep pipeline records naming those results. - This narrows what a Delta table takes from deltalake 1.5 on: a stored column's field metadata cannot change in a commit. So a column whose Arrow type is recorded cannot diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index d2ae36699..9af616456 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -650,6 +650,22 @@ def _duplicate_name_in(error: BaseException) -> str | None: return None +def _write_refused_for_duplicate_name(error: BaseException) -> str | None: + """The duplicate name for which Delta refused the write itself, else ``None``. + + Only an error deltalake raised for the write counts, never one that merely carries + a duplicate-name cause: a ``CommitFailedError`` (another writer committed first) + and a table that could not be loaded (``OrcapodDatabaseReadError``, raised before + the write) keep their rows queued for a later flush (review of PR 504, round + seven). + """ + from deltalake.exceptions import CommitFailedError + + if not _is_delta_error(error) or isinstance(error, CommitFailedError): + return None + return _duplicate_name_in(error) + + def _error_chain(error: BaseException) -> list[BaseException]: """``error`` and its explicit causes (``raise ... from``), each once. @@ -2253,27 +2269,25 @@ def _refuse_unmergeable_append( f"{'omit it' if omitted else 'hold a null'}", ) if refusal is None: - try: - delta_table = self._get_delta_table(record_path) - except OrcapodDatabaseReadError as unreadable: - duplicate = _duplicate_name_in(unreadable) - if duplicate is not None: - # Written before deltalake 1.5.1, which no longer reads it: every - # flush would fail the same way, so nothing is queued (ITL-1403). - raise InputValidationError( - f"Cannot append to the stored table " - f"{self._get_table_uri(record_path)!r}: it holds columns whose " - f"names differ only in case (one is {duplicate!r}), which " - "deltalake 1.5.1 and later cannot read: " - f"{_CASE_INSENSITIVE} of them. Nothing was queued. Rebuild the " - "table with distinct names, using a deltalake version before " - "1.5.1 to read it." - ) from unreadable - delta_table = None + delta_table = self._stored_table_for_check(record_path) if delta_table is not None: refusal = _append_refusal( delta_table, records, self.allow_schema_evolution ) + if refusal is not None: + # The handle may be cached from a version another writer has since + # replaced: the rows are refused only if the version stored now + # refuses them too (review of PR 504, round seven). An accepted add + # keeps the cached handle, so it costs no reload. + self._delta_table_cache.pop(self._get_record_key(record_path), None) + delta_table = self._stored_table_for_check(record_path) + refusal = ( + None + if delta_table is None + else _append_refusal( + delta_table, records, self.allow_schema_evolution + ) + ) if refusal is not None: column, reason = refusal raise InputValidationError( @@ -2282,6 +2296,35 @@ def _refuse_unmergeable_append( "The stored rows are unchanged and nothing was written." ) + def _stored_table_for_check( + self, record_path: tuple[str, ...] + ) -> deltalake.DeltaTable | None: + """The stored table rows added to ``record_path`` are checked against. + + ``None`` when no table is stored, or when it cannot be loaded for a reason the + flush reports (``OrcapodDatabaseReadError``). + + Raises: + InputValidationError: If the stored table holds two names differing only in + case, written before deltalake 1.5.1, which no longer reads it: every + flush would fail the same way, so nothing is queued (ITL-1403). + """ + try: + return self._get_delta_table(record_path) + except OrcapodDatabaseReadError as unreadable: + duplicate = _duplicate_name_in(unreadable) + if duplicate is not None: + raise InputValidationError( + f"Cannot append to the stored table " + f"{self._get_table_uri(record_path)!r}: it holds columns whose " + f"names differ only in case (one is {duplicate!r}), which " + "deltalake 1.5.1 and later cannot read: " + f"{_CASE_INSENSITIVE} of them. Nothing was queued. Rebuild the " + "table with distinct names, using a deltalake version before " + "1.5.1 to read it." + ) from unreadable + return None + def _refuse_declared_nulls( self, record_path: tuple[str, ...], rows: pa.Table ) -> None: @@ -3195,16 +3238,24 @@ def flush(self) -> None: (``_append_refusal``). The batch is dropped from the queue, since every later flush would refuse it too; the error says how many rows were not written. Correct the rows and add them again (ITL-1334). - - Any other failure (a table that cannot be loaded, a failed write): the batch - stays queued, so a later flush tries it again. + - Refused by Delta for the rows themselves (ITL-1403): a ``SchemaMismatchError``, + a ``DeltaError`` whose message starts with one of + ``PERMANENT_DELTA_ERROR_PREFIXES`` (raised as ``InputValidationError``), or two + names equal under Delta's case folding (raised as ``UnstorableColumnError``). + Every later flush would be refused the same way, so the batch is dropped from + the queue and nothing of it is written: correct the rows and add them again. + - Any other failure (a table that cannot be loaded, another writer committing + first, a storage error): the batch stays queued, so a later flush tries it + again. Raises: OrcapodDatabaseReadError: If a batch's existing table could not be loaded. It is raised as itself; every other batch that failed in this flush is added to it as a note. InputValidationError: If no batch failed with ``OrcapodDatabaseReadError`` but a - batch was refused by its stored table (dropped from the queue, above). - Other failed batches are added to it as notes. + batch was refused by its stored table or by Delta for its rows + (dropped from the queue, above). Other failed batches are added to it + as notes. UnstorableColumnError: If neither of the above, but Delta refused a batch for two names equal under its case folding (dropped from the queue: every later flush would refuse it too; ITL-1403). @@ -3438,7 +3489,7 @@ def _flush_by_key(self, record_key: str) -> None: raise refused from e except BaseException as e: permanent = isinstance(e, Exception) and _permanent_commit_failure(e) - reported = _duplicate_name_in(e) if isinstance(e, Exception) else None + reported = _write_refused_for_duplicate_name(e) if permanent and reported is None: # Refused by Delta for the rows themselves: every later flush would be # refused the same way, so the batch leaves the queue, and nothing of diff --git a/tests/test_databases/test_delta_add_time_property.py b/tests/test_databases/test_delta_add_time_property.py index 65ddf84cd..971e48cf4 100644 --- a/tests/test_databases/test_delta_add_time_property.py +++ b/tests/test_databases/test_delta_add_time_property.py @@ -20,7 +20,7 @@ from collections.abc import Iterator from itertools import product from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest @@ -107,7 +107,16 @@ def _variants() -> Iterator[tuple[str, Any, Any, Any, Any]]: VARIANTS = {label: rest for label, *rest in _variants()} -LOGICAL_RULE = {"logical changed", "logical empty to value", "logical value to empty"} +# Refused by the logical-identifier rule (ITL-1371, PR 492), an Orcapod rule by design: +# another logical type identifier's values must not be read as the stored one's, also +# for a null column that carries one. Delta itself may store these rows. +LOGICAL_RULE = { + "logical changed", + "logical empty to value", + "logical value to empty", + "path null readable old", + "path null unknown", +} def _rows(column: Any, ids: list[bytes], field: Any = None) -> pa.Table: @@ -123,22 +132,66 @@ def _rows(column: Any, ids: list[bytes], field: Any = None) -> pa.Table: ) +def _stored_ids(root: Path) -> list[bytes]: + table = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="rid") + return [] if table is None else cast(list[bytes], table.column("rid").to_pylist()) + + def _run( root: Path, initial: pa.Table, incoming: pa.Table, evolve: bool -) -> tuple[str, bool]: - """``(outcome, rows still queued)``: ``stored``, ``refused when added``, or - ``refused at flush``.""" +) -> tuple[str, bool, BaseException | None]: + """``(outcome, rows still queued, the error)``: ``stored``, ``refused when added``, + or ``refused at flush``. ``stored`` is read back through a fresh handle: every + incoming id is stored, each once (review of PR 504, round seven).""" db = DeltaTableDatabase(root, allow_schema_evolution=evolve) db.add_records(PATH, initial, record_id_column="rid", flush=True) + queued = lambda: bool(db._pending_batches) # noqa: E731 # pyright: ignore[reportPrivateUsage] try: db.add_records(PATH, incoming, record_id_column="rid") - except Exception: # noqa: BLE001 # the outcome is the subject - return "refused when added", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] + except Exception as error: # noqa: BLE001 # the outcome is the subject + return "refused when added", queued(), error try: db.flush() - except Exception: # noqa: BLE001 - return "refused at flush", bool(db._pending_batches) # pyright: ignore[reportPrivateUsage] - return "stored", False + except Exception as error: # noqa: BLE001 + return "refused at flush", queued(), error + expected = set(cast(list[bytes], initial.column("rid").to_pylist())) | set( + cast(list[bytes], incoming.column("rid").to_pylist()) + ) + stored = _stored_ids(root) + assert sorted(stored) == sorted(expected), f"stored {stored}, not {expected}" + return "stored", queued(), None + + +# Every check Orcapod makes when rows are added, and its stored-table check at the +# flush: switched off, the rows reach Delta's commit, whose verdict is the reference. +ADD_TIME_CHECKS = ( + "require_storable", + "_refuse_untyped_null_columns", + "_refuse_case_clash_with_pending", + "_refuse_changed_attributes", + "_refuse_declared_nulls", + "_refuse_unmergeable_append", +) + + +def _without_orcapod_checks(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ADD_TIME_CHECKS: + monkeypatch.setattr(DeltaTableDatabase, name, lambda *args: None) + monkeypatch.setattr(DeltaTableDatabase, "_identity_refusal", lambda *args: None) + monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) + + +def _refused_by_delta(error: BaseException | None) -> bool: + """Whether the commit itself was refused: an error deltalake raised is in the + chain of the flush's error.""" + from deltalake.exceptions import SchemaMismatchError + + seen: BaseException | None = error + while seen is not None: + if isinstance(seen, SchemaMismatchError) or dld._is_delta_error(seen): # pyright: ignore[reportPrivateUsage] + return True + seen = seen.__cause__ + return False @pytest.fixture(autouse=True) @@ -165,17 +218,19 @@ def test_orcapod_refuses_nothing_delta_stores( initial = _rows(a, [b"1"], field_a) incoming = _rows(b, [b"1", b"2"] if seen else [b"2"], field_b) - live, queued = _run(tmp_path / "live", initial, incoming, evolve) + live, queued, refusal = _run(tmp_path / "live", initial, incoming, evolve) assert not queued, f"{label}: rows still queued after the flush ({live})" - if live == "refused when added" and label not in LOGICAL_RULE: - # Delta's own verdict: the same rows with Orcapod's add-time checks off. - monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) - monkeypatch.setattr( - DeltaTableDatabase, "_refuse_case_clash_with_pending", lambda *args: None + if live == "refused when added" and label in LOGICAL_RULE: + assert "of logical type" in str(refusal), f"{label}: {refusal!r}" + elif live == "refused when added": + # Delta's own verdict: the same rows with every Orcapod check off reach the + # commit, and Delta refuses it. + _without_orcapod_checks(monkeypatch) + raw, _, error = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw == "refused at flush" and _refused_by_delta(error), ( + f"{label}: Orcapod refused rows Delta does not refuse ({raw}: {error!r})" ) - raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) - assert raw != "stored", f"{label}: Orcapod refused rows Delta stores" def test_the_sweep_covers_every_kind() -> None: @@ -199,12 +254,12 @@ def test_a_name_differing_in_case_from_a_stored_column( incoming = pa.table( {"rid": pa.array([b"2"], pa.large_binary()), "anchor": [2], "A": [22]} ) - live, queued = _run(tmp_path / "live", initial, incoming, evolve) + live, queued, _ = _run(tmp_path / "live", initial, incoming, evolve) assert not queued if not evolve: assert live == "stored" return assert live == "refused when added" - monkeypatch.setattr(dld, "_append_refusal", lambda *args: None) - raw, _ = _run(tmp_path / "raw", initial, incoming, evolve) - assert raw != "stored" + _without_orcapod_checks(monkeypatch) + raw, _, error = _run(tmp_path / "raw", initial, incoming, evolve) + assert raw == "refused at flush" and _refused_by_delta(error) diff --git a/tests/test_databases/test_delta_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py index 36efd6ca5..80a26be03 100644 --- a/tests/test_databases/test_delta_commit_failures.py +++ b/tests/test_databases/test_delta_commit_failures.py @@ -23,7 +23,14 @@ from orcapod.databases import DeltaTableDatabase from orcapod.databases import delta_lake_databases as dld -from orcapod.errors import InputValidationError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + UnstorableColumnError, +) +from tests.test_databases.test_delta_refused_before_queueing import ( + _legacy_case_only_table, # pyright: ignore[reportPrivateUsage] +) PATH = ("t",) @@ -307,6 +314,10 @@ def test_a_failure_inside_an_unrelated_handler_is_classified_on_its_own( info.value, (InputValidationError, UnstorableColumnError) ) assert db._pending_batches # pyright: ignore[reportPrivateUsage] + else: + # Review of PR 504, round seven: without the probe's error there is no + # ambient context, and the test would prove nothing. + pytest.fail("deltalake accepted two names equal under its case folding") finally: parent.chmod(0o700) db.flush() @@ -363,3 +374,92 @@ def row(rid: bytes, value: int) -> pa.Table: records, record_id_column="rid" ) assert stored is None or stored.num_rows == 0 + + +# ── Review of PR 504, round seven ─────────────────────────────────────────────────── + + +def _rows_of(*ids: bytes, column: str = "x") -> pa.Table: + return pa.table( + {"rid": pa.array(list(ids), pa.large_binary()), column: list(range(len(ids)))} + ) + + +@pytest.mark.parametrize("depth", [1, 2], ids=["its cause", "a cause of its cause"]) +@pytest.mark.parametrize( + "seen", [False, True], ids=["append (every id new)", "MERGE (a stored id)"] +) +def test_a_commit_conflict_carrying_a_duplicate_name_cause_stays_queued( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, seen: bool, depth: int +) -> None: + """Finding: a ``CommitFailedError`` (another writer committed first) whose cause + chain names a duplicate is not a refusal of the rows: the batch stays queued and a + later flush commits it, on the append path and the MERGE path.""" + from deltalake.exceptions import CommitFailedError, DeltaError + + db = DeltaTableDatabase(tmp_path) + db.add_records(PATH, _rows_of(b"1"), record_id_column="rid", flush=True) + db.add_records( + PATH, + _rows_of(b"1", b"2", b"3") if seen else _rows_of(b"2", b"3"), + record_id_column="rid", + ) + called: list[str] = [] + + def conflict(*args: Any, **kwargs: Any) -> Any: + called.append("merge" if "predicate" in kwargs else "append") + cause: BaseException = Exception( + "Schema error: Duplicate field name (case-insensitive): 'x'" + ) + for _ in range(depth - 1): + outer = DeltaError("Generic DeltaTable error") + outer.__cause__ = cause + cause = outer + raise CommitFailedError("another writer committed first") from cause + + with monkeypatch.context() as patched: + patched.setattr(deltalake, "write_deltalake", conflict) + patched.setattr(deltalake.DeltaTable, "merge", conflict) + with pytest.raises(RuntimeError, match="Failed to flush") as info: + db.flush() + assert called == ["merge" if seen else "append"] + assert isinstance(info.value.__cause__, CommitFailedError) + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("rid").to_pylist())) == [ + b"1", + b"2", + b"3", + ] + + +@pytest.mark.parametrize("column", ["a", "c"], ids=["a held name", "a new name"]) +def test_a_target_that_cannot_be_loaded_keeps_its_batch_queued( + tmp_path: Path, column: str +) -> None: + """Finding: rows queued for a table that a writer before deltalake 1.5.1 then + creates with ``a`` and ``A``. The flush fails loading the table, before any write: + the read error is raised as itself, the batch stays queued (a later flush retries + once the table is repaired), and a batch for another table is committed.""" + db = DeltaTableDatabase(tmp_path) + other = ("other",) + db.add_records(PATH, _rows_of(b"2", b"3", column=column), record_id_column="rid") + db.add_records(other, _rows_of(b"7", b"8"), record_id_column="rid") + _legacy_case_only_table(tmp_path) + with pytest.raises(OrcapodDatabaseReadError): + db.flush() + assert set(db._pending_batches) == {"t"} # pyright: ignore[reportPrivateUsage] + stored = DeltaTableDatabase(tmp_path).get_all_records(other, record_id_column="rid") + assert stored is not None and stored.num_rows == 2 + # Repaired: the table is removed, and the queued rows are committed. + import shutil + + shutil.rmtree(tmp_path / "t") + db.flush() + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + stored = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="rid") + assert stored is not None + assert sorted(cast(list[bytes], stored.column("rid").to_pylist())) == [b"2", b"3"] diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index e7089e693..57f451a7a 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -656,3 +656,50 @@ def test_the_backstop_names_the_column_colliding_with_a_stored_one( assert info.value.column == lower assert "int32" in str(info.value) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +# (stored, added, what another writer stores instead): a name the added rows hold that +# differs only in case from a stored one, as a column and as a struct field. +STALE_CLASHES: dict[str, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]] = { + "column": ({"a": pa.array([1])}, {"A": pa.array([2])}, {"b": pa.array([1])}), + "struct field": ( + {"s": pa.array([{"a": 1, "c": 1}])}, + {"s": pa.array([{"A": 2, "c": 2}])}, + {"s": pa.array([{"b": 1, "c": 1}])}, + ), +} + + +@pytest.mark.parametrize("replaced", [True, False], ids=["replaced", "unchanged"]) +@pytest.mark.parametrize("kind", sorted(STALE_CLASHES)) +def test_a_clash_with_a_cached_version_is_checked_against_the_stored_one( + tmp_path: Path, kind: str, replaced: bool +) -> None: + """Review of PR 504, round seven: the database holds a cached handle of the table; + another writer replaces the clashing name. The rows are checked again against the + version stored now before they are refused: accepted and stored when the clash is + gone, refused (nothing queued) when it is still there.""" + stored, added, other = STALE_CLASHES[kind] + anchor = {"anchor": pa.array([1])} + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + _add(db, _rows(b"1", **anchor, **stored), flush=True) + db.get_all_records(PATH, record_id_column="rid") # the handle is cached + assert db._delta_table_cache # pyright: ignore[reportPrivateUsage] + if replaced: + current = deltalake.DeltaTable(str(tmp_path / "t")).to_pyarrow_table() + names = [n for n in current.column_names if n not in stored] + deltalake.write_deltalake( + str(tmp_path / "t"), + current.select(names).append_column( + *next(iter((pa.field(k, v.type), v) for k, v in other.items())) + ), + mode="overwrite", + schema_mode="overwrite", + ) + _add(db, _rows(b"2", **anchor, **added), flush=True) + assert _stored_ids(tmp_path) == [b"1", b"2"] + else: + with pytest.raises(InputValidationError, match="differ only in case"): + _add(db, _rows(b"2", **anchor, **added)) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + assert _stored_ids(tmp_path) == [b"1"] diff --git a/tests/test_databases/test_delta_struct_evolution.py b/tests/test_databases/test_delta_struct_evolution.py index 210fbdc06..c15dd6291 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -172,14 +172,16 @@ def test_an_append_changing_a_recorded_type_is_refused_once_at_flush( record_id_column="id", flush=True, ) - with pytest.raises(InputValidationError, match="Delta refused the commit"): - db.add_records( - PATH, - _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)), - record_id_column="id", - flush=flush, - ) - db.flush() + rows = _rows([b"2"], k=([7], pa.int64()), x=(appended_values, appended)) + if flush: + with pytest.raises(InputValidationError, match="Delta refused the commit"): + db.add_records(PATH, rows, record_id_column="id", flush=True) + else: + # Accepted when added (review of PR 504, round seven): only the flush raises. + db.add_records(PATH, rows, record_id_column="id") + assert db._pending_batches # pyright: ignore[reportPrivateUsage] + with pytest.raises(InputValidationError, match="Delta refused the commit"): + db.flush() assert not db._pending_batches # pyright: ignore[reportPrivateUsage] db.flush() # a no-op back = DeltaTableDatabase(tmp_path).get_all_records(PATH, record_id_column="id") diff --git a/tests/test_pipeline/test_dropped_result_batch.py b/tests/test_pipeline/test_dropped_result_batch.py index 8fa1d17a9..11220740d 100644 --- a/tests/test_pipeline/test_dropped_result_batch.py +++ b/tests/test_pipeline/test_dropped_result_batch.py @@ -20,6 +20,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase +from orcapod.errors import OrcapodDatabaseWriteError, UnstorableColumnError from orcapod.system_constants import constants UPPER, LOWER = "Ᲊ", "ᲊ" @@ -45,11 +46,20 @@ def test_no_pipeline_record_names_a_dropped_result( job = PipelineJob(name="itl1403", database=database) with job: _pair.pod(source, label="pair") - with pytest.raises(Exception): # noqa: B017 # the run fails: the result batch is dropped + with pytest.raises(OrcapodDatabaseWriteError) as info: if use_async: asyncio.run(job.run_async()) else: job.run() + # The result batch was dropped at the flush, on Delta's own report of the two + # names (review of PR 504, round seven): not refused when added, and no other + # failure. + refusal = info.value.__cause__ + assert isinstance(refusal, UnstorableColumnError) + assert refusal.column == LOWER + assert "under its case folding" in str(refusal) + assert "were not written and are no longer queued" in str(refusal) + assert "_result" in str(refusal) fresh = DeltaTableDatabase(tmp_path) referenced: list[object] = [] for path in fresh.list_table_paths(): @@ -75,7 +85,7 @@ def test_a_result_batch_delta_refuses_withdraws_its_pipeline_records( import deltalake from deltalake.exceptions import SchemaMismatchError - from orcapod.errors import InputValidationError, OrcapodDatabaseWriteError + from orcapod.errors import InputValidationError real_write = deltalake.write_deltalake From 406b2364a99d9f6943c0df6b3351c4acecf7b02d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:21:54 -0800 Subject: [PATCH 11/12] fix(databases): a reopen drops the snapshot with the handle; a case clash beside a repeated name is refused (ITL-1403) Review of PR 504, round eight (CodeRabbit on a47bb0be): - A table reopened to check a refusal again (the stored-name check and the logical-identifier check, ITL-1371) drops the cached snapshot together with the handle (_forget_loaded_table): a table created again at the same version is no longer read through the old table's rows. This also closes ITL-1413's case on this path; its limit test now asserts the fixed result. - require_storable finds a case clash by position, so x, X, X is refused with UnstorableColumnError instead of raising KeyError. - _append_refusal folds the stored names once per check (nitpick). Co-Authored-By: Claude Opus 5.5 --- docs/dev/design_issues/ITL-1371-LI1.md | 6 +- src/orcapod/databases/delta_lake_databases.py | 54 ++++++++-- .../test_delta_refused_before_queueing.py | 99 +++++++++++++++++++ .../test_logical_identity_appends.py | 16 +-- 4 files changed, 156 insertions(+), 19 deletions(-) diff --git a/docs/dev/design_issues/ITL-1371-LI1.md b/docs/dev/design_issues/ITL-1371-LI1.md index 62dd996d0..83f377dfe 100644 --- a/docs/dev/design_issues/ITL-1371-LI1.md +++ b/docs/dev/design_issues/ITL-1371-LI1.md @@ -82,8 +82,10 @@ loaded, before anything is written. Two differences remain. One writes nothing e a duplicate-only append of the identifier a stale version holds is a no-op on the held handle, where a reopened handle refuses it. The other is pre-existing, as on main (ITL-1413): when the table is deleted and recreated at the same path and Delta version, the -held handle's duplicate scan reuses the old version's cached ids, so an old id is skipped as -a duplicate and a new one can be written twice. A connector database compares against the +held handle's duplicate scan reused the old version's cached ids, so an old id was skipped as +a duplicate and a new one could be written twice. When an add reopens the table (another +identifier, or a refusal checked again), the snapshot is now dropped with the handle (review +of PR 504, round eight); the general fix is ITL-1377's. A connector database compares against the stored schema it caches for the ITL-1334 check (`_stored_schemas`), as main's check does, so a table replaced by another connection is seen as main sees it (pre-existing). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 18adc91c1..7044b409e 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -586,11 +586,22 @@ def _merged_record( def _differ_only_in_case(names: list[str]) -> tuple[str, str] | None: """The first two of ``names`` that differ only in case, or ``None``.""" + position = _case_clash_position(names) + if position is None: + return None + second = names[position] + first = next(n for n in names if n.lower() == second.lower() and n != second) + return first, second + + +def _case_clash_position(names: list[str]) -> int | None: + """The position in ``names`` of the first name that differs only in case from an + earlier one, or ``None``. A position, since the name itself may be repeated.""" seen: dict[str, str] = {} - for name in names: + for position, name in enumerate(names): other = seen.setdefault(name.lower(), name) if other != name: - return other, name + return position return None @@ -1145,6 +1156,11 @@ def _append_refusal( if identity is not None: return identity held = _held_columns(delta_table) + # Folded once per check, not once per new column (review of PR 504, round eight). + held_clash = _differ_only_in_case(list(held)) + held_folded: dict[str, str] = {} + for name in held: + held_folded.setdefault(name.lower(), name) for field in rows.schema: if field.name in held: change = _column_change(held[field.name], field) @@ -1154,9 +1170,11 @@ def _append_refusal( # A new name enters the stored schema only when the MERGE evolves it; # without evolution Delta leaves an unknown column out, as main did # (review of PR 504, round four). - clash = _differ_only_in_case([*held, field.name]) - if clash is not None: - return field.name, _case_reason(*clash) + if held_clash is not None: + return field.name, _case_reason(*held_clash) + stored_name = held_folded.get(field.name.lower()) + if stored_name is not None: + return field.name, _case_reason(stored_name, field.name) exact = _exact_refusal(delta_table, rows) if exact is not None: return exact @@ -2153,12 +2171,16 @@ def require_storable(self, schema: pa.Schema) -> None: UnstorableColumnError: For the first column Delta cannot hold, naming the column, its Arrow type and Delta's reason. """ - clash = _differ_only_in_case(schema.names) - if clash is not None: + position = _case_clash_position(schema.names) + if position is not None: + # By position: the name may be repeated (``x``, ``X``, ``X``), and a + # lookup by a repeated name raises (review of PR 504, round eight). + clash = _differ_only_in_case(schema.names) + assert clash is not None raise UnstorableColumnError( database_kind=type(self).__name__, column=clash[1], - arrow_type=schema.field(clash[1]).type, + arrow_type=schema.field(position).type, reason=_case_reason(*clash), ) for field in schema: @@ -2277,7 +2299,7 @@ def _refuse_unmergeable_append( # replaced: the rows are refused only if the version stored now # refuses them too (review of PR 504, round seven). An accepted add # keeps the cached handle, so it costs no reload. - self._delta_table_cache.pop(self._get_record_key(record_path), None) + self._forget_loaded_table(record_path) delta_table = self._stored_table_for_check(record_path) refusal = ( None @@ -2294,6 +2316,18 @@ def _refuse_unmergeable_append( "The stored rows are unchanged and nothing was written." ) + def _forget_loaded_table(self, record_path: tuple[str, ...]) -> None: + """Drop the table handle and the snapshot of it cached for ``record_path``. + + Both go together: the next load may find a table another writer created + again at the same version, and a snapshot is kept by version only, so a + snapshot left behind would serve the old table's rows for the new one + (review of PR 504, round eight). + """ + record_key = self._get_record_key(record_path) + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + def _stored_table_for_check( self, record_path: tuple[str, ...] ) -> deltalake.DeltaTable | None: @@ -2417,7 +2451,7 @@ def _stored_identity_refusal( if identity_refusal(_stored_identities(delta_table), rows) is None: return None # Decide the refusal on the version stored now. - self._delta_table_cache.pop(self._get_record_key(record_path), None) + self._forget_loaded_table(record_path) try: delta_table = self._get_delta_table(record_path) except OrcapodDatabaseReadError: diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 57f451a7a..0cf7306b1 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -703,3 +703,102 @@ def test_a_clash_with_a_cached_version_is_checked_against_the_stored_one( _add(db, _rows(b"2", **anchor, **added)) assert not db._pending_batches # pyright: ignore[reportPrivateUsage] assert _stored_ids(tmp_path) == [b"1"] + + +@pytest.mark.parametrize( + "names", + [["a", "A", "A"], ["A", "a", "a"], ["a", "b", "A", "b"]], + ids=lambda names: "".join(names), +) +def test_a_case_clash_beside_a_repeated_name_names_the_column( + tmp_path: Path, names: list[str] +) -> None: + """Review of PR 504 (round eight) and PR 511: with a name repeated, the case clash + is still refused with ``UnstorableColumnError``, naming the column and the type at + its position.""" + types = [pa.int8(), pa.int16(), pa.int32(), pa.int64()][: len(names)] + table = pa.Table.from_arrays( + [pa.array([b"1"], pa.large_binary())] + [pa.array([1], t) for t in types], + names=["rid", *names], + ) + db = DeltaTableDatabase(tmp_path) + with pytest.raises(UnstorableColumnError) as info: + _add(db, table) + position = next( + i + for i, n in enumerate(names) + if any(m.lower() == n.lower() and m != n for m in names[:i]) + ) + assert info.value.column == names[position] + assert str(types[position]) in str(info.value) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize("trigger", ["a case clash", "a logical identifier"]) +def test_a_table_reopened_for_a_refusal_is_read_as_the_table_stored_now( + tmp_path: Path, unit_type: Any, trigger: str +) -> None: + """Review of PR 504, round eight: the database read a table (its handle and the + snapshot of its rows are cached); another writer creates the table again at the + same version with other rows. An add refused against the cached version reopens + the table, which takes the rows; reads then show the table stored now, never the + old table's rows from the snapshot kept by version. Both reopen paths: the stored + case clash and the logical identifier (ITL-1371).""" + import shutil + + def unit(value: int, serial: bytes) -> Any: + return pa.ExtensionArray.from_storage( + unit_type(serial), pa.array([value], pa.int64()) + ) + + if trigger == "a case clash": + first = {"anchor": pa.array([1]), "a": pa.array([11])} + other = {"anchor": pa.array([99])} + added = {"anchor": pa.array([2]), "A": pa.array([22])} + else: + first = {"anchor": pa.array([1]), "x": unit(11, b"old")} + other = {"anchor": pa.array([99]), "x": unit(99, b"new")} + added = {"anchor": pa.array([2]), "x": unit(22, b"new")} + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + _add(db, _rows(b"1", **first), flush=True) + before = db.get_record_by_id(PATH, b"1") + assert before is not None and before.column("anchor").to_pylist() == [1] + shutil.rmtree(tmp_path / "t") + DeltaTableDatabase(tmp_path, allow_schema_evolution=True).add_records( + PATH, _rows(b"1", **other), record_id_column="rid", flush=True + ) + assert deltalake.DeltaTable(str(tmp_path / "t")).version() == 0 + _add(db, _rows(b"2", **added)) # accepted against the table stored now + after = db.get_record_by_id(PATH, b"1") + assert after is not None + assert after.column("anchor").to_pylist() == [99] + db.flush() + assert _stored_ids(tmp_path) == [b"1", b"2"] + + +@pytest.mark.parametrize("evolve", [True, False], ids=["evolution on", "evolution off"]) +@pytest.mark.parametrize( + "new", [["b", "C", "d"], ["d", "C", "b"]], ids=["one order", "another order"] +) +def test_new_columns_are_checked_against_every_stored_name( + tmp_path: Path, new: list[str], evolve: bool +) -> None: + """Review of PR 504, round eight (the stored names are folded once per check): + several new columns, one of them differing only in case from a stored one, in two + orders. With schema evolution the clashing column is refused, named with the + stored one; without it Delta leaves the unknown columns out and the rows are + stored.""" + stored = {"a": pa.array([1]), "c": pa.array([2])} + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=evolve) + _add(db, _rows(b"1", **stored), flush=True) + # The rows omit the stored ``c``: their own names never clash. + rows = _rows(b"2", a=pa.array([1]), **{n: pa.array([3]) for n in new}) + if evolve: + with pytest.raises( + InputValidationError, match="'c' and 'C' differ only in case" + ): + _add(db, rows) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + else: + _add(db, rows, flush=True) + assert _stored_ids(tmp_path) == [b"1", b"2"] diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index 982767cb3..aa5f5cb0b 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -2316,14 +2316,16 @@ def test_delta_recorded_type_decides_a_child_the_log_keeps_plain( assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [b"1", b"22"] -def test_delta_stale_handle_after_delete_and_recreate_reuses_its_ids( +def test_delta_handle_after_delete_and_recreate_reads_the_new_tables_ids( tmp_path: Path, ) -> None: - """Pins a pre-existing limit, as on main (round 5, finding 2; ITL-1413): a held - handle whose table was deleted and recreated at the same path, at the same Delta - version, takes the new table's identifier on a reload but its duplicate scan - reuses the old version's cached ids, so a same-identifier append of an old id is - taken for a duplicate (nothing written) and one of a new id is written again.""" + """Round 5, finding 2 (ITL-1413): a held handle whose table was deleted and + recreated at the same path, at the same Delta version, no longer reuses the old + table's cached ids, so an old id the new table lacks is stored once, and an id of + the new table is not stored twice. Here the add of another identifier reopens the + table, and a reopen drops the snapshot with the handle (review of PR 504, round + eight); ITL-1377 also keys every snapshot by the Delta table's own id and commits + every append to an existing table as a MERGE.""" import shutil import deltalake @@ -2359,7 +2361,7 @@ def test_delta_stale_handle_after_delete_and_recreate_reuses_its_ids( stored = DeltaTableDatabase(root).get_all_records(PATH, record_id_column="id") assert stored is not None assert sorted(cast(list[bytes], stored.column("id").to_pylist())) == [ - b"c", + b"a", b"c", b"d", ] From b2feefd0c66d6cff895f2e288e73a3f72eb0f920 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:56:43 -0800 Subject: [PATCH 12/12] perf(databases): hold the queued names as a set; the pruning test checks there are files to prune (ITL-1403) From CodeRabbit's review of PR 511 on d6a25bb8, for code of this PR: - _refuse_case_clash_with_pending tests membership against a set of the queued names; the list keeps the order the clash is reported in (nitpick). - test_a_listed_column_prunes_files asserts three active files with disjoint v ranges before it checks that the query scans one of them. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/delta_lake_databases.py | 7 +++++-- .../test_delta_refused_before_queueing.py | 17 +++++++++++++++++ .../test_delta_statistics_columns.py | 7 +++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 7044b409e..d3a90ae43 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2209,8 +2209,11 @@ def _refuse_case_clash_with_pending( if pending is None: return queued = pending.schema.names + # A set for membership, the list for the order the clash is reported in + # (review of PR 511). + queued_names = set(queued) clash = _differ_only_in_case( - [*queued, *(n for n in schema.names if n not in queued)] + [*queued, *(n for n in schema.names if n not in queued_names)] ) if clash is not None: raise InputValidationError( @@ -2220,7 +2223,7 @@ def _refuse_case_clash_with_pending( # A struct queued and a struct added, merged as the flush would merge them, # must not hold two field names differing only in case, at any depth. for field in schema: - if field.name not in queued: + if field.name not in queued_names: continue try: merged = merged_type( diff --git a/tests/test_databases/test_delta_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py index 0cf7306b1..03f013147 100644 --- a/tests/test_databases/test_delta_refused_before_queueing.py +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -802,3 +802,20 @@ def test_new_columns_are_checked_against_every_stored_name( else: _add(db, rows, flush=True) assert _stored_ids(tmp_path) == [b"1", b"2"] + + +@pytest.mark.parametrize( + "added", [["a", "B", "d"], ["d", "B", "a"]], ids=["one order", "another order"] +) +def test_a_column_differing_in_case_from_a_queued_one_is_named( + tmp_path: Path, added: list[str] +) -> None: + """Review of PR 511 (pending names held as a set for membership): rows queued with + ``a`` and ``b``; rows added with a queued name, a new name and ``B``, in two + orders. ``B`` is refused, named with the queued ``b``, and nothing of the add is + queued.""" + db = DeltaTableDatabase(tmp_path) + _add(db, _rows(b"1", a=pa.array([1]), b=pa.array([2]))) + with pytest.raises(InputValidationError, match="'b' and 'B' differ only in case"): + _add(db, _rows(b"2", **{n: pa.array([3]) for n in added})) + assert db._pending_batches["t"].num_rows == 1 # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/test_delta_statistics_columns.py b/tests/test_databases/test_delta_statistics_columns.py index e13b369d8..f988c7045 100644 --- a/tests/test_databases/test_delta_statistics_columns.py +++ b/tests/test_databases/test_delta_statistics_columns.py @@ -442,6 +442,13 @@ def test_a_listed_column_prunes_files(self, tmp_path: Path) -> None: db.add_records(PATH, rows(range(lo, lo + 5)), flush=True) table = deltalake.DeltaTable(str(tmp_path / "t")) + # There are files to prune: three active files, with disjoint ``v`` ranges, + # one of them holding 101 (review of PR 511). + ranges = sorted( + (add["min.v"], add["max.v"]) + for add in pa.table(table.get_add_actions(flatten=True)).to_pylist() + ) + assert ranges == [(0, 4), (100, 104), (200, 204)] plan = pa.table( deltalake.QueryBuilder() .register("t", table)