Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
23 changes: 23 additions & 0 deletions changelog.d/ITL-1371.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
### Fixed

- **An append of another logical type is refused:** every database (in-memory, Delta Lake,
and the connector databases, directly and through `ExtensionAwareDatabase`) refuses rows
whose column, or a field nested in it (a struct child, a list item, a map key or item),
has the stored or pending column's storage type but another logical type identifier:
another extension name, the same name with other extension metadata, or a logical type
where the stored column has none, and the reverse. It raises `InputValidationError`
naming the column and both identifiers before anything is written, whatever
`skip_duplicates`: an append of only rows already stored is refused too (before, Delta
wrote nothing and raised nothing for it; the in-memory and connector databases already
refused it when the change showed in the field annotation). Before, such rows were
accepted in several cases (a Delta column in the annotated form, extension arrays whose
types differ only in their metadata) and read back as the stored type. An append with
the same identifier is decided as before, except at Delta's MERGE (a batch with an id
already stored), which now writes the identifier bytes Arrow holds, not what the
extension's serializer answers when asked again: with a serializer that changed or
raises, the stored form (and, for a raising one, the verdict) differs. Identifiers are
compared as stored bytes. A place of a stored Delta table whose identifier neither the log
nor the column's recorded type gives (a list item or map item of extension values,
ITL-1372) is decided as before. A zero-row append, and an encoding the database cannot
write, keep their verdict.
(ITL-1371)
4 changes: 3 additions & 1 deletion docs/dev/design_issues/ITL-1367-CO1.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ table between the flush's check and its write (a DDL in that window) is not seen
of `a` to `A` then stores the value under `A`, since SQLite resolves names without case, as
on main. Through `ExtensionAwareDatabase`, rows of another logical type over the same
storage type in the SAME column order are accepted and read back as the held logical type
(ITL-1371).
(ITL-1371 now refuses them, in either column order, wherever the held identifier is known:
not over a Delta column with no identifier and no recorded Arrow type, such as one written
from a dictionary of extension values, where the identity rule abstains; ITL-1372).

Not covered: the order of a struct's fields (a struct with its fields in another order is
another type here, and the fake keeps struct children as written): ITL-1368. A canonical
Expand Down
107 changes: 107 additions & 0 deletions docs/dev/design_issues/ITL-1371-LI1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
## `src/orcapod/databases/` — appending another logical type

### LI1 — An append of another logical type over the same storage type was accepted and read back as the stored type
**Status:** resolved
**Severity:** critical
**Issue:** ITL-1371

A table holds one logical type per column and per nested field. An append that gave a
column the same storage type but another logical type identifier (another extension name,
the same name with other extension metadata, or a logical type where the stored column has
none, and the reverse) was accepted in several places, and every appended row then read back
as the stored type, a type it was never written as:

- `DeltaTableDatabase`, a top-level column in the annotated form (storage type with
`ARROW:extension:name` / `ARROW:extension:metadata` field metadata, the form
`ExtensionAwareDatabase` passes on and a stored column reads back in): `_column_change`
left a logical column's extension keys out of its metadata comparison and relied on the
type check, which compares storage types only. This is the case reported.
- Extension arrays (in-memory and Delta, at every depth): pyarrow's equality of two Python
extension types ignores their serialized metadata, so two types with one name and other
metadata compare equal; the ITL-1334 checks (`appended_field_change`) treat an extension
type as a leaf and left it to that equality.
- `DeltaTableDatabase`, a committed table: the held column is the storage type with the
annotation, while the rows given are extension arrays, and the same short cut applied.

