Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions changelog.d/ITL-1403.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 4 additions & 2 deletions docs/dev/design_issues/ITL-1371-LI1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
69 changes: 69 additions & 0 deletions docs/dev/scripts/itl_1403/compare.py
Original file line number Diff line number Diff line change
@@ -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"], "<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())
137 changes: 137 additions & 0 deletions docs/dev/scripts/itl_1403/interop.py
Original file line number Diff line number Diff line change
@@ -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.

<python A> interop.py run STORE first
<python B> interop.py run STORE second # B reads and appends to A's tables
<python A or B> 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]))
17 changes: 17 additions & 0 deletions docs/dev/scripts/itl_1403/interop.sh
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading