From 0c518d1c90d2d888a9739bc3babc29eaebbbe2d6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 04:29:09 -0800 Subject: [PATCH 01/25] build(deps): spiral-sdk 0.16.78, and table metadata in the fake (ITL-1495) spiral-sdk 0.16.78 adds KeyedTable.get_metadata and set_metadata. The fake models them as measured live (rule table-metadata), and a conformance test runs on the fake and, opt-in, live; the live conformance suite passes with 0.16.78. Co-Authored-By: Claude Opus 5.5 --- RELEASING.md | 4 +- .../2026-11-26-itl-1495-spiral-store-names.md | 36 ++++++++++++ pyproject.toml | 2 +- tests/test_databases/fake_spiral_sdk.py | 42 +++++++++++++- .../test_spiraldb_connector_integration.py | 56 +++++++++++++++++++ uv.lock | 12 ++-- 6 files changed, 142 insertions(+), 10 deletions(-) create mode 100644 docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md diff --git a/RELEASING.md b/RELEASING.md index 72aa1fd26..c66d0de9d 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -358,12 +358,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.78 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.78 scripts/migrate_spiral_schemas.py \ verify --project --dataset --plan plan.json ``` diff --git a/docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md b/docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md new file mode 100644 index 000000000..8ac9dc1d3 --- /dev/null +++ b/docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md @@ -0,0 +1,36 @@ +# ITL-1495: SpiralDB store, stages 0 and 1 + +Stages 0 and 1 of `docs/dev/specs/itl-1446-round2-spiral-sdk.md` (PR 588), approved by the +coordinator on the developer's behalf (decisions 1, 2, 3, 4 and 6). One pull request. + +## Stage 0: spiral-sdk 0.16.78 + +1. `pyproject.toml`: `spiral-sdk==0.16.78`; `uv lock --upgrade-package spiral-sdk`. The version + in `RELEASING.md`'s migration commands follows. +2. `tests/test_databases/fake_spiral_sdk.py`: `get_metadata` / `set_metadata` on the fake keyed + table, as measured live with 0.16.78 (rule `table-metadata`): an upsert, never a deletion, + not versioned, readable before any row, a key over 255 UTF-8 bytes, or an entry whose key + and value together are over 8,192 bytes, refused with `status 400` and nothing written. +3. Tests first: a conformance test of table metadata in + `tests/test_databases/test_spiraldb_connector_integration.py`, run on the fake always and + live opt-in, with fixed keys so a live table does not grow. The live conformance suite is + rerun with 0.16.78 (`itl-1186-switch.md` section 7: a bump reruns it). + +## Stage 1: store table names + +`src/orcapod/databases/spiral_store_names.py`, pure, imports no client: + +- `SPIRAL_TABLE_NAME_LABEL = "spiral_table_name_v1"`, beside `store_table_digest(path)`: SHA-256 + of the canonical JSON array of the full path components, bare hex (a hash in a name). +- `table_name_hint(path)`, `store_table_name(path)` (`o1__`), and + `store_table_name_prefix(prefix)`, the name prefix every table under a path prefix has. +- `store_table_metadata(path, data_context_key)`: the four entries of spec 2.2. +- `classify_store_table(metadata, path)`: this path's table, or an unmarked one (2.5); any other + path, format or a partial record raises `SpiralStoreTableCollisionError`. + +Then: the hash site inventory row in `docs/reference/hashing.md` ("in a name"); a golden group +`spiral_table_name` in `tests/test_hashing/golden/cases.py`, written by the generator into a new +file (the diff adds only that file and its history entry). Tests: determinism, the length bound, +the alphabet, prefix property of the hint, injectivity on adversarial paths, refusals. + +Nothing calls the module yet; no other hash, stored path or golden value moves. diff --git a/pyproject.toml b/pyproject.toml index ff983e388..c41454f9a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,7 +48,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.78", ] # 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/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 5b9e13d61..6f4e55a74 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 conformance tests passed live with spiral-sdk 0.16.78 on November +26, 2026 (ITL-1495). """ from __future__ import annotations @@ -71,8 +72,16 @@ "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 +_MAX_METADATA_ENTRY_BYTES = 8192 + _ROOT_ENV = "FAKE_SPIRAL_SDK_ROOT" _API_URL = "https://api.fake.invalid" @@ -351,6 +360,29 @@ 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 {} + return {k: bytes.fromhex(v) for k, v in json.loads(path.read_text()).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) + stored = self.metadata(table_id) + stored.update(entries) + (self.root / table_id / "metadata.json").write_text( + json.dumps({k: v.hex() for k, v in stored.items()}) + ) + def keys(self, table_id: str) -> pa.Schema: """Return a table's key schema.""" raw = (self.root / table_id / "keys.arrow").read_bytes() @@ -626,6 +658,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 diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index f256de2fa..8b4e98e6b 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -17,6 +17,7 @@ import datetime as dt import math import os +import uuid from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path @@ -315,3 +316,58 @@ def test_an_early_close(place: _Place) -> None: batches: Any = place.connector().scan_batches("units") assert next(batches).num_rows > 0 batches.close() + + +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 diff --git a/uv.lock b/uv.lock index 1eac880a4..fa670afbf 100644 --- a/uv.lock +++ b/uv.lock @@ -1961,8 +1961,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.78" }, + { name = "spiral-sdk", marker = "extra == 'spiraldb'", specifier = "==0.16.78" }, { 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" }, @@ -3294,16 +3294,16 @@ wheels = [ [[package]] name = "spiral-sdk" -version = "0.16.74" +version = "0.16.78" 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/75/c3/80e29ea91bc97ed13e87314b43a7780673dd9cef08683fb7b40a9ab85e8f/spiral_sdk-0.16.78-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:c311e5399c4c3e2e6cc1d9dc52dde9d2130a9cbbefb9c31734a82cd80532a4bf", size = 79354908, upload-time = "2026-11-25T16:33:03.323Z" }, + { url = "https://files.pythonhosted.org/packages/93/e3/e87291bff0b8dce545ab1aa0d7d96bb209f4886da20abf423a6e2049cd5a/spiral_sdk-0.16.78-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7b0c86ca9401fc3240ead2ef362c21d7a64c37bfd595762b8718786388870865", size = 88577354, upload-time = "2026-11-25T16:33:08.39Z" }, + { url = "https://files.pythonhosted.org/packages/93/eb/1b555e169a221a4e2a18cb243415b385b01935c02ac8f45da98b245b3670/spiral_sdk-0.16.78-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:88602ed50666e705e953ddceba379119465500d04d4bb4756f92179bc59175fa", size = 91210197, upload-time = "2026-11-25T16:33:13.945Z" }, ] [[package]] From bf8de9c3833c6bd75d7ecc09e6061b7a808d70ad Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 04:38:53 -0800 Subject: [PATCH 02/25] feat(databases): short SpiralDB store table names derived from the path (ITL-1495) A store table's SpiralDB name is o1__; its metadata records the path, layout, format and data context, and a table recording another path is refused. Pure module, not called yet. Hash site inventory row (in a name) and a new golden group, spiral_table_name; no other golden value moves. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1495.md | 3 + docs/reference/hashing.md | 1 + src/orcapod/contexts/data/v1.json | 7 +- src/orcapod/databases/spiral_store_names.py | 239 ++++++++++++++++++ src/orcapod/errors.py | 19 ++ tests/test_databases/fake_spiral_sdk.py | 7 +- .../test_databases/test_spiral_store_names.py | 180 +++++++++++++ tests/test_hashing/golden/cases.py | 55 +++- .../golden/data/v1/spiral_table_name-01.json | 12 + 9 files changed, 516 insertions(+), 7 deletions(-) create mode 100644 changelog.d/ITL-1495.md create mode 100644 src/orcapod/databases/spiral_store_names.py create mode 100644 tests/test_databases/test_spiral_store_names.py create mode 100644 tests/test_hashing/golden/data/v1/spiral_table_name-01.json diff --git a/changelog.d/ITL-1495.md b/changelog.d/ITL-1495.md new file mode 100644 index 000000000..d78b72627 --- /dev/null +++ b/changelog.d/ITL-1495.md @@ -0,0 +1,3 @@ +### Changed + +- The `spiraldb` extra pins `spiral-sdk==0.16.78` (was `0.16.74`), the release that reads and writes a SpiralDB table's metadata. Orcapod still only reads SpiralDB; the conformance tests pass on the service with it. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 6130f2dd5..91bc7fe36 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -330,6 +330,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | | SpiralDB 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 table name | a store table's full path components, canonical JSON | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`, not written into the name) | the end of the table's SpiralDB name `o1__` (a name; pinned in the `spiral_table_name` golden group) | `databases/spiral_store_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) | | unused code | Arrow tables | SHA-256, SHA3, BLAKE2b | no caller; removal is ITL-1156 | (not reached) `hashing/arrow_utils.py`, `hashing/arrow_serialization.py` | diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index 45a4cb9b9..117a98e9d 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -253,13 +253,14 @@ "digest": "373ad66e7e9cc3a411708a4470a30d2176aedf9c9ba1ecdbe1111359ceb25867" }, { - "date": "2026-11-23", + "date": "2026-11-26", "release": null, "added": { - "pipeline-02.json": "af19c4b5bafcd7428011db8bf5ddb125f8b59083b7c085613411eae36e9e23c2" + "pipeline-02.json": "af19c4b5bafcd7428011db8bf5ddb125f8b59083b7c085613411eae36e9e23c2", + "spiral_table_name-01.json": "23f16efb72cafe90692e1b19bc0cdb7aee694cb255e5685f7b7892fb3d2c80c9" }, "previous": "373ad66e7e9cc3a411708a4470a30d2176aedf9c9ba1ecdbe1111359ceb25867", - "digest": "57215540370eca6c81d5170c471e0d979482ee04235e47e4bfd05317936f2a27" + "digest": "9954784272f13773cec21434ccb441b064ab640707f556f556ed789c6d5a229f" } ], "provisional": { diff --git a/src/orcapod/databases/spiral_store_names.py b/src/orcapod/databases/spiral_store_names.py new file mode 100644 index 000000000..48a97c99a --- /dev/null +++ b/src/orcapod/databases/spiral_store_names.py @@ -0,0 +1,239 @@ +"""Names and metadata records of SpiralDB store tables (ITL-1495). + +A store table's full path (the store's base path plus the record path) is too long for a +SpiralDB table name, so a table gets a short name computed from the path alone, +``o1__``, and the full path is written into the table's metadata. A store +computes the name to find a table and never lists to find one; the metadata says which path +a table holds, and a table recording another path is refused. + +- ````: the SHA-256 of the UTF-8 canonical JSON array of the path components, as 64 + lower-case hex digits. It is a hash in a name, so it is bare: the label below names the + algorithm and is never written into the name, whose ``o1_`` grammar fixes it. +- ````: the components joined with ``/``, each character mapped to one character (a + lower-case ASCII letter or digit to itself, an upper-case ASCII letter to its lower case, + anything else to ``_``), cut to 96 characters. It is for people, and narrows a listing: + the hint of a path starts with the hint of each of its prefixes. Nothing parses a name. + +The specification is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (section 2). The module +is pure and imports no SpiralDB client. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import cast + +from orcapod.errors import SpiralStoreTableCollisionError + +SPIRAL_TABLE_NAME_LABEL = "spiral_table_name_v1" +"""The algorithm of ``store_table_digest``. A new algorithm is a new name grammar (``o2_``).""" + +STORE_TABLE_NAME_PREFIX = "o1_" +"""The start of every store table's name; it versions the name grammar.""" + +HINT_LENGTH = 96 +"""The most characters of a name's hint.""" + +STORE_FORMAT = "orcapod.spiral_store.v1" +"""The format of a store table, recorded in its metadata.""" + +MAX_PATH_JSON_BYTES = 8000 +"""The longest recorded path, in UTF-8 bytes of its JSON. SpiralDB refuses an entry whose key +and value together are over 8,192 bytes; this leaves room for the key.""" + +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 _path_json(path: Sequence[str]) -> bytes: + """Return the UTF-8 canonical JSON array of ``path``'s components. + + Raises: + ValueError: If the path is empty, a component is not a string, or a component + cannot be written as UTF-8. + """ + components = list(path) + if not components: + raise ValueError("a store table path has at least one component") + if not all(type(c) is str for c in components): + raise ValueError(f"a store table path holds strings only: {components!r}") + try: + return json.dumps( + components, ensure_ascii=False, separators=(",", ":") + ).encode() + except UnicodeEncodeError as exc: + raise ValueError(f"a store table path must be valid UTF-8: {exc}") from exc + + +def store_table_digest(path: Sequence[str]) -> str: + """Return the bare hex digest of ``path`` that ends its table's name. + + Algorithm ``SPIRAL_TABLE_NAME_LABEL``: SHA-256 of the UTF-8 canonical JSON array of the + components (no spaces, non-ASCII characters as they are). + + Args: + path: The full path components. + + Raises: + ValueError: If the path cannot be named (``_path_json``). + """ + return hashlib.sha256(_path_json(path)).hexdigest() + + +def _hint_of(text: str) -> str: + """Map each character of ``text`` to one name character, cut to ``HINT_LENGTH``.""" + return "".join( + c.lower() if c.isascii() and c.isalnum() else "_" for c in text[:HINT_LENGTH] + ) + + +def table_name_hint(path: Sequence[str]) -> str: + """Return the readable part of ``path``'s table name. + + Args: + path: The full path components. + """ + return _hint_of("/".join(path)) + + +def 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 (``_path_json``). + """ + digest = store_table_digest(path) + return f"{STORE_TABLE_NAME_PREFIX}{table_name_hint(path)}_{digest}" + + +def 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) + + +@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 cannot be named or recorded (``MAX_PATH_JSON_BYTES``), or + the data context key is empty. + """ + path_json = _path_json(path) + if len(path_json) > MAX_PATH_JSON_BYTES: + size = len(path_json) + raise ValueError( + f"a store table path is at most {MAX_PATH_JSON_BYTES} bytes as JSON, not {size}" + ) + if not data_context_key: + raise ValueError("a store table records the data context that created it") + return { + STORE_KEY: STORE_FORMAT.encode(), + PATH_KEY: path_json, + LAYOUT_KEY: path[-1].encode(), + DATA_CONTEXT_KEY: data_context_key.encode(), + } + + +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. + """ + present = [k for k in _RECORD_KEYS if k in metadata] + if not present: + 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 (UnicodeDecodeError, json.JSONDecodeError) as exc: + 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)) + 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 {'/'.join(record.path)!r}, not {'/'.join(path)!r}" + ) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 7720e7980..5faf3617b 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -596,6 +596,25 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: super().__init__(_in_table(f"table schema: {reason}", table)) +class SpiralStoreTableCollisionError(ValueError): + """A SpiralDB table under a store table's name is not that store table (ITL-1495). + + A store table's name is computed from its full path; its metadata records the path, + the store format and the layout. A table whose record names another path, another + format, or is incomplete or unreadable is refused: never read, written or adopted. + + 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 + super().__init__(_in_table(f"not this store's table: {reason}", table)) + + class SpiralDBWriteNotSupportedError(NotImplementedError): """Orcapod does not write SpiralDB through spiral-sdk yet (ITL-1186): it reads it. diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 6f4e55a74..bacb01cd6 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -362,11 +362,12 @@ def drop(self, table_id: str) -> None: def metadata(self, table_id: str) -> dict[str, bytes]: """Return a table's metadata (``table-metadata``).""" - self.by_id(table_id) + _ = self.by_id(table_id) path = self.root / table_id / "metadata.json" if not path.exists(): return {} - return {k: bytes.fromhex(v) for k, v in json.loads(path.read_text()).items()} + 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``).""" @@ -379,7 +380,7 @@ def set_metadata(self, table_id: str, entries: dict[str, bytes]) -> None: raise _status(400) stored = self.metadata(table_id) stored.update(entries) - (self.root / table_id / "metadata.json").write_text( + _ = (self.root / table_id / "metadata.json").write_text( json.dumps({k: v.hex() for k, v in stored.items()}) ) diff --git a/tests/test_databases/test_spiral_store_names.py b/tests/test_databases/test_spiral_store_names.py new file mode 100644 index 000000000..6b63a57f0 --- /dev/null +++ b/tests/test_databases/test_spiral_store_names.py @@ -0,0 +1,180 @@ +"""SpiralDB store table names and their metadata record (ITL-1495; spec ITL-1446 round 2).""" + +from __future__ import annotations + +import hashlib +import json +import random +import re + +import pytest + +from orcapod.databases import spiral_store_names as names +from orcapod.errors import SpiralStoreTableCollisionError + +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_v1") +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: + expected = hashlib.sha256( + json.dumps(list(RESULT), ensure_ascii=False, separators=(",", ":")).encode() + ).hexdigest() + assert names.store_table_digest(RESULT) == expected + assert names.store_table_name(RESULT).endswith("_" + expected) + + +def test_the_label_names_the_algorithm() -> None: + assert names.SPIRAL_TABLE_NAME_LABEL == "spiral_table_name_v1" + # A hash in a name is bare hex: the label is not written into the name. + assert names.SPIRAL_TABLE_NAME_LABEL not in names.store_table_name(RESULT) + + +@pytest.mark.parametrize("path", [RESULT, PIPELINE, ("a",), ("É" * 300, "x" * 500)]) +def test_a_name_is_short_and_plain(path: tuple[str, ...]) -> None: + name = names.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: + assert names.table_name_hint(("My-Fn", "v0", "schema:AB")) == "my_fn_v0_schema_ab" + # one character to one: each other character, the separator included, is one '_' + assert names.table_name_hint(("é", "a/b")) == "__a_b" + assert names.table_name_hint(("é", "z")) == "__z" + assert len(names.table_name_hint(("x" * 200,))) == 96 + + +def test_the_name_is_deterministic_and_depends_on_every_component_and_its_order() -> ( + None +): + assert names.store_table_name(RESULT) == names.store_table_name(list(RESULT)) + assert names.store_table_name(RESULT) != names.store_table_name(RESULT[::-1]) + for i in range(len(RESULT)): + changed = RESULT[:i] + (RESULT[i] + "x",) + RESULT[i + 1 :] + assert names.store_table_name(changed) != names.store_table_name(RESULT) + + +def test_components_are_kept_apart() -> None: + # 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.store_table_name(left) != names.store_table_name(right) + + +def test_no_two_of_many_adversarial_paths_share_a_name() -> None: + 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.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: + assert names.store_table_name(path).startswith( + names.store_table_name_prefix(prefix) + ) + + +def test_the_name_prefix_of_nothing_is_every_store_table() -> None: + assert names.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: + with pytest.raises(ValueError, match="path"): + _ = names.store_table_name(path) # pyright: ignore[reportArgumentType] # refused on purpose + + +def test_the_metadata_record() -> None: + record = names.store_table_metadata(PIPELINE, "std:v1:default") + assert record == { + "orcapod.store": b"orcapod.spiral_store.v1", + "orcapod.path": json.dumps( + list(PIPELINE), ensure_ascii=False, separators=(",", ":") + ).encode(), + "orcapod.layout": b"pdb_v1", + "orcapod.data_context": b"std:v1:default", + } + found = names.read_store_table_metadata(record) + assert found == names.StoreTableRecord(PIPELINE, "pdb_v1", "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: + longest = ("x" * (names.MAX_PATH_JSON_BYTES - 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="path"): + _ = names.store_table_metadata( + ("x" * names.MAX_PATH_JSON_BYTES,), "std:v1:default" + ) + + +def test_a_table_without_orcapod_metadata_is_unmarked() -> None: + 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.v2"}, + {"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: + record = {**names.store_table_metadata(PIPELINE, "std:v1:default"), **change} + with pytest.raises(SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +@pytest.mark.parametrize("missing", ["orcapod.store", "orcapod.path", "orcapod.layout"]) +def test_a_partial_record_is_refused(missing: str) -> None: + record = names.store_table_metadata(PIPELINE, "std:v1:default") + del record[missing] + with pytest.raises(SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +def test_a_table_of_another_path_under_the_name_is_refused() -> None: + found = names.read_store_table_metadata( + names.store_table_metadata(RESULT, "std:v1:default") + ) + assert found is not None + with pytest.raises(SpiralStoreTableCollisionError, match="rdb_v1"): + names.require_store_table_path(found, PIPELINE) diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index a43a4b2f3..bbf184f1e 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -45,7 +45,15 @@ CaseFn = Callable[[], dict[str, Any]] -GROUPS = ("semantic", "schema", "arrow", "datagram", "pipeline", "torch") +GROUPS = ( + "semantic", + "schema", + "arrow", + "datagram", + "pipeline", + "torch", + "spiral_table_name", +) OPTIONAL_GROUPS: dict[str, str] = {"torch": "torch"} """Groups that need an optional dependency, mapped to the module they need (ITL-871). @@ -3765,3 +3773,48 @@ def _group_key_identity(stream: Any, unsigned: Any) -> dict[str, Any]: # pyrigh if source_info is not None: out[f"row[{row}]._source_k"] = _jsonable(source_info) return out + + +# --------------------------------------------------------------------------- +# SpiralDB store table names (ITL-1495): a store finds its tables by these names, so +# the function from a full path to a name is pinned like any hash in a name. +# --------------------------------------------------------------------------- + +_HEX_A = "0123456789abcdef" * 4 +_HEX_B = "fedcba9876543210" * 4 +SPIRAL_STORE_PATHS: dict[str, tuple[str, ...]] = { + "function_result": ("my_fn", _HEX_A, "v0", "python.function.v1", "rev1", "rdb_v1"), + "function_pipeline": ( + "my_fn", + _HEX_A, + "v0", + "python.function.v1", + f"schema:{_HEX_B}", + "pdb_v1", + ), + "side_effect_log": ("side_effects", "Notify Pod", f"schema:{_HEX_B}", "tdb_v1"), + "operator_cache": ("job", "Join", f"node:{_HEX_A}", "odb_v1"), + "cached_source": ("prefix", "source", f"instance:{_HEX_B}", "sdb_v1"), + "base_path": ( + "team", + "store", + "my_fn", + _HEX_A, + "v1", + "python.function.v1", + "rev1", + "rdb_v1", + ), + "upper_case_and_punctuation": ("My-Fn.v2", "A B:C", "rdb_v1"), + "non_ascii": ("función", "数据", "rdb_v1"), + "long_component": ("f" * 150, _HEX_A, "rdb_v1"), + "one_component": ("x",), +} + + +@case("spiral_table_name", "name") +def spiral_table_names() -> dict[str, Any]: + """The SpiralDB name of a store table at each path of ``SPIRAL_STORE_PATHS``.""" + from orcapod.databases.spiral_store_names import store_table_name + + return {k: store_table_name(v) for k, v in SPIRAL_STORE_PATHS.items()} diff --git a/tests/test_hashing/golden/data/v1/spiral_table_name-01.json b/tests/test_hashing/golden/data/v1/spiral_table_name-01.json new file mode 100644 index 000000000..4f6655ee0 --- /dev/null +++ b/tests/test_hashing/golden/data/v1/spiral_table_name-01.json @@ -0,0 +1,12 @@ +{ + "name.base_path": "o1_team_store_my_fn_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef_v1_python_func_bee6bbfd36fdbbfadf1784e82d8d6b86faae6aa57083c098cc7360d3335039b8", + "name.cached_source": "o1_prefix_source_instance_fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210_sdb_v1_58d2b3f0e808ded584aa4ea9d4db1099707c106abba232de5918a1b5dd1b01d8", + "name.function_pipeline": "o1_my_fn_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef_v0_python_function_v1_sch_98d66fffb3de7da52b52123a8147d5141f7301525e9051de885e6dd0f100fecb", + "name.function_result": "o1_my_fn_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef_v0_python_function_v1_rev_a04b0a8665db7770a82fe57e2293dcbdf07ed807b2c8a81687d91e18d3e71bbe", + "name.long_component": "o1_ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff_c985b5d8aaba35861b5d097c7b95a800a4ce1bc9c0778174170fa52812b4bc5b", + "name.non_ascii": "o1_funci_n____rdb_v1_4c0b0f48110dc57f910431847088e2e11d05b6bf2b26c3e8dfb8dd9dabf2c43b", + "name.one_component": "o1_x_cd65ea2c2ad99e94a85b1b6df72efef9cb2ed0ae933a60c32ce16317f7d7d6aa", + "name.operator_cache": "o1_job_join_node_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef_odb_v1_02fbf316b8379bfe96b2e58d443e0b1a7b63fe4839e56084c46a9fdc8eabb6a3", + "name.side_effect_log": "o1_side_effects_notify_pod_schema_fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210__f0427b81907d7562118de548cff33276360e0bad83979d078529661d832cef86", + "name.upper_case_and_punctuation": "o1_my_fn_v2_a_b_c_rdb_v1_03e85b03658f19d86fcedcd0e6824e3d009b06ff6eca86743d202e90295c96e9" +} From 2bf88ca0acd558c2ce22d2c4dd2b1f47668e4a1c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 04:47:37 -0800 Subject: [PATCH 03/25] fix(databases): review findings on store table names and the fake (ITL-1495) - The fake upserts table metadata atomically: two clients' keys are all kept, as measured live. - A store table record with an entry over SpiralDB's 8,192-byte limit is refused before any table is created. - A recorded path that no writer writes (a lone surrogate) is refused on read. - The collision message prints component lists. - The test no longer repeats the label literal. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiral_store_names.py | 22 ++++++++++- tests/test_databases/fake_spiral_sdk.py | 15 +++++--- .../test_databases/test_spiral_store_names.py | 31 +++++++++++++++- .../test_spiraldb_connector_integration.py | 37 +++++++++++++++++++ 4 files changed, 97 insertions(+), 8 deletions(-) diff --git a/src/orcapod/databases/spiral_store_names.py b/src/orcapod/databases/spiral_store_names.py index 48a97c99a..7861744a1 100644 --- a/src/orcapod/databases/spiral_store_names.py +++ b/src/orcapod/databases/spiral_store_names.py @@ -44,6 +44,10 @@ """The longest recorded path, in UTF-8 bytes of its JSON. SpiralDB refuses an entry whose key and value together are over 8,192 bytes; this leaves room for the key.""" +MAX_METADATA_ENTRY_BYTES = 8192 +"""The most UTF-8 bytes of a metadata entry's key and value together that SpiralDB accepts +(measured live with spiral-sdk 0.16.78).""" + STORE_KEY = "orcapod.store" PATH_KEY = "orcapod.path" LAYOUT_KEY = "orcapod.layout" @@ -168,12 +172,20 @@ def store_table_metadata( ) if not data_context_key: raise ValueError("a store table records the data context that created it") - return { + record = { STORE_KEY: STORE_FORMAT.encode(), PATH_KEY: path_json, LAYOUT_KEY: path[-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: @@ -214,6 +226,12 @@ def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord f"its path is not a list of names: {path!r}" ) components = tuple(cast("list[str]", items)) + try: + _ = _path_json(components) # what a writer refuses is refused on read too + 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}" @@ -235,5 +253,5 @@ def require_store_table_path(record: StoreTableRecord, path: Sequence[str]) -> N """ if record.path != tuple(path): raise SpiralStoreTableCollisionError( - f"it records path {'/'.join(record.path)!r}, not {'/'.join(path)!r}" + f"it records path {list(record.path)}, not {list(path)}" ) diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index bacb01cd6..7f6dbe6dd 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -16,6 +16,7 @@ import json import math import os +import threading import types import urllib.parse import uuid @@ -80,6 +81,9 @@ } _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" @@ -378,11 +382,12 @@ def set_metadata(self, table_id: str, entries: dict[str, bytes]) -> None: or size + len(value) > _MAX_METADATA_ENTRY_BYTES ): raise _status(400) - stored = self.metadata(table_id) - stored.update(entries) - _ = (self.root / table_id / "metadata.json").write_text( - json.dumps({k: v.hex() for k, v in stored.items()}) - ) + with _metadata_lock: # one upsert at a time: concurrent keys are all kept + stored = self.metadata(table_id) + stored.update(entries) + _ = (self.root / table_id / "metadata.json").write_text( + json.dumps({k: v.hex() for k, v in stored.items()}) + ) def keys(self, table_id: str) -> pa.Schema: """Return a table's key schema.""" diff --git a/tests/test_databases/test_spiral_store_names.py b/tests/test_databases/test_spiral_store_names.py index 6b63a57f0..6bd154594 100644 --- a/tests/test_databases/test_spiral_store_names.py +++ b/tests/test_databases/test_spiral_store_names.py @@ -27,7 +27,8 @@ def test_the_digest_is_sha256_of_the_canonical_json_of_the_components() -> None: def test_the_label_names_the_algorithm() -> None: - assert names.SPIRAL_TABLE_NAME_LABEL == "spiral_table_name_v1" + # The label is defined once, in the module (the hash label rule): not repeated here. + assert re.fullmatch(r"[a-z_]+_v[0-9]+", names.SPIRAL_TABLE_NAME_LABEL) # A hash in a name is bare hex: the label is not written into the name. assert names.SPIRAL_TABLE_NAME_LABEL not in names.store_table_name(RESULT) @@ -178,3 +179,31 @@ def test_a_table_of_another_path_under_the_name_is_refused() -> None: assert found is not None with pytest.raises(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. + 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. + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": b'["\\ud800","rdb_v1"]', + } + with pytest.raises(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. + 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(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) diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 8b4e98e6b..2c4a04b83 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -22,6 +22,7 @@ from dataclasses import dataclass from pathlib import Path from typing import Any +from unittest.mock import patch import pyarrow as pa import pytest @@ -371,3 +372,39 @@ def test_table_metadata(place: _Place) -> None: 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"} From 6646270a8a0315affaf14d9e11719fdbcd872530 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 05:03:19 -0800 Subject: [PATCH 04/25] feat(databases): the codec of a SpiralDB store table, on spiral-sdk (ITL-1497) Carried over from PR 545 and changed as measured live with spiral-sdk 0.16.78: the manifest is one record for the table's schema row (no chunks, digest or entry limit); timestamps of every unit and zone are written as they are; a null fixed-size list of structs is kept. Times stay integers (the service refuses a time outside one day). The fake refuses the empty name, '*' and times outside a day, as the service does, and the conformance tests run the codec through spiral-sdk on the fake and live. Co-Authored-By: Claude Opus 5.5 --- .../2026-11-26-itl-1497-spiral-store-codec.md | 43 + src/orcapod/databases/spiral_store.py | 1016 ++++++++++++ tests/test_databases/fake_spiral_sdk.py | 37 +- tests/test_databases/test_spiral_store.py | 1370 +++++++++++++++++ .../test_spiraldb_connector_integration.py | 132 ++ 5 files changed, 2596 insertions(+), 2 deletions(-) create mode 100644 docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.md create mode 100644 src/orcapod/databases/spiral_store.py create mode 100644 tests/test_databases/test_spiral_store.py diff --git a/docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.md b/docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.md new file mode 100644 index 000000000..5c4a7c063 --- /dev/null +++ b/docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.md @@ -0,0 +1,43 @@ +# ITL-1497: the codec of a SpiralDB store table, on spiral-sdk + +Stage 2 of `docs/dev/specs/itl-1446-round2-spiral-sdk.md` (PR 588), approved by the +coordinator on the developer's behalf (decision 4). It stacks on PR 589 (ITL-1495: spiral-sdk +0.16.78 and its fake). + +## What is carried over from PR 545 + +`src/orcapod/databases/spiral_store.py` and `tests/test_databases/test_spiral_store.py`, from +PR 545's branch, with these changes: + +- **The manifest is one record**, `manifest_bytes` / `read_manifest`, for the `schema` cell of + the table's row in the dataset's schema table (`__orcapod_schemas__`); that cell has no size + limit, so the chunks, the header, the digest and the 1,024-entry limit are gone. A table's + own metadata holds only its identity (`spiral_store_names`, PR 589). Writing the row is + stage 3. The format stays a draft (`orcapod.spiral_store.draft`, version 0) until stage 3 + fixes it as version 1. +- **Timestamps are written as they are**, not as integers. +- **A null fixed-size list of structs is kept**, no longer refused. +- Everything else is unchanged: names, types, nullability, refusals before anything is written, + reading by the manifest's stored names, no row order. + +## Measured live with spiral-sdk 0.16.78 (2026-11-26, throwaway tables) + +| 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 (`datetime.max` and `.min` included) | kept bit for bit: **written as they are** (pyspiral's service refused instants after 9999-12-30) | +| `time32` / `time64` within a day | kept; **outside one day: the whole write refused**, so times stay 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** (the refusal is lifted) | +| a null struct item inside a list | kept by the service; still refused by the codec, which does not yet carry a struct's validity (a later lift) | +| 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. Kept: `$`, `*` and `;` inside a name, control characters, case and Unicode normal forms apart, 1,024 characters. NUL is cut silently. The codec's escape rule covers every refusal and NUL, so it is unchanged | +| a write of no rows | publishes nothing; a key-only write is refused | + +The fake (`tests/test_databases/fake_spiral_sdk.py`) now refuses the empty name, `*` and times +outside a day as the service does. The conformance tests (`test_spiraldb_connector_integration.py`) +run the codec through spiral-sdk on the fake and live: the rows written are the rows read, and +each name or value the codec avoids is refused by the service. diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py new file mode 100644 index 000000000..aa95ff8bb --- /dev/null +++ b/src/orcapod/databases/spiral_store.py @@ -0,0 +1,1016 @@ +"""The codec of an Orcapod store table in SpiralDB (ITL-1446, ITL-1497). + +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. The design is +``docs/dev/specs/itl-1446-spiral-columns.md`` (PR 542, sections 3.1 to 3.3), as updated +for spiral-sdk by ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588, section 3); +what SpiralDB keeps was measured live with spiral-sdk 0.16.78 +(``docs/dev/plans/2026-11-26-itl-1497-spiral-store-codec.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 at creation and never changed + (``manifest_bytes``, ``read_manifest``): the record path, the kind, the logical + schema, and the stored names at every depth. It is kept in the table's row of the + dataset's schema table; the table's own metadata holds only its identity + (``spiral_store_names``). + +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 json +import re +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, cast + +import numpy as np +import pyarrow as pa + +from orcapod.databases.utils import identity_node +from orcapod.logical_types.canonical_form import ( + EXTENSION_METADATA_KEY, + EXTENSION_NAME_KEY, +) +from orcapod.utils import arrow_utils + +KEY_COLUMN = "__record_id" + +# ------------------------------------------------------------------------ errors + + +class SpiralStoreError(ValueError): + """A column, value, name or manifest the codec refuses. + + Attributes: + reason: What is wrong. + path: Where, from the column inwards: column name, struct field names and + ``"[]"`` for a list's items. Empty when the error is not about a column. + """ + + def __init__(self, reason: str) -> None: + self.reason = reason + self.path: tuple[str, ...] = () + super().__init__(reason) + + def __str__(self) -> str: + if not self.path: + return self.reason + where = repr(self.path[0]) + if len(self.path) > 1: + where += f" (at {list(self.path[1:])})" + return f"column {where}: {self.reason}" + + +class UnstorableInSpiralError(SpiralStoreError): + """Rows or a schema SpiralDB would not give back exactly. Nothing was written.""" + + +class StoredRowsError(SpiralStoreError): + """Rows read from SpiralDB are not what the manifest says was written.""" + + +class ManifestError(SpiralStoreError): + """A manifest cannot be read, 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), + Refusal("a duration", _REFUSED_LIVE, _types.is_duration), + Refusal("an interval", _REFUSED_LIVE, _types.is_interval), +) +"""Every refusal that new evidence or a decision may lift. A type that is in neither this +table nor ``_NATIVE``, and that ``_physical_type`` does not map, is refused too.""" + +_NATIVE: tuple[Callable[[pa.DataType], bool], ...] = ( + _types.is_boolean, + _types.is_integer, + _types.is_float16, + _types.is_float32, + _types.is_float64, + _types.is_decimal128, + _types.is_decimal256, + _types.is_date32, + _types.is_date64, + _types.is_null, + _types.is_large_string, + _types.is_large_binary, + _types.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 _without_identifier(field: pa.Field[Any]) -> dict[bytes, bytes]: + """The field's metadata without the two keys that hold a logical type identifier.""" + metadata = cast("dict[bytes, bytes]", dict(field.metadata or {})) + metadata.pop(EXTENSION_NAME_KEY, None) + metadata.pop(EXTENSION_METADATA_KEY, None) + return metadata + + +def _logical_field(field: pa.Field[Any]) -> pa.Field[Any]: + """Return a column in the form the manifest records. + + Types are in their large variants. A logical type, live or annotated, is its + storage type with its identifier as field metadata, the metadata key always + present. A logical type below the top of the column is refused. + """ + node = identity_node(field) + if not node.known: + raise UnstorableInSpiralError("its extension type cannot be identified") + arrow_type = field.type + if node.identifier is not None and EXTENSION_NAME_KEY not in (field.metadata or {}): + arrow_type = cast(Any, arrow_type).storage_type + _refuse_nested_identifier(arrow_type) + if _holds(arrow_type, _types.is_string_view) or _holds( + arrow_type, _types.is_binary_view + ): + raise VIEW.error() + metadata = _without_identifier(field) + if node.identifier is not None: + metadata[EXTENSION_NAME_KEY], metadata[EXTENSION_METADATA_KEY] = node.identifier + return pa.field( + field.name, + arrow_utils.normalize_to_large_types(arrow_type, keep_null=True), + field.nullable, + cast(Any, metadata or None), + ) + + +def _refuse_nested_identifier(arrow_type: Any) -> None: + """Refuse a logical type at or below ``arrow_type``, live or annotated.""" + if isinstance(arrow_type, pa.BaseExtensionType): + raise UnstorableInSpiralError("a logical type nested in another type") + for child in _children(arrow_type): + name = child.name # read also for a list's item, whose name must be text too + with _at(name if pa.types.is_struct(arrow_type) else "[]"): + if EXTENSION_NAME_KEY in (child.metadata or {}): + raise UnstorableInSpiralError("a logical type nested in another type") + _refuse_nested_identifier(child.type) + + +def _children(arrow_type: Any) -> list[pa.Field[Any]]: + """The child fields of a struct or a list; of other nested types, what they have.""" + return [arrow_type.field(i) for i in range(arrow_type.num_fields)] + + +def _holds(arrow_type: Any, matches: Callable[[pa.DataType], bool]) -> bool: + """Whether ``arrow_type`` is, or holds at any depth, a type that matches.""" + return matches(arrow_type) or any( + _holds(child.type, matches) for child in _children(arrow_type) + ) + + +def _holds_metadata(arrow_type: Any) -> bool: + """Whether a field below ``arrow_type``, at any depth, has metadata.""" + return any(f.metadata or _holds_metadata(f.type) for f in _children(arrow_type)) + + +def _stored_names(names: list[str]) -> list[str]: + """Return the stored names of siblings: columns, or the fields of one struct. + + SpiralDB folds neither case nor Unicode normal forms (measured live), so names that + differ are different. + """ + stored: list[str] = [] + for name in names: + with _at(name): + stored.append(encode_name(name)) + if len(set(stored)) != len(stored): + repeated = sorted({n for n in names if names.count(n) > 1}) + raise UnstorableInSpiralError(f"names used more than once: {repeated}") + return stored + + +def _stored_columns(names: list[str]) -> list[str]: + """The stored names of a table's columns: the key column keeps its own. + + No encoded name starts with ``__``, so none is the key column's. + """ + stored = iter(_stored_names([n for n in names if n != KEY_COLUMN])) + return [n if n == KEY_COLUMN else next(stored) for n in names] + + +def logical_schema(schema: pa.Schema) -> pa.Schema: + """Return ``schema`` in the form the manifest records, or refuse it. + + Args: + schema: The schema of rows to be stored, ``__record_id`` included. + + Returns: + The schema with every type in its large variant and every logical type as its + storage type with its identifier as field metadata. Names, column order, + nullability and metadata are kept at every depth. + + Raises: + UnstorableInSpiralError: If a column cannot be stored exactly, naming it, or if + the table has no single key column, no value column, a repeated name or a + name that is not UTF-8. + """ + try: + return _logical_schema(schema) + except UnicodeDecodeError as exc: + # pyarrow holds a name of any bytes, and fails where it is read as text. + raise UnstorableInSpiralError(f"a name is not UTF-8 text ({exc})") from exc + + +def _logical_schema(schema: pa.Schema) -> pa.Schema: + """``logical_schema``, for names that can be read.""" + fields: list[pa.Field[Any]] = [] + for field in schema: + with _at(field.name): + logical = _logical_field(field) + _ = _physical_type(logical.type) + if field.name == KEY_COLUMN and ( + logical.type != pa.large_binary() + or EXTENSION_NAME_KEY in (logical.metadata or {}) + ): + raise UnstorableInSpiralError("the key column must be binary") + fields.append(logical) + _ = _stored_columns(schema.names) + if schema.names.count(KEY_COLUMN) != 1: + raise UnstorableInSpiralError(f"not exactly one key column {KEY_COLUMN!r}") + if len(fields) < 2: + raise UnstorableInSpiralError("no column beside the key column") + return pa.schema(fields, metadata=cast(Any, schema.metadata)) + + +def _is_list(arrow_type: pa.DataType) -> bool: + """Whether ``arrow_type`` is a variable-size list of either width.""" + return pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type) + + +def _physical_type(arrow_type: pa.DataType) -> pa.DataType: + """Return the type a logical type (``_logical_field``) is written as, or refuse it. + + The one traversal of a type: struct fields and the items of every list kind, to any + depth. A logical type's storage is traversed as any other type. Struct fields get + encoded names; sibling names must differ. A struct is never null (``_encode``). + """ + t = pa.types + logical: Any = arrow_type + if t.is_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") + 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 + difference = schema_difference(manifest.schema, target) + if difference is not None or target.names != manifest.schema.names: + raise ManifestError(f"not the recorded schema: {difference or 'column order'}") + require_stored_schema(rows.schema, manifest) + columns: list[Any] = [] + for out, field, physical in zip(target, manifest.schema, manifest.physical): + with _at(field.name): + column = rows.column(physical.name) + if field.name == KEY_COLUMN and column.null_count: + raise StoredRowsError("a null key") + chunks = [_decode(c, field, physical) for c in column.chunks] + live = isinstance(out.type, pa.BaseExtensionType) + storage: Any = out.type.storage_type if live else out.type + if storage != field.type: + chunks = [c.cast(storage) for c in chunks] + if live: + chunks = [ + pa.ExtensionArray.from_storage(cast(Any, out.type), c) + for c in chunks + ] + columns.append(cast(Any, pa.chunked_array)(chunks, type=out.type)) + return pa.Table.from_arrays(columns, schema=target) + + +def empty_rows(manifest: StoreManifest) -> pa.Table: + """Return zero rows of the recorded schema. + + What a table with a manifest and no value columns reads as (a crash before its first + rows). Such a table is never scanned: the service refuses a key-only scan. + + Args: + manifest: The table's manifest. + + Returns: + A table with no rows. + """ + return manifest.schema.empty_table() + + +def _decode(array: Any, field: pa.Field[Any], physical: pa.Field[Any]) -> Any: + """Return stored values of ``physical`` as the logical values of ``field``.""" + logical: Any = field.type + stored: Any = physical.type + t = pa.types + restored: Any + if t.is_struct(logical): + if array.null_count: + raise StoredRowsError("a null struct, which Orcapod never writes") + names = [f.name for f in _children(array.type)] + children: list[Any] = [] + for child, child_stored in zip(_children(logical), _children(stored)): + with _at(child.name): + values = array.field(names.index(child_stored.name)) + children.append(_decode(values, child, child_stored)) + restored = pa.StructArray.from_arrays(children, fields=_children(logical)) + elif _is_list(logical): + with _at("[]"): + items = _decode(array.flatten(), logical.value_field, stored.value_field) + restored = _large_list(array, items, logical) + elif t.is_fixed_size_list(logical): + with _at("[]"): + items = _decode(array.flatten(), logical.value_field, stored.value_field) + restored = _fixed_size_list(array, items, logical) + elif t.is_map(logical): + with _at("[]"): + rows = _map_rows(array) + keys = array.keys.take(rows) + keys = _decode(keys, logical.key_field, stored.key_field) + items = array.items.take(rows) + items = _decode(items, logical.item_field, stored.item_field) + restored = _map(array, keys, items, logical) + else: + restored = array.cast(stored) + if t.is_time(logical): + restored = restored.view(logical) # the same integers + elif restored.type != logical: + restored = restored.cast(logical) # a decimal32 or decimal64 + if not field.nullable and restored.null_count: + raise StoredRowsError("a null in a non-nullable field") + return restored + + +# ---------------------------------------------------------------------- the manifest + +# A draft: no table may be written with it outside tests. The persisted format is fixed +# with the creation rules (stage 3 of the design), as version 1. +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 a path component is + not UTF-8 or holds ``/`` or NUL. + """ + for part in record_path: + _require_utf8(part) + if "/" in part or "\0" in part: + raise UnstorableInSpiralError(f"the path component {part!r}") + _require_utf8(kind) + return StoreManifest( + record_path, kind, logical_schema(schema), physical_schema(schema) + ) + + +def manifest_bytes(manifest: StoreManifest) -> bytes: + """Return the bytes that record ``manifest``. + + They are the ``schema`` cell of the table's row in its dataset's schema table + (``__orcapod_schemas__``), whose cells have no size limit; the row's ``format`` says + they are a store manifest. Equal manifests give equal 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(recorded: bytes, record_path: tuple[str, ...]) -> StoreManifest: + """Return the manifest ``manifest_bytes`` recorded. + + Args: + recorded: The bytes, as read from the table's row. + 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") + if tuple(cast("list[str]", path)) != record_path: + raise ManifestError( + f"the table is recorded as {path}, not as {list(record_path)}" + ) + schema = _map_metadata(_schema_of(fields.get("schema")), _unmark) + physical = _schema_of(fields.get("physical")) + try: + usable = logical_schema(schema) + expected = physical_schema(schema) + except UnstorableInSpiralError as exc: + raise ManifestError( + f"the recorded schema is not a store schema: {exc}" + ) from exc + # The stored names are read from the manifest, never recomputed; its shape and types + # must be the ones the logical schema is kept in. + if _without_names(physical) != _without_names(expected) or ( + usable.names.index(KEY_COLUMN) != physical.get_field_index(KEY_COLUMN) + ): + raise ManifestError("the recorded stored schema is not the logical one's") + _require_distinct(physical) + return StoreManifest(record_path, kind, usable, physical) + + +def _without_names(fields: Any) -> list[object]: + """The types of fields at every depth, without names.""" + shape: list[object] = [] + for field in fields: + arrow_type = field.type + inner = _children(arrow_type) + size = getattr(arrow_type, "list_size", None) + shape.append( + (arrow_type.id, size, _without_names(inner)) if inner else arrow_type + ) + return shape + + +def _require_distinct(fields: Any) -> None: + """Refuse a recorded stored schema with two siblings of one name.""" + names = [field.name for field in fields] + if len(set(names)) != len(names): + raise ManifestError("the recorded stored schema repeats a name") + for field in fields: + _require_distinct(_children(field.type)) + + +def _mark(key: bytes) -> bytes: + """The form a field metadata key is recorded in.""" + return _MARKED + key if key.startswith((_MARKED, _EXTENSION_KEYS)) else key + + +def _unmark(key: bytes) -> bytes: + """The inverse of ``_mark``.""" + return key.removeprefix(_MARKED) + + +def _map_metadata(schema: pa.Schema, change: Any) -> pa.Schema: + """Return ``schema`` with every field metadata key, at every depth, changed.""" + return pa.schema( + [_map_field(field, change) for field in schema], + metadata=cast(Any, schema.metadata), + ) + + +def _map_field(field: pa.Field[Any], change: Any) -> pa.Field[Any]: + """``_map_metadata`` for one field. A map has no metadata inside.""" + arrow_type: Any = field.type + if pa.types.is_struct(arrow_type): + arrow_type = pa.struct([_map_field(f, change) for f in _children(arrow_type)]) + elif pa.types.is_large_list(arrow_type): + arrow_type = pa.large_list(_map_field(arrow_type.value_field, change)) + elif pa.types.is_fixed_size_list(arrow_type): + arrow_type = pa.list_( + _map_field(arrow_type.value_field, change), arrow_type.list_size + ) + metadata = {change(k): v for k, v in (field.metadata or {}).items()} + return pa.field(field.name, arrow_type, field.nullable, cast(Any, metadata or None)) + + +# ------------------------------------------------- comparing a schema with a manifest's + + +def schema_difference(recorded: pa.Schema, other: pa.Schema) -> str | None: + """Return how a schema differs from a recorded one, or ``None`` when it is the same. + + Compared as decoded, never as bytes: the schema metadata, and each column by name, + with its type, nullability and metadata, field by field at every depth. The order of + columns and of metadata entries does not count: one pipeline's table may be written + with its columns in another order. + + Args: + recorded: A manifest's schema. + other: Another one, in any form ``logical_schema`` takes. + + Returns: + The first difference, in words. + + Raises: + UnstorableInSpiralError: If a schema cannot be stored. + """ + left, right = logical_schema(recorded), logical_schema(other) + if dict(left.metadata or {}) != dict(right.metadata or {}): + return "the schema metadata differs" + if set(left.names) != set(right.names): + return f"columns {sorted(left.names)} and {sorted(right.names)}" + for field in left: + difference = _field_difference(field, right.field(field.name), repr(field.name)) + if difference is not None: + return difference + return None + + +def _field_difference(a: pa.Field[Any], b: pa.Field[Any], where: str) -> str | None: + """How two fields differ. Arrow's own equality ignores nested names.""" + for what, x, y in ( + ("name", a.name, b.name), + ("nullable", a.nullable, b.nullable), + ("metadata", dict(a.metadata or {}), dict(b.metadata or {})), + ("type", a.type.id, b.type.id), + ("number of fields", a.type.num_fields, b.type.num_fields), + ): + if x != y: + shown = (a.type, b.type) if what == "type" else (x, y) + return f"{where}: {what} {shown[0]} and {shown[1]}" + if not a.type.num_fields: + return None if a.type == b.type else f"{where}: type {a.type} and {b.type}" + for what in ("list_size", "keys_sorted"): + x, y = (getattr(f.type, what, None) for f in (a, b)) + if x != y: + return f"{where}: {what} {x} and {y}" + struct = pa.types.is_struct(a.type) + for x, y in zip(_children(a.type), _children(b.type)): + inner = f"{where}.{x.name}" if struct else f"{where}[]" + difference = _field_difference(x, y, inner) + if difference is not None: + return difference + return None diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 7f6dbe6dd..7c2ab6d57 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -61,7 +61,10 @@ "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", + "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", "type-conflict": "a column of another type than stored is refused", "unsupported": "duration, interval, fixed-size binary, union, an empty struct and a " @@ -207,11 +210,36 @@ 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 _time_outside_a_day(array: Any) -> bool: + """Whether a time value outside one day is in ``array``, at any depth (``time-of-day``).""" + if isinstance(array, pa.ExtensionArray): + array = array.storage + 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``. @@ -443,6 +471,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 diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py new file mode 100644 index 000000000..683915adf --- /dev/null +++ b/tests/test_databases/test_spiral_store.py @@ -0,0 +1,1370 @@ +"""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 pathlib import Path +from typing import Any, cast + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.databases import spiral_store as store +from orcapod.logical_types.canonical_form import declaration_form_schema +from orcapod.utils.arrow_utils import normalize_to_large_types +from tests.test_databases.type_matrix import ( + ROWS, + Row, + build_table, + field_difference, +) +from tests.test_databases.type_matrix import ( + _same_values as same_values, # pyright: ignore[reportPrivateUsage] +) + +KEY = store.KEY_COLUMN +NAME_KEY, METADATA_KEY = b"ARROW:extension:name", b"ARROW:extension:metadata" + +chunked: Any = pa.chunked_array # the stubs type ``type=`` as None +map_of: Any = pa.map_ # the stubs lack fields and keys_sorted +schema_of: Any = pa.schema # the stubs take no mix of fields and pairs +# The stubs take literal units and zones only. +timestamp: Any = pa.timestamp +duration: Any = pa.duration + + +# ------------------------------------------------------------------------- helpers + + +def ids(n: int) -> Any: + return pa.array([f"r{i:04d}".encode() for i in range(n)], pa.large_binary()) + + +def keyed(columns: dict[str, Any], fields: list[Any] | None = None) -> pa.Table: + """A table of ``columns`` (arrays) with a key column in the middle.""" + n = len(next(iter(columns.values()))) + fields = fields or [pa.field(k, v.type) for k, v in columns.items()] + half = len(fields) // 2 + fields = [*fields[:half], pa.field(KEY, pa.large_binary(), False), *fields[half:]] + arrays = [ids(n) if f.name == KEY else columns[f.name] for f in fields] + return pa.Table.from_arrays(arrays, schema=schema_of(fields)) + + +def _returned(array: Any, small: bool) -> Any: + """One array as SpiralDB may give it back.""" + t = pa.types + if t.is_struct(array.type): + assert array.null_count == 0 + order = sorted( + range(array.type.num_fields), key=lambda i: array.type.field(i).name + ) + children = [_returned(array.field(i), small) for i in order] + names = [array.type.field(i).name for i in order] + return pa.StructArray.from_arrays( + children, fields=[pa.field(n, c.type) for n, c in zip(names, children)] + ) + mask = array.is_null() if array.null_count else None + if t.is_large_list(array.type): + items = _returned(array.flatten(), small) + offsets = array.offsets + offsets = pa.array(offsets.to_numpy() - offsets.to_numpy()[0], pa.int64()) + target = (pa.list_ if small else pa.large_list)(pa.field("element", items.type)) + cls: Any = pa.ListArray if small else pa.LargeListArray + return cls.from_arrays( + offsets.cast(pa.int32() if small else pa.int64()), + items, + type=target, + mask=mask, + ) + if small and t.is_large_string(array.type): + return array.cast(pa.string()) + if small and t.is_large_binary(array.type): + return array.cast(pa.binary()) + return array + + +def as_spiral_returns(rows: pa.Table, seed: int = 0, small: bool = False) -> pa.Table: + """Encoded rows as a scan gives them: a set of rows, columns sorted by name.""" + rng = random.Random(seed) + order = list(range(rows.num_rows)) + rng.shuffle(order) + columns: dict[str, Any] = {} + for name in sorted(rows.column_names): + whole = rows.column(name).combine_chunks().take(pa.array(order, pa.int64())) + cut = rng.randint(0, len(whole)) + pieces = [_returned(p, small) for p in (whole[:cut], whole[cut:])] + columns[name] = chunked(pieces, type=pieces[0].type) + return pa.table(columns) + + +def by_id(rows: pa.Table) -> pa.Table: + """Rows sorted by key: a store is a set of rows.""" + keys = rows.column(KEY).to_pylist() + return rows.take( + pa.array(sorted(range(len(keys)), key=lambda i: keys[i]), pa.int64()) + ) + + +PATH = ("run", "fn", "pdb_v1") + + +def new(schema: pa.Schema, path: tuple[str, ...] = PATH) -> store.StoreManifest: + return store.new_manifest(path, "function_pipeline", schema) + + +def entries(schema: pa.Schema, path: tuple[str, ...] = PATH) -> 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: + return store.read_manifest(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: + return normalize_to_large_types(arrow_type, keep_null=True) + + +def large(schema: pa.Schema) -> pa.Schema: + return schema_of( + [f.with_type(normalize_to_large_types(f.type, keep_null=True)) for f in schema], + metadata=cast(Any, schema.metadata), + ) + + +def assert_same(got: pa.Table, expected: pa.Table) -> None: + """Schema exactly (every depth); values bit for bit, as sets of rows.""" + assert got.schema.names == expected.schema.names + assert got.schema.metadata == expected.schema.metadata + for a, b in zip(expected.schema, got.schema): + assert field_difference(a, b, a.name) is None + got, expected = by_id(got), by_id(expected) + for name in expected.column_names: + left, right = got.column(name), expected.column(name) + assert same_values(left.combine_chunks(), right.combine_chunks()), name + got.validate() + + +def round_trip(rows: pa.Table, *, live: bool = False) -> pa.Table: + """Write, return as SpiralDB does, and restore through the manifest: every slice, + both variants.""" + expected_schema = large(rows.schema) + manifest = read(entries(rows.schema)) + schema = manifest.schema + if live: + converter = get_default_context().type_converter + schema = declaration_form_schema(schema, converter) + else: + expected_schema = store.logical_schema(rows.schema) + result = None + assert rows.num_rows + for piece in (rows, rows.slice(1), rows.slice(0, 1)): + if not piece.num_rows: + continue + encoded = store.encode_rows(piece) + assert encoded.schema.equals( + store.physical_schema(rows.schema), check_metadata=True + ) + _assert_physical(encoded.schema) + encoded.validate() # full: pyarrow refuses a date64 off midnight + for seed, small in ((1, False), (2, True)): + got = store.decode_rows( + as_spiral_returns(encoded, seed, small), manifest, schema + ) + want = pa.Table.from_arrays( + [ + chunked([_as_target(c, f) for c in col.chunks], type=f.type) + for col, f in zip(piece.columns, expected_schema) + ], + schema=expected_schema, + ) + assert_same(got, want) + result = result or got + assert result is not None + return result + + +def _as_target(chunk: Any, field: Any) -> Any: + """What was written, under the expected field (its storage, its large variants).""" + if chunk.type == field.type: + return chunk + if isinstance(chunk, pa.ExtensionArray): + chunk = chunk.storage + return chunk if chunk.type == field.type else chunk.cast(field.type) + + +def _assert_physical(schema: pa.Schema) -> None: + """SpiralDB's known rules on names and types, at every depth.""" + + def walk(field: Any, named: bool, in_map: bool = False) -> None: + assert (field.nullable or in_map) and not field.metadata + if named and field.name != KEY: + assert field.name and not field.name.startswith(("__", "$")) + assert not set(field.name) & set(".$*\0") + t = field.type + assert not ( + pa.types.is_fixed_size_binary(t) + or pa.types.is_duration(t) + or 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: + with pytest.raises(store.UnstorableInSpiralError) as info: + store.encode_rows(rows) + for word in words: + assert word in str(info.value) + return info.value + + +# --------------------------------------------------------------------------- names + + +@pytest.mark.parametrize( + ("name", "stored"), + [ + ("x", "x"), + ("_source_x", "_source_x"), + ("_tag_source_id::ab", "_tag_source_id::ab"), + ("a;b", "a;b"), + ("é", "é"), + ("a b", "a b"), + ("__data_context", "ox___data_context"), + ("a.b", "ox_a;2Eb"), + ("a;2Eb", "a;2Eb"), + ("ox_a;2Eb", "ox_ox_a;3B2Eb"), + ("ox_", "ox_ox_"), + ("", "ox_"), + ("$a*\x00\x7f\n", "ox_;24a;2A;00;7F;0A"), + ], +) +def test_the_names_of_the_design(name: str, stored: str) -> None: + assert store.encode_name(name) == stored + assert decoded(stored) == name + + +def decoded(stored: str) -> str: + """The inverse of ``encode_name``, which only the tests need.""" + if not stored.startswith("ox_"): + return stored + return re.sub(";([0-9A-F]{2})", lambda m: chr(int(m[1], 16)), stored[3:]) + + +def adversarial_names(count: int) -> set[str]: + rng = random.Random(1446) + pieces = ( + ["_", "__", "ox_", "ox", ".", ";", ";2E", ";3B", ";2e", ";G", "$", "*", "%2E"] + + ["a", "B", "é", "é", "::", " ", "\n", "\x00", "\x7f", "\x80", "{", '"'] + + ["x_", "o", "\U0001f600", "
", "2E", "3B"] + ) + names = {"", KEY, "ox_", "a.b", "a;2Eb", "ox_a;2Eb", "ox_order", "Å", "Å"} + names |= {chr(i) for i in range(0x300)} | {f"a{chr(i)}b" for i in range(0x300)} + while len(names) < count: + names.add("".join(rng.choices(pieces, k=rng.randint(0, 8)))) + return names + + +def test_names_round_trip_and_are_injective() -> None: + names = adversarial_names(210_000) + assert len(names) >= 200_000 + encoded = {name: store.encode_name(name) for name in names} + assert len(set(encoded.values())) == len(names) + for name, stored in encoded.items(): + assert decoded(stored) == name + assert stored and not stored.startswith("__") + assert not any(c in ".$*\x7f" or ord(c) < 32 for c in stored) + + +def test_an_already_stored_name_is_itself_encoded_injectively() -> None: + names = sorted(adversarial_names(5_000)) + once = [store.encode_name(n) for n in names] + twice = [store.encode_name(n) for n in once] + assert len(set(twice)) == len(names) + assert [decoded(decoded(t)) for t in twice] == names + + +@pytest.mark.parametrize( + "names", [["a.b", "a;2Eb", "ox_a;2Eb", "__a"], ["", "ox_", "$"]] +) +@pytest.mark.parametrize("depth", [0, 1, 2, 3]) +def test_names_in_rows_at_every_depth(names: list[str], depth: int) -> None: + for order in (names, list(reversed(names))): + columns = {n: pa.array([i, i + 1], pa.int64()) for i, n in enumerate(order)} + arrays, fields = ( + list(columns.values()), + [pa.field(n, pa.int64()) for n in order], + ) + for level in range(depth): + inner = pa.StructArray.from_arrays(arrays, fields=fields) + if level % 2: + inner = pa.LargeListArray.from_arrays( + pa.array([0, 1, 2], pa.int64()), inner + ) + arrays = [inner, pa.array([5, 6])] + fields = [pa.field("s.t", inner.type), pa.field("__z", pa.int64())] + _ = round_trip(keyed({f.name: a for f, a in zip(fields, arrays)}, fields)) + + +@pytest.mark.parametrize("nested", [False, True]) +def test_a_stored_name_never_matches_a_logical_name(nested: bool) -> None: + """``E("a.b")`` is ``ox_a;2Eb``, which is also another column's own name.""" + values = {"a.b": 1, "ox_a;2Eb": 2, "__record": 3, "ox___record": 4} + for order in (list(values), list(reversed(values))): + if nested: + ty = pa.struct([(n, pa.int64()) for n in order]) + table = keyed({"s": pa.array([values], ty)}) + assert round_trip(table).column("s").to_pylist() == [values] + else: + got = round_trip(keyed({n: pa.array([values[n]]) for n in order})) + assert {n: got.column(n)[0].as_py() for n in values} == values + + +def test_the_key_is_not_a_value_column_of_the_same_name() -> None: + inner = pa.array([{KEY: 7}], pa.struct([(KEY, pa.int64())])) + table = keyed({"ox_" + KEY: pa.array([1]), "s": inner}) + got = round_trip(table) + assert got.column(KEY).to_pylist() == ids(1).to_pylist() + assert got.column("ox_" + KEY).to_pylist() == [1] + encoded = store.encode_rows(table) + renamed = encoded.rename_columns( + ["ox_" + KEY if n == KEY else n for n in encoded.column_names] + ) + with pytest.raises(store.StoredRowsError, match="missing"): + decode(renamed, table.schema) + + +@pytest.mark.parametrize("name", ["\ud800", "a\udfff", "__\ud800.b"]) +def test_a_lone_surrogate_is_refused(name: str) -> None: + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + store.encode_name(name) + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + new(schema_of([("a", pa.int8()), (KEY, pa.large_binary())]), (name,)) + + +def test_a_name_that_is_not_utf8_is_refused_at_every_depth() -> None: + bad: Any = pa.field(cast(Any, b"a\xff"), pa.int8()) + for field in ( + bad, + pa.field("s", pa.struct([bad])), + pa.field("l", pa.list_(pa.struct([bad]))), + pa.field("i", pa.list_(bad)), + ): + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + store.logical_schema(schema_of([field, (KEY, pa.large_binary())])) + + +def wrappings(inner: Any) -> list[Any]: + """``inner`` alone, below each kind of nesting, and as a logical type's storage.""" + return [ + inner, + pa.list_(inner), + pa.struct([("s", pa.large_list(inner))]), + Labelled(inner, "test.storage", b""), + Labelled(pa.large_list(inner), "test.storage", b""), + ] + + +def test_duplicate_sibling_names_are_refused_at_every_depth() -> None: + twice = pa.struct([("a.b", pa.int8()), ("c", pa.int8()), ("a.b", pa.int8())]) + for ty in wrappings(twice): + with pytest.raises(store.UnstorableInSpiralError, match="more than once"): + store.logical_schema(schema_of([("x", ty), (KEY, pa.large_binary())])) + same_in_two_structs = pa.struct([("a", pa.struct([("a", pa.int8())]))]) + _ = store.logical_schema( + schema_of([("a", same_in_two_structs), (KEY, pa.large_binary())]) + ) + + +def test_names_that_differ_only_in_case_or_normal_form_are_kept_apart() -> None: + """The service folds neither (measured live).""" + names = ["A", "a", "a.B", "a.b", "__A", "__a", "\u00e9", "e\u0301", "a.\u00e9"] + for order in (names, list(reversed(names))): + inner = pa.array( + [{n: i for i, n in enumerate(order)}], + pa.struct([(n, pa.int8()) for n in order]), + ) + columns = {n: pa.array([i]) for i, n in enumerate(order)} + _ = round_trip(keyed({**columns, "s": inner})) + + +@pytest.mark.parametrize("as_storage", [False, True]) +def test_a_struct_parent_must_be_valid_also_in_a_logical_types_storage( + as_storage: bool, +) -> None: + struct = pa.struct([pa.field("a.b", pa.int8(), False)]) + for ty, value in ((struct, None), (pa.large_list(struct), [{"a.b": 1}, None])): + array = pa.array([value], ty) + if as_storage: + live = Labelled(ty, "test.parent", b"") + array = pa.ExtensionArray.from_storage(live, array) + refused(keyed({"c": array}), "'c'", "null struct") + + +# --------------------------------------------------------------------------- types + +REFUSED_ROWS = { + "struct<> (no fields)": "no fields", + "fixed_size_binary[4]": "fixed-size binary", + "uuid (Arrow's canonical extension type)": "fixed-size binary", + "map, keys sorted": "named key and value", + "map (item metadata)": "metadata inside a map", + "map (key metadata)": "metadata inside a map", + "map> (metadata inside the item)": "metadata inside a map", + **{r.label: "duration" for r in ROWS if r.label.startswith("duration")}, +} +# The matrix's second column holds a null row. +NULL_STRUCT_ROWS = { + "struct", + "struct[2]>", + "struct", + "user class, exact (dataclass)", + "user class, structural (orcapod.dataclass)", +} + + +def test_the_expectations_name_rows_of_the_matrix() -> None: + assert set(REFUSED_ROWS) | NULL_STRUCT_ROWS <= {r.label for r in ROWS} + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize("row", ROWS, ids=lambda r: r.label) +def test_every_row_of_the_type_matrix_is_kept_or_refused( + row: Row, tmp_path: Path +) -> None: + """Two columns of each type (the second nullable, with a null), both forms of a + logical type, and the column naming its refusal.""" + if row.label.startswith("torch"): + _ = pytest.importorskip("torch") + rows = build_table(row, tmp_path).rename_columns([KEY, "x", "y"]) + if row.label in REFUSED_ROWS: + refused(rows, REFUSED_ROWS[row.label], "'x'") + return + if row.label in NULL_STRUCT_ROWS: + refused(rows, "null struct", "'y'") + rows = rows.drop_columns(["y"]) + _ = round_trip(rows) + _ = round_trip(rows, live=True) + + +def scalar_cases() -> list[tuple[str, pa.DataType, list[Any]]]: + D = decimal.Decimal + return [ + ("int8", pa.int8(), [-128, 127, 0]), + ("uint64", pa.uint64(), [0, 2**64 - 1, 2**63]), + ("int64", pa.int64(), [-(2**63), 2**63 - 1, 0]), + ("bool", pa.bool_(), [True, False, True]), + ("float32", pa.float32(), [1.5, 0.0, -3.25]), + ("float64", pa.float64(), [0.1, math.inf, 5e-324]), + ("float16", pa.float16(), [0.5, -0.0, math.nan]), + ("decimal128", pa.decimal128(38, 4), [D("1.2500"), D("-9.0001"), D("0")]), + ("decimal256", pa.decimal256(70, 4), [D("1.2500"), D("-9.0001"), D("0")]), + ("date64", pa.date64(), [-(2**63), 1, 2**63 - 1]), + ("decimal32", pa.decimal32(9, 2), [D("1.25"), D("-9999999.99"), D("0")]), + ( + "decimal64", + pa.decimal64(18, 2), + [D("1.25"), D("-9999999999999999.99"), D("0")], + ), + ("null", pa.null(), [None, None, None]), + ("time32_s", pa.time32("s"), [0, 86_399, 1]), + ("time32_ms", pa.time32("ms"), [0, 86_399_999, 1]), + ("time64_us", pa.time64("us"), [0, 86_400 * 10**6 - 1, 1]), + ("time64_ns", pa.time64("ns"), [0, 86_400 * 10**9 - 1, 1]), + ( + "date32", + pa.date32(), + [dt.date(1, 1, 1), dt.date(9999, 12, 31), dt.date(1970, 1, 1)], + ), + ("large_string", pa.large_string(), ["", "é\x00", "x" * 100]), + ("string", pa.string(), ["", "é\x00", "y"]), + ("binary", pa.binary(), [b"", b"\x00\xff", b"a"]), + *( + (f"ts_{u}_{z}", timestamp(u, tz=z), [-1, 0, 2**40 + 1]) + for u in ("s", "ms", "us", "ns") + for z in (None, "UTC", "Asia/Kathmandu", "-03:30") + ), + ] + + +@pytest.mark.parametrize("case", scalar_cases(), ids=lambda c: c[0]) +@pytest.mark.parametrize("nullable", [True, False]) +def test_every_type_at_every_nesting_depth( + case: tuple[str, pa.DataType, list[Any]], nullable: bool +) -> None: + """Each kept type alone and below lists, fixed-size lists, structs and their + combinations, in several columns at once, in two column orders.""" + _, arrow_type, values = case + nullable = nullable or pa.types.is_null(arrow_type) + if nullable: + values = [*values, None] + else: + values = [*values, values[0]] + leaf = pa.field("v.1", arrow_type, nullable, {"unit": "m"}) + item = leaf.with_name("odd item") + plain_item = item.remove_metadata() + v, n = values, len(values) + shapes: dict[str, tuple[pa.DataType, list[Any]]] = { + "plain": (arrow_type, v), + "list": (pa.list_(item), [v, [], None, v[:1]]), + "large": (pa.large_list(item), [None, v[:2], v, []]), + "fixed": (pa.list_(item, 2), [v[:2], None, v[2:], v[1:3]]), + "fixed_fixed": ( + pa.list_(pa.list_(item, 1), 2), + [[v[:1], None], None, [v[1:2], v[2:3]], [v[:1], v[:1]]], + ), + "fixed0": (pa.list_(item, 0), [[], None, [], []]), + "list_fixed": (pa.list_(pa.list_(item, 1)), [[v[:1], None], [], None, [v[3:]]]), + "map": ( + map_of(pa.string(), item.with_name("value").remove_metadata()), + [[("b", v[0]), ("a", v[1])], None, [], [("", x) for x in v]], + ), + "map_sorted_list": ( + map_of(pa.binary(), pa.list_(plain_item), keys_sorted=True), + [None, [(b"a", v), (b"b", None)], [(b"", [])], []], + ), + "list_map": ( + pa.list_(map_of(pa.int16(), plain_item.with_name("value"))), + [[[(1, v[0])], None, []], None, [], [[(2, x)] for x in v]], + ), + "map_struct": ( + map_of( + pa.string(), + pa.struct( + [pa.field("z", pa.int8()), pa.field("a.b", arrow_type, nullable)] + ), + ), + [ + None, + [("k", {"z": 1, "a.b": v[0]})], + [], + [("", {"z": None, "a.b": v[1]})], + ], + ), + "fixed_struct": ( + pa.list_(pa.struct([pa.field("z", pa.int8()), leaf]), 1), + [[{"z": 1, "v.1": x}] for x in v], + ), + "struct": ( + pa.struct([leaf, pa.field("__b", pa.int8())]), + [{"v.1": x, "__b": i} for i, x in enumerate(v)], + ), + "struct_list": ( + pa.struct([pa.field("z", pa.list_(item)), pa.field("a", pa.int8())]), + [{"z": x, "a": 1} for x in ([], v, None, v[:1])], + ), + "list_struct": ( + pa.list_(pa.field("i", pa.struct([pa.field("z", pa.int8()), leaf]))), + [[{"z": 1, "v.1": v[0]}], None, [], [{"z": None, "v.1": x} for x in v]], + ), + "list_list": (pa.list_(pa.list_(item)), [[v, [], None], [], None, [v[:1]]]), + "deep": ( + pa.list_( + pa.struct([pa.field("s", pa.struct([pa.field("l", pa.list_(item))]))]) + ), + [[{"s": {"l": v}}, {"s": {"l": None}}], [], None, [{"s": {"l": []}}]], + ), + } + if not nullable or pa.types.is_null(arrow_type): + # pyarrow cannot cast a null fixed-size list over non-null items, or a sliced + # list of structs with a null-typed field, so the test + # could not state what it expects of the small variants. + shapes = {k: (large_type(t), rows) for k, (t, rows) in shapes.items()} + columns = {k: pa.array(rows, t) for k, (t, rows) in shapes.items()} + assert all(len(c) == n for c in columns.values()) + fields = [ + pa.field(k, c.type, nullable if k == "plain" else True, {"k": k}) + for k, c in columns.items() + ] + table = keyed(columns, fields) + _ = round_trip(table) + _ = round_trip(table.select(list(reversed(table.column_names)))) + + +@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) +@pytest.mark.parametrize( + "zone", [None, "UTC", "Europe/Berlin", "Asia/Kathmandu", "+05:45", "-03:30"] +) +def test_zone_aware_timestamps_are_exact(unit: str, zone: str) -> None: + """Extremes of the integer, the far past and sub-second ticks.""" + ticks = [-(2**63), 2**63 - 1, -(2**63) + 1, 0, -1, 1, -(10**15) - 7, 10**15 + 3] + ticks += [-62135596800 * {"s": 1, "ms": 10**3, "us": 10**6, "ns": 1}[unit] - 1] + values = [*ticks, None] + ts = timestamp(unit, tz=zone) + plain: Any = pa.array(values, pa.int64()).cast(ts) + columns = { + "t": plain, + "l": pa.array([[x, None] for x in values], pa.list_(pa.int64())).cast( + pa.list_(ts) + ), + "s": pa.StructArray.from_arrays([plain], fields=[pa.field("t", ts)]), + } + got = by_id(round_trip(keyed(columns))) + assert got.column("t").cast(pa.int64()).to_pylist() == values + assert got.schema.field("t").type == ts + encoded = store.encode_rows(keyed(columns)) + # 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(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) + monkeypatch.setattr(store, "encode_name", lambda name: "new_" + name.encode().hex()) + manifest = read(metadata) + assert "ox_a;2Eb" in manifest.physical.names + got = store.decode_rows(stored, manifest) + assert [got.column(n)[0].as_py() for n in table.column_names if n != KEY] == [ + 1, 2, {"c.d": 3}, + ] # fmt: skip + + +def _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)) + + +@pytest.mark.parametrize( + "make", + [ + 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))]))), + ], +) +def test_a_manifest_that_cannot_be_read_in_full_is_an_error(make: Any) -> None: + recorded = make(entries(schema_of(BASE))) + with pytest.raises(store.ManifestError): + store.read_manifest(recorded, PATH) + + +def test_a_large_manifest_is_kept() -> None: + """A schema row's cell has no metadata entry's limit: no chunks, no bound.""" + 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 diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 2c4a04b83..46cef7ddc 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -15,6 +15,7 @@ from __future__ import annotations import datetime as dt +import decimal import math import os import uuid @@ -408,3 +409,134 @@ def upsert(name: str) -> None: 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({"d": pa.array([1], pa.duration("s"))}), + 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 From 03bbac4d94fce3240cea010e6c31d5a08c137e14 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 05:07:06 -0800 Subject: [PATCH 05/25] refactor(databases): fewer type warnings in the store codec and its tests (ITL-1497) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiral_store.py | 8 +- tests/test_databases/test_spiral_store.py | 121 ++++++++++++---------- 2 files changed, 68 insertions(+), 61 deletions(-) diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py index aa95ff8bb..e9338901b 100644 --- a/src/orcapod/databases/spiral_store.py +++ b/src/orcapod/databases/spiral_store.py @@ -219,9 +219,9 @@ def error(self) -> UnstorableInSpiralError: def _without_identifier(field: pa.Field[Any]) -> dict[bytes, bytes]: """The field's metadata without the two keys that hold a logical type identifier.""" - metadata = cast("dict[bytes, bytes]", dict(field.metadata or {})) - metadata.pop(EXTENSION_NAME_KEY, None) - metadata.pop(EXTENSION_METADATA_KEY, None) + metadata = dict(field.metadata or {}) + _ = metadata.pop(EXTENSION_NAME_KEY, None) + _ = metadata.pop(EXTENSION_METADATA_KEY, None) return metadata @@ -237,7 +237,7 @@ def _logical_field(field: pa.Field[Any]) -> pa.Field[Any]: raise UnstorableInSpiralError("its extension type cannot be identified") arrow_type = field.type if node.identifier is not None and EXTENSION_NAME_KEY not in (field.metadata or {}): - arrow_type = cast(Any, arrow_type).storage_type + 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 diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py index 683915adf..af92dc7e3 100644 --- a/tests/test_databases/test_spiral_store.py +++ b/tests/test_databases/test_spiral_store.py @@ -16,6 +16,7 @@ import re import subprocess import sys +from collections.abc import Callable from pathlib import Path from typing import Any, cast @@ -244,7 +245,7 @@ def walk(field: Any, named: bool, in_map: bool = False) -> None: def refused(rows: pa.Table, *words: str) -> store.UnstorableInSpiralError: with pytest.raises(store.UnstorableInSpiralError) as info: - store.encode_rows(rows) + _ = store.encode_rows(rows) for word in words: assert word in str(info.value) return info.value @@ -363,15 +364,15 @@ def test_the_key_is_not_a_value_column_of_the_same_name() -> None: ["ox_" + KEY if n == KEY else n for n in encoded.column_names] ) with pytest.raises(store.StoredRowsError, match="missing"): - decode(renamed, table.schema) + _ = 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) + _ = store.encode_name(name) with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): - new(schema_of([("a", pa.int8()), (KEY, pa.large_binary())]), (name,)) + _ = 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: @@ -383,7 +384,7 @@ def test_a_name_that_is_not_utf8_is_refused_at_every_depth() -> None: pa.field("i", pa.list_(bad)), ): with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): - store.logical_schema(schema_of([field, (KEY, pa.large_binary())])) + _ = store.logical_schema(schema_of([field, (KEY, pa.large_binary())])) def wrappings(inner: Any) -> list[Any]: @@ -401,7 +402,7 @@ 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())])) + _ = 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())]) @@ -430,7 +431,7 @@ def test_a_struct_parent_must_be_valid_also_in_a_logical_types_storage( if as_storage: live = Labelled(ty, "test.parent", b"") array = pa.ExtensionArray.from_storage(live, array) - refused(keyed({"c": array}), "'c'", "null struct") + _ = refused(keyed({"c": array}), "'c'", "null struct") # --------------------------------------------------------------------------- types @@ -470,10 +471,10 @@ def test_every_row_of_the_type_matrix_is_kept_or_refused( _ = 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'") + _ = refused(rows, REFUSED_ROWS[row.label], "'x'") return if row.label in NULL_STRUCT_ROWS: - refused(rows, "null struct", "'y'") + _ = refused(rows, "null struct", "'y'") rows = rows.drop_columns(["y"]) _ = round_trip(rows) _ = round_trip(rows, live=True) @@ -734,7 +735,7 @@ def test_what_a_null_list_or_map_hides_is_not_written() -> None: def test_no_rows_are_never_written() -> None: - refused(keyed({"a": pa.array([1])}).slice(1), "no rows") + _ = refused(keyed({"a": pa.array([1])}).slice(1), "no rows") @pytest.mark.parametrize( @@ -751,7 +752,7 @@ def test_no_rows_are_never_written() -> None: ], ) def test_a_null_struct_at_any_depth_is_refused(make: Any) -> None: - refused(keyed({"ok": pa.array([1, 2]), "bad": make()}), "'bad'", "null") + _ = 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: @@ -772,7 +773,7 @@ def test_a_null_under_a_non_null_field_is_refused_at_any_depth() -> 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( + _ = refused( keyed( {"x": pa.array([None], pa.int8())}, [not_null.with_name("x").with_type(pa.int8())], @@ -820,7 +821,7 @@ def test_a_type_the_store_does_not_keep_is_refused_at_every_depth( ) for call in (store.physical_schema, store.logical_schema, entries): with pytest.raises(store.UnstorableInSpiralError, match="'bad'"): - call(schema) + _ = call(schema) def test_every_refusal_is_in_one_table() -> None: @@ -842,13 +843,13 @@ 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") + _ = 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") + _ = 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) @@ -870,9 +871,9 @@ 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) + _ = 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) + _ = decode(pa.table({KEY: key, "a": column}), schema) @pytest.mark.parametrize( @@ -894,7 +895,7 @@ def test_a_null_key_is_refused_whatever_the_schema_says(nullable: bool) -> None: ) 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)) + _ = store.physical_schema(schema_of(fields)) # ------------------------------------------------------------------- logical types @@ -986,11 +987,11 @@ def test_a_logical_type_below_a_plain_type_is_refused() -> None: ): schema = schema_of([("c", arrow_type), (KEY, pa.large_binary())]) with pytest.raises(store.UnstorableInSpiralError, match="nested"): - store.logical_schema(schema) + _ = 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())])) + _ = store.logical_schema(schema_of([both, (KEY, pa.large_binary())])) # ------------------------------------------------------------------- rows, as read @@ -1068,12 +1069,12 @@ def bad(name: str, array: Any, *words: str, value: bool = False) -> None: 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) + _ = 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) + _ = decode(repeated, schema) def test_rows_are_given_the_recorded_schema_only() -> None: @@ -1086,7 +1087,7 @@ def test_rows_are_given_the_recorded_schema_only() -> None: 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) + _ = store.decode_rows(stored, manifest, schema) def test_a_table_with_a_manifest_and_no_rows_reads_as_no_rows() -> None: @@ -1259,13 +1260,13 @@ 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(recorded, path) + _ = store.read_manifest(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)) + _ = new(schema_of(BASE), ("x", part)) def test_stored_names_come_from_the_manifest_not_from_the_rule( @@ -1280,7 +1281,11 @@ def test_stored_names_come_from_the_manifest_not_from_the_rule( } ) metadata, stored = entries(table.schema), _stored(table) - monkeypatch.setattr(store, "encode_name", lambda name: "new_" + name.encode().hex()) + + 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) @@ -1314,39 +1319,41 @@ def test_the_changed_payload_helper_builds_a_readable_manifest() -> None: assert read(_payload()) == new(schema_of(BASE)) -@pytest.mark.parametrize( - "make", - [ - 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))]))), - ], -) -def test_a_manifest_that_cannot_be_read_in_full_is_an_error(make: Any) -> None: +_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(recorded, PATH) + _ = store.read_manifest(recorded, PATH) def test_a_large_manifest_is_kept() -> None: From 548344dfde320f9d31ab70d01f7e83015d23d308 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 05:09:37 -0800 Subject: [PATCH 06/25] docs(plans): the SpiralDB connector's store mode, proposal (ITL-1498) Co-Authored-By: Claude Opus 5.5 --- .../2026-11-26-itl-1498-spiral-store-mode.md | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md diff --git a/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md b/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md new file mode 100644 index 000000000..4ec3af13d --- /dev/null +++ b/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md @@ -0,0 +1,78 @@ +# ITL-1498: the SpiralDB connector's store mode (stage 3) + +Stage 3 of `docs/dev/specs/itl-1446-round2-spiral-sdk.md` (PR 588), stacked on PR 590 +(ITL-1497, the codec) and PR 589 (ITL-1495, names and metadata). Proposal; the choices marked +**Q** wait for the coordinator. + +## What the code does today + +- `ConnectorArrowDatabase` owns the path-to-name rule (`_path_to_table_name`: sanitize, join + with `__`), tests existence with `name in connector.get_table_names()`, and lists paths by + splitting names back (`list_table_paths`). A connector sees table names only, never a path. +- Every read is a whole-table read (`SELECT * FROM ""`, then filtered in Arrow); there + is no keyed read. +- `SpiralDBConnector` reads only; every write raises `SpiralDBWriteNotSupportedError`. + +## Proposal + +**Q1. Naming moves into the connector.** `DBConnectorProtocol` gains three required methods +(protocols are internal, so no optional capability): + +- `table_name(path) -> str`: the stored name of the table at a full path; +- `has_table(table_name) -> bool`: whether it exists; +- `table_paths(prefix, pending_names) -> list[path]`: the paths of the stored tables under + `prefix`. + +`ConnectorArrowDatabase` calls these instead of its own rule. SQLite, PostgreSQL and a plain +SpiralDB connector implement them with today's rule, moved unchanged into one shared helper, +so nothing they do changes. The other shape, a separate database class for SpiralDB that +copies `ConnectorArrowDatabase`'s pending, flush and guard machinery, is not recommended: two +copies of that machinery can drift. + +**Store mode** (`SpiralDBConnector(project, dataset, _store=True)`): + +- `table_name(path)`: `spiral_store_names.store_table_name`. The connector remembers each + name's path; a name it has not seen is resolved from the table's metadata. +- `has_table(name)`: opens the table by name, with no listing. Its record is read and checked: + another path or format raises `SpiralStoreTableCollisionError`. +- `table_paths(prefix)`: one listing, then the names starting with + `store_table_name_prefix(prefix)`, then each candidate's metadata (cached by table id), then + the recorded paths under `prefix`. Stale-layout checks use this unchanged (ITL-954). +- `create_table_if_not_exists`: `create_keyed_table(exist_ok=False)` with the key column. A 409 + means the name exists: it is judged as `has_table` judges it. +- First `upsert_records` on a table: write the identity metadata, then the manifest, then the + rows. **Q4**: the data context recorded is the one of the rows' `__data_context`, which must + be a single value. A table found without a record, and with no rows and the expected key, is + adopted; otherwise it is refused (decision 3). +- `upsert_records`: rows through `spiral_store.encode_rows`; `skip_existing` reads the key + column once. A write of no rows is never sent. +- `get_column_info` and `iter_batches`: the logical columns, rows through + `spiral_store.decode_rows` against the manifest. +- Plain tables are not store tables: a store-mode connector sees only `o1_` tables. + +**Q2. Where the manifest lives (revisits decision 4).** On main, the dataset's schema table +(`__orcapod_schemas__`) is all or nothing: one completion marker holds a digest of every +row, and a dataset whose marker does not fit its rows is refused for every read. Adding a +store table would mean reading the whole schema table and writing its row plus a new marker +(one append, so atomic), and every plain reader would parse store rows too. Recommended: keep +the manifest in the table's own metadata, in chunks of at most 8 KiB (PR 545's chunked format, +which PR 590 replaced with one record), beside the identity keys. Store tables then stay +independent of each other and of the schema table. Measured: there is no total metadata limit +in sight; reads slow down only past a megabyte. + +**Q3. Store mode stays private until stage 5.** The flag is underscored, `to_config` refuses a +store-mode connector, and there is no lease yet (stage 4). Writes happen only in tests on the +fake and in the live conformance dataset. + +## Measured (live, spiral-sdk 0.16.78) + +- A key-range scan returns no row for an absent key, and rows in the order of the ranges + asked: no null rows (ITL-1476's second finding does not apply to spiral-sdk). +- Table names: the store's names are at most 164 characters in `[a-z0-9_]`, within the + service's 255 (ITL-1476's first finding). +- A write of no rows publishes nothing (ITL-1476's third finding); the store sends none. + +## Not in this stage + +The lease (stage 4), keyed reads in place of whole-table reads (a later performance stage), +and job integration with switch-on (stage 5). From 276b50fe4c2c516d23ed86391d98cfc17855dc91 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 05:19:49 -0800 Subject: [PATCH 07/25] fix(databases): review findings on the store codec and the fake (ITL-1497) - A map given back in another layout is rebuilt from its parts: pyarrow aborts the process casting a map between layouts. - A record id repeated in one write is refused before anything is written. - The fake rebuilds a zero-width fixed-size list from buffers. - The fake cuts a struct field name at NUL at every depth, as measured live. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiral_store.py | 38 ++++++++++++- tests/test_databases/fake_spiral_sdk.py | 54 ++++++++++++++++++- tests/test_databases/test_spiral_store.py | 41 ++++++++++++++ .../test_spiraldb_connector_integration.py | 37 +++++++++++++ 4 files changed, 168 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py index e9338901b..21cb327ad 100644 --- a/src/orcapod/databases/spiral_store.py +++ b/src/orcapod/databases/spiral_store.py @@ -43,6 +43,7 @@ import numpy as np import pyarrow as pa +import pyarrow.compute as pc from orcapod.databases.utils import identity_node from orcapod.logical_types.canonical_form import ( @@ -457,6 +458,11 @@ def encode_rows(rows: pa.Table) -> pa.Table: 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) @@ -672,7 +678,7 @@ def decode_rows( live = isinstance(out.type, pa.BaseExtensionType) storage: Any = out.type.storage_type if live else out.type if storage != field.type: - chunks = [c.cast(storage) for c in chunks] + chunks = [_retyped(c, storage) for c in chunks] if live: chunks = [ pa.ExtensionArray.from_storage(cast(Any, out.type), c) @@ -697,6 +703,36 @@ def empty_rows(manifest: StoreManifest) -> pa.Table: 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): + small_offsets = pa.array(_offsets(array).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 diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 7c2ab6d57..1606edd88 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -65,7 +65,8 @@ "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", + "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", @@ -290,12 +291,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``). @@ -451,6 +494,15 @@ 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 + cut = _names_cut_at_nul(field.type) + if cut != field.type: + column = rows.column(i) + rows = rows.set_column( + i, + field.name, + 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}'") diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py index af92dc7e3..97b169184 100644 --- a/tests/test_databases/test_spiral_store.py +++ b/tests/test_databases/test_spiral_store.py @@ -1375,3 +1375,44 @@ def test_the_codec_needs_no_spiral_client() -> None: "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") diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 46cef7ddc..35690361d 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -26,6 +26,7 @@ from unittest.mock import patch import pyarrow as pa +import pyarrow.compute as pc import pytest from orcapod.databases import SpiralDBConnector @@ -540,3 +541,39 @@ def test_what_the_store_codec_avoids_is_refused( _ = table.append(rows) again = client.keyed_table_by_id(table.resource_id) assert again.version_id == table.version_id + + +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}]] From fe4145c710f5090a16b08d8112fcce74b0d8fb23 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 05:46:01 -0800 Subject: [PATCH 08/25] feat(databases): the SpiralDB connector's store mode (ITL-1498) DBConnectorProtocol gains table_name, has_table and table_paths, and ConnectorArrowDatabase asks the connector instead of naming tables itself; SQLite, PostgreSQL and plain SpiralDB keep today's rule, moved unchanged into databases/table_names.py (checked against the old rule). A SpiralDB connector opened with _store=True names a table from its full path, finds it by opening that name, records its identity and manifest (in chunks of its own metadata) before its first rows, adopts an empty table without a record, refuses a table of another path, lists tables by their recorded paths, and writes and reads rows through the store codec. Private: not saved, no lease yet. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1498.md | 3 + .../2026-11-26-itl-1498-spiral-store-mode.md | 6 +- docs/reference/hashing.md | 1 + .../databases/connector_arrow_database.py | 57 +-- src/orcapod/databases/postgresql_connector.py | 18 +- src/orcapod/databases/spiral_store.py | 109 ++++- src/orcapod/databases/spiraldb_connector.py | 145 +++++- .../databases/spiraldb_store_tables.py | 443 ++++++++++++++++++ src/orcapod/databases/sqlite_connector.py | 18 +- src/orcapod/databases/table_names.py | 57 +++ .../protocols/db_connector_protocol.py | 38 +- .../test_core/sources/test_db_table_source.py | 18 +- .../sources/test_tag_columns_normalization.py | 18 +- tests/test_databases/fake_spiral_sdk.py | 1 + .../test_connector_arrow_database.py | 18 +- tests/test_databases/test_spiral_store.py | 59 ++- .../test_spiraldb_connector_integration.py | 39 ++ .../test_spiraldb_store_mode.py | 323 +++++++++++++ tests/test_databases/test_table_names.py | 115 +++++ 19 files changed, 1404 insertions(+), 82 deletions(-) create mode 100644 changelog.d/ITL-1498.md create mode 100644 src/orcapod/databases/spiraldb_store_tables.py create mode 100644 src/orcapod/databases/table_names.py create mode 100644 tests/test_databases/test_spiraldb_store_mode.py create mode 100644 tests/test_databases/test_table_names.py diff --git a/changelog.d/ITL-1498.md b/changelog.d/ITL-1498.md new file mode 100644 index 000000000..155056d74 --- /dev/null +++ b/changelog.d/ITL-1498.md @@ -0,0 +1,3 @@ +### Breaking changes and migration + +- `DBConnectorProtocol` has three more required methods: `table_name(path)`, `has_table(table_name)` and `table_paths(prefix, pending)`. `ConnectorArrowDatabase` now asks the connector to name its tables, test their existence and list their paths. SQLite, PostgreSQL and SpiralDB keep the names and listings they had. A connector of your own implements the three methods; `orcapod.databases.table_names` has the rule the built-in connectors use. diff --git a/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md b/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md index 4ec3af13d..562dcd093 100644 --- a/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md +++ b/docs/dev/plans/2026-11-26-itl-1498-spiral-store-mode.md @@ -1,8 +1,10 @@ # ITL-1498: the SpiralDB connector's store mode (stage 3) Stage 3 of `docs/dev/specs/itl-1446-round2-spiral-sdk.md` (PR 588), stacked on PR 590 -(ITL-1497, the codec) and PR 589 (ITL-1495, names and metadata). Proposal; the choices marked -**Q** wait for the coordinator. +(ITL-1497, the codec) and PR 589 (ITL-1495, names and metadata). Q1 to Q4 approved as +recommended by the coordinator on the developer's behalf (2026-11-26); Q2 revises decision 4. +Implemented in `databases/table_names.py`, `databases/spiraldb_store_tables.py`, the +connector's `_store` flag, and the chunked manifest of `spiral_store.manifest_entries`. ## What the code does today diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 91bc7fe36..10bbc0259 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -330,6 +330,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | | SpiralDB 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) | SHA-256 hex | the header's check of the manifest chunks in the table's metadata (a checksum of a stored record) | `databases/spiral_store.py:_checksum` | | SpiralDB store table name | a store table's full path components, canonical JSON | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`, not written into the name) | the end of the table's SpiralDB name `o1__` (a name; pinned in the `spiral_table_name` golden group) | `databases/spiral_store_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/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..a43651076 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -18,7 +18,6 @@ from __future__ import annotations -import re from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager @@ -163,17 +162,8 @@ def _get_record_key(self, record_path: tuple[str, ...]) -> str: return "/".join(self._path_prefix + record_path) def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: - """Map a record_path to a safe SQL table name. - - Each component is sanitized (non-alphanumeric chars → ``_``), then - joined with ``__`` as separator. A ``t_`` prefix is added if the result - starts with a digit to ensure a valid SQL identifier. - """ - parts = [re.sub(r"[^a-zA-Z0-9_]", "_", part) for part in record_path] - name = "__".join(parts) - if name and name[0].isdigit(): - name = "t_" + name - return name + """The connector's name of the table at a full record path (ITL-1498).""" + return self._connector.table_name(record_path) def _validate_record_path(self, record_path: tuple[str, ...]) -> None: if not record_path: @@ -250,7 +240,7 @@ def _get_committed_table(self, record_path: tuple[str, ...]) -> pa.Table | None: """Fetch all committed records for a path from the connector.""" table_name = self._path_to_table_name(self._path_prefix + record_path) self._require_table_name(table_name) - if table_name not in self._connector.get_table_names(): + if not self._connector.has_table(table_name): return None batches = list(self._connector.iter_batches(f'SELECT * FROM "{table_name}"')) if not batches: @@ -260,17 +250,10 @@ def _get_committed_table(self, record_path: tuple[str, ...]) -> pa.Table | None: def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. - A table name in the backend does not keep the path it was made from (see - ``_path_to_table_name``), so this lists by name: the tables, committed or - pending, whose name starts with the name ``prefix`` maps to. The components - after ``prefix`` are the rest of the name split at ``__``. They are in the - backend's form: every character other than letters, digits and ``_`` is - ``_``, and a component that holds ``__`` comes back as two. Such a path - still names the same table. A table of another path that maps to a name - with the same beginning is listed as well. With an empty prefix at the - root, a name that got the ``t_`` prefix keeps it. - - Costs one listing of the backend's table names; no table is read. + The connector lists them (``DBConnectorProtocol.table_paths``), committed or + pending. A relational connector's names lose information, so its paths are in + the names' form (``table_names.joined_table_paths``); a SpiralDB store gives the + paths its tables record. Args: prefix: Leading path components, relative to ``self.base_path``. @@ -279,21 +262,9 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] The table paths, relative to ``self.base_path``, sorted. """ full_prefix = self._path_prefix + prefix - names = set(self._connector.get_table_names()) - names.update( - self._path_to_table_name(tuple(key.split("/"))) - for key in self._pending_batches - ) - stem = self._path_to_table_name(full_prefix) if full_prefix else "" - found: set[tuple[str, ...]] = set() - for name in names: - if not stem: - found.add(tuple(name.split("__"))) - elif name == stem: - found.add(prefix) - elif name.startswith(stem + "__"): - found.add(prefix + tuple(name[len(stem) + 2 :].split("__"))) - return sorted(found) + pending = [tuple(key.split("/")) for key in self._pending_batches] + found = self._connector.table_paths(full_prefix, pending) + return sorted({path[len(self._path_prefix) :] for path in found}) def table_exists(self, record_path: tuple[str, ...]) -> bool: """Return ``True`` if a table exists at ``record_path``. @@ -313,7 +284,7 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: record_key = self._get_record_key(record_path) if record_key in self._pending_batches: return True - return table_name in self._connector.get_table_names() + return self._connector.has_table(table_name) # ── Storable columns ────────────────────────────────────────────────────── @@ -327,7 +298,7 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) try: - if table_name not in self._connector.get_table_names(): + if not self._connector.has_table(table_name): pending = self._pending_batches.get(self._get_record_key(record_path)) return None if pending is None else pending.schema return pa.schema( @@ -556,7 +527,7 @@ def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": """The stored table's columns as the connector reports them now, in its order (``get_column_info``, large-normalized types), or ``None`` when it does not exist. Never remembered: each call asks the connector.""" - if table_name not in self._connector.get_table_names(): + if not self._connector.has_table(table_name): return None return [ pa.field( @@ -580,7 +551,7 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: held.append(pending.schema) table_name = self._path_to_table_name(self._path_prefix + record_path) stored = self._stored_schemas.get(table_name) - if stored is None and table_name in self._connector.get_table_names(): + if stored is None and self._connector.has_table(table_name): stored = self._read_stored_schema(table_name) if stored is not None: self._stored_schemas[table_name] = stored diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 0417c04c5..d76d1b565 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -19,7 +19,7 @@ import re import threading import uuid -from collections.abc import Iterator +from collections.abc import Collection, Iterator from typing import TYPE_CHECKING, Any import pyarrow as pa @@ -28,6 +28,7 @@ from orcapod.errors import UnstorableTableNameError from orcapod.types import ColumnInfo from orcapod.utils.lazy_module import LazyModule +from orcapod.databases.table_names import joined_table_name, joined_table_paths if TYPE_CHECKING: import psycopg @@ -411,6 +412,21 @@ def _validate_table_name(table_name: str) -> None: # ── Schema introspection ────────────────────────────────────────────────── + def table_name(self, path: tuple[str, ...]) -> str: + """Return the name of the table at a full record path: the joined rule.""" + return joined_table_name(path) + + def has_table(self, table_name: str) -> bool: + """Return whether the table exists.""" + return table_name in self.get_table_names() + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the tables under ``prefix``, in the names' form.""" + names = {*self.get_table_names(), *(joined_table_name(p) for p in pending)} + return joined_table_paths(names, prefix) + def get_table_names(self) -> list[str]: """Return all user table names in this database (sorted, excludes views).""" with self._lock: diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py index 21cb327ad..b0b08f0be 100644 --- a/src/orcapod/databases/spiral_store.py +++ b/src/orcapod/databases/spiral_store.py @@ -14,11 +14,11 @@ 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 at creation and never changed - (``manifest_bytes``, ``read_manifest``): the record path, the kind, the logical - schema, and the stored names at every depth. It is kept in the table's row of the - dataset's schema table; the table's own metadata holds only its identity - (``spiral_store_names``). +* **The manifest.** One a table, written before its first rows (``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, beside the table's + identity record (``spiral_store_names``); never in the dataset's schema table, which is + all or nothing under one completion marker (decision of 2026-11-26, ITL-1498). 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 @@ -34,9 +34,10 @@ import base64 import binascii +import hashlib import json import re -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass from typing import Any, cast @@ -835,11 +836,9 @@ def new_manifest( def manifest_bytes(manifest: StoreManifest) -> bytes: - """Return the bytes that record ``manifest``. + """Return the payload that records ``manifest``; equal manifests give equal bytes. - They are the ``schema`` cell of the table's row in its dataset's schema table - (``__orcapod_schemas__``), whose cells have no size limit; the row's ``format`` says - they are a store manifest. Equal manifests give equal bytes. + ``manifest_entries`` cuts it into a table's metadata entries. Args: manifest: The manifest. @@ -878,11 +877,11 @@ def _schema_of(text: object) -> pa.Schema: raise ManifestError(f"a schema cannot be read ({exc})") from exc -def read_manifest(recorded: bytes, record_path: tuple[str, ...]) -> StoreManifest: +def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreManifest: """Return the manifest ``manifest_bytes`` recorded. Args: - recorded: The bytes, as read from the table's row. + recorded: The payload. record_path: The record path the table was looked up for. Returns: @@ -937,6 +936,92 @@ def read_manifest(recorded: bytes, record_path: tuple[str, ...]) -> StoreManifes 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, + "sha256": _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, 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}") + count = fields.get("chunks") + if type(count) is not int or count < 1: + raise ManifestError(f"invalid chunk count {count!r}") + 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("sha256") != _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] = [] diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index bd72e28fe..e9cdf3795 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -24,7 +24,7 @@ import urllib.parse import urllib.request import warnings -from collections.abc import Iterator, Mapping +from collections.abc import Collection, Iterator, Mapping from contextlib import contextmanager from copy import copy from threading import local @@ -39,6 +39,7 @@ check_no_nulls, schema_paths, ) +from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.databases.spiraldb_schema_table import ( SCHEMA_TABLE, SchemaTable, @@ -46,6 +47,7 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in +from orcapod.databases.table_names import joined_table_name, joined_table_paths from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -624,6 +626,9 @@ class SpiralDBConnector: dataset: Dataset within the project. Defaults to ``"default"``. overrides: Optional: ``{"server.url": "https://api.spiraldb.dev"}``, the address of the service. Any other key is refused. + _store: Open the dataset as a pipeline store (``spiraldb_store_tables``): + tables named from their paths, rows through the store codec. Private until + the store is switched on (ITL-1446, stage 5): such a connector is not saved. """ def __init__( @@ -631,6 +636,8 @@ def __init__( project_id: str, dataset: str = "default", overrides: dict[str, str] | None = None, + *, + _store: bool = False, ) -> None: self._project_id = project_id self._dataset = dataset @@ -641,6 +648,16 @@ def __init__( # Shared by every connector on this client (``share_client``). self._counts: dict[tuple[str, str], tuple[int, bool]] = {} client = self._client + self._store: StoreTables | None = None + if _store: + self._store = StoreTables( + client, + project_id, + dataset, + lambda name: _open_keyed_table(client, project_id, dataset, name), + lambda: _list_keyed_tables(client, project_id, dataset), + lambda doing: _service_call(f"{doing} of {project_id}/{dataset}"), + ) self._schemas = SchemaTable( project_id, dataset, @@ -675,6 +692,44 @@ def _require_user_table(self, table_name: str) -> None: f"the tables of dataset {self._dataset!r}" ) + def table_name(self, path: tuple[str, ...]) -> str: + """Return the name of the table at a full record path. + + A store names it from the path (``spiral_store_names``); otherwise the joined + rule of the relational connectors (``table_names.joined_table_name``). + """ + if self._store is not None: + return self._store.table_name(path) + return joined_table_name(path) + + def has_table(self, table_name: str) -> bool: + """Return whether the table exists; a store opens it by name, with no listing.""" + self._require_open() + if self._store is not None: + return self._store.has_table(table_name) + return table_name in self.get_table_names() + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the tables under ``prefix``, stored or pending. + + A store gives the paths its tables record; otherwise the joined rule's form. + """ + self._require_open() + if self._store is not None: + return self._store.table_paths(prefix, pending) + names = {*self.get_table_names(), *(joined_table_name(p) for p in pending)} + return joined_table_paths(names, prefix) + + def _refuse_in_store_mode(self, what: str) -> None: + """Refuse an operation on raw tables in a store-mode connector.""" + if self._store is not None: + raise ValueError( + f"{what} reads raw SpiralDB tables; a store-mode connector reads its " + "tables through the store codec only" + ) + def get_table_names(self) -> list[str]: """Return all table names in this connector's dataset, sorted alphabetically. @@ -687,6 +742,9 @@ def get_table_names(self) -> list[str]: Returns: Sorted list of plain table name strings (no ``dataset.`` prefix). """ + if self._store is not None: + self._require_open() + return self._store.table_names() self._require_open() with self._service_call("list the tables of", "*"): listed = _list_keyed_tables(self._client, self._project_id, self._dataset) @@ -716,6 +774,7 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: SpiralDBTableNotFoundError: If there is no such table. ValueError: If the name is the schema table's. """ + self._refuse_in_store_mode("lookup_table") self._require_open() self._require_user_table(table_name) missing = f"Table not found: {self._project_id}.{self._dataset}.{table_name}" @@ -792,6 +851,8 @@ def get_pk_columns(self, table_name: str) -> list[str]: Returns: List of PK column names. """ + if self._store is not None: + return [self._store.key_column] return self.lookup_table(table_name).key_columns def get_column_info(self, table_name: str) -> list[ColumnInfo]: @@ -818,6 +879,9 @@ def get_column_info(self, table_name: str) -> list[ColumnInfo]: SpiralDBTableNotFoundError: If the table does not exist. TableSchemaError: If the table's row cannot be read or disagrees with it. """ + if self._store is not None: + self._require_open() + return self._store.column_info(table_name) return [ ColumnInfo(name=f.name, arrow_type=f.type, nullable=f.nullable) for f in self.lookup_table(table_name).arrow_schema() @@ -868,6 +932,9 @@ def iter_batches( "Ignoring batch_size=%r", batch_size, ) + if self._store is not None: + yield from self._store.scan(_parse_table_name(query)) + return yield from self.scan_batches(_parse_table_name(query)) def scan_batches( @@ -901,6 +968,7 @@ def scan_batches( NullInNonNullableColumnError: If a batch holds a null in a recorded non-nullable column (naming the table and the column). """ + self._refuse_in_store_mode("scan_batches") yield from self.lookup_table(table_name).scan_batches( where=where, limit=limit, asof=asof ) @@ -918,6 +986,9 @@ def get_arrow_schema(self, table_name: str) -> pa.Schema: Raises: TableSchemaError: If the table's row cannot be read or disagrees with it. """ + if self._store is not None: + self._require_open() + return self._store.arrow_schema(table_name) return self.lookup_table(table_name).arrow_schema() def get_spiral_table_id(self, table_name: str) -> str: @@ -977,13 +1048,26 @@ def create_table_if_not_exists( columns: list[ColumnInfo], pk_column: str, ) -> None: - """Refuse to create a table: Orcapod does not write SpiralDB yet. + """Create a store table; refuse it on a plain connector. + + A store creates the table at a name it computed, unless it exists or is to be + adopted (``spiraldb_store_tables``). Its columns are recorded by its first + write. + + Args: + table_name: A name ``table_name`` returned. + columns: The columns (recorded by the first write, from its rows). + pk_column: The key column: the store's ``__record_id``. Raises: - SpiralDBWriteNotSupportedError: Always (ITL-1186). + SpiralDBWriteNotSupportedError: On a plain connector (ITL-1186). + ValueError: If the key column is not the store's. """ self._require_open() - raise SpiralDBWriteNotSupportedError(_NO_WRITES) + if self._store is None: + raise SpiralDBWriteNotSupportedError(_NO_WRITES) + self._store.require_key_column(pk_column) + self._store.create(table_name) def upsert_records( self, @@ -992,13 +1076,25 @@ def upsert_records( id_column: str, skip_existing: bool = False, ) -> None: - """Refuse to write rows: Orcapod does not write SpiralDB yet. + """Write rows to a store table; refuse them on a plain connector. + + Args: + table_name: A name ``table_name`` returned, of a table ``create_table_if_not_exists`` + made. + records: The rows, the key column included. + id_column: The key column: the store's ``__record_id``. + skip_existing: Leave out rows whose key the table holds. Raises: - SpiralDBWriteNotSupportedError: Always (ITL-1186). + SpiralDBWriteNotSupportedError: On a plain connector (ITL-1186). + ValueError: If the key column is not the store's, the rows hold no single data + context, or their columns are not the table's. """ self._require_open() - raise SpiralDBWriteNotSupportedError(_NO_WRITES) + if self._store is None: + raise SpiralDBWriteNotSupportedError(_NO_WRITES) + self._store.require_key_column(id_column) + self._store.write(table_name, records, skip_existing) @property def keeps_field_metadata(self) -> bool: @@ -1010,8 +1106,9 @@ def keeps_field_metadata(self) -> bool: def unstorable_column_reason( self, name: str, arrow_type: pa.DataType, *, primary_key: bool ) -> str | None: - """Refuse every column: Orcapod does not write SpiralDB yet. A job whose database - is on this connector is refused when the database is attached, before it runs. + """Say why a store cannot keep a column; refuse every column on a plain connector. + + A store keeps what the store codec keeps (``spiral_store``). Args: name: The column's name. @@ -1019,14 +1116,20 @@ def unstorable_column_reason( primary_key: Whether the column is the table's primary key. Raises: - SpiralDBWriteNotSupportedError: Always (ITL-1186). + SpiralDBWriteNotSupportedError: On a plain connector: Orcapod does not write + its tables (ITL-1186). A job whose database is on one is refused when the + database is attached, before it runs. """ - raise SpiralDBWriteNotSupportedError(_NO_WRITES) + if self._store is None: + raise SpiralDBWriteNotSupportedError(_NO_WRITES) + return self._store.unstorable_column_reason(name, arrow_type, primary_key) def unstorable_table_name_reason(self, table_name: str) -> str | None: """Say why SpiralDB cannot hold a table of this name: it holds every name. - The database's table names are letters, digits and ``_``. + A plain connector's names are letters, digits and ``_``; a store's are names it + computed (``spiral_store_names``), within SpiralDB's 255 characters by + construction. Args: table_name: The table name. @@ -1037,16 +1140,21 @@ def unstorable_table_name_reason(self, table_name: str) -> str | None: return None def validate_records(self, records: pa.Table) -> None: - """Refuse the rows: Orcapod does not write SpiralDB yet. Called before a database - on this connector buffers them. + """Check rows before a database buffers them; refuse them on a plain connector. + + A store runs the store codec on them (the last row of each key, as the database + keeps), so a row it cannot keep is refused before anything is written. Args: records: The rows. Raises: - SpiralDBWriteNotSupportedError: Always (ITL-1186). + SpiralDBWriteNotSupportedError: On a plain connector (ITL-1186). + UnstorableInSpiralError: If the store codec refuses the rows. """ - raise SpiralDBWriteNotSupportedError(_NO_WRITES) + if self._store is None: + raise SpiralDBWriteNotSupportedError(_NO_WRITES) + self._store.validate(records) def close(self) -> None: """Close this connector and release its SDK client. Idempotent.""" @@ -1072,6 +1180,11 @@ def to_config(self) -> dict[str, Any]: Raises: RuntimeError: If this connector has been closed. """ + if self._store is not None: + raise ValueError( + "a store-mode SpiralDB connector is not saved yet: the store is not " + "switched on (ITL-1446)" + ) self._require_open() return { "connector_type": "spiraldb", diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py new file mode 100644 index 000000000..9c35492b1 --- /dev/null +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -0,0 +1,443 @@ +"""The tables of a SpiralDB pipeline store, one dataset's (ITL-1498). + +What a ``SpiralDBConnector`` in store mode does with its tables; the design is +``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2. + +- A table's name is computed from its full record path (``spiral_store_names``); a + table is found by opening that name, never by listing. +- Its metadata holds its identity record and its manifest (``spiral_store``): the record + path, layout, data context, and the logical schema with the stored names. They are + written in one upsert before its first rows. +- A table under the name that records another path or format, or holds rows without a + record, is refused (``SpiralStoreTableCollisionError``). A table with no record and no + rows (a creation that stopped before its first rows) is adopted. +- Rows are encoded on write and decoded on read by the codec; a read gives the logical + columns, logical types live. +- The store's tables are listed by one listing of the dataset, narrowed by name, and the + metadata of each candidate (cached by table id): that is how stale layouts are found + (ITL-954). + +Private until the store is switched on (stage 5): there is no lease yet (stage 4). +""" + +from __future__ import annotations + +from collections.abc import Callable, Collection, Iterator +from contextlib import AbstractContextManager +from dataclasses import dataclass +from typing import TYPE_CHECKING, Protocol + +import pyarrow as pa +import pyarrow.compute as pc + +import orcapod.databases.spiral_store as codec +import orcapod.databases.spiral_store_names as names +from orcapod.errors import SpiralStoreTableCollisionError +from orcapod.logical_types.canonical_form import declaration_form_schema +from orcapod.types import ColumnInfo + +if TYPE_CHECKING: + import spiral as sp +else: + from orcapod.utils.lazy_module import LazyModule + + sp = LazyModule("spiral") + +DATA_CONTEXT_COLUMN = "__data_context" +"""The column every stored row's data context is in (``constants.DATA_CONTEXT_COL``).""" + + +class _Scan(Protocol): + """The part of spiral-sdk's scan the store uses.""" + + def to_table(self) -> pa.Table: ... + + +class _KeyedTable(Protocol): + """The part of spiral-sdk's ``KeyedTable`` the store uses.""" + + @property + def resource_id(self) -> str: ... + + @property + def key_columns(self) -> tuple[str, ...]: ... + + def get_metadata(self) -> dict[str, bytes]: ... + + def set_metadata(self, metadata: dict[str, bytes]) -> None: ... + + def scan( + self, columns: list[str] | None = None, *, limit: int | None = None + ) -> _Scan: ... + + def append(self, data: pa.Table) -> _KeyedTable: ... + + +class _Project(Protocol): + """The part of spiral-sdk's ``Project`` the store uses.""" + + def create_keyed_table( + self, dataset: str, name: str, key_schema: pa.Schema + ) -> _KeyedTable: ... + + +class _Client(Protocol): + """The part of spiral-sdk's ``Client`` the store uses.""" + + def project(self, id: str) -> _Project: ... + + def keyed_table_by_id(self, table_id: str) -> _KeyedTable: ... + + +@dataclass(frozen=True) +class _Found: + """A store table that exists, with what its metadata records.""" + + table_id: str + record: names.StoreTableRecord + manifest: codec.StoreManifest + + +class StoreTables: + """The store tables of one SpiralDB dataset. + + Args: + client: A spiral-sdk client. + project_id: The project. + dataset: The dataset. + open_table: Opens a keyed table by name; ``None`` when there is none. + list_tables: Lists the dataset's keyed tables: names by table id. + service_call: A context that notes on a failing SDK call what it was doing. + """ + + def __init__( + self, + client: _Client, + project_id: str, + dataset: str, + open_table: Callable[[str], _KeyedTable | None], + list_tables: Callable[[], dict[str, str]], + service_call: Callable[[str], AbstractContextManager[None]], + ) -> None: + self._client: _Client = client + self._project_id: str = project_id + self._dataset: str = dataset + self._open_table: Callable[[str], _KeyedTable | None] = open_table + self._list_tables: Callable[[], dict[str, str]] = list_tables + self._service_call: Callable[[str], AbstractContextManager[None]] = service_call + self._paths: dict[str, tuple[str, ...]] = {} + self._found: dict[str, _Found] = {} + self._records_by_id: dict[str, names.StoreTableRecord | None] = {} + + key_column: str = codec.KEY_COLUMN + """The key column of every store table.""" + + def require_key_column(self, name: str) -> None: + """Refuse a key column other than the store's.""" + if name != codec.KEY_COLUMN: + raise ValueError( + f"a SpiralDB store table's key is {codec.KEY_COLUMN!r}, not {name!r}" + ) + + def unstorable_column_reason( + self, name: str, arrow_type: pa.DataType, primary_key: bool + ) -> str | None: + """Why the codec cannot keep a column, or ``None``.""" + if primary_key: + if name == codec.KEY_COLUMN and pa.types.is_large_binary(arrow_type): + return None + return f"a store table's key is {codec.KEY_COLUMN!r}, large_binary" + key = pa.field(codec.KEY_COLUMN, pa.large_binary(), nullable=False) + try: + _ = codec.logical_schema(pa.schema([pa.field(name, arrow_type), key])) + except codec.UnstorableInSpiralError as exc: + return str(exc) + return None + + def validate(self, records: pa.Table) -> None: + """Run the codec on rows to buffer: the last row of each key, as kept.""" + if records.num_rows == 0: + return + _ = _one_data_context(records) + _ = codec.encode_rows(_last_of_each_key(records)) + + # ── names ──────────────────────────────────────────────────────────────── + + def table_name(self, path: tuple[str, ...]) -> str: + """Return the table name of a full record path, and remember the path.""" + name = names.store_table_name(path) + self._paths[name] = tuple(path) + return name + + def _path_of(self, table_name: str) -> tuple[str, ...]: + """The path a name was computed from (``table_name``).""" + path = self._paths.get(table_name) + if path is None: + raise KeyError( + f"{table_name!r} is not a name this store computed for a path" + ) + return path + + # ── finding a table ────────────────────────────────────────────────────── + + def _judge(self, table_name: str) -> _Found | None: + """Return the table at a name if it holds rows of this path, ``None`` if it is + absent or a table to adopt (no record and no rows, or a record and no rows). + + Raises: + SpiralStoreTableCollisionError: If the table is another path's, of another + format, or holds rows without a manifest. + """ + found = self._found.get(table_name) + if found is not None: + return found + path = self._path_of(table_name) + table = self._open_table(table_name) + if table is None: + return None + with self._service_call(f"read the metadata of {table_name}"): + metadata = table.get_metadata() + try: + record = names.read_store_table_metadata(metadata) + if record is not None: + names.require_store_table_path(record, path) + manifest = None if record is None else codec.read_manifest(metadata, path) + except (SpiralStoreTableCollisionError, codec.ManifestError) as exc: + raise SpiralStoreTableCollisionError( + str(exc), table=self._qualified(table_name) + ) from exc + if manifest is None: + self._require_key(table, table_name) + if self._holds_rows(table): + raise SpiralStoreTableCollisionError( + "it holds rows but no store manifest", + table=self._qualified(table_name), + ) + return None + assert record is not None + found = _Found(str(table.resource_id), record, manifest) + self._found[table_name] = found + return found + + def has_table(self, table_name: str) -> bool: + """Whether the store table at a computed name exists (holds a manifest).""" + return self._judge(table_name) is not None + + def _holds_rows(self, table: _KeyedTable) -> bool: + """Whether a keyed table has a row.""" + with self._service_call("read a key of a store table"): + keys = table.scan([codec.KEY_COLUMN], limit=1).to_table() + return keys.num_rows > 0 + + def _require_key(self, table: _KeyedTable, table_name: str) -> None: + """Refuse a table to adopt whose key is not the store's.""" + if tuple(table.key_columns) != (codec.KEY_COLUMN,): + raise SpiralStoreTableCollisionError( + f"its key columns are {list(table.key_columns)}, " + + f"not [{codec.KEY_COLUMN!r}]", + table=self._qualified(table_name), + ) + + def _qualified(self, table_name: str) -> str: + return f"{self._project_id}/{self._dataset}/{table_name}" + + # ── listing ────────────────────────────────────────────────────────────── + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the store tables under ``prefix``, and of the + pending ones. + + One listing of the dataset; the names that start as a table under ``prefix`` + must; then the record of each candidate, read once per table id. A listed table + whose record is of a path with another name is refused. + """ + start = names.store_table_name_prefix(prefix) + found = {p for p in pending if p[: len(prefix)] == prefix} + with self._service_call("list the store tables"): + listed = self._list_tables() + for table_id, table_name in listed.items(): + if not table_name.startswith(start): + continue + record = self._record_of(table_id, table_name) + if record is not None and record.path[: len(prefix)] == prefix: + found.add(record.path) + return sorted(found) + + def _record_of( + self, table_id: str, table_name: str + ) -> names.StoreTableRecord | None: + """The record of a listed table, read once per id; ``None`` without one.""" + if table_id not in self._records_by_id: + with self._service_call(f"read the metadata of {table_name}"): + metadata = self._client.keyed_table_by_id(table_id).get_metadata() + try: + record = names.read_store_table_metadata(metadata) + except SpiralStoreTableCollisionError as exc: + raise SpiralStoreTableCollisionError( + str(exc), table=self._qualified(table_name) + ) from exc + if record is not None and names.store_table_name(record.path) != table_name: + raise SpiralStoreTableCollisionError( + f"it records path {list(record.path)}, whose table has another name", + table=self._qualified(table_name), + ) + self._records_by_id[table_id] = record + return self._records_by_id[table_id] + + def table_names(self) -> list[str]: + """The names of the dataset's tables that start as store tables do, sorted.""" + with self._service_call("list the store tables"): + listed = self._list_tables() + prefix = names.STORE_TABLE_NAME_PREFIX + return sorted(n for n in listed.values() if n.startswith(prefix)) + + # ── reading ────────────────────────────────────────────────────────────── + + def _require(self, table_name: str) -> _Found: + found = self._judge(table_name) + if found is None: + raise KeyError(f"no store table {self._qualified(table_name)}") + return found + + def arrow_schema(self, table_name: str) -> pa.Schema: + """The schema rows of the table are read with: logical types live.""" + return _live(self._require(table_name).manifest.schema) + + def column_info(self, table_name: str) -> list[ColumnInfo]: + """The table's columns, as ``arrow_schema`` gives them.""" + return [ + ColumnInfo(name=f.name, arrow_type=f.type, nullable=f.nullable) + for f in self.arrow_schema(table_name) + ] + + def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: + """Every row of the table, decoded; nothing for a table with no rows.""" + found = self._require(table_name) + schema = _live(found.manifest.schema) + with self._service_call(f"read {table_name}"): + stored = self._client.keyed_table_by_id(found.table_id).scan().to_table() + if stored.num_rows == 0: + return + rows = codec.decode_rows(stored, found.manifest, schema) + yield from rows.to_batches() + + # ── writing ────────────────────────────────────────────────────────────── + + def create(self, table_name: str) -> None: + """Create the table at a computed name, unless it exists or is to be adopted.""" + if self._judge(table_name) is not None: + return + if self._open_table(table_name) is not None: + return # to adopt: its first write records it + key = pa.schema([pa.field(codec.KEY_COLUMN, pa.large_binary(), nullable=False)]) + project = self._client.project(self._project_id) + try: + with self._service_call(f"create {table_name}"): + _ = project.create_keyed_table(self._dataset, table_name, key) + except sp.SpiralError as exc: + if "status 409" not in str(exc): + raise + # Made meanwhile: judged as any table found under the name. + _ = self._judge(table_name) + + def write(self, table_name: str, records: pa.Table, skip_existing: bool) -> None: + """Upsert rows; the first write records the table's identity and manifest. + + Raises: + ValueError: If the rows hold no ``__data_context`` column, or several data + contexts, or columns other than the manifest's. + UnstorableInSpiralError: If the codec refuses the rows. + """ + path = self._path_of(table_name) + context = _one_data_context(records) + found = self._judge(table_name) + table = self._open_table(table_name) + if table is None: + raise KeyError(f"no store table {self._qualified(table_name)}") + if found is None: + manifest = codec.new_manifest(path, path[-1], records.schema) + encoded = _encoded(records) + metadata = { + **names.store_table_metadata(path, context), + **codec.manifest_entries(manifest), + } + with self._service_call(f"record {table_name}"): + table.set_metadata(metadata) + found = _Found( + str(table.resource_id), + names.StoreTableRecord(path, path[-1], context), + manifest, + ) + self._found[table_name] = found + else: + difference = codec.schema_difference(found.manifest.schema, records.schema) + if difference is not None: + raise ValueError( + f"the rows are not of the table's schema ({difference}): " + + "schema evolution is not supported" + ) + if skip_existing: + records = self._without_stored_keys(found, records) + encoded = _encoded(records) + if encoded.num_rows == 0: + return # a write of no rows is never sent + with self._service_call(f"write {table_name}"): + _ = table.append(encoded) + + def _without_stored_keys(self, found: _Found, records: pa.Table) -> pa.Table: + """The rows whose key the table does not hold yet.""" + with self._service_call("read the keys of a store table"): + stored = ( + self._client.keyed_table_by_id(found.table_id) + .scan([codec.KEY_COLUMN]) + .to_table() + ) + if stored.num_rows == 0: + return records + held = stored.column(codec.KEY_COLUMN).cast(pa.large_binary()) + return records.filter(pc.invert(pc.is_in(records[codec.KEY_COLUMN], held))) + + +def _last_of_each_key(records: pa.Table) -> pa.Table: + """The last row of each key, in row order (what ``ConnectorArrowDatabase`` keeps).""" + if codec.KEY_COLUMN not in records.column_names: + return records # refused by the codec, naming the key + keys = records.column(codec.KEY_COLUMN).to_pylist() + last = {key: i for i, key in enumerate(keys)} + if len(last) == len(keys): + return records + return records.take(pa.array(sorted(last.values()), pa.int64())) + + +def _encoded(records: pa.Table) -> pa.Table: + """The rows as written, or an empty table for no rows (never sent).""" + if records.num_rows == 0: + return records + return codec.encode_rows(records) + + +def _one_data_context(records: pa.Table) -> str: + """The one data context of rows to store (ITL-1359: one per datagram). + + Raises: + ValueError: If there is no data context column, a null in it, or two values. + """ + if DATA_CONTEXT_COLUMN not in records.column_names: + raise ValueError( + f"a SpiralDB store keeps rows with a {DATA_CONTEXT_COLUMN!r} column only" + ) + values = pc.unique(records.column(DATA_CONTEXT_COLUMN)).to_pylist() + if len(values) != 1 or not isinstance(values[0], str) or not values[0]: + raise ValueError( + f"rows of one write to a SpiralDB store hold one data context, not {values}" + ) + return values[0] + + +def _live(schema: pa.Schema) -> pa.Schema: + """A manifest's schema with its logical types live, as the rows were given.""" + from orcapod.contexts import get_default_context + + return declaration_form_schema(schema, get_default_context().type_converter) diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index e3bb8e10f..8b5bfa863 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -18,13 +18,14 @@ import os import sqlite3 import threading -from collections.abc import Iterator +from collections.abc import Collection, Iterator from typing import Any import pyarrow as pa from orcapod.databases.utils import is_direct_projection from orcapod.types import ColumnInfo +from orcapod.databases.table_names import joined_table_name, joined_table_paths logger = logging.getLogger(__name__) @@ -271,6 +272,21 @@ def _validate_table_name(table_name: str) -> None: # ── Schema introspection ────────────────────────────────────────────────── + def table_name(self, path: tuple[str, ...]) -> str: + """Return the name of the table at a full record path: the joined rule.""" + return joined_table_name(path) + + def has_table(self, table_name: str) -> bool: + """Return whether the table exists.""" + return table_name in self.get_table_names() + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the tables under ``prefix``, in the names' form.""" + names = {*self.get_table_names(), *(joined_table_name(p) for p in pending)} + return joined_table_paths(names, prefix) + def get_table_names(self) -> list[str]: """Return all user table names in this database (excludes views and SQLite internals). diff --git a/src/orcapod/databases/table_names.py b/src/orcapod/databases/table_names.py new file mode 100644 index 000000000..6dc81f6ed --- /dev/null +++ b/src/orcapod/databases/table_names.py @@ -0,0 +1,57 @@ +"""The joined table-name rule of the relational connectors (ITL-1498). + +``ConnectorArrowDatabase`` names a table by its full record path. SQLite, PostgreSQL and a +plain SpiralDB connector use this one rule, the one ``ConnectorArrowDatabase`` used before +naming moved into the connectors (``DBConnectorProtocol.table_name``, ``table_paths``): +each component sanitized (anything but letters, digits and ``_`` becomes ``_``), joined +with ``__``, and ``t_`` in front of a name that starts with a digit. The rule loses +information, so a listing gives back paths in the name's form. +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Sequence + + +def joined_table_name(path: Sequence[str]) -> str: + """Return the table name of ``path`` under the joined rule. + + Args: + path: The full record path components. + """ + parts = [re.sub(r"[^a-zA-Z0-9_]", "_", part) for part in path] + name = "__".join(parts) + if name and name[0].isdigit(): + name = "t_" + name + return name + + +def joined_table_paths( + names: Iterable[str], prefix: tuple[str, ...] +) -> list[tuple[str, ...]]: + """Return the paths, under ``prefix``, of tables named by the joined rule. + + The tables whose name starts with the name ``prefix`` maps to. The components after + ``prefix`` are the rest of the name split at ``__``, in the name's form: a component + that held ``__`` comes back as two, and a table of another path whose name has the + same beginning is listed as well. With an empty prefix, a name that got the ``t_`` + prefix keeps it. + + Args: + names: The table names, stored and pending. + prefix: Leading full path components. + + Returns: + The full paths, sorted. + """ + stem = joined_table_name(prefix) if prefix else "" + found: set[tuple[str, ...]] = set() + for name in names: + if not stem: + found.add(tuple(name.split("__"))) + elif name == stem: + found.add(prefix) + elif name.startswith(stem + "__"): + found.add(prefix + tuple(name[len(stem) + 2 :].split("__"))) + return sorted(found) diff --git a/src/orcapod/protocols/db_connector_protocol.py b/src/orcapod/protocols/db_connector_protocol.py index 6ed2f94bd..be48c8675 100644 --- a/src/orcapod/protocols/db_connector_protocol.py +++ b/src/orcapod/protocols/db_connector_protocol.py @@ -12,7 +12,7 @@ from __future__ import annotations -from collections.abc import Iterator +from collections.abc import Collection, Iterator from typing import Any, Protocol, TYPE_CHECKING, runtime_checkable from orcapod.types import ColumnInfo @@ -63,6 +63,42 @@ def get_column_info(self, table_name: str) -> list[ColumnInfo]: """Return column metadata for a table, with types mapped to Arrow.""" ... + # ── Table names (ITL-1498) ──────────────────────────────────────────────── + + def table_name(self, path: tuple[str, ...]) -> str: + """Return the name of the table that holds the records at a full path. + + ``ConnectorArrowDatabase`` names every table through this. The relational + connectors join the sanitized components (``table_names.joined_table_name``). + + Args: + path: The full record path (the database's base path, then the record path). + """ + ... + + def has_table(self, table_name: str) -> bool: + """Return whether the table exists. + + Args: + table_name: A name ``table_name`` returned. + """ + ... + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the tables under ``prefix``, stored or pending. + + Args: + prefix: Leading full path components; empty for every table. + pending: The full paths of tables whose rows are not written yet. + + Returns: + The paths, sorted. A connector whose names lose information gives them in + its names' form (``table_names.joined_table_paths``). + """ + ... + # ── Read ────────────────────────────────────────────────────────────────── def iter_batches( diff --git a/tests/test_core/sources/test_db_table_source.py b/tests/test_core/sources/test_db_table_source.py index 0b37f6180..92d3369ff 100644 --- a/tests/test_core/sources/test_db_table_source.py +++ b/tests/test_core/sources/test_db_table_source.py @@ -15,7 +15,7 @@ from __future__ import annotations import re -from collections.abc import Iterator +from collections.abc import Collection, Iterator from typing import Any import pyarrow as pa @@ -26,6 +26,7 @@ from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.types import ColumnInfo from orcapod.protocols.hashing_protocols import PipelineElementProtocol +from orcapod.databases.table_names import joined_table_name, joined_table_paths # --------------------------------------------------------------------------- @@ -48,6 +49,21 @@ def __init__( self._tables: dict[str, pa.Table] = dict(tables or {}) self._pk_columns: dict[str, list[str]] = dict(pk_columns or {}) + def table_name(self, path: tuple[str, ...]) -> str: + """Return the name of the table at a full record path: the joined rule.""" + return joined_table_name(path) + + def has_table(self, table_name: str) -> bool: + """Return whether the table exists.""" + return table_name in self.get_table_names() + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the tables under ``prefix``, in the names' form.""" + names = {*self.get_table_names(), *(joined_table_name(p) for p in pending)} + return joined_table_paths(names, prefix) + def get_table_names(self) -> list[str]: return list(self._tables.keys()) diff --git a/tests/test_core/sources/test_tag_columns_normalization.py b/tests/test_core/sources/test_tag_columns_normalization.py index 2b3f73bba..23a720fa6 100644 --- a/tests/test_core/sources/test_tag_columns_normalization.py +++ b/tests/test_core/sources/test_tag_columns_normalization.py @@ -10,13 +10,14 @@ import re import sqlite3 -from collections.abc import Iterator +from collections.abc import Collection, Iterator from typing import Any import pyarrow as pa import pytest from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.databases.table_names import joined_table_name, joined_table_paths # --------------------------------------------------------------------------- @@ -349,6 +350,21 @@ def __init__( } self._pk_columns = pk_columns or {"events": ["session_id"]} + def table_name(self, path: tuple[str, ...]) -> str: + """Return the name of the table at a full record path: the joined rule.""" + return joined_table_name(path) + + def has_table(self, table_name: str) -> bool: + """Return whether the table exists.""" + return table_name in self.get_table_names() + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the tables under ``prefix``, in the names' form.""" + names = {*self.get_table_names(), *(joined_table_name(p) for p in pending)} + return joined_table_paths(names, prefix) + def get_table_names(self) -> list[str]: return list(self._tables.keys()) diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 1606edd88..745c7be9c 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -1074,6 +1074,7 @@ def install(root: Path | str): with ( patch.dict(os.environ, {_ROOT_ENV: str(root)}), patch("orcapod.databases.spiraldb_connector.sp", fake_module), + patch("orcapod.databases.spiraldb_store_tables.sp", fake_module), patch("orcapod.databases.spiraldb_connector.require_sign_in", lambda: None), patch( "orcapod.databases.spiraldb_connector._http_get_json", fake_http_get_json diff --git a/tests/test_databases/test_connector_arrow_database.py b/tests/test_databases/test_connector_arrow_database.py index 5fdb3934a..2c7311b10 100644 --- a/tests/test_databases/test_connector_arrow_database.py +++ b/tests/test_databases/test_connector_arrow_database.py @@ -24,7 +24,7 @@ from __future__ import annotations import re -from collections.abc import Iterator +from collections.abc import Collection, Iterator from typing import Any import pyarrow as pa @@ -39,6 +39,7 @@ from orcapod.types import ColumnInfo from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.databases import ConnectorArrowDatabase +from orcapod.databases.table_names import joined_table_name, joined_table_paths # --------------------------------------------------------------------------- @@ -89,6 +90,21 @@ def __init__( # ── Schema introspection ────────────────────────────────────────────────── + def table_name(self, path: tuple[str, ...]) -> str: + """Return the name of the table at a full record path: the joined rule.""" + return joined_table_name(path) + + def has_table(self, table_name: str) -> bool: + """Return whether the table exists.""" + return table_name in self.get_table_names() + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the tables under ``prefix``, in the names' form.""" + names = {*self.get_table_names(), *(joined_table_name(p) for p in pending)} + return joined_table_paths(names, prefix) + def get_table_names(self) -> list[str]: return list(self._tables.keys()) diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py index 97b169184..a1207bfab 100644 --- a/tests/test_databases/test_spiral_store.py +++ b/tests/test_databases/test_spiral_store.py @@ -134,7 +134,7 @@ def entries(schema: pa.Schema, path: tuple[str, ...] = PATH) -> bytes: def read(recorded: bytes, path: tuple[str, ...] = PATH) -> store.StoreManifest: - return store.read_manifest(recorded, path) + return store.read_manifest_bytes(recorded, path) def decode(rows: pa.Table, schema: pa.Schema) -> pa.Table: @@ -1260,7 +1260,7 @@ 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(recorded, path) + _ = store.read_manifest_bytes(recorded, path) @pytest.mark.parametrize("part", ["a/b", "a\0", "\udc00"]) @@ -1353,7 +1353,7 @@ def test_a_manifest_that_cannot_be_read_in_full_is_an_error( ) -> None: recorded = make(entries(schema_of(BASE))) with pytest.raises(store.ManifestError): - _ = store.read_manifest(recorded, PATH) + _ = store.read_manifest_bytes(recorded, PATH) def test_a_large_manifest_is_kept() -> None: @@ -1416,3 +1416,56 @@ def test_a_record_id_repeated_in_one_write_is_refused() -> None: 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]: + 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, sha256="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) diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 35690361d..4b85cda65 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -577,3 +577,42 @@ def test_nul_is_cut_in_nested_field_names(place: _Place) -> None: 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}]] + + +# ------------------------------------------------ store mode (ITL-1498) + + +def test_a_store_writes_reads_and_lists_its_table(place: _Place) -> None: + """Store mode under ``ConnectorArrowDatabase``: a fixed path, so a fixed table; the + same rows are written on every run (an upsert).""" + from orcapod.databases import ConnectorArrowDatabase + from orcapod.databases import spiral_store_names as names + + path = ("conformance_store", "0123456789abcdef" * 4, "rdb_v1") + written = _codec_rows() + store = SpiralDBConnector( + place.project, place.dataset, place.overrides, _store=True + ) + db = ConnectorArrowDatabase(store) + db.add_records(path, written, record_id_column="__record_id", flush=True) + fresh = ConnectorArrowDatabase( + SpiralDBConnector(place.project, place.dataset, place.overrides, _store=True) + ) + assert fresh.table_exists(path) + got = fresh.get_all_records(path, record_id_column="__record_id") + assert got is not None + got = got.sort_by("__record_id") + assert got.column_names == written.column_names + for name in written.column_names: + a, b = got.column(name).combine_chunks(), written.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.cast(a.type)), name + assert path in fresh.list_table_paths(("conformance_store",)) + client = _client(place) + table = client.keyed_table( + place.project, place.dataset, names.store_table_name(path) + ) + record = names.read_store_table_metadata(table.get_metadata()) + assert record is not None and record.path == path diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py new file mode 100644 index 000000000..4ee506f10 --- /dev/null +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -0,0 +1,323 @@ +"""A SpiralDB connector in store mode, under ``ConnectorArrowDatabase`` (ITL-1498). + +On the fake (``fake_spiral_sdk``). The live run of the same operations is in +``test_spiraldb_connector_integration.py``. +""" + +from __future__ import annotations + +import datetime as dt +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.contexts.stored import tables_of_another_layout +from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import spiral_store as codec +from orcapod.databases import spiral_store_names as names +from orcapod.errors import ( + SpiralDBWriteNotSupportedError, + SpiralStoreTableCollisionError, +) +from tests.test_databases import fake_spiral_sdk as fake + +CONTEXT = "std:v1:default" +H = "0123456789abcdef" * 4 +RESULT = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") +utc = dt.timezone.utc + + +@pytest.fixture +def root(tmp_path: Path) -> Iterator[Path]: + with fake.install(tmp_path): + yield tmp_path + + +def store(project: str = "p", dataset: str = "d") -> SpiralDBConnector: + return SpiralDBConnector(project, dataset, _store=True) + + +def rows(ids: list[str], *, context: str = CONTEXT, offset: int = 0) -> pa.Table: + """Rows of a stored table: names the codec escapes, an instant, a struct.""" + n = len(ids) + return pa.table( + { + "__record_id": pa.array([i.encode() for i in ids], pa.large_binary()), + "__data_context": pa.array([context] * n, pa.large_string()), + "a.b": pa.array([offset + i for i in range(n)], pa.int64()), + "__pod_ts": pa.array( + [dt.datetime(2026, 1, 1, tzinfo=utc)] * n, pa.timestamp("us", tz="UTC") + ), + "s": pa.array([{"x": i} for i in range(n)], pa.struct([("x", pa.int8())])), + } + ) + + +def by_id(table: pa.Table) -> pa.Table: + return table.sort_by("__record_id") + + +def _client() -> Any: + return fake.FakeClient() + + +def _table(name: str) -> Any: + return _client().keyed_table("p", "d", name) + + +# ------------------------------------------------------------------ write and read + + +@pytest.mark.usefixtures("root") +def test_rows_round_trip() -> None: + db = ConnectorArrowDatabase(store()) + written = rows(["r1", "r0", "r2"]) + db.add_records(RESULT, written, record_id_column="__record_id") + assert db.table_exists(RESULT) # pending + db.flush() + assert db.table_exists(RESULT) + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None + assert by_id(got).equals(by_id(written)) + one = db.get_record_by_id(RESULT, b"r2", record_id_column="__record_id") + assert one is not None and one.column("a.b").to_pylist() == [2] + schema = db.get_table_schema(RESULT) + assert schema is not None and schema.names == written.schema.names + + +@pytest.mark.usefixtures("root") +def test_the_table_is_named_from_its_full_path_and_records_it() -> None: + db = ConnectorArrowDatabase(store()).at("team", "store") + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + db.flush() + full = ("team", "store", *RESULT) + table = _table(names.store_table_name(full)) + metadata = table.get_metadata() + record = names.read_store_table_metadata(metadata) + assert record == names.StoreTableRecord(full, "rdb_v1", CONTEXT) + manifest = codec.read_manifest(metadata, full) + assert manifest is not None and "a.b" in manifest.schema.names + # the stored column names are the codec's, not Orcapod's + assert "a.b" not in table.schema().names + + +@pytest.mark.usefixtures("root") +def test_a_path_too_long_for_a_joined_name_is_stored() -> None: + long_path = ("f" * 300, H, "v0", "python.function.v1", f"schema:{H}", "pdb_v1") + db = ConnectorArrowDatabase(store()) + db.add_records(long_path, rows(["r0"]), record_id_column="__record_id") + db.flush() + assert len(names.store_table_name(long_path)) <= 164 + assert db.list_table_paths(("f" * 300,)) == [long_path] + + +@pytest.mark.usefixtures("root") +def test_later_writes_append_and_skip_existing_keeps_stored_rows() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0", "r1"]), record_id_column="__record_id") + db.flush() + db.add_records(RESULT, rows(["r2"]), record_id_column="__record_id") + db.flush() + again = rows(["r1", "r3"], offset=100) + db.add_records(RESULT, again, record_id_column="__record_id", skip_duplicates=True) + db.flush() + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None + values = dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) + assert values == {b"r0": 0, b"r1": 1, b"r2": 0, b"r3": 101} + + +@pytest.mark.usefixtures("root") +def test_a_new_connector_reads_what_another_wrote() -> None: + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["r0"]), record_id_column="__record_id", flush=True + ) + fresh = ConnectorArrowDatabase(store()) + assert fresh.table_exists(RESULT) + got = fresh.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None and got.num_rows == 1 + + +# ---------------------------------------------------------------- refusals + + +@pytest.mark.parametrize( + "bad", + [ + rows(["r0"]).drop_columns(["__data_context"]), + pa.concat_tables([rows(["r0"]), rows(["r1"], context="std:v2:other")]), + rows(["r0"]).set_column( + 4, "s", pa.array([None], pa.struct([("x", pa.int8())])) + ), + ], + ids=["no data context", "two data contexts", "a null struct"], +) +@pytest.mark.usefixtures("root") +def test_rows_the_store_cannot_keep_are_refused_before_anything_is_written( + bad: pa.Table, +) -> None: + db = ConnectorArrowDatabase(store()) + with pytest.raises((ValueError, codec.UnstorableInSpiralError)): + db.add_records(RESULT, bad, record_id_column="__record_id") + assert fake.FakeClient()._store.tables() == [] # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.usefixtures("root") +def test_another_schema_is_refused() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + other = rows(["r1"]).append_column("more", pa.array([1])) + fresh = ConnectorArrowDatabase(store()) + with pytest.raises(ValueError, match="(?i)schema"): + fresh.add_records(RESULT, other, record_id_column="__record_id", flush=True) + + +def _make_table(name: str, metadata: dict[str, bytes], *, with_rows: bool) -> None: + key = pa.schema([pa.field("__record_id", pa.large_binary(), nullable=False)]) + table = _client().project("p").create_keyed_table("d", name, key) + if metadata: + table.set_metadata(metadata) + if with_rows: + _ = table.append( + pa.table( + { + "__record_id": pa.array([b"x"], pa.large_binary()), + "v": pa.array([1]), + } + ) + ) + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_path_under_the_name_is_refused() -> None: + other = ("another", "rdb_v1") + _make_table( + names.store_table_name(RESULT), + names.store_table_metadata(other, CONTEXT), + with_rows=False, + ) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="another"): + _ = db.table_exists(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + + +@pytest.mark.usefixtures("root") +def test_a_table_with_rows_and_no_record_is_refused() -> None: + _make_table(names.store_table_name(RESULT), {}, with_rows=True) + with pytest.raises(SpiralStoreTableCollisionError, match="no store manifest"): + _ = ConnectorArrowDatabase(store()).table_exists(RESULT) + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_without_a_record_is_adopted() -> None: + """A creation that stopped before the first write (decision 3).""" + _make_table(names.store_table_name(RESULT), {}, with_rows=False) + db = ConnectorArrowDatabase(store()) + assert not db.table_exists(RESULT) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None and got.num_rows == 1 + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_with_another_key_is_refused() -> None: + key = pa.schema([pa.field("k", pa.large_string(), nullable=False)]) + _ = ( + _client() + .project("p") + .create_keyed_table("d", names.store_table_name(RESULT), key) + ) + with pytest.raises(SpiralStoreTableCollisionError, match="key"): + _ = ConnectorArrowDatabase(store()).table_exists(RESULT) + + +# ---------------------------------------------------------------- listing + + +PATHS = [ + RESULT, + ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v0"), + ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v1"), + ("my_fnx", H, "rdb_v1"), + ("side_effects", "Notify Pod", f"schema:{H}", "tdb_v1"), +] + + +@pytest.mark.usefixtures("root") +def test_tables_are_listed_by_their_recorded_paths() -> None: + db = ConnectorArrowDatabase(store()) + for path in reversed(PATHS): + db.add_records(path, rows(["r0"]), record_id_column="__record_id") + db.flush() + db.add_records( + ("my_fn", "pending", "rdb_v1"), rows(["r0"]), record_id_column="__record_id" + ) + _make_table("someone_elses", {}, with_rows=True) + _make_table("o1_unmarked_" + "0" * 64, {}, with_rows=False) + assert db.list_table_paths() == sorted([*PATHS, ("my_fn", "pending", "rdb_v1")]) + assert db.list_table_paths(("my_fn",)) == sorted( + [p for p in PATHS if p[0] == "my_fn"] + [("my_fn", "pending", "rdb_v1")] + ) + assert db.list_table_paths(("side_effects", "Notify Pod")) == [PATHS[-1]] + assert db.at("my_fn").list_table_paths((H,)) == sorted( + p[1:] for p in PATHS if p[:2] == ("my_fn", H) + ) + + +@pytest.mark.usefixtures("root") +def test_stale_layouts_are_found_by_their_recorded_paths() -> None: + """ITL-954: by the recorded path, never by a computed hash.""" + db = ConnectorArrowDatabase(store()) + for path in PATHS: + db.add_records(path, rows(["r0"]), record_id_column="__record_id") + db.flush() + # Under ("my_fn",): the current result and pipeline tables, and one of layout + # rdb_v0; ("my_fnx", ...) shares the name's beginning, not the path. + assert tables_of_another_layout(db, ("my_fn",), result_revision="rev1") == [ + PATHS[1] + ] + + +@pytest.mark.usefixtures("root") +def test_a_listed_table_recording_a_path_of_another_name_is_refused() -> None: + """A table copied or renamed under another name.""" + _make_table( + "o1_my_fn_" + "0" * 64, + names.store_table_metadata(RESULT, CONTEXT), + with_rows=True, + ) + with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +# ---------------------------------------------------------------- private, plain + + +@pytest.mark.usefixtures("root") +def test_a_store_mode_connector_is_not_saved() -> None: + with pytest.raises(ValueError, match="not saved"): + _ = store().to_config() + + +@pytest.mark.usefixtures("root") +def test_raw_reads_are_refused_in_store_mode() -> None: + connector = store() + for call in ( + lambda: connector.lookup_table("x"), + lambda: list(connector.scan_batches("x")), + ): + with pytest.raises(ValueError, match="store-mode"): + _ = call() + + +@pytest.mark.usefixtures("root") +def test_a_plain_connector_still_writes_nothing() -> None: + connector = SpiralDBConnector("p", "d") + assert connector.table_name(("a", "b")) == "a__b" + with pytest.raises(SpiralDBWriteNotSupportedError): + connector.validate_records(rows(["r0"])) diff --git a/tests/test_databases/test_table_names.py b/tests/test_databases/test_table_names.py new file mode 100644 index 000000000..aa779f9e1 --- /dev/null +++ b/tests/test_databases/test_table_names.py @@ -0,0 +1,115 @@ +"""The relational connectors' table names did not change when naming moved (ITL-1498). + +``ConnectorArrowDatabase`` used to name tables and list paths itself; the connectors do +now (``DBConnectorProtocol.table_name``, ``has_table``, ``table_paths``). The rule it used +is kept below as the oracle, verbatim, and every name and listing must equal it. +""" + +from __future__ import annotations + +import random +import re +from pathlib import Path + +import pyarrow as pa +import pytest + +from orcapod.databases import ConnectorArrowDatabase +from orcapod.databases.sqlite_connector import SQLiteConnector +from orcapod.databases.table_names import joined_table_name, joined_table_paths + + +def _old_path_to_table_name(record_path: tuple[str, ...]) -> str: + """``ConnectorArrowDatabase._path_to_table_name`` before ITL-1498, verbatim.""" + parts = [re.sub(r"[^a-zA-Z0-9_]", "_", part) for part in record_path] + name = "__".join(parts) + if name and name[0].isdigit(): + name = "t_" + name + return name + + +def _old_list_table_paths( + names: set[str], + pending_keys: list[str], + path_prefix: tuple[str, ...], + prefix: tuple[str, ...], +) -> list[tuple[str, ...]]: + """``ConnectorArrowDatabase.list_table_paths`` before ITL-1498, verbatim.""" + full_prefix = path_prefix + prefix + names = set(names) + names.update(_old_path_to_table_name(tuple(key.split("/"))) for key in pending_keys) + stem = _old_path_to_table_name(full_prefix) if full_prefix else "" + found: set[tuple[str, ...]] = set() + for name in names: + if not stem: + found.add(tuple(name.split("__"))) + elif name == stem: + found.add(prefix) + elif name.startswith(stem + "__"): + found.add(prefix + tuple(name[len(stem) + 2 :].split("__"))) + return sorted(found) + + +_ALPHABET = ["a", "b", "1", "_", "__", "-", ".", "é", "A", ":", " "] + + +def _component(rng: random.Random) -> str: + return "".join(rng.choice(_ALPHABET) for _ in range(rng.randint(1, 4))) + + +def _path(rng: random.Random) -> tuple[str, ...]: + return tuple(_component(rng) for _ in range(rng.randint(1, 4))) + + +def test_names_are_the_old_rule() -> None: + rng = random.Random(1498) + for _ in range(20_000): + path = _path(rng) + assert joined_table_name(path) == _old_path_to_table_name(path) + + +@pytest.mark.parametrize("seed", range(40)) +def test_listings_are_the_old_rule(seed: int) -> None: + rng = random.Random(seed) + stored = {_old_path_to_table_name(_path(rng)) for _ in range(rng.randint(0, 12))} + pending = ["/".join(_path(rng)) for _ in range(rng.randint(0, 4))] + for path_prefix in ((), _path(rng)[:1]): + for prefix in ((), _path(rng)[:1], _path(rng)[:2]): + full = [ + p[len(path_prefix) :] + for p in joined_table_paths( + { + *stored, + *(joined_table_name(tuple(k.split("/"))) for k in pending), + }, + path_prefix + prefix, + ) + ] + assert sorted(set(full)) == _old_list_table_paths( + stored, pending, path_prefix, prefix + ) + + +def test_a_database_on_sqlite_names_and_lists_as_before(tmp_path: Path) -> None: + """Through ``ConnectorArrowDatabase``: stored and pending tables, with a base path.""" + connector = SQLiteConnector(str(tmp_path / "db.sqlite")) + db = ConnectorArrowDatabase(connector) + rows = pa.table({"x": pa.array([1], pa.int64())}) + stored_paths = [("fn-1", "v0", "rdb_v1"), ("fn.1", "v0"), ("2nd", "x__y")] + for path in stored_paths: + db.add_record(path, b"r", rows) + db.flush() + db.add_record(("fn-1", "pending"), b"r", rows) + names = set(connector.get_table_names()) + assert names == {_old_path_to_table_name(p) for p in stored_paths} + for prefix in ((), ("fn-1",), ("fn.1",), ("2nd",)): + assert db.list_table_paths(prefix) == _old_list_table_paths( + names, ["fn-1/pending"], (), prefix + ) + scoped = db.at("fn-1") + assert scoped.list_table_paths() == _old_list_table_paths( + names, ["fn-1/pending"], ("fn-1",), () + ) + for path in stored_paths: + assert db.table_exists(path) + assert not db.table_exists(("absent",)) From 20640eaa437a173f6fc5be147ab5f6597bda9ded Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 06:01:15 -0800 Subject: [PATCH 09/25] docs(scripts): end-to-end evaluation of the SpiralDB store (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/scripts/itl_1446_store_evaluation.py | 515 ++++++++++++++++++ 1 file changed, 515 insertions(+) create mode 100644 docs/dev/scripts/itl_1446_store_evaluation.py diff --git a/docs/dev/scripts/itl_1446_store_evaluation.py b/docs/dev/scripts/itl_1446_store_evaluation.py new file mode 100644 index 000000000..6fbf2abf9 --- /dev/null +++ b/docs/dev/scripts/itl_1446_store_evaluation.py @@ -0,0 +1,515 @@ +"""End-to-end evaluation of the SpiralDB store as of ITL-1498 (no lease, one process). + +One job (a function pod, a join, a filter, a group by, a second function, a side effect) +through every scenario of ITL-1446's goals, on Delta and on a SpiralDB store (the fake, or +live), compared value for value; every SpiralDB call is counted per table. + + uv run python docs/dev/scripts/itl_1446_store_evaluation.py fake + SPIRAL_PROJECT_ID=... uv run python docs/dev/scripts/itl_1446_store_evaluation.py live + +Live runs need a sign-in spiral-sdk finds (``SPIRAL_CLIENT_ID``, ``SPIRAL_PRIVATE_KEY``) and +write fixed-name tables of a fresh job name into ``ORCAPOD_SPIRAL_CONFORMANCE_DATASET`` +(default ``orcapod_conformance``). Prints a JSON report; numbers measured live are not +kept in the repository. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import re +import sys +import tempfile +import time +import uuid +import warnings +from collections import Counter, defaultdict +from contextlib import ExitStack +from pathlib import Path +from typing import Any + +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + SpiralDBConnector, +) +from orcapod.side_effects import SideEffectPod +from orcapod.sources import ArrowTableSource + +warnings.filterwarnings("ignore") +REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO)) + +CALLS: Counter[str] = Counter() +SENT: list[float] = [] + + +def make_rate(version: str) -> Any: + @function_pod(output_keys="rate_hz", version=version) + def firing_rate(n_spikes: int, duration_s: float) -> float: + CALLS["firing_rate"] += 1 + return n_spikes / duration_s + + return firing_rate + + +@function_pod(output_keys="mean_rate_hz") +def mean_rate(rate_hz: list[float]) -> float: + CALLS["mean_rate"] += 1 + return sum(rate_hz) / len(rate_hz) + + +def notify(ctx: Any, mean_rate_hz: float) -> None: + SENT.append(mean_rate_hz) + + +def units_table(extra: bool = False) -> pa.Table: + rows = [ + (s, u, 100 + 7 * i, 10.0 + (i % 3)) + for i, (s, u) in enumerate( + (s, u) for s in ("m1", "m2", "m3", "m4") for u in ("u1", "u2", "u3") + ) + ] + if extra: + rows += [("m1", "u4", 999, 9.0), ("m2", "u4", 555, 11.0)] + schema = pa.schema( + [ + pa.field("subject_id", pa.large_string(), nullable=False), + pa.field("unit", pa.large_string(), nullable=False), + pa.field("n_spikes", pa.int64(), nullable=False), + pa.field("duration_s", pa.float64(), nullable=False), + ] + ) + return pa.Table.from_pylist( + [dict(zip(schema.names, r)) for r in rows], schema=schema + ) + + +SUBJECTS = pa.Table.from_pylist( + [ + {"subject_id": s, "genotype": g} + for s, g in (("m1", "ko"), ("m2", "ko"), ("m3", "wt"), ("m4", "ko")) + ], + schema=pa.schema( + [ + pa.field("subject_id", pa.large_string(), nullable=False), + pa.field("genotype", pa.large_string(), nullable=False), + ] + ), +) + + +def sources(extra: bool = False) -> dict[str, Any]: + return { + "units": ArrowTableSource( + units_table(extra), + tag_columns=["subject_id", "unit"], + tag_only_columns=True, + source_id="units", + record_id_columns=["subject_id", "unit"], + ), + "subjects": ArrowTableSource( + SUBJECTS, + tag_columns=["subject_id"], + source_id="subjects", + record_id_columns=["subject_id"], + ), + } + + +def build(job: PipelineJob, *, extra: bool = False, version: str = "v1.0") -> None: + given = sources(extra) + units, subjects = given["units"], given["subjects"] + with job: + rates = make_rate(version).pod(units, label="rates") + kept = rates.join(subjects).filter(genotype="ko") + grouped = kept.group_by(["subject_id"]).select_data_columns(["rate_hz"]) + means = mean_rate.pod(grouped, label="means") + SideEffectPod(notify)(means, label="notify") + + +# ----------------------------------------------------------------- what is compared + + +def node_rows(job: PipelineJob) -> dict[str, pa.Table]: + columns = {"system_tags": True, "source": True, "content_hash": True} + return {n: job.nodes[n].as_table(columns=columns) for n in sorted(job.nodes)} + + +def node_hashes(job: PipelineJob) -> dict[str, tuple[str, str]]: + out = {} + for name in sorted(job.nodes): + node = job.nodes[name] + out[name] = (node.content_hash().to_string(), node.pipeline_hash().to_string()) + return out + + +def stored(db: Any) -> dict[tuple[str, ...], pa.Table]: + out = {} + for path in db.list_table_paths(): + table = db.get_all_records(path, record_id_column="__record_id") + if table is not None: + out[path] = table.sort_by("__record_id") + return out + + +def as_set(table: pa.Table) -> list[str]: + return sorted(json.dumps(r, sort_keys=True, default=str) for r in table.to_pylist()) + + +def compare_tables(a: pa.Table, b: pa.Table, *, ordered: bool) -> str | None: + if sorted(a.column_names) != sorted(b.column_names): + return f"columns {sorted(a.column_names)} vs {sorted(b.column_names)}" + b = b.select(a.column_names) + if ordered: + return None if a.to_pylist() == b.to_pylist() else "rows differ (ordered)" + return None if as_set(a) == as_set(b) else "rows differ (as sets)" + + +GENERATED = {"__pod_ts", "__recorded_at", "executed_at", "__run_id", "__executor_info"} + + +def compare_stores( + delta: dict[tuple[str, ...], pa.Table], spiral: dict[tuple[str, ...], pa.Table] +) -> list[str]: + problems = [] + if set(delta) != set(spiral): + problems.append( + f"paths only in Delta {sorted(set(delta) - set(spiral))}, only in the store " + f"{sorted(set(spiral) - set(delta))}" + ) + for path in sorted(set(delta) & set(spiral)): + a, b = delta[path], spiral[path] + ids_a = a["__record_id"].to_pylist() + ids_b = b["__record_id"].to_pylist() + if ids_a != ids_b: + problems.append(f"{'/'.join(path)}: record ids differ") + continue + for name in a.column_names: + if name in GENERATED or name not in b.column_names: + continue + if a[name].to_pylist() != b[name].to_pylist(): + problems.append(f"{'/'.join(path)}: column {name!r} differs") + extra = sorted(set(a.column_names) ^ set(b.column_names)) + if extra: + problems.append(f"{'/'.join(path)}: columns in one store only {extra}") + return problems + + +# ------------------------------------------------------------------- SpiralDB calls + + +class Calls: + """Counts the SDK calls of a store-mode connector, per table name.""" + + def __init__(self, connector: SpiralDBConnector) -> None: + self.counts: Counter[tuple[str, str]] = Counter() + store = connector._store # pyright: ignore[reportPrivateUsage] + assert store is not None + self.store = store + open_table, list_tables = store._open_table, store._list_tables # pyright: ignore[reportPrivateUsage] + names_by_id: dict[str, str] = {} + + def counted_open(name: str) -> Any: + self.counts[("open by name", name)] += 1 + table = open_table(name) + if table is None: + return None + names_by_id[str(table.resource_id)] = name + return _Table(table, name, self.counts) + + def counted_list() -> dict[str, str]: + self.counts[("list dataset", "*")] += 1 + listed = list_tables() + names_by_id.update(listed) + return listed + + client = store._client # pyright: ignore[reportPrivateUsage] + + store._open_table = counted_open # pyright: ignore[reportPrivateUsage] + store._list_tables = counted_list # pyright: ignore[reportPrivateUsage] + store._client = _Client(client, self.counts, names_by_id) # pyright: ignore[reportPrivateUsage] + + def by_path(self) -> dict[str, dict[str, int]]: + out: dict[str, dict[str, int]] = defaultdict(dict) + paths = {n: "/".join(p) for n, p in self.store._paths.items()} # pyright: ignore[reportPrivateUsage] + for (what, name), n in sorted(self.counts.items()): + out[paths.get(name, name)][what] = n + return dict(out) + + def total(self) -> int: + return sum(self.counts.values()) + + +class _Client: + def __init__( + self, client: Any, counts: Counter[tuple[str, str]], names_by_id: dict[str, str] + ) -> None: + self._client, self._c, self._names = client, counts, names_by_id + + def project(self, id: str) -> Any: + return _Project(self._client.project(id), self._c) + + def keyed_table_by_id(self, table_id: str, **kw: Any) -> Any: + name = self._names.get(table_id, table_id) + self._c[("open by id", name)] += 1 + return _Table(self._client.keyed_table_by_id(table_id, **kw), name, self._c) + + +class _Project: + def __init__(self, project: Any, counts: Counter[tuple[str, str]]) -> None: + self._p, self._c = project, counts + + def create_keyed_table(self, dataset: str, name: str, key: Any, **kw: Any) -> Any: + self._c[("create", name)] += 1 + return _Table( + self._p.create_keyed_table(dataset, name, key, **kw), name, self._c + ) + + +class _Table: + def __init__(self, table: Any, name: str, counts: Counter[tuple[str, str]]) -> None: + self._t, self._n, self._c = table, name, counts + + def __getattr__(self, attr: str) -> Any: + return getattr(self._t, attr) + + def get_metadata(self) -> Any: + self._c[("metadata read", self._n)] += 1 + return self._t.get_metadata() + + def set_metadata(self, metadata: Any) -> None: + self._c[("metadata write", self._n)] += 1 + self._t.set_metadata(metadata) + + def append(self, data: Any) -> Any: + self._c[("commit", self._n)] += 1 + return _Table(self._t.append(data), self._n, self._c) + + def scan(self, columns: Any = None, **kw: Any) -> Any: + kind = "whole-table scan" if columns is None else f"scan of {list(columns)}" + if "limit" in kw: + kind += f" limit {kw['limit']}" + self._c[(kind, self._n)] += 1 + return self._t.scan(columns, **kw) + + +# ------------------------------------------------------------------------ scenarios + + +def open_backend(kind: str, root: Path, resources: ExitStack, run: str) -> Any: + """Return (database, result database, calls) of one backend.""" + if kind == "control": + db = DeltaTableDatabase(root / "control") + return db, db.at("results"), None + if kind == "delta": + db = DeltaTableDatabase(root / "delta") + return db, db.at("results"), None + if kind == "fake": + from tests.test_databases import fake_spiral_sdk as fake + + resources.enter_context(fake.install(root / "spiral")) + project, dataset, overrides = "p", "d", None + else: + project = os.environ["SPIRAL_PROJECT_ID"] + dataset = os.environ.get( + "ORCAPOD_SPIRAL_CONFORMANCE_DATASET", "orcapod_conformance" + ) + overrides = { + "server.url": os.environ.get( + "SPIRAL_SERVER_URL", "https://api.spiraldb.dev" + ) + } + connector = SpiralDBConnector(project, dataset, overrides, _store=True) + calls = Calls(connector) + db = ConnectorArrowDatabase(connector) + return db, db.at("results"), calls + + +def evaluate(kind: str) -> dict[str, Any]: + run = uuid.uuid4().hex[:8] + report: dict[str, Any] = {"backend": kind, "steps": {}, "failures": []} + with tempfile.TemporaryDirectory() as tmp, ExitStack() as resources: + root = Path(tmp) + backends = { + "delta": open_backend("delta", root, resources, run), + "control": open_backend("control", root, resources, run), + "spiral": open_backend(kind, root, resources, run), + } + name = f"eval_{run}" + saved = root / "job.json" + jobs: dict[str, dict[str, PipelineJob]] = defaultdict(dict) + + def step(label: str, fn: Any) -> None: + for backend, (db, rdb, calls) in backends.items(): + CALLS.clear() + SENT.clear() + before = calls.total() if calls else 0 + kinds_before = ( + Counter(k for (k, _), n in calls.counts.items() for _ in range(n)) + if calls + else Counter() + ) + start = time.perf_counter() + try: + job = fn(backend, db, rdb) + error = None + except Exception as exc: # noqa: BLE001 # every failure is reported + job, error = None, f"{type(exc).__name__}: {exc}" + took = time.perf_counter() - start + entry: dict[str, Any] = { + "seconds": round(took, 3), + "function_calls": dict(CALLS), + "side_effects_sent": len(SENT), + } + if calls is not None: + entry["spiral_calls"] = calls.total() - before + kinds = Counter( + k for (k, _), n in calls.counts.items() for _ in range(n) + ) + entry["spiral_calls_by_kind"] = dict(kinds - kinds_before) + if error: + entry["error"] = error + report["failures"].append(f"{label} on {backend}: {error}") + report["steps"].setdefault(label, {})[backend] = entry + if job is not None: + jobs[label][backend] = job + pair = jobs.get(label, {}) + try: + compare(label, pair) + except Exception as exc: # noqa: BLE001 # every failure is reported + report["failures"].append( + f"{label}: comparing: {type(exc).__name__}: {exc}" + ) + + def differences( + label: str, d: PipelineJob, other: PipelineJob, db: Any + ) -> set[str]: + found: set[str] = set() + if node_hashes(d) != node_hashes(other): + found.add("node hashes differ") + ordered = "async" not in label + rd, ro = node_rows(d), node_rows(other) + for node in rd: + problem = compare_tables(rd[node], ro[node], ordered=ordered) + if problem: + found.add(f"node {node}: {problem}") + for problem in compare_stores(stored(backends["delta"][0]), stored(db)): + found.add(f"store: {problem}") + return found + + def compare(label: str, pair: dict[str, PipelineJob]) -> None: + if len(pair) != 3: + return + # Two Delta stores differ in generated values (result ids and the tokens + # holding them, run ids, timestamps): only what the control does not show + # is a difference of the SpiralDB store. + control = differences( + label, pair["delta"], pair["control"], backends["control"][0] + ) + spiral = differences( + label, pair["delta"], pair["spiral"], backends["spiral"][0] + ) + report.setdefault("generated_differences", {})[label] = sorted(control) + for problem in sorted(spiral - control): + report["failures"].append(f"{label}: {problem}") + + def first(backend: str, db: Any, rdb: Any) -> PipelineJob: + job = PipelineJob(name=name, database=db) + build(job) + job.run() + if backend == "delta": + job.save(saved) + return job + + def again(backend: str, db: Any, rdb: Any, **options: Any) -> PipelineJob: + job = PipelineJob(name=name, database=db) + build(job, **options) + job.run() + return job + + step("first run", first) + step("unchanged rerun", again) + step("added rows", lambda b, db, rdb: again(b, db, rdb, extra=True)) + step( + "changed function version", + lambda b, db, rdb: again(b, db, rdb, extra=True, version="v2.0"), + ) + + def run_async(backend: str, db: Any, rdb: Any) -> PipelineJob: + job = PipelineJob(name=name + "_async", database=db) + build(job) + asyncio.run(job.run_async()) + return job + + step("run_async (first run, compared as sets)", run_async) + + def load_only(backend: str, db: Any, rdb: Any) -> PipelineJob: + job = PipelineJob.load(saved, database=db) + job.bind(sources=sources()) + job.run(load_only=True) + return job + + step("save, load, run(load_only=True)", load_only) + + def cleared(backend: str, db: Any, rdb: Any) -> PipelineJob: + job = PipelineJob(name=name, database=db) + build(job) + job.run() + for node in job.nodes.values(): + clear = getattr(node, "clear_cache", None) + if clear is not None: + clear() + job.run() + return job + + step("clear_cache, then run", cleared) + + def separate(backend: str, db: Any, rdb: Any) -> PipelineJob: + job = PipelineJob(name=name + "_sep", database=db, result_database=rdb) + build(job) + job.run() + return job + + step("separate result database", separate) + + traces: dict[str, str] = {} + for backend in ("delta", "control", "spiral"): + job = jobs.get("first run", {}).get(backend) + if job is None: + continue + try: + trace = job.nodes["means"].trace({"subject_id": "m1"}, "mean_rate_hz") + # Times and run ids are generated: masked. + text = re.sub( + r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d UTC", "