**Fix:** one rule, `databases/utils.logical_identity_change`, over `IdentityNode`s
(`identity_node` for a field as given, `first_logical_identity_change` for schemas): at every
column and nested place (struct children by name, list items of every kind including list
views, map keys and items, union members, dictionary values, run-end encoded children, and
an extension type held directly as another's storage, one extension level at a time; a
dictionary is an encoding, so its values stand where it stands), the raw identifier bytes
must be the held ones; no logical type is an identifier too. The bytes are those Arrow holds
(an extension type's C data interface export, never its serializer called again; for an
extension type whose storage is another extension type, which Arrow cannot export, that
level is not known and not compared, its storage still is) or the `ARROW:extension:*`
annotation; never decoded to decide (a name that is not UTF-8 is shown as a bytes literal,
`b'\xff'`, a form no text name takes), never Arrow type equality. A given column's field and
each of its chunks are compared, a zero-length chunk too (pyarrow lets the chunks of one
column carry other extension metadata and other nested annotations). Places pair by name, or by
occurrence where a name repeats among siblings (Arrow allows two struct children, union
members or columns of one name), never by name alone. Only a bare `pa.null()` claims no
type; an annotated null claims its annotation.

The rule only ADDS a refusal where it KNOWS the identifiers differ: from the fields as given
(in-memory, a pending batch, a connector's stored schema) and, for a stored Delta table, from
the Delta log and the column's recorded Arrow type (`_delta_identity_node`). A stored Delta
place's identifier is known from, in this order: the physical field's own annotation (the log
keeps the field metadata of a column and of each struct child byte for byte); else the place
inside the column's recorded Arrow type (`orcapod:arrow_type`): its annotation there, or no
logical type where the recorded place is plain; else it is unknown and the rule abstains.
Missing physical metadata alone never proves "no logical type": a list item or map key or
item keeps none in the log (ITL-1372), a dictionary child is written as plain values (its
identifier stays in the record), and a column written from a dictionary of extension values
records no type at all (pre-existing, ITL-1372), so there the absence proves nothing,
whatever the given encoding; where the record says plain, another identifier is refused,
dictionary-encoded or not. A recorded place the Arrow registry reads back as an extension
type is unknown too (the registry may give other bytes than the ones stored), and so is a
record that cannot be read. Also where a side is an untyped
null (`pa.null()`, which holds no value and claims no type), it abstains, and the database's
other checks decide exactly as before. A place only one side has (struct evolution, another
kind of type) is left to those checks too. The ITL-1334 comparison is unchanged and runs after
it. In-memory and connector databases apply it in `add_records`, Delta in `add_records`
(`_identity_refusal`, pending and stored) and again at flush (`_append_refusal`).
A refusal raises `InputValidationError` naming the column, the path and both identifiers'
text, before anything is buffered, whatever `skip_duplicates`: an append whose column carries
a known different identifier is refused, duplicate-only or not (on main a duplicate-only
append with `skip_duplicates` was a silent no-op; nothing was or is written), while a
duplicate-only append of the same identifier stays a no-op. The order is the same with
either setting: in Delta the rule reads the log and the columns' recorded Arrow types
(decoding a record is part of the rule: a record that cannot be decoded only makes its
places unknown, it raises nothing) and runs first, before the duplicate scan and the
ordinary held-column checks, so no read failure can come before it; only when it passes or
abstains does the duplicate scan run, and a read failure there propagates as a read
failure. The database type matrix appends each logical type again under another extension
name, which every database refuses.

Delta decides every refusal on the version stored now: a difference found on the handle it
holds (loaded at its last load or flush) is compared again on the table loaded afresh, so a
held handle never refuses what a reopened one accepts; accepting reads the held handle (no
extra read per append), and an accept is checked again at flush, against the version then
loaded, before anything is written. Two differences remain. One writes nothing either way:
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
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).

