Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@<new>" \
--with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \
--with spiral-sdk==0.16.78 scripts/migrate_spiral_schemas.py \
write --project <project> --dataset <dataset> --plan plan.json --digest <printed digest>

uv run --no-project --isolated --python 3.12 \
--with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@<new>" \
--with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \
--with spiral-sdk==0.16.78 scripts/migrate_spiral_schemas.py \
verify --project <project> --dataset <dataset> --plan plan.json
```

Expand Down
3 changes: 3 additions & 0 deletions changelog.d/ITL-1495.md
Original file line number Diff line number Diff line change
@@ -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.
36 changes: 36 additions & 0 deletions docs/dev/plans/2026-11-26-itl-1495-spiral-store-names.md
Original file line number Diff line number Diff line change
@@ -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_<hint>_<digest>`), 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.
1 change: 1 addition & 0 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@<fingerprint>` (a name) | `logical_types/user_class_identity.py:identity_string` |
| database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_<hex>` 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_<hint>_<hex>` (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` |
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions src/orcapod/contexts/data/v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
257 changes: 257 additions & 0 deletions src/orcapod/databases/spiral_store_names.py
Original file line number Diff line number Diff line change
@@ -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_<hint>_<digest>``, 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.

- ``<digest>``: 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.
- ``<hint>``: 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_<hint>_<digest>``, 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)}"
)
19 changes: 19 additions & 0 deletions src/orcapod/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``"<project>/<dataset>/<table>"``, 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.

Expand Down
Loading
Loading