diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 0a1ff215c..a8d4d29f6 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -330,6 +330,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | | SpiralDB nullability record | the nullability path list | SHA-256 hex | chunk key and checksum of a stored record (a name) | `databases/spiraldb_nullability.py:_encode`, `databases/spiraldb_nullability.py:read_nullability_record` | +| SpiralDB store manifest | the manifest's JSON payload (record path and Arrow schema) | SHA-256 hex | key and checksum of the manifest in a table's metadata (a name) | `databases/spiral_store.py:_digest` | | synthesized struct class name | the field signature | MD5 hex, 8 digits | a Python class name (a name) | (not reached by a traced test) `semantic_types/universal_converter.py` | | random ids | nothing | `uuid4`, `uuid7` | run ids, datagram and record uuids, observer ids, correlation keys | (not hashes) | | unused code | Arrow tables | SHA-256, SHA3, BLAKE2b | no caller; removal is ITL-1156 | (not reached) `hashing/arrow_utils.py`, `hashing/arrow_serialization.py` | diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py new file mode 100644 index 000000000..18fdf66b6 --- /dev/null +++ b/src/orcapod/databases/spiral_store.py @@ -0,0 +1,1112 @@ +"""The codec of an Orcapod store table in SpiralDB (ITL-1446). + +Pure functions, with no pyspiral: they say how a table Orcapod stores is written to +SpiralDB and how it is read back. Nothing calls them yet. The design is +``docs/dev/specs/itl-1446-spiral-columns.md`` (sections 3.1 to 3.3). + +* **Names.** ``encode_name`` gives a value column, or a struct field at any depth, a + name SpiralDB accepts. The key column ``__record_id`` keeps its name. Nothing decodes + a name: a read looks for exactly the stored names the manifest lists. +* **Types.** Rows are written in a *physical* form (``physical_schema``, ``encode_rows``) + and restored to the *logical* one (``decode_rows``). A type either comes back exactly + or is refused. Every refusal of a type, a name or a value that may be lifted is an + entry of one table, ``REFUSALS``. +* **The manifest.** One a table, in its key-value metadata, written at creation and + never changed (``manifest_entries``, ``read_manifest``): the record path, the kind, + the logical schema, and the stored names at every depth. + +Logical types are handled by their identifier (extension name and metadata) alone, as +``ARROW:extension:*`` field metadata over the storage type: neither writing nor reading +a manifest consults the types registered in the process. +``canonical_form.declaration_form_schema`` makes them live. + +A SpiralDB store is a set of rows: the order of rows is not kept. An order-sensitive +step (``Batch``) over a stored source may therefore group differently than over a Delta +store. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import re +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, cast + +import numpy as np +import pyarrow as pa + +from orcapod.databases.utils import identity_node +from orcapod.logical_types.canonical_form import ( + EXTENSION_METADATA_KEY, + EXTENSION_NAME_KEY, +) +from orcapod.utils import arrow_utils + +KEY_COLUMN = "__record_id" + +# ------------------------------------------------------------------------ errors + + +class SpiralStoreError(ValueError): + """A column, value, name or manifest the codec refuses. + + Attributes: + reason: What is wrong. + path: Where, from the column inwards: column name, struct field names and + ``"[]"`` for a list's items. Empty when the error is not about a column. + """ + + def __init__(self, reason: str) -> None: + self.reason = reason + self.path: tuple[str, ...] = () + super().__init__(reason) + + def __str__(self) -> str: + if not self.path: + return self.reason + where = repr(self.path[0]) + if len(self.path) > 1: + where += f" (at {list(self.path[1:])})" + return f"column {where}: {self.reason}" + + +class UnstorableInSpiralError(SpiralStoreError): + """Rows or a schema SpiralDB would not give back exactly. Nothing was written.""" + + +class StoredRowsError(SpiralStoreError): + """Rows read from SpiralDB are not what the manifest says was written.""" + + +class ManifestError(SpiralStoreError): + """A manifest cannot be read in full, is not the one table's only one, is not the one + asked for, or does not fit in a table's metadata.""" + + +@contextmanager +def _at(segment: str) -> Iterator[None]: + """Add ``segment`` in front of the path of an error raised inside.""" + try: + yield + except SpiralStoreError as exc: + exc.path = (segment, *exc.path) + raise + + +# ------------------------------------------------------------------------- names + +_MARK = "ox_" +_CONTROL = "\x00-\x1f\x7f" +_NOT_PLAIN = re.compile(f"[.$*{_CONTROL}]") +_ESCAPED = re.compile(f"[.$*;{_CONTROL}]") + + +def encode_name(name: str) -> str: + """Return the stored name of a value column or a struct field. + + A plain name is stored as it is. Any other one (empty, starting with ``__`` or + ``ox_``, or holding ``.``, ``$``, ``*`` or a control character) is ``ox_`` followed + by the name with each of those characters, and ``;``, as ``;`` and two upper-case + hex digits. Injective. + + Args: + name: The Orcapod name. + + Returns: + The stored name. It is never empty, never starts with ``__`` and holds none of + the characters above. + + Raises: + UnstorableInSpiralError: If the name is not UTF-8 text (a lone surrogate). + """ + _require_utf8(name) + if name and not name.startswith(("__", _MARK)) and not _NOT_PLAIN.search(name): + return name + return _MARK + _ESCAPED.sub(lambda m: f";{ord(m[0]):02X}", name) + + +def _require_utf8(text: str) -> None: + """Refuse text with no UTF-8 form: a lone surrogate.""" + try: + _ = text.encode("utf-8") + except UnicodeEncodeError as exc: + raise UnstorableInSpiralError(f"{text!r} is not UTF-8 text") from exc + + +# ------------------------------------------------------------- what is refused, and why + + +@dataclass(frozen=True) +class Refusal: + """Something the store does not keep. + + Attributes: + what: What it is. + why: The evidence: what the service or its client was measured to do, or that + it is not measured. + matches: Whether an Arrow type is it; ``None`` when it is not about a type. + """ + + what: str + why: str + matches: Callable[[pa.DataType], bool] | None = None + + def error(self) -> UnstorableInSpiralError: + """The refusal as an error.""" + return UnstorableInSpiralError( + f"a SpiralDB store refuses {self.what} ({self.why})" + ) + + +_types = pa.types +_NOT_MEASURED = "not measured" +_REFUSED_LIVE = "the service or its client refuses it" +NULL_STRUCT = Refusal("a null struct", _REFUSED_LIVE) +EMPTY_STRUCT = Refusal("a struct with no fields", _REFUSED_LIVE) +NO_ROWS = Refusal("a write of no rows", "the client panics") +NULL_LIST_OF_STRUCTS = Refusal( + "a null fixed-size list of structs", _NOT_MEASURED + "; it holds null structs" +) +RENAMED_MAP = Refusal( + "a map whose fields are not named key and value", "Arrow IPC renames them" +) +MAP_METADATA = Refusal("field metadata inside a map", "decided in the design") +VIEW = Refusal( + "a string view or binary view", "Orcapod's tables hold the large variants" +) +REFUSALS: tuple[Refusal, ...] = ( + NULL_STRUCT, + EMPTY_STRUCT, + NO_ROWS, + NULL_LIST_OF_STRUCTS, + RENAMED_MAP, + MAP_METADATA, + VIEW, + # Substitutes that held live, not used yet: large_binary, int64. + Refusal("a fixed-size binary", _REFUSED_LIVE, _types.is_fixed_size_binary), + Refusal("a duration", _REFUSED_LIVE, _types.is_duration), + Refusal("an interval", _REFUSED_LIVE, _types.is_interval), +) +"""Every refusal that new evidence or a decision may lift. A type that is in neither this +table nor ``_NATIVE``, and that ``_physical_type`` does not map, is refused too.""" + +_NATIVE: tuple[Callable[[pa.DataType], bool], ...] = ( + _types.is_boolean, + _types.is_integer, + _types.is_float16, + _types.is_float32, + _types.is_float64, + _types.is_decimal128, + _types.is_decimal256, + _types.is_date32, + _types.is_date64, + _types.is_null, + _types.is_large_string, + _types.is_large_binary, +) +"""Types written as they are (measured live, bit for bit).""" + + +# -------------------------------------------------------------- types, as declared + + +def _without_identifier(field: pa.Field[Any]) -> dict[bytes, bytes]: + """The field's metadata without the two keys that hold a logical type identifier.""" + metadata = cast("dict[bytes, bytes]", dict(field.metadata or {})) + metadata.pop(EXTENSION_NAME_KEY, None) + metadata.pop(EXTENSION_METADATA_KEY, None) + return metadata + + +def _logical_field(field: pa.Field[Any]) -> pa.Field[Any]: + """Return a column in the form the manifest records. + + Types are in their large variants. A logical type, live or annotated, is its + storage type with its identifier as field metadata, the metadata key always + present. A logical type below the top of the column is refused. + """ + node = identity_node(field) + if not node.known: + raise UnstorableInSpiralError("its extension type cannot be identified") + arrow_type = field.type + if node.identifier is not None and EXTENSION_NAME_KEY not in (field.metadata or {}): + arrow_type = cast(Any, arrow_type).storage_type + _refuse_nested_identifier(arrow_type) + if _holds(arrow_type, _types.is_string_view) or _holds( + arrow_type, _types.is_binary_view + ): + raise VIEW.error() + metadata = _without_identifier(field) + if node.identifier is not None: + metadata[EXTENSION_NAME_KEY], metadata[EXTENSION_METADATA_KEY] = node.identifier + return pa.field( + field.name, + arrow_utils.normalize_to_large_types(arrow_type, keep_null=True), + field.nullable, + cast(Any, metadata or None), + ) + + +def _refuse_nested_identifier(arrow_type: Any) -> None: + """Refuse a logical type at or below ``arrow_type``, live or annotated.""" + if isinstance(arrow_type, pa.BaseExtensionType): + raise UnstorableInSpiralError("a logical type nested in another type") + for child in _children(arrow_type): + name = child.name # read also for a list's item, whose name must be text too + with _at(name if pa.types.is_struct(arrow_type) else "[]"): + if EXTENSION_NAME_KEY in (child.metadata or {}): + raise UnstorableInSpiralError("a logical type nested in another type") + _refuse_nested_identifier(child.type) + + +def _children(arrow_type: Any) -> list[pa.Field[Any]]: + """The child fields of a struct or a list; of other nested types, what they have.""" + return [arrow_type.field(i) for i in range(arrow_type.num_fields)] + + +def _holds(arrow_type: Any, matches: Callable[[pa.DataType], bool]) -> bool: + """Whether ``arrow_type`` is, or holds at any depth, a type that matches.""" + return matches(arrow_type) or any( + _holds(child.type, matches) for child in _children(arrow_type) + ) + + +def _holds_metadata(arrow_type: Any) -> bool: + """Whether a field below ``arrow_type``, at any depth, has metadata.""" + return any(f.metadata or _holds_metadata(f.type) for f in _children(arrow_type)) + + +def _stored_names(names: list[str]) -> list[str]: + """Return the stored names of siblings: columns, or the fields of one struct. + + SpiralDB folds neither case nor Unicode normal forms (measured live), so names that + differ are different. + """ + stored: list[str] = [] + for name in names: + with _at(name): + stored.append(encode_name(name)) + if len(set(stored)) != len(stored): + repeated = sorted({n for n in names if names.count(n) > 1}) + raise UnstorableInSpiralError(f"names used more than once: {repeated}") + return stored + + +def _stored_columns(names: list[str]) -> list[str]: + """The stored names of a table's columns: the key column keeps its own. + + No encoded name starts with ``__``, so none is the key column's. + """ + stored = iter(_stored_names([n for n in names if n != KEY_COLUMN])) + return [n if n == KEY_COLUMN else next(stored) for n in names] + + +def logical_schema(schema: pa.Schema) -> pa.Schema: + """Return ``schema`` in the form the manifest records, or refuse it. + + Args: + schema: The schema of rows to be stored, ``__record_id`` included. + + Returns: + The schema with every type in its large variant and every logical type as its + storage type with its identifier as field metadata. Names, column order, + nullability and metadata are kept at every depth. + + Raises: + UnstorableInSpiralError: If a column cannot be stored exactly, naming it, or if + the table has no single key column, no value column, a repeated name or a + name that is not UTF-8. + """ + try: + return _logical_schema(schema) + except UnicodeDecodeError as exc: + # pyarrow holds a name of any bytes, and fails where it is read as text. + raise UnstorableInSpiralError(f"a name is not UTF-8 text ({exc})") from exc + + +def _logical_schema(schema: pa.Schema) -> pa.Schema: + """``logical_schema``, for names that can be read.""" + fields: list[pa.Field[Any]] = [] + for field in schema: + with _at(field.name): + logical = _logical_field(field) + _ = _physical_type(logical.type) + if field.name == KEY_COLUMN and ( + logical.type != pa.large_binary() + or EXTENSION_NAME_KEY in (logical.metadata or {}) + ): + raise UnstorableInSpiralError("the key column must be binary") + fields.append(logical) + _ = _stored_columns(schema.names) + if schema.names.count(KEY_COLUMN) != 1: + raise UnstorableInSpiralError(f"not exactly one key column {KEY_COLUMN!r}") + if len(fields) < 2: + raise UnstorableInSpiralError("no column beside the key column") + return pa.schema(fields, metadata=cast(Any, schema.metadata)) + + +def _is_list(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` is a variable-size list of either width.""" + return pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type) + + +def _physical_type(arrow_type: pa.DataType) -> pa.DataType: + """Return the type a logical type (``_logical_field``) is written as, or refuse it. + + The one traversal of a type: struct fields and the items of every list kind, to any + depth. A logical type's storage is traversed as any other type. Struct fields get + encoded names; sibling names must differ. A struct is never null (``_encode``). + """ + t = pa.types + logical: Any = arrow_type + if t.is_timestamp(arrow_type) or t.is_time64(arrow_type): + # As integers: the service refuses a timestamp after 9999-12-30 22:00 UTC (so + # ``datetime.max``) and a time of day outside one day, as a whole write. + return pa.int64() + if t.is_time32(arrow_type): + return pa.int32() + if t.is_decimal32(arrow_type) or t.is_decimal64(arrow_type): + # What the service stores them as. + return pa.decimal128(logical.precision, logical.scale) + if t.is_struct(arrow_type): + fields = _children(arrow_type) + if not fields: + raise EMPTY_STRUCT.error() + physical: list[pa.Field[Any]] = [] + for field, stored in zip(fields, _stored_names([f.name for f in fields])): + with _at(field.name): + physical.append(pa.field(stored, _physical_type(field.type))) + return pa.struct(physical) + if _is_list(arrow_type): + with _at("[]"): + return pa.large_list(pa.field("item", _physical_type(logical.value_type))) + if t.is_fixed_size_list(arrow_type): + with _at("[]"): + item = pa.field("item", _physical_type(logical.value_type)) + return pa.list_(item, logical.list_size) + if t.is_map(arrow_type): + key, item = logical.key_field, logical.item_field + if (key.name, item.name) != ("key", "value"): + raise RENAMED_MAP.error() + if _holds_metadata(arrow_type): + raise MAP_METADATA.error() + with _at("[]"): + # Raw pyspiral drops ``keys_sorted``: the manifest restores it. + return pa.map_(_physical_type(key.type), _physical_type(item.type)) + for refusal in REFUSALS: + if refusal.matches is not None and refusal.matches(arrow_type): + raise refusal.error() + if any(matches(arrow_type) for matches in _NATIVE): + return arrow_type + raise UnstorableInSpiralError(f"a SpiralDB store keeps no type {arrow_type}") + + +def physical_schema(schema: pa.Schema) -> pa.Schema: + """Return the schema rows of ``schema`` are written with. + + Args: + schema: The schema of rows to be stored. + + Returns: + Stored names and physical types, in the order given. Every field is nullable + and has no metadata. + + Raises: + UnstorableInSpiralError: As ``logical_schema``. + """ + logical = logical_schema(schema) + return pa.schema( + [ + pa.field(stored, _physical_type(f.type)) + for f, stored in zip(logical, _stored_columns(logical.names)) + ] + ) + + +# ------------------------------------------------------------------ rows, to write + + +def encode_rows(rows: pa.Table) -> pa.Table: + """Return ``rows`` as they are written to SpiralDB. + + Args: + rows: The rows, ``__record_id`` included. + + Returns: + The same rows under ``physical_schema(rows.schema)``. + + Raises: + UnstorableInSpiralError: If the schema is refused (``logical_schema``), or a + column holds a null under a non-null field, a null struct, a refused value, + or a null key, or there are no rows. The column is named. This is per batch: rows of earlier + batches stay stored. + """ + schema = logical_schema(rows.schema) + physical = physical_schema(rows.schema) + if not rows.num_rows: + raise NO_ROWS.error() + columns: list[Any] = [] + for field, stored, column in zip(schema, physical, rows.columns): + with _at(field.name): + if field.name == KEY_COLUMN and column.null_count: + raise UnstorableInSpiralError("a null key") + chunks = [_encode(_storage(c), field) for c in column.chunks] + columns.append(cast(Any, pa.chunked_array)(chunks, type=stored.type)) + return pa.Table.from_arrays(columns, schema=physical) + + +def _storage(array: Any) -> Any: + """The storage of an extension array; any other array as it is.""" + return array.storage if isinstance(array, pa.ExtensionArray) else array + + +def _require_flag(array: Any, field: pa.Field[Any]) -> None: + """Refuse a null under a non-null field.""" + if not field.nullable and array.null_count: + raise UnstorableInSpiralError("a null in a non-nullable field") + + +def _encode(array: Any, field: pa.Field[Any]) -> Any: + """Return ``array``, the values of ``field``, in its physical form. + + Nested types are rebuilt around their converted children, from the rows a reader + sees: what a null list hides is not written. + """ + _require_flag(array, field) + logical: Any = field.type + t = pa.types + if t.is_struct(logical): + if array.null_count: + raise NULL_STRUCT.error() + children: list[Any] = [] + for i, child in enumerate(logical): + with _at(child.name): + children.append(_encode(array.field(i), child)) + fields = _children(_physical_type(logical)) + return pa.StructArray.from_arrays(children, fields=fields) + if _is_list(logical): + with _at("[]"): + items = _encode(array.flatten(), logical.value_field) + return _large_list(array, items, _physical_type(logical)) + if t.is_fixed_size_list(logical): + if array.null_count and _holds_struct_slots(logical.value_type): + raise NULL_LIST_OF_STRUCTS.error() + with _at("[]"): + items = _encode(array.flatten(), logical.value_field) + return _fixed_size_list(array, items, _physical_type(logical)) + if t.is_map(logical): + with _at("[]"): + rows = _map_rows(array) + keys = _encode(array.keys.take(rows), logical.key_field) + items = _encode(array.items.take(rows), logical.item_field) + return _map(array, keys, items, _physical_type(logical)) + if t.is_timestamp(logical) or t.is_time(logical): + return array.view(_physical_type(logical)) # the same integers + return array.cast(_physical_type(logical)) + + +def _holds_struct_slots(item_type: Any) -> bool: + """Whether a null fixed-size list of these items has null structs in its slots.""" + if pa.types.is_fixed_size_list(item_type): + return _holds_struct_slots(item_type.value_type) + return pa.types.is_struct(item_type) + + +# ------------------------------------------------------------- nested array builders + + +def _valid(array: Any) -> Any: + """The rows of ``array`` that are not null, as a NumPy mask.""" + return array.is_valid().to_numpy(zero_copy_only=False) + + +def _lengths(array: Any) -> Any: + """The number of items of each row of a list or map array; 0 of a null row.""" + return np.diff(array.offsets.to_numpy(zero_copy_only=False)) * _valid(array) + + +def _offsets(array: Any) -> Any: + """Offsets from zero for the items of the non-null rows of a list or map array.""" + return np.concatenate([[0], np.cumsum(_lengths(array))]) + + +def _map_rows(array: Any) -> Any: + """Where the items of a map array's non-null rows are, in row order.""" + starts = array.offsets.to_numpy(zero_copy_only=False)[:-1] + lengths, offsets = _lengths(array), _offsets(array) + first = np.repeat(starts - offsets[:-1], lengths) + return pa.array((first + np.arange(offsets[-1])).astype(np.int64)) + + +def _map(array: Any, keys: Any, items: Any, target: Any) -> Any: + """Rebuild a map array around new keys and items, of its non-null rows.""" + return pa.MapArray.from_arrays( + pa.array(_offsets(array).astype(np.int32)), + keys, + items, + type=target, + mask=array.is_null() if array.null_count else None, + ) + + +def _fixed_size_list(array: Any, items: Any, target: Any) -> Any: + """Rebuild a fixed-size list array around new items, one per item of its non-null + rows; a null row's slots are filled with nulls, which no reader sees.""" + valid = _valid(array) + if not valid.all(): + slots = np.repeat(valid, target.list_size) + positions = np.cumsum(slots, dtype=np.int64) - 1 + items = items.take(pa.array(positions, pa.int64(), mask=~slots)) + # From buffers: a zero-width list keeps its row count, and a non-null item field + # may have the null slots of a null row. + return pa.Array.from_buffers( + target, + len(array), + cast(Any, [None if valid.all() else pa.array(valid).buffers()[1]]), + null_count=int((~valid).sum()), + children=[items], + ) + + +def _large_list(array: Any, items: Any, target: Any) -> Any: + """Rebuild a list array around new items, one per item of its non-null rows.""" + offsets = _offsets(array).astype(np.int64) + return pa.LargeListArray.from_arrays( + pa.array(offsets, pa.int64()), + items, + type=target, + mask=array.is_null() if array.null_count else None, + ) + + +# ------------------------------------------------------------------- rows, as read + + +def require_stored_schema(found: pa.Schema, manifest: StoreManifest) -> None: + """Refuse a table whose stored columns are not exactly the ones the manifest lists. + + For rows as read, and for the first commit of a table read back. + + Args: + found: The stored schema; columns and struct fields in any order, in small or + large variants. + manifest: The table's manifest. + + Raises: + StoredRowsError: If a column or a struct field, at any depth, is missing, extra, + repeated or of another type. + """ + _require_names(found.names, manifest.physical.names) + for field, physical in zip(manifest.schema, manifest.physical): + with _at(field.name): + _require_type(found.field(physical.name).type, field.type, physical.type) + + +def _require_names(found: list[str], expected: list[str]) -> None: + """Refuse stored sibling names other than the expected ones.""" + if sorted(found) != sorted(expected): + missing = sorted(set(expected) - set(found)) + extra = sorted(set(found) - set(expected)) + repeated = sorted({n for n in found if found.count(n) > 1}) + raise StoredRowsError( + f"stored names missing {missing}, not expected {extra}, repeated {repeated}" + ) + + +def _require_type(found: Any, logical: Any, stored: Any) -> None: + """Refuse a stored type other than ``stored``, under which ``logical`` is kept.""" + if pa.types.is_struct(stored) and pa.types.is_struct(found): + _require_names( + [f.name for f in _children(found)], [f.name for f in _children(stored)] + ) + for field, kept in zip(_children(logical), _children(stored)): + with _at(field.name): + _require_type(found.field(kept.name).type, field.type, kept.type) + elif _is_list(stored) and _is_list(found): + with _at("[]"): + _require_type(*(cast(Any, x).value_type for x in (found, logical, stored))) + elif pa.types.is_fixed_size_list(stored) and pa.types.is_fixed_size_list(found): + sizes = [cast(Any, x).list_size for x in (found, stored)] + if sizes[0] != sizes[1]: + raise StoredRowsError(f"stored as {found}, not as {stored} ({logical})") + with _at("[]"): + _require_type(*(cast(Any, x).value_type for x in (found, logical, stored))) + elif pa.types.is_map(stored) and pa.types.is_map(found): + with _at("[]"): + for part in ("key_type", "item_type"): + _require_type(*(getattr(x, part) for x in (found, logical, stored))) + elif arrow_utils.normalize_to_large_types(found, keep_null=True) != stored: + raise StoredRowsError(f"stored as {found}, not as {stored} ({logical})") + + +def decode_rows( + rows: pa.Table, manifest: StoreManifest, schema: pa.Schema | None = None +) -> pa.Table: + """Return rows read from SpiralDB as the logical rows they were written from. + + Args: + rows: Rows as read: stored names, columns and struct fields in any order. + manifest: The table's manifest. Columns are found by the stored names it lists. + schema: The manifest's schema with some of its logical types live, to give the + rows; the manifest's own when ``None``. + + Returns: + The rows under the schema, columns and struct fields in its order. + + Raises: + StoredRowsError: If the stored columns are not the manifest's + (``require_stored_schema``), or a value is not one that was written; the + column is named. + ManifestError: If ``schema`` is not the manifest's. + """ + target = manifest.schema if schema is None else schema + difference = schema_difference(manifest.schema, target) + if difference is not None or target.names != manifest.schema.names: + raise ManifestError(f"not the recorded schema: {difference or 'column order'}") + require_stored_schema(rows.schema, manifest) + columns: list[Any] = [] + for out, field, physical in zip(target, manifest.schema, manifest.physical): + with _at(field.name): + column = rows.column(physical.name) + if field.name == KEY_COLUMN and column.null_count: + raise StoredRowsError("a null key") + chunks = [_decode(c, field, physical) for c in column.chunks] + live = isinstance(out.type, pa.BaseExtensionType) + storage: Any = out.type.storage_type if live else out.type + if storage != field.type: + chunks = [c.cast(storage) for c in chunks] + if live: + chunks = [ + pa.ExtensionArray.from_storage(cast(Any, out.type), c) + for c in chunks + ] + columns.append(cast(Any, pa.chunked_array)(chunks, type=out.type)) + return pa.Table.from_arrays(columns, schema=target) + + +def empty_rows(manifest: StoreManifest) -> pa.Table: + """Return zero rows of the recorded schema. + + What a table with a manifest and no value columns reads as (a crash before its first + rows). Such a table is never scanned: the service refuses a key-only scan. + + Args: + manifest: The table's manifest. + + Returns: + A table with no rows. + """ + return manifest.schema.empty_table() + + +def _decode(array: Any, field: pa.Field[Any], physical: pa.Field[Any]) -> Any: + """Return stored values of ``physical`` as the logical values of ``field``.""" + logical: Any = field.type + stored: Any = physical.type + t = pa.types + restored: Any + if t.is_struct(logical): + if array.null_count: + raise StoredRowsError("a null struct, which Orcapod never writes") + names = [f.name for f in _children(array.type)] + children: list[Any] = [] + for child, child_stored in zip(_children(logical), _children(stored)): + with _at(child.name): + values = array.field(names.index(child_stored.name)) + children.append(_decode(values, child, child_stored)) + restored = pa.StructArray.from_arrays(children, fields=_children(logical)) + elif _is_list(logical): + with _at("[]"): + items = _decode(array.flatten(), logical.value_field, stored.value_field) + restored = _large_list(array, items, logical) + elif t.is_fixed_size_list(logical): + with _at("[]"): + items = _decode(array.flatten(), logical.value_field, stored.value_field) + restored = _fixed_size_list(array, items, logical) + elif t.is_map(logical): + with _at("[]"): + rows = _map_rows(array) + keys = array.keys.take(rows) + keys = _decode(keys, logical.key_field, stored.key_field) + items = array.items.take(rows) + items = _decode(items, logical.item_field, stored.item_field) + restored = _map(array, keys, items, logical) + else: + restored = array.cast(stored) + if t.is_timestamp(logical) or t.is_time(logical): + restored = restored.view(logical) # the same integers + elif restored.type != logical: + restored = restored.cast(logical) # a decimal32 or decimal64 + if not field.nullable and restored.null_count: + raise StoredRowsError("a null in a non-nullable field") + return restored + + +# ---------------------------------------------------------------------- the manifest + +MANIFEST_PREFIX = "__orcapod_store__/" +# A draft: no table may be written with it outside tests. The persisted format, with its +# tag, is fixed with the creation and recovery rules (PR 6 of the design), as version 1. +_FORMAT = "orcapod.spiral_store.draft" +_VERSION = 0 +# SpiralDB: 1,024 entries a table, 8 KiB a key and value together. +_MAX_ENTRIES = 1024 +_MAX_PAIR_BYTES = 8192 +# Part of the format: two writers must cut one payload at the same places. +_CHUNK_BYTES = _MAX_PAIR_BYTES - 128 +_KEY = re.compile(re.escape(MANIFEST_PREFIX) + "([0-9a-f]{64})(?:/(0|[1-9][0-9]*))?") +# In the recorded Arrow schema an ``ARROW:extension:*`` key is written behind this +# mark (and a key that starts with the mark too, so the marking is reversible), so +# reading it back never builds an extension type that happens to be registered. +_MARKED = b"orcapod:key:" +_EXTENSION_KEYS = b"ARROW:extension:" + + +@dataclass(frozen=True) +class StoreManifest: + """What a store table's manifest says. Make one with ``new_manifest``. + + Attributes: + record_path: The table's full record path, each component exact. + kind: What the table is, as text; the codec does not interpret it. + schema: The table's logical schema (``logical_schema``). + physical: The stored schema (``physical_schema``), field for field in the order + of ``schema`` at every depth: it lists the stored names. + """ + + record_path: tuple[str, ...] + kind: str + schema: pa.Schema + physical: pa.Schema + + +def new_manifest( + record_path: tuple[str, ...], kind: str, schema: pa.Schema +) -> StoreManifest: + """Return the manifest of a table to be created. + + Args: + record_path: The table's full record path. + kind: What the table is. + schema: The schema of its rows. + + Returns: + The manifest. + + Raises: + UnstorableInSpiralError: If the schema cannot be stored, or a path component is + not UTF-8 or holds ``/`` or NUL. + """ + for part in record_path: + _require_utf8(part) + if "/" in part or "\0" in part: + raise UnstorableInSpiralError(f"the path component {part!r}") + _require_utf8(kind) + return StoreManifest( + record_path, kind, logical_schema(schema), physical_schema(schema) + ) + + +def manifest_entries( + manifest: StoreManifest, +) -> tuple[dict[str, bytes], dict[str, bytes]]: + """Return the metadata entries that record ``manifest``. + + The two dictionaries are written in this order, one call each, so that a reader + never sees a header whose chunks are missing. Chunks without a header are no + manifest. + + Args: + manifest: The manifest. + + Returns: + The chunk entries, and the header entry. + + Raises: + ManifestError: If the manifest does not fit in a table's metadata. + """ + payload = json.dumps( + { + "kind": manifest.kind, + "physical": _schema_text(manifest.physical), + "record_path": list(manifest.record_path), + "schema": _schema_text(_map_metadata(manifest.schema, _mark)), + "version": _VERSION, + }, + separators=(",", ":"), + sort_keys=True, + ).encode("ascii") + digest = _digest(payload) + pieces = [ + payload[i : i + _CHUNK_BYTES] for i in range(0, len(payload), _CHUNK_BYTES) + ] + if len(pieces) + 1 > _MAX_ENTRIES: + raise ManifestError( + f"the schema needs {len(pieces) + 1} metadata entries; SpiralDB holds " + f"{_MAX_ENTRIES} a table" + ) + header = { + "chunks": len(pieces), + "format": _FORMAT, + "sha256": digest, + "version": _VERSION, + } + return ( + {f"{MANIFEST_PREFIX}{digest}/{i}": piece for i, piece in enumerate(pieces)}, + { + f"{MANIFEST_PREFIX}{digest}": json.dumps( + header, separators=(",", ":"), sort_keys=True + ).encode("ascii") + }, + ) + + +def _schema_text(schema: pa.Schema) -> str: + """An Arrow schema as base64 of its IPC form.""" + return base64.b64encode(schema.serialize().to_pybytes()).decode("ascii") + + +def _schema_of(text: object) -> pa.Schema: + """The inverse of ``_schema_text``.""" + if not isinstance(text, str): + raise ManifestError("a schema is not text") + try: + raw = base64.b64decode(text, validate=True) + return pa.ipc.read_schema(pa.py_buffer(raw)) + except (binascii.Error, ValueError, pa.ArrowException, OSError) as exc: + raise ManifestError(f"a schema cannot be read ({exc})") from exc + + +def read_manifest( + metadata: Mapping[str, bytes], record_path: tuple[str, ...] +) -> StoreManifest | None: + """Return the manifest in a table's key-value metadata. + + Args: + metadata: All of the table's key-value metadata. + record_path: The record path the table was looked up for. + + Returns: + The manifest, or ``None`` when the table holds none: no header, whether or not + there are chunks of an interrupted creation. + + Raises: + ManifestError: If there are two headers; the manifest cannot be read in full, is + of an unknown format or version, or is another path's; or an entry under + ``__orcapod_store__/`` is not one of a manifest. + """ + headers: list[str] = [] + chunks: dict[str, list[int]] = {} + for key in metadata: + if not key.startswith(MANIFEST_PREFIX): + continue + match = _KEY.fullmatch(key) + if match is None: + raise ManifestError(f"unknown manifest entry {key!r}") + if match[2] is None: + headers.append(match[1]) + else: + chunks.setdefault(match[1], []).append(int(match[2])) + if not headers: + return None + if len(headers) > 1: + raise ManifestError( + f"the table holds more than one manifest: {sorted(headers)}" + ) + manifest = _read_one(metadata, headers[0], sorted(chunks.get(headers[0], []))) + if manifest.record_path != record_path: + raise ManifestError( + f"the table is recorded as {list(manifest.record_path)}, not as " + f"{list(record_path)}" + ) + return manifest + + +def _digest(payload: bytes) -> str: + """The digest that names a manifest (bare hex, in a name).""" + return hashlib.sha256(payload).hexdigest() + + +def _json_object(text: bytes) -> dict[str, Any]: + """Parse a JSON object.""" + try: + value = json.loads(text.decode("ascii")) + except (ValueError, RecursionError) as exc: + raise ManifestError(f"a manifest part is not JSON ({exc})") from exc + if not isinstance(value, dict): + raise ManifestError("a manifest part is not a JSON object") + return cast("dict[str, Any]", value) + + +def _require_version(value: object) -> None: + """Refuse a format version this Orcapod does not read.""" + if type(value) is not int or value != _VERSION: + raise ManifestError( + f"unsupported manifest version {value!r} (this Orcapod reads {_VERSION})" + ) + + +def _read_one( + metadata: Mapping[str, bytes], digest: str, found: list[int] +) -> StoreManifest: + """Read the manifest named by ``digest``, whose chunks ``found`` are there.""" + header = _json_object(metadata[MANIFEST_PREFIX + digest]) + if header.get("format") != _FORMAT: + raise ManifestError(f"unknown manifest format {header.get('format')!r}") + _require_version(header.get("version")) + count = header.get("chunks") + if type(count) is not int or not 1 <= count < _MAX_ENTRIES: + raise ManifestError(f"invalid chunk count {count!r}") + if header.get("sha256") != digest: + raise ManifestError(f"the header of {digest} names another digest") + if found != list(range(count)): + raise ManifestError(f"chunks {found} of {digest}, not 0 to {count - 1}") + payload = b"".join(metadata[f"{MANIFEST_PREFIX}{digest}/{i}"] for i in range(count)) + if _digest(payload) != digest: + raise ManifestError(f"the chunks of {digest} do not match it") + body = _json_object(payload) + _require_version(body.get("version")) + path, kind = body.get("record_path"), body.get("kind") + if not isinstance(path, list) or not all( + isinstance(part, str) for part in cast("list[object]", path) + ): + raise ManifestError("the record path is not a list of strings") + if not isinstance(kind, str): + raise ManifestError("the kind is not text") + schema = _map_metadata(_schema_of(body.get("schema")), _unmark) + physical = _schema_of(body.get("physical")) + try: + usable = logical_schema(schema) + expected = physical_schema(schema) + except UnstorableInSpiralError as exc: + raise ManifestError( + f"the recorded schema is not a store schema: {exc}" + ) from exc + # The stored names are read from the manifest, never recomputed; its shape and types + # must be the ones the logical schema is kept in. + if _without_names(physical) != _without_names(expected) or ( + usable.names.index(KEY_COLUMN) != physical.get_field_index(KEY_COLUMN) + ): + raise ManifestError("the recorded stored schema is not the logical one's") + _require_distinct(physical) + return StoreManifest(tuple(cast("list[str]", path)), kind, usable, physical) + + +def _without_names(fields: Any) -> list[object]: + """The types of fields at every depth, without names.""" + shape: list[object] = [] + for field in fields: + arrow_type = field.type + inner = _children(arrow_type) + size = getattr(arrow_type, "list_size", None) + shape.append( + (arrow_type.id, size, _without_names(inner)) if inner else arrow_type + ) + return shape + + +def _require_distinct(fields: Any) -> None: + """Refuse a recorded stored schema with two siblings of one name.""" + names = [field.name for field in fields] + if len(set(names)) != len(names): + raise ManifestError("the recorded stored schema repeats a name") + for field in fields: + _require_distinct(_children(field.type)) + + +def _mark(key: bytes) -> bytes: + """The form a field metadata key is recorded in.""" + return _MARKED + key if key.startswith((_MARKED, _EXTENSION_KEYS)) else key + + +def _unmark(key: bytes) -> bytes: + """The inverse of ``_mark``.""" + return key.removeprefix(_MARKED) + + +def _map_metadata(schema: pa.Schema, change: Any) -> pa.Schema: + """Return ``schema`` with every field metadata key, at every depth, changed.""" + return pa.schema( + [_map_field(field, change) for field in schema], + metadata=cast(Any, schema.metadata), + ) + + +def _map_field(field: pa.Field[Any], change: Any) -> pa.Field[Any]: + """``_map_metadata`` for one field. A map has no metadata inside.""" + arrow_type: Any = field.type + if pa.types.is_struct(arrow_type): + arrow_type = pa.struct([_map_field(f, change) for f in _children(arrow_type)]) + elif pa.types.is_large_list(arrow_type): + arrow_type = pa.large_list(_map_field(arrow_type.value_field, change)) + elif pa.types.is_fixed_size_list(arrow_type): + arrow_type = pa.list_( + _map_field(arrow_type.value_field, change), arrow_type.list_size + ) + metadata = {change(k): v for k, v in (field.metadata or {}).items()} + return pa.field(field.name, arrow_type, field.nullable, cast(Any, metadata or None)) + + +# ------------------------------------------------- comparing a schema with a manifest's + + +def schema_difference(recorded: pa.Schema, other: pa.Schema) -> str | None: + """Return how a schema differs from a recorded one, or ``None`` when it is the same. + + Compared as decoded, never as bytes: the schema metadata, and each column by name, + with its type, nullability and metadata, field by field at every depth. The order of + columns and of metadata entries does not count: one pipeline's table may be written + with its columns in another order. + + Args: + recorded: A manifest's schema. + other: Another one, in any form ``logical_schema`` takes. + + Returns: + The first difference, in words. + + Raises: + UnstorableInSpiralError: If a schema cannot be stored. + """ + left, right = logical_schema(recorded), logical_schema(other) + if dict(left.metadata or {}) != dict(right.metadata or {}): + return "the schema metadata differs" + if set(left.names) != set(right.names): + return f"columns {sorted(left.names)} and {sorted(right.names)}" + for field in left: + difference = _field_difference(field, right.field(field.name), repr(field.name)) + if difference is not None: + return difference + return None + + +def _field_difference(a: pa.Field[Any], b: pa.Field[Any], where: str) -> str | None: + """How two fields differ. Arrow's own equality ignores nested names.""" + for what, x, y in ( + ("name", a.name, b.name), + ("nullable", a.nullable, b.nullable), + ("metadata", dict(a.metadata or {}), dict(b.metadata or {})), + ("type", a.type.id, b.type.id), + ("number of fields", a.type.num_fields, b.type.num_fields), + ): + if x != y: + shown = (a.type, b.type) if what == "type" else (x, y) + return f"{where}: {what} {shown[0]} and {shown[1]}" + if not a.type.num_fields: + return None if a.type == b.type else f"{where}: type {a.type} and {b.type}" + for what in ("list_size", "keys_sorted"): + x, y = (getattr(f.type, what, None) for f in (a, b)) + if x != y: + return f"{where}: {what} {x} and {y}" + struct = pa.types.is_struct(a.type) + for x, y in zip(_children(a.type), _children(b.type)): + inner = f"{where}.{x.name}" if struct else f"{where}[]" + difference = _field_difference(x, y, inner) + if difference is not None: + return difference + return None diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py new file mode 100644 index 000000000..3a010eec5 --- /dev/null +++ b/tests/test_databases/test_spiral_store.py @@ -0,0 +1,1445 @@ +"""The codec of a SpiralDB store table: names, types, rows and the manifest (ITL-1446). + +No SpiralDB and no fake: ``as_spiral_returns`` does to encoded rows what SpiralDB does +(columns and struct fields sorted by name, rows in another order and other chunks, other +list item names, small or large variants). +""" + +from __future__ import annotations + +import base64 +import datetime as dt +import decimal +import json +import math +import random +import re +import subprocess +import sys +from pathlib import Path +from typing import Any, cast + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.databases import spiral_store as store +from orcapod.logical_types.canonical_form import declaration_form_schema +from orcapod.utils.arrow_utils import normalize_to_large_types +from tests.test_databases.type_matrix import ( + ROWS, + Row, + build_table, + field_difference, +) +from tests.test_databases.type_matrix import ( + _same_values as same_values, # pyright: ignore[reportPrivateUsage] +) + +KEY = store.KEY_COLUMN +NAME_KEY, METADATA_KEY = b"ARROW:extension:name", b"ARROW:extension:metadata" + +chunked: Any = pa.chunked_array # the stubs type ``type=`` as None +map_of: Any = pa.map_ # the stubs lack fields and keys_sorted +schema_of: Any = pa.schema # the stubs take no mix of fields and pairs +# The stubs take literal units and zones only. +timestamp: Any = pa.timestamp +duration: Any = pa.duration + + +# ------------------------------------------------------------------------- helpers + + +def ids(n: int) -> Any: + return pa.array([f"r{i:04d}".encode() for i in range(n)], pa.large_binary()) + + +def keyed(columns: dict[str, Any], fields: list[Any] | None = None) -> pa.Table: + """A table of ``columns`` (arrays) with a key column in the middle.""" + n = len(next(iter(columns.values()))) + fields = fields or [pa.field(k, v.type) for k, v in columns.items()] + half = len(fields) // 2 + fields = [*fields[:half], pa.field(KEY, pa.large_binary(), False), *fields[half:]] + arrays = [ids(n) if f.name == KEY else columns[f.name] for f in fields] + return pa.Table.from_arrays(arrays, schema=schema_of(fields)) + + +def _returned(array: Any, small: bool) -> Any: + """One array as SpiralDB may give it back.""" + t = pa.types + if t.is_struct(array.type): + assert array.null_count == 0 + order = sorted( + range(array.type.num_fields), key=lambda i: array.type.field(i).name + ) + children = [_returned(array.field(i), small) for i in order] + names = [array.type.field(i).name for i in order] + return pa.StructArray.from_arrays( + children, fields=[pa.field(n, c.type) for n, c in zip(names, children)] + ) + mask = array.is_null() if array.null_count else None + if t.is_large_list(array.type): + items = _returned(array.flatten(), small) + offsets = array.offsets + offsets = pa.array(offsets.to_numpy() - offsets.to_numpy()[0], pa.int64()) + target = (pa.list_ if small else pa.large_list)(pa.field("element", items.type)) + cls: Any = pa.ListArray if small else pa.LargeListArray + return cls.from_arrays( + offsets.cast(pa.int32() if small else pa.int64()), + items, + type=target, + mask=mask, + ) + if small and t.is_large_string(array.type): + return array.cast(pa.string()) + if small and t.is_large_binary(array.type): + return array.cast(pa.binary()) + return array + + +def as_spiral_returns(rows: pa.Table, seed: int = 0, small: bool = False) -> pa.Table: + """Encoded rows as a scan gives them: a set of rows, columns sorted by name.""" + rng = random.Random(seed) + order = list(range(rows.num_rows)) + rng.shuffle(order) + columns: dict[str, Any] = {} + for name in sorted(rows.column_names): + whole = rows.column(name).combine_chunks().take(pa.array(order, pa.int64())) + cut = rng.randint(0, len(whole)) + pieces = [_returned(p, small) for p in (whole[:cut], whole[cut:])] + columns[name] = chunked(pieces, type=pieces[0].type) + return pa.table(columns) + + +def by_id(rows: pa.Table) -> pa.Table: + """Rows sorted by key: a store is a set of rows.""" + keys = rows.column(KEY).to_pylist() + return rows.take( + pa.array(sorted(range(len(keys)), key=lambda i: keys[i]), pa.int64()) + ) + + +PATH = ("run", "fn", "pdb_v1") + + +def new(schema: pa.Schema, path: tuple[str, ...] = PATH) -> store.StoreManifest: + return store.new_manifest(path, "function_pipeline", schema) + + +def entries(schema: pa.Schema, path: tuple[str, ...] = PATH) -> dict[str, bytes]: + chunks, header = store.manifest_entries(new(schema, path)) + return {**chunks, **header} + + +def read( + metadata: dict[str, bytes], path: tuple[str, ...] = PATH +) -> store.StoreManifest: + manifest = store.read_manifest(metadata, path) + assert manifest is not None + return manifest + + +def decode(rows: pa.Table, schema: pa.Schema) -> pa.Table: + """Decode through a manifest read back, giving ``schema`` (live types kept).""" + return store.decode_rows(rows, read(entries(schema)), large(schema)) + + +def large_type(arrow_type: Any) -> Any: + return normalize_to_large_types(arrow_type, keep_null=True) + + +def large(schema: pa.Schema) -> pa.Schema: + return schema_of( + [f.with_type(normalize_to_large_types(f.type, keep_null=True)) for f in schema], + metadata=cast(Any, schema.metadata), + ) + + +def assert_same(got: pa.Table, expected: pa.Table) -> None: + """Schema exactly (every depth); values bit for bit, as sets of rows.""" + assert got.schema.names == expected.schema.names + assert got.schema.metadata == expected.schema.metadata + for a, b in zip(expected.schema, got.schema): + assert field_difference(a, b, a.name) is None + got, expected = by_id(got), by_id(expected) + for name in expected.column_names: + left, right = got.column(name), expected.column(name) + assert same_values(left.combine_chunks(), right.combine_chunks()), name + got.validate() + + +def round_trip(rows: pa.Table, *, live: bool = False) -> pa.Table: + """Write, return as SpiralDB does, and restore through the manifest: every slice, + both variants.""" + expected_schema = large(rows.schema) + manifest = read(entries(rows.schema)) + schema = manifest.schema + if live: + converter = get_default_context().type_converter + schema = declaration_form_schema(schema, converter) + else: + expected_schema = store.logical_schema(rows.schema) + result = None + assert rows.num_rows + for piece in (rows, rows.slice(1), rows.slice(0, 1)): + if not piece.num_rows: + continue + encoded = store.encode_rows(piece) + assert encoded.schema.equals( + store.physical_schema(rows.schema), check_metadata=True + ) + _assert_physical(encoded.schema) + encoded.validate() # full: pyarrow refuses a date64 off midnight + for seed, small in ((1, False), (2, True)): + got = store.decode_rows( + as_spiral_returns(encoded, seed, small), manifest, schema + ) + want = pa.Table.from_arrays( + [ + chunked([_as_target(c, f) for c in col.chunks], type=f.type) + for col, f in zip(piece.columns, expected_schema) + ], + schema=expected_schema, + ) + assert_same(got, want) + result = result or got + assert result is not None + return result + + +def _as_target(chunk: Any, field: Any) -> Any: + """What was written, under the expected field (its storage, its large variants).""" + if chunk.type == field.type: + return chunk + if isinstance(chunk, pa.ExtensionArray): + chunk = chunk.storage + return chunk if chunk.type == field.type else chunk.cast(field.type) + + +def _assert_physical(schema: pa.Schema) -> None: + """SpiralDB's known rules on names and types, at every depth.""" + + def walk(field: Any, named: bool, in_map: bool = False) -> None: + assert (field.nullable or in_map) and not field.metadata + if named and field.name != KEY: + assert field.name and not field.name.startswith(("__", "$")) + assert not set(field.name) & set(".$*\0") + t = field.type + assert not ( + pa.types.is_fixed_size_binary(t) + or pa.types.is_duration(t) + or isinstance(t, pa.BaseExtensionType) + or (pa.types.is_timestamp(t) and t.tz is not None) + ) + if pa.types.is_map(t): + walk(t.key_field, False, in_map=True) + walk(t.item_field, False) + return + for i in range(t.num_fields): + walk(t.field(i), pa.types.is_struct(t)) + + for f in schema: + walk(f, True) + + +def refused(rows: pa.Table, *words: str) -> store.UnstorableInSpiralError: + with pytest.raises(store.UnstorableInSpiralError) as info: + store.encode_rows(rows) + for word in words: + assert word in str(info.value) + return info.value + + +# --------------------------------------------------------------------------- names + + +@pytest.mark.parametrize( + ("name", "stored"), + [ + ("x", "x"), + ("_source_x", "_source_x"), + ("_tag_source_id::ab", "_tag_source_id::ab"), + ("a;b", "a;b"), + ("é", "é"), + ("a b", "a b"), + ("__data_context", "ox___data_context"), + ("a.b", "ox_a;2Eb"), + ("a;2Eb", "a;2Eb"), + ("ox_a;2Eb", "ox_ox_a;3B2Eb"), + ("ox_", "ox_ox_"), + ("", "ox_"), + ("$a*\x00\x7f\n", "ox_;24a;2A;00;7F;0A"), + ], +) +def test_the_names_of_the_design(name: str, stored: str) -> None: + assert store.encode_name(name) == stored + assert decoded(stored) == name + + +def decoded(stored: str) -> str: + """The inverse of ``encode_name``, which only the tests need.""" + if not stored.startswith("ox_"): + return stored + return re.sub(";([0-9A-F]{2})", lambda m: chr(int(m[1], 16)), stored[3:]) + + +def adversarial_names(count: int) -> set[str]: + rng = random.Random(1446) + pieces = ( + ["_", "__", "ox_", "ox", ".", ";", ";2E", ";3B", ";2e", ";G", "$", "*", "%2E"] + + ["a", "B", "é", "é", "::", " ", "\n", "\x00", "\x7f", "\x80", "{", '"'] + + ["x_", "o", "\U0001f600", "
", "2E", "3B"] + ) + names = {"", KEY, "ox_", "a.b", "a;2Eb", "ox_a;2Eb", "ox_order", "Å", "Å"} + names |= {chr(i) for i in range(0x300)} | {f"a{chr(i)}b" for i in range(0x300)} + while len(names) < count: + names.add("".join(rng.choices(pieces, k=rng.randint(0, 8)))) + return names + + +def test_names_round_trip_and_are_injective() -> None: + names = adversarial_names(210_000) + assert len(names) >= 200_000 + encoded = {name: store.encode_name(name) for name in names} + assert len(set(encoded.values())) == len(names) + for name, stored in encoded.items(): + assert decoded(stored) == name + assert stored and not stored.startswith("__") + assert not any(c in ".$*\x7f" or ord(c) < 32 for c in stored) + + +def test_an_already_stored_name_is_itself_encoded_injectively() -> None: + names = sorted(adversarial_names(5_000)) + once = [store.encode_name(n) for n in names] + twice = [store.encode_name(n) for n in once] + assert len(set(twice)) == len(names) + assert [decoded(decoded(t)) for t in twice] == names + + +@pytest.mark.parametrize( + "names", [["a.b", "a;2Eb", "ox_a;2Eb", "__a"], ["", "ox_", "$"]] +) +@pytest.mark.parametrize("depth", [0, 1, 2, 3]) +def test_names_in_rows_at_every_depth(names: list[str], depth: int) -> None: + for order in (names, list(reversed(names))): + columns = {n: pa.array([i, i + 1], pa.int64()) for i, n in enumerate(order)} + arrays, fields = ( + list(columns.values()), + [pa.field(n, pa.int64()) for n in order], + ) + for level in range(depth): + inner = pa.StructArray.from_arrays(arrays, fields=fields) + if level % 2: + inner = pa.LargeListArray.from_arrays( + pa.array([0, 1, 2], pa.int64()), inner + ) + arrays = [inner, pa.array([5, 6])] + fields = [pa.field("s.t", inner.type), pa.field("__z", pa.int64())] + _ = round_trip(keyed({f.name: a for f, a in zip(fields, arrays)}, fields)) + + +@pytest.mark.parametrize("nested", [False, True]) +def test_a_stored_name_never_matches_a_logical_name(nested: bool) -> None: + """``E("a.b")`` is ``ox_a;2Eb``, which is also another column's own name.""" + values = {"a.b": 1, "ox_a;2Eb": 2, "__record": 3, "ox___record": 4} + for order in (list(values), list(reversed(values))): + if nested: + ty = pa.struct([(n, pa.int64()) for n in order]) + table = keyed({"s": pa.array([values], ty)}) + assert round_trip(table).column("s").to_pylist() == [values] + else: + got = round_trip(keyed({n: pa.array([values[n]]) for n in order})) + assert {n: got.column(n)[0].as_py() for n in values} == values + + +def test_the_key_is_not_a_value_column_of_the_same_name() -> None: + inner = pa.array([{KEY: 7}], pa.struct([(KEY, pa.int64())])) + table = keyed({"ox_" + KEY: pa.array([1]), "s": inner}) + got = round_trip(table) + assert got.column(KEY).to_pylist() == ids(1).to_pylist() + assert got.column("ox_" + KEY).to_pylist() == [1] + encoded = store.encode_rows(table) + renamed = encoded.rename_columns( + ["ox_" + KEY if n == KEY else n for n in encoded.column_names] + ) + with pytest.raises(store.StoredRowsError, match="missing"): + decode(renamed, table.schema) + + +@pytest.mark.parametrize("name", ["\ud800", "a\udfff", "__\ud800.b"]) +def test_a_lone_surrogate_is_refused(name: str) -> None: + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + store.encode_name(name) + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + new(schema_of([("a", pa.int8()), (KEY, pa.large_binary())]), (name,)) + + +def test_a_name_that_is_not_utf8_is_refused_at_every_depth() -> None: + bad: Any = pa.field(cast(Any, b"a\xff"), pa.int8()) + for field in ( + bad, + pa.field("s", pa.struct([bad])), + pa.field("l", pa.list_(pa.struct([bad]))), + pa.field("i", pa.list_(bad)), + ): + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + store.logical_schema(schema_of([field, (KEY, pa.large_binary())])) + + +def wrappings(inner: Any) -> list[Any]: + """``inner`` alone, below each kind of nesting, and as a logical type's storage.""" + return [ + inner, + pa.list_(inner), + pa.struct([("s", pa.large_list(inner))]), + Labelled(inner, "test.storage", b""), + Labelled(pa.large_list(inner), "test.storage", b""), + ] + + +def test_duplicate_sibling_names_are_refused_at_every_depth() -> None: + twice = pa.struct([("a.b", pa.int8()), ("c", pa.int8()), ("a.b", pa.int8())]) + for ty in wrappings(twice): + with pytest.raises(store.UnstorableInSpiralError, match="more than once"): + store.logical_schema(schema_of([("x", ty), (KEY, pa.large_binary())])) + same_in_two_structs = pa.struct([("a", pa.struct([("a", pa.int8())]))]) + _ = store.logical_schema( + schema_of([("a", same_in_two_structs), (KEY, pa.large_binary())]) + ) + + +def test_names_that_differ_only_in_case_or_normal_form_are_kept_apart() -> None: + """The service folds neither (measured live).""" + names = ["A", "a", "a.B", "a.b", "__A", "__a", "\u00e9", "e\u0301", "a.\u00e9"] + for order in (names, list(reversed(names))): + inner = pa.array( + [{n: i for i, n in enumerate(order)}], + pa.struct([(n, pa.int8()) for n in order]), + ) + columns = {n: pa.array([i]) for i, n in enumerate(order)} + _ = round_trip(keyed({**columns, "s": inner})) + + +@pytest.mark.parametrize("as_storage", [False, True]) +def test_a_struct_parent_must_be_valid_also_in_a_logical_types_storage( + as_storage: bool, +) -> None: + struct = pa.struct([pa.field("a.b", pa.int8(), False)]) + for ty, value in ((struct, None), (pa.large_list(struct), [{"a.b": 1}, None])): + array = pa.array([value], ty) + if as_storage: + live = Labelled(ty, "test.parent", b"") + array = pa.ExtensionArray.from_storage(live, array) + refused(keyed({"c": array}), "'c'", "null struct") + + +# --------------------------------------------------------------------------- types + +REFUSED_ROWS = { + "struct<> (no fields)": "no fields", + "fixed_size_binary[4]": "fixed-size binary", + "uuid (Arrow's canonical extension type)": "fixed-size binary", + "map, keys sorted": "named key and value", + "map (item metadata)": "metadata inside a map", + "map (key metadata)": "metadata inside a map", + "map> (metadata inside the item)": "metadata inside a map", + **{r.label: "duration" for r in ROWS if r.label.startswith("duration")}, +} +# The matrix's second column holds a null row. +NULL_STRUCT_ROWS = { + "struct", + "struct[2]>", + "struct", + "user class, exact (dataclass)", + "user class, structural (orcapod.dataclass)", +} + + +def test_the_expectations_name_rows_of_the_matrix() -> None: + assert set(REFUSED_ROWS) | NULL_STRUCT_ROWS <= {r.label for r in ROWS} + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize("row", ROWS, ids=lambda r: r.label) +def test_every_row_of_the_type_matrix_is_kept_or_refused( + row: Row, tmp_path: Path +) -> None: + """Two columns of each type (the second nullable, with a null), both forms of a + logical type, and the column naming its refusal.""" + if row.label.startswith("torch"): + _ = pytest.importorskip("torch") + rows = build_table(row, tmp_path).rename_columns([KEY, "x", "y"]) + if row.label in REFUSED_ROWS: + refused(rows, REFUSED_ROWS[row.label], "'x'") + return + if row.label in NULL_STRUCT_ROWS: + refused(rows, "null struct", "'y'") + rows = rows.drop_columns(["y"]) + _ = round_trip(rows) + _ = round_trip(rows, live=True) + + +def scalar_cases() -> list[tuple[str, pa.DataType, list[Any]]]: + D = decimal.Decimal + return [ + ("int8", pa.int8(), [-128, 127, 0]), + ("uint64", pa.uint64(), [0, 2**64 - 1, 2**63]), + ("int64", pa.int64(), [-(2**63), 2**63 - 1, 0]), + ("bool", pa.bool_(), [True, False, True]), + ("float32", pa.float32(), [1.5, 0.0, -3.25]), + ("float64", pa.float64(), [0.1, math.inf, 5e-324]), + ("float16", pa.float16(), [0.5, -0.0, math.nan]), + ("decimal128", pa.decimal128(38, 4), [D("1.2500"), D("-9.0001"), D("0")]), + ("decimal256", pa.decimal256(70, 4), [D("1.2500"), D("-9.0001"), D("0")]), + ("date64", pa.date64(), [-(2**63), 1, 2**63 - 1]), + ("decimal32", pa.decimal32(9, 2), [D("1.25"), D("-9999999.99"), D("0")]), + ( + "decimal64", + pa.decimal64(18, 2), + [D("1.25"), D("-9999999999999999.99"), D("0")], + ), + ("null", pa.null(), [None, None, None]), + ("time32_s", pa.time32("s"), [0, 86_399, 1]), + ("time32_ms", pa.time32("ms"), [0, 86_399_999, 1]), + ("time64_us", pa.time64("us"), [0, 86_400 * 10**6 - 1, 1]), + ("time64_ns", pa.time64("ns"), [0, 86_400 * 10**9 - 1, 1]), + ( + "date32", + pa.date32(), + [dt.date(1, 1, 1), dt.date(9999, 12, 31), dt.date(1970, 1, 1)], + ), + ("large_string", pa.large_string(), ["", "é\x00", "x" * 100]), + ("string", pa.string(), ["", "é\x00", "y"]), + ("binary", pa.binary(), [b"", b"\x00\xff", b"a"]), + *( + (f"ts_{u}_{z}", timestamp(u, tz=z), [-1, 0, 2**40 + 1]) + for u in ("s", "ms", "us", "ns") + for z in (None, "UTC", "Asia/Kathmandu", "-03:30") + ), + ] + + +@pytest.mark.parametrize("case", scalar_cases(), ids=lambda c: c[0]) +@pytest.mark.parametrize("nullable", [True, False]) +def test_every_type_at_every_nesting_depth( + case: tuple[str, pa.DataType, list[Any]], nullable: bool +) -> None: + """Each kept type alone and below lists, fixed-size lists, structs and their + combinations, in several columns at once, in two column orders.""" + _, arrow_type, values = case + nullable = nullable or pa.types.is_null(arrow_type) + if nullable: + values = [*values, None] + else: + values = [*values, values[0]] + leaf = pa.field("v.1", arrow_type, nullable, {"unit": "m"}) + item = leaf.with_name("odd item") + plain_item = item.remove_metadata() + v, n = values, len(values) + shapes: dict[str, tuple[pa.DataType, list[Any]]] = { + "plain": (arrow_type, v), + "list": (pa.list_(item), [v, [], None, v[:1]]), + "large": (pa.large_list(item), [None, v[:2], v, []]), + "fixed": (pa.list_(item, 2), [v[:2], None, v[2:], v[1:3]]), + "fixed_fixed": ( + pa.list_(pa.list_(item, 1), 2), + [[v[:1], None], None, [v[1:2], v[2:3]], [v[:1], v[:1]]], + ), + "fixed0": (pa.list_(item, 0), [[], None, [], []]), + "list_fixed": (pa.list_(pa.list_(item, 1)), [[v[:1], None], [], None, [v[3:]]]), + "map": ( + map_of(pa.string(), item.with_name("value").remove_metadata()), + [[("b", v[0]), ("a", v[1])], None, [], [("", x) for x in v]], + ), + "map_sorted_list": ( + map_of(pa.binary(), pa.list_(plain_item), keys_sorted=True), + [None, [(b"a", v), (b"b", None)], [(b"", [])], []], + ), + "list_map": ( + pa.list_(map_of(pa.int16(), plain_item.with_name("value"))), + [[[(1, v[0])], None, []], None, [], [[(2, x)] for x in v]], + ), + "map_struct": ( + map_of( + pa.string(), + pa.struct( + [pa.field("z", pa.int8()), pa.field("a.b", arrow_type, nullable)] + ), + ), + [ + None, + [("k", {"z": 1, "a.b": v[0]})], + [], + [("", {"z": None, "a.b": v[1]})], + ], + ), + "fixed_struct": ( + pa.list_(pa.struct([pa.field("z", pa.int8()), leaf]), 1), + [[{"z": 1, "v.1": x}] for x in v], + ), + "struct": ( + pa.struct([leaf, pa.field("__b", pa.int8())]), + [{"v.1": x, "__b": i} for i, x in enumerate(v)], + ), + "struct_list": ( + pa.struct([pa.field("z", pa.list_(item)), pa.field("a", pa.int8())]), + [{"z": x, "a": 1} for x in ([], v, None, v[:1])], + ), + "list_struct": ( + pa.list_(pa.field("i", pa.struct([pa.field("z", pa.int8()), leaf]))), + [[{"z": 1, "v.1": v[0]}], None, [], [{"z": None, "v.1": x} for x in v]], + ), + "list_list": (pa.list_(pa.list_(item)), [[v, [], None], [], None, [v[:1]]]), + "deep": ( + pa.list_( + pa.struct([pa.field("s", pa.struct([pa.field("l", pa.list_(item))]))]) + ), + [[{"s": {"l": v}}, {"s": {"l": None}}], [], None, [{"s": {"l": []}}]], + ), + } + if not nullable or pa.types.is_null(arrow_type): + # pyarrow cannot cast a null fixed-size list over non-null items, or a sliced + # list of structs with a null-typed field, so the test + # could not state what it expects of the small variants. + shapes = {k: (large_type(t), rows) for k, (t, rows) in shapes.items()} + columns = {k: pa.array(rows, t) for k, (t, rows) in shapes.items()} + assert all(len(c) == n for c in columns.values()) + fields = [ + pa.field(k, c.type, nullable if k == "plain" else True, {"k": k}) + for k, c in columns.items() + ] + table = keyed(columns, fields) + _ = round_trip(table) + _ = round_trip(table.select(list(reversed(table.column_names)))) + + +@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) +@pytest.mark.parametrize( + "zone", [None, "UTC", "Europe/Berlin", "Asia/Kathmandu", "+05:45", "-03:30"] +) +def test_zone_aware_timestamps_are_exact(unit: str, zone: str) -> None: + """Extremes of the integer, the far past and sub-second ticks.""" + ticks = [-(2**63), 2**63 - 1, -(2**63) + 1, 0, -1, 1, -(10**15) - 7, 10**15 + 3] + ticks += [-62135596800 * {"s": 1, "ms": 10**3, "us": 10**6, "ns": 1}[unit] - 1] + values = [*ticks, None] + ts = timestamp(unit, tz=zone) + plain: Any = pa.array(values, pa.int64()).cast(ts) + columns = { + "t": plain, + "l": pa.array([[x, None] for x in values], pa.list_(pa.int64())).cast( + pa.list_(ts) + ), + "s": pa.StructArray.from_arrays([plain], fields=[pa.field("t", ts)]), + } + got = by_id(round_trip(keyed(columns))) + assert got.column("t").cast(pa.int64()).to_pylist() == values + assert got.schema.field("t").type == ts + encoded = store.encode_rows(keyed(columns)) + assert encoded.schema.field("t").type == pa.int64() + assert encoded.column("t").cast(pa.int64()).to_pylist() == values + + +def _float(bits: int, width: int) -> Any: + ints = np.array([bits], dtype=f"u{width // 8}") + return pa.array(ints).view(pa.float32() if width == 32 else pa.float64()) + + +FLOATS = { + 32: [0, 0x80000000, 1, 0x80000001, 0x7F800000, 0xFF800000, 0x7FC00000, 0x7F7FFFFF] + + [0x7FC00001, 0xFFC00000, 0x7F800001, 0xFF800001, 0x7FFFFFFF], + 64: [0, 1 << 63, 1, (1 << 63) + 1, 0x7FF << 52, 0xFFF << 52, 0x7FF8 << 48] + + [(0x7FF8 << 48) + 1, 0xFFF8 << 48, (0x7FF << 52) + 1, (1 << 63) - 1], +} + + +@pytest.mark.parametrize("width", [16, 32, 64]) +@pytest.mark.parametrize("nested", ["plain", "list", "fixed", "struct"]) +def test_float_bits_are_kept(width: int, nested: str) -> None: + """Negative zero and every NaN payload, signalling ones included, bit for bit.""" + if width == 16: # every float16 there is + array: Any = pa.array(np.arange(2**16, dtype=np.uint16)).view(pa.float16()) + else: + array = pa.concat_arrays([_float(b, width) for b in FLOATS[width]]) + if nested == "list": + array = pa.ListArray.from_arrays( + pa.array(range(len(array) + 1), pa.int32()), array + ) + elif nested == "fixed": + array = pa.FixedSizeListArray.from_arrays(array, 1) + elif nested == "struct": + array = pa.StructArray.from_arrays([array], names=["f"]) + _ = round_trip(keyed({"f": array})) + + +def test_datetime_max_and_min_are_kept() -> None: + """The service refuses a timestamp after 9999-12-30: they are written as integers.""" + utc = dt.timezone.utc + values = [ + dt.datetime.max, + dt.datetime.min, + dt.datetime(9999, 12, 30, 22, 0, 1), + None, + ] + table = keyed( + { + "naive": pa.array(values, timestamp("us")), + "utc": pa.array( + [v and v.replace(tzinfo=utc) for v in values], timestamp("us", tz="UTC") + ), + } + ) + got = by_id(round_trip(table)) + assert got.column("naive").to_pylist() == values + + +@pytest.mark.parametrize("arrow_type", [pa.time32("s"), pa.time32("ms")], ids=str) +def test_every_time32_is_kept(arrow_type: Any) -> None: + """Also one outside a day, which the service refuses as a time.""" + ticks = [0, 86_399, 86_400, 86_400_000, -1, -(2**31), 2**31 - 1, None] + array: Any = pa.array(ticks, pa.int32()).view(arrow_type) + got: Any = by_id(round_trip(keyed({"t": array}))) + assert got.column("t").combine_chunks().view(pa.int32()).to_pylist() == ticks + + +@pytest.mark.parametrize("arrow_type", [pa.time64("us"), pa.time64("ns")], ids=str) +@pytest.mark.parametrize("nested", ["plain", "list", "fixed", "struct", "map"]) +def test_every_time64_is_kept(arrow_type: Any, nested: str) -> None: + ticks = [0, 86_400 * 10**6, 86_400 * 10**9, -1, -(2**63), 2**63 - 1] + array: Any = pa.array(ticks, pa.int64()).view(arrow_type) + offsets: Any = pa.array(range(len(ticks) + 1), pa.int32()) + if nested == "list": + array = pa.ListArray.from_arrays(offsets, array) + elif nested == "fixed": + array = pa.FixedSizeListArray.from_arrays(array, 2) + elif nested == "struct": + array = pa.StructArray.from_arrays([array], names=["t"]) + elif nested == "map": + array = pa.MapArray.from_arrays(offsets, pa.array(list("abcdef")), array) + _ = round_trip(keyed({"t": array})) + + +def test_what_a_null_list_or_map_hides_is_not_written() -> None: + raw = pa.array([-1, 5], pa.int64()).view(pa.time64("us")) + offsets: Any = pa.array([0, 1, 2], pa.int32()) + mask = pa.array([True, False]) + lists = pa.ListArray.from_arrays(offsets, raw, mask=mask) + maps = pa.MapArray.from_arrays(offsets, pa.array(["hidden", "b"]), raw, mask=mask) + table = keyed({"l": lists, "m": maps}) + _ = round_trip(table) + encoded: Any = store.encode_rows(table) + assert len(encoded.column("l").chunk(0).values) == 1 + assert encoded.column("m").chunk(0).keys.to_pylist() == ["b"] + + +def test_no_rows_are_never_written() -> None: + refused(keyed({"a": pa.array([1])}).slice(1), "no rows") + + +@pytest.mark.parametrize( + "make", + [ + lambda: pa.array([None, {"a": 1}], pa.struct([("a", pa.int8())])), + lambda: pa.array( + [[{"a": 1}, None], []], pa.list_(pa.struct([("a", pa.int8())])) + ), + lambda: pa.array( + [{"s": None}, {"s": {"a": 1}}], + pa.struct([("s", pa.struct([("a", pa.int8())]))]), + ), + ], +) +def test_a_null_struct_at_any_depth_is_refused(make: Any) -> None: + refused(keyed({"ok": pa.array([1, 2]), "bad": make()}), "'bad'", "null") + + +def test_a_null_struct_hidden_by_a_null_list_is_not_written() -> None: + items = pa.array([None, {"a": 1}], pa.struct([("a", pa.int8())])) + lists = pa.ListArray.from_arrays( + pa.array([0, 1, 2], pa.int32()), items, mask=pa.array([True, False]) + ) + _ = round_trip(keyed({"l": lists})) + + +def test_a_null_under_a_non_null_field_is_refused_at_any_depth() -> None: + not_null: Any = pa.field("v", pa.int64(), nullable=False) + for arrow_type, value in ( + (pa.list_(not_null), [[1, None]]), + (pa.struct([not_null]), [{"v": None}]), + (pa.list_(pa.struct([not_null])), [[{"v": 1}, {"v": None}]]), + ): + table = keyed({"x": pa.array(value, arrow_type)}) + error = refused(table, "'x'", "non-nullable") + assert error.path[0] == "x" and len(error.path) > 1 + refused( + keyed( + {"x": pa.array([None], pa.int8())}, + [not_null.with_name("x").with_type(pa.int8())], + ), + "'x'", + ) + + +def test_a_null_list_over_non_null_items_is_kept() -> None: + item = pa.field("item", pa.int64(), nullable=False) + _ = round_trip(keyed({"b": pa.array([[1], None, []], pa.list_(item))})) + + +@pytest.mark.parametrize( + "arrow_type", + [ + pa.string_view(), + pa.binary_view(), + pa.binary(4), + pa.duration("us"), + pa.month_day_nano_interval(), + pa.dictionary(pa.int32(), pa.string()), + pa.run_end_encoded(pa.int32(), pa.string()), + pa.list_view(pa.int64()), + pa.large_list_view(pa.int64()), + map_of(pa.field("k", pa.string(), False), pa.field("v", pa.int8())), + pa.sparse_union([pa.field("a", pa.int8())]), + pa.struct([]), + map_of(pa.string(), pa.field("value", pa.int8(), metadata={"k": "v"})), + map_of(pa.string(), pa.list_(pa.field("i", pa.int8(), metadata={"k": "v"}))), + ], + ids=str, +) +def test_a_type_the_store_does_not_keep_is_refused_at_every_depth( + arrow_type: pa.DataType, +) -> None: + for wrapped in ( + arrow_type, + pa.list_(arrow_type), + pa.struct([("ok", pa.int8()), ("s", arrow_type)]), + pa.list_(pa.struct([("s", pa.large_list(arrow_type))])), + ): + schema = schema_of( + [("a", pa.int64()), ("bad", wrapped), (KEY, pa.large_binary())] + ) + for call in (store.physical_schema, store.logical_schema, entries): + with pytest.raises(store.UnstorableInSpiralError, match="'bad'"): + call(schema) + + +def test_every_refusal_is_in_one_table() -> None: + assert [r.what for r in store.REFUSALS] == [ + "a null struct", + "a struct with no fields", + "a write of no rows", + "a null fixed-size list of structs", + "a map whose fields are not named key and value", + "field metadata inside a map", + "a string view or binary view", + "a fixed-size binary", + "a duration", + "an interval", + ] + assert all(r.why for r in store.REFUSALS) + + +def test_lifting_a_type_is_one_entry(monkeypatch: pytest.MonkeyPatch) -> None: + """A type shown to be kept natively moves from one table to the other.""" + matches = pa.types.is_duration + table = keyed({"d": pa.array([1, None, -2], duration("us"))}) + refused(table, "duration", "refuses") + monkeypatch.setattr( + store, + "REFUSALS", + tuple(r for r in store.REFUSALS if r.matches is not matches), + ) + refused(table, "keeps no type duration") + monkeypatch.setattr(store, "_NATIVE", (*store._NATIVE, matches)) # pyright: ignore[reportPrivateUsage] + encoded = store.encode_rows(table) + assert_same(decode(as_spiral_returns(encoded), table.schema), table) + + +def test_a_null_fixed_size_list_of_structs_is_refused() -> None: + struct = pa.struct([("a", pa.int8())]) + for ty, value in ( + (pa.list_(struct, 1), [[{"a": 1}], None]), + (pa.list_(pa.list_(struct, 1), 1), [[[{"a": 1}]], None]), + ): + refused(keyed({"f": pa.array(value, ty)}), "'f'", "null fixed-size list") + + +@pytest.mark.parametrize("nullable", [True, False]) +def test_a_null_key_is_refused_whatever_the_schema_says(nullable: bool) -> None: + key = pa.array([b"a", None], pa.large_binary()) + schema = schema_of([pa.field(KEY, pa.large_binary(), nullable), ("a", pa.int8())]) + column = pa.array([1, 2], pa.int8()) + refused(pa.Table.from_arrays([key, column], schema=schema), KEY) + with pytest.raises(store.StoredRowsError, match="null key"): + decode(pa.table({KEY: key, "a": column}), schema) + + +@pytest.mark.parametrize( + ("fields", "words"), + [ + ([("a", pa.int8())], "key column"), + ([(KEY, pa.large_binary())], "no column beside"), + ([(KEY, pa.int64()), ("a", pa.int8())], "must be binary"), + ([(KEY, pa.binary()), ("a", pa.int8()), ("a", pa.int8())], "more than once"), + ([(KEY, pa.binary()), (KEY, pa.binary()), ("a", pa.int8())], "key column"), + ( + [ + (KEY, pa.binary()), + ("a", pa.struct([("x", pa.int8()), ("x", pa.int8())])), + ], + "'a'", + ), + ], +) +def test_a_table_the_store_cannot_hold_is_refused(fields: Any, words: str) -> None: + with pytest.raises(store.UnstorableInSpiralError, match=words): + store.physical_schema(schema_of(fields)) + + +# ------------------------------------------------------------------- logical types + + +_ALIVE: list[Any] = [] +"""Arrow asks the class to read a type whose Python object is gone: keep them all.""" + + +class Labelled(pa.ExtensionType): + """An extension type registered or not, whose reading may fail.""" + + def __init__(self, storage: Any, name: str, metadata: bytes) -> None: + self._metadata = metadata + _ALIVE.append(self) + super().__init__(storage, name) + + def __arrow_ext_serialize__(self) -> bytes: + return self._metadata + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + raise AssertionError("the codec reads identifiers, never registered types") + + +@pytest.mark.parametrize("metadata", [b"", b'{"version":1}', b"\xff\x00\xfe"]) +@pytest.mark.parametrize("registered", [False, True]) +def test_a_logical_type_is_kept_by_its_identifier( + metadata: bytes, registered: bool +) -> None: + """Live and annotated give one schema; a registered type is never consulted.""" + storage = pa.struct( + [pa.field("z.1", timestamp("us", tz="UTC")), ("a", pa.binary())] + ) + name = f"test.itl1446.{metadata.hex()}" + live = Labelled(storage, name, metadata) + values = [{"z.1": dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc), "a": b"xy"}] * 2 + stored = pa.array(values, storage) + annotated = pa.field( + "c", + storage, + True, + {NAME_KEY: name.encode(), METADATA_KEY: metadata, b"k": b"v"}, + ) # pyright: ignore[reportArgumentType] + if registered: + pa.register_extension_type(cast(Any, live)) + try: + one = keyed( + {"c": pa.ExtensionArray.from_storage(live, stored), "d": pa.array([1, 2])}, + [pa.field("c", live, True, {"k": "v"}), pa.field("d", pa.int64())], + ) + two = keyed( + {"c": stored, "d": pa.array([1, 2])}, [annotated, pa.field("d", pa.int64())] + ) + assert store.encode_rows(one).equals(store.encode_rows(two)) + assert_same(round_trip(one), round_trip(two)) + schema = read(entries(one.schema)).schema + assert schema.field("c").metadata == annotated.metadata + assert pa.types.is_struct(schema.field("c").type) + back = decode(as_spiral_returns(store.encode_rows(one)), one.schema) + assert by_id(back).column("c").chunk(0).type == live + finally: + if registered: + pa.unregister_extension_type(name) + + +def test_another_identifier_is_another_schema() -> None: + def schema(name: str, metadata: bytes) -> pa.Schema: + live = Labelled(pa.large_string(), name, metadata) + return schema_of([("c", live), (KEY, pa.large_binary())]) + + base = schema("n", b"1") + assert store.schema_difference(base, schema("n", b"1")) is None + for other in (schema("n", b"2"), schema("m", b"1"), schema("n", b"")): + difference = store.schema_difference(base, other) + assert difference is not None and "'c'" in difference + + +def test_a_logical_type_below_a_plain_type_is_refused() -> None: + live = Labelled(pa.int8(), "test.nested", b"") + annotated = pa.field("v", pa.int8(), metadata={NAME_KEY: b"n"}) + inners: Any = (pa.field("v", live), annotated, pa.field("v", pa.uuid())) + for inner in inners: + for arrow_type in ( + pa.list_(inner), + pa.struct([inner]), + pa.list_(pa.struct([inner])), + map_of(pa.string(), inner), + ): + schema = schema_of([("c", arrow_type), (KEY, pa.large_binary())]) + with pytest.raises(store.UnstorableInSpiralError, match="nested"): + store.logical_schema(schema) + # A live type whose field is annotated as another one is two logical types. + both = pa.field("c", live, metadata={NAME_KEY: b"n"}) + with pytest.raises(store.UnstorableInSpiralError, match="nested"): + store.logical_schema(schema_of([both, (KEY, pa.large_binary())])) + + +# ------------------------------------------------------------------- rows, as read + + +def _stored(table: pa.Table) -> pa.Table: + return as_spiral_returns(store.encode_rows(table)) + + +def large_table(table: pa.Table) -> pa.Table: + return table.cast(large(table.schema)) + + +def test_rows_that_are_not_what_was_written_are_refused() -> None: + inner = pa.struct([pa.field("a.b", pa.int8(), False), pa.field("c", pa.int8())]) + fields = [ + pa.field("n", pa.int64(), False), + pa.field("t", timestamp("us", tz="UTC")), + pa.field("s", inner), + pa.field("l", pa.list_(inner)), + pa.field("f", pa.list_(pa.int8(), 2)), + pa.field("m", pa.map_(pa.string(), pa.int8())), + ] + table = keyed( + { + "n": pa.array([1]), + "t": pa.array([1], timestamp("us", tz="UTC")), + "s": pa.array([{"a.b": 1, "c": 2}], inner), + "l": pa.array([[{"a.b": 1, "c": 2}]], pa.list_(inner)), + "f": pa.array([[1, 2]], pa.list_(pa.int8(), 2)), + "m": pa.array([[("a", 1)]], pa.map_(pa.string(), pa.int8())), + }, + fields, + ) + schema, good = table.schema, _stored(table) + manifest = new(schema) + assert_same(decode(good, schema), large_table(table)) + store.require_stored_schema(good.schema, manifest) + + def bad(name: str, array: Any, *words: str, value: bool = False) -> None: + rows = good.set_column(good.column_names.index(name), name, array) + calls: list[Any] = [lambda: decode(rows, schema)] + if not value: + calls.append(lambda: store.require_stored_schema(rows.schema, manifest)) + for call in calls: + with pytest.raises(store.StoredRowsError) as info: + call() + assert all(w in str(info.value) for w in (f"'{name}'", *words)) + + stored = pa.struct([("c", pa.int8()), ("ox_a;2Eb", pa.int8())]) + more = pa.struct([*stored, pa.field("x", pa.int8())]) + raw = pa.struct([("c", pa.int8()), ("a.b", pa.int8())]) + bad("n", pa.array([None], pa.int64()), "null", value=True) + bad("n", pa.array([1], pa.int32()), "int32") + bad("t", pa.array([1], timestamp("us")), "timestamp[us]") + bad("t", pa.array([1], timestamp("us", tz="UTC")), "UTC") + bad("t", pa.array([1], pa.int32()), "int32") + bad("s", pa.array([{"c": 1}], pa.struct([("c", pa.int8())])), "missing") + bad("s", pa.array([{"c": 1}], more), "not expected ['x']") + bad("s", pa.array([{"c": 1}], raw), "not expected ['a.b']") + bad("s", pa.array([1]), "int64") + bad("s", pa.array([[]], pa.list_(pa.int8())), "list") + bad("s", pa.array([None], stored), "null struct", value=True) + bad("s", pa.array([{"c": 1}], stored), "a.b", "null", value=True) + bad("l", pa.array([[{"c": 1}]], pa.list_(stored)), "a.b", "null", value=True) + bad("l", pa.array([[{"c": 1}]], pa.list_(raw)), "not expected ['a.b']") + bad("l", pa.array([1]), "int64") + bad("f", pa.array([[1, 2, 3]], pa.list_(pa.int8(), 3)), "[3]") + bad("f", pa.array([[1, 2]], pa.list_(pa.int16(), 2)), "int16") + bad("f", pa.array([[1, 2]], pa.list_(pa.int8())), "list") + bad("m", pa.array([[("a", 1)]], pa.map_(pa.string(), pa.int16())), "int16") + bad("m", pa.array([[(b"a", 1)]], pa.map_(pa.binary(), pa.int8())), "binary") + bad("m", pa.array([1]), "int64") + for rows in (good.drop_columns(["n"]), good.append_column("m", pa.array([1]))): + with pytest.raises(store.StoredRowsError, match="'(n|m)'"): + decode(rows, schema) + repeated = pa.Table.from_arrays( + [*good.columns, good.column("n")], names=[*good.column_names, "n"] + ) + with pytest.raises(store.StoredRowsError, match="repeated"): + decode(repeated, schema) + + +def test_rows_are_given_the_recorded_schema_only() -> None: + table = keyed({"a": pa.array([1]), "b": pa.array(["x"])}) + manifest, stored = new(table.schema), _stored(table) + for schema in ( + table.schema.set(0, pa.field("a", pa.int32())), + table.schema.remove(0), + schema_of(list(reversed(list(table.schema)))), + table.schema.set(0, pa.field("a", pa.int64(), metadata={"k": "v"})), + ): + with pytest.raises(store.ManifestError, match="not the recorded schema"): + store.decode_rows(stored, manifest, schema) + + +def test_a_table_with_a_manifest_and_no_rows_reads_as_no_rows() -> None: + schema = wide_schema(20) + rows = store.empty_rows(read(entries(schema))) + assert rows.num_rows == 0 + assert rows.schema.equals(store.logical_schema(schema), check_metadata=True) + + +# ------------------------------------------------------------------------ manifest + + +def wide_schema(columns: int = 200) -> pa.Schema: + """Several tags, data columns and nested ones, each with metadata.""" + fields: list[Any] = [pa.field(KEY, pa.large_binary(), False)] + for i in range(columns - 1): + arrow_type: Any = [ + pa.int64(), + timestamp("ns", tz="Asia/Kathmandu"), + pa.struct([pa.field("__a.b", pa.string(), False, {"depth": "1"})]), + pa.list_(pa.field("odd", pa.binary(), False, {"unit": "m" * 30})), + Labelled(pa.large_string(), f"test.wide.{i}", b'{"version":1}'), + ][i % 5] + metadata = {"orcapod:data_tag": "1", "note": f"{i:040d}", b"\xff": b"\x00\xfe"} + fields.append( + pa.field(f"__col.{i}", arrow_type, i % 3 > 0, cast(Any, metadata)) + ) + return schema_of(fields, metadata={"table": "x" * 100}) + + +def test_a_manifest_of_200_columns_with_metadata() -> None: + schema = wide_schema() + assert len(schema) == 200 + path = ("run", "a", "b", "", "é", '"', "\u2028") + metadata = {**entries(schema, path), "other": b"kept"} + ours = {k: v for k, v in metadata.items() if k.startswith(store.MANIFEST_PREFIX)} + assert 3 < len(ours) <= 1024 + for key, value in ours.items(): + assert len(key) <= 90 and key.isascii() + assert len(key) + len(value) <= 8192 + manifest = read(metadata, path) + assert manifest == new(schema, path) + assert manifest.record_path == path + assert manifest.kind == "function_pipeline" + assert manifest.schema.equals(store.logical_schema(schema), check_metadata=True) + for a, b in zip(store.logical_schema(schema), manifest.schema): + assert field_difference(a, b, a.name) is None + + +def test_a_manifest_does_not_depend_on_the_order_of_the_metadata() -> None: + metadata = {**entries(wide_schema()), "other": b"x"} + items = list(metadata.items()) + for seed in range(5): + random.Random(seed).shuffle(items) + assert read(dict(items)) == read(metadata) + + +def test_a_payload_of_another_pyarrow_is_the_same_schema(monkeypatch: Any) -> None: + """Other bytes (field metadata written in another order) decode to one schema.""" + schema = wide_schema(20) + first = entries(schema) + + def reordered(field: Any) -> Any: + t = field.type + if pa.types.is_struct(t): + t = pa.struct([reordered(f) for f in t]) + elif pa.types.is_large_list(t): + t = pa.large_list(reordered(t.value_field)) + metadata = dict(reversed(list((field.metadata or {}).items()))) + return pa.field(field.name, t, field.nullable, cast(Any, metadata or None)) + + original = store.logical_schema + monkeypatch.setattr( + store, + "logical_schema", + lambda s: schema_of([reordered(f) for f in original(s)], metadata=s.metadata), + ) + second = entries(schema) + monkeypatch.undo() + assert not set(first) & set(second) + with pytest.raises(store.ManifestError, match="more than one"): + store.read_manifest({**second, **first}, PATH) + one, two = read(first).schema, read(second).schema + assert list(one.field(1).metadata or {}) != list(two.field(1).metadata or {}) + assert store.schema_difference(one, two) is None + + +def test_every_row_of_the_matrix_round_trips_in_one_manifest(tmp_path: Path) -> None: + fields: list[Any] = [pa.field(KEY, pa.large_binary(), False)] + for row in ROWS: + if row.label in REFUSED_ROWS: + continue + if row.provisional: + continue + for name in ("x", "y"): + fields.append( + build_table(row, tmp_path) + .schema.field(name) + .with_name(f"{row.label}.{name}") + ) + for order in (fields, list(reversed(fields))): + schema = schema_of(order) + got = read(entries(schema)).schema + assert got.names == schema.names + for a, b in zip(store.logical_schema(schema), got): + assert field_difference(a, b, a.name) is None + + +def test_metadata_keys_that_look_like_the_marks_are_kept() -> None: + metadata = { + b"orcapod:key:ARROW:extension:name": b"1", + b"orcapod:key:": b"2", + b"orcapod:key:orcapod:key:x": b"3", + b"ARROW:extension:other": b"4", + NAME_KEY: b"n", + METADATA_KEY: b"m", + } + field = pa.field("a", pa.int8(), metadata=cast(Any, metadata)) + schema = schema_of([field, (KEY, pa.large_binary())]) + assert read(entries(schema)).schema.field("a").metadata == metadata + + +BASE: list[Any] = [ + pa.field("a", pa.struct([pa.field("x", pa.int8()), pa.field("y", pa.int8())])), + pa.field("l", pa.large_list(pa.field("item", timestamp("us", tz="UTC")))), + pa.field("f", pa.large_list(pa.field("item", pa.int8()))), + pa.field(KEY, pa.large_binary(), False), +] +MAPPED: list[Any] = [*BASE, pa.field("x", map_of(pa.string(), pa.int8()))] + + +def test_the_order_of_columns_is_no_difference() -> None: + for order in ([3, 2, 1, 0], [1, 0, 3, 2]): + other = schema_of([BASE[i] for i in order]) + assert store.schema_difference(schema_of(BASE), other) is None + + +@pytest.mark.parametrize( + "changed", + [ + BASE[0].with_name("b"), + BASE[0].with_nullable(False), + BASE[0].with_metadata({"k": "v"}), + BASE[0].with_type(pa.struct([("x", pa.int8()), ("z", pa.int8())])), + BASE[0].with_type(pa.struct([("y", pa.int8()), ("x", pa.int8())])), + BASE[0].with_type(pa.struct([("x", pa.int8())])), + BASE[0].with_type( + pa.struct([pa.field("x", pa.int8(), False), ("y", pa.int8())]) + ), + BASE[0].with_type( + pa.struct([pa.field("x", pa.int8(), metadata={"k": "v"}), ("y", pa.int8())]) + ), + BASE[0].with_type(pa.int8()), + BASE[1].with_type(pa.large_list(pa.field("other", timestamp("us", tz="UTC")))), + BASE[1].with_type(pa.large_list(timestamp("us", tz="Etc/UTC"))), + BASE[1].with_type(pa.large_list(timestamp("us"))), + BASE[1].with_type(pa.large_list(timestamp("ms", tz="UTC"))), + BASE[2].with_type(pa.large_list(pa.int16())), + BASE[2].with_type(pa.list_(pa.int8(), 2)), + pa.field("x", map_of(pa.string(), pa.int8(), keys_sorted=True)), + BASE[2].with_type(pa.large_list(pa.large_list(pa.int8()))), + ], + ids=str, +) +def test_another_schema_is_a_difference(changed: Any) -> None: + index = next((i for i, f in enumerate(MAPPED) if f.name == changed.name), 0) + fields = list(MAPPED) + fields[index] = changed + one, other = read(entries(schema_of(MAPPED))).schema, schema_of(fields) + for a, b in ((one, other), (other, one)): + assert store.schema_difference(a, b) is not None + + +def test_schema_metadata_and_more_columns_are_a_difference() -> None: + schema = schema_of(BASE) + for other in ( + schema.with_metadata({"k": "v"}), + schema_of([*BASE, ("more", pa.int8())]), + ): + assert store.schema_difference(schema, other) is not None + + +@pytest.mark.parametrize("same", [True, False]) +def test_two_headers_are_refused_also_when_they_agree(same: bool) -> None: + fields = list(reversed(BASE)) if same else BASE[1:] + one, other = entries(schema_of(BASE)), entries(schema_of(fields)) + for both in ({**one, **other}, {**other, **one}): + with pytest.raises(store.ManifestError, match="more than one") as info: + store.read_manifest(both, PATH) + for key in (k for k in both if k.count("/") == 1): + assert key.split("/")[1] in str(info.value) + + +def test_a_manifest_of_another_path_is_refused() -> None: + metadata = entries(schema_of(BASE), ("a", "b")) + for path in (("a",), ("b", "a"), ("a", "b", ""), ("a_b",), ()): + with pytest.raises(store.ManifestError, match="recorded as"): + store.read_manifest(metadata, path) + + +@pytest.mark.parametrize("part", ["a/b", "a\0", "\udc00"]) +def test_a_path_component_the_store_cannot_name_is_refused(part: str) -> None: + with pytest.raises(store.UnstorableInSpiralError): + new(schema_of(BASE), ("x", part)) + + +def test_stored_names_come_from_the_manifest_not_from_the_rule( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A table written under an earlier naming rule is still read by its own names.""" + table = keyed( + { + "a.b": pa.array([1]), + "ox_a;2Eb": pa.array([2]), + "s": pa.array([{"c.d": 3}], pa.struct([("c.d", pa.int64())])), + } + ) + metadata, stored = entries(table.schema), _stored(table) + monkeypatch.setattr(store, "encode_name", lambda name: "new_" + name.encode().hex()) + manifest = read(metadata) + assert "ox_a;2Eb" in manifest.physical.names + got = store.decode_rows(stored, manifest) + assert [got.column(n)[0].as_py() for n in table.column_names if n != KEY] == [ + 1, 2, {"c.d": 3}, + ] # fmt: skip + + +def test_a_table_without_a_manifest_has_none() -> None: + for other in ({}, {"__arrow_metadata__": b"{}", "x": b""}): + assert store.read_manifest(other, PATH) is None + chunks, header = store.manifest_entries(new(schema_of(BASE))) + assert store.read_manifest(chunks, PATH) is None # the header never came + # Chunks of another creation that was interrupted change nothing. + more, _ = store.manifest_entries(new(schema_of(BASE), ("z",))) + assert read({**more, **chunks, **header}) == new(schema_of(BASE)) + + +def _rewritten(metadata: dict[str, bytes], **changes: Any) -> dict[str, bytes]: + key = next(k for k in metadata if k.count("/") == 1) + return { + **metadata, + key: json.dumps({**json.loads(metadata[key]), **changes}).encode(), + } + + +def _payload(**changes: Any) -> dict[str, bytes]: + """A manifest whose payload is changed, under the digest it then has.""" + chunks, _ = store.manifest_entries(new(schema_of(BASE))) + body = {**json.loads(b"".join(chunks.values())), **changes} + payload = json.dumps(body).encode() + digest = store._digest(payload) # pyright: ignore[reportPrivateUsage] + header = { + "chunks": 1, + "format": "orcapod.spiral_store.draft", + "sha256": digest, + "version": 0, + } + return { + f"{store.MANIFEST_PREFIX}{digest}": json.dumps(header).encode(), + f"{store.MANIFEST_PREFIX}{digest}/0": payload, + } + + +def _ipc(schema: pa.Schema) -> str: + return base64.b64encode(schema.serialize().to_pybytes()).decode() + + +def _header(metadata: dict[str, bytes]) -> str: + return next(k for k in metadata if k.count("/") == 1) + + +_A = pa.struct([("x", pa.int8()), ("y", pa.int8())]) +_TWICE = pa.struct([("x", pa.int8()), ("x", pa.int8())]) +_B = pa.large_binary() +_L = pa.large_list(timestamp("us")) + + +def _physical(index: int, field: Any) -> Any: + """The stored schema of ``BASE`` with one column changed.""" + return store.physical_schema(schema_of(BASE)).set(index, field) + + +def test_chunks_in_another_order_are_refused() -> None: + metadata = entries(wide_schema()) + header = _header(metadata) + swapped = {**metadata, f"{header}/0": metadata[f"{header}/1"]} + swapped[f"{header}/1"] = metadata[f"{header}/0"] + with pytest.raises(store.ManifestError, match="do not match"): + store.read_manifest(swapped, PATH) + + +def test_the_changed_payload_helper_builds_a_readable_manifest() -> None: + assert read(_payload()) == new(schema_of(BASE)) + + +@pytest.mark.parametrize( + "make", + [ + lambda m: {k: v for k, v in m.items() if not k.endswith("/0")}, + lambda m: {k: (v + b" " if k.endswith("/0") else v) for k, v in m.items()}, + lambda m: {k: (b"[]" if k.count("/") == 1 else v) for k, v in m.items()}, + lambda m: {k: (b"\xff" if k.count("/") == 1 else v) for k, v in m.items()}, + lambda m: _rewritten(m, format="other"), + lambda m: _rewritten(m, version=1), + lambda m: _rewritten(m, version=False), + lambda m: _rewritten(m, chunks=0), + lambda m: _rewritten(m, chunks="1"), + lambda m: _rewritten(m, chunks=10**9), + lambda m: _rewritten(m, chunks=2), + lambda m: _rewritten(m, sha256="0" * 64), + lambda m: {**m, store.MANIFEST_PREFIX + "other": b""}, + lambda m: {**m, _header(m) + "/1": b""}, + lambda m: {**m, _header(m) + "/7": b""}, + lambda m: _payload(kind=1), + lambda m: _payload(record_path=["other"]), + lambda m: _payload(physical=_ipc(schema_of([("a", pa.int8())]))), + lambda m: _payload(physical=_ipc(_physical(0, pa.field("a", pa.int8())))), + lambda m: _payload(physical=_ipc(_physical(0, pa.field(KEY, _A)))), + lambda m: _payload(physical=_ipc(_physical(3, pa.field("k", _B)))), + lambda m: _payload(physical=_ipc(_physical(1, pa.field("f", _L)))), + lambda m: _payload(physical=_ipc(_physical(0, pa.field("a", _TWICE)))), + lambda m: {**m, store.MANIFEST_PREFIX + "0" * 64 + "/01": b""}, + lambda m: _payload(version=1), + lambda m: _payload(record_path="a"), + lambda m: _payload(record_path=[1]), + lambda m: _payload(schema=1), + lambda m: _payload(schema="!!"), + lambda m: _payload(schema=base64.b64encode(b"junk").decode()), + lambda m: _payload(schema=_ipc(schema_of([("a", pa.int8())]))), + lambda m: _payload(schema=_ipc(schema_of([*BASE, ("m", pa.binary(2))]))), + ], +) +def test_a_manifest_that_cannot_be_read_in_full_is_an_error(make: Any) -> None: + metadata = make(entries(schema_of(BASE))) + with pytest.raises(store.ManifestError): + store.read_manifest(metadata, PATH) + + +def test_a_manifest_over_the_limit_is_refused() -> None: + field = pa.field("a", pa.int8(), metadata={"k": "v" * 7_000_000}) + with pytest.raises(store.ManifestError, match="1024"): + entries(schema_of([field, (KEY, pa.large_binary())])) + small = pa.field("a", pa.int8(), metadata={"k": "v" * 1_000_000}) + schema = schema_of([small, (KEY, pa.large_binary())]) + assert read(entries(schema)).schema.equals(schema, check_metadata=True) + + +def test_writing_the_same_manifest_twice_changes_nothing() -> None: + one = entries(wide_schema()) + assert entries(wide_schema()) == one + chunks, header = store.manifest_entries(read(one)) + assert {**chunks, **header} == one + + +def test_the_codec_needs_no_pyspiral() -> None: + code = ( + "import sys, orcapod.databases.spiral_store\n" + "assert not [m for m in sys.modules if m.split('.')[0] == 'spiral']" + ) + assert subprocess.run([sys.executable, "-c", code], check=False).returncode == 0