Limits and differences from main, stated: Delta's MERGE source (a batch with an id already
stored) now carries the identifier bytes Arrow holds, not the serializer asked again, so for
an extension whose serializer changes after its type was made, or raises, the stored form
(and, for a raising serializer, the verdict: main failed the commit) differs from main in
that one case. A decode failure of the duplicate scan that is a `TypeIdentityError`
propagates as itself (main's ITL-881 carve-out), not as `OrcapodDatabaseReadError`. A
zero-row append, and an encoding the database cannot write (refused as unstorable before the
rule: metadata that is not UTF-8 in Delta, any field metadata in SQLite), are outside the
identity rule and keep main's verdict.

So, apart from the stated MERGE case, the only appends whose verdict differs from main are
those with a known different identifier. Where Delta stored a nested extension type as plain storage (a list item or map
value, ITL-1372) the rule abstains and main's verdict stands (a second map is accepted with
any identifier, a second list refused for its item's name); a column Delta wrote from a
dictionary of extension values takes the same type again, as a dictionary or not, as on
main. Also pre-existing (ITL-1372):
Delta refuses any second append of a registered logical type nested in a column with a
recorded type, even the identical one. Probe: `docs/dev/scripts/itl_1371_logical_identity_appends.py`.
180 changes: 180 additions & 0 deletions docs/dev/scripts/itl_1371_logical_identity_appends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
"""Which appends of another logical type identifier each database accepts (ITL-1371).

usage: PYTHONPATH=. uv run python docs/dev/scripts/itl_1371_logical_identity_appends.py

A table holds a column ``x`` of logical type ``probe.a`` (metadata ``m``), at the top
level, as a struct child, as a list item or as a map item; a second batch appends ``x``
with the same storage type and the same, or another, identifier, either as a real Arrow
extension array or as the annotated physical form (storage type with
``ARROW:extension:name`` / ``ARROW:extension:metadata`` field metadata), against the
pending batch, the committed table, and (Delta, SpiralDB fake) a reopened database.
Prints ``accepted`` or ``refused: <error>`` per case.
"""

from __future__ import annotations

import itertools
import os
import sys
import tempfile
import warnings
from pathlib import Path
from typing import Any

import pyarrow as pa

from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase
from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase
from orcapod.databases.spiraldb_connector import SpiralDBConnector
from orcapod.databases.sqlite_connector import SQLiteConnector

NAME = b"ARROW:extension:name"
META = b"ARROW:extension:metadata"


def _probe_class(name: str) -> Any:
"""An extension type named ``name`` whose metadata is any bytes."""

class Probe(pa.ExtensionType):
def __init__(self, meta: bytes) -> None:
self._meta = meta
super().__init__(pa.large_string(), name)

def __arrow_ext_serialize__(self) -> bytes:
return self._meta

@classmethod
def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any:
return cls(serialized)

return Probe


PROBES: dict[str, Any] = {name: _probe_class(name) for name in ("probe.a", "probe.b")}


IDENTIFIERS = {
"same": ("probe.a", b"m"),
"other name": ("probe.b", b"m"),
"other metadata": ("probe.a", b"n"),
"plain": None,
}


def leaf(identifier: tuple[str, bytes] | None, form: str, values: list[str]):
"""The leaf field and array of ``x``."""
storage = pa.array(values, pa.large_string())
if identifier is None:
return pa.field("v", pa.large_string()), storage
if form == "extension":
ext = PROBES[identifier[0]](identifier[1])
return pa.field("v", ext), pa.ExtensionArray.from_storage(ext, storage)
meta = {NAME: identifier[0].encode(), META: identifier[1]}
return pa.field("v", pa.large_string(), metadata=meta), storage


def column(identifier, form: str, depth: str, values: list[str]):
field, array = leaf(identifier, form, values)
n = len(values)
if depth == "top":
return field.with_name("x"), array
if depth == "struct":
arr = pa.StructArray.from_arrays([array], fields=[field])
return pa.field("x", arr.type), arr
if depth == "list":
offsets = pa.array(list(range(n + 1)), pa.int64())
typ = pa.large_list(field.with_name("item"))
arr = pa.LargeListArray.from_arrays(offsets, array, type=typ)
return pa.field("x", typ), arr
if depth == "map value":
# The stubs type pa.map_'s arguments as types and from_arrays' offsets as
# int64; pyarrow takes key and item fields, and int32 offsets for a map.
offsets: Any = pa.array(list(range(n + 1)), pa.int32())
keys = pa.array([f"k{i}" for i in range(n)], pa.large_string())
typ: Any = pa.map_(
pa.field("key", pa.large_string(), nullable=False), # pyright: ignore[reportArgumentType]
field.with_name("value"), # pyright: ignore[reportArgumentType]
)
from_arrays: Any = pa.MapArray.from_arrays
arr = from_arrays(offsets, keys, array, type=typ)
return pa.field("x", typ), arr
raise AssertionError(depth)


def table(identifier, form, depth, ids: list[bytes]):
field, arr = column(identifier, form, depth, [i.decode() for i in ids])
return pa.Table.from_arrays(
[pa.array(ids, pa.large_binary()), arr],
schema=pa.schema([pa.field("id", pa.large_binary()), field]),
)


def open_db(kind: str, root: Path):
if kind == "in-memory":
return InMemoryArrowDatabase()
if kind == "Delta":
return DeltaTableDatabase(root / "delta")
if kind == "SQLite":
return ConnectorArrowDatabase(SQLiteConnector(str(root / "s.db")))
if kind == "SpiralDB":
return ConnectorArrowDatabase(SpiralDBConnector("p"))
raise AssertionError(kind)


def case(kind, state, form, depth, change, root: Path) -> str:
path = ("t",)
db = open_db(kind, root)
base = IDENTIFIERS["same"]
try:
db.add_records(
path,
table(base, form, depth, [b"1"]),
record_id_column="id",
flush=state != "pending",
)
except Exception as e: # noqa: BLE001
return f"first write refused: {type(e).__name__}"
if state == "reopened":
db = open_db(kind, root)
incoming = table(IDENTIFIERS[change], form, depth, [b"2"])
try:
db.add_records(path, incoming, record_id_column="id")
db.flush()
except Exception as e: # noqa: BLE001
return f"refused: {type(e).__name__}: {(str(e).splitlines() or [''])[0][:110]}"
return "accepted"


def main() -> None:
warnings.simplefilter("ignore")
kinds = ["in-memory", "Delta", "SQLite", "SpiralDB"]
with tempfile.TemporaryDirectory() as tmp:
from tests.test_databases import fake_pyspiral

with fake_pyspiral.install(Path(tmp) / "spiral"):
fake_pyspiral.FakeSpiral().project("p")
for i, (kind, state, form, depth, change) in enumerate(
itertools.product(
kinds,
("pending", "committed", "reopened"),
("extension", "annotated"),
("top", "struct", "list", "map value"),
IDENTIFIERS,
)
):
if state == "reopened" and kind == "in-memory":
continue
root = Path(tmp) / str(i)
root.mkdir()
if kind == "SpiralDB":
fake_pyspiral.FakeSpiral().project("p")
print(
f"{kind:9} {state:9} {form:9} {depth:9} {change:14} "
f"{case(kind, state, form, depth, change, root)}"
)


if __name__ == "__main__":
main()
sys.stdout.flush()
os._exit(0)
6 changes: 4 additions & 2 deletions docs/reference/database-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ How it is measured: a table holding two columns of the type (the second nullable
null row) is written with `add_records` and flushed. The same type is then appended as
slices of a larger table (three rows over two chunks, then the null row alone), and the
same columns with other field metadata (the column's own, and a nested field's) are
appended, which every database must refuse, naming the column. Every batch written is read
back with `get_all_records`.
appended, which every database must refuse, naming the column; for a logical type, so are
the same values under another logical type identifier (another extension name over the
same storage), which would otherwise read back as the stored type. Every batch written is
read back with `get_all_records`.
The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which
models what SpiralDB does to a column (no SpiralDB is used). No database tells tag
columns from data columns, so a type is kept or refused the same way in either role.
Expand Down
2 changes: 1 addition & 1 deletion src/orcapod/databases/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
from .extension_aware_database import ExtensionAwareDatabase
from .in_memory_databases import InMemoryArrowDatabase
from .noop_database import NoOpArrowDatabase
from .postgresql_connector import PostgreSQLConnector
from .spiraldb_connector import SpiralDBConnector
from .spiraldb_nullability import read_nullability_record, write_nullability_record
from .sqlite_connector import SQLiteConnector
from .postgresql_connector import PostgreSQLConnector

__all__ = [
"ConnectorArrowDatabase",
Expand Down
Loading
Loading