diff --git a/RELEASING.md b/RELEASING.md index 72aa1fd26..db3c95d4a 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -342,6 +342,11 @@ releases daily, of which Orcapod uses two attributes that are not public API To move the pin: change it there, run `uv lock`, and run the conformance tests live (`tests/test_databases/test_spiraldb_connector_integration.py`, see its docstring). A refusal or a value that changed is a change of `tests/test_databases/fake_spiral_sdk.py` (its `RULES`) first. +From 0.16.79 spiral-sdk warns on every keyed-table open; Orcapod's connector ignores that one +message for its own opens (`spiraldb_connector._ignore_keyed_table_deprecation`), and +`tests/test_databases/test_spiraldb_keyed_table_deprecation.py` fails if a new release changes +the message, the category or the module it is attributed to. The move off keyed tables is +ITL-1846. ### Migrating a SpiralDB dataset from pyspiral @@ -358,12 +363,12 @@ uv run --no-project --isolated --python 3.12 \ uv run --no-project --isolated --python 3.12 \ --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ - --with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \ + --with spiral-sdk==0.16.80 scripts/migrate_spiral_schemas.py \ write --project --dataset --plan plan.json --digest uv run --no-project --isolated --python 3.12 \ --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ - --with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \ + --with spiral-sdk==0.16.80 scripts/migrate_spiral_schemas.py \ verify --project --dataset --plan plan.json ``` diff --git a/changelog.d/ITL-1837.md b/changelog.d/ITL-1837.md new file mode 100644 index 000000000..4fa7f484e --- /dev/null +++ b/changelog.d/ITL-1837.md @@ -0,0 +1,16 @@ +### Changed + +- The `spiraldb` extra pins `spiral-sdk==0.16.80` (was `0.16.74`), a release that reads + and writes a SpiralDB table's own metadata. spiral-sdk 0.16.79 and later mark the keyed + tables Orcapod reads as deprecated and warn on every open; Orcapod ignores that one + warning for its own opens only, so a direct call to spiral-sdk still warns. The move to + spiral-sdk's newer table format is ITL-1846. Orcapod still only reads SpiralDB. + (ITL-1837) + +### Known limitations + +- Orcapod cannot yet use SpiralDB as a job's database: `SpiralDBConnector` still refuses + every write. The groundwork for it (the encoding of a stored table's columns and the + identity record kept in a table's metadata) is internal and its format is provisional: + outside the 0.4.0 freeze, it may change before the store is offered, and tables written + in it may then need to be written again. (ITL-1837) diff --git a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md new file mode 100644 index 000000000..de7f31bdd --- /dev/null +++ b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md @@ -0,0 +1,139 @@ +# ITL-1837: SpiralDB store, stage A (dependency, identity record, codec) + +Stage A of using SpiralDB as a job's pipeline and result database (ITL-1446). It carries +the still-valid parts of PRs 589 (ITL-1495) and 590 (ITL-1497) onto current `main`, and the +manifest-in-metadata part of PR 595 (ITL-1498). Those branches were sources to copy from; +none is merged. Nothing here is public: no way to open a store exists, and +`SpiralDBConnector` still refuses every write (`SpiralDBWriteNotSupportedError`). + +## The store format is provisional + +Everything this stage defines about what a store table holds is **provisional**: outside +the 0.4.0 freeze, free to change until the store is switched on (a later stage, with a +developer decision). That covers the identity record's keys and values, the manifest's +header and chunking, the codec's physical encoding and its name escape. Both markers say +so: the identity record's format is `orcapod.spiral_store.draft` +(`spiral_store_identity.STORE_FORMAT`), the manifest's `orcapod.spiral_store.draft` +version 0 (`spiral_store.MANIFEST_FORMAT`). When the format is fixed it gets a new marker, +and what to do with draft tables is decided then. No golden value pins any of it. + +## 1. spiral-sdk 0.16.80 + +Table metadata arrives in two steps: `KeyedTable.get_metadata` first appears in 0.16.76, +and `set_metadata` in 0.16.77 (neither is in 0.16.74 or 0.16.75). The table metadata, the +type rules and the entry limits were measured live with 0.16.78 (2026-11-26). Compared with +`main`'s 0.16.74, the Python layer changes only those two methods (and the generated service +schemas); the snapshot pinning (`keyed_table_by_id(..., asof=)`), projection +(`scan(columns=)`) and key ranges `main` uses are untouched. + +The pin is 0.16.80 (2026-12-01), the newest release, at the developer's request: the newest +SDK, provided the keyed-table deprecation can be silenced in a targeted way. 0.16.79 marks +keyed tables deprecated: `Client.keyed_table`, `keyed_table_by_id` and +`Project.create_keyed_table` each call `warn("Keyed tables are deprecated.", +DeprecationWarning, stacklevel=3)`, so the warning is attributed to the module that calls +the SDK. 0.16.80 changes nothing else Orcapod uses (it removes the duration types, which +the store already refuses). Orcapod's only module that opens or creates keyed tables is +`orcapod.databases.spiraldb_connector` (the schema migration script opens and creates +through its helpers `_open_keyed_table` and `_create_keyed_table`); before each open or +creation it puts one filter FIRST in the filter list: action `ignore`, that exact message, +`DeprecationWarning`, and that module only (`_ignore_keyed_table_deprecation`). First, not +merely present, because the first matching filter wins: a filter added after an earlier +open (`simplefilter("error")`, `pytest.warns`, a recording `catch_warnings`) would +otherwise rank ahead of it. `filterwarnings` removes the older copy before inserting, so +the list never grows. A user's own call to the SDK, another message and another category +still warn. It is installed before each open, not once at import, because a +`warnings.catch_warnings` block (pytest wraps every test in one) drops a filter added +inside it, and it uses no `catch_warnings` itself, which is not safe with threads. +`tests/test_databases/test_spiraldb_keyed_table_deprecation.py` checks both sides with the +real SDK client over a stub native client, and the fake SDK warns as 0.16.80 does (rule +`deprecated`). Not tested: Python 3.14's context-aware warnings (the default of the +free-threaded build), where `catch_warnings` filters are context-local; CI covers Python +3.11 to 3.13 only. + +The live conformance run on 0.16.80 (2026-12-01, as the agent workload, in the +conformance dataset of the test project) found one measured rule change: a keyed-table +write of a `duration[s]` column, which 0.16.78 refused, is accepted and read back with the +same unit and value (the same case run again with 0.16.78 is still refused, so the change +comes with the SDK, not the service). The fake follows 0.16.80 (rule `unsupported`), the +refusal test no longer lists durations, and +`test_a_duration_is_stored_and_read_back_as_given` checks the read-back. The store codec +still refuses durations: whether it stores them is ITL-1852. `main`'s CI keeps the 0.16.78 +rules until this pin merges. Side effect of the run: the existing fixed table +`store_codec_refusals` got a new version at 2026-12-01 23:41:50 UTC with a new column +`d: duration[s]` and one row (`k = "r0"`, one second), and the read-back check wrote that +same row again at 23:44:22 UTC. No table was created. A SpiralDB source over a duration +column reads it as any source does: the Arrow type is kept and the Python type is `Any`; +no test pins it. + +Keyed tables are on their way out; their replacement (Tables, with branches and commits) +has no primary key and no table metadata. The move is ITL-1846. The conformance tests ran +live on 0.16.80 before the pin moved. + +The bump is a dependency change for the developer to approve; it is one commit of its own +(`pyproject.toml`, `uv.lock`, `RELEASING.md`, the filter and its tests). + +## 2. The fake's table metadata + +`tests/test_databases/fake_spiral_sdk.py`, rule `table-metadata` (measured live with +0.16.78 on 2026-11-26): bytes by text key; an upsert that never deletes (an empty value is +stored); not versioned (every snapshot, `asof` included, sees the latest; a metadata write +makes no snapshot); readable before any row; a key over 255 UTF-8 bytes, or a key and value +together over 8,192 bytes, is refused with status 400 and nothing is written. Upserts of +different keys from two clients are all kept, and a reader never sees a half-written file. + +## 3. The identity record + +`src/orcapod/databases/spiral_store_identity.py`, on `main`'s shared rule +(`store_table_names.py`, ITL-1552): the table name is +`store_table_name(path, hint_length=96, digest_length=64)`. The label +`SPIRAL_TABLE_NAME_LABEL` stays defined there only, and no golden group is added (PR 589's +`spiral_table_name` group is not carried over); `test_store_table_names.py` keeps the test +vector. + +The table's metadata records, as four entries: the store format, the full path (compact +UTF-8 JSON array), the layout (the path's last component) and the data context of the +writer that created it. A table whose record is partial, of another format, unreadable, or +of another path than the one looked up raises `SpiralStoreTableCollisionError`; a table with +none of the entries is unmarked (`None`), for the caller to judge. + +## 4. The codec + +`src/orcapod/databases/spiral_store.py` (pure; no client), from PR 590 with PR 595's +manifest functions. Names (`encode_name`), types (`physical_schema`, `encode_rows`, +`decode_rows`), refusals before anything is written (`REFUSALS`), and the manifest: the +record path, the kind, the logical schema and the stored names at every depth, as one +payload (`manifest_bytes`) cut into metadata entries of at most 8,000 bytes +(`manifest_entries`) under a header naming the format, version, chunk count and a SHA-256 of +the payload (`payload_digest`; renamed from PR 595's `sha256` key, which the hash label rule +reads as a label literal). A header names exactly its chunks, so chunks of an earlier, +longer manifest are never read. + +`main`'s type matrix gained four rows after PR 590 (ITL-1372): a live logical type in a +struct child, a list item and a map value, and in dictionary values. The codec refuses all +four, naming the column: it records a logical type only on a whole column, and a dictionary +is an encoding it refuses. They are now listed as expected refusals; the four rows and the +round trip of every other row in one manifest pass. + +### Measured live with spiral-sdk 0.16.78 (2026-11-26, throwaway tables; PR 590) + +| What | Result | +|---|---| +| booleans, integers (`uint64` max), floats (signed zeros and NaN payloads, `float16` too), `decimal128/256`, `date32`, `date64` off midnight, `null` | kept bit for bit | +| timestamps of every unit, with and without a zone, every `int64` value | kept bit for bit: written as they are | +| `time32` / `time64` within a day | kept; outside one day the whole write is refused, so times are written as integers | +| `decimal32/64` | come back as `decimal128`: written as such, restored | +| strings, binaries, lists | come back in their small variants: normalized on read | +| struct fields | sorted by name at the top level (not inside a list): restored by name | +| map `keys_sorted` | dropped: restored from the manifest | +| a null fixed-size list of structs | kept | +| a null struct item inside a list | kept by the service; refused by the codec, which does not carry a struct's validity yet | +| a null struct at the top level, an empty struct, `fixed_size_binary`, `duration`, `interval` | refused | +| column and struct field names | refused: a `__` or `$` prefix, any `.`, exactly `*`, the empty name; NUL is cut silently. The codec's escape covers each | +| a write of no rows | publishes nothing; a key-only write is refused | + +## What is left (later stages of ITL-1446) + +Store mode in `SpiralDBConnector` and `ConnectorArrowDatabase` (create on first write, find +by name, the identity and manifest checks, data-context checks, listing for stale layouts), +the write rules of ITL-1386 for the store, the one-writer lease, the public switch-on with +save and load, and every table kind end to end. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 365a3703d..b987f3d6f 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -391,6 +391,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 schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` | +| SpiralDB store manifest checksum | a store table's manifest payload (record path and Arrow schemas, canonical JSON); the store is provisional | SHA-256 hex | the manifest header's check of its chunks in the table's metadata (a checksum of a stored record) | `databases/spiral_store.py:_checksum` | | Connector store table name | the full store path, as a compact UTF-8 JSON array of path components | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`) | the bare hexadecimal suffix in a table name, with a length set by the backend | `databases/store_table_names.py:store_table_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) | diff --git a/pyproject.toml b/pyproject.toml index d5db39436..6a22699a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ postgresql = ["psycopg[binary]>=3.1.17"] spiraldb = [ # Exact: a pre-alpha that releases daily, and Orcapod reads two attributes that are # not its public API (ITL-1186). How to move it: RELEASING.md. - "spiral-sdk==0.16.74", + "spiral-sdk==0.16.80", ] # Convenience extra that installs PyTorch. Orcapod's torch.Tensor support depends only on # torch being importable, however it was installed (ITL-871). 2.6 is the first version whose diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 811de8d79..e7557892e 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -342,7 +342,10 @@ def require_unchanged( rows: list[Any], ) -> None: """Refuse unless every table of the dataset is as the plan found it.""" - from orcapod.databases.spiraldb_connector import _list_keyed_tables + from orcapod.databases.spiraldb_connector import ( + _list_keyed_tables, + _open_keyed_table, + ) from orcapod.databases.spiraldb_schema_table import ( compared_columns, describe_difference, @@ -358,8 +361,10 @@ def require_unchanged( f"{sorted(set(names) ^ set(planned))}" ) for table, row in zip(tables, rows): - handle = client.keyed_table(project, dataset, row.table_name) + handle = _open_keyed_table(client, project, dataset, row.table_name) where = f"{dataset}/{row.table_name}" + if handle is None: + raise MigrationError(f"{where} was removed since it was listed") if handle.resource_id != row.table_id: raise MigrationError(f"{where} is another table than in the dry run") if int(handle.version_id) != table["row"]["captured_version"]: @@ -459,6 +464,7 @@ def write(args: argparse.Namespace) -> None: import pyarrow as pa from orcapod.databases import spiraldb_schema_table as st + from orcapod.databases.spiraldb_connector import _create_keyed_table plan = read_plan(args.plan) require_scope(plan, args) @@ -499,8 +505,13 @@ def put(dataset: str, values: dict[str, Any]) -> None: # Created once, exclusively; the note is there before and after. write_note(args, dataset, CREATING) try: - handle = client.project(project).create_keyed_table( - dataset, SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=False + handle = _create_keyed_table( + client, + project, + dataset, + SCHEMA_TABLE, + st.KEY_SCHEMA, + exist_ok=False, ) except Exception as exc: if "status 409" not in str(exc): diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py new file mode 100644 index 000000000..100d0bbab --- /dev/null +++ b/src/orcapod/databases/spiral_store.py @@ -0,0 +1,1202 @@ +"""The codec of an Orcapod store table in SpiralDB (ITL-1446, ITL-1837). + +Pure functions, with no SpiralDB client: they say how a table Orcapod stores is written to +SpiralDB and how it is read back. Nothing calls them yet, and the format they write is +provisional (outside the 0.4.0 freeze). What SpiralDB keeps was measured live with +spiral-sdk 0.16.78; the measurements and the design are summarized in +``docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md``. + +* **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, written before its first rows; a table that still has + no rows may be recorded again (``manifest_entries``, ``read_manifest``): the + record path, the kind, the logical schema, and the stored names at every depth. It is + kept in the table's own metadata, in chunks of at most 8 KiB, beside the table's identity + record (``spiral_store_identity``); never in the dataset's schema table, which is all + or nothing under one completion marker (decision of 2026-11-26). + +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 +import pyarrow.compute as pc + +from orcapod.databases.store_table_names import require_store_path_domain +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, is of an unknown format or version, or is not the one + asked for.""" + + +@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 +_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", "it publishes nothing; the store sends none") +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, + 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), + # spiral-sdk 0.16.80 accepts a duration column (0.16.78 refused it); whether the + # store keeps durations is decided apart (ITL-1852). + Refusal("a duration", "its encoding is not decided (ITL-1852)", _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.is_timestamp, +) +"""Types written as they are (measured live, bit for bit: floats with their NaN payloads +and signed zeros; timestamps of every unit with their zone, ``datetime.max`` and +``datetime.min`` included; ``date64`` off midnight).""" + + +# -------------------------------------------------------------- types, as declared + + +def _recorded_metadata( + field: pa.Field[Any], identifier: tuple[bytes, bytes] | None +) -> dict[bytes, bytes]: + """The field's metadata as the manifest records it. + + A logical type's identifier replaces the two keys that hold one. A plain field (no + identifier) keeps its metadata exactly, an ``ARROW:extension:metadata`` entry with + no extension name included: that entry names no type, so it is the user's. + """ + metadata = dict(field.metadata or {}) + if identifier is not None: + _ = metadata.pop(EXTENSION_NAME_KEY, None) + _ = metadata.pop(EXTENSION_METADATA_KEY, None) + metadata[EXTENSION_NAME_KEY], metadata[EXTENSION_METADATA_KEY] = identifier + 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 pa.types.is_dictionary(arrow_type): + # An encoding, not a type: refused here, before a dictionary of a logical + # type's values is taken for that type (``identity_node`` looks through it). + raise UnstorableInSpiralError(f"a SpiralDB store keeps no type {arrow_type}") + if node.identifier is not None and EXTENSION_NAME_KEY not in (field.metadata or {}): + arrow_type = 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 = _recorded_metadata(field, 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_time64(arrow_type): + # As integers: the service refuses a time of day outside one day, as a whole + # write; Arrow holds such values. + 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("[]"): + # SpiralDB 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") + if field.name == KEY_COLUMN and pc.count_distinct(column).as_py() < len( + column + ): + # The service refuses the whole write: refused before any table is made. + raise UnstorableInSpiralError("a record id repeated in one write") + 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): + 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_time(logical): + return array.view(_physical_type(logical)) # the same integers + return array.cast(_physical_type(logical)) + + +# ------------------------------------------------------------- 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 + try: + difference = schema_difference(manifest.schema, target) + except UnstorableInSpiralError as exc: + raise ManifestError(f"not the recorded schema: {exc}") from exc + 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 = [_retyped(c, 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 _retyped(array: Any, target: Any) -> Any: + """Return decoded values in another layout of their type (small or large variants). + + A type holding a map is rebuilt from its parts: pyarrow aborts the process when it + casts a map between layouts. Any other type is cast. + """ + t = pa.types + if not _holds(target, t.is_map): + return array.cast(target) + mask = array.is_null() if array.null_count else None + if t.is_struct(target): + children = [ + _retyped(array.field(i), target.field(i).type) + for i in range(target.num_fields) + ] + return pa.StructArray.from_arrays(children, fields=_children(target), mask=mask) + if t.is_map(target): + rows = _map_rows(array) + keys = _retyped(array.keys.take(rows), target.key_type) + items = _retyped(array.items.take(rows), target.item_type) + return _map(array, keys, items, target) + items = _retyped(array.flatten(), target.value_type) + if t.is_fixed_size_list(target): + return _fixed_size_list(array, items, target) + if t.is_list(target): + offsets = _offsets(array) + if offsets[-1] > np.iinfo(np.int32).max: + raise StoredRowsError( + f"{offsets[-1]} items in one chunk, more than a {target} can index" + ) + small_offsets = pa.array(offsets.astype(np.int32), pa.int32()) + return pa.ListArray.from_arrays(small_offsets, items, type=target, mask=mask) + return _large_list(array, items, target) + + +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_time(logical): + restored = restored.view(logical) # the same integers + elif restored.type != logical: + # A decimal32 or decimal64. A coefficient over the precision is refused + # before the cast: pyarrow's narrowing cast lets some through, wrapped. + try: + restored.validate(full=True) + restored = restored.cast(logical) + except pa.ArrowInvalid as exc: + raise StoredRowsError(f"not a {logical} value: {exc}") from exc + if not field.nullable and restored.null_count: + raise StoredRowsError("a null in a non-nullable field") + return restored + + +# ---------------------------------------------------------------------- the manifest + +# A draft, written only while no public way opens a store: the persisted format and +# version are fixed when the store is switched on, with a decision then on reading the +# tables written in this draft format. Provisional: outside the 0.4.0 freeze. +MANIFEST_FORMAT = "orcapod.spiral_store.draft" +MANIFEST_VERSION = 0 +# 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 the path is outside + the store path domain (``store_table_names.require_store_path_domain``, + which the table's identity record applies too). + """ + try: + _ = require_store_path_domain(record_path) + except ValueError as exc: + raise UnstorableInSpiralError(str(exc)) from exc + _require_utf8(kind) + return StoreManifest( + record_path, kind, logical_schema(schema), physical_schema(schema) + ) + + +def manifest_bytes(manifest: StoreManifest) -> bytes: + """Return the payload that records ``manifest``. + + ``manifest_entries`` cuts it into a table's metadata entries. Writing the same + manifest again gives the same bytes. Two manifests whose schemas are equivalent but + represented differently (field metadata in another insertion order) can give + different bytes, because the Arrow IPC inside is not canonical: compare schemas with + ``schema_difference``, never by these bytes. + + Args: + manifest: The manifest. + + Returns: + Canonical JSON: the format and its version, the kind, the record path, and both + schemas as base64 of their Arrow IPC form. + """ + return json.dumps( + { + "format": MANIFEST_FORMAT, + "kind": manifest.kind, + "physical": _schema_text(manifest.physical), + "record_path": list(manifest.record_path), + "schema": _schema_text(_map_metadata(manifest.schema, _mark)), + "version": MANIFEST_VERSION, + }, + 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_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreManifest: + """Return the manifest ``manifest_bytes`` recorded. + + Args: + recorded: The payload, as reassembled from the chunks in the table's metadata + (``read_manifest``). + record_path: The record path the table was looked up for. + + Returns: + The manifest. + + Raises: + ManifestError: If the bytes are not a manifest, of an unknown format or version, + or of another path; or the recorded schemas are not a store table's. + """ + try: + body = json.loads(recorded.decode("ascii")) + except (ValueError, RecursionError) as exc: + raise ManifestError(f"a manifest is not JSON ({exc})") from exc + if not isinstance(body, dict): + raise ManifestError("a manifest is not a JSON object") + fields = cast("dict[str, Any]", body) + if fields.get("format") != MANIFEST_FORMAT: + raise ManifestError(f"unknown manifest format {fields.get('format')!r}") + version = fields.get("version") + if type(version) is not int or version != MANIFEST_VERSION: + raise ManifestError( + f"unsupported manifest version {version!r} " + f"(this Orcapod reads {MANIFEST_VERSION})" + ) + path, kind = fields.get("record_path"), fields.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") + try: + _require_utf8( + kind + ) # what a writer refuses (``new_manifest``), a reader refuses + except UnstorableInSpiralError as exc: + raise ManifestError(f"the kind is not UTF-8 text: {exc}") from exc + try: + _ = require_store_path_domain(cast("list[str]", path)) + except ValueError as exc: + raise ManifestError(f"the recorded path is not a store path: {exc}") from exc + if tuple(cast("list[str]", path)) != record_path: + raise ManifestError( + f"the table is recorded as {path}, not as {list(record_path)}" + ) + try: + schema = _map_metadata(_schema_of(fields.get("schema")), _unmark) + physical = _schema_of(fields.get("physical")) + 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 + except UnicodeDecodeError as exc: + # pyarrow holds a name of any bytes, and fails where it is read as text. + raise ManifestError(f"a recorded name is not UTF-8 text ({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") + try: + _require_distinct(physical) + except UnicodeDecodeError as exc: + raise ManifestError(f"a recorded name is not UTF-8 text ({exc})") from exc + return StoreManifest(record_path, kind, usable, physical) + + +MANIFEST_KEY = "orcapod.manifest" +"""The metadata key of a manifest's header; its chunks are ``/``.""" +# SpiralDB holds a key and its value in 8,192 bytes together (measured with spiral-sdk +# 0.16.78); a chunk leaves room for its key. Part of the format: one payload is always +# cut at the same places. +_CHUNK_BYTES = 8_000 + + +def manifest_entries(manifest: StoreManifest) -> dict[str, bytes]: + """Return the metadata entries that record ``manifest`` in its table. + + The chunks of the payload, then the header: the format, the version, the number of + chunks and the SHA-256 of the payload, a checksum of what the chunks hold. Written in + one upsert; a header always names exactly its chunks, so chunks of an earlier, + interrupted manifest are never read. + + Args: + manifest: The manifest. + + Returns: + The entries, chunks first. + """ + payload = manifest_bytes(manifest) + pieces = [ + payload[i : i + _CHUNK_BYTES] for i in range(0, len(payload), _CHUNK_BYTES) + ] + header = { + "chunks": len(pieces), + "format": MANIFEST_FORMAT, + "payload_digest": _checksum(payload), + "version": MANIFEST_VERSION, + } + entries = {f"{MANIFEST_KEY}/{i}": piece for i, piece in enumerate(pieces)} + entries[MANIFEST_KEY] = json.dumps( + header, separators=(",", ":"), sort_keys=True + ).encode("ascii") + return entries + + +def read_manifest( + metadata: Mapping[str, bytes], record_path: tuple[str, ...] +) -> StoreManifest | None: + """Return the manifest in a table's metadata. + + Args: + metadata: All of the table's metadata. + record_path: The record path the table was looked up for. + + Returns: + The manifest, or ``None`` when the table holds no header (a creation that + stopped before its manifest). + + Raises: + ManifestError: If the header or its chunks cannot be read in full, the header + is of another format or version, the chunks do not match their checksum, + or the manifest is not one of ``read_manifest_bytes``. + """ + raw = metadata.get(MANIFEST_KEY) + if raw is None: + return None + try: + header = json.loads(raw.decode("ascii")) + except (ValueError, RecursionError) as exc: + raise ManifestError(f"a manifest header is not JSON ({exc})") from exc + if not isinstance(header, dict): + raise ManifestError("a manifest header is not a JSON object") + fields = cast("dict[str, Any]", header) + if fields.get("format") != MANIFEST_FORMAT: + raise ManifestError(f"unknown manifest format {fields.get('format')!r}") + version = fields.get("version") + if type(version) is not int or version != MANIFEST_VERSION: + raise ManifestError( + f"unsupported manifest header version {version!r} " + f"(this Orcapod reads {MANIFEST_VERSION})" + ) + count = fields.get("chunks") + if type(count) is not int or count < 1: + raise ManifestError(f"invalid chunk count {count!r}") + if count > len(metadata): + # More chunks than the metadata has entries: some must be missing. Refused + # before a key is listed for each, so a corrupt count allocates nothing. + raise ManifestError( + f"the manifest names {count} chunks; the metadata holds " + f"{len(metadata)} entries" + ) + keys = [f"{MANIFEST_KEY}/{i}" for i in range(count)] + missing = [k for k in keys if k not in metadata] + if missing: + raise ManifestError(f"the manifest's chunks {missing} are missing") + payload = b"".join(metadata[k] for k in keys) + if fields.get("payload_digest") != _checksum(payload): + raise ManifestError("the manifest's chunks do not match its checksum") + return read_manifest_bytes(payload, record_path) + + +def _checksum(payload: bytes) -> str: + """The SHA-256 of a manifest payload, as hex: the header's check of its chunks.""" + return hashlib.sha256(payload).hexdigest() + + +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/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_store_identity.py new file mode 100644 index 000000000..baae18c2b --- /dev/null +++ b/src/orcapod/databases/spiral_store_identity.py @@ -0,0 +1,227 @@ +"""The name and identity record of a SpiralDB store table (ITL-1837). + +A store table's full path (the store's base path plus the record path) is too long for a +SpiralDB table name, so the table is named by the rule every connector store shares, +``store_table_names.store_table_name``, with SpiralDB's budget: a hint of at most +``SPIRAL_HINT_LENGTH`` characters and the whole 64-digit digest. The full path is written +into the table's own metadata, with the store format, the layout and the data context of +the writer that created it. A store computes the name to find a table and never lists to +find one; the record says which path a table holds, and a table recording another path is +refused (``SpiralStoreTableCollisionError``). + +The store format is provisional: it is outside the 0.4.0 freeze, and no public way to +open a store exists yet. Its marker (``STORE_FORMAT``) says so, so a table written in it +is told apart from one written in the format that is eventually fixed. + +The module is pure: it imports no SpiralDB client. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import cast + +from orcapod.databases.store_table_names import ( + STORE_TABLE_NAME_PREFIX, + require_store_path_domain, + store_table_name, + store_table_path_json, + table_name_hint, +) + + +class SpiralStoreTableCollisionError(ValueError): + """A SpiralDB table under a store table's name is not that store table. + + A store table's name is computed from its full path; its metadata records the path, + the store format, the layout and the data context. A table whose record names another + path or format, or is incomplete or unreadable, is refused: never read, written or + adopted. Internal while the store is not offered (it moves to ``orcapod.errors`` when + a store can be opened). + + Attributes: + reason: What is wrong. + table: The table, as ``"//"``, added by the caller that + knows it; ``None`` otherwise. + """ + + def __init__(self, reason: str, *, table: str | None = None) -> None: + self.reason = reason + self.table = table + where = "" if table is None else f"table {table}: " + super().__init__(f"{where}not this store's table: {reason}") + + +SPIRAL_HINT_LENGTH = 96 +"""The most characters of a SpiralDB store table name's hint.""" + +SPIRAL_DIGEST_LENGTH = 64 +"""The hex digits of the path digest a SpiralDB store table name keeps: all of them.""" + +STORE_FORMAT = "orcapod.spiral_store.draft" +"""The format of a store table, recorded in its metadata. Provisional: fixed (and renamed) +when the store is switched on.""" + +MAX_METADATA_ENTRY_BYTES = 8192 +"""The most UTF-8 bytes of a metadata entry's key and value together that SpiralDB accepts +(measured with spiral-sdk 0.16.78).""" + +STORE_KEY = "orcapod.store" +PATH_KEY = "orcapod.path" +LAYOUT_KEY = "orcapod.layout" +DATA_CONTEXT_KEY = "orcapod.data_context" +_RECORD_KEYS = (STORE_KEY, PATH_KEY, LAYOUT_KEY, DATA_CONTEXT_KEY) + + +def spiral_store_table_name(path: Sequence[str]) -> str: + """Return the SpiralDB name of the store table at ``path``. + + Args: + path: The full path components: the store's base path, then the record path. + + Returns: + ``o1__``, at most 164 characters, all in ``[a-z0-9_]``. + + Raises: + ValueError: If the path cannot be named (``store_table_path_json``). + """ + return store_table_name( + path, hint_length=SPIRAL_HINT_LENGTH, digest_length=SPIRAL_DIGEST_LENGTH + ) + + +def spiral_store_table_name_prefix(prefix: Sequence[str]) -> str: + """Return the start of the name of every store table whose path starts with ``prefix``. + + Tables of other paths can share it: a listing narrowed by it is a superset, and each + table's recorded path decides. + + Args: + prefix: Leading full path components; empty for every store table. + """ + if not prefix: + return STORE_TABLE_NAME_PREFIX + return STORE_TABLE_NAME_PREFIX + table_name_hint( + prefix, hint_length=SPIRAL_HINT_LENGTH + ) + + +@dataclass(frozen=True) +class StoreTableRecord: + """What a store table's metadata records. + + Attributes: + path: The full path components. + layout: The table's layout, the path's last component. + data_context_key: The data context of the writer that created the table. + """ + + path: tuple[str, ...] + layout: str + data_context_key: str + + +def store_table_metadata( + path: Sequence[str], data_context_key: str +) -> dict[str, bytes]: + """Return the metadata a new store table at ``path`` is given. + + Args: + path: The full path components. + data_context_key: The data context of the writer creating the table. + + Raises: + ValueError: If the path is outside the store path domain + (``store_table_names.require_store_path_domain``), the data context key is + empty, or an entry is over SpiralDB's entry limit + (``MAX_METADATA_ENTRY_BYTES``). + """ + components = require_store_path_domain(path) # one read of ``path``, kept + path_json = store_table_path_json(components) + if not data_context_key: + raise ValueError("a store table records the data context that created it") + record = { + STORE_KEY: STORE_FORMAT.encode(), + PATH_KEY: path_json, + LAYOUT_KEY: components[-1].encode(), + DATA_CONTEXT_KEY: data_context_key.encode(), + } + for key, value in record.items(): + size = len(key.encode()) + len(value) + if size > MAX_METADATA_ENTRY_BYTES: + limit = MAX_METADATA_ENTRY_BYTES + raise ValueError( + f"the metadata entry {key!r} is {size} bytes, over SpiralDB's {limit}" + ) + return record + + +def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord | None: + """Return the store table record in a table's metadata. + + Args: + metadata: The table's metadata, as SpiralDB returns it. + + Returns: + The record, or ``None`` when the table holds none of its entries: a table whose + creation stopped before its metadata, or another program's. + + Raises: + SpiralStoreTableCollisionError: If the record is partial, of another format, or + unreadable. + """ + if not any(k in metadata for k in _RECORD_KEYS): + return None + missing = [k for k in _RECORD_KEYS if k not in metadata] + if missing: + raise SpiralStoreTableCollisionError(f"its record lacks {missing}") + if metadata[STORE_KEY] != STORE_FORMAT.encode(): + raise SpiralStoreTableCollisionError( + f"its format is {metadata[STORE_KEY]!r}, not {STORE_FORMAT!r}" + ) + try: + path: object = json.loads(metadata[PATH_KEY].decode()) # pyright: ignore[reportAny] # checked below + layout = metadata[LAYOUT_KEY].decode() + data_context_key = metadata[DATA_CONTEXT_KEY].decode() + except (ValueError, RecursionError) as exc: # JSON, UTF-8, the integer limit, depth + raise SpiralStoreTableCollisionError( + f"its record cannot be read: {exc}" + ) from exc + items = cast("list[object]", path) if isinstance(path, list) else [] + if not items or not all(isinstance(c, str) for c in items): + raise SpiralStoreTableCollisionError( + f"its path is not a list of names: {path!r}" + ) + components = tuple(cast("list[str]", items)) + try: + # What a writer refuses, a reader refuses. + _ = require_store_path_domain(components) + except ValueError as exc: + raise SpiralStoreTableCollisionError( + f"its path cannot be named: {exc}" + ) from exc + if layout != components[-1]: + raise SpiralStoreTableCollisionError( + f"its layout {layout!r} is not its path's last component {components[-1]!r}" + ) + if not data_context_key: + raise SpiralStoreTableCollisionError("it records no data context") + return StoreTableRecord(components, layout, data_context_key) + + +def require_store_table_path(record: StoreTableRecord, path: Sequence[str]) -> None: + """Refuse a store table whose record is of another path than ``path``. + + Args: + record: The table's record (``read_store_table_metadata``). + path: The full path the table was looked up for. + + Raises: + SpiralStoreTableCollisionError: If the record is of another path. + """ + if record.path != tuple(path): + raise SpiralStoreTableCollisionError( + f"it records path {list(record.path)}, not {list(path)}" + ) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 61e695bd9..7067b2daf 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -167,6 +167,44 @@ def _service_call(doing: str, health: _Health | None = None) -> Iterator[None]: raise +# spiral-sdk 0.16.79 and later warn on every keyed-table open, attributed to the module +# that calls the SDK (``stacklevel=3``): this one, for every open Orcapod makes. Orcapod +# reads and writes keyed tables until it moves to spiral-sdk's Table format (ITL-1846), so +# this one message is ignored for this module's own opens only: a user's own call to the +# SDK, another message, and another category still warn. +_KEYED_TABLE_DEPRECATION = r"Keyed tables are deprecated\.\Z" +_THIS_MODULE = re.escape(__name__) + r"\Z" +# The filter as ``warnings.filterwarnings`` stores it, to find it in ``warnings.filters``. +_KEYED_TABLE_FILTER = ( + "ignore", + re.compile(_KEYED_TABLE_DEPRECATION, re.IGNORECASE), + DeprecationWarning, + re.compile(_THIS_MODULE), + 0, +) + + +def _ignore_keyed_table_deprecation() -> None: + """Ignore spiral-sdk's keyed-table deprecation for this module's own opens. + + Called before each open, not once at import: a ``warnings.catch_warnings`` block + (pytest wraps every test in one) drops a filter added inside it. The first matching + filter wins, so the filter is kept FIRST, not merely present: a filter added after + an earlier open (``simplefilter("error")``, ``pytest.warns``, a recording + ``catch_warnings``) would otherwise rank ahead of it. ``filterwarnings`` removes the + older copy before inserting at the front, so the list never grows; in steady state + the filter is already first and the list does not change. No ``catch_warnings`` + here: it swaps the process-wide filter list and is not safe with threads. + """ + if not warnings.filters or warnings.filters[0] != _KEYED_TABLE_FILTER: + warnings.filterwarnings( + "ignore", + message=_KEYED_TABLE_DEPRECATION, + category=DeprecationWarning, + module=_THIS_MODULE, + ) + + def _open_keyed_table( client: Any, project_id: str, @@ -182,6 +220,7 @@ def _open_keyed_table( """ with _service_call(f"open table {project_id}/{dataset}/{name}", health): try: + _ignore_keyed_table_deprecation() return client.keyed_table(project_id, dataset, name) except sp.SpiralError as exc: if str(exc).strip() != f"resource not found: {project_id}.{dataset}.{name}": @@ -189,6 +228,34 @@ def _open_keyed_table( return None +def _create_keyed_table( + client: Any, + project_id: str, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool, +) -> Any: + """Create a keyed table and return it, with the SDK's errors as they are. + + The one place Orcapod creates a keyed table, so that its creation is attributed to + this module and covered by the same filter as its opens (ITL-1837). + + Args: + client: The spiral-sdk client. + project_id: The project. + dataset: The dataset. + name: The table. + key_schema: Its key columns, in key order. + exist_ok: Whether a table already there with these key columns is returned. + """ + _ignore_keyed_table_deprecation() + return client.project(project_id).create_keyed_table( + dataset, name, key_schema, exist_ok=exist_ok + ) + + def _warn_unrecorded(table: str, table_id: str) -> None: """Warn once per table and process that its schema is not recorded. @@ -658,6 +725,7 @@ def _at(self, asof: int | None) -> Any: opened = self._versions.get(str(asof)) if opened is None: with self._connector._service_call("open a version of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + _ignore_keyed_table_deprecation() opened = self._connector._client.keyed_table_by_id( # pyright: ignore[reportPrivateUsage] # owns the handle self.table_id, asof=asof ) diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 96f05453e..79cec7cab 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -12,6 +12,52 @@ STORE_TABLE_NAME_PREFIX = "o1_" +def require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: + """Refuse a path outside the SpiralDB store's component syntax. + + A SpiralDB store table's full path is at least one component, and every component + is a non-empty ``str`` (not a subclass) with a UTF-8 form that holds neither ``/`` + nor NUL. Every writer and reader of a SpiralDB store table's identity record and + manifest applies it, so they accept and refuse the same component syntax. It is + the SpiralDB store's rule only: the other databases keep their own path rules (the + in-memory store accepts a lone surrogate or a ``str`` subclass, the Delta store + refuses a quoted component). Naming (``store_table_path_json``) encodes any path of + strings. + + A path inside this syntax can still be refused for its size: each entry of the + identity record is capped at SpiralDB's entry limit + (``spiral_store_identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an + 8,192-character component is valid here, round-trips through the chunked manifest, + and is refused by ``spiral_store_identity.store_table_metadata``. + + Args: + path: The store's base path followed by its record path. + + Returns: + The path, as a tuple. + + Raises: + ValueError: If the path is outside the domain, naming the component. + """ + components = tuple(path) + if not components: + raise ValueError("a store table path has at least one component") + for component in components: + if type(component) is not str or not component: + raise ValueError(f"a store table path component is {component!r}") + if "/" in component or "\0" in component: + raise ValueError( + f"a store table path component holds '/' or NUL: {component!r}" + ) + try: + _ = component.encode() + except UnicodeEncodeError as exc: + raise ValueError( + f"a store table path component is not UTF-8 text: {component!r}" + ) from exc + return components + + def store_table_path_json(path: Sequence[str]) -> bytes: """Encode the full store path as a compact UTF-8 JSON array. diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index e022d4207..c2c0cdba0 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -7,7 +7,8 @@ Each rule of ``RULES`` was seen on the service with spiral-sdk 0.16.74 and 0.16.75 on November 24, 2026, on throwaway tables, unless it says otherwise; its name is cited where -the rule is applied. +the rule is applied. The table-metadata and store-codec conformance tests passed live with +spiral-sdk 0.16.78 on November 26, 2026 (ITL-1495, ITL-1497). """ from __future__ import annotations @@ -16,9 +17,11 @@ import operator import os import struct +import threading import types import urllib.parse import uuid +import warnings from collections.abc import Iterator from contextlib import contextmanager from dataclasses import dataclass @@ -60,11 +63,19 @@ "null-key": "a null key is refused", "key-only": "a write without a value column is refused", "no-key": "a write without a key column is refused", - "reserved": "a value column starting with '__' or '$', or any with '.', is refused", - "nul": "a column name is cut at a NUL character", + "reserved": "a value column or struct field starting with '__' or '$', any with '.', " + "and one named '' or '*' (spiral-sdk 0.16.78, November 26, 2026) is refused", + "time-of-day": "spiral-sdk 0.16.78 (November 26, 2026): a time32 or time64 value outside " + "one day, at any depth, refuses the whole write", + "nul": "a column name is cut at a NUL character; so is a struct field name, at every " + "depth (spiral-sdk 0.16.78, November 26, 2026)", "type-conflict": "a column of another type than stored is refused", - "unsupported": "duration, interval, fixed-size binary, union, an empty struct and a " - "null struct outside a list are refused", + "deprecated": "spiral-sdk 0.16.79 and later (read in the 0.16.80 wheel, December 1, " + "2026): keyed_table, keyed_table_by_id and create_keyed_table warn 'Keyed tables are " + "deprecated.' (DeprecationWarning, stacklevel=3: attributed to the calling module)", + "unsupported": "interval, fixed-size binary, union, an empty struct and a null " + "struct outside a list are refused; a duration is accepted and read back as given " + "(spiral-sdk 0.16.80, December 1, 2026: a duration[s] column, which 0.16.78 refused)", "non-null": "a null in a column, struct field or list item declared or stored " "non-null is refused", "literal": "a literal must have the column's exact type (large_string is none)", @@ -75,8 +86,19 @@ "rows": "rows come in key order; filter before limit", "list": "the documented listing filters a dataset and pages; a page can be empty " "(documented, not seen)", + "table-metadata": "spiral-sdk 0.16.78 (November 26, 2026): get_metadata and " + "set_metadata hold bytes by text key, an upsert that never deletes (an empty value is " + "stored); not versioned (every snapshot, asof included, sees the latest; a write makes " + "no snapshot); readable before any row; a key over 255 UTF-8 bytes, or an entry whose " + "key and value together are over 8,192 bytes: 'status 400' and nothing written", } +_MAX_METADATA_KEY_BYTES = 255 +# Upserts of metadata are atomic on the service (two clients' keys are all kept); the +# fake's stores are in one process. +_metadata_lock = threading.Lock() +_MAX_METADATA_ENTRY_BYTES = 8192 + _ROOT_ENV = "FAKE_SPIRAL_SDK_ROOT" _API_URL = "https://api.fake.invalid" @@ -176,8 +198,7 @@ def _refused_type(t: pa.DataType) -> str | None: if isinstance(t, pa.BaseExtensionType): return _refused_type(t.storage_type) if ( - pa.types.is_duration(t) - or pa.types.is_interval(t) + pa.types.is_interval(t) or pa.types.is_fixed_size_binary(t) or pa.types.is_union(t) ): @@ -198,11 +219,128 @@ def _refused_type(t: pa.DataType) -> str | None: def _reserved(name: str) -> str | None: """Return the refusal of a reserved column name (``reserved``).""" - if name.startswith(("__", "$")) or "." in name: + if name.startswith(("__", "$")) or "." in name or name in ("", "*"): return f'Column name "{name}" is reserved' return None +_DAY = {"s": 86_400, "ms": 86_400_000, "us": 86_400_000_000, "ns": 86_400_000_000_000} + + +def _decoded(array: Any) -> Any: + """``array`` with every dictionary and run-end encoding at its top undone, as the + service stores it (``types``); a run-end-encoded struct included, which pyarrow + cannot decode itself.""" + if isinstance(array, pa.ExtensionArray): + array = array.storage + if pa.types.is_dictionary(array.type): + return _decoded(array.dictionary_decode()) + if pa.types.is_run_end_encoded(array.type): + return _decoded(array.values.take(pa.array(_run_indices(array), pa.int64()))) + return array + + +def _run_indices(array: Any) -> list[int]: + """The run of each row of a run-end-encoded array (a slice of one included): only + the runs that overlap the slice are expanded, and only where they overlap it.""" + start, stop = array.offset, array.offset + len(array) + indices: list[int] = [] + begin = 0 + for run, end in enumerate(array.run_ends.to_pylist()): + low, high = max(begin, start), min(end, stop) + if low < high: + indices.extend([run] * (high - low)) + if end >= stop: + break + begin = end + return indices + + +def _needs_decoding(t: Any, *, in_extension: bool = False) -> bool: + """Whether a column must be rebuilt as the service stores it before its names are + cut (``types``, ``nul``): it holds a dictionary or run-end encoding at any depth, or + an extension type whose storage holds a struct field name with NUL.""" + if pa.types.is_dictionary(t) or pa.types.is_run_end_encoded(t): + return True + if isinstance(t, pa.BaseExtensionType): + return _needs_decoding(t.storage_type, in_extension=True) + if in_extension and pa.types.is_struct(t): + if any("\0" in t.field(i).name for i in range(t.num_fields)): + return True + return any( + _needs_decoding(t.field(i).type, in_extension=in_extension) + for i in range(t.num_fields) + ) + + +def _deep_decoded(array: Any) -> Any: + """``array`` with every dictionary and run-end encoding undone, at any depth, as the + service stores it (``types``), so nested names are cut as at the top (``nul``).""" + a = _decoded(array) + if a.offset: + a = pa.concat_arrays([a]) # rebuilt from offset zero: pyarrow builds no slice + t = a.type + mask = a.is_null() if a.null_count else None + if pa.types.is_struct(t): + children = [_deep_decoded(a.field(i)) for i in range(t.num_fields)] + fields = [t.field(i).with_type(c.type) for i, c in enumerate(children)] + return pa.StructArray.from_arrays(children, fields=fields, mask=mask) + if pa.types.is_list(t) or pa.types.is_large_list(t): + values = _deep_decoded(a.values) + kind: Any = pa.list_ if pa.types.is_list(t) else pa.large_list + cls: Any = pa.ListArray if pa.types.is_list(t) else pa.LargeListArray + target = kind(t.value_field.with_type(values.type)) + return cls.from_arrays(a.offsets, values, type=target, mask=mask) + if pa.types.is_fixed_size_list(t): + size = t.list_size + values = _deep_decoded(a.values.slice(a.offset * size, len(a) * size)) + target = pa.list_(t.value_field.with_type(values.type), size) + if size == 0: # no values to count the rows by: from buffers + valid = pc.is_valid(a).buffers()[1] if a.null_count else None + return pa.Array.from_buffers( + target, + len(a), + cast(Any, [valid]), # the stubs take no None for an absent buffer + null_count=a.null_count, + children=[values], + ) + return cast(Any, pa.FixedSizeListArray).from_arrays( + values, type=target, mask=mask + ) + if pa.types.is_map(t): + keys, items = _deep_decoded(a.keys), _deep_decoded(a.items) + target = cast(Any, pa.map_)( + t.key_field.with_type(keys.type), + t.item_field.with_type(items.type), + keys_sorted=t.keys_sorted, + ) + return cast(Any, pa.MapArray).from_arrays( + a.offsets, keys, items, type=target, mask=mask + ) + return a + + +def _time_outside_a_day(array: Any) -> bool: + """Whether a time value outside one day is in ``array``, at any depth (``time-of-day``).""" + array = _decoded(array) + t = array.type + if pa.types.is_time(t): + ticks = array.view(pa.int32() if pa.types.is_time32(t) else pa.int64()) + day = _DAY[t.unit] + return any(v is not None and not 0 <= v < day for v in ticks.to_pylist()) + if pa.types.is_struct(t): + return any(_time_outside_a_day(array.field(i)) for i in range(t.num_fields)) + if pa.types.is_map(t): + return _time_outside_a_day(array.keys) or _time_outside_a_day(array.items) + if ( + pa.types.is_list(t) + or pa.types.is_large_list(t) + or pa.types.is_fixed_size_list(t) + ): + return _time_outside_a_day(array.flatten()) + return False + + def _stored_array(array: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: """Return ``array`` as it is stored, of type ``target``. @@ -216,10 +354,7 @@ def _stored_array(array: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: a: Any = array if isinstance(a, pa.ExtensionArray): a = a.storage - if pa.types.is_dictionary(a.type): - a = a.dictionary_decode() - if pa.types.is_run_end_encoded(a.type): - a = cast(Any, pc).run_end_decode(a) + a = _decoded(a) if a.type == target: return a t: Any = target @@ -253,12 +388,54 @@ def _stored_array(array: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: values = _stored_array( a.values.slice(a.offset * t.list_size, len(a) * t.list_size), t.value_type ) + if t.list_size == 0: # no values to count the rows by: from buffers + valid = pc.is_valid(a).buffers()[1] if a.null_count else None + return pa.Array.from_buffers( + t, + len(a), + cast(Any, [valid]), # the stubs take no None for an absent buffer + null_count=a.null_count, + children=[values], + ) return cast(Any, pa.FixedSizeListArray).from_arrays( values, type=t, mask=a.is_null() if a.null_count else None ) return a.cast(target) +def _names_cut_at_nul(t: Any) -> Any: + """Return ``t`` with every struct field name cut at its first NUL (``nul``).""" + if isinstance(t, pa.BaseExtensionType): + return t + if pa.types.is_struct(t): + return pa.struct( + [ + pa.field( + f.name.split("\0")[0], + _names_cut_at_nul(f.type), + f.nullable, + f.metadata, + ) + for f in t + ] + ) + if pa.types.is_large_list(t) or pa.types.is_list(t): + item = t.value_field + kind: Any = pa.large_list if pa.types.is_large_list(t) else pa.list_ + return kind(item.with_type(_names_cut_at_nul(item.type))) + if pa.types.is_fixed_size_list(t): + item = t.value_field + return pa.list_(item.with_type(_names_cut_at_nul(item.type)), t.list_size) + if pa.types.is_map(t): + map_of: Any = pa.map_ # the stubs take no fields and keys_sorted together + return map_of( + t.key_field.with_type(_names_cut_at_nul(t.key_type)), + t.item_field.with_type(_names_cut_at_nul(t.item_type)), + keys_sorted=t.keys_sorted, + ) + return t + + def _check_nulls(array: Any, field: pa.Field[Any], *, in_list: bool) -> None: """Refuse a null where the written type has none, or a null struct (``non-null``, ``unsupported``). @@ -368,6 +545,33 @@ def drop(self, table_id: str) -> None: path.unlink() folder.rmdir() + def metadata(self, table_id: str) -> dict[str, bytes]: + """Return a table's metadata (``table-metadata``).""" + _ = self.by_id(table_id) + path = self.root / table_id / "metadata.json" + if not path.exists(): + return {} + stored = cast("dict[str, str]", json.loads(path.read_text())) + return {k: bytes.fromhex(v) for k, v in stored.items()} + + def set_metadata(self, table_id: str, entries: dict[str, bytes]) -> None: + """Upsert ``entries`` into a table's metadata (``table-metadata``).""" + for key, value in entries.items(): + size = len(key.encode()) + if ( + size > _MAX_METADATA_KEY_BYTES + or size + len(value) > _MAX_METADATA_ENTRY_BYTES + ): + raise _status(400) + with _metadata_lock: # one upsert at a time: concurrent keys are all kept + stored = self.metadata(table_id) + stored.update(entries) + # Written beside, then put in place: a reader sees a whole mapping. + target = self.root / table_id / "metadata.json" + written = target.with_suffix(".json.tmp") + _ = written.write_text(json.dumps({k: v.hex() for k, v in stored.items()})) + _ = written.replace(target) + def keys(self, table_id: str) -> pa.Schema: """Return a table's key schema.""" raw = (self.root / table_id / "keys.arrow").read_bytes() @@ -402,6 +606,21 @@ def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: """Validate ``rows`` and return them as they are stored (``stage``).""" names = [name.split("\0")[0] for name in rows.column_names] # nul rows = rows.rename_columns(names) + for i, field in enumerate(rows.schema): # nul, at every depth + if _needs_decoding(field.type): + # Stored as its values (``types``): decoded first, so its names are cut. + chunks = rows.column(i).chunks or [pa.array([], field.type)] # no chunk + decoded = pa.chunked_array([_deep_decoded(c) for c in chunks]) + rows = rows.set_column(i, field.with_type(decoded.type), decoded) + field = rows.schema.field(i) + cut = _names_cut_at_nul(field.type) + if cut != field.type: + column = rows.column(i) + rows = rows.set_column( + i, + field.with_type(cut), # the field, flag and metadata kept + pa.chunked_array([c.view(cut) for c in column.chunks], type=cut), + ) for key in keys: if key not in names: raise _refuse(f"Input batch is missing key field '{key}'") @@ -422,6 +641,11 @@ def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: rows.column(field.name).chunks or [pa.array([], field.type)] ) _check_nulls(array, field, in_list=False) + if _time_outside_a_day(array): + raise SpiralError( + "Scandal:Internal (message: Vortex error: Invalid time scalar: adding " + "duration to time overflowed)" + ) target = _stored_type(field.type) if field.name in stored.names: kept = stored.field(field.name).type @@ -675,6 +899,14 @@ def key_columns(self) -> tuple[str, ...]: """The key columns, in key order.""" return tuple(self._table["keys"]) + def get_metadata(self) -> dict[str, bytes]: + """Return the table's metadata, the latest whatever the snapshot (``table-metadata``).""" + return self._store.metadata(self.resource_id) + + def set_metadata(self, metadata: dict[str, bytes]) -> None: + """Upsert entries of the table's metadata (``table-metadata``).""" + self._store.set_metadata(self.resource_id, metadata) + def schema(self) -> pa.Schema: """Return the snapshot's schema.""" return self._store.read(self.resource_id, self._version).schema @@ -817,6 +1049,13 @@ def _open(store: _Store, table: dict[str, Any], asof: int | None) -> FakeKeyedTa return FakeKeyedTable(store, table, version) +def _warn_deprecated() -> None: + """Warn as spiral-sdk 0.16.79 and later do on every keyed-table open and creation + (``deprecated``): from a helper at ``stacklevel=3``, so the warning is attributed to + the module that called the SDK.""" + warnings.warn("Keyed tables are deprecated.", DeprecationWarning, stacklevel=3) + + class FakeProject: """Stands in for ``spiral.projects.Project``.""" @@ -827,7 +1066,15 @@ def __init__(self, store: _Store, project: str) -> None: def create_keyed_table( self, dataset: str, name: str, key_schema: pa.Schema, *, exist_ok: bool = False ) -> FakeKeyedTable: - """Create a table (``create-409``, ``create-key-types``, ``names``).""" + """Create a table (``create-409``, ``create-key-types``, ``names``, + ``deprecated``).""" + _warn_deprecated() + return self._create(dataset, name, key_schema, exist_ok=exist_ok) + + def _create( + self, dataset: str, name: str, key_schema: pa.Schema, *, exist_ok: bool + ) -> FakeKeyedTable: + """Create a table, with no deprecation warning: the fake's own creations.""" if not dataset or not name: raise ValueError("dataset and table names must be nonempty") if len(name) > 255: @@ -873,7 +1120,8 @@ def project(self, id: str) -> FakeProject: def keyed_table( self, project: str, dataset: str, name: str, *, asof: int | None = None ) -> FakeKeyedTable: - """Open a table by name (``missing``).""" + """Open a table by name (``missing``, ``deprecated``).""" + _warn_deprecated() table = self._store.find(project, dataset, name) if table is None: raise SpiralError(f"resource not found: {project}.{dataset}.{name}") @@ -882,7 +1130,8 @@ def keyed_table( def keyed_table_by_id( self, table_id: str, *, asof: int | None = None ) -> FakeKeyedTable: - """Open a table by its id.""" + """Open a table by its id (``deprecated``).""" + _warn_deprecated() return _open(self._store, self._store.by_id(table_id), asof) @@ -1035,7 +1284,7 @@ def migrate( from orcapod.utils import arrow_utils store = _store() - handle = FakeProject(store, project).create_keyed_table( + handle = FakeProject(store, project)._create( dataset, SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=True ) stored = store.read(handle.resource_id, int(handle.version_id)) diff --git a/tests/test_databases/test_fake_spiral_sdk.py b/tests/test_databases/test_fake_spiral_sdk.py new file mode 100644 index 000000000..c572d95e8 --- /dev/null +++ b/tests/test_databases/test_fake_spiral_sdk.py @@ -0,0 +1,68 @@ +"""The SpiralDB fake's own decoding of what it is given (CodeRabbit on PR 595).""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from tests.test_databases import fake_spiral_sdk as fake + + +def test_a_run_end_encoded_slice_expands_only_its_own_rows() -> None: + """Every slice decodes to its own values, and a slice of one row of a run of two + billion values builds one index, not one per value of the run.""" + small = pa.RunEndEncodedArray.from_arrays( + pa.array([3, 5, 9], pa.int32()), pa.array(["a", "b", "c"]) + ) + for offset in range(10): + for length in range(10 - offset): + piece: Any = small.slice(offset, length) + assert fake._decoded(piece).to_pylist() == piece.to_pylist() # pyright: ignore[reportPrivateUsage] + huge = pa.RunEndEncodedArray.from_arrays( + pa.array([1, 2**31 - 1], pa.int32()), pa.array(["a", "b"]) + ) + last = huge.slice(2**31 - 2, 1) + assert fake._run_indices(last) == [1] # pyright: ignore[reportPrivateUsage] + assert fake._decoded(last).to_pylist() == ["b"] # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize("offset", [0, 1]) +def test_a_zero_width_fixed_size_list_of_dictionaries_keeps_its_rows( + offset: int, +) -> None: + """A fixed-size list of size 0 has no values to count its rows by: it is rebuilt + from its buffers, rows and nulls kept.""" + arrow_type = pa.list_(pa.dictionary(pa.int8(), pa.string()), 0) + given: Any = pa.array([[], None, [], []], arrow_type).slice(offset) + got = fake._deep_decoded(given) # pyright: ignore[reportPrivateUsage] + assert len(got) == len(given) + assert got.to_pylist() == given.to_pylist() + assert got.type == pa.list_(pa.string(), 0) + + +@pytest.mark.parametrize( + "encoded", + [ + pa.dictionary(pa.int8(), pa.string()), + pa.run_end_encoded(pa.int32(), pa.string()), + ], +) +def test_an_encoded_column_with_no_chunk_is_written_as_no_rows( + tmp_path: Path, encoded: Any +) -> None: + """CodeRabbit on PR 691 (fake_spiral_sdk.py:610): a dictionary or run-end encoded + column with no chunk at all (``Table.from_batches([], schema)``) is decoded to its + values' type, as one with rows is, and the write stores no rows.""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + schema = pa.schema( + [pa.field("k", pa.large_string(), False), pa.field("v", encoded)] + ) + rows = pa.Table.from_batches([], schema=schema) + assert rows.column("v").num_chunks == 0 + written = table.append(rows) + assert written.scan().to_table().num_rows == 0 diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 655fd8fb9..125f922d6 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -9,6 +9,7 @@ import argparse import importlib.util import json +import warnings from collections.abc import Callable from pathlib import Path from types import ModuleType @@ -150,6 +151,32 @@ def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: assert schema.field("v").metadata == {b"unit": b"mV"} +def test_the_dry_run_reads_raise_no_keyed_table_deprecation( + tool: ModuleType, project: Any +) -> None: + """The dry run's reads of each table go through the connector, which ignores the + SDK's keyed-table deprecation for its own opens, after an earlier open too.""" + fake.migrate("p", dict.fromkeys(_TABLES, _WRITTEN), "one") + connector = SpiralDBConnector("p", "one") + _ = connector.lookup_table("trials") # an earlier open, before the error filter + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + for name in _TABLES: + described = tool.describe_table(connector, "p", "one", name) + assert described["row"]["table_name"] == name + + +def test_the_write_and_verify_raise_no_keyed_table_deprecation( + tool: ModuleType, args: argparse.Namespace +) -> None: + """The write opens each planned table and creates each schema table through the + connector's helpers, never the SDK directly, so neither warns.""" + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + tool.write(args) + tool.verify(args) + + @pytest.mark.parametrize("stop_after", [1, 2, 3, 4]) def test_an_interrupted_write_is_refused_by_reads_and_resumed( tool: ModuleType, args: argparse.Namespace, stop_after: int diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py new file mode 100644 index 000000000..0c37ecb3f --- /dev/null +++ b/tests/test_databases/test_spiral_store.py @@ -0,0 +1,1762 @@ +"""The codec of a SpiralDB store table: names, types, rows and the manifest (ITL-1446, ITL-1497). + +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 collections.abc import Callable +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 ``n`` distinct record ids, ``r0000`` onward, as a key column. + + Args: + n: The number of ids. + + Returns: + A ``large_binary`` array. + """ + 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: + """A manifest of a table of ``schema`` at ``path``, in memory (not serialized).""" + return store.new_manifest(path, "function_pipeline", schema) + + +def entries(schema: pa.Schema, path: tuple[str, ...] = PATH) -> bytes: + """The recorded manifest of a table of ``schema`` at ``path``.""" + return store.manifest_bytes(new(schema, path)) + + +def read(recorded: bytes, path: tuple[str, ...] = PATH) -> store.StoreManifest: + """Parse a raw manifest payload (``manifest_bytes``), not a table's metadata.""" + return store.read_manifest_bytes(recorded, path) + + +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: + """An Arrow type in its large variants, at every depth (no other change).""" + return normalize_to_large_types(arrow_type, keep_null=True) + + +def large(schema: pa.Schema) -> pa.Schema: + """A schema with every field's type in its large variants, metadata kept.""" + 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 _storage_form(schema: pa.Schema) -> pa.Schema: + """What a read gives without making logical types live, derived from the input, + never by the codec: large variants, every field's metadata kept at every depth, and + a top-level logical type as its storage type with its identifier as metadata.""" + fields: list[Any] = [] + for field in schema: + arrow_type = field.type + metadata = dict(field.metadata or {}) + if isinstance(arrow_type, pa.BaseExtensionType): + metadata[NAME_KEY] = arrow_type.extension_name.encode() + metadata[METADATA_KEY] = cast(Any, arrow_type).__arrow_ext_serialize__() + arrow_type = arrow_type.storage_type + elif NAME_KEY in metadata: + metadata.setdefault(METADATA_KEY, b"") + fields.append( + pa.field( + field.name, + large_type(arrow_type), + field.nullable, + cast(Any, metadata or None), + ) + ) + return schema_of(fields, metadata=cast(Any, schema.metadata)) + + +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 = _storage_form(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 pa.types.is_interval(t) + or isinstance(t, pa.BaseExtensionType) + # spiral-sdk 0.16.78: a time of day outside one day is refused, so times are + # written as integers; timestamps, zoned or not, are written as they are. + or pa.types.is_time(t) + ) + 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: + """Check that ``encode_rows`` refuses ``rows`` with a message holding every word. + + Args: + rows: The rows to encode. + *words: Fragments the message must hold, each of them. + + Returns: + The error, for assertions on what it says (``error.path``). + """ + 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")}, + # A live logical type below the top level (ITL-1372's rows): Orcapod never builds + # one, and the codec records a logical type only on a whole column. + "extension type in struct child": "logical type nested", + "extension type in list item": "logical type nested", + "extension type in map value": "logical type nested", + # A dictionary is an encoding, refused before its values' type is looked at. + "extension type in dictionary values": "no type dictionary", +} +# 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]]]: + """Return one case per scalar Arrow type: its label, the type and three values. + + Returns: + ``(label, type, values)`` tuples, the values at the type's edges where it has + them. + """ + 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)) + # Written as they are (measured live with spiral-sdk 0.16.78: every int64, every + # unit, zoned or not, bit for bit). + assert encoded.schema.field("t").type == ts + 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: + """pyspiral's service refused a timestamp after 9999-12-30; spiral-sdk's keeps it.""" + 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 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_kept() -> None: + """Measured live with spiral-sdk 0.16.78: the null row's struct slots are accepted.""" + 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]), + ): + rows = keyed({"f": pa.array(value, ty)}) + assert by_id(round_trip(rows)).column("f").to_pylist() == value + + +@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="Europe/Paris")), "Europe/Paris") + bad("t", pa.array([1], timestamp("ms", tz="UTC")), "timestamp[ms") + bad("t", pa.array([1], pa.int64()), "int64") + 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") + recorded = entries(schema, path) + assert recorded.isascii() + manifest = read(recorded, 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_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 first != second + 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 + + +def test_a_manifest_of_another_path_is_refused() -> None: + recorded = 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_bytes(recorded, 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) + + def renamed(name: str) -> str: + return "new_" + name.encode().hex() + + monkeypatch.setattr(store, "encode_name", renamed) + 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 _payload(**changes: Any) -> bytes: + """The recorded manifest of ``BASE`` with fields of its JSON changed.""" + body = {**json.loads(entries(schema_of(BASE))), **changes} + return json.dumps(body).encode() + + +def _ipc(schema: pa.Schema) -> str: + return base64.b64encode(schema.serialize().to_pybytes()).decode() + + +_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_the_changed_payload_helper_builds_a_readable_manifest() -> None: + assert read(_payload()) == new(schema_of(BASE)) + + +_BROKEN_MANIFESTS: list[Callable[[bytes], bytes]] = [ + lambda m: b"", + lambda m: b"[]", + lambda m: b"\xff", + lambda m: m + b" junk", + lambda m: b'"text"', + lambda m: _payload(format="other"), + lambda m: _payload(format=None), + lambda m: _payload(version=1), + lambda m: _payload(version=False), + 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: _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))]))), +] + + +@pytest.mark.parametrize("make", _BROKEN_MANIFESTS) +def test_a_manifest_that_cannot_be_read_in_full_is_an_error( + make: Callable[[bytes], bytes], +) -> None: + recorded = make(entries(schema_of(BASE))) + with pytest.raises(store.ManifestError): + _ = store.read_manifest_bytes(recorded, PATH) + + +def test_a_large_manifest_is_kept() -> None: + """A raw manifest payload has no size bound of its own: 7 MB of field metadata + round-trips through ``manifest_bytes`` and ``read_manifest_bytes``. The chunk + tests below cover the metadata entry limit of a table.""" + field = pa.field("a", pa.int8(), metadata={"k": "v" * 7_000_000}) + schema = schema_of([field, (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 + assert store.manifest_bytes(read(one)) == one + + +def test_the_codec_needs_no_spiral_client() -> 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 + + +_NARROWED_MAP = """ +import pyarrow as pa +from orcapod.databases import spiral_store as store + +maps = pa.map_(pa.string(), pa.int64()) +rows = pa.table( + { + store.KEY_COLUMN: pa.array([b"a", b"b", b"c"], pa.large_binary()), + "m": pa.array([[("x", 1), ("y", None)], None, []], maps), + "s": pa.array([{"m": [("x", 1)]}] * 3, pa.struct([("m", maps)])), + "l": pa.array([[[("x", 1)]], None, [[]]], pa.list_(maps)), + } +) +manifest = store.new_manifest(("p", "rdb_v1"), "k", rows.schema) +got = store.decode_rows(store.encode_rows(rows), manifest, rows.schema) +assert got.schema == rows.schema, got.schema +assert got.to_pylist() == rows.to_pylist(), got.to_pylist() +""" + + +def test_a_map_given_back_in_small_variants_is_rebuilt_not_cast() -> None: + """Review of PR 590, finding 1: pyarrow aborts the process casting a map from large to + small variants. Run in a subprocess, so an abort fails this test only.""" + done = subprocess.run( + [sys.executable, "-c", _NARROWED_MAP], + capture_output=True, + text=True, + check=False, + ) + assert done.returncode == 0, done.stderr[-2000:] + + +def test_a_record_id_repeated_in_one_write_is_refused() -> None: + """Review of PR 590, finding 2: refused before anything is written.""" + rows = keyed({"a": pa.array([1, 2])}) + rows = rows.set_column( + rows.column_names.index(KEY), KEY, pa.array([b"x", b"x"], pa.large_binary()) + ) + refused(rows, "repeated") + + +# ------------------------------------------------- the manifest in a table's metadata + + +def test_a_manifest_in_chunks_round_trips_within_the_entry_limit() -> None: + manifest = new(wide_schema(), PATH) + entries_ = store.manifest_entries(manifest) + assert len(entries_) > 2 # several chunks and the header + for key, value in entries_.items(): + assert len(key.encode()) + len(value) <= 8192 + others = {"orcapod.path": b"[]", "someone.else": b"x"} + assert store.read_manifest({**others, **entries_}, PATH) == manifest + + +def test_a_table_without_a_manifest_header_has_none() -> None: + entries_ = store.manifest_entries(new(schema_of(BASE))) + chunks = {k: v for k, v in entries_.items() if k != store.MANIFEST_KEY} + assert store.read_manifest({}, PATH) is None + assert store.read_manifest(chunks, PATH) is None + + +def test_chunks_of_an_earlier_longer_manifest_are_not_read() -> None: + longer = store.manifest_entries(new(wide_schema(), PATH)) + shorter = store.manifest_entries(new(schema_of(BASE), PATH)) + assert len(longer) > len(shorter) + assert store.read_manifest({**longer, **shorter}, PATH) == new(schema_of(BASE)) + + +def _header_changed(entries_: dict[str, bytes], **changes: Any) -> dict[str, bytes]: + """Return manifest entries whose header has ``changes`` applied, chunks unchanged. + + Args: + entries_: A manifest's metadata entries. + **changes: Header fields to set. + + Returns: + The entries with the header rewritten. + """ + header = {**json.loads(entries_[store.MANIFEST_KEY]), **changes} + return {**entries_, store.MANIFEST_KEY: json.dumps(header).encode()} + + +_BROKEN_ENTRIES: list[Callable[[dict[str, bytes]], dict[str, bytes]]] = [ + lambda e: {k: v for k, v in e.items() if k != f"{store.MANIFEST_KEY}/0"}, + lambda e: {**e, f"{store.MANIFEST_KEY}/0": e[f"{store.MANIFEST_KEY}/0"] + b" "}, + lambda e: {**e, store.MANIFEST_KEY: b"\xff"}, + lambda e: {**e, store.MANIFEST_KEY: b"[]"}, + lambda e: _header_changed(e, format="other"), + lambda e: _header_changed(e, chunks=0), + lambda e: _header_changed(e, chunks="1"), + lambda e: _header_changed(e, chunks=10**6), + lambda e: _header_changed(e, payload_digest="0" * 64), +] + + +@pytest.mark.parametrize("make", _BROKEN_ENTRIES) +def test_a_manifest_in_chunks_that_cannot_be_read_is_an_error( + make: Callable[[dict[str, bytes]], dict[str, bytes]], +) -> None: + with pytest.raises(store.ManifestError): + _ = store.read_manifest(make(store.manifest_entries(new(wide_schema()))), PATH) + + +# --------------------------------------- CodeRabbit on PR 590 (b433047e) + + +def test_a_schema_override_that_is_not_a_store_schema_is_a_manifest_error() -> None: + """``decode_rows`` raises its documented ``ManifestError``, also for a schema that + is no store schema at all (no key column).""" + table = keyed({"a": pa.array([1])}) + manifest = new(table.schema) + without_key = table.schema.remove(table.schema.get_field_index(KEY)) + with pytest.raises(store.ManifestError): + _ = store.decode_rows(_stored(table), manifest, without_key) + + +@pytest.mark.parametrize("where", ["schema", "physical"]) +def test_a_recorded_name_that_is_not_utf8_is_a_manifest_error(where: str) -> None: + """``read_manifest`` raises only ``ManifestError``, also for a name of bytes: in the + logical schema, and in a stored schema of the right shape (so that the name, not the + shape, is what is refused).""" + if where == "schema": + bad: Any = pa.field(cast(Any, b"a\xff"), pa.int8()) + recorded = _payload(schema=_ipc(schema_of([bad, (KEY, pa.large_binary())]))) + else: + first = store.physical_schema(schema_of(BASE)).field(0) + renamed: Any = pa.field(cast(Any, b"a\xff"), first.type, first.nullable) + recorded = _payload(physical=_ipc(_physical(0, renamed))) + with pytest.raises(store.ManifestError, match="UTF-8"): + _ = store.read_manifest_bytes(recorded, PATH) + + +# --------------------------------------- CodeRabbit on PR 595 (49f1642d) + + +def test_an_impossible_chunk_count_is_refused_before_any_key_is_listed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A header naming more chunks than the metadata holds entries is refused at once: + no key is built for each (a count of 10**12 would exhaust memory).""" + entries_ = store.manifest_entries(new(schema_of(BASE))) + real_range = range + + def bounded(*args: Any) -> Any: + stop = args[0] if len(args) == 1 else args[1] + if stop > len(entries_): + raise AssertionError(f"a key listed for each of {stop} declared chunks") + return real_range(*args) + + monkeypatch.setattr(store, "range", bounded, raising=False) + with pytest.raises(store.ManifestError, match="10000000000"): + _ = store.read_manifest(_header_changed(entries_, chunks=10**10), PATH) + monkeypatch.undo() + # A complete manifest of many chunks still reads, and a surplus chunk of an earlier + # manifest beside it is still ignored. + longer = store.manifest_entries(new(wide_schema(), PATH)) + assert store.read_manifest(longer, PATH) == new(wide_schema()) + + +@pytest.mark.parametrize("version", [1, -1, "0", 0.0, None, True]) +def test_a_manifest_header_of_another_version_is_refused(version: Any) -> None: + """The header's version is checked as the payload's is: an exact integer.""" + entries_ = store.manifest_entries(new(schema_of(BASE))) + changed = _header_changed(entries_, version=version) + with pytest.raises(store.ManifestError, match="header version"): + _ = store.read_manifest(changed, PATH) + without = json.loads(entries_[store.MANIFEST_KEY]) + del without["version"] + missing = {**entries_, store.MANIFEST_KEY: json.dumps(without).encode()} + with pytest.raises(store.ManifestError, match="header version"): + _ = store.read_manifest(missing, PATH) + + +@pytest.mark.parametrize("annotated", [False, True]) +def test_a_dictionary_of_a_logical_types_values_is_refused_as_unstorable( + annotated: bool, +) -> None: + """A dictionary whose values are a logical type, live or annotated, raises the + codec's ``UnstorableInSpiralError`` naming the column (it raised AttributeError).""" + live = Labelled(pa.large_string(), "test.dictionary", b"") + value_type: Any = pa.large_string() if annotated else live + values: Any = pa.dictionary(pa.int32(), value_type) + metadata = {NAME_KEY: b"test.dictionary", METADATA_KEY: b""} if annotated else None + field = pa.field("bad", values, True, cast(Any, metadata)) + schema = schema_of([("a", pa.int64()), field, (KEY, pa.large_binary())]) + for call in (store.physical_schema, store.logical_schema, entries): + with pytest.raises(store.UnstorableInSpiralError, match="'bad'"): + _ = call(schema) + + +# ------------------------------- independent review of PR 691 (10ac3d07d), round 1 + + +def test_extension_metadata_without_a_name_round_trips_through_chunks() -> None: + """Finding 1: ``ARROW:extension:metadata`` on a plain field (no extension name) names + no type; it is kept exactly, at the top of a column and nested, through the chunked + manifest and the rows.""" + plain = {b"ARROW:extension:metadata": b"preserve"} + inner = pa.field("a", pa.int64(), True, {b"ARROW:extension:metadata": b"inner"}) + schema = schema_of( + [ + (KEY, pa.large_binary()), + pa.field("x", pa.int64(), True, plain), + pa.field("y", pa.large_string(), True, {**plain, b"note": b"n"}), + pa.field("s", pa.struct([inner]), True), + ] + ) + rows = pa.Table.from_arrays( + [ + pa.array([b"k", b"j"], pa.large_binary()), + pa.array([1, None]), + pa.array(["a", "b"], pa.large_string()), + pa.array([{"a": 1}, {"a": None}], schema.field("s").type), + ], + schema=schema, + ) + loaded = store.read_manifest(store.manifest_entries(new(schema)), PATH) + assert loaded is not None + assert loaded.schema.equals(schema, check_metadata=True) + got = store.decode_rows(store.encode_rows(rows), loaded) + assert got.schema.equals(schema, check_metadata=True) + assert got.schema.field("x").metadata == plain + assert got.to_pylist() == rows.to_pylist() + # The entry counts in a comparison: a schema without it is another schema. + without = schema.set(1, pa.field("x", pa.int64())) + assert store.schema_difference(loaded.schema, without) is not None + + +@pytest.mark.parametrize("target", [7_999, 8_000, 8_001, 15_999, 16_000, 16_001]) +def test_the_manifest_is_cut_every_8000_bytes(target: int) -> None: + """Finding 4: the chunk boundary is part of the format. A payload of exactly + ``target`` bytes (the free-text kind pads it) is cut into 8,000-byte chunks, the + header's digest is the SHA-256 of the whole payload, it reads back whatever order + the metadata comes in, and a missing or modified last chunk is refused.""" + import hashlib + + schema = schema_of(BASE) + base = len(store.manifest_bytes(store.new_manifest(PATH, "", schema))) + manifest = store.new_manifest(PATH, "k" * (target - base), schema) + payload = store.manifest_bytes(manifest) + assert len(payload) == target + entries_ = store.manifest_entries(manifest) + count = -(-target // 8_000) + chunks = [entries_[f"{store.MANIFEST_KEY}/{i}"] for i in range(count)] + assert [len(c) for c in chunks] == [8_000] * (count - 1) + [ + target - 8_000 * (count - 1) + ] + assert set(entries_) == { + store.MANIFEST_KEY, + *(f"{store.MANIFEST_KEY}/{i}" for i in range(count)), + } + header = json.loads(entries_[store.MANIFEST_KEY]) + assert header["chunks"] == count + assert header["payload_digest"] == hashlib.sha256(payload).hexdigest() + assert b"".join(chunks) == payload + backwards = dict(reversed(list(entries_.items()))) + assert store.read_manifest(backwards, PATH) == manifest + last = f"{store.MANIFEST_KEY}/{count - 1}" + missing = {k: v for k, v in entries_.items() if k != last} + modified = {**entries_, last: entries_[last][:-1] + b"#"} + for broken in (missing, modified): + with pytest.raises(store.ManifestError): + _ = store.read_manifest(broken, PATH) + + +# ------------------------------------- CodeRabbit review of PR 691 (216f1982d) + + +def _decimal128(coefficients: list[int], precision: int) -> Any: + """A ``decimal128(precision, 2)`` array holding ``coefficients`` as they are, beyond + the precision too, as rows read back from a table could hold them.""" + data = b"".join(c.to_bytes(16, "little", signed=True) for c in coefficients) + from_buffers: Any = pa.Array.from_buffers # the stubs take no missing validity + return from_buffers( + pa.decimal128(precision, 2), len(coefficients), [None, pa.py_buffer(data)] + ) + + +@pytest.mark.parametrize( + ("logical", "precision"), [(pa.decimal32(9, 2), 9), (pa.decimal64(18, 2), 18)] +) +@pytest.mark.parametrize("over", [0, 3, 12]) +def test_a_stored_decimal_over_its_precision_is_refused( + logical: Any, precision: int, over: int +) -> None: + """Thread on spiral_store.py:789: a stored coefficient with more digits than the + logical decimal's precision is a ``StoredRowsError`` naming the column, never a raw + Arrow error, and never a wrapped value (pyarrow's narrowing cast lets 10**12 into a + decimal32 as -7273799.68).""" + D = decimal.Decimal + table = keyed({"d": pa.array([D("1.25"), D("-3.50")], logical)}) + good = _stored(table) + assert_same(decode(good, table.schema), large_table(table)) + wide = 10 ** (precision + over) + rows = good.set_column( + good.column_names.index("d"), "d", _decimal128([125, wide], precision) + ) + with pytest.raises(store.StoredRowsError, match="'d'"): + _ = decode(rows, table.schema) + + +def test_a_small_list_over_its_offset_range_is_refused( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Thread on spiral_store.py:748: a decoded large list of maps rebuilt as a small + list whose items do not fit 32-bit offsets is a ``StoredRowsError``, never wrapped + offsets. Reaching it for real takes more than 2**31 map items in one chunk (some + 16 GB), so the large list's offsets are made to say so.""" + entry = pa.map_(pa.large_string(), pa.int8()) + given: Any = pa.array([[[("a", 1)]]], pa.large_list(entry)) + target = pa.list_(pa.map_(pa.string(), pa.int8())) + real = store._offsets # pyright: ignore[reportPrivateUsage] + + def offsets(array: Any) -> Any: + if pa.types.is_large_list(array.type): + return np.array([0, 2**31], np.int64) + return real(array) + + assert store._retyped(given, target).to_pylist() == given.to_pylist() # pyright: ignore[reportPrivateUsage] + monkeypatch.setattr(store, "_offsets", offsets) + with pytest.raises(store.StoredRowsError, match="2147483648 items"): + _ = store._retyped(given, target) # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/test_spiral_store_identity.py b/tests/test_databases/test_spiral_store_identity.py new file mode 100644 index 000000000..55fae7171 --- /dev/null +++ b/tests/test_databases/test_spiral_store_identity.py @@ -0,0 +1,453 @@ +"""SpiralDB store table names and their identity record (ITL-1837; spec ITL-1446 round 2). + +The name rule itself, digest and hint, is main's shared one (``test_store_table_names.py``); +these tests cover SpiralDB's budget of it and the record in a table's metadata. +""" + +from __future__ import annotations + +import hashlib +import json +import random +import re +from collections.abc import Sequence +from typing import overload + +import pyarrow as pa +import pytest + +from orcapod.databases import spiral_store +from orcapod.databases import spiral_store_identity as names +from orcapod.databases import store_table_names + +H = "0123456789abcdef" * 4 +RESULT = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") +PIPELINE = ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2") +NAME = re.compile(r"^o1_[a-z0-9_]{1,96}_[0-9a-f]{64}$") + + +def test_the_digest_is_sha256_of_the_canonical_json_of_the_components() -> None: + """The digest is SHA-256 of the canonical JSON array of the components, ending the name.""" + expected = hashlib.sha256( + json.dumps(list(RESULT), ensure_ascii=False, separators=(",", ":")).encode() + ).hexdigest() + assert store_table_names.store_table_digest(RESULT) == expected + assert names.spiral_store_table_name(RESULT).endswith("_" + expected) + + +@pytest.mark.parametrize("path", [RESULT, PIPELINE, ("a",), ("É" * 300, "x" * 500)]) +def test_a_name_is_short_and_plain(path: tuple[str, ...]) -> None: + """A name is ``o1__<64 hex>``, within 164 characters, for short and long paths.""" + name = names.spiral_store_table_name(path) + assert NAME.match(name), name + assert len(name) <= 3 + 96 + 1 + 64 <= 255 + + +def test_the_hint_keeps_lower_case_letters_and_digits() -> None: + """The hint maps one character to one and is cut to 96 characters.""" + assert ( + store_table_names.table_name_hint(("My-Fn", "v0", "schema:AB"), hint_length=96) + == "my_fn_v0_schema_ab" + ) + # one character to one: each other character, the separator included, is one '_' + assert store_table_names.table_name_hint(("é", "a/b"), hint_length=96) == "__a_b" + assert store_table_names.table_name_hint(("é", "z"), hint_length=96) == "__z" + assert len(names.spiral_store_table_name(("x" * 200,))) - len("o1__") - 64 == 96 + + +def test_the_name_is_deterministic_and_depends_on_every_component_and_its_order() -> ( + None +): + """A name follows every component and their order, and nothing else.""" + assert names.spiral_store_table_name(RESULT) == names.spiral_store_table_name( + list(RESULT) + ) + assert names.spiral_store_table_name(RESULT) != names.spiral_store_table_name( + RESULT[::-1] + ) + for i in range(len(RESULT)): + changed = RESULT[:i] + (RESULT[i] + "x",) + RESULT[i + 1 :] + assert names.spiral_store_table_name(changed) != names.spiral_store_table_name( + RESULT + ) + + +def test_components_are_kept_apart() -> None: + # Paths whose joined text or hint agree still get different names. + """Paths whose joined text or hint agree still get different names.""" + pairs = [ + (("a", "b"), ("a/b",)), + (("a_b",), ("a-b",)), + (("ab", "c"), ("a", "bc")), + (("A",), ("a",)), + (("x",), ("x", "")), + ] + for left, right in pairs: + assert names.spiral_store_table_name(left) != names.spiral_store_table_name( + right + ) + + +def test_no_two_of_many_adversarial_paths_share_a_name() -> None: + """No two of 20,000 adversarial paths share a name.""" + rng = random.Random(1495) + alphabet = "aA0_-./:é \x00 " + seen: dict[str, tuple[str, ...]] = {} + for _ in range(20_000): + path = tuple( + "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 4))) + for _ in range(rng.randint(1, 3)) + ) + name = names.spiral_store_table_name(path) + assert seen.setdefault(name, path) == path + + +@pytest.mark.parametrize( + ("path", "prefix"), + [ + (RESULT, ()), + (RESULT, ("my_fn",)), + (RESULT, RESULT[:3]), + (RESULT, RESULT), + (("side_effects", "My Pod", H, "tdb_v1"), ("side_effects", "My Pod")), + (("f" * 120, H, "rdb_v1"), ("f" * 120,)), + (("f" * 60, "g" * 60, "rdb_v1"), ("f" * 60,)), + ], +) +def test_a_table_under_a_prefix_has_the_prefix_s_name_prefix( + path: tuple[str, ...], prefix: tuple[str, ...] +) -> None: + """Every table under a path prefix has the prefix's name prefix, also past 96 characters.""" + assert names.spiral_store_table_name(path).startswith( + names.spiral_store_table_name_prefix(prefix) + ) + + +def test_the_name_prefix_of_nothing_is_every_store_table() -> None: + """The name prefix of the empty path prefix is the one every store table has.""" + assert names.spiral_store_table_name_prefix(()) == "o1_" + + +@pytest.mark.parametrize("path", [(), ("a", 1), ("\ud800",)]) +def test_a_path_that_cannot_be_named_is_refused(path: tuple[object, ...]) -> None: + """An empty path, a component that is not text and one that is not UTF-8 are refused.""" + with pytest.raises(ValueError, match="path"): + _ = names.spiral_store_table_name(path) # pyright: ignore[reportArgumentType] # refused on purpose + + +def test_the_metadata_record() -> None: + """A table's record holds its format, path, layout and data context, and reads back.""" + record = names.store_table_metadata(PIPELINE, "std:v1:default") + assert record == { + "orcapod.store": b"orcapod.spiral_store.draft", + "orcapod.path": json.dumps( + list(PIPELINE), ensure_ascii=False, separators=(",", ":") + ).encode(), + "orcapod.layout": b"pdb_v2", + "orcapod.data_context": b"std:v1:default", + } + found = names.read_store_table_metadata(record) + assert found == names.StoreTableRecord(PIPELINE, "pdb_v2", "std:v1:default") + assert found is not None + names.require_store_table_path(found, PIPELINE) + + +def test_every_entry_fits_the_service_s_entry_limit() -> None: + """Every entry of a record fits SpiralDB's entry limit; a longer path is refused.""" + # The JSON of a one-component path is the component and 4 bytes: ``["..."]``. + longest = ("x" * (8192 - len("orcapod.path") - 4),) + record = names.store_table_metadata(longest, "std:v1:default") + assert all(len(k.encode()) + len(v) <= 8192 for k, v in record.items()) + with pytest.raises(ValueError, match="8192"): + _ = names.store_table_metadata((longest[0] + "x",), "std:v1:default") + + +def test_a_valid_component_can_still_be_too_long_for_the_identity_record() -> None: + """A component inside the path syntax is refused by the identity record's entry + limit, not by the syntax: the manifest, which is chunked, still keeps it.""" + path = ("x" * 8192, "rdb_v1") + assert store_table_names.require_store_path_domain(path) == path + manifest = spiral_store.new_manifest(path, "k", _schema()) + entries = spiral_store.manifest_entries(manifest) + assert spiral_store.read_manifest(entries, path) == manifest + with pytest.raises( + ValueError, match="'orcapod.path' is 8217 bytes, over SpiralDB's 8192" + ): + _ = names.store_table_metadata(path, "std:v1:default") + + +def test_a_table_without_orcapod_metadata_is_unmarked() -> None: + """A table with none of the record's entries is unmarked.""" + assert names.read_store_table_metadata({}) is None + assert names.read_store_table_metadata({"someone.else": b"1"}) is None + + +@pytest.mark.parametrize( + "change", + [ + {"orcapod.store": b"orcapod.spiral_store.v1"}, + {"orcapod.path": b"not json"}, + {"orcapod.path": b'{"a": 1}'}, + {"orcapod.path": b"[]"}, + {"orcapod.path": b'["a", 1]'}, + {"orcapod.layout": b"odb_v1"}, + {"orcapod.data_context": b""}, + {"orcapod.path": b"\xff"}, + ], +) +def test_a_record_that_is_not_this_store_s_is_refused(change: dict[str, bytes]) -> None: + """A record of another format, or with an unreadable or inconsistent entry, is refused.""" + record = {**names.store_table_metadata(PIPELINE, "std:v1:default"), **change} + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +@pytest.mark.parametrize( + "missing", + ["orcapod.store", "orcapod.path", "orcapod.layout", "orcapod.data_context"], +) +def test_a_partial_record_is_refused(missing: str) -> None: + """A record lacking one of its entries is refused.""" + record = names.store_table_metadata(PIPELINE, "std:v1:default") + del record[missing] + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +def test_a_table_of_another_path_under_the_name_is_refused() -> None: + """A record of another path than the one looked up is refused, naming it.""" + found = names.read_store_table_metadata( + names.store_table_metadata(RESULT, "std:v1:default") + ) + assert found is not None + with pytest.raises(names.SpiralStoreTableCollisionError, match="rdb_v1"): + names.require_store_table_path(found, PIPELINE) + + +def test_a_record_with_an_entry_over_the_service_s_limit_is_refused() -> None: + # Review of PR 589, finding 2: the data context key is the caller's text too. + """A record entry over SpiralDB's limit is refused before any table is created.""" + with pytest.raises(ValueError, match="8192"): + _ = names.store_table_metadata(PIPELINE, "x" * 8192) + + +def test_a_recorded_path_that_writers_refuse_is_refused_on_read() -> None: + # Review of PR 589, finding 3: JSON can spell a lone surrogate, which no writer writes. + """A recorded path no writer writes (a lone surrogate) is refused on read.""" + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": b'["\\ud800","rdb_v1"]', + } + with pytest.raises(names.SpiralStoreTableCollisionError, match="UTF-8"): + _ = names.read_store_table_metadata(record) + + +def test_the_collision_message_keeps_components_apart() -> None: + # Review of PR 589, finding 4: ("a b", ...) and ("a", "b", ...) must read differently. + """The collision message shows component lists, so different paths read differently.""" + found = names.read_store_table_metadata( + names.store_table_metadata(("a b", "rdb_v1"), "std:v1:default") + ) + assert found is not None + with pytest.raises(names.SpiralStoreTableCollisionError) as raised: + names.require_store_table_path(found, ("a", "b", "rdb_v1")) + assert "['a b', 'rdb_v1']" in str(raised.value) + assert "['a', 'b', 'rdb_v1']" in str(raised.value) + + +@pytest.mark.parametrize( + "path_json", + [b"[" + b"1" * 5000 + b"]", b"[" * 2000 + b"0" + b"]" * 2000], + ids=["a 5,000-digit integer", "2,000 nested arrays"], +) +def test_a_path_the_json_parser_refuses_is_a_collision(path_json: bytes) -> None: + """CodeRabbit on PR 589: every unreadable record raises the collision error.""" + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": path_json, + } + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +def test_the_spiraldb_name_is_the_shared_rule_with_spiraldb_s_budget() -> None: + """The name is main's shared store rule at hint 96 and the whole digest: the vector + ``test_store_table_names.py`` pins for SpiralDB, and no rule of its own.""" + path = ("función", "数据", "rdb_v1") + assert names.spiral_store_table_name(path) == ( + "o1_funci_n____rdb_v1_" + "4c0b0f48110dc57f910431847088e2e11d05b6bf2b26c3e8dfb8dd9dabf2c43b" + ) + assert names.spiral_store_table_name(path) == store_table_names.store_table_name( + path, hint_length=96, digest_length=64 + ) + + +def test_the_store_format_is_marked_provisional() -> None: + """Tables are written in a draft format until the store is switched on, so a table + of this format is told apart from one of the format eventually fixed.""" + assert names.STORE_FORMAT.endswith(".draft") + + +def test_the_collision_error_names_the_table_its_caller_gives() -> None: + """The caller that knows the table adds it; the reason stays readable on its own.""" + plain = names.SpiralStoreTableCollisionError("its record lacks ['orcapod.path']") + assert str(plain) == "not this store's table: its record lacks ['orcapod.path']" + assert plain.table is None + placed = names.SpiralStoreTableCollisionError("x", table="p/d/o1_t") + assert str(placed) == "table p/d/o1_t: not this store's table: x" + assert (placed.reason, placed.table) == ("x", "p/d/o1_t") + + +# ------------------------------- independent review of PR 691 (10ac3d07d), round 1 + +_OUTSIDE = [ + (), + ("",), + ("base", "", "rdb_v1"), + ("base/part", "rdb_v1"), + ("base", "a\0b", "rdb_v1"), + ("\udc00", "rdb_v1"), + ("base", 1, "rdb_v1"), +] +_INSIDE = [ + ("rdb_v1",), + ("base", "part", "rdb_v1"), + ("run", " ", "é", '"', "\u2028", "a.b:c", "pdb_v2"), +] + + +def _schema() -> pa.Schema: + return pa.schema( + [ + pa.field(spiral_store.KEY_COLUMN, pa.large_binary(), False), + pa.field("x", pa.int64()), + ] + ) + + +def _manifest_payload(path: object) -> bytes: + """A manifest payload recording ``path``, as a writer outside the domain would.""" + body = json.loads( + spiral_store.manifest_bytes( + spiral_store.new_manifest(("ok", "rdb_v1"), "k", _schema()) + ) + ) + body["record_path"] = path + return json.dumps(body).encode() + + +@pytest.mark.parametrize("path", _OUTSIDE) +def test_the_record_and_the_manifest_refuse_the_same_paths( + path: tuple[object, ...], +) -> None: + """Finding 2: the identity record and the manifest refuse one path domain + (``store_table_names.require_store_path_domain``), on write and on read.""" + with pytest.raises(ValueError, match="path"): + _ = store_table_names.require_store_path_domain(path) # pyright: ignore[reportArgumentType] # refused on purpose + with pytest.raises(ValueError, match="path"): + _ = names.store_table_metadata(path, "std:v1:default") # pyright: ignore[reportArgumentType] # refused on purpose + with pytest.raises(spiral_store.UnstorableInSpiralError): + _ = spiral_store.new_manifest(path, "k", _schema()) # pyright: ignore[reportArgumentType] # refused on purpose + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": json.dumps(list(path)).encode(), + "orcapod.layout": (str(path[-1]) if path else "").encode("utf-8", "replace"), + } + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + with pytest.raises(spiral_store.ManifestError): + _ = spiral_store.read_manifest_bytes(_manifest_payload(list(path)), path) # pyright: ignore[reportArgumentType] # refused on purpose + + +@pytest.mark.parametrize("path", _INSIDE) +def test_the_record_and_the_manifest_accept_the_same_paths( + path: tuple[str, ...], +) -> None: + """Finding 2: a path inside the domain is written and read back by both.""" + assert store_table_names.require_store_path_domain(path) == path + found = names.read_store_table_metadata( + names.store_table_metadata(path, "std:v1:default") + ) + assert found is not None and found.path == path + manifest = spiral_store.new_manifest(path, "k", _schema()) + entries = spiral_store.manifest_entries(manifest) + assert spiral_store.read_manifest(entries, path) == manifest + + +# ------------------------------------- CodeRabbit review of PR 691 (216f1982d) + + +class _ShiftingPath(Sequence[str]): + """A path whose last component reads as another name after its first full read.""" + + def __init__(self) -> None: + """Start with ``("base", "rdb_v1")``, read once.""" + self.reads = 0 + + def __len__(self) -> int: + """Two components.""" + return 2 + + @overload + def __getitem__(self, index: int) -> str: ... + @overload + def __getitem__(self, index: slice) -> Sequence[str]: ... + def __getitem__(self, index: int | slice) -> str | Sequence[str]: + """``rdb_v1`` as the last component on the first read, ``pdb_v2`` later.""" + if isinstance(index, slice): + return [self[i] for i in range(2)][index] + if index < 0: + index += 2 + if index not in (0, 1): + raise IndexError(index) + if index == 0: + return "base" + self.reads += 1 + return "rdb_v1" if self.reads == 1 else "pdb_v2" + + +def test_the_layout_is_the_last_component_of_the_path_recorded() -> None: + """Thread on spiral_store_identity.py:147: the layout is taken from the validated + snapshot of the path, so a path that reads differently later records one path.""" + record = names.store_table_metadata(_ShiftingPath(), "std:v1:default") + found = names.read_store_table_metadata(record) + assert found is not None + assert (found.path, found.layout) == (("base", "rdb_v1"), "rdb_v1") + + +def test_the_record_keeps_the_order_of_its_path_components() -> None: + """Thread on test_spiral_store_identity.py:315: the same components in two orders + are two recorded paths, each read back in the order given; the layout is fixed.""" + first, second = ("base", "part", "rdb_v1"), ("part", "base", "rdb_v1") + one = names.store_table_metadata(first, "std:v1:default") + two = names.store_table_metadata(second, "std:v1:default") + assert one[names.PATH_KEY] != two[names.PATH_KEY] + assert one[names.LAYOUT_KEY] == two[names.LAYOUT_KEY] == b"rdb_v1" + for path, record in ((first, one), (second, two)): + found = names.read_store_table_metadata(record) + assert found is not None and found.path == path + + +@pytest.mark.parametrize("kind", ["", "k", "é
"]) +def test_a_manifest_kind_is_read_as_any_utf8_text(kind: str) -> None: + """Thread on spiral_store.py:937: an empty or non-ASCII kind still reads back.""" + path = ("ok", "rdb_v1") + manifest = spiral_store.new_manifest(path, kind, _schema()) + assert ( + spiral_store.read_manifest_bytes(spiral_store.manifest_bytes(manifest), path) + == manifest + ) + + +def test_a_manifest_kind_with_no_utf8_form_is_refused_on_read() -> None: + """Thread on spiral_store.py:937: a JSON escape can give a kind with a lone + surrogate, which ``new_manifest`` refuses; the reader refuses it too.""" + path = ("ok", "rdb_v1") + payload = spiral_store.manifest_bytes( + spiral_store.new_manifest(path, "k", _schema()) + ) + escaped = payload.replace(b'"kind":"k"', b'"kind":"\\udc00"') + assert escaped != payload + with pytest.raises(spiral_store.ManifestError, match="kind"): + _ = spiral_store.read_manifest_bytes(escaped, path) diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 29b8ac231..010316e3d 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -15,14 +15,17 @@ from __future__ import annotations import datetime as dt +import decimal import math import operator import os import struct +import uuid from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path from typing import Any +from unittest.mock import patch import pyarrow as pa import pyarrow.compute as pc @@ -481,3 +484,461 @@ def test_a_source_reads_a_window_with_an_equality_and_a_limit(place: _Place) -> assert limited.as_table()["k"].to_pylist() == expected[:2] with pytest.raises(TypeError, match="integer, timestamp or date"): place.source("ranges").where(col("x") > 0.0) + + +def _client(place: _Place) -> Any: + """Return an SDK client on the place, for the test's own reads and writes.""" + if place.overrides is None: + return fake.FakeClient() + return place.connector()._client # pyright: ignore[reportPrivateUsage] # the SDK's client, for the test's own writes + + +def test_table_metadata(place: _Place) -> None: + """Table metadata as measured with spiral-sdk 0.16.78 (the fake's ``table-metadata``). + + Fixed keys only, so a live table does not grow from run to run. + """ + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, "table_metadata", key, exist_ok=True + ) + token = uuid.uuid4().hex.encode() + table.set_metadata({"conformance.a": token, "conformance.b": b"before"}) + table.set_metadata({"conformance.b": token, "conformance.empty": b""}) + found = table.get_metadata() + assert found["conformance.a"] == token # an upsert keeps the other keys + assert found["conformance.b"] == token + assert found["conformance.empty"] == b"" # stored as empty, not deleted + + # Not versioned: a snapshot taken before a write sees metadata set after it, and a + # metadata write makes no snapshot. + before = client.keyed_table(place.project, place.dataset, "table_metadata") + after = before.append( + pa.table({"k": pa.array(["r"], pa.large_string()), "v": pa.array([token])}) + ) + after.set_metadata({"conformance.after": token}) + assert before.get_metadata()["conformance.after"] == token + pinned = client.keyed_table_by_id(before.resource_id, asof=int(before.version_id)) + assert pinned.get_metadata()["conformance.after"] == token + again = client.keyed_table(place.project, place.dataset, "table_metadata") + assert again.version_id == after.version_id + + # Limits: a key up to 255 UTF-8 bytes, a key and its value together up to 8,192. + table.set_metadata( + {"m" * 255: b"x" * (8192 - 255), "conformance.max": b"x" * (8192 - 15)} + ) + for refused in ( + {"m" * 256: token}, + {"conformance.big": b"x" * (8192 - 15 + 1)}, + {"m" * 255: b"x" * (8192 - 255 + 1)}, + ): + with pytest.raises(Exception, match=r"status 400"): # noqa: PT011 # the SDK's error type differs from the fake's + table.set_metadata(refused) + found = table.get_metadata() + assert found["m" * 255] == b"x" * (8192 - 255) + assert "m" * 256 not in found + assert "conformance.big" not in found + + +def test_the_fake_keeps_concurrent_upserts_of_different_keys(tmp_path: Path) -> None: + """Two clients upserting different keys at once keep both (measured live, 0.16.78). + + Review of PR 589, finding 1: each read waits for the other writer's read, so an + upsert that is not atomic would lose one key. + """ + import threading + + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + made = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + both_read = threading.Barrier(2, timeout=0.5) + original = fake._Store.metadata # pyright: ignore[reportPrivateUsage] # the read an upsert starts from + + def metadata_after_the_other_read(self: Any, table_id: str) -> dict[str, bytes]: + found = original(self, table_id) + try: + _ = both_read.wait() + except threading.BrokenBarrierError: + pass # an atomic upsert holds the other writer back: no meeting + return found + + def upsert(name: str) -> None: + fake.FakeClient().keyed_table_by_id(made.resource_id).set_metadata( + {name: b"1"} + ) + + with patch.object(fake._Store, "metadata", metadata_after_the_other_read): # pyright: ignore[reportPrivateUsage] + writers = [threading.Thread(target=upsert, args=(n,)) for n in "ab"] + for w in writers: + w.start() + for w in writers: + w.join() + assert made.get_metadata() == {"a": b"1", "b": b"1"} + + +# ------------------------------------------------ the store codec (ITL-1497) + + +map_of: Any = pa.map_ # the stubs lack keys_sorted + + +def _codec_rows() -> pa.Table: + """Rows of a store table: names the codec escapes, and every kept kind of value.""" + from orcapod.databases import spiral_store + + utc = dt.timezone.utc + inner = pa.struct([pa.field("a.b", pa.int8(), False), pa.field("__c", pa.int8())]) + keys = [b"r0", b"r1", b"r2"] + columns: dict[str, Any] = { # pyarrow arrays of several types + spiral_store.KEY_COLUMN: pa.array(keys, pa.large_binary()), + "__data_context": pa.array(["std:v1:default"] * 3, pa.large_string()), + "a.b": pa.array([1, 2, None], pa.int64()), + "$x": pa.array([True, None, False]), + "*": pa.array([b"", b"\x00", None], pa.large_binary()), + "ok$*;": pa.array([0, 2**64 - 1, None], pa.uint64()), + "ts_utc": pa.array( + [ + dt.datetime.max.replace(tzinfo=utc), + dt.datetime.min.replace(tzinfo=utc), + None, + ], + pa.timestamp("us", tz="UTC"), + ), + "ts_ns": pa.array([2**63 - 1, -(2**63), 0], pa.int64()).view( + pa.timestamp("ns", tz="-03:30") + ), + "time": pa.array([-1, 86_400_000_000, None], pa.int64()).view(pa.time64("us")), + "f32": pa.array([0x7FC00001, 0x80000000, 0xFF800001], pa.uint32()).view( + pa.float32() + ), + "d32": pa.array( + [decimal.Decimal("1.23"), None, decimal.Decimal("-0.01")], + pa.decimal32(5, 2), + ), + "d64": pa.array([86_400_000 + 1, 0, None], pa.int64()).view(pa.date64()), + "s": pa.array([{"a.b": 1, "__c": None}] * 3, inner), + "ls": pa.array( + [[{"a.b": 1, "__c": 2}, {"a.b": 2, "__c": None}], None, []], + pa.large_list(inner), + ), + "fl": pa.array( + [[{"a.b": 1, "__c": 2}], None, [{"a.b": 3, "__c": None}]], + pa.list_(inner, 1), + ), + "m": pa.array( + [[("b", 1), ("a", 2)], None, []], + map_of(pa.large_string(), pa.int64(), keys_sorted=True), + ), + "n": pa.array([None, None, None], pa.null()), + } + return pa.table(columns) + + +def test_the_store_codec_round_trips(place: _Place) -> None: + """Encoded rows written through spiral-sdk and decoded back are the rows, exactly. + + A fixed table and fixed rows, so a live run writes the same rows each time. + """ + from orcapod.databases import spiral_store + + rows = _codec_rows() + manifest = spiral_store.new_manifest(("conformance", "rdb_v1"), "test", rows.schema) + encoded = spiral_store.encode_rows(rows) + key = pa.schema([pa.field(spiral_store.KEY_COLUMN, pa.large_binary(), False)]) + client = _client(place) + table = client.project(place.project).create_keyed_table( + place.dataset, "store_codec", key, exist_ok=True + ) + table = table.append(encoded) + read_back = client.keyed_table_by_id(table.resource_id).scan().to_table() + decoded = spiral_store.decode_rows(read_back, manifest) + order = pa.array( + sorted( + range(decoded.num_rows), + key=lambda i: decoded[spiral_store.KEY_COLUMN][i].as_py(), + ), + pa.int64(), + ) + got = decoded.take(order) + want = rows.cast(spiral_store.logical_schema(rows.schema)) + assert got.schema.equals(want.schema, check_metadata=True) + for name in want.column_names: + a, b = got.column(name).combine_chunks(), want.column(name).combine_chunks() + if pa.types.is_floating(a.type): + assert a.view(pa.uint32()).equals(b.view(pa.uint32())), name + else: + assert a.equals(b), name + + +@pytest.mark.parametrize( + "column", + [ + pa.table({"*": pa.array([1])}), + pa.table({"": pa.array([1])}), + pa.table({"__x": pa.array([1])}), + pa.table({"$x": pa.array([1])}), + pa.table({"a.b": pa.array([1])}), + pa.table({"s": pa.array([{"a.b": 1}], pa.struct([("a.b", pa.int8())]))}), + pa.table({"t": pa.array([86_400], pa.int32()).view(pa.time32("s"))}), + pa.table({"t": pa.array([-1], pa.int64()).view(pa.time64("ns"))}), + pa.table({"b": pa.array([b"ab"], pa.binary(2))}), + pa.table({"s": pa.array([{"a": 1}, None], pa.struct([("a", pa.int8())]))}), + pa.table({"s": pa.array([{}], pa.struct([]))}), + ], + ids=lambda t: f"{t.schema.names[0]!r}: {t.schema.types[0]}", +) +def test_what_the_store_codec_avoids_is_refused( + place: _Place, column: pa.Table +) -> None: + """The service refuses each name and value the codec never writes; nothing is written.""" + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, "store_codec_refusals", key, exist_ok=True + ) + n = column.num_rows + rows = column.add_column( + 0, "k", pa.array([f"r{i}" for i in range(n)], pa.large_string()) + ) + with pytest.raises(Exception): # noqa: B017, PT011 # the SDK's error type differs from the fake's + _ = table.append(rows) + again = client.keyed_table_by_id(table.resource_id) + assert again.version_id == table.version_id + + +def test_a_duration_is_stored_and_read_back_as_given(place: _Place) -> None: + """A duration column is accepted from spiral-sdk 0.16.80 and read back with its unit + and value (the fake's ``unsupported``; 0.16.78 refused it). Written to the table of + the refusals above, which already holds this column and row: no new table.""" + column = pa.table({"d": pa.array([1], pa.duration("s"))}) + got = _written_and_read(place, "store_codec_refusals", column) + assert got.schema.field("d").type == pa.duration("s") + assert got.column("d").to_pylist() == [dt.timedelta(seconds=1)] + + +def _written_and_read(place: _Place, name: str, column: pa.Table) -> pa.Table: + """Write ``column`` under keys r0... to a fixed table and read those rows back.""" + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, name, key, exist_ok=True + ) + keys = pa.array([f"r{i}" for i in range(column.num_rows)], pa.large_string()) + table = table.append(column.add_column(0, "k", keys)) + read = client.keyed_table_by_id(table.resource_id).scan().to_table() + return read.filter(pc.is_in(read.column("k"), keys)).sort_by("k") + + +def test_a_zero_width_fixed_size_list_of_strings_round_trips(place: _Place) -> None: + """Review of PR 590, finding 3 (the fake's rebuild of a zero-width list).""" + value = [[], None, []] + column = pa.table({"z": pa.array(value, pa.list_(pa.large_string(), 0))}) + got = _written_and_read(place, "zero_width_lists", column) + assert got.column("z").to_pylist() == value + + +def test_nul_is_cut_in_nested_field_names(place: _Place) -> None: + """Review of PR 590, finding 4: the service cuts a name at NUL at every depth + (measured live with spiral-sdk 0.16.78).""" + inner = pa.struct([("x\0y", pa.int8()), ("z", pa.int8())]) + column = pa.table( + { + "s": pa.array([{"x\0y": 1, "z": 2}], inner), + "l": pa.array([[{"x\0y": 3, "z": 4}]], pa.large_list(inner)), + } + ) + got = _written_and_read(place, "nul_in_field_names", column) + assert got.column("s").to_pylist() == [{"x": 1, "z": 2}] + assert got.column("l").to_pylist() == [[{"x": 3, "z": 4}]] + + +def test_the_fake_never_shows_a_half_written_metadata_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """CodeRabbit on PR 589: a reader during a metadata write sees a whole mapping. + + Every file write is made to call a reader after it has truncated its file and before + it has written anything. + """ + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + table.set_metadata({"a": b"1"}) + seen: list[dict[str, bytes]] = [] + original = Path.write_text + + def write_text_with_a_reader( + self: Path, data: str, *args: Any, **kw: Any + ) -> int: + with self.open("w") as handle: + handle.flush() + seen.append( + fake.FakeClient() + .keyed_table_by_id(table.resource_id) + .get_metadata() + ) + return original(self, data, *args, **kw) + + monkeypatch.setattr(Path, "write_text", write_text_with_a_reader) + table.set_metadata({"b": b"2"}) + monkeypatch.undo() + assert seen == [{"a": b"1"}] + assert table.get_metadata() == {"a": b"1", "b": b"2"} + + +@pytest.mark.parametrize("child", ["x", "x\0y"]) +def test_a_null_under_a_non_null_column_is_refused_whatever_its_names( + place: _Place, child: str +) -> None: + """Review of PR 590 (round 2): cutting a nested name at NUL keeps the column's flag.""" + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, "nul_names_non_null", key, exist_ok=True + ) + item = pa.struct([(child, pa.int8())]) + schema = pa.schema( + [ + pa.field("k", pa.large_string(), False), + pa.field("l", pa.large_list(item), nullable=False), + ] + ) + rows = pa.Table.from_arrays( + [ + pa.array(["r0", "r1"], pa.large_string()), + pa.array([[{child: 1}], None], pa.large_list(item)), + ], + schema=schema, + ) + with pytest.raises(Exception): # noqa: B017, PT011 # the SDK's error type differs from the fake's + _ = table.append(rows) + + +def _encoded(array: Any, how: str) -> Any: + """``array`` (of two equal values) dictionary-encoded or run-end encoded, built + from parts, as pyarrow encodes no struct itself.""" + one = array.slice(0, 1) + if how == "dictionary": + return pa.DictionaryArray.from_arrays(pa.array([0, 0], pa.int32()), one) + return pa.RunEndEncodedArray.from_arrays(pa.array([2], pa.int32()), one) + + +@pytest.mark.parametrize("how", ["dictionary"]) +def test_the_fake_refuses_an_encoded_time_outside_a_day( + tmp_path: Path, how: str +) -> None: + """CodeRabbit on PR 590: the time rule holds inside encoded arrays too. (pyarrow + refuses to build a run-end-encoded array of such a time, so only a dictionary can + carry one.)""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + times = pa.array([-1, -1], pa.int64()).view(pa.time64("ns")) + rows = pa.table( + {"k": pa.array(["a", "b"], pa.large_string()), "t": _encoded(times, how)} + ) + with pytest.raises(fake.SpiralError, match="time"): + _ = table.append(rows) + + +@pytest.mark.parametrize("how", ["dictionary", "run_end"]) +def test_the_fake_cuts_nul_in_names_inside_encoded_arrays( + tmp_path: Path, how: str +) -> None: + """CodeRabbit on PR 590: the NUL rule holds inside encoded arrays too.""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + values = pa.array([{"x\0y": 1}, {"x\0y": 1}], pa.struct([("x\0y", pa.int8())])) + rows = pa.table( + {"k": pa.array(["a", "b"], pa.large_string()), "s": _encoded(values, how)} + ) + stored = table.append(rows).scan().to_table() + assert stored.column("s").to_pylist() == [{"x": 1}, {"x": 1}] + + +def test_the_fake_cuts_nul_in_names_inside_nested_encoded_arrays( + tmp_path: Path, +) -> None: + """CodeRabbit on PR 590 (round 2): an encoded struct inside a list is cut too.""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + one = pa.array([{"x\0y": 1}], pa.struct([("x\0y", pa.int8())])) + encoded = pa.DictionaryArray.from_arrays(pa.array([0, 0], pa.int32()), one) + lists = pa.LargeListArray.from_arrays(pa.array([0, 1, 2], pa.int64()), encoded) + rows = pa.table({"k": pa.array(["a", "b"], pa.large_string()), "l": lists}) + stored = table.append(rows).scan().to_table() + assert stored.column("l").to_pylist() == [[{"x": 1}], [{"x": 1}]] + + +# ---------------------------------- verification r3 of PR 590 (0dc34c95) + + +class _ProbeExtension(pa.ExtensionType): + """An extension type of the tests' own, over any storage.""" + + def __init__(self, storage: Any) -> None: + super().__init__(storage, "orcapod.test.probe") + + def __arrow_ext_serialize__(self) -> bytes: + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(storage_type) + + +def _struct_one(name: str) -> Any: + return pa.array([{name: 1}], pa.struct([(name, pa.int8())])) + + +def _dictionary_of(values: Any, n: int) -> Any: + return pa.DictionaryArray.from_arrays(pa.array([0] * n, pa.int32()), values) + + +def test_a_sliced_nullable_list_of_encoded_structs_round_trips(place: _Place) -> None: + """A null row of a sliced list over dictionary-encoded structs is kept (measured + live with spiral-sdk 0.16.78: such a list is stored as its decoded values).""" + lists = pa.LargeListArray.from_arrays( + pa.array([0, 1, 2, 3], pa.int64()), + _dictionary_of(_struct_one("x"), 3), + mask=pa.array([False, True, False]), + ) + got = _written_and_read( + place, "sliced_encoded_lists", pa.table({"l": lists.slice(1, 2)}) + ) + assert got.column("l").to_pylist() == [None, [{"x": 1}]] + + +@pytest.mark.parametrize("encoded", [False, True], ids=["plain", "dictionary"]) +def test_nul_is_cut_in_names_inside_an_extension(place: _Place, encoded: bool) -> None: + """An extension column is stored as its storage, its struct names cut at NUL (measured + live with spiral-sdk 0.16.78 for a plain struct).""" + storage = _struct_one("x\0y") + if encoded: + storage = _dictionary_of(storage, 1) + column = pa.ExtensionArray.from_storage(_ProbeExtension(storage.type), storage) + got = _written_and_read( + place, f"nul_in_extension_{encoded}", pa.table({"e": column}) + ) + assert got.column("e").to_pylist() == [{"x": 1}] + + +def test_a_reserved_name_inside_an_encoded_struct_is_refused(place: _Place) -> None: + """Measured live with spiral-sdk 0.16.78: a struct field named ``$a`` is refused, also + when the struct is dictionary-encoded.""" + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, "reserved_in_encoded", key, exist_ok=True + ) + rows = pa.table( + { + "k": pa.array(["r0", "r1"], pa.large_string()), + "s": _dictionary_of(_struct_one("$a"), 2), + } + ) + with pytest.raises(Exception, match="reserved"): # noqa: B017, PT011 # the SDK's error type differs from the fake's + _ = table.append(rows) diff --git a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py new file mode 100644 index 000000000..48ce773b6 --- /dev/null +++ b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py @@ -0,0 +1,147 @@ +"""spiral-sdk's keyed-table deprecation is ignored for Orcapod's own opens only (ITL-1837). + +spiral-sdk 0.16.79 and later warn on every keyed-table open, attributed to the module that +calls the SDK. These tests use the real spiral-sdk client, its native client replaced by a +stub, so the warning is the SDK's own and no service is called. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Iterator +from typing import Any +from unittest.mock import patch + +import pytest + +sp = pytest.importorskip("spiral") + +from orcapod.databases import spiraldb_connector # noqa: E402 # after the skip +from orcapod.databases.spiraldb_connector import ( # noqa: E402 # after the skip + SpiralDBConnector, + SpiralDBTableNotFoundError, +) + +MESSAGE = r"Keyed tables are deprecated\." + + +class _NativeTable: + """What the SDK's keyed table handle reads from its native table.""" + + resource_id = "tbl_1" + version_id = "1" + key_columns = ("k",) + + +class _NativeClient: + """A native client that answers an open of table ``t`` and nothing else.""" + + def keyed_table( + self, project: str, dataset: str, name: str, *, asof: int | None = None + ) -> _NativeTable: + """Open ``t``; any other name is not found, in the service's words.""" + if name == "t": + return _NativeTable() + raise sp.SpiralError(f"resource not found: {project}.{dataset}.{name}") + + def keyed_table_by_id(self, table_id: str, *, asof: int | None = None) -> Any: + """Refuse every version: the tests stop at the open.""" + raise sp.SpiralError(f"no version {asof} of {table_id}") + + +class _Client(sp.Client): + """spiral-sdk's client with the stub native client: its own methods run.""" + + def __init__(self, **_: Any) -> None: # pyright: ignore[reportMissingSuperCall] # the SDK's would sign in + """Hold the stub; sign in nowhere.""" + self._native = _NativeClient() + + +class _SDK: + """The ``spiral`` module as the connector sees it, with the stubbed client.""" + + Client = _Client + SpiralError = sp.SpiralError + + +@pytest.fixture +def connector() -> Iterator[SpiralDBConnector]: + """A connector on the real spiral-sdk client over the stub native client.""" + with ( + patch.object(spiraldb_connector, "sp", _SDK), + patch.object(spiraldb_connector, "require_sign_in", lambda: None), + ): + made = SpiralDBConnector("p", "d") + yield made + made.close() + + +def test_orcapod_opens_keyed_tables_with_no_deprecation_warning( + connector: SpiralDBConnector, +) -> None: + """With every warning an error, Orcapod's opens of a table (by name, found and not + found) and of a version (by id) raise what the stub raises, never the deprecation.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(SpiralDBTableNotFoundError): + _ = connector.lookup_table("missing") + table = connector.lookup_table("t") + assert table.table_id == "tbl_1" + with pytest.raises(sp.SpiralError, match="no version 2"): + _ = table.arrow_schema(asof=2) + + +def test_a_direct_sdk_open_still_warns(connector: SpiralDBConnector) -> None: + """The filter Orcapod installs covers its own module only: an open called from + another module (this test), by name or by id, still warns, after Orcapod's open.""" + client = _Client() + with warnings.catch_warnings(): + warnings.simplefilter("error") + _ = connector.lookup_table("t") # installs Orcapod's filter + with pytest.raises(DeprecationWarning, match=MESSAGE): + _ = client.keyed_table("p", "d", "t") + with pytest.raises(DeprecationWarning, match=MESSAGE): + _ = client.keyed_table_by_id("tbl_1", asof=1) + + +def test_an_error_filter_added_after_an_open_does_not_reach_orcapods_opens( + connector: SpiralDBConnector, +) -> None: + """The first matching filter wins: an error filter added after Orcapod's first open + ranks ahead of a filter that is merely present. Orcapod's later opens, by name and + by id, still raise no warning and no misleading connection error.""" + with warnings.catch_warnings(): + table = connector.lookup_table("t") # installs Orcapod's filter + warnings.simplefilter("error") + again = connector.lookup_table("t") + assert again.table_id == "tbl_1" + with pytest.raises(sp.SpiralError, match="no version 2"): + _ = table.arrow_schema(asof=2) + + +def test_a_pytest_warns_block_after_an_open_records_no_deprecation( + connector: SpiralDBConnector, +) -> None: + """``pytest.warns`` adds an "always" filter; Orcapod's opens inside it, after an + earlier open, record nothing of the SDK's deprecation.""" + with warnings.catch_warnings(): + table = connector.lookup_table("t") # installs Orcapod's filter + with pytest.warns(UserWarning, match="the block's own") as recorded: + _ = connector.lookup_table("t") + with pytest.raises(sp.SpiralError, match="no version 2"): + _ = table.arrow_schema(asof=2) + warnings.warn("the block's own", UserWarning, stacklevel=1) + assert [type(w.message) for w in recorded] == [UserWarning] + + +def test_the_filter_is_kept_once_however_often_orcapod_opens( + connector: SpiralDBConnector, +) -> None: + """Moved to the front rather than added again: the filter list never grows.""" + with warnings.catch_warnings(): + for _ in range(3): + _ = connector.lookup_table("t") + warnings.simplefilter("error") + _ = connector.lookup_table("t") + assert warnings.filters[0] == spiraldb_connector._KEYED_TABLE_FILTER + assert warnings.filters.count(spiraldb_connector._KEYED_TABLE_FILTER) == 1 diff --git a/uv.lock b/uv.lock index 57da3a714..f69cfb20b 100644 --- a/uv.lock +++ b/uv.lock @@ -1960,8 +1960,8 @@ requires-dist = [ { name = "redis", marker = "extra == 'all'", specifier = ">=6.2.0" }, { name = "redis", marker = "extra == 'redis'", specifier = ">=6.2.0" }, { name = "s3fs", specifier = ">=2025.12.0" }, - { name = "spiral-sdk", marker = "extra == 'all'", specifier = "==0.16.74" }, - { name = "spiral-sdk", marker = "extra == 'spiraldb'", specifier = "==0.16.74" }, + { name = "spiral-sdk", marker = "extra == 'all'", specifier = "==0.16.80" }, + { name = "spiral-sdk", marker = "extra == 'spiraldb'", specifier = "==0.16.80" }, { name = "starfix", specifier = ">=0.6.0,<0.7" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'all'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'torch'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, @@ -3292,16 +3292,16 @@ wheels = [ [[package]] name = "spiral-sdk" -version = "0.16.74" +version = "0.16.80" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "pyarrow" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/e4/35/68f43088c6d1ec1db947620a58ea9d3096b6871b22367cb7aee86da88387/spiral_sdk-0.16.74-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:3f624ce767c074fbc04e0d2c96db6b4587fae2f8b653f1b15a8c9d35bc524586", size = 78387050, upload-time = "2026-11-24T19:03:05.807Z" }, - { url = "https://files.pythonhosted.org/packages/b4/23/47a6e94f2b86ed7113f1c2ee2c7289667168829d8098d5a3cdcd75bd1b9a/spiral_sdk-0.16.74-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ab2278a9b47828f98d93f76e2b93d57f16cf0b2008fc723ae7f788ea8607d495", size = 87372785, upload-time = "2026-11-24T19:03:11.829Z" }, - { url = "https://files.pythonhosted.org/packages/b9/d0/96107cf185d1bef4cfd427775553594c4decf420997019913a26eb8e5c38/spiral_sdk-0.16.74-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:46bb6f94583e507fcf31b2a3344ab4a582129c495c1bd782aaf64b4dd513ac9b", size = 90075516, upload-time = "2026-11-24T19:03:17.262Z" }, + { url = "https://files.pythonhosted.org/packages/37/68/bd93a203ee7f396392793f80e39171d06bc76795a0b8d6a7e0c14b2df1b0/spiral_sdk-0.16.80-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:c95b6904c52fea12f490c86bb304faa7d094e2c4799bf8727658064b32c5f99e", size = 81700548, upload-time = "2026-12-01T19:57:09.62Z" }, + { url = "https://files.pythonhosted.org/packages/4f/e9/fc70c16a510718d9291d4f5488b04906e66af201a169cfe282d7394374f9/spiral_sdk-0.16.80-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0e68cea27f8adecce96bde17e5360b0a5e3a78f8d223e739db7b438798666a4e", size = 92515194, upload-time = "2026-12-01T19:57:20.856Z" }, + { url = "https://files.pythonhosted.org/packages/76/6d/8a582e269c35854464bd99f64900e248ddafe6dbf23435f494229ddf34c0/spiral_sdk-0.16.80-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:283915dfbac6b30b9e9ec813c475713b23d1c4cbab893ae510c8d93ddf24d3fb", size = 94853432, upload-time = "2026-12-01T19:57:25.124Z" }, ] [[package]]