diff --git a/changelog.d/ITL-1403.md b/changelog.d/ITL-1403.md new file mode 100644 index 000000000..597ca4c0e --- /dev/null +++ b/changelog.d/ITL-1403.md @@ -0,0 +1,76 @@ +### 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. 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 or field added beside a + 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, + 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. +- 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 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. 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 + 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 + with one of `PERMANENT_DELTA_ERROR_PREFIXES` (`type_coercion`, `Invalid data found`, + `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, 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 + 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. +- 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 + 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/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/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..8bed7b585 --- /dev/null +++ b/docs/dev/scripts/itl_1403/premise.py @@ -0,0 +1,322 @@ +"""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. +- ``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 +""" + +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.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 +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) + ) + + +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] = {} + + # 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) + ) + + # 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}") + + +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 1fc8911b3..0468ac5f7 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -81,10 +81,39 @@ 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 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 +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. 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 9c2cc0051..b192070e6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -206,6 +206,33 @@ 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 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, 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 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 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 ### I edited my function and the results did not change @@ -303,25 +330,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 a9ae8ff33..d3a90ae43 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 @@ -66,6 +67,10 @@ import pyarrow.dataset as pa_ds import pyarrow.fs as pa_fs from upath import UPath + + from orcapod.logical_types.protocols import ( + TypeConverterProtocol as LogicalTypeConverterProtocol, + ) else: deltalake = LazyModule("deltalake") pa_ds = LazyModule("pyarrow.dataset") @@ -446,36 +451,342 @@ 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 - stored_record = stored_records.get(field.name) - incoming_record = recorded_type(field.metadata) - if stored_record is None and incoming_record is None: + 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 - 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) - ) - written = written.set_column( - index, - with_recorded_type(field, merged_type(base, incoming)), - written.column(index), - ) + 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 + 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, + 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``.""" + 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 position, name in enumerate(names): + other = seen.setdefault(name.lower(), name) + if other != name: + return position + 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}" + + +# delta-rs reports two names equal under its case folding (Rust ``to_lowercase``). +# 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\): '(.*)'", + re.DOTALL, # a name may hold a newline +) + + +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): + if not _is_delta_error(seen): + continue + match = _DUPLICATE_NAME.match(str(seen)) + if match is not None: + return match.group(1) + 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. + + 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__ + 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", +) + + +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.match(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. + + 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 prefix, children in _structs_of(schema): + probe = pa.schema([pa.field(c.name, pa.int64()) for c in children]) + try: + deltalake.Schema.from_arrow(probe) + except Exception as refused: # noqa: BLE001 # only a duplicate name is looked at + if _duplicate_name_in(refused) is None: + continue + 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 + # 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() + + +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(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): + visit(prefix, arrow_type.field(i).type) + + for field in schema: + visit(f"{field.name}.", field.type) + return found + + _EXTENSION_KEYS = (b"ARROW:extension:name", b"ARROW:extension:metadata") @@ -774,8 +1085,47 @@ def _stored_identities( ] -def _append_refusal( +def _exact_refusal( delta_table: deltalake.DeltaTable, rows: pa.Table +) -> tuple[str, str] | None: + """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``). Refused + here, for certain: a struct evolution that would put two field names differing + only in case into one struct, which Delta refuses whatever the commit route. + (Another logical type identifier is ITL-1371's rule, ``identity_refusal``.) + + 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) + for field in rows.schema: + position = stored.get_field_index(field.name) + if position < 0: + continue + if isinstance(field.type, pa.ExtensionType): + # A logical column's identifier is ITL-1371's rule (``identity_refusal``). + continue + try: + evolved = merged_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 + 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, schema_evolution: bool ) -> tuple[str, str] | None: """The first column of ``rows`` the stored table cannot take, and why (ITL-1334). @@ -795,6 +1145,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. @@ -803,11 +1156,28 @@ 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) if change is not None: return field.name, change + 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). + 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 violation = _non_null_violation(held, rows) if violation is not None: name, omitted = violation @@ -978,6 +1348,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'" @@ -1163,16 +1536,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 @@ -1789,10 +2164,25 @@ 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. """ + 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(position).type, + reason=_case_reason(*clash), + ) for field in schema: reason = delta_unstorable_reason(field) if reason is not None: @@ -1803,6 +2193,55 @@ 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 + # 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_names)] + ) + 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." + ) + # 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_names: + 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, record_path: tuple[str, ...], @@ -1853,12 +2292,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: - delta_table = None + delta_table = self._stored_table_for_check(record_path) 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: + # 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._forget_loaded_table(record_path) + 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( @@ -1867,6 +2319,47 @@ 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: + """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: @@ -1961,7 +2454,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: @@ -2153,6 +2646,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 @@ -2776,16 +3273,27 @@ 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). RuntimeError: If batches failed with other errors only, naming the failed batches, with the first failure as its ``__cause__``. """ @@ -2938,7 +3446,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( @@ -3012,8 +3522,53 @@ def _flush_by_key(self, record_key: str) -> None: self._pending_commits.finish(record_key, committed=False) logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e - except BaseException as exc: - logger.error(f"Error flushing batch for {record_key}: {exc}") + except BaseException as e: + permanent = isinstance(e, Exception) and _permanent_commit_failure(e) + 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 + # it was written (ITL-1403). The flush is the point of truth. Records + # waiting on this commit (pipeline records of these results) are + # withdrawn with it (ITL-1412). + 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." + ) + self._pending_commits.forget(record_key, pending_ids) + self._pending_commits.finish(record_key, committed=False) + logger.error(f"Refused batch for {record_key}: {refused}") + raise refused from 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 + # fail the same way, so the batch leaves the queue and nothing of it + # was written (ITL-1403); records waiting on it are withdrawn. + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + 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" + ), + ) + self._pending_commits.forget(record_key, pending_ids) + self._pending_commits.finish(record_key, committed=False) + logger.error(f"Refused batch for {record_key}: {refused}") + raise refused from e + logger.error(f"Error flushing batch for {record_key}: {e}") self._pending_commits.finish(record_key, committed=False) self._pending_commits.restore(record_key, pending_batch, pending_ids) raise diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index 3143463f7..81a4f77c0 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -439,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"])) @@ -458,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()), 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..971e48cf4 --- /dev/null +++ b/tests/test_databases/test_delta_add_time_property.py @@ -0,0 +1,265 @@ +"""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, cast + +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()} +# 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: + 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 _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, 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 as error: # noqa: BLE001 # the outcome is the subject + return "refused when added", queued(), error + try: + db.flush() + 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) +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, 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 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})" + ) + + +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 + + +@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" + _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_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index d37919f53..6309da989 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) 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) @@ -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: 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]])), + 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_commit_failures.py b/tests/test_databases/test_delta_commit_failures.py new file mode 100644 index 000000000..80a26be03 --- /dev/null +++ b/tests/test_databases/test_delta_commit_failures.py @@ -0,0 +1,465 @@ +"""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, + OrcapodDatabaseReadError, + UnstorableColumnError, +) +from tests.test_databases.test_delta_refused_before_queueing import ( + _legacy_case_only_table, # pyright: ignore[reportPrivateUsage] +) + +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 + + +# ── 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 + + +# ── 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] + 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() + 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( + "refusal", ["SchemaMismatchError", "duplicate name"], ids=lambda r: str(r) +) +def test_a_refused_result_batch_withdraws_the_records_waiting_on_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, refusal: str +) -> None: + """The flush's refusal goes through the pending-commit path (ITL-1412): a record + guarded on a result batch that Delta refuses permanently is withdrawn with it, and + a later, successful commit of the same table never publishes it.""" + from deltalake.exceptions import SchemaMismatchError + + real_write = deltalake.write_deltalake + refusals = [True] + + def refuse_once(table_or_uri: Any, *args: Any, **kwargs: Any) -> None: + if refusals and "results" in str(table_or_uri): + refusals.pop() + if refusal == "SchemaMismatchError": + raise SchemaMismatchError("Schema error: refused for the test") + raise Exception( # deltalake's own form of this refusal: a bare Exception + "External error: Schema error: Duplicate field name " + "(case-insensitive): 'v'" + ) + real_write(table_or_uri, *args, **kwargs) + + monkeypatch.setattr(deltalake, "write_deltalake", refuse_once) + db = DeltaTableDatabase(tmp_path) + results, records = ("results",), ("records",) + + def row(rid: bytes, value: int) -> pa.Table: + return pa.table({"rid": pa.array([rid], pa.large_binary()), "v": [value]}) + + db.add_records(results, row(b"r1", 1), record_id_column="rid") + dependency = db.pending_result(results, b"r1") + assert dependency is not None + with db.guard_record(records, b"p1", dependency): + db.add_records(records, row(b"p1", 1), record_id_column="rid") + with pytest.raises((InputValidationError, UnstorableColumnError)): + db.flush_batch(results) + assert not db._pending_batches.get("results") # pyright: ignore[reportPrivateUsage] + # A later result commits; the withdrawn record must not ride on it. + db.add_records(results, row(b"r2", 2), record_id_column="rid") + db.flush() + db.flush() # anything the commit released is published by now + stored = DeltaTableDatabase(tmp_path).get_all_records( + 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_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 8948b9db8..4af6e7292 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -469,24 +469,24 @@ 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: 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())])) - append(db, rows([b"b"], pa.array([[{"a": 2, "b": 3}]], evolved))) + 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" ) 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_refused_before_queueing.py b/tests/test_databases/test_delta_refused_before_queueing.py new file mode 100644 index 000000000..03f013147 --- /dev/null +++ b/tests/test_databases/test_delta_refused_before_queueing.py @@ -0,0 +1,821 @@ +"""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, + OrcapodDatabaseReadError, + 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 _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}]) + + +# (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=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"] + + +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_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) + _add(db, _rows(b"2", x=appended)) # accepted when added + _refused_once_at_flush(db) + 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") + + +@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, first: bytes, second: bytes +) -> None: + """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( + unit_type(serial), pa.array([value], pa.int64()) + ) + + db = DeltaTableDatabase(tmp_path) + _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, 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 _path_column() -> Any: + converter = get_default_context().type_converter + table = converter.python_dicts_to_arrow_table( + [{"x": Path("/a")}], python_schema={"x": Path | None} + ) + 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, _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 == field.type + assert back.sort_by("rid").column("x").to_pylist() == [value, None] + + +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(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 (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: + 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") + + +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", **{k: pa.array(v) for k, v in columns.items()})) + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + db.flush() + + +# 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, flush=True) + 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 (CodeRabbit on PR 504): another identifier, refused when added by ITL-1371's + rule (PR 492), nothing queued.""" + + 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")) # ITL-1371: refused when added + 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_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 + 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), + } + ) + + db.add_records( + PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + ) # accepted when added, on every route + if evolution: + _refused_once_at_flush(db) + assert _stored_ids(tmp_path) == [b"1"] + else: + db.flush() + 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)) + ) + + if variant in ("a readable older identifier", "another name"): + # Another identifier is ITL-1371's rule (on main, PR 492): refused when the + # rows are added, on every route, whatever schema evolution says. + with pytest.raises(InputValidationError, match="logical type"): + db.add_records( + PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 1 + ) + assert _stored_ids(tmp_path) == [b"1"] + else: + db.add_records( + PATH, rows, record_id_column="rid", skip_duplicates=len(ids) == 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 == 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", "\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.""" + 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) + + +# ── 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( + tmp_path: Path, evolution: bool +) -> None: + """Third review: a bare null queued, then a null carrying a foreign identifier. + The foreign identifier is refused when added by ITL-1371's rule (PR 492, on main), + which judges each add on its own; the queued bare null is untouched and stored.""" + 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"", + }, + ) + with pytest.raises(InputValidationError, match="review.different"): + _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] + + +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: what holds when the rows are added may change before the flush. + List items widening to nullable (non-null values) with schema evolution off: a + MERGE that keeps the stored schema stores them. When schema evolution is turned on + before the flush, the commit sends the changed record and Delta refuses it: the + flush raises once, nothing stays queued. When another writer deletes a stored row, + the commit is still decided at the flush, and the rows are stored.""" + 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=False) + _add(db, _rows(b"1", x=pa.array([[1]], stored)), flush=True) + rows = pa.table( + { + "rid": pa.array([b"1", b"2"], pa.large_binary()), + "x": pa.array([[1], [2]], wider), + } + ) + 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'") + db.flush() + assert _stored_ids(tmp_path) == [b"1", b"2"] + assert not db._pending_batches # pyright: ignore[reportPrivateUsage] + 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] + + +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] + + +# (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"] + + +@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"] + + +@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 87d368bd3..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) @@ -449,14 +456,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 +475,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..c15dd6291 100644 --- a/tests/test_databases/test_delta_struct_evolution.py +++ b/tests/test_databases/test_delta_struct_evolution.py @@ -3,9 +3,15 @@ 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 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 new list) is refused naming the column and the path, before anything is buffered. @@ -88,19 +94,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 +156,65 @@ 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_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( + PATH, + _rows([b"1"], k=([7], pa.int64()), x=(first_values, first)), + record_id_column="id", + flush=True, + ) + 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") + 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 +391,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 +535,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/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", ] diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 12882654a..246876cfa 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1085,10 +1085,39 @@ 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 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 +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. 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/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..6387cb5bb --- /dev/null +++ b/tests/test_pipeline/test_delta_refusals_in_jobs.py @@ -0,0 +1,122 @@ +"""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, 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. + +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 ( + InputValidationError, + 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 + # 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"]) +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() 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..11220740d --- /dev/null +++ b/tests/test_pipeline/test_dropped_result_batch.py @@ -0,0 +1,122 @@ +"""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 ITL-1412's (on main, PR 509): the flush's refusal goes through the same +pending-commit path, so the records waiting on the dropped batch are withdrawn. +""" + +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.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import OrcapodDatabaseWriteError, UnstorableColumnError +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.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(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(): + 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] == [] + + +@function_pod(output_keys=["doubled"]) +def _double(x: int | None) -> int: + return 2 * (x or 0) + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +def test_a_result_batch_delta_refuses_withdraws_its_pipeline_records( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, use_async: bool +) -> None: + """A result batch the commit refuses permanently (deltalake's own + ``SchemaMismatchError`` on the result table): the flush raises it once + (``InputValidationError``, the job's ``OrcapodDatabaseWriteError`` cause), the batch + leaves the queue, and the pipeline records waiting on it are never published.""" + import deltalake + from deltalake.exceptions import SchemaMismatchError + + from orcapod.errors import InputValidationError + + real_write = deltalake.write_deltalake + + def refuse_results(table_or_uri: Any, *args: Any, **kwargs: Any) -> None: + if "_result" in str(table_or_uri): + raise SchemaMismatchError("Schema error: refused for the test") + real_write(table_or_uri, *args, **kwargs) + + monkeypatch.setattr(deltalake, "write_deltalake", refuse_results) + 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: + _double.pod(source, label="double") + with pytest.raises(OrcapodDatabaseWriteError) as info: + if use_async: + asyncio.run(job.run_async()) + else: + job.run() + assert isinstance(info.value.__cause__, InputValidationError) + assert "Delta refused the commit" in str(info.value.__cause__) + 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] == [] 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" },