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/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/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/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/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/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..7ebe3bda1 --- /dev/null +++ b/src/orcapod/databases/spiral_store_names.py @@ -0,0 +1,257 @@ +"""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.""" + +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" +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") + 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: + """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 (ValueError, RecursionError) as exc: # JSON, UTF-8, the integer limit, depth + raise SpiralStoreTableCollisionError( + f"its record cannot be read: {exc}" + ) from exc + items = cast("list[object]", path) if isinstance(path, list) else [] + if not items or not all(isinstance(c, str) for c in items): + raise SpiralStoreTableCollisionError( + f"its path is not a list of names: {path!r}" + ) + components = tuple(cast("list[str]", items)) + try: + _ = _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}" + ) + if not data_context_key: + raise SpiralStoreTableCollisionError("it records no data context") + return StoreTableRecord(components, layout, data_context_key) + + +def require_store_table_path(record: StoreTableRecord, path: Sequence[str]) -> None: + """Refuse a store table whose record is of another path than ``path``. + + Args: + record: The table's record (``read_store_table_metadata``). + path: The full path the table was looked up for. + + Raises: + SpiralStoreTableCollisionError: If the record is of another path. + """ + if record.path != tuple(path): + raise SpiralStoreTableCollisionError( + f"it records path {list(record.path)}, not {list(path)}" + ) diff --git a/src/orcapod/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 5b9e13d61..60a2e105a 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 @@ -15,6 +16,7 @@ import json import math import os +import threading import types import urllib.parse import uuid @@ -71,8 +73,19 @@ "rows": "rows come in key order; filter before limit", "list": "the documented listing filters a dataset and pages; a page can be empty " "(documented, not seen)", + "table-metadata": "spiral-sdk 0.16.78 (November 26, 2026): get_metadata and " + "set_metadata hold bytes by text key, an upsert that never deletes (an empty value is " + "stored); not versioned (every snapshot, asof included, sees the latest; a write makes " + "no snapshot); readable before any row; a key over 255 UTF-8 bytes, or an entry whose " + "key and value together are over 8,192 bytes: 'status 400' and nothing written", } +_MAX_METADATA_KEY_BYTES = 255 +# Upserts of metadata are atomic on the service (two clients' keys are all kept); the +# fake's stores are in one process. +_metadata_lock = threading.Lock() +_MAX_METADATA_ENTRY_BYTES = 8192 + _ROOT_ENV = "FAKE_SPIRAL_SDK_ROOT" _API_URL = "https://api.fake.invalid" @@ -351,6 +364,33 @@ def drop(self, table_id: str) -> None: path.unlink() folder.rmdir() + def metadata(self, table_id: str) -> dict[str, bytes]: + """Return a table's metadata (``table-metadata``).""" + _ = self.by_id(table_id) + path = self.root / table_id / "metadata.json" + if not path.exists(): + return {} + stored = cast("dict[str, str]", json.loads(path.read_text())) + return {k: bytes.fromhex(v) for k, v in stored.items()} + + def set_metadata(self, table_id: str, entries: dict[str, bytes]) -> None: + """Upsert ``entries`` into a table's metadata (``table-metadata``).""" + for key, value in entries.items(): + size = len(key.encode()) + if ( + size > _MAX_METADATA_KEY_BYTES + or size + len(value) > _MAX_METADATA_ENTRY_BYTES + ): + raise _status(400) + with _metadata_lock: # one upsert at a time: concurrent keys are all kept + stored = self.metadata(table_id) + stored.update(entries) + # Written beside, then put in place: a reader sees a whole mapping. + target = self.root / table_id / "metadata.json" + written = target.with_suffix(".json.tmp") + _ = written.write_text(json.dumps({k: v.hex() for k, v in stored.items()})) + _ = written.replace(target) + def keys(self, table_id: str) -> pa.Schema: """Return a table's key schema.""" raw = (self.root / table_id / "keys.arrow").read_bytes() @@ -626,6 +666,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_spiral_store_names.py b/tests/test_databases/test_spiral_store_names.py new file mode 100644 index 000000000..3673dbf7e --- /dev/null +++ b/tests/test_databases/test_spiral_store_names.py @@ -0,0 +1,243 @@ +"""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: + """The digest is SHA-256 of the canonical JSON array of the components, ending the name.""" + expected = hashlib.sha256( + json.dumps(list(RESULT), ensure_ascii=False, separators=(",", ":")).encode() + ).hexdigest() + assert names.store_table_digest(RESULT) == expected + assert names.store_table_name(RESULT).endswith("_" + expected) + + +def test_the_label_names_the_algorithm() -> None: + # The label is defined once, in the module (the hash label rule): not repeated here. + """The label constant has the label form and is not written into the name.""" + 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) + + +@pytest.mark.parametrize("path", [RESULT, PIPELINE, ("a",), ("É" * 300, "x" * 500)]) +def test_a_name_is_short_and_plain(path: tuple[str, ...]) -> None: + """A name is ``o1__<64 hex>``, within 164 characters, for short and long paths.""" + name = names.store_table_name(path) + assert NAME.match(name), name + assert len(name) <= 3 + 96 + 1 + 64 <= 255 + + +def test_the_hint_keeps_lower_case_letters_and_digits() -> None: + """The hint maps one character to one and is cut to 96 characters.""" + assert 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 +): + """A name follows every component and their order, and nothing else.""" + 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. + """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: + """No two of 20,000 adversarial paths share a name.""" + rng = random.Random(1495) + alphabet = "aA0_-./:é \x00 " + seen: dict[str, tuple[str, ...]] = {} + for _ in range(20_000): + path = tuple( + "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 4))) + for _ in range(rng.randint(1, 3)) + ) + name = names.store_table_name(path) + assert seen.setdefault(name, path) == path + + +@pytest.mark.parametrize( + ("path", "prefix"), + [ + (RESULT, ()), + (RESULT, ("my_fn",)), + (RESULT, RESULT[:3]), + (RESULT, RESULT), + (("side_effects", "My Pod", H, "tdb_v1"), ("side_effects", "My Pod")), + (("f" * 120, H, "rdb_v1"), ("f" * 120,)), + (("f" * 60, "g" * 60, "rdb_v1"), ("f" * 60,)), + ], +) +def test_a_table_under_a_prefix_has_the_prefix_s_name_prefix( + path: tuple[str, ...], prefix: tuple[str, ...] +) -> None: + """Every table under a path prefix has the prefix's name prefix, also past 96 characters.""" + assert names.store_table_name(path).startswith( + names.store_table_name_prefix(prefix) + ) + + +def test_the_name_prefix_of_nothing_is_every_store_table() -> None: + """The name prefix of the empty path prefix is the one every store table has.""" + assert names.store_table_name_prefix(()) == "o1_" + + +@pytest.mark.parametrize("path", [(), ("a", 1), ("\ud800",)]) +def test_a_path_that_cannot_be_named_is_refused(path: tuple[object, ...]) -> None: + """An empty path, a component that is not text and one that is not UTF-8 are refused.""" + with pytest.raises(ValueError, match="path"): + _ = names.store_table_name(path) # pyright: ignore[reportArgumentType] # refused on purpose + + +def test_the_metadata_record() -> None: + """A table's record holds its format, path, layout and data context, and reads back.""" + record = names.store_table_metadata(PIPELINE, "std:v1:default") + assert record == { + "orcapod.store": b"orcapod.spiral_store.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: + """Every entry of a record fits SpiralDB's entry limit; a longer path is refused.""" + 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: + """A table with none of the record's entries is unmarked.""" + assert names.read_store_table_metadata({}) is None + assert names.read_store_table_metadata({"someone.else": b"1"}) is None + + +@pytest.mark.parametrize( + "change", + [ + {"orcapod.store": b"orcapod.spiral_store.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: + """A record of another format, or with an unreadable or inconsistent entry, is refused.""" + record = {**names.store_table_metadata(PIPELINE, "std:v1:default"), **change} + with pytest.raises(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: + """A record lacking one of its entries is refused.""" + 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: + """A record of another path than the one looked up is refused, naming it.""" + found = names.read_store_table_metadata( + names.store_table_metadata(RESULT, "std:v1:default") + ) + assert found is not None + with pytest.raises(SpiralStoreTableCollisionError, match="rdb_v1"): + names.require_store_table_path(found, PIPELINE) + + +def test_a_record_with_an_entry_over_the_service_s_limit_is_refused() -> None: + # Review of PR 589, finding 2: the data context key is the caller's text too. + """A record entry over SpiralDB's limit is refused before any table is created.""" + with pytest.raises(ValueError, match="8192"): + _ = names.store_table_metadata(PIPELINE, "x" * 8192) + + +def test_a_recorded_path_that_writers_refuse_is_refused_on_read() -> None: + # Review of PR 589, finding 3: JSON can spell a lone surrogate, which no writer writes. + """A recorded path no writer writes (a lone surrogate) is refused on read.""" + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": b'["\\ud800","rdb_v1"]', + } + with pytest.raises(SpiralStoreTableCollisionError, match="UTF-8"): + _ = names.read_store_table_metadata(record) + + +def test_the_collision_message_keeps_components_apart() -> None: + # Review of PR 589, finding 4: ("a/b", ...) and ("a", "b", ...) must read differently. + """The collision message shows component lists, so different paths read differently.""" + found = names.read_store_table_metadata( + names.store_table_metadata(("a/b", "rdb_v1"), "std:v1:default") + ) + assert found is not None + with pytest.raises(SpiralStoreTableCollisionError) as raised: + names.require_store_table_path(found, ("a", "b", "rdb_v1")) + assert "['a/b', 'rdb_v1']" in str(raised.value) + assert "['a', 'b', 'rdb_v1']" in str(raised.value) + + +@pytest.mark.parametrize( + "path_json", + [b"[" + b"1" * 5000 + b"]", b"[" * 2000 + b"0" + b"]" * 2000], + ids=["a 5,000-digit integer", "2,000 nested arrays"], +) +def test_a_path_the_json_parser_refuses_is_a_collision(path_json: bytes) -> None: + """CodeRabbit on PR 589: every unreadable record raises the collision error.""" + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": path_json, + } + with pytest.raises(SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index f256de2fa..eb278cda7 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -17,10 +17,12 @@ import datetime as dt import math import os +import uuid from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path from typing import Any +from unittest.mock import patch import pyarrow as pa import pytest @@ -315,3 +317,128 @@ 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 + + +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"} + + +def test_the_fake_never_shows_a_half_written_metadata_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """CodeRabbit on PR 589: a reader during a metadata write sees a whole mapping. + + Every file write is made to call a reader after it has truncated its file and before + it has written anything. + """ + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + table.set_metadata({"a": b"1"}) + seen: list[dict[str, bytes]] = [] + original = Path.write_text + + def write_text_with_a_reader( + self: Path, data: str, *args: Any, **kw: Any + ) -> int: + with self.open("w") as handle: + handle.flush() + seen.append( + fake.FakeClient() + .keyed_table_by_id(table.resource_id) + .get_metadata() + ) + return original(self, data, *args, **kw) + + monkeypatch.setattr(Path, "write_text", write_text_with_a_reader) + table.set_metadata({"b": b"2"}) + monkeypatch.undo() + assert seen == [{"a": b"1"}] + assert table.get_metadata() == {"a": b"1", "b": b"2"} 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" +} 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]]